GLOBALGRID2050 / EXPLORE CODE

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

G204 Gps Camera 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 589 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. G204 Compact Dock interaction · gridatlas / atlas/modules/g204-compact-dock.js lines 1–50
  2. G204 Gps Camera geodesy · gridatlas / atlas/modules/g204-gps-camera.js lines 1–650

G204 Compact Dock

A JavaScript file in the atlas folder of GridAtlas. It is built from the mount step (`mount`) and the ready step (`ready`).

interactiongridatlas / atlas/modules/g204-compact-dock.js · lines 1–50 of 50 · Not reached from any entry point (candidate for review) · pattern ready (shared by 44 files)

What it does
It draws its content. Defines mount, ready. Side effects: changes the web page (DOM).
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.
What it achieves
G203-01: one native layout owner; original controls and listeners retained. It responds to satnav, pageshow and pagehide 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
mount, ready
Defines here
mount, ready
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/g204-compact-dock.js:1-50 · blob 0a62eddde72d37b3bd0cf264259fd25dcf5cb378 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: duplicate_candidate
/* G203-01: one native layout owner; original controls and listeners retained. */
(function(){
 'use strict';
 const D=document,W=window,R=D.documentElement;
 if(D.getElementById('g203-native-dock-style'))return;
 const css=D.createElement('style');css.id='g203-native-dock-style';
 css.textContent=`
 #g203-native-dock{position:fixed!important;left:max(8px,env(safe-area-inset-left,0px))!important;bottom:max(8px,env(safe-area-inset-bottom,0px))!important;top:auto!important;right:auto!important;z-index:10031!important;display:grid!important;grid-template-columns:repeat(4,minmax(44px,1fr));grid-template-rows:44px 44px;gap:4px;width:min(284px,calc(100vw - 16px - env(safe-area-inset-left,0px) - env  … [line shortened here: 450 characters; full line on GitHub]
 #g203-native-dock #gridatlas-mobile-tray{display:contents!important;position:static!important}
 #g203-native-dock :is(#satnav-toggle,#gridatlas-dash-toggle,#gridatlas-mobile-tray>button){position:static!important;inset:auto!important;float:none!important;transform:none!important;margin:0!important;box-sizing:border-box!important;width:100%!important;min-width:44px!important;max-width:none!important;height:44px!important;min-height:44px!important;padding:0 3px!important;font:600 11px/1 syste  … [line shortened here: 501 characters; full line on GitHub]
 #g203-native-dock #satnav-toggle{grid-area:2/1}
 #g203-native-dock #gridatlas-mobile-tray>button:nth-child(2){grid-area:2/2}
 #g203-native-dock #gridatlas-mobile-tray>button:nth-child(3){grid-area:2/3}
 #g203-native-dock #gridatlas-dash-toggle{grid-area:2/4}
 #g203-native-dock #gridatlas-mobile-tray>button:nth-child(1){grid-area:1/1}
 #g203-native-dock #gridatlas-mobile-tray>button:nth-child(4){grid-area:1/2}
 #g203-native-dock #gridatlas-mobile-tray>button:nth-child(5){grid-area:1/3}
 #g203-native-dock :is(#satnav-toggle,#gridatlas-dash-toggle,#gridatlas-mobile-tray>button:nth-child(2),#gridatlas-mobile-tray>button:nth-child(3)){font-size:0!important}
 #g203-native-dock :is(#satnav-toggle,#gridatlas-dash-toggle,#gridatlas-mobile-tray>button:nth-child(2),#gridatlas-mobile-tray>button:nth-child(3))::after{font:600 11px/1 system-ui,sans-serif}
 #g203-native-dock #satnav-toggle::after{content:'SATNAV'}
 #g203-native-dock #satnav-toggle[aria-expanded=true]::after{content:'SATNAV ▴'}
 #g203-native-dock #satnav-toggle[aria-label*="GPS active"]::after{content:'SATNAV •'}
 #g203-native-dock #gridatlas-mobile-tray>button:nth-child(2)::after{content:'GRID'}
 #g203-native-dock #gridatlas-mobile-tray>button:nth-child(3)::after{content:'SUBS'}
 #g203-native-dock #gridatlas-dash-toggle{display:flex!important;align-items:center!important;justify-content:center!important;text-align:center!important;background:#081820ed!important;color:#e4f7f7!important;border:1px solid #367078!important;border-radius:6px!important;box-shadow:none!important;line-height:1!important;letter-spacing:normal!important}
 #g203-native-dock #gridatlas-dash-toggle>*{display:none!important}
 #g203-native-dock #gridatlas-dash-toggle::before{content:none!important}
 #g203-native-dock #gridatlas-dash-toggle::after{content:'LAYERS';display:block!important;position:static!important;margin:0!important;color:inherit!important;font:600 11px/1 system-ui,sans-serif!important}
 #g203-native-dock #gridatlas-dash-toggle:focus-visible{outline:2px solid white!important;outline-offset:2px}
 html[data-g203-compact-dock]{--g203-dock-clearance:104px}
 `;
 D.head.append(css);
 const dock=D.createElement('div');dock.id='g203-native-dock';dock.setAttribute('role','group');dock.setAttribute('aria-label','GridAtlas map controls');
 function mount(){
   const host=D.fullscreenElement||D.webkitFullscreenElement||D.body;
   const toggle=D.getElementById('satnav-toggle'),tray=D.getElementById('gridatlas-mobile-tray'),layers=D.getElementById('gridatlas-dash-toggle');
   if(!host||!toggle||!tray||!layers)return false;
   if(dock.parentElement!==host)host.append(dock);
   for(const el of [toggle,tray,layers])if(el.parentElement!==dock)dock.append(el);
   for(const key of ['position','top','bottom','right','left','z-index','pointer-events','touch-action','min-height'])if(layers.style.getPropertyPriority(key)==='important')layers.style.removeProperty(key);
   layers.hidden=false;R.setAttribute('data-g203-compact-dock','');return true;
 }
 const ready=()=>{if(mount())observer.disconnect()};
 const observer=new MutationObserver(ready);
 if(!mount())observer.observe(D.documentElement,{childList:true,subtree:true});
 D.addEventListener('satnav:ready',ready);
 for(const event of ['fullscreenchange','webkitfullscreenchange'])D.addEventListener(event,mount);
 W.addEventListener('pageshow',mount);
 W.addEventListener('pagehide',()=>observer.disconnect(),{once:true});
}());

