GLOBALGRID2050 / EXPLORE CODE

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

SatNav Practice Line and 4 more files

A JavaScript file in the atlas folder of GridAtlas using data from the SatNav repository. It formats metres (`formatMetres`), draws features (`drawFeatures`) and stops tracking (`stopTracking`).

674 lines of JavaScript from gridatlas, in 5 files. Topic: Maps, GIS and field navigation. Section 538 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. SatNav Practice Line render · gridatlas / atlas/modules/202611242248-satnav-practice-line.js lines 1–280
  2. Vicinity Legal Evidence render · gridatlas / atlas/modules/202611280016-vicinity-legal-evidence.js lines 1–75
  3. SatNav Compact Preview interaction · gridatlas / atlas/modules/202611281237-satnav-compact-preview.js lines 1–143
  4. SatNav Field Compass interaction · gridatlas / atlas/modules/202611281255-satnav-field-compass.js lines 1–147
  5. SatNav Offline Plan render · gridatlas / atlas/modules/202611281256-satnav-offline-plan.js lines 1–29

SatNav Practice Line

A JavaScript file in the atlas folder of GridAtlas using data from the SatNav repository. It formats metres (`formatMetres`), draws features (`drawFeatures`) and stops tracking (`stopTracking`).

rendergridatlas / atlas/modules/202611242248-satnav-practice-line.js · lines 1–280 of 280 · version 2026-11-24 22:48 · Not reached from any entry point (candidate for review) · pattern clearSelection (shared by 2 files)

