GLOBALGRID2050 / EXPLORE CODE

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

Orient17b Walk and 1 more file

A JavaScript file in the atlas folder of GridAtlas that resets recovery (`resetRecovery`), attaches map (`attachMap`), syncs plan (`syncPlan`) and reads inputs for SatNav walk mode and SatNav route objective.

440 lines of JavaScript from gridatlas, in 2 files. Topic: Maps, GIS and field navigation. Section 574 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. Orient17b Walk geodesy · gridatlas / atlas/modules/202612040110-orient17b-walk.js lines 1–354
  2. Orient17a Compass interaction · gridatlas / atlas/modules/202612040126-orient17a-compass.js lines 1–86

Orient17b Walk

A JavaScript file in the atlas folder of GridAtlas that resets recovery (`resetRecovery`), attaches map (`attachMap`), syncs plan (`syncPlan`) and reads inputs for SatNav walk mode and SatNav route objective.

geodesygridatlas / atlas/modules/202612040110-orient17b-walk.js · lines 1–354 of 354 · version 2026-12-04 01:10 · Not reached from any entry point (candidate for review) · pattern renderRegional (shared by 3 files)

What it does
It maps its content. Defines 19 functions or classes, including mount, routed, unsupported, choose, resetRecovery. Side effects: changes the web page (DOM).
Why it exists in the grid workflow
Domain stage field_execution (path word 'walk'): 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.
Inputs & outputs
In: form fields (user input).
What it achieves
It resets recovery (`resetRecovery`), attaches map (`attachMap`) and syncs plan (`syncPlan`). Location and camera remain owned by the waypoint cartridge. It responds to resize, fullscreenchange and webkitfullscreenchange 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, routed, unsupported, choose, resetRecovery, manualRecovery, distance, bearing, clearHeader, draw, attachMap, clearRoute
Defines here
mount, routed, unsupported, choose, resetRecovery, manualRecovery, distance, bearing, clearHeader, draw, attachMap, clearRoute, calculate, syncPlan, liveRoute, renderRegional, show, render, stopWalk
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/202612040110-orient17b-walk.js:1-354 · blob 552061539ac6d2da6ef69972d4760cdff6507079 · 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
/* ORIENT-17.2 regional candidate, no production promotion. Location and camera remain owned by the waypoint cartridge. */
void async function () {
  const root = new URL('../../../', location.href);
  const [{createDirectWalk,walkTargets}, compass, {createRouteFollower}, {mountGateControls}, {prepareGateJob}, {createRecovery}, {createRegionalProvider}, {regionalConfig}, {createSnapshotProvider, snapshot}] = await Promise.all([
    import(new URL('tools/satnav/walk/orient17a-v9212-direct.mjs',root)),
    import(new URL('tools/satnav/vendor/9698781539e549deaa6ecaa4a2b34610c1f9fd29/nav/compass.mjs',root)),
    import(new URL('tools/satnav/line/route-follower.mjs',root)),
    import(new URL('tools/satnav/walk/gate/jobs/controls.mjs',root)),
    import(new URL('tools/satnav/walk/gate/jobs/plan.mjs',root)),
    import(new URL('tools/satnav/line/orient16-recovery-safe.mjs',root)),
    import(new URL('tools/satnav/regional/valhalla-provider.mjs',root)),
    import(new URL('tools/satnav/regional/regional-config.mjs',root)),
    import(new URL('tools/satnav/regional/vedic-snapshot-provider.mjs',root)),
  ]);
  let mounted = false;
  function mount() {
    const panel = document.getElementById('satnav-compact');
    const api = panel?.satnavSurvey;
    if (mounted || !api) return;
    mounted = true;
    const css = document.createElement('style');
    css.textContent = `
      #satnav-compact{--satnav-walk-top:max(env(safe-area-inset-top,0px),var(--gridatlas-menu-bar-clear,8px),var(--satnav-measured-menu-bottom,8px));top:var(--satnav-walk-top)!important;max-height:calc(100dvh - var(--satnav-walk-top) - 42px)!important}
      #gridatlas-menu-bar{z-index:10045!important}
      body:has(#gridatlas-menu-bar .gm-open) #satnav-compact{visibility:hidden}
      #satnav-compact #satnav-guide{display:none!important}
      #satnav-walk-actions{display:grid;grid-template-columns:1fr 1fr;gap:4px}
      #satnav-walk-actions select{min-height:44px;min-width:0;width:100%;border:1px solid #367078;border-radius:6px;background:#081820;color:#e4f7f7;font:inherit}
      #satnav-walk-actions [hidden]{display:none!important}
      #satnav-walk-actions #satnav-walk-start{border-color:#60d6d9}
      #satnav-walk-guidance{background:#081820ed;color:#b2faf7;margin:0;padding:4px 7px;border-radius:4px;font-size:12px;line-height:1.35}
      #satnav-walk-guidance:empty{display:none}
      #satnav-walk-source{background:#081820ed;padding:4px 7px;border-radius:4px;font-size:11px}
      #satnav-gate-actions{padding:3px 7px;background:#081820ed;color:#b2faf7}
      #satnav-gate-actions[hidden]{display:none}
      #satnav-gate-actions button{min-height:44px;padding:4px 8px}
      #satnav-gate-actions output:not(:empty){display:block;padding:4px 0}
      #satnav-compact .satnav-job-name{display:none}
      #satnav-compact .satnav-job-endpoint[aria-pressed=false] span{display:none}
      #satnav-compact .satnav-job-endpoint[aria-pressed=false] .satnav-job-name{display:inline-block;max-width:calc(100% - 46px);vertical-align:middle;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
      #satnav-gate-switch{margin:0;padding:4px 7px;background:#081820ed;color:#b2faf7;font-size:12px}
      #satnav-walk-source a{color:#8bf7f7}
    `;
    document.head.append(css);
    const row = document.createElement('div');
    row.id = 'satnav-walk-actions';
    row.innerHTML = '<select id="satnav-walk-mode" aria-label="Guidance mode"><option value="walking">Walking · distance prioritised</option><option value="driving">Driving</option><option value="direct" selected>Manual orientation</option><option value="mapped">Mapped footpath (legacy)</option></select><select id="satnav-route-objective" aria-label="Driving route objective" hidden><option value="  … [line shortened here: 659 characters; full line on GitHub]
    const message = document.createElement('p');
    message.id = 'satnav-walk-guidance';
    message.setAttribute('role','status');
    const sourceNote = document.createElement('details');
    sourceNote.id = 'satnav-walk-source';sourceNote.hidden = true;
    sourceNote.innerHTML = '<summary>Footpath source and restrictions</summary><span></span> <a target="_blank" rel="noopener">Council closures</a> · <a target="_blank" rel="noopener">Licence</a>';
    document.getElementById('satnav-to').after(row,message,sourceNote);
    const start = row.querySelector('#satnav-walk-start'), stop = row.querySelector('#satnav-walk-stop');
    const mode = row.querySelector('select');
    const objective = row.querySelector('#satnav-route-objective');
    const routed = () => ['walking','driving'].includes(mode.value);
    // Explicit development opt-in: no national service, no private location upload.
    const pilot = new URLSearchParams(location.search).get('routing-pilot') === 'oxford';
    const provider = pilot ? createSnapshotProvider({maths:api.maths}) : null;
    const unsupported = () => mode.value !== 'direct' && !(routed() && provider);
    const gps = panel.querySelector('#satnav-location'), stopGps = panel.querySelector('#satnav-stop');
    const choose = () => panel.querySelector('[data-loop]')?.getAttribute('aria-pressed') === 'true';
    const direct = createDirectWalk(api.maths,compass);
    const recovery = createRecovery({maths:api.maths,provider});
    let recoveryKey='', recoveryTimer=null, resumeAfter=-Infinity, routeDrawKey='';
    function resetRecovery(){recovery.stop();recoveryKey='';routeDrawKey='';if(recoveryTimer!==null){clearInterval(recoveryTimer);recoveryTimer=null;}}
    function manualRecovery(sample){
      const target=targets[0]?.coordinate;
      if(!target)return null;
      const identity=JSON.stringify(target);
      if(identity!==recoveryKey){recovery.setJourney({mode:'direct',target});recoveryKey=identity;recovery.start();}
      if(sample)recovery.ingest(sample);
      return recovery.tick().instruction;
    }
    const distance = m => m < 1000 ? Math.round(m) + ' m' : (m / 1000).toFixed(2) + ' km';
    const bearing = n => Math.round(n) % 360 + '° true';
    const lineId = 'satnav-active-walking-route';
    let active = false, stopped = false, targets = [], walkingOrigin = null;
    let routerPromise = null, key = '', request = 0, routeState = 'none', geometry = null, follow = null;
    let routeMap = null, drawn = null, arrived = false;

    // Only the built-in replay is temporary. A file the crew opens is their plan.
    const gateApi = {...api, replacePlan: points => api.replacePlan(points, {example: mode.value === 'gate'})};
    const gate = mountGateControls({api:gateApi, compass, message, start, mode, render, isActive:() => active});

    panel.openSatnavGateJob = doc => {
      const job = prepareGateJob(doc, api.maths, compass);
      if (active) stop.click();
      if (choose()) panel.querySelector('[data-loop]').click();
      stopped = false;
      walkingOrigin = null;
      arrived = false;
      direct.restart();
      gate.useJob(job);
      syncPlan();
      const {name, widthM} = job.plan.gate;
      return [name + ' · ' + widthM + ' m opening', job.plan.assetName, job.warning].filter(Boolean).join(' · ');
    };

    let observedMenu = null;
    function clearHeader() {
      const menu = document.getElementById('gridatlas-menu-bar');
      if (observedMenu !== menu) {
        if (observedMenu) menuSize?.unobserve(observedMenu);
        observedMenu = menu;
        if (menu) menuSize?.observe(menu);
      }
      const px = Math.ceil(menu?.getBoundingClientRect().bottom ?? 0) + 8;
      panel.style.setProperty('--satnav-measured-menu-bottom',px + 'px');
    }
    const menuSize = typeof ResizeObserver === 'function' ? new ResizeObserver(clearHeader) : null;
    clearHeader();
    // The existing GridAtlas bar can mount after the SatNav cartridge.
    if (!observedMenu) {
      const discovery = new MutationObserver(() => {clearHeader();if (observedMenu) discovery.disconnect();});
      discovery.observe(document.body,{subtree:true,childList:true});
    }
    window.addEventListener('resize',clearHeader);
    window.visualViewport?.addEventListener('resize',clearHeader);
    document.addEventListener('fullscreenchange',clearHeader);
    document.addEventListener('webkitfullscreenchange',clearHeader);
    panel.addEventListener('click', event => {
      const control = event.target.closest?.('button');
      if (control && ['satnav-from','satnav-to','satnav-add','satnav-replace'].includes(control.id)
          && control.getAttribute('aria-pressed') !== 'true') {
        const zoom = api.getMap()?.doubleClickZoom;
        // A deliberate toolbar selection interrupts the previous map tap pair.
        if (zoom?.isEnabled()) {zoom.disable();zoom.enable();}
      }
    },true);

    function draw() {
      if (!routeMap?.getLayer('l-sat')) return;
      let source = routeMap.getSource(lineId);
      const data = {type:'FeatureCollection',features:geometry ?
        [{type:'Feature',properties:{kind:routed()?'regional-route':'mapped-footpath'},geometry}] : []};
      if (!source) {routeMap.addSource(lineId,{type:'geojson',data});source = routeMap.getSource(lineId);}
      else if (drawn !== geometry) source.setData(data);
      if (!routeMap.getLayer(lineId)) routeMap.addLayer({id:lineId,type:'line',source:lineId,paint:{'line-color':'#77ed91','line-width':5}},
        routeMap.getLayer('gridatlas-satnav-waypoints-via') ? 'gridatlas-satnav-waypoints-via' : undefined);
      drawn = geometry;
    }
    function attachMap() {
      gate.attachMap();
      const next = api.getMap();
      if (next !== routeMap) {
        routeMap?.off('style.load',draw);routeMap = next;
        routeMap?.on('style.load',draw);drawn = null;
      }
      draw();
      clearHeader();
    }
    function clearRoute(status) {
      routeState = status;geometry = null;follow = null;arrived = false;sourceNote.hidden = true;draw();
    }
    async function calculate(points, revision) {
      try {
        routerPromise ??= import(new URL('tools/satnav/walk/council/council-router.mjs',root))
          .then(module => module.loadPedestrianRouter(api.maths)).catch(error => {routerPromise = null;throw error;});
        const route = await routerPromise;
        if (request !== revision) return;
        const coordinates = [];
        let publication;
        for (let i = 1; i < points.length; i++) {
          const result = route(points[i-1],points[i]);
          if (result.status !== 'mapped') {
            if (result.reason === 'footpath-data-unavailable') routerPromise = null;
            clearRoute('unavailable');render();return;
          }
          publication = result;
          const leg = result.geometry.coordinates;
          if (i > 1 && api.maths.distanceKm(...coordinates.at(-1),...leg[0]) > 0.0001) {
            clearRoute('unavailable');render();return;
          }
          for (let j = i === 1 ? 0 : 1; j < leg.length; j++) coordinates.push(leg[j]);
          if (coordinates.length > 20_000) {clearRoute('unavailable');render();return;}
        }
        geometry = {type:'LineString',coordinates};
        follow = createRouteFollower(geometry,api.maths);
        sourceNote.querySelector('span').textContent = publication.attribution + ' ';
        const [closures,licence] = sourceNote.querySelectorAll('a');
        closures.href = publication.closureNotices;licence.href = publication.licence;sourceNote.hidden = false;
        routeState = 'mapped';draw();render();
      } catch {
        if (request === revision) {clearRoute('unavailable');render();}
      }
    }
    function syncPlan() {
      if (gate.selected() && (!gate.matchesPlan() || choose() || (mode.value === 'gate' && !api.isExample()))) {
        mode.value = 'direct';
        gate.select();
        api.leaveExample();
      }
      const pins = api.getPins(), [from] = api.getEndpoints();
      targets = walkTargets(pins,from,choose());
      direct.setTargets(targets);
      if (mode.value === 'mapped') {
        const fix = api.getFix();
        if (!from && !walkingOrigin && compass.fixQuality(fix) === 'usable') walkingOrigin = [fix.longitude,fix.latitude];
        const origin = from ?? walkingOrigin;
        const points = origin && targets.length ? [origin,...targets.map(pin => pin.coordinate)] : [];
        const next = JSON.stringify(points);
        if (key !== next) {
          key = next;const revision = ++request;
          clearRoute(points.length >= 2 ? 'loading' : 'none');
          if (points.length >= 2) void calculate(points,revision);
        }
      } else if (key) {key = '';request++;clearRoute('none');}
      render();
    }
    function liveRoute(fix) {
      const now = Date.now();
      const projection = follow(fix,now);
      if (projection.status !== 'ok') return 'Position on mapped path uncertain';
      if (projection.offRoute) return 'Away from mapped footpath';
      const end = geometry.coordinates.at(-1);
      // No single-fix route arrival; routed modes are gated during 17A.
      arrived = false;
      if (arrived) return 'Near mapped path end · verify position and access';
      const next = geometry.coordinates[projection.segmentIndex + 1];
      const forward = compass.guide(fix,{coordinates:next},now);
      const parts = [distance(projection.remainingM) + ' remaining'];
      if (Number.isFinite(forward?.bearingDeg)) parts.push(bearing(forward.bearingDeg));
      return parts.join(' · ');
    }
    function renderRegional(sample) {
      const label=(mode.value==='walking'?'Walking · mapped distance':objective.value==='fastest'?'Driving · estimated time':'Driving · mapped distance')+' · Oxford pilot · '+snapshot.attribution;
      function show(snapshot){
        const next=snapshot?.geometry??null;
        const k=next?JSON.stringify(next.coordinates):'';
        if(k!==routeDrawKey || (!next&&geometry)){geometry=next;routeDrawKey=k;draw();}
        const status=snapshot?.status??'waiting-gps';
        if(status==='tracking'&&snapshot.instruction?.kind==='route')
          return label+' · '+distance(snapshot.instruction.remainingM)+' remaining · snapshot only · check access · no live traffic';
        const messages={routing:'Calculating route',unavailable:'Route unavailable',offline:'Offline · route hidden','retry-exhausted':'Route unavailable · retry budget exhausted','retry-wait':'Waiting before retry',timeout:'Route request timed out',suspect:'Position away from route · checking',uncertain:'Position uncertain',deviated:'Recalculating route','waiting-gps':'Waiting for accurate fresh   … [line shortened here: 406 characters; full line on GitHub]
        return label+' · '+(messages[status]??'Waiting for route');
      }
      if(!active){show(null);return stopped?'Guidance stopped':label+' · limited area; verify current access';}
      if(targets.length!==1){recovery.stop();recoveryKey='';show(null);return label+' · select one destination; use manual mode for ordered pins';}
      const target=targets[0].coordinate;
      const wanted=JSON.stringify([mode.value,mode.value==='driving'?objective.value:'shortest',target]);
      if(document.hidden||!sample||sample.timestampMs<=resumeAfter){recovery.stop();show(null);return label+' · Waiting for fresh GPS';}
      if(wanted!==recoveryKey){
        recovery.setJourney({mode:mode.value,target,objective:mode.value==='driving'?objective.value:'shortest'});
        recoveryKey=wanted;
      }
      recovery.network(navigator.onLine);
      if(!recovery.snapshot().active)recovery.start();
      recovery.ingest(sample);
      return show(recovery.tick());
    }
    function render() {
      start.hidden = active;stop.hidden = !active;
      panel.satnavOrientationTarget=null;
      const isPath = mode.value === 'mapped';
      const label = isPath ? 'Mapped footpath · shortest unverified' : 'Manual orientation · straight-line guidance';
      objective.hidden = mode.value !== 'driving';
      start.disabled = unsupported();
      let text = '';
      if (unsupported()) text = 'Route unavailable · no verified regional service or graph';
      else if (routed()) text = renderRegional(api.getFix());
      else if (gate.selected()) text = gate.describe(active, stopped);
      else if (stopped && !active) text = 'Walk stopped';
      else if (isPath && routeState === 'unavailable') text = 'Mapped footpath unavailable here · no route';
      else if (isPath && routeState === 'loading') text = 'Checking mapped footpaths';
      else if (active && document.hidden) {direct.suspend();text = label + ' · Guidance suspended';}
      else if (active) {
        const sample = api.getFix();
        const quality = compass.fixQuality(sample);
        if (sample?.timestampMs <= resumeAfter || (resumeAfter > -Infinity && !sample)) text = label + ' · Waiting for a fresh GPS fix';
        else if (!targets.length) text = label + ' · Tap TO, then tap your destination on the map';
        else if (quality !== 'usable') {direct.locate(sample);text = label + ' · ' + (quality === 'poor' ? 'Waiting for more accurate GPS' : 'Waiting for a fresh GPS fix');}
        else if (isPath) text = routeState === 'mapped' ? label + ' · ' + liveRoute(sample) + ' · check current access' : 'Waiting for route origin';
        else {
          const guidance = direct.locate(sample);
          panel.satnavOrientationTarget = guidance.status==='guiding' ? targets[guidance.targetIndex]?.coordinate : null;
          if (guidance.status === 'complete') text = label + ' · Near last pin · verify position and access';
          else if (guidance.status === 'guiding') {
            const [, destination] = api.getEndpoints();
            const parts = [label];
            if (targets.length > 1) {
              if (destination) {
                const metres = api.maths.distanceKm(sample.longitude, sample.latitude, ...destination) * 1000;
                parts.push(distance(metres) + ' straight to destination');
              }
              parts.push('Waypoint ' + (guidance.targetIndex + 1) + ' of ' + targets.length, distance(guidance.distanceM) + ' to waypoint');
            } else {
              parts.push(distance(guidance.distanceM) + (destination ? ' straight to destination' : ' straight to waypoint'));
            }
            if (Number.isFinite(guidance.bearingDeg)) parts.push(bearing(guidance.bearingDeg));
            if (targets.length > 1) parts.push(distance(guidance.remainingM) + ' geometric distance via pins');
            text = parts.join(' · ');
          } else text = label + ' · Waiting for a fresh GPS fix';
        }
      } else if (isPath && routeState === 'mapped') text = 'Mapped footpath ready · shortest unverified · check current access';
      if (message.textContent !== text) message.textContent = text;
    }
    start.onclick = () => {
      if (unsupported()) {render();return;}
      resetRecovery();
      active = true;stopped = false;arrived = false;walkingOrigin = null;direct.restart();
      // This is the UI's existing user-initiated watch. It freezes a missing
      // FROM on the first usable fix and preserves an imported or hand-picked FROM.
      if (!api.isTracking()) gps.click();
      if (!api.isTracking()) {active = false;stopped = true;}
      if (active) {gate.begin();recoveryTimer=setInterval(render,1000);}
      syncPlan();
    };
    function stopWalk(reason) {
      resetRecovery();
      gate.end(typeof reason === 'string' ? reason : 'location stopped');
      active = false;stopped = true;walkingOrigin = null;
      request++;key = '';clearRoute('none');direct.restart();render();
    }
    stop.onclick = () => {stopWalk('stop walk');if (api.isTracking()) stopGps.click();};
    mode.onchange = () => {
      // Explicit mode selection invalidates old route state before any reentrant plan event.
      resetRecovery();
      active = false;walkingOrigin = null;stopped = false;arrived = false;direct.restart();
      request++;key = '';clearRoute('none');
      gate.select();
      if (!gate.selected()) api.leaveExample();
      syncPlan();
    };
    objective.onchange = () => {request++;key = '';recovery.stop();recoveryKey='';routeDrawKey='';clearRoute('none');render();};
    panel.addEventListener('satnav:fix',() => {
      if (stopped && !active) {render();return;}
      if (mode.value === 'mapped' && !walkingOrigin && !api.getEndpoints()[0]) syncPlan();
      else render();
    });
    panel.addEventListener('satnav:stop',event=>{if(event.detail==='Location suspended'){resumeAfter=Date.now();direct.suspend(resumeAfter);render();}else stopWalk(event);});
    panel.addEventListener('satnav:pins',()=>{if(!routed()){recovery.stop();recoveryKey='';}syncPlan();});
    panel.addEventListener('satnav:map',attachMap);
    panel.addEventListener('click',event => {if (event.target.closest?.('[data-loop]')) syncPlan();});
    document.addEventListener('visibilitychange',()=>{resumeAfter=Date.now();direct.suspend(resumeAfter);recovery.stop();if(!routed())recoveryKey='';render();});
    window.addEventListener('offline',()=>{if(routed()){recovery.network(false);render();}});
    window.addEventListener('online',() => {
      if(routed()){recovery.network(true);render();}
      if (mode.value === 'mapped' && routeState === 'unavailable') {routerPromise = null;key = '';syncPlan();}
    });
    window.addEventListener('pagehide',event=>{if(event.persisted){resumeAfter=Date.now();direct.suspend(resumeAfter);resetRecovery();}else stopWalk(event);});
    window.addEventListener('pageshow',event=>{if(event.persisted&&active){resumeAfter=Date.now();direct.suspend(resumeAfter);recoveryTimer=setInterval(render,1000);render();}});
    attachMap();
    if (!api.getPins().length && new URLSearchParams(location.search).has('pilot')) {
      mode.value = 'gate';
      gate.select();
    }
    syncPlan();
  }
  document.addEventListener('satnav:ready',mount);
  mount();
}().catch(error => console.error('SatNav walking controls failed',error));

Orient17a Compass

A JavaScript file in the atlas folder of GridAtlas that resets heading (`resetHeading`) and draws SVG graphics.

interactiongridatlas / atlas/modules/202612040126-orient17a-compass.js · lines 1–86 of 86 · version 2026-12-04 01:26 · Not reached from any entry point (candidate for review) · pattern invalidate (shared by 16 files)

What it does
It draws its content. Defines 7 functions or classes, including mount, resetHeading, screenAngle, attach, render. 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.
Inputs & outputs
Out: SVG drawing.
What it achieves
It resets heading (`resetHeading`) and is built from the mount step (`mount`) and the screen angle helper (`screenAngle`). ORIENT-17A: compact view of the existing survey GPS and manual controller. It responds to deviceorientation, deviceorientationabsolute and change 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, resetHeading, screenAngle, attach, render, invalidate, stop
Defines here
mount, resetHeading, screenAngle, attach, render, invalidate, stop
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/202612040126-orient17a-compass.js:1-86 · blob 4c55baafa249faf4e3163aa8ab57f021bc2600ed · 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
/* ORIENT-17A: compact view of the existing survey GPS and manual controller.
 * No new map, GPS watch or camera writer. Local WMM2025 reference with strict acquisition gates. */
void async function(){
 const root=new URL('../../../',location.href);
 const [{geometry,relativeGuidance},{eligibleObservation,createReference,stableLabel},{createHeadingFilter},{createEventClock}]=await Promise.all([
   import(new URL('tools/satnav/orientation/orient17a-v9212-navigation.mjs',root)),
   import(new URL('tools/satnav/orientation/orient17a-v9212-heading.mjs',root)),
   import(new URL('tools/satnav/orientation/orient17a-heading-filter.mjs',root)),
   import(new URL('tools/satnav/orientation/orient17a-v9214-event-clock.mjs',root))]);
 let mounted=false;
 function mount(){
  const panel=document.getElementById('satnav-compact'),api=panel?.satnavSurvey;
  if(mounted||!api)return;mounted=true;
  const controls=document.createElement('section');controls.id='field-compass';
  controls.innerHTML='<button id="field-compass-toggle" type="button" aria-pressed="false">Compass</button><div id="field-compass-reading" role="status"></div>';
  panel.querySelector('#satnav-field-tools').prepend(controls);
  const card=document.createElement('section');card.id='orient17a-direction';card.hidden=true;card.setAttribute('aria-label','Manual orientation');
  card.innerHTML='<svg id="orient17a-arrow" aria-hidden="true" viewBox="0 0 48 48" hidden><path fill="currentColor" d="M24 3 43 43 24 33 5 43Z"/></svg><div><strong id="orient17a-label">Direction uncertain</strong><div id="orient17a-distance"></div><small id="orient17a-reason"></small></div>';
  const css=document.createElement('style');css.textContent='#orient17a-direction{position:fixed;z-index:10028;right:max(8px,env(safe-area-inset-right,0px));top:max(72px,calc(env(safe-area-inset-top,0px) + 60px));max-width:min(180px,calc(100vw - 16px));padding:8px;border:1px solid #367078;border-radius:6px;background:#081820;color:#e4f7f7;display:flex;align-items:center;gap:6px;font:13px/1.3 syste  … [line shortened here: 682 characters; full line on GitHub]
  document.head.append(css);
  const toggle=controls.querySelector('button'),reading=controls.querySelector('#field-compass-reading'),arrow=card.querySelector('svg'),label=card.querySelector('strong'),distance=card.querySelector('#orient17a-distance'),reason=card.querySelector('small');
  let state='stopped',epoch=0,handler=null,raw=null,frame=null;
  const filter=createHeadingFilter(),reference=createReference(),eventClock=createEventClock();let priorLabel=null;
  const resetHeading=()=>{filter.reset();reference.reset();priorLabel=null;raw=null;};
  const screenAngle=()=>window.screen.orientation?.angle??window.orientation??0;
  function attach(){const host=document.fullscreenElement||document.webkitFullscreenElement||document.body;if(card.parentElement!==host)host.append(card);}
  function render(){
   attach();const mode=document.getElementById('satnav-walk-mode');
   const active=mode?.value==='direct'&&api.isTracking()&&document.getElementById('satnav-walk-stop')?.hidden===false;
   card.hidden=!active;
   const target=panel.satnavOrientationTarget;
   const fix=api.getFix(),now=Date.now();
   const metrics=geometry(fix,target,now);
   let trueHeading=null;
   if(state==='active'&&raw&&raw.frame===screenAngle()&&now-raw.timestampMs<=3000&&!document.hidden){
    trueHeading=reference.resolve(raw,fix,now);
   }
   if(raw&&(now-raw.timestampMs>3000||!fix||!Number.isFinite(metrics.distanceM)))resetHeading();
   const guide=relativeGuidance(metrics,trueHeading,now);
   arrow.hidden=!Number.isFinite(guide.relativeDeg)||card.hidden;
   arrow.style.transform=arrow.hidden?'none':'rotate('+guide.relativeDeg+'deg)';
   priorLabel=stableLabel(guide,priorLabel);label.textContent=priorLabel;
   distance.textContent=Number.isFinite(guide.distanceM)?(guide.distanceM<1000?Math.round(guide.distanceM)+' m':(guide.distanceM/1000).toFixed(2)+' km')+' straight line':'';
   reason.textContent=guide.reason||(trueHeading?.source?.altitudeAssumed?'Altitude assumed · compass not independently cross-checked':'Compass not independently cross-checked');
   if(state==='active')reading.textContent=raw&&now-raw.timestampMs<=3000?'Compass reading · '+(trueHeading?'true reference':'reference unverified'):'Waiting for fresh compass';
  }
  function invalidate(){resetHeading();frame=screenAngle();eventClock.reset();render();}
  function stop(status='stopped'){epoch++;if(handler){window.removeEventListener('deviceorientation',handler);window.removeEventListener('deviceorientationabsolute',handler);}handler=null;resetHeading();state=status;toggle.setAttribute('aria-pressed','false');reading.textContent='Compass '+status;render();}
  toggle.onclick=async()=>{
   if(state==='active'||state==='pending'){stop();return;}
   const sensor=window.DeviceOrientationEvent;
   if(!window.isSecureContext||!sensor){stop('unsupported');return;}
   state='pending';reading.textContent='Compass permission pending';const own=++epoch;
   try{
    if(typeof sensor.requestPermission==='function'&&await sensor.requestPermission(true)!=='granted'){if(own===epoch)stop('denied');return;}
    if(own!==epoch||document.hidden)return;
    state='active';toggle.setAttribute('aria-pressed','true');invalidate();
    handler=event=>{
     if(own!==epoch||state!=='active'||document.hidden)return;
     if(screenAngle()!==frame){invalidate();return;}
     // A wholly absent sample is not evidence against a previous observation.
     // Do not consume its timestamp, refresh the filter, or extend freshness.
     const empty=['alpha','beta','gamma','webkitCompassHeading','webkitCompassAccuracy'].every(key=>event[key]==null);
     if(empty){render();return;}
     const t=eventClock.stamp(event);
     if(t===null)return;
     const obs=eligibleObservation(event,frame,t);
     if(!obs)resetHeading();
     else raw=filter.push(obs);
     render();
    };
    window.addEventListener('deviceorientation',handler);
    window.addEventListener('deviceorientationabsolute',handler);
   }catch{if(own===epoch)stop('unavailable');}
  };
  window.screen.orientation?.addEventListener('change',invalidate);
  window.addEventListener('orientationchange',invalidate);
  panel.addEventListener('satnav:fix',render);panel.addEventListener('satnav:pins',render);panel.addEventListener('satnav:stop',()=>stop());
  document.addEventListener('visibilitychange',()=>{if(document.hidden)stop('suspended');else render();});
  document.addEventListener('fullscreenchange',render);document.addEventListener('webkitfullscreenchange',render);
  let timer=setInterval(render,250);window.addEventListener('pagehide',()=>{clearInterval(timer);stop('suspended');});
  window.addEventListener('pageshow',event=>{if(event.persisted){clearInterval(timer);timer=setInterval(render,250);render();}});
  render();
 }
 document.addEventListener('satnav:ready',mount);mount();
}().catch(error=>console.error('ORIENT17A compass failed',error));