GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Maps, GIS and field navigation / gridatlas / atlas/modules

Unified SatNav Dock and 1 more file

A JavaScript file in the atlas folder of GridAtlas that maps substations and 11kV. It sets panel open (`setPanelOpen`), updates text (`updateText`) and refreshes guidance (`refreshGuidance`).

700 lines of JavaScript from gridatlas, in 2 files. Topic: Maps, GIS and field navigation. Section 568 of 2044.

Cut 2026-12-06T03:07:51+00:00. A copy for reading; the repository at the stated commit is the source.

In the State lines below, domain stage, users and canonical status are rule-based first approximations from code and path evidence (rules explore-agent-rules-v1), not observed facts: the rules.

In this section

  1. Secondary Neon Engine geodesy · gridatlas / atlas/modules/202612020205-secondary-neon-engine.js lines 8848–9008
  2. Unified SatNav Dock geodesy · gridatlas / atlas/modules/202612020205-unified-satnav-dock.js lines 1–539

Secondary Neon Engine

A JavaScript file in the atlas folder of GridAtlas that maps connection points, GB transmission network, price decade rollup and grid substations, using haversine.

geodesygridatlas / atlas/modules/202612020205-secondary-neon-engine.js · lines 8848–9008 of 9008 · version 2026-12-02 02:05 (continued from section 555) · Not reached from any entry point (candidate for review) · pattern isInterconnectorArrival (shared by 3 files)

What it does
It maps connection points, GB transmission network, price decade rollup and grid substations. Defines 274 functions or classes, including distanceKm, distanceKm, representativePoint, voltagesKv, destinationPoint. Side effects: changes the web page (DOM); reads or writes files; makes network requests; uses storage (browser storage, DuckDB or Parquet).
Why it exists in the grid workflow
Domain stage upstream_foresight (path word 'atlas'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: 750kV, 415kV, 400kV, 275kV, 220kV, 132kV.
Inputs & outputs
In: JSON file connection-points.v3.json; JSON file gb-transmission-network.v1.json; JSON file price-decade-rollup.json; GeoJSON file grid_substations.geojson; JSON file neso-connection-sites.lean.json; GeoJSON file interconnectors.geojson; browser storage (getItem); DuckDB queries. Out: browser storage (setItem); interactive map. Coordinate systems named: WGS84 / EPSG:4326. Voltage levels named: 750kV, 415kV, 400kV, 275kV, 220kV, 132kV, 110kV, 66kV.
What it achieves
It creates compute observer (`createComputeObserver`), describes compute receipt (`describeComputeReceipt`) and builds stats (`buildStats`). Receipt and distance owner: Ventusltd/ventus-grid-engine. Its code works with 400 kV, 132 kV and 33 kV. It responds to click, keydown and touchstart events.
Why it matters
No other file in the estate was found to import it.
Application
gridatlas · atlas/modules · script
VEDIC
MEASURE (GG2050-VEDIC-000001): GridAtlas / Geodesy · Mathematics / Spherical geometry. coordinate_pair, coordinate_pair → distance_km
VEDIC
REPRESENT (GG2050-VEDIC-000002): GridAtlas / Geodesy · Computer science / Geometry processing. geojson_geometry → coordinate_pair_or_null
VEDIC
VOLTAGE (GG2050-VEDIC-000003): GridAtlas / Geodesy · Computer science / Data normalisation. voltage_properties → kilovolt_list
Uses
none found
Used by
none found
Produces
distanceKm, distanceKm, representativePoint, voltagesKv, destinationPoint, initialBearingDeg, copy, finite, located, sameLocation, sameEntity, createComputeObserver
Defines here
boot, ready, go, fit, schedule
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 atlas/modules/202612020205-secondary-neon-engine.js:8848-9008 · blob 26e5045a356c11088820207d3cbe95eb4b89374f · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, network, storage · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
        paint: { 'circle-radius': 5, 'circle-color': '#ffae00', 'circle-stroke-width': 1, 'circle-stroke-color': '#0b0d10' },
      });
    }
  }

  async function boot(map) {
    let geojson;
    try {
      const absolute = new URL(DATA_URL, document.baseURI).href;
      const body = await new Promise((resolve, reject) => {
        const xhr = new XMLHttpRequest();
        xhr.open("GET", absolute);
        xhr.onload = () => (xhr.status >= 200 && xhr.status < 300)
          ? resolve(xhr.responseText)
          : reject(new Error("HTTP " + xhr.status));
        xhr.onerror = () => reject(new Error("transport failed"));
        xhr.send();
      });
      geojson = JSON.parse(body);
    } catch (error) {
      state.error = 'interconnector data not served: ' + String(error && error.message || error);
      /* arrive() is never reached, so without this an interconnector arrival on
         a page whose data file did not serve is completely silent: the project
         lane stood down at its guard and this lane never started. */
      if (isInterconnectorArrival()) answer(false, 'INTERCONNECTOR_DATA_NOT_SERVED', null);
      return;
    }

    const subs = (window.__GRIDATLAS_NEON_LINKS__ || {}).substations
      || (window.__GRIDATLAS_SUBSTATIONS__ || []);
    const km = searchKm();

    state.links = (geojson.features || [])
      .filter((f) => f.properties && f.properties.feature_role === 'link-line')
      .map((f) => {
        const p = f.properties;
        const [a, b] = f.geometry.coordinates;
        return {
          link: p.link, bmrs: p.bmrs_code, gb_converter: p.gb_converter, far_converter: p.far_converter,
          span_km: p.straight_line_km,
          geometry_kind: p.geometry_kind,
          route_factor: p.route_factor ?? null,
          known_submarine_cable_km: p.known_submarine_cable_km ?? null,
          net_mwh: p.net_mwh ?? null,
          net_direction: p.net_direction ?? null,
          label: label(p, km),
          ends: [
            measureEnd('gb', a[0], a[1], km, subs),
            measureEnd('far', b[0], b[1], km, []),
          ],
        };
      });

    state.loaded = true;
    state.search_km = km;
    paint(map, geojson);
    try { arrive(map, geojson); }
    catch (error) {
      state.error = 'interconnector arrival threw: ' + String(error && error.message || error);
      if (isInterconnectorArrival()) answer(false, 'INTERCONNECTOR_ARRIVAL_THREW', null);
    }
  }

  function ready(map) {
    if (!map) return;
    if (map.loaded && map.loaded()) { boot(map); return; }
    let started = false;
    const go = () => { if (!started) { started = true; boot(map); } };
    map.once('load', go);
    map.once('idle', go);
    const settle = setInterval(() => {
      if (map.loaded && map.loaded()) { clearInterval(settle); go(); }
    }, 500);
    setTimeout(() => clearInterval(settle), 60000);
  }

  const timer = setInterval(() => {
    const map = window.__GRIDATLAS_V9_MAP__;
    if (!map) return;
    clearInterval(timer);
    try { ready(map); }
    catch (error) {
      state.error = String(error && error.message || error);
      if (isInterconnectorArrival()) answer(false, 'INTERCONNECTOR_MODULE_THREW', null);
    }
  }, 400);
  setTimeout(() => {
    clearInterval(timer);
    /* Ninety seconds and no map ever appeared on the window. The module never
       got as far as loading, so nothing below it can speak for it. */
    if (!state.loaded && isInterconnectorArrival()) answer(false, 'NO_MAP_WITHIN_90S', null);
  }, 90000);
})();