What it does
It maps its content. Defines 10 functions or classes, including button, readout, formatMetres, drawFeatures, render. 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.
What it achieves
SatNav practice section preview. Positions and section coordinates are session-local. It responds to keydown, pagehide and pageshow 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
button, readout, formatMetres, drawFeatures, render, stopTracking, clearSelection, mapClick, showPanel, refresh
Defines here
button, readout, formatMetres, drawFeatures, render, stopTracking, clearSelection, mapClick, showPanel, refresh
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/202611242248-satnav-practice-line.js:1-280 · blob f8125829f7b62a8a4798533f6ba47ee4f1a79e52 · 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
/* SatNav practice section preview. Positions and section coordinates are session-local. */
void async function () {
  const root = new URL('../../../', location.href);
  const p1 = new URL('https://ventusltd.github.io/satnav/preview/9698781539e549deaa6ecaa4a2b34610c1f9fd29/');
  const [maths, { MAX_AGE_MS, fixQuality }, { createPositionOverlay, point }, { validCoordinate }, { buildDestination }] =
    await Promise.all([
      import(new URL('vendor/grid-distance-maths/src/geodesy.mjs', p1)),
      import(new URL('nav/compass.mjs', p1)),
      import(new URL('tools/satnav/line/position-overlay.mjs', root)),
      import(new URL('tools/vicinity/src/model.mjs', root)),
      import(new URL('tools/satnav/place.mjs', root)),
    ]);

  const style = document.createElement('style');
  style.textContent = `
    :root { --line-tracker-top:128px; }
    @media (max-width:600px) { :root { --line-tracker-top:136px; } }
    @media (max-width:359px) { :root { --line-tracker-top:214px; } }
    #line-open { position:fixed; top:var(--line-tracker-top); left:12px; z-index:10019; }
    #line-panel { position:fixed; top:calc(var(--line-tracker-top) + 52px); right:12px; z-index:10019;
      width:min(360px,calc(100% - 24px)); max-height:calc(100dvh - var(--line-tracker-top) - 64px);
      overflow:auto; padding:12px; box-sizing:border-box; color:#e4f7f7;
      background:#08141bf5; border:1px solid #367078; border-radius:6px;
      font:14px/1.4 ui-monospace,monospace; }
    #line-panel h2 { font-size:16px; margin:0 0 8px; color:#00ffff; }
    #line-panel p { margin:6px 0; }
    #line-open, #line-panel button { min-height:44px; padding:6px 8px; border:1px solid #367078;
      border-radius:4px; color:#bff7f9; background:#07191f; font:14px/1.4 ui-monospace,monospace;
      cursor:pointer; touch-action:manipulation; }
    #line-panel button:disabled { color:#8ba0a2; cursor:default; }
    #line-open:focus-visible, #line-panel button:focus-visible { outline:2px solid #fff; outline-offset:1px; }
    #line-panel .line-controls { display:flex; gap:6px; flex-wrap:wrap; margin:8px 0; }
    #line-panel [hidden], #line-panel[hidden] { display:none; }
    #line-panel .line-values { display:grid; grid-template-columns:1fr auto; gap:4px 10px; margin:8px 0; }
    #line-panel dd { margin:0; color:#00ffff; }
  `;
  document.head.append(style);

  const panel = document.createElement('section');
  panel.id = 'line-panel';
  panel.hidden = true;
  panel.setAttribute('aria-labelledby', 'line-title');
  const title = document.createElement('h2');
  title.id = 'line-title';
  title.textContent = 'Practice line tracking';
  const description = document.createElement('p');
  description.textContent = 'Draw a short practice section on the map. Track your position from a public path.';
  const status = document.createElement('p');
  status.id = 'line-status';
  status.setAttribute('role', 'status');
  status.textContent = 'Waiting for GridAtlas…';
  const choices = document.createElement('div');
  choices.className = 'line-controls';
  const controls = document.createElement('div');
  controls.className = 'line-controls';
  function button(id, label, parent) {
    const element = document.createElement('button');
    element.type = 'button';
    element.id = 'line-' + id;
    element.textContent = label;
    parent.append(element);
    return element;
  }
  const open = button('open', 'Line tracker', document.body);
  open.setAttribute('aria-controls', panel.id);
  open.setAttribute('aria-expanded', 'false');
  const dark = button('dark', 'Dark', choices);
  const satellite = button('satellite', 'Satellite', choices);
  const draw = button('draw', 'Pick start and end', controls);
  const cancel = button('cancel', 'Cancel selection', controls);
  const start = button('start', 'Start location', controls);
  const stop = button('stop', 'Stop location', controls);
  const compass = button('compass', 'Compass to end', controls);
  const close = button('close', 'Close', controls);
  const values = document.createElement('dl');
  values.className = 'line-values';
  function readout(id, label) {
    const term = document.createElement('dt');
    term.textContent = label;
    const value = document.createElement('dd');
    value.id = 'line-' + id;
    values.append(term, value);
    return value;
  }
  const accuracy = readout('accuracy', 'GPS accuracy');
  const offset = readout('offset', 'Distance from line');
  const progress = readout('progress', 'Progress from first tap');
  const legend = document.createElement('p');
  legend.textContent = 'Cyan: practice line. Yellow: your GPS. Pink: nearest point on the line.';
  panel.append(title, description, status, choices, controls, values, legend);
  document.body.append(panel);

  const sourceId = 'gridatlas-satnav-line-position';
  const layerSpecs = [
    ['accuracy', 'gps-accuracy', 'fill', { 'fill-color': '#ffdf61', 'fill-opacity': 0.22 }],
    ['section', 'selected-section', 'line', { 'line-color': '#00ffff', 'line-width': 4 }],
    ['start', 'start-point', 'circle', { 'circle-color': '#00ffff', 'circle-radius': 5 }],
    ['nearest', 'nearest-on-section', 'circle', { 'circle-color': '#ff65d5', 'circle-radius': 5 }],
    ['gps', 'measured-gps', 'circle', { 'circle-color': '#ffdf61', 'circle-radius': 6, 'circle-stroke-color': '#171100', 'circle-stroke-width': 2 }],
  ];
  let map, ownedSource, first, end, tracker, fix;
  let picking = false;
  let watch = null;
  let watchGeneration = 0;
  const formatMetres = value => Math.round(value) + ' m';

  function drawFeatures(features) {
    if (!map) return;
    if (!ownedSource) {
      if (!features.length || map.getSource(sourceId)) return;
      map.addSource(sourceId, { type: 'geojson', data: { type: 'FeatureCollection', features: [] } });
      ownedSource = map.getSource(sourceId);
      for (const [id, role, type, paint] of layerSpecs) {
        map.addLayer({
          id: sourceId + '-' + id, source: sourceId, type, paint,
          filter: ['==', ['get', 'role'], role],
        });
      }
    }
    if (map.getSource(sourceId) === ownedSource) ownedSource.setData({ type: 'FeatureCollection', features });
  }

  function render() {
    const { metrics, features } = tracker ? tracker(fix, Date.now()) :
      { metrics: null, features: first ? [point('start-point', first)] : [] };
    drawFeatures(features);
    choices.hidden = picking;
    description.hidden = picking || !!tracker;
    draw.hidden = picking || watch !== null;
    cancel.hidden = !picking;
    start.hidden = stop.hidden = values.hidden = legend.hidden = !tracker;
    compass.hidden = !tracker || watch !== null;
    draw.disabled = !map;
    start.disabled = watch !== null || !tracker;
    stop.disabled = watch === null;
    const usable = metrics?.status === 'ok';
    const quality = fixQuality(fix);
    accuracy.textContent = quality === 'usable' || quality === 'poor' ? '±' + formatMetres(fix.accuracyM) : '—';
    offset.textContent = usable ? formatMetres(metrics.offsetM) : '—';
    progress.textContent = usable ? formatMetres(metrics.progressM) + ' / ' + formatMetres(metrics.totalM) : '—';
    return metrics;
  }

  function stopTracking(message) {
    watchGeneration++;
    if (watch !== null) navigator.geolocation.clearWatch(watch);
    watch = null;
    fix = null;
    if (message) status.textContent = message;
  }

  function clearSelection(message) {
    stopTracking(message);
    tracker = first = end = null;
    picking = false;
    render();
  }

  function mapClick(event) {
    if (!picking || panel.hidden || !event.lngLat) return;
    const at = [event.lngLat.lng, event.lngLat.lat];
    if (!validCoordinate(at)) return;
    if (!first) {
      first = at;
      status.textContent = 'Tap the end less than 1 km from your first point.';
      render();
      return;
    }
    const length = maths.distanceKm(...first, ...at);
    if (length === 0 || length > 1) {
      status.textContent = 'Choose a different end within 1 km of your first point.';
      return;
    }
    tracker = createPositionOverlay([first, at], maths);
    end = at;
    picking = false;
    status.textContent = 'Practice section selected. Start location when ready.';
    render();
  }

  function showPanel(show) {
    panel.hidden = !show;
    open.setAttribute('aria-expanded', String(show));
    if (!show) {
      if (picking) clearSelection('Selection cancelled.');
      else stopTracking(tracker ? 'Location stopped. Your practice line is still selected.' : null);
    }
    render();
  }
  open.onclick = () => showPanel(panel.hidden);
  close.onclick = () => { showPanel(false); open.focus({ preventScroll: true }); };
  draw.onclick = () => {
    clearSelection('Tap the start of your practice line.');
    picking = true;
    render();
  };
  cancel.onclick = () => clearSelection('Selection cancelled.');
  dark.onclick = () => document.querySelector('#scada-ui-container input[name="bm"][value="dark"]')?.click();
  satellite.onclick = () => document.querySelector('#scada-ui-container input[name="bm"][value="sat"]')?.click();
  compass.onclick = () => {
    if (end) location.assign(new URL(buildDestination({ name: 'Practice line end', coordinates: end }), new URL('nav/', p1)));
  };

  start.onclick = () => {
    if (!tracker || watch !== null) return;
    if (!isSecureContext || !navigator.geolocation) {
      status.textContent = 'Location needs a secure browser connection.';
      return;
    }
    const generation = ++watchGeneration;
    status.textContent = 'Waiting for your location…';
    try {
      watch = navigator.geolocation.watchPosition(position => {
        if (generation !== watchGeneration) return;
        const { longitude, latitude, accuracy: accuracyM } = position.coords;
        fix = { longitude, latitude, accuracyM, timestampMs: position.timestamp };
        const metrics = render();
        const quality = fixQuality(fix);
        if (quality === 'usable') {
          status.textContent = metrics.status === 'ok' ? 'Location fix received.' : 'Progress is uncertain on this section.';
        } else if (quality === 'poor') {
          status.textContent = 'GPS accuracy is too low for line progress.';
        } else {
          status.textContent = 'Waiting for a usable location fix.';
        }
      }, error => {
        if (generation !== watchGeneration) return;
        if (error.code === 1) stopTracking('Location permission denied.');
        else {
          fix = null;
          status.textContent = 'Location unavailable. Waiting for another fix.';
        }
        render();
      }, { enableHighAccuracy: true, maximumAge: 1000, timeout: 10000 });
    } catch {
      stopTracking('Location could not start.');
    }
    render();
  };
  stop.onclick = () => { stopTracking('Location stopped.'); render(); };

  for (const event of ['click', 'dblclick', 'mousedown', 'pointerdown', 'touchstart']) {
    panel.addEventListener(event, input => input.stopPropagation());
  }
  panel.addEventListener('keydown', event => {
    if (event.key === 'Escape') { event.preventDefault(); showPanel(false); open.focus({ preventScroll: true }); }
  });

  function refresh() {
    const host = document.fullscreenElement || document.webkitFullscreenElement || document.body;
    if (open.parentElement !== host) host.append(open, panel);
    const nextMap = window.__GRIDATLAS_V9_MAP__;
    if (nextMap && nextMap !== map && nextMap.getLayer('l-sat')) {
      map?.off('click', mapClick);
      map = nextMap;
      ownedSource = null;
      map.on('click', mapClick);
      status.textContent = 'Pick a start and end on the map.';
      render();
    }
    if (fix && Date.now() - fix.timestampMs > MAX_AGE_MS) {
      fix = null;
      status.textContent = 'GPS fix is stale. Waiting for a fresh fix.';
      render();
    }
  }
  render();
  refresh();
  let timer = setInterval(refresh, 250);
  window.addEventListener('pagehide', () => {
    clearInterval(timer);
    stopTracking('Location stopped.');
    render();
  });
  window.addEventListener('pageshow', event => {
    if (!event.persisted) return;
    refresh();
    timer = setInterval(refresh, 250);
  });
}().catch(error => console.error('SatNav practice line preview failed', error));

