GLOBALGRID2050 / EXPLORE CODE

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

Orient17a Camera

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

379 lines of JavaScript from gridatlas, in 1 file. Topic: Maps, GIS and field navigation. Section 572 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. Orient17a Camera geodesy · gridatlas / atlas/modules/202612040055-orient17a-camera.js lines 353–731

Orient17a Camera

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

Set aside from the main view: 96% of its lines are the same as atlas/modules/g203-03-gps-camera-candidate.js (gridatlas), which stays. (near-copy-of, proposed by families.py). 96% of lines shared with G203 03 Gps Camera Candidate; read that one first. All set-aside files, with reasons. Nothing was deleted.

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

geodesygridatlas / atlas/modules/202612040055-orient17a-camera.js · lines 353–731 of 731 · version 2026-12-04 00:55 (continued from section 571) · Not reached from any entry point (candidate for review) · pattern shouldAcceptCameraFix (shared by 3 files)

What it does
It maps substations and 11kV. Defines 40 functions or classes, including setPanelOpen, notify, updateText, distanceText, bearingText. Side effects: changes the web page (DOM).
Why it exists in the grid workflow
Domain stage 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: substations, 11kV, 33kV.
Inputs & outputs
Voltage levels named: 33kV, 11kV.
What it achieves
Unified GridAtlas/SatNav candidate. Derived from the immutable 2 km convergence cartridge; native shell geometry stays owned by GridAtlas. Its code works with 11 kV and 33 kV. It responds to click, visibilitychange and offline events.
Why it matters
No other file in the estate was found to import it.
Application
gridatlas · atlas/modules · script
Uses
none found
Used by
mentioned in Standalone (comment link)
Produces
setPanelOpen, notify, updateText, distanceText, bearingText, collection, cameraTarget, shouldAcceptCameraFix, pauseFollow, pauseGesture, refreshGuidance, changePlan
Defines here
arm, mapClick, selectedIndex, stopTracking, centreOnFix, installAssetActions, current, button, selectedOrigin, neon, valid, renderGridNodes, refresh, put
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/202612040055-orient17a-camera.js:353-731 · blob 18ee706f7fa7d1ca941579bdb8717a2cc6c84077 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: duplicate_candidate
    controls.stop.disabled = watch === null;
    updateText(controls.location, watch !== null ? (followCamera ? 'Following GPS' : 'Resume follow') : roles.from ? 'Start GPS' : 'My location');
    controls.undo.disabled = !localPlan && !history.length;
    controls.edit.disabled = !count || Boolean(localPlan);
    controls.edit.setAttribute('aria-expanded', String(!controls.editor.hidden));
    updateText(controls.from.querySelector('span'), picking === 'from' ? 'Tap map' : roles.from ? (roles.gpsOrigin ? 'GPS fix' : 'Selected point') : 'My location');
    updateText(controls.to.querySelector('span'), picking === 'to' || !roles.to ? 'Tap map' : 'Selected point');
    for (const key of ['from','to','add']) controls[key].setAttribute('aria-pressed', String(picking === key));
    controls['use-fix'].hidden = !picking || compass.fixQuality(fix) !== 'usable';
    if (!controls.editor.hidden) {
      const index = snapshot.pins.findIndex(pin => pin.id === selected);
      updateText(controls.selected, 'Pin ' + (index+1) + ' of ' + count + (selected === roles.from ? ' · FROM' : selected === roles.to ? ' · TO' : ''));
      updateText(controls.limit, 'Maximum ' + snapshot.maxPins.toLocaleString('en-GB') + ' pins');
      controls.prev.disabled = index <= 0;
      controls.next.disabled = index >= count - 1;
      const via = selected !== roles.from && selected !== roles.to;
      controls.earlier.disabled = !via || index <= (roles.from ? 1 : 0);
      controls.later.disabled = !via || index >= count - (roles.to ? 2 : 1);
    }
    const messages = [];
    if (!map) messages.push('Loading map');
    else if (picking) messages.push(picking === 'add' ? 'Tap map to add pin' : picking === 'replace' ? 'Tap map to move pin' : 'Tap map to set ' + picking.toUpperCase());
    else if (count > 1) messages.push(count + ' pins · ' + distanceText(planDistance) + ' planned');
    if (dateLineLegs) messages.push('Line omitted at the date line');
    if (notice) messages.push(notice);
    if (fieldState(fix).mapAvailability === 'offline-unverified') messages.push('Offline · map coverage unverified');
    if (fix) {
      messages.push('GPS ±' + Math.round(fix.accuracyM) + ' m');
      if (fix.heading !== null && compass.fixQuality(fix) === 'usable') messages.push('GPS course ' + bearingText(fix.heading));
    }
    updateText(controls.status, messages.join(' · '));
    const guide = guidanceText();
    updateText(controls.guide, guide);
    updateText(toggle, panelOpen ? 'HIDE SATNAV' : watch !== null ? 'SATNAV · GPS active' : 'SATNAV');
    toggle.setAttribute('aria-label', panelOpen ? 'Hide SatNav controls' : watch !== null ? 'Show SatNav controls, GPS active' : 'Show SatNav controls');
    if (!panelOpen && watch !== null && guide) toggle.title = guide;
    else toggle.removeAttribute('title');
  }
  function arm(which) {
    picking = picking === which ? null : which;
    notice = '';
    if (picking === 'from') pendingLocation = false;
    render();
  }
  function mapClick(event) {
    if (picking && event.lngLat) {
      const at = event.lngLat.wrap ? event.lngLat.wrap() : event.lngLat;
      place([at.lng, at.lat]);
    } else if (event.point && !localPlan) {
      const {x,y} = event.point;
      const ids = ['start','via','end'].map(role => planSource + '-' + role);
      if (!ids.every(id => map.getLayer(id))) return;
      const hit = map.queryRenderedFeatures([[x-7,y-7],[x+7,y+7]], {layers:ids})[0];
      if (hit?.properties?.pinId) { selected = hit.properties.pinId; controls.editor.hidden = false; render(); }
    }
  }
  for (const name of ['from','to','add','replace']) controls[name].onclick = () => arm(name);
  controls['use-fix'].onclick = () => {
    if (compass.fixQuality(fix) === 'usable') place([fix.longitude,fix.latitude], true);
    else {notice = 'Waiting for a usable GPS fix';render();}
  };
  controls.undo.onclick = undo;
  controls.edit.onclick = () => {controls.editor.hidden = !controls.editor.hidden; picking = null; render();};
  const selectedIndex = () => snapshot.pins.findIndex(pin => pin.id === selected);
  for (const [name,offset] of [['prev',-1],['next',1]]) controls[name].onclick = () => {
    selected = snapshot.pins[selectedIndex() + offset].id;
    picking = null;
    render();
  };
  for (const [name,offset] of [['earlier',-1],['later',1]]) controls[name].onclick = () => {
    picking = null;
    edit(() => state.move(selected, selectedIndex() + offset));
  };
  controls.remove.onclick = () => {
    picking = null;
    edit(() => {
      const removed = selected;
      state.remove(removed);
      if (removed === roles.from) { roles.from = null; roles.gpsOrigin = false; pendingLocation = false; }
      if (removed === roles.to) roles.to = null;
      return true;
    });
  };
  function stopTracking(message) {
    generation++;
    if (watch !== null) navigator.geolocation.clearWatch(watch);
    watch = null;
    followCamera = false;
    streetZoomPending = false;
    locationRequestedAt = null;
    lastFixMs = -Infinity;
    pendingLocation = false;
    notice = message;
    setFix(null);
    notify('stop',message);
    render();
  }
  function centreOnFix() {
    if ((!pendingLocation && !followCamera) ||
        !shouldAcceptCameraFix(fix,fieldState(fix).gpsState,locationRequestedAt,document.hidden)) return;
    const first = pendingLocation;
    pendingLocation = false;
    locationRequestedAt = null;
    const at = [fix.longitude,fix.latitude];
    // Preserve explicit FROM and route pins; only an empty FROM takes the first fix.
    try { if (first && !roles.from) setPin('from', at, true); }
    catch (error) { notice = error.message; return; }
    if (!followCamera) return; // A gesture may precede the first usable fix.
    const target = cameraTarget(map,fix,streetZoomPending);
    if (target) {
      streetZoomPending = false;
      map.jumpTo(target); // Subsequent fixes and Resume follow preserve zoom/bearing/pitch.
    }
  }
  controls.location.onclick = () => {
    if (!isSecureContext || !navigator.geolocation) {notice = 'Location needs HTTPS and device GPS';render();return;}
    pendingLocation = true;
    followCamera = true;
    permissionDenied = false;
    picking = null;
    notice = 'Waiting for GPS';
    if (watch !== null) {
      if (shouldAcceptCameraFix(fix,fieldState(fix).gpsState,locationRequestedAt,document.hidden)) {notice = '';centreOnFix();}
      render();
      return;
    }
    locationRequestedAt = Date.now();
    streetZoomPending = true;
    const active = ++generation;
    try {
      watch = navigator.geolocation.watchPosition(position => {
        if (active !== generation) return;
        const {longitude,latitude,accuracy:accuracyM,heading,speed,altitude,altitudeAccuracy} = position.coords;
        const next = Object.freeze({longitude,latitude,accuracyM,altitudeM:altitude,altitudeAccuracyM:altitudeAccuracy,timestampMs:position.timestamp,
          heading:Number.isFinite(heading) && heading >= 0 && heading < 360 && Number.isFinite(speed) && speed > 0 ? heading : null});
        const field = fieldState(next);
        const quality = field.gpsState;
        if (field.showMeasuredFix) {
          if (next.timestampMs <= lastFixMs) return;
          lastFixMs = next.timestampMs;
          setFix(next);
          notice = quality === 'poor' ? 'Low GPS accuracy' : '';
          centreOnFix();
        } else {
          setFix(null);
          notice = quality === 'stale' ? 'GPS fix is stale' : 'Waiting for a fresh GPS fix';
        }
        render();
      }, error => {
        if (active !== generation) return;
        if (error.code === 1) {permissionDenied = true;stopTracking('Location permission denied');}
        else {setFix(null); notice = 'Location unavailable'; render();}
      }, {enableHighAccuracy:true,maximumAge:0,timeout:10000});
      notify('watch');
    } catch {stopTracking('Location could not start');}
    render();
  };
  controls.stop.onclick = () => stopTracking('Location stopped');
  document.addEventListener('visibilitychange', () => {
    if (!document.hidden) resumedAt = Date.now();
    if (watch !== null) {
      setFix(null);
      notice = document.hidden ? 'GPS in background' : 'Waiting for a fresh GPS fix';
      render();
    }
  });
  window.addEventListener('offline', render);
  window.addEventListener('online', render);
  panel.addEventListener('keydown', event => {
    if (event.key === 'Escape') {event.stopPropagation(); picking = null; controls.editor.hidden = true; setPanelOpen(false); toggle.focus();}
  });
  for (const element of [toggle,panel,access]) {
    for (const name of ['click','dblclick','mousedown','pointerdown','touchstart']) element.addEventListener(name, event => event.stopPropagation());
  }
  // This is an interface-owned extension of the selected UKPN card.
  // No second popup, map, GPS watch, fabricated REPD identity or data fetch.
  function installAssetActions() {
    const card = map?.getContainer().querySelector('[data-ukpn-detail][data-site]');
    if (!card || card.querySelector('[data-satnav-asset-actions]')) return;
    const site = card.dataset.site;
    const actions = document.createElement('section');
    actions.dataset.satnavAssetActions = '1';
    const current = () => card.isConnected && actions.isConnected && card.dataset.site === site;
    const output = document.createElement('div');
    output.setAttribute('role','status');
    const button = (label, run) => {
      const el = document.createElement('button');
      el.type = 'button'; el.textContent = label;
      el.style.cssText = 'min-height:44px;display:block;width:100%;margin:3px 0';
      el.addEventListener('click', event => {
        event.stopPropagation();
        if (current()) run();
      });
      return el;
    };
    const selectedOrigin = () => {
      const source = map.getSource('src-ukpn_secondary');
      const feature = source?.serialize()?.data?.features?.find(f => String(f.id) === site);
      return feature?.geometry?.type === 'Point' ? feature.geometry.coordinates : null;
    };
    let gridRequest = 0;
    const neon = () => window.__GRIDATLAS_NEON_LINKS__;
    const clean = new MutationObserver(() => {if (!card.isConnected || card.dataset.site!==site) {++gridRequest;neon()?.clearSecondaryLinks?.(site);clean.disconnect();}});
    clean.observe(map.getContainer(),{childList:true,subtree:true,attributes:true,attributeFilter:['data-site']});
    actions.append(button('Ventus Grid Engine', async () => {
      const request = ++gridRequest;
      const valid = () => current() && request === gridRequest;
      output.replaceChildren();
      neon()?.clearSecondaryLinks?.();
      const origin = selectedOrigin();
      if (!origin) { output.textContent = 'Selected asset unavailable'; return; }
      const originalCamera = [map.getCenter().lng,map.getCenter().lat,map.getZoom(),map.getBearing(),map.getPitch()];
      output.textContent = 'Loading higher-voltage substations…';
      // Use the existing Grid Engine acquisition boundary, not a second dataset.
      try {
        window.__GRIDATLAS_NEON_LINKS__?.enableSubstationLayer?.();
        const deadline = Date.now() + 60000;
        let nodes = [];
        while (valid()) {
          const engine = window.__GRIDATLAS_NEON_LINKS__;
          const distance = typeof engine?.measure?.distanceKm === 'function'
            ? (...args) => engine.measure.distanceKm(...args)
            : typeof globalThis.VentusGridCompute?.distanceKm === 'function'
              ? (...args) => globalThis.VentusGridCompute.distanceKm(...args) : null;
          if (engine?.substations?.length && distance) nodes = rankHigherVoltage(engine.substations, origin, distance);
          if (nodes.length || Date.now() >= deadline) break;
          await new Promise(resolve => setTimeout(resolve,250));
        }
        if (!valid()) return;
        if (!nodes.length) { output.textContent = 'No qualifying higher-voltage sites loaded; try again'; return; }
        const ok = neon()?.drawSecondaryLinks?.({site,origin,nodes});
        if (!valid()) return;
        renderGridNodes(nodes, origin, valid);
        if (!ok) output.prepend('Neon geometry unavailable; retry. ');
        else if (watch === null && [map.getCenter().lng,map.getCenter().lat,map.getZoom(),map.getBearing(),map.getPitch()].every((v,i)=>v===originalCamera[i])) {
          const points=[origin,...nodes.map(n=>n.at)];
          const bounds=[[Math.min(...points.map(p=>p[0])),Math.min(...points.map(p=>p[1]))],[Math.max(...points.map(p=>p[0])),Math.max(...points.map(p=>p[1]))]];
          map.fitBounds(bounds,{padding:Math.min(56,Math.floor(innerWidth/6),Math.floor(innerHeight/6)),maxZoom:13,duration:300});
        }
      } catch (error) {
        if (valid()) output.textContent = 'Grid Engine unavailable; try again';
      }
    }), button('Vicinity', () => {
      ++gridRequest;
      neon()?.clearSecondaryLinks?.();
      const origin = selectedOrigin();
      const engine = window.__GRIDATLAS_MODULES__?.ukOfftakers;
      if (!origin || typeof engine?.openSecondaryVicinity !== 'function') {
        output.textContent = 'Secondary Vicinity is not available in this composition'; return;
      }
      if (!engine.openSecondaryVicinity({site,at:origin})) {
        output.textContent = 'Vicinity not ready; try again'; return;
      }
      notice = 'Vicinity opened for '+site;
      render();
    }), output);
    function renderGridNodes(nodes, origin, valid) {
      output.textContent = 'Mapped substations ≥33 kV · straight-line screening, not proven electrical connections or access.';
      if (!nodes.length) { output.append(' No qualifying sites found.'); return; }
      for (const node of nodes) {
        const row = document.createElement('div');
        row.textContent = node.name + ' · ' + node.kv + ' kV · ' + node.km.toFixed(2) + ' km from selected secondary';
        row.append(button('Use this destination', () => {
          if (!valid()) return;
          const result = prepareAssetDestination(maths, fix, node.at, watch !== null, fieldState(fix).gpsState);
          if (!result.ok) { notice = result.reason; render(); return; }
          replacePlan(result.coordinates);
          notice = 'Destination: ' + node.name;
          render();
        }));
        output.append(row);
      }
    }
    card.append(actions);
  }
  function refresh() {
    const host = document.fullscreenElement || document.webkitFullscreenElement || document.body;
    const dockOwnsControls = Boolean(document.getElementById('g203-native-dock')?.isConnected);
    if (panel.parentElement !== host || access.parentElement !== host) host.append(panel,access);
    if (!dockOwnsControls && toggle.parentElement !== host) host.append(toggle);
    const mapBounds = window.__GRIDATLAS_V9_MAP__?.getContainer()?.getBoundingClientRect();
    const layers = document.getElementById('gridatlas-dash-toggle')?.getBoundingClientRect();
    const tray = document.getElementById('gridatlas-mobile-tray');
    const mapBottom = Math.min(innerHeight,mapBounds?.bottom ?? innerHeight);
    const right = Math.max(12,innerWidth-Math.min(innerWidth,mapBounds?.right ?? innerWidth)+8);
    const layerAtBottom = layers?.height>0 && layers.top>innerHeight/2;
    const trayBottom = Math.max(12,innerHeight-mapBottom+8,layerAtBottom?innerHeight-layers.top+6:0);
    const put = (el,key,value) => {const v=Math.round(value)+'px';if(el.style.getPropertyValue(key)!==v)el.style.setProperty(key,v);};
    if (tray) {
      if (!dockOwnsControls && tray.parentElement!==host) host.appendChild(tray);
      if (!tray.hasAttribute('data-satnav-dock')) tray.setAttribute('data-satnav-dock','');
      put(tray,'--satnav-dock-right',right);put(tray,'--satnav-tray-bottom',trayBottom);
    }
    const trayHeight = Math.max(44,tray?.getBoundingClientRect().height||44);
    const toggleBottom = trayBottom+trayHeight+6;
    put(toggle,'--satnav-dock-right',right);put(toggle,'--satnav-dock-bottom',toggleBottom);
    const panelBottom = toggleBottom+Math.max(44,toggle.getBoundingClientRect().height)+6;
    put(panel,'--satnav-dock-right',right);put(panel,'--satnav-panel-bottom',panelBottom);
    put(panel,'--satnav-panel-height',Math.max(64,innerHeight-panelBottom-Math.max(48,mapBounds?.top??0)-8));
    const next = window.__GRIDATLAS_V9_MAP__;
    if (next && next.getLayer('l-sat') && next !== map) {
      map?.off('click',mapClick);
      map?.off('dragstart',pauseFollow);
      map?.off('zoomstart',pauseGesture);
      map?.off('rotatestart',pauseGesture);
      map?.off('pitchstart',pauseGesture);
      map = next;
      planDirty = positionDirty = true;
      map.on('click',mapClick);
      map.on('dragstart',pauseFollow);
      map.on('zoomstart',pauseGesture);
      map.on('rotatestart',pauseGesture);
      map.on('pitchstart',pauseGesture);
      map.resize();
      notify('map',map);
    }
    if (fix && compass.fixQuality(fix) === 'stale') {setFix(null);notice = 'GPS fix is stale';}
    installAssetActions();
    if (!layerSearch && installUnifiedLayerSearch) {
      try {layerSearch = installUnifiedLayerSearch(document);}
      catch(error){installUnifiedLayerSearch=null;console.error('Optional Layers search unavailable; native Layers retained',error);}
    }
    render();
  }
  panel.satnavSurvey = Object.freeze({
    getPins: () => snapshot.pins,
    getEndpoints: () => [roles.from ? snapshot.pins[0].coordinate : null, roles.to ? snapshot.pins.at(-1).coordinate : null],
    getMap: () => map,
    getFix: () => ['usable','poor'].includes(compass.fixQuality(fix)) ? fix : null,
    isTracking: () => watch !== null,
    isPanelOpen: () => panelOpen,
    setPanelOpen,
    maths,
    distanceKm: maths.distanceKm,
    fixQuality: compass.fixQuality,
    replacePlan,
    leaveExample,
    isExample: () => Boolean(localPlan),
    setDestination: at => { const changed = setPin('to', at); picking = null; render(); return changed; },
    isFollowing: () => followCamera,
    transferSearchDestination(handle) {
      const at = handle?.at;
      if (!map || localPlan) return {ok:false,reason:'Return to your own plan first'};
      if (watch !== null) {
        const result = prepareAssetDestination(maths,fix,at,true,fieldState(fix).gpsState);
        if (!result.ok) return result;
        replacePlan(result.coordinates);
      } else {
        const pins = snapshot.pins.map(pin=>pin.coordinate);
        if (roles.to) pins.pop();
        const previous = pins.at(-1) || null;
        const result = validateDestinationLeg(previous,at,(a,b)=>maths.distanceKm(...a,...b));
        if (!result.ok) return result;
        if (previous && classifyDirectLeg(maths,previous,at).status === 'coincident') return {ok:false,reason:'Unsupported direct leg'};
        if (!setPin('to',at)) return {ok:false,reason:'Destination unchanged'};
      }
      picking = null; notice = 'Destination: ' + handle.label; setPanelOpen(true);
      return {ok:true};
    },
    setClosedLoop(enabled) {
      if (enabled && (!roles.from || snapshot.pins.length < 3 || snapshot.pins.length >= snapshot.maxPins)) return false;
      const previous = closed;
      closed = Boolean(enabled);
      if (closed !== previous) {refreshGuidance();render();}
      return true;
    },
  });
  refresh();
  document.dispatchEvent(new Event('satnav:ready'));
  let timer = setInterval(refresh, 500);
  window.addEventListener('pagehide', event => {clearInterval(timer); stopTracking(event.persisted?'Location suspended':'Location stopped');});
  window.addEventListener('pageshow', event => {if (event.persisted) {refresh();timer = setInterval(refresh, 500);}});
}().catch(error => {
  console.error('SatNav waypoint map failed', error);
  const message = document.createElement('p');
  message.setAttribute('role','alert');
  message.textContent = 'SatNav controls could not load. Reload to try again.';
  document.body.prepend(message);
});