G204 Gps Camera

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: 98% of its lines are the same as atlas/modules/g203-03-gps-camera-candidate.js (gridatlas), which stays. (near-copy-of, proposed by families.py). 97% of lines shared with G203 03 Gps Camera Candidate; read that one first. All set-aside files, with reasons. Nothing was deleted.

Evidence
  • line-jaccard 0.9766 to gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 atlas/modules/g203-03-gps-camera-candidate.js:1-735 e48c743713123f1c7d099641118d83aa4886286d
  • sha256 219589528cfeafa2fe9031fb272c29236f4f9d0df9e5cad559d2a7782d80da00
  • target sha256 198e80cfdb7ed663a5633413ee51e8f77188e3311c6fc081e1cb6b3ca1e50790
  • group of 3 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines

geodesygridatlas / atlas/modules/g204-gps-camera.js · lines 1–650 of 731 · Not reached from any entry point (candidate for review) · pattern shouldAcceptCameraFix (shared by 3 files)

What it does
It maps substations and 11kV. Defines 40 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 'gps'): 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
Unified GridAtlas/SatNav candidate. 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, cameraTarget, shouldAcceptCameraFix, pauseFollow, pauseGesture, refreshGuidance, changePlan
Defines here
setPanelOpen, notify, updateText, distanceText, bearingText, collection, cameraTarget, shouldAcceptCameraFix, pauseFollow, pauseGesture, refreshGuidance, changePlan, edit, setPin, place, restoreLocalPlan, leaveExample, replacePlan, undo, setFix, fieldState, refreshSources, guidanceText, nativeLayer, syncInfrastructureControls, render, arm, mapClick, selectedIndex, stopTracking
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/g204-gps-camera.js:1-650 · blob a2f977d2bf13bf51a3cbb8e4bda0b78c9e188b0a · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: field_execution · users: EPC_contractor, landowner_planner · canonical: duplicate_candidate
/* 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-unlimited.mjs', root)),
    import(new URL('tools/satnav/field-reliability/state.mjs', root)),
    import(new URL('tools/satnav/guidance/convergence-unlimited.mjs', root)),
    import(new URL('atlas/modules/unified-destination-unlimited.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;
  let locationRequestedAt = null, streetZoomPending = false;
  // G203-03 camera policy; no additional watch, listener timer, or data acquisition.
  function cameraTarget(map,fix,streetZoom){
    if (!map || !fix) return null;
    const target={center:[fix.longitude,fix.latitude]};
    if(streetZoom){
      const current=map.getZoom(), maximum=map.getMaxZoom();
      if(Number.isFinite(current)&&Number.isFinite(maximum))target.zoom=Math.min(maximum,Math.max(17,current));
    }
    return target;
  }
  function shouldAcceptCameraFix(fix,quality,requestedAt,hidden){
    return !hidden && quality==="usable" && fix!==null && Number.isFinite(fix.timestampMs) && (requestedAt===null||fix.timestampMs>=requestedAt);
  }
  const pauseFollow = () => {
    if (followCamera) {
      followCamera = false;
      streetZoomPending = false;
      render();
    }
  };
  const pauseGesture = event => { if (event?.originalEvent) pauseFollow(); };
  let resumedAt = null, lastFixMs = -Infinity, permissionDenied = false;
  let notice = '', planData = collection([]), positionData = collection([]);
  let planDirty = true, positionDirty = true, planDistance = 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;
    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 === '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 !== '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 (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;
    streetZoomPending = false;
    locationRequestedAt = null;
    lastFixMs = -Infinity;
    pendingLocation = false;
    notice = message;
    setFix(null);
    notify('stop');
    render();
  }
  function centreOnFix() {
    if ((!pendingLocation && !followCamera) ||
        !shouldAcceptCameraFix(fix,fieldState(fix).gpsState,locationRequestedAt,document.hidden)) return;
    const first = pendingLocation;
    pendingLocation = false;
    locationRequestedAt = null;
    const at = [fix.longitude,fix.latitude];
    // Preserve explicit FROM and route pins; only an empty FROM takes the first fix.
    try { if (first && !roles.from) setPin('from', at, true); }
    catch (error) { notice = error.message; return; }
    if (!followCamera) return; // A gesture may precede the first usable fix.
    const target = cameraTarget(map,fix,streetZoomPending);
    if (target) {
      streetZoomPending = false;
      map.jumpTo(target); // Subsequent fixes and Resume follow preserve zoom/bearing/pitch.
    }
  }
  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 (shouldAcceptCameraFix(fix,fieldState(fix).gpsState,locationRequestedAt,document.hidden)) {notice = '';centreOnFix();}
      render();
      return;
    }
    locationRequestedAt = Date.now();
    streetZoomPending = true;
    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:0,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.
      try {
        window.__GRIDATLAS_NEON_LINKS__?.enableSubstationLayer?.();
        const deadline = Date.now() + 60000;
        let nodes = [];
        while (valid()) {
          const engine = window.__GRIDATLAS_NEON_LINKS__;
          const distance = typeof engine?.measure?.distanceKm === 'function'
            ? (...args) => engine.measure.distanceKm(...args)
            : typeof globalThis.VentusGridCompute?.distanceKm === 'function'
              ? (...args) => globalThis.VentusGridCompute.distanceKm(...args) : null;
          if (engine?.substations?.length && distance) nodes = rankHigherVoltage(engine.substations, origin, distance);
          if (nodes.length || Date.now() >= deadline) break;
          await new Promise(resolve => setTimeout(resolve,250));
        }
        if (!valid()) return;
        if (!nodes.length) { output.textContent = 'No qualifying higher-voltage sites loaded; try again'; return; }
        const ok = neon()?.drawSecondaryLinks?.({site,origin,nodes});
        if (!valid()) return;
        renderGridNodes(nodes, origin, valid);
        if (!ok) output.prepend('Neon geometry unavailable; retry. ');
        else if (watch === null && [map.getCenter().lng,map.getCenter().lat,map.getZoom(),map.getBearing(),map.getPitch()].every((v,i)=>v===originalCamera[i])) {
          const points=[origin,...nodes.map(n=>n.at)];
          const bounds=[[Math.min(...points.map(p=>p[0])),Math.min(...points.map(p=>p[1]))],[Math.max(...points.map(p=>p[0])),Math.max(...points.map(p=>p[1]))]];
          map.fitBounds(bounds,{padding:Math.min(56,Math.floor(innerWidth/6),Math.floor(innerHeight/6)),maxZoom:13,duration:300});
        }
      } catch (error) {
        if (valid()) output.textContent = 'Grid Engine unavailable; try again';
      }
    }), button('Vicinity', () => {
      ++gridRequest;
      neon()?.clearSecondaryLinks?.();
      const origin = selectedOrigin();
      const engine = window.__GRIDATLAS_MODULES__?.ukOfftakers;
      if (!origin || typeof engine?.openSecondaryVicinity !== 'function') {
        output.textContent = 'Secondary Vicinity is not available in this composition'; return;
      }
      if (!engine.openSecondaryVicinity({site,at:origin})) {
        output.textContent = 'Vicinity not ready; try again'; return;
      }
      notice = 'Vicinity opened for '+site;
      render();
    }), output);
    function renderGridNodes(nodes, origin, valid) {
      output.textContent = 'Mapped substations ≥33 kV · straight-line screening, not proven electrical connections or access.';
      if (!nodes.length) { output.append(' No qualifying sites found.'); return; }
      for (const node of nodes) {
        const row = document.createElement('div');
        row.textContent = node.name + ' · ' + node.kv + ' kV · ' + node.km.toFixed(2) + ' km from selected secondary';
        row.append(button('Use this destination', () => {
          if (!valid()) return;
          const result = prepareAssetDestination(maths, fix, node.at, watch !== null, fieldState(fix).gpsState);
          if (!result.ok) { notice = result.reason; render(); return; }
          replacePlan(result.coordinates);
          notice = 'Destination: ' + node.name;
          render();
        }));
        output.append(row);
      }
    }
    card.append(actions);
  }
  function refresh() {
    const host = document.fullscreenElement || document.webkitFullscreenElement || document.body;
    const dockOwnsControls = Boolean(document.getElementById('g203-native-dock')?.isConnected);
    if (panel.parentElement !== host || access.parentElement !== host) host.append(panel,access);
    if (!dockOwnsControls && toggle.parentElement !== host) host.append(toggle);
    const mapBounds = window.__GRIDATLAS_V9_MAP__?.getContainer()?.getBoundingClientRect();
    const layers = document.getElementById('gridatlas-dash-toggle')?.getBoundingClientRect();
    const tray = document.getElementById('gridatlas-mobile-tray');
    const mapBottom = Math.min(innerHeight,mapBounds?.bottom ?? innerHeight);
    const right = Math.max(12,innerWidth-Math.min(innerWidth,mapBounds?.right ?? innerWidth)+8);
    const layerAtBottom = layers?.height>0 && layers.top>innerHeight/2;
    const trayBottom = Math.max(12,innerHeight-mapBottom+8,layerAtBottom?innerHeight-layers.top+6:0);
    const put = (el,key,value) => {const v=Math.round(value)+'px';if(el.style.getPropertyValue(key)!==v)el.style.setProperty(key,v);};
    if (tray) {
      if (!dockOwnsControls && tray.parentElement!==host) host.appendChild(tray);
      if (!tray.hasAttribute('data-satnav-dock')) tray.setAttribute('data-satnav-dock','');
      put(tray,'--satnav-dock-right',right);put(tray,'--satnav-tray-bottom',trayBottom);
    }
    const trayHeight = Math.max(44,tray?.getBoundingClientRect().height||44);
    const toggleBottom = trayBottom+trayHeight+6;
    put(toggle,'--satnav-dock-right',right);put(toggle,'--satnav-dock-bottom',toggleBottom);
    const panelBottom = toggleBottom+Math.max(44,toggle.getBoundingClientRect().height)+6;
    put(panel,'--satnav-dock-right',right);put(panel,'--satnav-panel-bottom',panelBottom);