Vicinity Legal Evidence

A JavaScript module in the atlas folder of GridAtlas covering the Renewable Energy Planning Database (REPD) register and uses data from the legislation repository.

rendergridatlas / atlas/modules/202611280016-vicinity-legal-evidence.js · lines 1–75 of 75 · version 2026-11-28 00:16 · Not reached from any entry point (candidate for review)

What it does
It draws the REPD register. Defines evidenceUrl, render, sync. 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. Domain terms in the code: the REPD register.
What it achieves
It is built from the evidence URL helper (`evidenceUrl`), the render step (`render`) and the sync step (`sync`). Read-only adapter for the selected origin in GridAtlas Vicinity. It responds to pagehide events.
Why it matters
No other file in the estate was found to import it.
Application
gridatlas · atlas/modules · JavaScript module
Uses
Legislation — Legal Evidence Page (estate URL)
Used by
none found
Produces
evidenceUrl, render, sync
Defines here
evidenceUrl, render, sync
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/202611280016-vicinity-legal-evidence.js:1-75 · blob cba4627b6b71135a710f79679518415afc2c2400 · 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: unreached_review
/* Read-only adapter for the selected origin in GridAtlas Vicinity. */
(function () {
  'use strict';
  const reader = 'https://ventusltd.github.io/legislation/legal-evidence/';

  function evidenceUrl(arrival, selectedRef) {
    let url;
    try { url = new URL(arrival); } catch { return null; }
    if (url.origin !== 'https://ventusltd.github.io' || url.username || url.password ||
        !/^\/gridatlas\/atlas\/(?:v\/\d{12}\/)?(?:index\.html)?$/.test(url.pathname)) return null;
    const query = url.searchParams;
    const keys = ['repd_ref','origin_id','origin_type','project','name','technology','capacity_mw','status','latitude','longitude'];
    if (keys.some(key => query.getAll(key).length > 1)) return null;
    const ref = query.get('repd_ref');
    if (!/^[1-9]\d{0,11}$/.test(ref || '') || String(selectedRef) !== ref) return null;
    if ((query.has('origin_type') && query.get('origin_type') !== 'repd') ||
        (query.has('origin_id') && query.get('origin_id') !== 'repd:' + ref)) return null;
    for (const [key, min, max] of [['latitude',49.5,61.5], ['longitude',-11,3]]) {
      const value = query.get(key);
      if (!value?.trim() || !Number.isFinite(Number(value)) || Number(value) < min || Number(value) > max) return null;
    }
    if (Math.abs(Number(query.get('latitude'))-49.766807) < .0001 &&
        Math.abs(Number(query.get('longitude'))+7.55716) < .0001) return null;
    const result = new URL(reader);
    result.searchParams.set('source_app','gridatlas');
    result.searchParams.set('repd_ref',ref);
    const version = /\/atlas\/v\/(\d{12})\//.exec(url.pathname);
    if (version) result.searchParams.set('source_release',version[1]);
    for (const [key,value,limit] of [['project',query.get('project') || query.get('name'),180],
      ['technology',query.get('technology'),80],['status',query.get('status'),80]]) {
      if (value?.trim()) result.searchParams.set(key,value.trim().slice(0,limit));
    }
    const mw = query.get('capacity_mw');
    if (mw?.trim() && Number.isFinite(Number(mw)) && Number(mw) > 0) result.searchParams.set('mw',String(Number(mw)));
    return result.href;
  }

  function render(card, arrival) {
    const box = card?.__vicFocus?.box;
    if (!box) return;
    const anchor = box.querySelector('[data-legislation-evidence]');
    const href = card.isConnected && card.project && card.__vicFocus.origin
      ? evidenceUrl(arrival, card.r?.p?.repd_ref) : null;
    if (!href) { anchor?.remove(); return; }
    if (anchor?.href === href) return;
    const link = anchor || box.ownerDocument.createElement('a');
    link.href = href;
    link.textContent = 'Legal evidence';
    link.dataset.legislationEvidence = '';
    link.target = '_blank';
    link.rel = 'noopener noreferrer';
    if (!anchor) box.appendChild(link);
  }

  if (typeof module === 'object' && module.exports) module.exports = {evidenceUrl, render};
  if (typeof window === 'undefined' || typeof document === 'undefined') return;
  let active, observer;
  function sync() {
    const card = window.__GRIDATLAS_MODULES__?.ukOfftakers?.state?.pp;
    if (active !== card) {
      observer?.disconnect();
      active = card;
      if (active) {
        observer = new MutationObserver(() => render(active,window.location.href));
        observer.observe(active,{subtree:true,childList:true});
      }
    }
    render(active,window.location.href);
  }
  // The focus cartridge changes this attribute as the project card opens/closes.
  const focus = new MutationObserver(sync);
  focus.observe(document.documentElement,{attributes:true,attributeFilter:['data-vicinity-focus']});
  window.addEventListener('pagehide',() => { focus.disconnect(); observer?.disconnect(); },{once:true});
  sync();
})();

