In this section
- SatNav Start Walk geodesy · gridatlas / atlas/modules/202611281340-satnav-start-walk.js lines 1–230
- SatNav Walk Saved Plan render · gridatlas / atlas/modules/202611281340-satnav-walk-saved-plan.js lines 1–69
- SatNav Layers interaction · gridatlas / atlas/modules/202611281342-satnav-layers.js lines 1–60
- SatNav Field Survey interaction · gridatlas / atlas/modules/202611281725-satnav-field-survey.js lines 1–171
- SatNav Layout Import interaction · gridatlas / atlas/modules/202611281725-satnav-layout-import.js lines 1–167
SatNav Start Walk
A JavaScript file in the atlas folder of GridAtlas that attaches map (`attachMap`), syncs plan (`syncPlan`) and reads inputs for SatNav walk mode.
geodesygridatlas / atlas/modules/202611281340-satnav-start-walk.js · lines 1–230 of 230 · version 2026-11-28 13:40 · Not reached from any entry point (candidate for review) · pattern clearHeader (shared by 10 files)
- What it does
- It maps its content. Defines 13 functions or classes, including mount, choose, distance, bearing, clearHeader. 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.
- Inputs & outputs
- In: form fields (user input).
- What it achieves
- It attaches map (`attachMap`), syncs plan (`syncPlan`) and stops walk (`stopWalk`). Explicit walking on the existing field map. 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, choose, distance, bearing, clearHeader, draw, attachMap, clearRoute, calculate, syncPlan, liveRoute, render
- Defines here
- mount, choose, distance, bearing, clearHeader, draw, attachMap, clearRoute, calculate, syncPlan, liveRoute, 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/202611281340-satnav-start-walk.js:1-230 · blob 1d78c41703c9d3e3c2ab8601f610bff3c08a1ce1 · 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
/* Explicit walking on the existing field map. Location is owned by the waypoint cartridge. */
void async function () {
const root = new URL('../../../', location.href);
const [{createDirectWalk,walkTargets}, compass, {createRouteFollower}] = await Promise.all([
import(new URL('tools/satnav/walk/direct.mjs',root)),
import(new URL('tools/satnav/vendor/9698781539e549deaa6ecaa4a2b34610c1f9fd29/nav/compass.mjs',root)),
import(new URL('tools/satnav/line/route-follower.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 #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-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="direct">Direct to pin</option><option value="walking">Walking route</option></select><button id="satnav-walk-start" type="button">Start walk</button><button id="satnav-walk-stop" type="button" hidden>Stop walk</button>';
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 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 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;
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:'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() {
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() {
const pins = api.getPins(), [from] = api.getEndpoints();
targets = walkTargets(pins,from,choose());
direct.setTargets(targets);
if (mode.value === 'walking') {
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);
if (projection.remainingM <= 15 && api.maths.distanceKm(fix.longitude,fix.latitude,...end) * 1000 + fix.accuracyM <= 15) arrived = true;
if (arrived) return 'Arrived at mapped path end';
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 render() {
start.hidden = active;stop.hidden = !active;
const isPath = mode.value === 'walking';
const label = isPath ? 'Walking route' : 'Direct to pin';
let text = '';
if (stopped && !active) text = 'Walk stopped';
else if (isPath && routeState === 'unavailable') text = 'Walking route unavailable here · choose Direct to pin';
else if (isPath && routeState === 'loading') text = 'Checking mapped footpaths';
else if (active) {
const sample = api.getFix();
const quality = compass.fixQuality(sample);
if (!targets.length) text = 'Select TO or add a waypoint';
else if (quality !== 'usable') 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);
if (guidance.status === 'complete') text = label + ' · Arrived';
else if (guidance.status === 'guiding') {
const parts = [label,distance(guidance.distanceM)];
if (Number.isFinite(guidance.bearingDeg)) parts.push(bearing(guidance.bearingDeg));
if (targets.length > 1) parts.push('Waypoint ' + (guidance.targetIndex + 1) + ' of ' + targets.length,distance(guidance.remainingM) + ' remaining');
text = parts.join(' · ');
} else text = label + ' · Waiting for a fresh GPS fix';
}
} else if (isPath && routeState === 'mapped') text = 'Walking route ready · check current access';
if (message.textContent !== text) message.textContent = text;
}
start.onclick = () => {
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;}
syncPlan();
};
function stopWalk() {
active = false;stopped = true;walkingOrigin = null;
request++;key = '';clearRoute('none');direct.restart();render();
}
stop.onclick = () => {stopWalk();if (api.isTracking()) stopGps.click();};
mode.onchange = () => {walkingOrigin = null;stopped = false;arrived = false;direct.restart();syncPlan();};
panel.addEventListener('satnav:fix',() => {
if (stopped && !active) {render();return;}
if (mode.value === 'walking' && !walkingOrigin && !api.getEndpoints()[0]) syncPlan();
else render();
});
panel.addEventListener('satnav:stop',stopWalk);
panel.addEventListener('satnav:pins',syncPlan);
panel.addEventListener('satnav:map',attachMap);
panel.addEventListener('click',event => {if (event.target.closest?.('[data-loop]')) syncPlan();});
document.addEventListener('visibilitychange',render);
window.addEventListener('online',() => {
if (mode.value === 'walking' && routeState === 'unavailable') {routerPromise = null;key = '';syncPlan();}
});
window.addEventListener('pagehide',stopWalk);
attachMap();syncPlan();
}
document.addEventListener('satnav:ready',mount);
mount();
}().catch(error => console.error('SatNav walking controls failed',error));SatNav Walk Saved Plan
A JavaScript file in the atlas folder of GridAtlas that restores this version's saved design pins to the same map used for a hand-placed walk.
rendergridatlas / atlas/modules/202611281340-satnav-walk-saved-plan.js · lines 1–69 of 69 · version 2026-11-28 13:40 · Not reached from any entry point (candidate for review) · pattern mount (shared by 45 files)
- What it does
- It draws its content. Defines mount. 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
- Defines `mount`. 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
- mount
- Defines here
- mount
- 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/202611281340-satnav-walk-saved-plan.js:1-69 · blob 5d99674faff9e7dd8adfc9b12455747f6295be35 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: dom · domain stage: field_execution · users: EPC_contractor, landowner_planner · canonical: unreached_review
/* Restore this version's saved design pins to the same map used for a hand-placed walk. */
void function () {
const scope = new URL('./', location.href);
const root = new URL('../../../', scope);
let mounted = false;
async function mount() {
const host = document.getElementById('satnav-field-tools');
const survey = document.getElementById('satnav-compact')?.satnavSurvey;
if (!host || !survey || mounted) return;
mounted = true;
document.removeEventListener('satnav:ready', mount);
try {
const {mountOfflinePlan} = await import(new URL('tools/satnav/field-reliability/offline-plan.mjs', root));
const area = mountOfflinePlan({container: host, getPins: survey.getPins, maths: survey.maths});
const [save, forget] = area.querySelectorAll('button');
if (save.disabled) return;
const status = area.querySelector('[role="status"]');
const restore = document.createElement('button');
restore.type = 'button';
restore.textContent = 'Use saved plan';
forget.before(restore, ' ');
// Saving and forgetting already lock these controls while the cache is changing.
new MutationObserver(() => { restore.disabled = save.disabled; })
.observe(save, {attributes: true, attributeFilter: ['disabled']});
restore.onclick = async () => {
if (save.disabled) return;
const previous = survey.getPins();
save.disabled = forget.disabled = restore.disabled = true;
try {
const key = new URL('__saved-field-plan__', scope);
const response = await caches.match(key, {cacheName: 'ventus-satnav-offline-plans-v1'});
if (!response) {
status.textContent = 'No saved plan for this map.';
return;
}
// The existing offline document stores design coordinates as JSON.
// Read its data in an inert template, without loading its offline viewer.
const snapshot = document.createElement('template');
snapshot.innerHTML = await response.text();
const data = snapshot.content.querySelector('script#saved-plan[type="application/json"]');
const coordinates = JSON.parse(data?.textContent ?? 'null')?.coordinates;
if (!Array.isArray(coordinates) || coordinates.length < 2) throw Error('Invalid saved plan');
if (survey.getPins() !== previous) {
status.textContent = 'The plan changed. Tap Use saved plan again to replace it.';
return;
}
// replacePlan validates every pin before changing endpoints and notifying walking guidance.
survey.replacePlan(coordinates);
status.textContent = 'Saved plan loaded · ' + coordinates.length.toLocaleString('en-GB') + ' pins.';
} catch {
status.textContent = 'Could not load the saved plan.';
} finally {
save.disabled = forget.disabled = restore.disabled = false;
}
};
} catch {
const message = document.createElement('p');
message.setAttribute('role', 'status');
message.textContent = 'Saved plan controls could not load.';
host.append(message);
}
}
document.addEventListener('satnav:ready', mount);
void mount();
}();SatNav Layers
A JavaScript file in the atlas folder of GridAtlas. It is built from the mount step (`mount`) and the reflect step (`reflect`).
interactiongridatlas / atlas/modules/202611281342-satnav-layers.js · lines 1–60 of 60 · version 2026-11-28 13:42 · Not reached from any entry point (candidate for review) · pattern reflect (shared by 17 files)
- What it does
- It draws its content. Defines mount, reflect. 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
- The field map covers the ordinary dashboard. It responds to fullscreenchange, webkitfullscreenchange and keydown 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, reflect
- Defines here
- mount, reflect
- 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/202611281342-satnav-layers.js:1-60 · blob 6cf5a542ec457d17d8e066b7b7f71dc59806d0c3 · 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
/* The field map covers the ordinary dashboard. Keep its Layers button and expose
* the engine's original, synchronised layer controls above the map. */
(() => {
const root = document.documentElement;
function mount() {
const toggle = document.getElementById('gridatlas-dash-toggle');
const dashboard = document.querySelector('.scada-wrapper');
const curtain = document.getElementById('fs-curtain');
if (!toggle || !dashboard || !curtain || !document.getElementById('satnav-compact')) return false;
const style = document.createElement('style');
style.textContent = `
html.satnav-field-layers body:not(.fs-active) .scada-wrapper { display:none!important }
html.satnav-field-layers #fs-curtain {
display:none!important; position:fixed; top:auto; left:auto;
right:max(8px,env(safe-area-inset-right)); bottom:calc(max(12px,env(safe-area-inset-bottom)) + 52px);
width:min(380px,calc(100% - max(8px,env(safe-area-inset-left)) - max(8px,env(safe-area-inset-right))));
max-height:calc(100dvh - max(var(--gridatlas-menu-bar-clear,42px),env(safe-area-inset-top)) - max(12px,env(safe-area-inset-bottom)) - 60px);
padding:10px 12px; overflow:auto; overscroll-behavior:contain;
transform:none; transition:none; z-index:10042; border:1px solid #367078; border-radius:6px; background:#081820fa;
}
html.satnav-field-layers.satnav-layers-open #fs-curtain { display:block!important }
html.satnav-field-layers #fs-curtain .key-item { min-height:44px; box-sizing:border-box; align-items:center }
html.satnav-field-layers #gridatlas-dash-toggle {
right:max(12px,env(safe-area-inset-right)); bottom:max(12px,env(safe-area-inset-bottom)); min-height:44px; z-index:10043;
}`;
document.head.append(style);
root.classList.add('satnav-field-layers');
toggle.setAttribute('aria-controls', curtain.id);
function reflect() {
const fullscreen = document.fullscreenElement || document.webkitFullscreenElement ||
document.body.classList.contains('fs-active');
const open = fullscreen ? curtain.classList.contains('curtain-open') :
dashboard.dataset.gridatlasCollapsed !== '1';
root.classList.toggle('satnav-layers-open', open);
toggle.setAttribute('aria-expanded', String(open));
}
const changes = new MutationObserver(reflect);
changes.observe(dashboard, {attributes:true, attributeFilter:['data-gridatlas-collapsed']});
changes.observe(curtain, {attributes:true, attributeFilter:['class']});
changes.observe(document.body, {attributes:true, attributeFilter:['class']});
document.addEventListener('fullscreenchange', reflect);
document.addEventListener('webkitfullscreenchange', reflect);
curtain.addEventListener('keydown', event => {
if (event.key === 'Escape' && toggle.getAttribute('aria-expanded') === 'true') {
event.preventDefault();
toggle.click();
toggle.focus();
}
});
reflect();
return true;
}
if (!mount()) {
const pending = new MutationObserver(() => { if (mount()) pending.disconnect(); });
pending.observe(document.documentElement, {childList:true, subtree:true});
}
})();SatNav Field Survey
A JavaScript file in the atlas folder of GridAtlas that attaches map (`attachMap`), applies loop (`applyLoop`) and stops recording (`stopRecording`).
interactiongridatlas / atlas/modules/202611281725-satnav-field-survey.js · lines 1–171 of 171 · version 2026-11-28 17:25 · Not reached from any entry point (candidate for review) · pattern length (shared by 4 files)
- What it does
- It maps its content. Defines 8 functions or classes, including mount, length, draw, scheduleDraw, attachMap. Side effects: changes the web page (DOM).
- Why it exists in the grid workflow
- Domain stage field_execution (path word 'field'): 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). Out: downloaded file ventus-survey-.
- What it achieves
- It attaches map (`attachMap`), applies loop (`applyLoop`) and stops recording (`stopRecording`). Add a local field survey to the waypoint map's existing pins and GPS watch. It responds to satnav and toggle 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, length, draw, scheduleDraw, attachMap, render, applyLoop, stopRecording
- Defines here
- mount, length, draw, scheduleDraw, attachMap, render, applyLoop, stopRecording
- 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/202611281725-satnav-field-survey.js:1-171 · blob d11ea64ba95899381657f7a16eddb5473a823605 · 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 a local field survey to the waypoint map's existing pins and GPS watch. */
(() => {
let mounting = false;
async function mount() {
const panel = document.getElementById('satnav-compact');
const host = panel?.querySelector('#satnav-field-tools');
const api = panel?.satnavSurvey;
if (!host || !api || mounting) return;
mounting = true;
try {
const root = new URL('../../../', location.href);
const { createFieldSurvey } = await import(new URL('tools/satnav/survey/model.mjs', root));
const survey = createFieldSurvey({ fixQuality: api.fixQuality, distanceKm: api.distanceKm });
const disclosure = document.createElement('details');
disclosure.id = 'satnav-survey';
disclosure.innerHTML = '<summary>Field survey</summary><div class="survey-sheet"><div class="survey-actions"><button type="button" data-loop>Close perimeter</button><button type="button" data-record>Record track</button><button type="button" data-stop>Stop track</button><button type="button" data-export>Export GeoJSON</button></div><p data-plan></p><p data-track></p><div data-gate-device hid … [line shortened here: 649 characters; full line on GitHub]
host.append(disclosure);
const style = document.createElement('style');
style.textContent = '#satnav-survey{border-radius:6px;background:#081820ed;color:#e4f7f7}#satnav-survey summary{padding:10px;cursor:pointer;min-height:40px;box-sizing:border-box}#satnav-survey .survey-sheet{max-height:min(42dvh,19rem);overflow-y:auto;overscroll-behavior:contain;padding:0 6px 5px}#satnav-survey .survey-actions{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:4px … [line shortened here: 786 characters; full line on GitHub]
document.head.append(style);
const loop = disclosure.querySelector('[data-loop]');
const record = disclosure.querySelector('[data-record]');
const stop = disclosure.querySelector('[data-stop]');
const download = disclosure.querySelector('[data-export]');
const planText = disclosure.querySelector('[data-plan]');
const trackText = disclosure.querySelector('[data-track]');
const exportNote = disclosure.querySelector('[data-export-note]');
const message = disclosure.querySelector('[data-message]');
const gateDevice = disclosure.querySelector('[data-gate-device]');
const sourceId = 'satnav-field-survey';
const layers = [
['area', 'perimeter', 'fill', { 'fill-color': '#a98efa', 'fill-opacity': 0.12 }],
['boundary', 'perimeter', 'line', { 'line-color': '#b59bff', 'line-width': 2, 'line-dasharray': [2, 2] }],
['trail', 'walked-track', 'line', { 'line-color': '#ffa56b', 'line-width': 4 }],
['fix', 'walked-fix', 'circle', { 'circle-radius': 4, 'circle-color': '#ffa56b', 'circle-stroke-color': '#182028', 'circle-stroke-width': 1 }],
];
const errors = {
INVALID_VERTEX_COUNT: 'Use 3 to 1,000 boundary pins.',
INVALID_COORDINATE: 'Perimeters require points between 85° S and 85° N.',
DUPLICATE_VERTEX: 'Move or remove the repeated boundary pin.',
SELF_INTERSECTION: 'Reorder the pins so the boundary does not cross itself.',
BACKTRACKING_EDGE: 'Move the pin that doubles back along a boundary edge.',
DEGENERATE_POLYGON: 'Move a pin so the boundary encloses an area.',
UNSUPPORTED_LONGITUDE_SPAN: 'This perimeter crosses the supported longitude range.',
};
let map = null;
let drawTimer = null;
const length = metres => metres < 1000 ? Math.round(metres) + ' m' : (metres / 1000).toFixed(2) + ' km';
function draw() {
drawTimer = null;
if (!map?.getStyle()?.layers?.length) return;
if (!map.getSource(sourceId)) map.addSource(sourceId, { type: 'geojson', data: survey.mapData() });
else map.getSource(sourceId).setData(survey.mapData());
const before = map.getStyle().layers.find(layer => layer.type === 'circle' && layer.id.includes('satnav') && layer.source !== sourceId)?.id;
for (const [suffix, role, type, paint] of layers) {
const id = sourceId + '-' + suffix;
if (!map.getLayer(id)) map.addLayer({ id, source: sourceId, type, paint, filter: ['==', ['get', 'satnavRole'], role] }, before);
}
}
function scheduleDraw() {
if (drawTimer === null) drawTimer = setTimeout(draw, 500);
}
function attachMap() {
const next = api.getMap();
if (map !== next) {
map?.off('style.load', scheduleDraw);
map = next;
map?.on('style.load', scheduleDraw);
}
scheduleDraw();
}
function render() {
const pins = api.getPins();
const polygon = survey.perimeter;
loop.disabled = !polygon && pins.length < 3;
loop.textContent = polygon ? 'Open perimeter' : 'Close perimeter';
loop.setAttribute('aria-pressed', String(!!polygon));
record.textContent = { recording: 'Pause track', paused: 'Resume track' }[survey.status] ?? 'Record track';
record.disabled = survey.full || !api.isTracking();
stop.disabled = !['recording', 'paused'].includes(survey.status);
download.disabled = !pins.length && !survey.pointCount && !panel.satnavGateLog?.hasWalks();
if (polygon) {
const area = polygon.areaM2 < 10_000 ? Math.round(polygon.areaM2) + ' m²' : polygon.areaHa.toFixed(2) + ' ha';
planText.textContent = 'Planned perimeter ' + length(polygon.perimeterM) + ' · ' + area +
(polygon.exceedsFollowerSegmentLimit ? ' · Deviation unavailable on legs over 1 km.' : '');
} else planText.textContent = '';
const progress = { recording: 'Recording', paused: 'Paused', stopped: 'Stopped' }[survey.status];
if (survey.full) trackText.textContent = '20,000 fixes recorded. Export your track.';
else if (progress) trackText.textContent = progress + ' · ' + survey.pointCount + (survey.pointCount === 1 ? ' fix · ' : ' fixes · ') + length(survey.distanceM) + ' measured';
else trackText.textContent = api.isTracking() ? '' : 'Start GPS to record a track.';
const gateWalk = panel.satnavGateLog?.hasWalks();
gateDevice.hidden = !gateWalk;
exportNote.textContent = gateWalk ? 'Export entrance observations before closing this page.' :
survey.pointCount ? 'Export before closing this page.' : '';
}
function applyLoop() {
try {
survey.close(api.getPins());
if (api.setClosedLoop(true) === false) message.textContent = 'Perimeter drawn. Return guidance unavailable.';
} catch (error) {
survey.reopen();
api.setClosedLoop(false);
message.textContent = errors[error.message] ?? 'These pins cannot form a perimeter.';
}
}
loop.onclick = () => {
message.textContent = '';
if (survey.perimeter) { survey.reopen(); api.setClosedLoop(false); }
else applyLoop();
render();
scheduleDraw();
};
record.onclick = () => {
message.textContent = '';
if (!api.isTracking()) return;
if (survey.status === 'recording') survey.pause();
else if (survey.status === 'paused') survey.resume();
else survey.start();
render();
};
const stopRecording = () => { survey.stop(); render(); scheduleDraw(); };
stop.onclick = stopRecording;
download.onclick = () => {
try {
const data = survey.exportData(api.getPins());
const gateWalk = panel.satnavGateLog?.snapshot(
gateDevice.querySelector('[data-device]').value.trim(), gateDevice.querySelector('[data-browser]').value.trim());
if (gateWalk) data.gateEvidence = gateWalk;
const blob = new Blob([JSON.stringify(data)], { type: 'application/geo+json' });
const link = document.createElement('a');
link.href = URL.createObjectURL(blob);
link.download = 'ventus-survey-' + new Date().toISOString().replace(/[:.]/g, '-') + '.geojson';
document.body.append(link);
link.click();
link.remove();
setTimeout(() => URL.revokeObjectURL(link.href), 60_000);
message.textContent = '';
} catch { message.textContent = 'Export could not be prepared. Your track is still here.'; }
};
panel.addEventListener('satnav:pins', () => {
message.textContent = '';
if (survey.perimeter) applyLoop();
render();
scheduleDraw();
});
panel.addEventListener('satnav:fix', event => {
if (survey.ingest(event.detail)) { render(); scheduleDraw(); }
});
panel.addEventListener('satnav:watch', render);
panel.addEventListener('satnav:stop', stopRecording);
panel.addEventListener('satnav:map', attachMap);
disclosure.addEventListener('toggle', render);
attachMap();
render();
} catch (error) {
console.error('Field survey could not start', error);
const message = document.createElement('p');
message.setAttribute('role', 'status');
message.textContent = 'Field survey unavailable.';
host.append(message);
}
}
document.addEventListener('satnav:ready', mount, { once: true });
void mount();
})();SatNav Layout Import
A JavaScript file in the atlas folder of GridAtlas that lists choices (`listChoices`). It draws layout (`drawLayout`) and lists choices (`listChoices`).
interactiongridatlas / atlas/modules/202611281725-satnav-layout-import.js · lines 1–167 of 167 · version 2026-11-28 17:25 · Not reached from any entry point (candidate for review) · pattern drawLayout (shared by 3 files)
- What it does
- It maps its content. Defines mount, drawLayout, listChoices. 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.
- Inputs & outputs
- In: user-supplied file (file picker); form fields (user input). Out: GeoJSON file -layout.geojson.
- What it achieves
- Local engineering layouts for the versioned SatNav survey map. It responds to cancel and 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
- mount, drawLayout, listChoices
- Defines here
- mount, drawLayout, listChoices
- 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/202611281725-satnav-layout-import.js:1-167 · blob 8c95a050451b3d5da716e2153a52850272c9a723 · 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
/* Local engineering layouts for the versioned SatNav survey map. */
void async function () {
const root = new URL('../../../', location.href);
const { readLayout, layoutChoices, walkLayoutChoice, MAX_FILE_BYTES } =
await import(new URL('tools/satnav/interchange/layout-import.mjs', root));
const {JOB_SCHEMA} = await import(new URL('tools/satnav/walk/gate/jobs/plan.mjs', root));
const sourceId = 'satnav-imported-layout';
const mapLayers = [
['perimeters', 'fill', ['==', ['get', 'satnavRole'], 'perimeter'], { 'fill-color': '#8de7ae', 'fill-opacity': 0.13 }],
['design', 'line', ['in', ['get', 'satnavRole'], ['literal', ['planned-route', 'perimeter']]], { 'line-color': '#8de7ae', 'line-width': 3, 'line-dasharray': [3, 2] }],
['waypoints', 'circle', ['==', ['get', 'satnavRole'], 'waypoint'], { 'circle-color': '#8de7ae', 'circle-stroke-color': '#10251b', 'circle-stroke-width': 1, 'circle-radius': 5 }],
['track', 'line', ['==', ['get', 'satnavRole'], 'walked-track'], { 'line-color': '#bb9cff', 'line-width': 3 }],
['fix', 'circle', ['==', ['get', 'satnavRole'], 'walked-fix'], { 'circle-color': '#bb9cff', 'circle-radius': 4 }],
];
function mount() {
const survey = document.querySelector('#satnav-compact')?.satnavSurvey;
const host = document.querySelector('#satnav-field-tools');
if (!survey || !host || document.getElementById('satnav-layout')) return;
const controls = document.createElement('details');
controls.id = 'satnav-layout';
controls.innerHTML = `
<summary>Layouts</summary>
<button type="button" data-import>Import layout or job</button>
<input type="file" accept=".json,.geojson,application/json,application/geo+json" aria-label="Local GIS, GeoJSON or entrance job file" hidden>
<input type="search" placeholder="Find a design feature" aria-label="Find a design feature" hidden>
<select aria-label="Design feature" hidden></select>
<button type="button" data-walk hidden>Use for walk</button>
<button type="button" data-show hidden>Show layout on map</button>
<button type="button" data-export hidden>Save layout GeoJSON</button>
<p role="status" aria-live="polite"></p>`;
host.append(controls);
const file = controls.querySelector('input[type=file]');
const search = controls.querySelector('input[type=search]');
const select = controls.querySelector('select');
const status = controls.querySelector('[role=status]');
const show = controls.querySelector('[data-show]');
const walk = controls.querySelector('[data-walk]');
const save = controls.querySelector('[data-export]');
let layout = null;
let choices = [];
let filename = '';
let request = 0;
let map = null;
let renderedLayout = null;
const panel = document.querySelector('#satnav-compact');
function drawLayout() {
const nextMap = survey.getMap();
if (map !== nextMap) {
map?.off('style.load', drawLayout);
map = nextMap;
renderedLayout = null;
map?.on('style.load', drawLayout);
}
if (!map || !layout) return;
if (!map.getSource(sourceId)) {
if (!map.getLayer('l-sat') && !map.isStyleLoaded()) return;
map.addSource(sourceId, { type: 'geojson', data: layout });
renderedLayout = layout;
} else if (renderedLayout !== layout) {
map.getSource(sourceId).setData(layout);
renderedLayout = layout;
}
for (const [name, type, filter, paint] of mapLayers) {
const id = sourceId + '-' + name;
if (!map.getLayer(id)) map.addLayer({ id, type, source: sourceId, filter, paint });
}
}
function listChoices() {
const term = search.value.trim().toLowerCase();
select.replaceChildren();
for (const choice of choices) {
if (!choice.label.toLowerCase().includes(term)) continue;
const option = document.createElement('option');
option.value = String(choice.index);
option.textContent = choice.label;
select.append(option);
if (select.length >= 50) break;
}
select.hidden = select.length === 0;
walk.hidden = select.hidden;
}
controls.querySelector('[data-import]').onclick = () => { request++; file.click(); };
file.addEventListener('cancel', () => { request++; });
search.oninput = listChoices;
file.onchange = async () => {
const selected = file.files[0];
file.value = '';
const active = ++request;
if (!selected) return;
try {
if (selected.size > MAX_FILE_BYTES) throw Error('Choose a file smaller than 16 MiB.');
const doc = JSON.parse(await selected.text());
if (active !== request) return;
if (doc?.schema === JOB_SCHEMA) {
if (!panel.openSatnavGateJob) throw Error('Walking controls are loading. Open the file again.');
const summary = panel.openSatnavGateJob(doc);
layout = null;
choices = [];
search.hidden = select.hidden = walk.hidden = show.hidden = save.hidden = true;
map?.getSource(sourceId)?.setData({type:'FeatureCollection', features:[]});
renderedLayout = null;
status.textContent = summary;
return;
}
const next = readLayout(doc);
const items = layoutChoices(next);
if (active !== request) return;
layout = next;
choices = items;
filename = selected.name;
search.hidden = items.length <= 50;
search.value = '';
listChoices();
show.hidden = save.hidden = false;
drawLayout();
const measured = next.features.filter(f => ['walked-track', 'walked-fix'].includes(f.properties.satnavRole)).length;
status.textContent = filename + ' · ' + (next.features.length - measured) + ' design · ' + measured + ' recorded';
} catch (error) {
if (active === request) status.textContent = 'Import failed. ' + error.message;
}
};
walk.onclick = () => {
const chosen = choices.find(item => item.index === Number(select.value));
try {
const applied = walkLayoutChoice(survey, layout, chosen);
if (applied === false) throw Error('The map could not use this selection.');
status.textContent = chosen.label + ' selected for walking.';
} catch (error) {
status.textContent = error.message;
}
};
show.onclick = () => {
drawLayout();
if (!map || !layout) return;
let west = 180, east = -180, south = 90, north = -90;
for (const { geometry } of layout.features) {
const coordinates = geometry.type === 'Point' ? [geometry.coordinates] :
geometry.type === 'Polygon' ? geometry.coordinates[0] : geometry.coordinates;
for (const [lng, lat] of coordinates) {
west = Math.min(west, lng); east = Math.max(east, lng);
south = Math.min(south, lat); north = Math.max(north, lat);
}
}
if (west === east && south === north) map.jumpTo({ center: [west, south], zoom: 16 });
else map.fitBounds([[west, south], [east, north]], { padding: 50, duration: 0, maxZoom: 17 });
};
save.onclick = () => {
if (!layout) return;
const url = URL.createObjectURL(new Blob([JSON.stringify(layout)], { type: 'application/geo+json' }));
const download = document.createElement('a');
download.href = url;
download.download = filename.replace(/\.(geojson|json)$/i, '') + '-layout.geojson';
controls.append(download);
download.click();
download.remove();
setTimeout(() => URL.revokeObjectURL(url), 1000);
};
drawLayout();
panel.addEventListener('satnav:map', drawLayout);
}
document.addEventListener('satnav:ready', mount);
mount();
}().catch(error => console.error('SatNav layout import failed', error));