/** Keep ordinary feature cards clear of the fixed search/menu controls.
 * Project cards have their own draggable bar and mobile sheet; preserve it.
 */
(() => {
  let queued = false;
  const ordinaryStyles = new WeakMap();
  function fit() {
    queued = false;
    const container = window.__GRIDATLAS_V9_MAP__?.getContainer();
    if (!container) return;
    const map = container.getBoundingClientRect();
    const menu = document.getElementById('gridatlas-menu-bar')?.getBoundingClientRect();
    const search = document.querySelector('.search-bar-wrapper')?.getBoundingClientRect();
    for (const popup of container.querySelectorAll('.maplibregl-popup')) {
      const content = popup.querySelector('.maplibregl-popup-content');
      const close = popup.querySelector('.maplibregl-popup-close-button');
      if (!content || !close) continue;
      if (popup.querySelector('.gridatlas-card-bar') || popup.classList.contains('gridatlas-sheet')) {
        // Arrival cards gain their project bar asynchronously. Give back only
        // styles we still own; do not leave a second decorated close button or
        // an extra 44px header above the project's own controls.
        for (const saved of ordinaryStyles.get(content) || []) {
          if (saved.element.style.getPropertyValue(saved.property) === saved.written) {
            if (saved.previous) saved.element.style.setProperty(saved.property, saved.previous, saved.priority);
            else saved.element.style.removeProperty(saved.property);
          }
        }
        ordinaryStyles.delete(content);
        continue;
      }
      if (!ordinaryStyles.has(content)) {
        ordinaryStyles.set(content, [
          ...['min-width', 'min-height', 'color', 'background', 'border'].map(property => ({element: close, property})),
          {element: content, property: 'padding-top'}
        ].map(saved => ({...saved, previous: saved.element.style.getPropertyValue(saved.property),
          priority: saved.element.style.getPropertyPriority(saved.property)})));
      }
      // A normal feature popup's close control otherwise measures only 20px.
      close.style.minWidth = '44px';
      close.style.minHeight = '44px';
      close.style.color = '#bfe9ee';
      close.style.background = '#0a1a1d';
      close.style.border = '1px solid #2f6f75';
      content.style.paddingTop = '44px';
      for (const saved of ordinaryStyles.get(content)) saved.written = saved.element.style.getPropertyValue(saved.property);
      const top = Math.max(map.top, menu?.bottom || 0, search?.bottom || 0) + 8;
      const bottom = Math.min(map.bottom, window.innerHeight) - 8;
      content.style.setProperty('max-height', Math.max(44, bottom - top - 20) + 'px', 'important');
      const rect = popup.getBoundingClientRect();
      const left = Math.max(map.left + 8, Math.min(rect.left, map.right - rect.width - 8));
      const y = Math.max(top, Math.min(rect.top, bottom - rect.height));
      if (rect.top < top || rect.bottom > bottom || rect.left < map.left || rect.right > map.right) {
        popup.classList.add('gridatlas-free');
        popup.style.setProperty('--gx', left + 'px');
        popup.style.setProperty('--gy', y + 'px');
      }
    }
  }
  function schedule() {
    if (!queued) { queued = true; requestAnimationFrame(fit); }
  }
  // Observe content insertion, not our own style writes.
  new MutationObserver(schedule).observe(document.documentElement, {childList: true, subtree: true});
  window.addEventListener('resize', schedule);
  window.visualViewport?.addEventListener('resize', schedule);
  schedule();
})();

Unified SatNav Dock

A JavaScript file in the atlas folder of GridAtlas that maps substations and 11kV. It sets panel open (`setPanelOpen`), updates text (`updateText`) and refreshes guidance (`refreshGuidance`).