SatNav Compact Preview

A JavaScript file in the atlas folder of GridAtlas using data from the SatNav repository. It maps click (`mapClick`), stops tracking (`stopTracking`) and applies location (`applyLocation`).

interactiongridatlas / atlas/modules/202611281237-satnav-compact-preview.js · lines 1–143 of 143 · version 2026-11-28 12:37 · Not reached from any entry point (candidate for review) · pattern features (shared by 5 files)

What it does
It maps its content. Defines 7 functions or classes, including features, render, arm, mapClick, stopTracking. 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.
What it achieves
GridAtlas map, independent endpoints, session-only GPS. It responds to keydown, pagehide and pageshow 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
features, render, arm, mapClick, stopTracking, applyLocation, refresh
Defines here
features, render, arm, mapClick, stopTracking, applyLocation, refresh
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/202611281237-satnav-compact-preview.js:1-143 · blob f1304517efa96295897b89c62076951de9e659c5 · 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
/* SatNav compact preview: GridAtlas map, independent endpoints, session-only GPS. */
void async function () {
  const root = new URL('../../../', location.href);
  const p1 = new URL('https://ventusltd.github.io/satnav/preview/9698781539e549deaa6ecaa4a2b34610c1f9fd29/');
  const [maths, { MAX_AGE_MS, fixQuality }, { point }, { validCoordinate }] = await Promise.all([
    import(new URL('vendor/grid-distance-maths/src/geodesy.mjs', p1)),
    import(new URL('nav/compass.mjs', p1)),
    import(new URL('tools/satnav/line/position-overlay.mjs', root)),
    import(new URL('tools/vicinity/src/model.mjs', root)),
  ]);
  const style = document.createElement('style');
  style.textContent = `
    body .dashboard { position:fixed!important; inset:0!important; height:100dvh!important; width:100vw!important; padding:0!important; display:block!important; }
    body #map-container { position:absolute!important; inset:0!important; width:100%!important; height:100%!important; border:0!important; border-radius:0!important; }
    body .hud-header,body .scada-wrapper,body .podcast-shoutout,body .search-bar-wrapper,body .map-controls,body #btn-fullscreen,body #fs-curtain-tab,body #fs-letterhead { display:none!important; }
    #satnav-compact { position:fixed; top:max(8px,env(safe-area-inset-top)); left:max(8px,env(safe-area-inset-left)); z-index:10030; display:grid; gap:5px; width:min(210px,calc(100vw - 24px)); color:#e4f7f7; font:13px/1.3 system-ui,sans-serif; }
    #satnav-compact button { min-height:44px; border:1px solid #367078; border-radius:6px; background:#081820; color:#e4f7f7; text-align:left; padding:6px 9px; font:inherit; touch-action:manipulation; }
    #satnav-compact button[aria-pressed=true] { outline:2px solid #00ffff; }
    #satnav-compact button:focus-visible { outline:2px solid white; }
    #satnav-compact button:disabled { opacity:.55; }
    #satnav-compact b { display:inline-block; width:45px; color:#68e8f5; }
    #satnav-gps-row { display:flex; gap:5px; }
    #satnav-gps-row button { flex:1; text-align:center; }
    #satnav-status { background:#081820e8; border-radius:4px; padding:3px 6px; margin:0; font-size:11px; overflow-wrap:anywhere; }
  `;
  document.head.append(style);
  const panel=document.createElement('section');
  panel.id='satnav-compact';
  panel.setAttribute('aria-label','SatNav map selection');
  panel.innerHTML='<button type="button" id="satnav-from" aria-pressed="false"><b>FROM</b><span>My location</span></button><button type="button" id="satnav-to" aria-pressed="false"><b>TO</b><span>Tap map</span></button><div id="satnav-gps-row"><button type="button" id="satnav-location">My location</button><button type="button" id="satnav-stop" disabled>Stop</button></div><p id="satnav-status" role  … [line shortened here: 427 characters; full line on GitHub]
  document.body.append(panel);
  const fromButton=panel.querySelector('#satnav-from'), toButton=panel.querySelector('#satnav-to'), locate=panel.querySelector('#satnav-location'), stop=panel.querySelector('#satnav-stop'), status=panel.querySelector('#satnav-status');
  let map, source, first=null, end=null, picking=null, fix=null, watch=null, generation=0, useLocation=true, pendingLocation=false, notice='', drawnKey=null;
  const sourceId='gridatlas-satnav-compact';
  const layers=[
    ['accuracy','gps-accuracy','fill',{'fill-color':'#ffdf61','fill-opacity':.22}],
    ['line','selected-section','line',{'line-color':'#00ffff','line-width':3,'line-opacity':.8}],
    ['start','start-point','circle',{'circle-color':'#00ffff','circle-radius':6,'circle-stroke-color':'#071820','circle-stroke-width':2}],
    ['end','destination-point','circle',{'circle-color':'#ff65d5','circle-radius':8,'circle-stroke-color':'#071820','circle-stroke-width':2}],
    ['gps','measured-gps','circle',{'circle-color':'#ffdf61','circle-radius':7,'circle-stroke-color':'#171100','circle-stroke-width':2}],
  ];
  function features() {
    const out=[];
    if(first)out.push(point('start-point',first));
    if(end)out.push(point('destination-point',end));
    const distance=first&&end?maths.distanceKm(...first,...end):null;
    if(distance>0&&distance<=1)out.push({type:'Feature',properties:{role:'selected-section'},geometry:{type:'LineString',coordinates:[first,end]}});
    if(fix&&['usable','poor'].includes(fixQuality(fix))&&Date.now()-fix.timestampMs<=MAX_AGE_MS){
      const at=[fix.longitude,fix.latitude];
      out.push(point('measured-gps',at));
      if(fix.accuracyM>0)out.push({type:'Feature',properties:{role:'gps-accuracy'},geometry:{type:'Polygon',coordinates:[maths.geodesicCircle(...at,fix.accuracyM/1000,64)]}});
    }
    return {out,distance};
  }
  function render() {
    const {out,distance}=features();
    const key=JSON.stringify(out);
    if(map&&source&&map.getSource(sourceId)===source&&key!==drawnKey){source.setData({type:'FeatureCollection',features:out});drawnKey=key;}
    fromButton.disabled=toButton.disabled=!map;
    fromButton.querySelector('span').textContent=picking==='from'?'Tap map':useLocation?'My location':first?'Selected point':'Tap map';
    toButton.querySelector('span').textContent=picking==='to'?'Tap map':end?'Selected point':'Tap map';
    fromButton.setAttribute('aria-pressed',String(picking==='from'));
    toButton.setAttribute('aria-pressed',String(picking==='to'));
    locate.disabled=!map;
    stop.disabled=watch===null;
    const parts=[];
    if(!map)parts.push('Loading map');
    else if(picking)parts.push('Tap map to set '+picking.toUpperCase());
    else if(distance!==null)parts.push(distance===0?'Same point':distance>1?'Points selected; practice line limited to 1 km':Math.round(distance*1000)+' m straight line');
    else parts.push('Select FROM or TO');
    if(notice)parts.push(notice);
    if(fix&&['usable','poor'].includes(fixQuality(fix)))parts.push('GPS ±'+Math.round(fix.accuracyM)+' m');
    const message=parts.join(' · ');
    if(status.textContent!==message)status.textContent=message;
  }
  function arm(which){picking=picking===which?null:which;render();}
  function mapClick(event){
    if(!picking||!event.lngLat)return;
    const at=[event.lngLat.lng,event.lngLat.lat];
    if(!validCoordinate(at))return;
    if(picking==='from'){first=at;useLocation=false;pendingLocation=false;}else end=at;
    picking=null;
    render();
  }
  fromButton.onclick=()=>arm('from');toButton.onclick=()=>arm('to');
  function stopTracking(message){
    generation++;
    if(watch!==null)navigator.geolocation.clearWatch(watch);
    watch=null;fix=null;pendingLocation=false;notice=message;render();
  }
  function applyLocation(){
    if(!pendingLocation||!fix||!validCoordinate([fix.longitude,fix.latitude]))return;
    first=[fix.longitude,fix.latitude];useLocation=true;pendingLocation=false;
    map?.jumpTo({center:first,zoom:Math.max(15,map.getZoom())});
  }
  locate.onclick=()=>{
    if(!isSecureContext||!navigator.geolocation){notice='Location needs HTTPS';render();return;}
    pendingLocation=true;picking=null;notice='Waiting for GPS';
    if(watch!==null){
      if(fix&&fixQuality(fix)==='usable'&&Date.now()-fix.timestampMs<=MAX_AGE_MS){applyLocation();notice='';}
      render();return;
    }
    const active=++generation;
    try {
      watch=navigator.geolocation.watchPosition(position=>{
        if(active!==generation)return;
        const {longitude,latitude,accuracy:accuracyM}=position.coords;
        fix={longitude,latitude,accuracyM,timestampMs:position.timestamp};
        if(fixQuality(fix)==='usable'&&Date.now()-fix.timestampMs<=MAX_AGE_MS&&validCoordinate([longitude,latitude])){
          applyLocation();
          notice='';
        }else notice='Waiting for a usable GPS fix';
        render();
      },error=>{
        if(active!==generation)return;
        if(error.code===1)stopTracking('Location permission denied');
        else{fix=null;notice='Location unavailable';render();}
      },{enableHighAccuracy:true,maximumAge:1000,timeout:10000});
    }catch{stopTracking('Location could not start');}
    render();
  };
  stop.onclick=()=>stopTracking('Location stopped');
  for(const event of ['click','dblclick','mousedown','pointerdown','touchstart'])panel.addEventListener(event,e=>e.stopPropagation());
  panel.addEventListener('keydown',e=>{if(e.key==='Escape'){picking=null;render();}});
  function refresh(){
    const host=document.fullscreenElement||document.webkitFullscreenElement||document.body;
    if(panel.parentElement!==host)host.append(panel);
    const next=window.__GRIDATLAS_V9_MAP__;
    if(next&&next.getLayer('l-sat')&&next!==map){
      map?.off('click',mapClick);map=next;source=null;drawnKey=null;map.on('click',mapClick);map.resize();
    }
    if(map&&!map.getSource(sourceId)){
      map.addSource(sourceId,{type:'geojson',data:{type:'FeatureCollection',features:[]}});
      source=map.getSource(sourceId);drawnKey=null;
      for(const [id,role,type,paint] of layers)map.addLayer({id:sourceId+'-'+id,source:sourceId,type,paint,filter:['==',['get','role'],role]});
    }
    if(fix&&Date.now()-fix.timestampMs>MAX_AGE_MS){fix=null;notice='GPS fix is stale';}
    render();
  }
  render();refresh();let timer=setInterval(refresh,250);
  window.addEventListener('pagehide',()=>{clearInterval(timer);stopTracking('Location stopped');});
  window.addEventListener('pageshow',event=>{if(event.persisted){refresh();timer=setInterval(refresh,250);}});
}().catch(error=>console.error('SatNav compact preview failed',error));

SatNav Field Compass

A JavaScript file in the atlas folder of GridAtlas that updates bearing (`updateBearing`) and attaches map (`attachMap`). It updates bearing (`updateBearing`) and attaches map (`attachMap`).

interactiongridatlas / atlas/modules/202611281255-satnav-field-compass.js · lines 1–147 of 147 · version 2026-11-28 12:55 · Not reached from any entry point (candidate for review) · pattern resume (shared by 6 files)

What it does
It draws its content. Defines 6 functions or classes, including orientation, stop, updateBearing, sourceChanged, attachMap. Side effects: changes the web page (DOM).
Why it exists in the grid workflow
Domain stage field_execution (path word 'compass'): 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.
What it achieves
Add-on for the versioned SatNav maps. It responds to click, deviceorientationabsolute and deviceorientation 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
orientation, stop, updateBearing, sourceChanged, attachMap, resume
Defines here
orientation, stop, updateBearing, sourceChanged, attachMap, resume
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/202611281255-satnav-field-compass.js:1-147 · blob 79932671eb52131b50c681d110054fe5742cf3f0 · 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
/* Add-on for the versioned SatNav maps. Reuses the existing location overlay. */
void (async function () {
  const root = new URL('../../../', location.href);
  const { deviceHeading, compactTargetBearing, formatDegrees } =
    await import(new URL('tools/satnav/orientation/heading.mjs', root));
  const panel = document.createElement('section');
  panel.id = 'field-compass';
  panel.setAttribute('aria-label', 'Field compass and land access');
  panel.innerHTML = `
    <div class="field-compass-row">
      <button id="field-compass-toggle" type="button" aria-pressed="false">Compass</button>
      <details id="field-land-access">
        <summary>Land access</summary>
        <p>Use an existing right of access or obtain permission. You and your organisation must respect restrictions and work safely. Ventus retains its own legal and safety duties.</p>
      </details>
    </div>
    <div id="field-compass-reading"></div>
    <div id="field-target-bearing"></div>`;
  const style = document.createElement('style');
  style.textContent = `
    #field-compass { position:fixed; z-index:10029; left:max(8px,env(safe-area-inset-left)); bottom:max(27px,calc(env(safe-area-inset-bottom) + 17px)); max-width:calc(100vw - 24px); color:#e4f7f7; font:13px/1.3 system-ui,sans-serif; }
    #satnav-field-tools > #field-compass { position:static; max-width:none; }
    .field-compass-row { display:flex; gap:5px; align-items:end; }
    #field-compass button,#field-compass summary { min-height:44px; box-sizing:border-box; padding:10px 9px; background:#081820; border:1px solid #367078; border-radius:6px; color:inherit; font:inherit; cursor:pointer; touch-action:manipulation; }
    #field-compass summary { display:flex; align-items:center; }
    #field-compass button[aria-pressed=true] { outline:2px solid #68e8f5; }
    #field-compass :focus-visible { outline:2px solid white; }
    #field-land-access p { position:absolute; left:0; bottom:100%; width:min(250px,calc(100vw - 36px)); padding:10px; border:1px solid #367078; border-radius:6px; background:#081820; }
    #field-compass-reading:not(:empty),#field-target-bearing:not(:empty) { background:#081820ed; width:fit-content; padding:2px 6px; margin-top:3px; border-radius:4px; font-variant-numeric:tabular-nums; }
  `;
  document.head.append(style);
  document.body.append(panel);
  const toggle = panel.querySelector('#field-compass-toggle');
  const reading = panel.querySelector('#field-compass-reading');
  const bearing = panel.querySelector('#field-target-bearing');
  const access = panel.querySelector('details');
  const sourceId = 'gridatlas-satnav-compact';
  let map = null;
  let enabled = false;
  let generation = 0;
  let expiry;
  let discovery;

  function orientation(event) {
    if (!enabled) return;
    const apple = typeof event.webkitCompassHeading === 'number';
    if (!apple && event.type !== 'deviceorientationabsolute' && event.absolute !== true) return;
    const angle = window.screen.orientation?.angle ?? window.orientation ?? 0;
    const heading = deviceHeading(event, angle);
    clearTimeout(expiry);
    if (!heading) {
      reading.textContent = 'Compass unavailable · hold phone level';
      return;
    }
    reading.textContent = 'Heading ' + formatDegrees(heading.degrees) + ' ' + heading.reference;
    expiry = setTimeout(() => { reading.textContent = 'Waiting for a fresh heading'; }, 10000);
  }
  function stop(message = '') {
    generation++;
    enabled = false;
    clearTimeout(expiry);
    window.removeEventListener('deviceorientation', orientation);
    window.removeEventListener('deviceorientationabsolute', orientation);
    toggle.setAttribute('aria-pressed', 'false');
    reading.textContent = message;
  }
  toggle.addEventListener('click', async () => {
    if (enabled) { stop(); return; }
    const api = window.DeviceOrientationEvent;
    if (!window.isSecureContext || !api) {
      reading.textContent = 'Phone compass unavailable';
      return;
    }
    const thisRun = ++generation;
    enabled = true;
    toggle.setAttribute('aria-pressed', 'true');
    reading.textContent = 'Waiting for compass';
    try {
      if (typeof api.requestPermission === 'function') {
        const result = await api.requestPermission(true);
        if (thisRun !== generation) return;
        if (result !== 'granted') { stop('Compass permission denied'); return; }
      }
      window.addEventListener('deviceorientationabsolute', orientation);
      window.addEventListener('deviceorientation', orientation);
      expiry = setTimeout(() => { reading.textContent = 'No compass reading · hold phone level'; }, 7000);
    } catch {
      if (thisRun === generation) stop('Compass permission unavailable');
    }
  });
  function updateBearing() {
    const features = map?.getSource(sourceId)?.serialize().data?.features;
    const text = compactTargetBearing(features);
    if (bearing.textContent !== text) bearing.textContent = text;
  }
  function sourceChanged(event) {
    if (event.sourceId === sourceId) updateBearing();
  }
  function attachMap() {
    access.hidden = Boolean(document.getElementById('satnav-access'));
    const fieldTools = document.getElementById('satnav-field-tools');
    if (fieldTools) {
      // Successor maps own the waypoint bearing and the access notice.
      if (panel.parentElement !== fieldTools) fieldTools.append(panel);
      bearing.textContent = '';
      clearInterval(discovery);
      map?.off('sourcedata', sourceChanged);
      map = null;
      return;
    }
    const current = window.__GRIDATLAS_V9_MAP__;
    if (current && current !== map) {
      map?.off('sourcedata', sourceChanged);
      map = current;
      map.on('sourcedata', sourceChanged);
      updateBearing();
    }
    const host = document.fullscreenElement || document.webkitFullscreenElement || document.body;
    if (panel.parentElement !== host) host.append(panel);
  }
  function resume() {
    clearInterval(discovery);
    discovery = setInterval(attachMap, 1000);
    attachMap();
  }
  document.addEventListener('satnav:ready', attachMap);
  // The waypoints panel dispatches this event even when permission is lost.
  document.addEventListener('satnav:stop', () => stop(), true);
  // The two-endpoint map has the same Stop button and no custom stop event.
  document.addEventListener('click', event => {
    if (event.target.closest?.('#satnav-stop')) stop();
  }, true);
  document.addEventListener('visibilitychange', () => {
    if (document.hidden) stop();
  });
  window.addEventListener('pagehide', () => {
    stop();
    clearInterval(discovery);
    map?.off('sourcedata', sourceChanged);
    map = null;
  });
  window.addEventListener('pageshow', event => { if (event.persisted) resume(); });
  panel.addEventListener('keydown', event => {
    if (event.key === 'Escape' && access.open) { access.open = false; access.querySelector('summary').focus(); }
  });
  resume();
})().catch(error => console.error('Field compass failed to initialise', error));