Set aside from the main view: 93% of its lines are the same as atlas/modules/satnav-unified-waypoint-map-agent1.js (gridatlas), which stays. (near-copy-of, proposed by families.py). 93% of lines shared with SatNav Unified Waypoint Map Agent1; read that one first. All set-aside files, with reasons. Nothing was deleted.

Evidence
  • line-jaccard 0.9321 to gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 atlas/modules/satnav-unified-waypoint-map-agent1.js:1-669 fe0f52ac502230fec070fc0eea676e44d553a751
  • sha256 c204da77e36b12333bb76fc9ce4d3841be44fc954c80a4beb709822a405947ae
  • target sha256 5585e7db619709c9ace7d4e4810bd029efb9f9041e7d856444f6b6006520315f
  • group of 2 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines

geodesygridatlas / atlas/modules/202612020205-unified-satnav-dock.js · lines 1–539 of 696 · version 2026-12-02 02:05 · Not reached from any entry point (candidate for review) · pattern setPanelOpen (shared by 5 files)

What it does
It maps substations and 11kV. Defines 37 functions or classes, including setPanelOpen, notify, updateText, distanceText, bearingText. Side effects: changes the web page (DOM).
Why it exists in the grid workflow
Domain stage field_execution (path word 'satnav'): on-road and off-road field navigation to the farm gate (access gates, terrain slope, ground-bearing limits, electrical hazards), as Ventus Ltd describes its SatNav work. Domain terms in the code: substations, 11kV, 33kV.
Inputs & outputs
Voltage levels named: 33kV, 11kV.
What it achieves
Derived from the immutable 2 km convergence cartridge; native shell geometry stays owned by GridAtlas. Its code works with 11 kV and 33 kV. It responds to click, visibilitychange and offline events.
Why it matters
No other file in the estate was found to import it.
Application
gridatlas · atlas/modules · script
Uses
none found
Used by
none found
Produces
setPanelOpen, notify, updateText, distanceText, bearingText, collection, pauseFollow, refreshGuidance, changePlan, edit, setPin, place
Defines here
setPanelOpen, notify, updateText, distanceText, bearingText, collection, pauseFollow, refreshGuidance, changePlan, edit, setPin, place, restoreLocalPlan, leaveExample, replacePlan, undo, setFix, fieldState, refreshSources, guidanceText, nativeLayer, syncInfrastructureControls, render, arm, mapClick, selectedIndex, stopTracking, centreOnFix, installAssetActions, current
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 atlas/modules/202612020205-unified-satnav-dock.js:1-539 · blob ede342d6aa58e5afd5feefd40dce23cc864bda34 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: field_execution · users: EPC_contractor, landowner_planner · canonical: unreached_review
/* Unified GridAtlas/SatNav candidate. Derived from the immutable 2 km convergence cartridge; native shell geometry stays owned by GridAtlas. */
void async function () {
  const root = new URL('../../../', location.href);
  const vendor = new URL('tools/satnav/vendor/9698781539e549deaa6ecaa4a2b34610c1f9fd29/', root);
  let installUnifiedLayerSearch = null;
  void import(new URL('atlas/modules/unified-layer-search-ui.mjs', root)).then(module => {installUnifiedLayerSearch=module.installUnifiedLayerSearch;}).catch(error => console.error('Optional Layers search unavailable; native Layers retained',error));
  const [maths, compass, { point }, { createWaypointState }, { createWaypointGuidance }, { assessFieldState }, { classifyDirectLeg, directLegGeometry, reconcileNavigationLayers, prepareAssetDestination, rankHigherVoltage }, {validateDestinationLeg}] = await Promise.all([
    import(new URL('vendor/grid-distance-maths/src/geodesy.mjs', vendor)),
    import(new URL('nav/compass.mjs', vendor)),
    import(new URL('tools/satnav/line/position-overlay.mjs', root)),
    import(new URL('tools/satnav/waypoints/state.mjs', root)),
    import(new URL('tools/satnav/guidance/ordered-convergence-2km.mjs', root)),
    import(new URL('tools/satnav/field-reliability/state.mjs', root)),
    import(new URL('tools/satnav/guidance/convergence-2km.mjs', root)),
    import(new URL('atlas/modules/unified-destination-contract.mjs', root)),
  ]);

  const style = document.createElement('style');
  style.textContent = `
    #satnav-toggle{position:fixed;right:var(--satnav-dock-right,12px);bottom:var(--satnav-dock-bottom,112px);z-index:10031;min-height:44px;padding:6px 12px;background:#081820ed;color:#e4f7f7;border:1px solid #367078;border-radius:6px;font:600 13px system-ui,sans-serif;cursor:pointer}
    #satnav-toggle:focus-visible{outline:2px solid white;outline-offset:2px}
    #satnav-compact[hidden],#satnav-access[hidden]{display:none!important}
    #satnav-compact,#satnav-access{position:fixed;left:max(8px,env(safe-area-inset-left));color:#e4f7f7;font:13px/1.3 system-ui,sans-serif;z-index:10030}
    #satnav-compact{left:auto;right:var(--satnav-dock-right,12px);bottom:var(--satnav-panel-bottom,166px);width:min(260px,calc(100vw - 20px));display:grid;gap:4px;max-height:min(45dvh,max(64px,var(--satnav-panel-height,240px)));overflow:auto;overscroll-behavior:contain}
    #gridatlas-mobile-tray[data-satnav-dock]{position:fixed!important;top:auto!important;left:auto!important;right:var(--satnav-dock-right,12px)!important;bottom:var(--satnav-tray-bottom,60px)!important;z-index:10029!important;display:flex!important;gap:4px;pointer-events:auto;width:max-content!important;max-width:calc(100vw - 20px)}
    #satnav-compact [hidden],#satnav-compact :empty.satnav-readout,#satnav-field-tools:empty{display:none!important}
    #satnav-compact button,#satnav-access{background:#081820ed;color:#e4f7f7;border:1px solid #367078;border-radius:6px}
    #satnav-compact button{min-width:0;min-height:44px;padding:4px 7px;font:inherit;touch-action:manipulation;cursor:pointer}
    #satnav-compact button:disabled{opacity:.55;cursor:default}
    #satnav-compact button[aria-pressed=true]{border-color:#67f9ff;box-shadow:inset 0 0 0 1px #67f9ff}
    #satnav-compact :focus-visible,#satnav-access :focus-visible{outline:2px solid white;outline-offset:-3px}
    #satnav-compact .satnav-endpoint{text-align:left}
    #satnav-compact .satnav-endpoint b{display:inline-block;width:43px;color:#68e8f5}
    #satnav-compact .satnav-row{display:flex;gap:4px}
    #satnav-compact .satnav-row button{flex:1}
    #satnav-editor{display:grid;gap:4px;background:#081820ed;padding:4px;border-radius:6px}
    #satnav-selected,#satnav-limit{margin:2px 3px}
    #satnav-selected{font-weight:bold}
    #satnav-limit{font-size:11px;color:#b6d4d6}
    #satnav-compact .satnav-readout{background:#081820ed;margin:0;padding:3px 6px;border-radius:4px;font-size:12px;overflow-wrap:anywhere}
    #satnav-guide{color:#8bf7f7}
    #satnav-access{bottom:max(8px,env(safe-area-inset-bottom));max-width:min(300px,calc(100vw - 110px));font-size:11px}
    #satnav-access summary{min-height:24px;box-sizing:border-box;padding:4px 7px;cursor:pointer}
    #satnav-access p{margin:0;padding:2px 8px 7px}
  `;
  document.head.append(style);
  const panel = document.createElement('section');
  panel.id = 'satnav-compact';
  panel.setAttribute('aria-label', 'SatNav map controls');
  panel.innerHTML = `
    <button class="satnav-endpoint" type="button" id="satnav-from" aria-pressed="false"><b>FROM</b><span>My location</span></button>
    <button class="satnav-endpoint" type="button" id="satnav-to" aria-pressed="false"><b>TO</b><span>Tap map</span></button>
    <div class="satnav-row">
      <button type="button" id="satnav-add" aria-label="Add a waypoint" aria-pressed="false">+ Pin</button>
      <button type="button" id="satnav-undo" disabled>Undo</button>
      <button type="button" id="satnav-edit" aria-controls="satnav-editor" aria-expanded="false" disabled>Edit</button>
    </div>
    <button type="button" id="satnav-use-fix" hidden>Place at my GPS fix</button>
    <div id="satnav-editor" hidden>
      <div class="satnav-row"><button type="button" id="satnav-prev" aria-label="Previous pin">Previous</button><button type="button" id="satnav-next" aria-label="Next pin">Next</button></div>
      <p id="satnav-selected"></p>
      <div class="satnav-row"><button type="button" id="satnav-replace">Move on map</button><button type="button" id="satnav-remove">Delete</button></div>
      <div class="satnav-row"><button type="button" id="satnav-earlier">Earlier</button><button type="button" id="satnav-later">Later</button></div>
      <p id="satnav-limit"></p>
    </div>
    <div class="satnav-row"><button type="button" id="satnav-location">My location</button><button type="button" id="satnav-stop" disabled>Stop</button></div>
    <p class="satnav-readout" id="satnav-status" role="status"></p>
    <p class="satnav-readout" id="satnav-guide" aria-label="Waypoint guidance"></p>
    <details id="satnav-infrastructure"><summary>Infrastructure layers</summary>
      <div class="satnav-row"><button type="button" id="satnav-osm11" aria-pressed="false" disabled>11 kV (OSM)</button></div>
      <div class="satnav-row"><button type="button" id="satnav-ukpn" aria-pressed="false" disabled>UKPN secondary</button></div>
      <p class="satnav-readout" id="satnav-layer-status" role="status"></p>
    </details>
    <div id="satnav-field-tools"></div>`;
  const access = document.createElement('details');
  access.id = 'satnav-access';
  access.innerHTML = '<summary>Check access before entry</summary><p>Maps do not grant access. You and your organisation must check land rights, restrictions and safe working conditions. Ventus retains its own legal and safety duties.</p>';
  const toggle = document.createElement('button');
  toggle.id = 'satnav-toggle';
  toggle.type = 'button';
  toggle.setAttribute('aria-controls', panel.id);
  let panelOpen = false;
  function setPanelOpen(open) {
    panelOpen = Boolean(open);
    panel.hidden = access.hidden = !panelOpen;
    toggle.setAttribute('aria-expanded', String(panelOpen));
    if (!panelOpen) picking = null; // cancel an uncommitted map-pick, never stop GPS or change the route
    render();
  }
  toggle.addEventListener('click', () => setPanelOpen(!panelOpen));
  panel.hidden = access.hidden = true;
  toggle.setAttribute('aria-expanded', 'false');
  toggle.textContent = 'SATNAV';
  document.body.append(toggle, panel, access);
  const controls = Object.fromEntries([...panel.querySelectorAll('[id]')].map(el => [el.id.slice(7), el]));
  const notify = (name, detail) => panel.dispatchEvent(new CustomEvent('satnav:' + name, { detail }));
  const updateText = (element, value) => { if (element.textContent !== value) element.textContent = value; };
  const distanceText = metres => metres >= 1000 ? (metres / 1000).toFixed(1) + ' km' : Math.round(metres) + ' m';
  const bearingText = degrees => (Math.round(degrees) % 360) + '°';
  const collection = features => ({ type: 'FeatureCollection', features });

  let state = createWaypointState();
  let snapshot = state.snapshot();
  let roles = { from: null, to: null, gpsOrigin: false };
  let selected = null, picking = null, closed = false;
  let guidance = createWaypointGuidance(maths, compass);
  // The model records reversible coordinate edits. Keep matching endpoint roles with each edit.
  let history = [], localPlan = null;
  let map = null, fix = null, watch = null, generation = 0, pendingLocation = false;
  let followCamera = false, layerSearch = null;
  const pauseFollow = () => { if (followCamera) { followCamera = false; render(); } };
  let resumedAt = null, lastFixMs = -Infinity, permissionDenied = false;
  let notice = '', planData = collection([]), positionData = collection([]);
  let planDirty = true, positionDirty = true, planDistance = 0, longLegs = 0, dateLineLegs = 0;
  const planSource = 'gridatlas-satnav-waypoints';
  const positionSource = 'gridatlas-satnav-position';
  const layers = [
    [positionSource, 'accuracy', 'gps-accuracy', 'fill', {'fill-color':'#ffdf61','fill-opacity':.22}],
    [planSource, 'line', 'selected-section', 'line', {'line-color':'#00ffff','line-width':3,'line-dasharray':[3,2]}],
    [planSource, 'via', 'waypoint', 'circle', {'circle-color':'#ffffff','circle-radius':6,'circle-stroke-color':'#006a76','circle-stroke-width':3}],
    [planSource, 'start', 'start-point', 'circle', {'circle-color':'#00ffff','circle-radius':7,'circle-stroke-color':'#071820','circle-stroke-width':2}],
    [planSource, 'end', 'destination-point', 'circle', {'circle-color':'#ff65d5','circle-radius':8,'circle-stroke-color':'#071820','circle-stroke-width':2}],
    [positionSource, 'gps', 'measured-gps', 'circle', {'circle-color':'#ffdf61','circle-radius':7,'circle-stroke-color':'#171100','circle-stroke-width':2}],
  ];

  function refreshGuidance() {
    let pins = roles.from && snapshot.pins.length > 1 ? snapshot.pins : [];
    if (closed) pins = [...pins, {id:'return-' + roles.from, coordinate:pins[0].coordinate}];
    guidance.setRoute(pins);
  }
  function changePlan() {
    snapshot = state.snapshot();
    closed = false;
    if (!snapshot.pins.some(pin => pin.id === selected)) selected = snapshot.pins[0]?.id ?? null;
    if (!selected) controls.editor.hidden = true;
    planDistance = 0;
    longLegs = 0;
    dateLineLegs = 0;
    const features = [];
    for (const [i, pin] of snapshot.pins.entries()) {
      const role = pin.id === roles.from ? 'start-point' : pin.id === roles.to ? 'destination-point' : 'waypoint';
      const feature = point(role, pin.coordinate);
      feature.properties.pinId = pin.id;
      feature.properties.order = i + 1;
      features.push(feature);
      if (!i) continue;
      const previous = snapshot.pins[i - 1].coordinate;
      const leg = classifyDirectLeg(maths, previous, pin.coordinate);
      planDistance += leg.metres;
      if (leg.status === 'over-limit') { longLegs++; continue; }
      if (leg.status === 'antimeridian') { dateLineLegs++; continue; }
      const geometry = directLegGeometry(maths, previous, pin.coordinate);
      if (geometry) features.push({type:'Feature', properties:{role:'selected-section'}, geometry});
    }
    planData = collection(features);
    planDirty = true;
    refreshGuidance();
    notify('pins', snapshot.pins);
    render();
  }
  function edit(operation) {
    const before = {...roles};
    if (!operation()) return false;
    history.push({roles:before});
    if (history.length > 256) history.shift();
    changePlan();
    return true;
  }
  function setPin(which, at, fromGps = false) {
    if (localPlan) {
      // A bad coordinate must leave the preview and the user's plan intact.
      createWaypointState().add(at);
      leaveExample();
      if (which === 'from' || (which === 'add' && !roles.from)) pendingLocation = false;
      if (which === 'to' && !roles.from && watch !== null && compass.fixQuality(fix) === 'usable') {
        pendingLocation = false;
        setPin('from', [fix.longitude, fix.latitude], true);
      }
    }
    const replaceId = which === 'replace' ? selected : roles[which];
    if (replaceId) {
      return edit(() => {
        if (!state.replace(replaceId, at)) return false;
        if (replaceId === roles.from) roles.gpsOrigin = fromGps;
        return true;
      });
    }
    return edit(() => {
      const toIndex = roles.to ? snapshot.pins.length - 1 : snapshot.pins.length;
      const establishesFrom = which === 'from' || (which === 'add' && !roles.from);
      const atIndex = establishesFrom ? 0 : which === 'to' ? snapshot.pins.length : toIndex;
      const id = state.add(at, atIndex);
      if (establishesFrom) {roles.from = id; roles.gpsOrigin = fromGps;}
      if (which === 'to') roles.to = id;
      selected = id;
      return true;
    });
  }
  function place(at, fromGps = false) {
    if (!picking) return;
    const which = picking;
    picking = null;
    if (which === 'from' || (which === 'add' && !roles.from) || (which === 'replace' && selected === roles.from)) pendingLocation = false;
    try { notice = ''; setPin(which, at, fromGps); }
    catch (error) { notice = error.message; }
    render();
  }
  function restoreLocalPlan() {
    if (!localPlan) return false;
    ({state, roles, selected, history} = localPlan);
    localPlan = null;
    snapshot = state.snapshot();
    guidance = createWaypointGuidance(maths, compass);
    pendingLocation = !roles.from && watch !== null;
    picking = null;
    notice = '';
    return true;
  }
  function leaveExample() {
    if (restoreLocalPlan()) changePlan();
  }
  function replacePlan(coordinates, {example = false} = {}) {
    if (!Array.isArray(coordinates) || !coordinates.length || coordinates.length > snapshot.maxPins) throw new RangeError('Choose a plan with 1 to 20,000 pins');
    const imported = createWaypointState();
    for (const at of coordinates) imported.add(at); // Validate everything before switching state.
    const newPins = imported.snapshot().pins;
    if (example) {
      localPlan ??= {state, roles, selected, history};
      history = [];
      controls.editor.hidden = true;
    } else {
      restoreLocalPlan();
      history = [{state, roles:{...roles}}];
    }
    state = imported;
    roles = {from:newPins[0].id, to:newPins.length > 1 ? newPins.at(-1).id : null, gpsOrigin:false};
    guidance = createWaypointGuidance(maths, compass);
    picking = null;
    pendingLocation = false;
    selected = roles.from;
    notice = '';
    changePlan();
  }
  function undo() {
    if (localPlan) {leaveExample(); return;}
    const previous = history.pop();
    if (!previous) return;
    if (previous.state) {
      state = previous.state;
      guidance = createWaypointGuidance(maths, compass);
    } else state.undo();
    roles = previous.roles;
    picking = null;
    pendingLocation = false;
    notice = '';
    changePlan();
  }

  function setFix(next) {
    fix = next;
    const features = [];
    if (next) {
      const at = [next.longitude, next.latitude];
      features.push(point('measured-gps', at));
      if (next.accuracyM > 0) features.push({type:'Feature',properties:{role:'gps-accuracy'},geometry:{type:'Polygon',coordinates:[maths.geodesicCircle(...at,next.accuracyM/1000,64)]}});
    }
    positionData = collection(features);
    positionDirty = true;
    notify('fix', next);
  }
  function fieldState(sample) {
    return assessFieldState({tracking:watch !== null,hidden:document.hidden,resumedAt,fix:sample,
      networkOnline:navigator.onLine,permissionDenied}, compass.fixQuality);
  }
  function refreshSources() {
    if (!map || !map.getLayer('l-sat')) return;
    for (const [id, data] of [[planSource,planData],[positionSource,positionData]]) {
      if (!map.getSource(id)) map.addSource(id, {type:'geojson',data});
      else if (id === planSource ? planDirty : positionDirty) map.getSource(id).setData(data);
    }
    for (const [source, key, role, type, paint] of layers) {
      const id = source + '-' + key;
      if (!map.getLayer(id)) map.addLayer({id,source,type,paint,filter:['==',['get','role'],role]});
    }
    // Keep the separately owned mapped-footpath line above infrastructure too.
    // One ordering owner avoids two timers fighting over the last layer.
    const navigationOrder = layers.map(([source,key]) => source + '-' + key);
    if (map.getLayer('satnav-active-walking-route')) navigationOrder.splice(2,0,'satnav-active-walking-route');
    reconcileNavigationLayers(map, navigationOrder);
    planDirty = positionDirty = false;
  }
  function guidanceText() {
    const result = guidance.locate(fix, Date.now());
    if (result.status === 'complete') return 'Arrived at the final pin';
    if (result.status === 'over-limit') return 'Direct leg exceeds 2 km · choose a nearer waypoint or destination';
    if (result.status !== 'guiding' || !Number.isFinite(result.distanceM)) return '';
    const name = closed && result.targetIndex === snapshot.pins.length ? 'Return to FROM' : 'Pin ' + (result.targetIndex + 1);
    const parts = [name, distanceText(result.distanceM)];
    if (Number.isFinite(result.bearingDeg)) parts.push(bearingText(result.bearingDeg) + ' true');
    if (Number.isFinite(result.remainingM)) parts.push(distanceText(result.remainingM) + ' remaining');
    if (result.offRoute === true) parts.push('Off planned line');
    return parts.join(' · ');
  }
  // The compact interface delegates selection to the existing native controls.
  // Never create a second infrastructure source or independently toggle visibility.
  const nativeLayers = [['osm11','11kv'],['ukpn','ukpn_secondary']];
  function nativeLayer(id) {
    return document.querySelector('#scada-ui-container input[data-layer-id="'+id+'"]');
  }
  function syncInfrastructureControls() {
    for (const [key,id] of nativeLayers) {
      const input = nativeLayer(id), button = controls[key];
      button.disabled = !map || !input || input.disabled || !map.getLayer('l-'+id);
      button.setAttribute('aria-pressed',String(Boolean(input?.checked)));
    }
    const available = nativeLayers.filter(([key]) => !controls[key].disabled).length;
    const deferred = nativeLayers.filter(([key,id]) => !controls[key].disabled && controls[key].getAttribute('aria-pressed') === 'true' && map.getZoom() < (map.getLayer('l-'+id).minzoom ?? 0));
    updateText(controls['layer-status'], !available ? 'Infrastructure unavailable in this composition'
      : deferred.length ? 'Selected layers appear at zoom '+Math.min(...deferred.map(([,id])=>map.getLayer('l-'+id).minzoom))+' or higher'
      : available < nativeLayers.length ? 'Some layers are unavailable in this composition' : '');
  }
  for (const [key,id] of nativeLayers) controls[key].onclick = () => {
    const input = nativeLayer(id);
    if (!map || !input || input.disabled || !map.getLayer('l-'+id)) return;
    input.click();
    syncInfrastructureControls();
    refreshSources();
  };
  function render() {
    refreshSources();
    syncInfrastructureControls();
    const count = snapshot.pins.length;
    controls.from.disabled = controls.to.disabled = controls.location.disabled = !map;
    controls.add.disabled = !map || count >= snapshot.maxPins;
    controls.stop.disabled = watch === null;
    updateText(controls.location, watch !== null ? (followCamera ? 'Following GPS' : 'Resume follow') : roles.from ? 'Start GPS' : 'My location');
    controls.undo.disabled = !localPlan && !history.length;
    controls.edit.disabled = !count || Boolean(localPlan);
    controls.edit.setAttribute('aria-expanded', String(!controls.editor.hidden));
    updateText(controls.from.querySelector('span'), picking === 'from' ? 'Tap map' : roles.from ? (roles.gpsOrigin ? 'GPS fix' : 'Selected point') : 'My location');
    updateText(controls.to.querySelector('span'), picking === 'to' || !roles.to ? 'Tap map' : 'Selected point');
    for (const key of ['from','to','add']) controls[key].setAttribute('aria-pressed', String(picking === key));
    controls['use-fix'].hidden = !picking || compass.fixQuality(fix) !== 'usable';
    if (!controls.editor.hidden) {
      const index = snapshot.pins.findIndex(pin => pin.id === selected);
      updateText(controls.selected, 'Pin ' + (index+1) + ' of ' + count + (selected === roles.from ? ' · FROM' : selected === roles.to ? ' · TO' : ''));
      updateText(controls.limit, 'Maximum ' + snapshot.maxPins.toLocaleString('en-GB') + ' pins');
      controls.prev.disabled = index <= 0;
      controls.next.disabled = index >= count - 1;
      const via = selected !== roles.from && selected !== roles.to;
      controls.earlier.disabled = !via || index <= (roles.from ? 1 : 0);
      controls.later.disabled = !via || index >= count - (roles.to ? 2 : 1);
    }
    const messages = [];
    if (!map) messages.push('Loading map');
    else if (picking) messages.push(picking === 'add' ? 'Tap map to add pin' : picking === 'replace' ? 'Tap map to move pin' : 'Tap map to set ' + picking.toUpperCase());
    else if (count > 1) messages.push(count + ' pins · ' + distanceText(planDistance) + ' planned');
    if (longLegs) messages.push('Direct leg exceeds 2 km · add a nearer waypoint or destination');
    if (dateLineLegs) messages.push('Line omitted at the date line');
    if (notice) messages.push(notice);
    if (fieldState(fix).mapAvailability === 'offline-unverified') messages.push('Offline · map coverage unverified');
    if (fix) {
      messages.push('GPS ±' + Math.round(fix.accuracyM) + ' m');
      if (fix.heading !== null && compass.fixQuality(fix) === 'usable') messages.push('GPS course ' + bearingText(fix.heading));
    }
    updateText(controls.status, messages.join(' · '));
    const guide = guidanceText();
    updateText(controls.guide, guide);
    updateText(toggle, panelOpen ? 'HIDE SATNAV' : watch !== null ? 'SATNAV · GPS active' : 'SATNAV');
    toggle.setAttribute('aria-label', panelOpen ? 'Hide SatNav controls' : watch !== null ? 'Show SatNav controls, GPS active' : 'Show SatNav controls');
    if (!panelOpen && watch !== null && guide) toggle.title = guide;
    else toggle.removeAttribute('title');
  }
  function arm(which) {
    picking = picking === which ? null : which;
    notice = '';
    if (picking === 'from') pendingLocation = false;
    render();
  }
  function mapClick(event) {
    if (picking && event.lngLat) {
      const at = event.lngLat.wrap ? event.lngLat.wrap() : event.lngLat;
      place([at.lng, at.lat]);
    } else if (event.point && !localPlan) {
      const {x,y} = event.point;
      const ids = ['start','via','end'].map(role => planSource + '-' + role);
      if (!ids.every(id => map.getLayer(id))) return;
      const hit = map.queryRenderedFeatures([[x-7,y-7],[x+7,y+7]], {layers:ids})[0];
      if (hit?.properties?.pinId) { selected = hit.properties.pinId; controls.editor.hidden = false; render(); }
    }
  }
  for (const name of ['from','to','add','replace']) controls[name].onclick = () => arm(name);
  controls['use-fix'].onclick = () => {
    if (compass.fixQuality(fix) === 'usable') place([fix.longitude,fix.latitude], true);
    else {notice = 'Waiting for a usable GPS fix';render();}
  };
  controls.undo.onclick = undo;
  controls.edit.onclick = () => {controls.editor.hidden = !controls.editor.hidden; picking = null; render();};
  const selectedIndex = () => snapshot.pins.findIndex(pin => pin.id === selected);
  for (const [name,offset] of [['prev',-1],['next',1]]) controls[name].onclick = () => {
    selected = snapshot.pins[selectedIndex() + offset].id;
    picking = null;
    render();
  };
  for (const [name,offset] of [['earlier',-1],['later',1]]) controls[name].onclick = () => {
    picking = null;
    edit(() => state.move(selected, selectedIndex() + offset));
  };
  controls.remove.onclick = () => {
    picking = null;
    edit(() => {
      const removed = selected;
      state.remove(removed);
      if (removed === roles.from) { roles.from = null; roles.gpsOrigin = false; pendingLocation = false; }
      if (removed === roles.to) roles.to = null;
      return true;
    });
  };
  function stopTracking(message) {
    generation++;
    if (watch !== null) navigator.geolocation.clearWatch(watch);
    watch = null;
    followCamera = false;
    lastFixMs = -Infinity;
    pendingLocation = false;
    notice = message;
    setFix(null);
    notify('stop');
    render();
  }
  function centreOnFix() {
    if ((!pendingLocation && !followCamera) || compass.fixQuality(fix) !== 'usable') return;
    const first = pendingLocation;
    pendingLocation = false;
    const at = [fix.longitude,fix.latitude];
    // An imported or hand-picked start belongs to the plan. Starting the GPS
    // centres the map. Only an empty FROM field takes this first measured fix.
    try { if (first && !roles.from) setPin('from', at, true); }
    catch (error) { notice = error.message; return; }
    map?.jumpTo({center:at});
  }
  controls.location.onclick = () => {
    if (!isSecureContext || !navigator.geolocation) {notice = 'Location needs HTTPS and device GPS';render();return;}
    pendingLocation = true;
    followCamera = true;
    permissionDenied = false;
    picking = null;
    notice = 'Waiting for GPS';
    if (watch !== null) {
      if (compass.fixQuality(fix) === 'usable') {notice = '';centreOnFix();}
      render();
      return;
    }
    const active = ++generation;
    try {
      watch = navigator.geolocation.watchPosition(position => {
        if (active !== generation) return;
        const {longitude,latitude,accuracy:accuracyM,heading,speed} = position.coords;
        const next = Object.freeze({longitude,latitude,accuracyM,timestampMs:position.timestamp,
          heading:Number.isFinite(heading) && heading >= 0 && heading < 360 && Number.isFinite(speed) && speed > 0 ? heading : null});
        const field = fieldState(next);
        const quality = field.gpsState;
        if (field.showMeasuredFix) {
          if (next.timestampMs < lastFixMs) return;
          lastFixMs = next.timestampMs;
          setFix(next);
          notice = quality === 'poor' ? 'Low GPS accuracy' : '';
          centreOnFix();
        } else {
          setFix(null);
          notice = quality === 'stale' ? 'GPS fix is stale' : 'Waiting for a fresh GPS fix';
        }
        render();
      }, error => {
        if (active !== generation) return;
        if (error.code === 1) {permissionDenied = true;stopTracking('Location permission denied');}
        else {setFix(null); notice = 'Location unavailable'; render();}
      }, {enableHighAccuracy:true,maximumAge:1000,timeout:10000});
      notify('watch');
    } catch {stopTracking('Location could not start');}
    render();
  };
  controls.stop.onclick = () => stopTracking('Location stopped');
  document.addEventListener('visibilitychange', () => {
    if (!document.hidden) resumedAt = Date.now();
    if (watch !== null) {
      setFix(null);
      notice = document.hidden ? 'GPS in background' : 'Waiting for a fresh GPS fix';
      render();
    }
  });
  window.addEventListener('offline', render);
  window.addEventListener('online', render);
  panel.addEventListener('keydown', event => {
    if (event.key === 'Escape') {event.stopPropagation(); picking = null; controls.editor.hidden = true; setPanelOpen(false); toggle.focus();}
  });
  for (const element of [toggle,panel,access]) {
    for (const name of ['click','dblclick','mousedown','pointerdown','touchstart']) element.addEventListener(name, event => event.stopPropagation());
  }
  // This is an interface-owned extension of the selected UKPN card.
  // No second popup, map, GPS watch, fabricated REPD identity or data fetch.
  function installAssetActions() {
    const card = map?.getContainer().querySelector('[data-ukpn-detail][data-site]');
    if (!card || card.querySelector('[data-satnav-asset-actions]')) return;
    const site = card.dataset.site;
    const actions = document.createElement('section');
    actions.dataset.satnavAssetActions = '1';
    const current = () => card.isConnected && actions.isConnected && card.dataset.site === site;
    const output = document.createElement('div');
    output.setAttribute('role','status');
    const button = (label, run) => {
      const el = document.createElement('button');
      el.type = 'button'; el.textContent = label;
      el.style.cssText = 'min-height:44px;display:block;width:100%;margin:3px 0';
      el.addEventListener('click', event => {
        event.stopPropagation();
        if (current()) run();
      });
      return el;
    };
    const selectedOrigin = () => {
      const source = map.getSource('src-ukpn_secondary');
      const feature = source?.serialize()?.data?.features?.find(f => String(f.id) === site);
      return feature?.geometry?.type === 'Point' ? feature.geometry.coordinates : null;
    };
    let gridRequest = 0;
    const neon = () => window.__GRIDATLAS_NEON_LINKS__;
    const clean = new MutationObserver(() => {if (!card.isConnected || card.dataset.site!==site) {++gridRequest;neon()?.clearSecondaryLinks?.(site);clean.disconnect();}});
    clean.observe(map.getContainer(),{childList:true,subtree:true,attributes:true,attributeFilter:['data-site']});
    actions.append(button('Ventus Grid Engine', async () => {
      const request = ++gridRequest;
      const valid = () => current() && request === gridRequest;
      output.replaceChildren();
      neon()?.clearSecondaryLinks?.();
      const origin = selectedOrigin();
      if (!origin) { output.textContent = 'Selected asset unavailable'; return; }
      const originalCamera = [map.getCenter().lng,map.getCenter().lat,map.getZoom(),map.getBearing(),map.getPitch()];
      output.textContent = 'Loading higher-voltage substations…';
      // Use the existing Grid Engine acquisition boundary, not a second dataset.