SatNav Offline Plan

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

rendergridatlas / atlas/modules/202611281256-satnav-offline-plan.js · lines 1–29 of 29 · version 2026-11-28 12:56 · Not reached from any entry point (candidate for review) · pattern attach (shared by 32 files)

What it does
It draws its content. Defines attach. 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.
What it achieves
Optional cartridge for the versioned waypoint maps. It responds to satnav 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
attach
Defines here
attach
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/202611281256-satnav-offline-plan.js:1-29 · blob 8f3a5c04fe87b835c315d3931307da396bd104cf · 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
// Optional cartridge for the versioned waypoint maps. Loading it never stores a plan.
void async function () {
  if (!/\/atlas\/v\/satnav-[\w.-]+\/(?:index\.html)?$/.test(location.pathname)) return;
  const root = new URL('../../../', location.href);
  const hostId = 'satnav-field-tools';
  let mounted = false;

  async function attach() {
    const host = document.getElementById(hostId);
    const survey = document.getElementById('satnav-compact')?.satnavSurvey;
    if (mounted || !host || !survey?.getPins) return;
    mounted = true;
    document.removeEventListener('satnav:ready', attach);
    try {
      const [{mountOfflinePlan}, maths] = await Promise.all([
        import(new URL('tools/satnav/field-reliability/offline-plan.mjs', root)),
        import(new URL('tools/satnav/vendor/9698781539e549deaa6ecaa4a2b34610c1f9fd29/vendor/grid-distance-maths/src/geodesy.mjs', root)),
      ]);
      mountOfflinePlan({container: host, getPins: survey.getPins, maths});
    } catch {
      const message = document.createElement('p');
      message.setAttribute('role', 'status');
      message.textContent = 'Offline plan controls could not load.';
      host.append(message);
    }
  }
  document.addEventListener('satnav:ready', attach);
  await attach();
}();