GLOBALGRID2050 / EXPLORE CODE

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

SatNav Handoff and 2 more files

A JavaScript file in the atlas folder of GridAtlas that maps grid substations and postcodes, and uses data from the SatNav repository.

651 lines of JavaScript from gridatlas, in 3 files. Topic: Maps, GIS and field navigation. Section 536 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. Vicinity Controls Rescue interaction · gridatlas / atlas/modules/202611222343-vicinity-controls-rescue.js lines 1–131
  2. SatNav Handoff render · gridatlas / atlas/modules/202611242030-satnav-handoff.js lines 1–351
  3. SatNav Origin Focus interaction · gridatlas / atlas/modules/202611242030-satnav-origin-focus.js lines 1–169

Vicinity Controls Rescue

A JavaScript file in the atlas folder of GridAtlas that works with float layers (`floatLayers`) and full mode (`fullMode`) (units: MW).

Set aside from the main view: 99% of its lines are the same as atlas/modules/g203-vicinity-controls-rescue.js (gridatlas), which stays. (near-copy-of, proposed by families.py). 99% of lines shared with G203 Vicinity Controls Rescue; read that one first. All set-aside files, with reasons. Nothing was deleted.

Evidence
  • line-jaccard 0.9913 to gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 atlas/modules/g203-vicinity-controls-rescue.js:1-132 3f6d8c4e6c314383b31449553f8cf3e1c7d2c89b
  • sha256 97cb8d05c7c0855b3bdd02ba614f470fbe2d489ed2db7181ca0b7edd5313c8fc
  • target sha256 f85d774c825fb95f0ba644f81a62f24ff56f36ab9bd42986cab7a898956fbd77
  • group of 2 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines

interactiongridatlas / atlas/modules/202611222343-vicinity-controls-rescue.js · lines 1–131 of 131 · version 2026-11-22 23:43 · Not reached from any entry point (candidate for review) · pattern floatLayers (shared by 2 files)

What it does
Defines 8 functions or classes, including answered, floatLayers, wake, fallback, tick. Side effects: changes the web page (DOM).
Why it exists in the grid workflow
Domain stage upstream_foresight (path word 'atlas'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight.
What it achieves
It is built from the answered step (`answered`), the float layers helper (`floatLayers`) and the wake step (`wake`). The V9.194 launcher put this button INSIDE the map-controls stacking context. It responds to visibilitychange, pagehide and click 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
answered, floatLayers, wake, fallback, tick, later, fullMode, reflect
Defines here
answered, floatLayers, wake, fallback, tick, later, fullMode, 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/202611222343-vicinity-controls-rescue.js:1-131 · blob 1ec6d6807561950e8e203199461b69864186250c · 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
/* GridAtlas V9.196: keep the inherited Grid Engine; repair PDF/tab wake and Layers hit target. */
(function(){
 'use strict';
 const W=window,D=document,q=new URLSearchParams(W.location.search);
 const ref=q.get('repd_ref'),latRaw=q.get('latitude'),lonRaw=q.get('longitude');
 if(!/^[1-9]\d{0,11}$/.test(ref||'')||!latRaw?.trim()||!lonRaw?.trim())return;
 if(['repd_ref','latitude','longitude'].some(k=>q.getAll(k).length!==1))return;
 const lat=Number(latRaw),lon=Number(lonRaw);
 if(!Number.isFinite(lat)||!Number.isFinite(lon)||lat<49.5||lat>61.5||lon< -11||lon>3)return;
 if(Math.abs(lat-49.766807)<.0001&&Math.abs(lon+7.55716)<.0001)return;
 const loc=[lon,lat],name=(q.get('project')||q.get('name')||'REPD '+ref).slice(0,180);
 const tech=(q.get('technology')||'').slice(0,80),mw=Number(q.get('capacity_mw'));
 const started=Date.now(),qa=W.__GRIDATLAS_VICINITY_LINK_QA__={generation:'202611222325',repd_ref:ref,layers:'pending',grid:'pending',fallback_attempts:0};
 function answered(){const e=W.__GRIDATLAS_NEON_LINKS__;return Boolean(e?.arrival_engine?.answered===true||e?.links_drawn>0||e?.declared_connection_framed===true)}
 function floatLayers(){
   const b=D.getElementById('gridatlas-dash-toggle');if(!b)return;
   // The V9.194 launcher put this button INSIDE the map-controls stacking
   // context. Its huge z-index could not outrank the project card.
   const host=D.fullscreenElement||D.webkitFullscreenElement||D.body;
   if(!host)return;
   if(b.parentElement!==host)host.appendChild(b);
   b.hidden=false;
   const menu=D.getElementById('gridatlas-menu-bar'),map=W.__GRIDATLAS_V9_MAP__?.getContainer?.();
   const anchor=menu?.getBoundingClientRect?.().bottom??map?.getBoundingClientRect?.().top??0;
   const height=Math.max(80,W.innerHeight||D.documentElement.clientHeight||852);
   const top=Math.min(Math.max(8,Math.ceil(anchor)+8),Math.max(8,height-54));
   for(const [k,v] of Object.entries({position:'fixed',top:top+'px',bottom:'auto',right:'12px',left:'auto','z-index':'2147483646','pointer-events':'auto','touch-action':'manipulation','min-height':'44px'}))b.style.setProperty(k,v,'important');
   qa.layers='accessible-floating-toggle';
 }
 let wakes=0,recovered=false,inflight=false;
 function wake(){
   const l=W.__GRIDATLAS_NEON_LINKS__;
   if(D.visibilityState!=='visible'||answered()||wakes>=2)return;
   if(!l?.arrival_attempts||l?.arrival_engine?.reason==='DEFERRED_FOR_VISIBILITY'){
     wakes++;D.dispatchEvent(new Event('visibilitychange'));qa.grid='visible-wake-'+wakes;
   }
 }
 async function fallback(){
   if(answered()){qa.grid='answered';return}
   if(D.visibilityState!=='visible'||Date.now()-started<20000||recovered||inflight)return;
   const l=W.__GRIDATLAS_NEON_LINKS__;
   if(typeof l?.selectAt!=='function'||l.arrival_engine?.terminal===false)return;
   if(['FALSE_ORIGIN','NOT_IN_REGISTER','HANDED_TO_INTERCONNECTORS','IDENTITY_REJECTED'].includes(l.arrival_engine?.reason))return;
   recovered=inflight=true;qa.fallback_attempts++;qa.grid='measuring-original-engine';
   try{
     const ok=await l.selectAt(loc,name,tech,false,Number.isFinite(mw)&&mw>0?mw:null);
     qa.grid=ok===true?'original-engine-completed':'original-engine-unavailable';
   }catch(error){qa.grid='original-engine-failed';qa.error=String(error?.message||error).slice(0,160)}
   finally{inflight=false}
 }
 function tick(){floatLayers();if(answered()){qa.grid='answered';return}if(Date.now()-started>1500&&wakes===0)wake();void fallback()}
 const timer=setInterval(tick,1000);
 const later=()=>setTimeout(tick,0);
 for(const n of ['focus','pageshow','resize','orientationchange'])W.addEventListener(n,later);
 for(const n of ['fullscreenchange','webkitfullscreenchange'])D.addEventListener(n,later);
 D.addEventListener('visibilitychange',later);
 W.addEventListener('pagehide',()=>clearInterval(timer),{once:true});
 tick();
})();

/* V9.197 correction: the native dash toggle controls .scada-wrapper.
 * In fullscreen (including Safari's CSS-only fullscreen) that wrapper is
 * outside the visible map; the working original control is #fs-curtain-tab.
 * Route the same visible floating button into the original curtain handler.
 * Never claim that a changed .collapsed Boolean means a layer panel appeared.
 */
(function fullscreenLayerBridge(){
 'use strict';
 const W=window,D=document;
 const fullMode=()=>!!(D.fullscreenElement||D.webkitFullscreenElement||
   D.body.classList.contains('fs-active')||
   D.getElementById('map-container')?.classList.contains('is-fullscreen'));
 let wired=null,origin=null;
 const result=W.__GRIDATLAS_LAYER_VISIBILITY_QA__={
   generation:'202611222343',mode:'waiting',curtain_clicks:0,fullscreen_panel_visible:false};
 function reflect(){
   const button=D.getElementById('gridatlas-dash-toggle');
   const curtain=D.getElementById('fs-curtain');
   const tab=D.getElementById('fs-curtain-tab');
   if(!button||!curtain||!tab)return;
   const nativeFull=D.fullscreenElement||D.webkitFullscreenElement;
   if(nativeFull&&!nativeFull.contains(curtain)){
     if(!origin)origin={parent:curtain.parentNode,next:curtain.nextSibling};
     nativeFull.appendChild(curtain); // moves original controls/listeners, never clones
   }else if(!nativeFull&&origin){
     if(origin.next?.parentNode===origin.parent)origin.parent.insertBefore(curtain,origin.next);
     else origin.parent.appendChild(curtain);
     origin=null;
   }
   const fullscreen=fullMode();
   if(wired!==button){
     wired=button;
     button.addEventListener('click',event=>{
       if(!fullMode())return; // ordinary view keeps original .scada-wrapper logic
       event.preventDefault();event.stopImmediatePropagation();
       const target=D.getElementById('fs-curtain-tab');
       const panel=D.getElementById('fs-curtain');
       if(!target||!panel){result.mode='missing-original-curtain';return}
       target.click(); // the original GridAtlas engine owns curtainOpen
       result.curtain_clicks++;
       result.mode='fullscreen-curtain';
       result.fullscreen_panel_visible=panel.classList.contains('curtain-open');
       reflect();
     },true);
   }
   if(fullscreen){
     button.hidden=false;
     const shown=curtain.classList.contains('curtain-open');
     button.textContent=shown?'▴ HIDE LAYERS':'▾ LAYERS';
     button.setAttribute('aria-label',shown?'Hide the fullscreen layers panel':'Show the fullscreen layers panel');
     button.setAttribute('aria-pressed',String(shown));
     result.mode='fullscreen-curtain';
     result.fullscreen_panel_visible=shown;
   }else{
     result.mode='normal-scada-panel';
     result.fullscreen_panel_visible=false;
     // The original control still owns ordinary collapse, label and state.
     const collapsed=W.__GRIDATLAS_DASH__?.collapsed;
     if(typeof collapsed==='boolean'){
       button.textContent=collapsed?'▴ LAYERS':'▾ HIDE LAYERS';
       button.setAttribute('aria-pressed',String(collapsed));
       button.setAttribute('aria-label',collapsed?'Show the layers panel':'Hide the layers panel');
     }
   }
 }
 const timer=setInterval(reflect,250);
 for(const event of ['focus','pageshow','resize','orientationchange'])W.addEventListener(event,reflect);
 for(const event of ['fullscreenchange','webkitfullscreenchange'])D.addEventListener(event,reflect);
 W.addEventListener('pagehide',()=>clearInterval(timer),{once:true});
 reflect();
})();

SatNav Handoff

A JavaScript file in the atlas folder of GridAtlas that maps grid substations and postcodes, and uses data from the SatNav repository.

rendergridatlas / atlas/modules/202611242030-satnav-handoff.js · lines 1–351 of 351 · version 2026-11-24 20:30 · Not reached from any entry point (candidate for review) · pattern satellite (shared by 2 files)

What it does
It maps grid substations and postcodes. Defines 21 functions or classes, including button, field, disclosure, samePoint, satellite. Side effects: changes the web page (DOM); makes network requests.
Why it exists in the grid workflow
Domain stage agent_infra (path word 'handoff'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief). Domain terms in the code: postcodes.
Inputs & outputs
In: data source: satnav data; GeoJSON file grid_substations.geojson. Out: interactive map. Coordinate systems named: WGS84 / EPSG:4326.
What it achieves
It places search (`placeSearch`), searches input (`searchInput`) and closes panel (`closePanel`). Native GridAtlas M1 candidate; adapted from Agent33 . It responds to input, keydown and pagehide events.
Why it matters
No other file in the estate was found to import it.
Application
gridatlas · atlas/modules · script
Uses
none found
Used by
none found
Produces
button, field, disclosure, samePoint, satellite, projectRef, placeSearch, projectSelection, searchInput, closePanel, currentCardPoint, reset
Defines here
button, field, disclosure, samePoint, satellite, projectRef, placeSearch, projectSelection, searchInput, closePanel, currentCardPoint, reset, render, stage, mapClick, selectedProject, selectedLocation, stillCurrent, destinationName, syncFullscreenHost, refresh
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 atlas/modules/202611242030-satnav-handoff.js:1-351 · blob 57de2d89222a24306618a165ccfa84d7b70b3eb4 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, network · domain stage: agent_infra · users: ai_agent · canonical: unreached_review
/* Native GridAtlas M1 candidate; adapted from Agent33 c07f23de. */
// Loader v2 composes script text inline; preview route is /atlas/v/<candidate>/.
const satnavRoot = new URL('../../../', location.href);
void async function () {
  const compass = new URL('https://ventusltd.github.io/satnav/preview/9698781539e549deaa6ecaa4a2b34610c1f9fd29/nav/');
  const { buildDestination } = await import(new URL('tools/satnav/place.mjs', satnavRoot));
  const { normaliseOrigin, validCoordinate } = await import(new URL('tools/vicinity/src/model.mjs', satnavRoot));
  const style = document.createElement('style');
  style.textContent = `
    :root { --gridatlas-satnav-top:128px; }
    @media (max-width:600px) { :root { --gridatlas-satnav-top:136px; } }
    @media (max-width:359px) { :root { --gridatlas-satnav-top:214px; } }
    #gridatlas-satnav-toggle { position:fixed; z-index:10019; left:12px; top:var(--gridatlas-satnav-top); }
    #gridatlas-satnav-satnav { position:fixed; z-index:10019; right:12px; top:calc(var(--gridatlas-satnav-top) + 52px);
      width:min(380px,calc(100% - 24px)); max-height:calc(100dvh - var(--gridatlas-satnav-top) - 64px);
      overflow:auto; box-sizing:border-box; padding:12px;
      border:1px solid #367078; border-radius:6px; background:#08141bed;
      color:#e4f7f7; font:14px/1.45 ui-monospace,monospace; }
    #gridatlas-satnav-satnav h2 { margin:0 0 8px; font:inherit; font-weight:bold; color:#00ffff; }
    #gridatlas-satnav-satnav p { margin:8px 0 0; overflow-wrap:anywhere; }
    #gridatlas-satnav-satnav .actions { display:flex; flex-wrap:wrap; gap:6px; }
    #gridatlas-satnav-toggle, #gridatlas-satnav-satnav button { min-height:44px; max-width:100%; padding:6px 9px;
      border:1px solid #367078; border-radius:3px; background:#07191f;
      color:#bff7f9; font:14px/1.45 ui-monospace,monospace; cursor:pointer; text-align:left; touch-action:manipulation; }
    #gridatlas-satnav-satnav button:disabled { color:#8ba0a2; cursor:default; }
    #gridatlas-satnav-toggle:focus-visible, #gridatlas-satnav-satnav button:focus-visible { outline:2px solid #fff; outline-offset:1px; }
    #gridatlas-satnav-satnav summary { display:flex; align-items:center; min-height:44px; cursor:pointer; }
    #gridatlas-satnav-satnav summary::before { content:'▸'; margin-right:.5em; }
    #gridatlas-satnav-satnav details[open] summary::before { content:'▾'; }
    #gridatlas-satnav-satnav input { display:block; box-sizing:border-box; width:100%; min-height:44px;
      background:#07191f; color:white; border:1px solid #367078; font-size:16px; }
    #gridatlas-satnav-pin-label { width:100%; }
    #gridatlas-satnav-satnav [hidden] { display:none; }
  `;
  document.head.append(style);
  const panel = document.createElement('section');
  panel.id = 'gridatlas-satnav-satnav';
  panel.setAttribute('aria-labelledby', 'gridatlas-satnav-satnav-title');
  const heading = document.createElement('h2');
  heading.id = 'gridatlas-satnav-satnav-title';
  heading.textContent = 'Where are you going?';
  const actions = document.createElement('div');
  actions.className = 'actions';
  const confirmation = document.createElement('div');
  confirmation.className = 'actions';
  const status = document.createElement('p');
  status.setAttribute('role', 'status');
  status.textContent = 'Waiting for the GridAtlas map…';
  function button(id, name, parent = actions) {
    const element = document.createElement('button');
    element.type = 'button';
    element.id = `gridatlas-satnav-${id}`;
    element.textContent = name;
    parent.append(element);
    return element;
  }
  const mapSearch = button('map-search', 'Search projects, places or postcodes');
  const planned = button('planned', 'Use selected search result');
  const pick = button('pick', 'Choose point on satellite');
  const origin = button('origin', 'Use Vicinity origin');
  const asset = button('asset', 'Use highlighted asset');
  const confirm = button('confirm', 'Use in SatNav', confirmation);
  const cancel = button('cancel', 'Cancel', confirmation);
  const vicinity = button('vicinity', 'Explore this point in Vicinity', confirmation);
  const pinLabel = document.createElement('label');
  pinLabel.id = 'gridatlas-satnav-pin-label';
  pinLabel.textContent = 'Name this pin (optional)';
  const pinName = document.createElement('input');
  pinName.type = 'text';
  pinName.maxLength = 120;
  pinLabel.append(pinName);
  confirmation.prepend(pinLabel);
  const manual = document.createElement('form');
  const field = (label, id) => {
    const wrap=document.createElement('label');wrap.textContent=label;
    const input=document.createElement('input');input.id='gridatlas-satnav-'+id;
    input.type='text';
    wrap.append(input);manual.append(wrap);return input;
  };
  const latitude=field('Latitude (signed WGS84)','latitude');
  const longitude=field('Longitude (signed WGS84)','longitude');
  latitude.inputMode=longitude.inputMode='decimal';
  const manualLabel=field('Optional destination label','label');
  const commit=button('manual','Choose coordinates',manual);commit.type='submit';
  const lookup=document.createElement('form');
  const searchLabel=document.createElement('label');searchLabel.textContent='Existing substation name or source ID';
  const search=document.createElement('input');search.type='search';searchLabel.append(search);lookup.append(searchLabel);
  const find=button('search','Find substations',lookup);
  find.type='submit';
  const results=document.createElement('div');lookup.append(results);
  function disclosure(id, title, content) {
    const details = document.createElement('details');
    details.id = `gridatlas-satnav-${id}-details`;
    const summary = document.createElement('summary');
    summary.textContent = title;
    details.append(summary, content);
    return details;
  }
  panel.append(heading, actions, status, confirmation,
    disclosure('station', 'Find an existing substation', lookup),
    disclosure('manual', 'Enter coordinates (advanced)', manual));
  document.body.append(panel);
  panel.hidden = true;
  const toggle = button('toggle','SatNav',document.body);
  toggle.setAttribute('aria-label','SatNav destination');
  toggle.setAttribute('aria-controls',panel.id);
  toggle.setAttribute('aria-expanded','false');
  const close=button('close','Close destination panel',panel);

  const samePoint = (a, b) => a?.length === 2 && b?.length === 2 && a[0] === b[0] && a[1] === b[1];
  const satellite = () => document.querySelector('#scada-ui-container input[name="bm"][value="sat"]');
  let map, marker, armed = false, pending = null, searchEpoch=0;
  const defaultStatus = 'Search for a destination, choose a satellite point or use an open Vicinity card.';
  const projectRef = () => new URLSearchParams(location.search).get('repd_ref');
  const placeSearch = () => window.__GRIDATLAS_PLACE_SEARCH__;
  const projectSelection = () => placeSearch()?.last_selection;
  const searchInput = () => document.getElementById('search-input');

  function closePanel() {
    if (armed) reset('Selection cancelled.');
    panel.hidden = true;
    toggle.setAttribute('aria-expanded', 'false');
  }

  toggle.onclick = () => {
    if (!panel.hidden) { closePanel(); return; }
    panel.hidden = false;
    toggle.setAttribute('aria-expanded', 'true');
  };
  close.onclick = () => { closePanel(); toggle.focus({ preventScroll: true }); };
  mapSearch.onclick = () => {
    closePanel();
    searchInput()?.focus();
  };

  // Read the exact current project or swiped item from the native Vicinity card.
  function currentCardPoint(kind) {
    const card = window.__GRIDATLAS_MODULES__?.ukOfftakers?.state.pp;
    if (!card?.project) return null;
    if (kind === 'origin') {
      const selected = projectSelection();
      const ref = card.r.p.repd_ref;
      if (ref && ((selected && String(selected.repd_ref) === String(ref) && selected.mapped !== true) ||
        samePoint(card.r.a, [-7.55716, 49.766807]))) return null;
      return { card, name: card.r.n, at: card.r.a };
    }
    if(card.__vicFocus?.origin) return null;
    const swipe = card.swipe;
    const entry = swipe?.entries[swipe.index];
    const highlight = swipe?.marker?.getLngLat();
    if (!entry || !highlight || !samePoint([highlight.lng, highlight.lat], entry.at)) return null;
    return { card, index: swipe.index, name: entry.name, at: entry.at };
  }

  function reset(message) {
    armed = false;
    pending = null;
    pinName.value = '';
    marker?.remove();
    marker = null;
    status.textContent = message;
    render();
  }

  function render() {
    pick.disabled = !map?.getLayer('l-sat') || !satellite();
    pick.setAttribute('aria-pressed', String(armed));
    mapSearch.disabled = !searchInput() || !placeSearch()?.ready;
    origin.disabled = !currentCardPoint('origin');
    asset.disabled = !currentCardPoint('asset');
    origin.hidden = origin.disabled;
    asset.hidden = asset.disabled;
    confirmation.hidden = !armed && !pending;
    confirm.hidden = !pending;
    vicinity.hidden = !pending;
    pinLabel.hidden = pending?.kind !== 'map';
  }

  function stage(kind, selection) {
    if (!selection) return;
    searchEpoch++;
    results.textContent='';
    reset('');
    try {
      const value = normaliseOrigin({ at: selection.at, name: selection.name, type: 'map-point' });
      pending = { kind, selection: { ...selection, at: value.at }, value };
      if (kind === 'map') marker = new window.maplibregl.Marker({ color: '#00ffff' }).setLngLat(value.at).addTo(map);
      status.textContent = `${value.name} · ${value.at[1].toFixed(6)}, ${value.at[0].toFixed(6)}`;
      render();
      confirm.focus();
    } catch {
      reset('Choose a valid map point.');
    }
  }

  // Same armed MapLibre click and [longitude, latitude] order as Vicinity bootstrap.
  function mapClick(event) {
    if (!panel.hidden && armed && event.lngLat) {
      stage('map', { name: 'Chosen map point', at: [event.lngLat.lng, event.lngLat.lat] });
    }
  }

  pick.onclick = () => {
    searchEpoch++;
    results.textContent='';
    if (armed) { reset('Selection cancelled.'); return; }
    reset('Tap a point on the satellite map.');
    const input = satellite();
    if (!input.checked) input.click();
    armed = true;
    render();
  };
  origin.onclick = () => stage('origin', currentCardPoint('origin'));
  asset.onclick = () => stage('asset', currentCardPoint('asset'));
  function selectedProject() {
    const selected = projectSelection();
    if (selected?.mapped !== true || String(selected.repd_ref) !== projectRef() ||
      !validCoordinate([selected.longitude, selected.latitude])) return null;
    // Keep the exact record for source status and address.
    const rows = placeSearch().last_results.filter(row => row.repd_ref === selected.repd_ref &&
      row.longitude === selected.longitude && row.latitude === selected.latitude);
    return rows.length === 1 ? rows[0] : null;
  }

  function selectedLocation() {
    const selected = placeSearch()?.last_location_selection;
    return projectRef() === null && selected?.mapped === true &&
      validCoordinate([selected.longitude, selected.latitude]) ? selected : null;
  }

  planned.onclick = () => {
    const selected = projectSelection();
    if (selected && String(selected.repd_ref) === projectRef() && selected.mapped !== true) {
      reset('This project has no mapped location. Choose a point on satellite or enter known coordinates.');
      return;
    }
    const record = selectedProject();
    if (record) {
      stage('planned', { name: record.name, at: [record.longitude, record.latitude], record });
      if (pending) status.textContent += ' · ' + [
        'REPD ' + record.repd_ref, record.status, record.address, record.postcode, 'Source point; entrance unverified',
      ].filter(Boolean).join(' · ');
      return;
    }
    const place = selectedLocation();
    if (place) {
      stage('location', { name: place.label, at: [place.longitude, place.latitude], place });
      if (pending) status.textContent += ' · ' + [place.sublabel, place.provider, 'Location only'].filter(Boolean).join(' · ');
      return;
    }
    reset('Select a mapped result in GridAtlas search, or choose a point on satellite.');
  };
  manual.onsubmit=event=>{
    event.preventDefault();
    const number=/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)$/;
    if(!number.test(latitude.value.trim())||!number.test(longitude.value.trim())||Math.abs(Number(latitude.value))>90||Math.abs(Number(longitude.value))>180||(!Number(latitude.value)&&!Number(longitude.value))){status.textContent='Enter valid signed latitude and longitude. Previous selection retained.';return;}
    searchEpoch++;results.textContent='';
    stage('manual',{name:manualLabel.value.trim()||'Manual coordinate point',at:[Number(longitude.value),Number(latitude.value)]});
  };
  let stationIndex;
  search.addEventListener('input', () => {
    searchEpoch++;
    results.textContent = '';
  });
  lookup.onsubmit=async event=>{
    event.preventDefault();
    const epoch=++searchEpoch;const query=search.value.trim();results.textContent='';
    if(!query)return;
    reset('Loading the existing mapped substation snapshot…');
    try{
      if(!stationIndex){
        const [{buildStationIndex},response]=await Promise.all([import(new URL('tools/train/src/station-index.mjs',satnavRoot)),fetch(new URL('atlas/releases/202608300453-atlas-v9/data/grid_substations.geojson',satnavRoot))]);
        if(!response.ok)throw Error('Substation source unavailable');
        const data=await response.json();
        const geodesy=window.__GRIDATLAS_MODULES__?.geodesy;
        if(!geodesy)throw Error('Canonical geodesy is not ready');
        stationIndex=buildStationIndex(data.features,{geodesy,datasetPin:'gridatlas baseline 1c9ed251ea31de67cc9d7e3b3d7908ea6aa39779'});
      }
      if(epoch!==searchEpoch)return;
      const matches=stationIndex.search(query,{limit:25});
      status.textContent=matches.matched?matches.matched+' source records; select the exact location. Addresses are not supplied by this snapshot.':'No matching substation in the mapped snapshot.';
      for(const row of matches.rows){
        const item=button('station-'+results.children.length,row.name+' · '+row.stationId+' · '+row.at[1]+', '+row.at[0],results);
        item.onclick=()=>{if(epoch!==searchEpoch)return;stage('station',{name:row.name,at:row.at,row});};
      }
    }catch(error){if(epoch===searchEpoch)status.textContent='Substation provider failed: '+error.message;}
  };
  function stillCurrent(){
    if(!pending)return false;
    if(pending.kind==='planned'&&selectedProject()!==pending.selection.record){reset('Project selection changed. Select it again.');return false;}
    if(pending.kind==='location'&&selectedLocation()!==pending.selection.place){reset('Location selection changed. Select it again.');return false;}
    if(['origin','asset'].includes(pending.kind)){
      const current=currentCardPoint(pending.kind), selection=pending.selection;
      if(!current||current.card!==selection.card||current.index!==selection.index||current.name!==selection.name||!samePoint(current.at,pending.value.at)){reset('The Vicinity selection changed. Select it again.');return false;}
    }
    return true;
  }
  function destinationName(kind, value) {
    return kind === 'map' ? pinName.value.trim() || value.name : value.name;
  }
  vicinity.onclick=()=>{
    if(!stillCurrent())return;
    const {value,selection,kind}=pending;
    const opened=window.__GRIDATLAS_MODULES__?.ukOfftakers?.openPointVicinity?.({at:value.at,name:destinationName(kind,value),kind,repdRef:kind==='planned'?selection.record.repd_ref:null,status:kind==='planned'?selection.record.status:null});
    if(opened){reset('Vicinity opened at the selected source point.');closePanel();}
    else status.textContent='Vicinity engine not ready. Selection retained; retry when loaded.';
  };
  cancel.onclick = () => { searchEpoch++;results.textContent='';reset('Selection cancelled.'); pick.focus(); };
  confirm.onclick = () => {
    if (!stillCurrent()) return;
    const { kind, value } = pending;
    const query = buildDestination({ name: destinationName(kind, value), coordinates: value.at, mode: 'compass' });
    location.assign(new URL(query, compass));
  };
  panel.addEventListener('keydown', event => {
    if (event.key === 'Escape' && (armed || pending)) { event.preventDefault(); cancel.click(); }
  });
  for (const type of ['click', 'dblclick', 'mousedown', 'pointerdown', 'touchstart']) {
    panel.addEventListener(type, event => event.stopPropagation());
  }

  function syncFullscreenHost() {
    const host = document.fullscreenElement || document.webkitFullscreenElement || document.body;
    if (toggle.parentElement !== host) host.append(toggle, panel);
  }

  function refresh() {
    const nativeMap = window.__GRIDATLAS_V9_MAP__;
    if (nativeMap && nativeMap !== map && nativeMap.getLayer('l-sat')) {
      map?.off('click', mapClick);
      map = nativeMap;
      map.on('click', mapClick);
      status.textContent = defaultStatus;
    }
    syncFullscreenHost();
    render();
  }
  refresh();
  let timer = setInterval(refresh, 250);
  window.addEventListener('pagehide', () => {
    clearInterval(timer);
    map?.off('click', mapClick);
    reset(defaultStatus);
    map = null;
  });
  window.addEventListener('pageshow', event => {
    if (!event.persisted) return;
    refresh();
    timer = setInterval(refresh, 250);
  });
}().catch(error => console.error('Detached SatNav handoff failed', error));

SatNav Origin Focus

A JavaScript file in the atlas folder of GridAtlas covering the Renewable Energy Planning Database (REPD) register and substations.

Set aside from the main view: 91% of its lines are the same as atlas/modules/202612012118-secondary-vicinity-focus.js (gridatlas), which stays. (near-copy-of, proposed by families.py). 90% of lines shared with Secondary Vicinity Focus; read that one first. All set-aside files, with reasons. Nothing was deleted.

Evidence
  • line-jaccard 0.9057 to gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 atlas/modules/202612012118-secondary-vicinity-focus.js:1-173 c414dfd9f09a698adf28b8e3300130e9223571ae
  • sha256 fd8e6a8ca6109f9e6b374d0ad64a921f4d64e94221c0649ed9e7b9f17d9b2aec
  • target sha256 83f9d06546c9250560c6c90a482d1ba167e7e6b19007e08fc4bd380abf14e98a
  • group of 3 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines

interactiongridatlas / atlas/modules/202611242030-satnav-origin-focus.js · lines 1–169 of 169 · version 2026-11-24 20:30 · Not reached from any entry point (candidate for review) · pattern safely (shared by 3 files)

What it does
It draws the REPD register and substations. Defines 10 functions or classes, including module, map, fmt, safely, label. 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. Domain terms in the code: the REPD register, substations.
What it achieves
It is built from the module step (`module`), the map step (`map`) and the fmt step (`fmt`). GridAtlas V9.195 candidate: asset-first VICINITY focus. It responds to click, touchstart and touchend 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
module, map, fmt, safely, label, asset, render, navigate, install, sync
Defines here
module, map, fmt, safely, label, asset, render, navigate, install, sync
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 atlas/modules/202611242030-satnav-origin-focus.js:1-169 · blob 016d61536430e4d08b082d7c92713e219844532c · 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
/* GridAtlas V9.195 candidate: asset-first VICINITY focus.
 * Adds a single browseable source-backed asset card without changing the V9.194
 * engine, its 30/30/30 caps, 5/10/20 km calculations or the canonical MAP.
 * Layout Sandbox is closed and suppressed only while Project vicinity is active.
 */
(()=>{'use strict';
 const W=window,D=document,ROOT=D.documentElement;
 const module=()=>W.__GRIDATLAS_MODULES__?.ukOfftakers;
 const map=()=>W.__GRIDATLAS_V9_MAP__;
 const id='gridatlas-vicinity-focus-style';
 if(!D.getElementById(id)){
   const css=D.createElement('style');css.id=id;
   css.textContent=`html[data-vicinity-focus="on"] #gridatlas-sld-panel{display:none!important}
   [data-vicinity-focus-card]{border:1px solid #367078;border-radius:5px;background:#06151b;padding:10px;margin:7px 0;line-height:1.55;max-width:100%;box-sizing:border-box}
   [data-vicinity-focus-title]{font:600 15px/1.4 monospace;color:#c3f5f1;overflow-wrap:anywhere}
   [data-vicinity-focus-row]{display:flex;gap:8px;justify-content:space-between;border-bottom:1px solid #17383b;padding:4px 0;align-items:baseline}
   [data-vicinity-focus-row]>span:first-child{color:#9badb2;flex:0 0 34%}
   [data-vicinity-focus-row]>span:last-child{color:#e7f4ef;flex:1;text-align:right;overflow-wrap:anywhere}
   [data-vicinity-browse-toggle]{display:block;min-height:44px;width:100%;background:#07191f;color:#a6e9e3;border:1px solid #367078;border-radius:4px;margin:4px 0 8px;padding:8px;cursor:pointer;text-align:left;font:12px monospace}`;
   D.head.appendChild(css);
 }
 let active=null,observing=null,mapBound=null,shutdown=false;
 const fmt=n=>Number.isFinite(+n)?Number(n).toLocaleString('en-GB',{maximumFractionDigits:2}):'not stated';
 const safely=v=>v==null||v===''?'not stated':String(v).slice(0,200);
 const label=(p,txt,attr)=>{const e=D.createElement('div');if(attr)e.dataset[attr]='';e.textContent=txt;p.appendChild(e);return e};
 const asset=(card)=>{
   const s=card.swipe;if(!s)return null;
   if(card.__vicFocus?.origin){
     const p=card.r?.p||{};
     return{title:card.r?.n||'Selected REPD project',kind:p.repd_ref?'REPD project (origin)':'Chosen source point (origin)',
       source:p.repd_ref?'REPD source point; entrance and connection unverified':'Explicit '+(p.origin_kind||'map')+' point; no asset identity inferred',
       rows:[['Distance','0 km straight line (origin)'],[p.repd_ref?'REPD reference':'Asset identity',p.repd_ref?safely(p.repd_ref):'not asserted'],
         ['Technology',safely(p.technology)],['Registered capacity',p.capacity_mw>0?fmt(p.capacity_mw)+' MW':'MW not stated']],
       index:'origin',count:s.entries?.length||0};
   }
   if(!s.entries?.length)return null;
   const r=s.entries[s.index],position=s.entries.slice(0,s.index).filter(x=>x.tab===r.tab).length;
   const rows=[['Distance',fmt(r.km)+' km straight line']];
   let title=r.name,kind='Asset',source='',record;
   if(r.tab==='s'){
     kind='Substation';record=card.k?.[position];
     if(record){title=record.name||title;rows.push(['Voltage',fmt(record.kv)+' kV']);if(record.operator)rows.push(['Operator',safely(record.operator)]);}
     source='Map substation register / OpenStreetMap, ODbL';
   }else if(r.tab==='r'){
     kind='REPD project';record=card.P?.[position]?.parts?.[0];
     if(record){title=record.name||title;rows.push(['Technology',safely(record.raw_tech||record.tech)]);rows.push(['Status',safely(record.status)]);rows.push(['Registered capacity',record.capacity>0?fmt(record.capacity)+' MW':'MW not stated']);if(card.P[position].parts.length>1)rows.push(['Shared site',card.P[position].parts.length+' registered projects']);}
     source='REPD map register, DESNZ; exact-source details via existing REPD tab';
   }else if(r.tab==='v'){
     kind='Conventional power site';record=card.cv?.[position]?.q;
     if(record){title=record.n||title;rows.push(['Operator',safely(record.op)]);rows.push(['Fuel / technology',[record.f,record.te].filter(Boolean).join(' / ')||'not stated']);rows.push(['Status',safely(record.st)]);rows.push(['Installed capacity',record.mw>0?fmt(record.mw)+' MW':'MW not stated']);}
     source='Conventional power open register; see detailed source in existing tab';
   }
   return{title,kind,source,rows,index:s.index+1,count:s.entries.length};
 };
 function render(card){
   if(active!==card||!card.isConnected||!card.__vicFocus)return;
   const ui=card.__vicFocus,a=asset(card);
   const signature=a?JSON.stringify(a):'empty';
   if(ui.signature===signature)return;ui.signature=signature;
   const box=ui.box;box.textContent='';
   if(!a){label(box,'Loading nearby substations, REPD projects and power stations.','vicinityFocusTitle');return;}
   label(box,a.kind+' | '+a.index+' of '+a.count,'vicinityFocusKind');
   label(box,a.title,'vicinityFocusTitle').setAttribute('data-vicinity-focus-title','');
   for(const [key,value] of a.rows){const row=D.createElement('div');row.setAttribute('data-vicinity-focus-row','');const l=D.createElement('span'),v=D.createElement('span');l.textContent=key;v.textContent=safely(value);row.append(l,v);box.appendChild(row)}
   label(box,'Source: '+a.source,'vicinityFocusSource').style.cssText='padding-top:7px;color:#9aabb0;font-size:10px';
   label(box,'Screening only: proximity does not establish a grid connection, route, capacity or headroom.','vicinityFocusCaveat').style.cssText='padding-top:6px;color:#adc4c7;font-size:10px';
 }
 function navigate(card,type,rank){
   const s=card.swipe;if(!s||!s.entries?.length)return false;
   let count=0,target=-1;
   for(let i=0;i<s.entries.length;i++)if(s.entries[i].tab===type){if(count===rank){target=i;break;}count++}
   if(target<0)return false;
   card.__vicFocus.origin=false;s.label.style.visibility='';
   s.index=(target+s.entries.length-1)%s.entries.length;
   s.next.click();render(card);
   return true;
 }
 function install(card){
   if(card.__vicFocus)return;
   const s=card.swipe;if(!s)return;
   // Keep map and asset foreground; the old four tabs and full listings remain
   // available from the secondary Browse sets control.
   const nav=s.prev.parentElement;
   card.head.insertBefore(nav,card.tl);
   const panel=D.createElement('div');panel.setAttribute('data-vicinity-focus-card','');
   panel.setAttribute('role','group');panel.setAttribute('aria-label','Selected vicinity asset');
   card.head.insertBefore(panel,card.tl);
   const more=D.createElement('button');more.type='button';more.setAttribute('data-vicinity-browse-toggle','');more.textContent='Browse nearby sets and full records +';
   more.setAttribute('aria-expanded','false');card.head.insertBefore(more,card.tl);
   const groups=[card.tl,card.pn,card.csv];
   groups.forEach(g=>{g.style.display='none'});
   more.addEventListener('click',()=>{const open=more.getAttribute('aria-expanded')!=='true';more.setAttribute('aria-expanded',String(open));more.textContent=open?'Hide nearby sets -':'Browse nearby sets and full records +';groups.forEach(g=>g.style.display=open?'':'none')});
   card.d.open=false;card.d.querySelector('summary')?.setAttribute('title','Show 5/10/20 km area analysis');
   card.setAttribute('aria-label','Project vicinity asset browser');
   card.__vicFocus={box:panel,more,signature:null,origin:!s.marker};
   // The first card is always the clicked PipelineNews project; the 90
   // neighbouring locations start only after the first left/right movement.
   s.label.style.visibility=card.__vicFocus.origin?'hidden':'';
   for(const [button,direction] of [[s.next,1],[s.prev,-1]]){
     button.addEventListener('click',()=>{
       if(!card.__vicFocus?.origin||!s.entries.length)return;
       card.__vicFocus.origin=false;
       s.index=direction===1?s.entries.length-1:0;
       s.label.style.visibility='';
     },true);
   }
   let touchOrigin=null;
   card.addEventListener('touchstart',e=>{if(e.touches.length===1)touchOrigin={x:e.touches[0].clientX,y:e.touches[0].clientY}},{passive:true,capture:true});
   card.addEventListener('touchend',e=>{
     if(!card.__vicFocus?.origin||!s.entries.length||!touchOrigin||!e.changedTouches.length)return;
     const x=e.changedTouches[0].clientX-touchOrigin.x,y=e.changedTouches[0].clientY-touchOrigin.y;
     touchOrigin=null;
     if(Math.abs(x)>54&&Math.abs(x)>1.5*Math.abs(y)){
       card.__vicFocus.origin=false;
       s.index=x<0?s.entries.length-1:0;
       s.label.style.visibility='';
     }
   },{passive:true,capture:true});
   card.addEventListener('click',e=>{
     if(!card.__vicFocus||!card.isConnected)return;
     const row=e.target.closest('[data-offtakers-row]');
     if(!row||!card.contains(row)||!['s','r','v'].includes(card.tab))return;
     const rank=Number(row.dataset.offtakersRow);
     if(!Number.isInteger(rank)||rank<0)return;
     if(navigate(card,card.tab,rank)){e.preventDefault();e.stopImmediatePropagation();if(more.getAttribute('aria-expanded')==='true')more.click()}
   },true);
   const watch=new MutationObserver(()=>render(card));watch.observe(s.label,{childList:true,characterData:true,subtree:true});
   observing?.disconnect();observing=watch;
   render(card);
 }
 function sync(){
   if(shutdown)return;
   const card=module()?.state?.pp;
   const focused=!!(card?.project&&card.isConnected&&card.swipe);
   if(!focused){
     if(active){observing?.disconnect();observing=null;active=null}
     ROOT.removeAttribute('data-vicinity-focus');return;
   }
   ROOT.setAttribute('data-vicinity-focus','on');
   if(card!==active){
     active=card;
     // Stop the unrelated layout calculation panel taking over the screen.
     const close=D.querySelector('#gridatlas-sld-panel .sld-close');
     if(close)try{close.click()}catch(_){}
     install(card);
   }
   render(card);
   const m=map();
   if(m&&m!==mapBound&&typeof m.on==='function'){
     mapBound=m;
     m.on('click',e=>{
       const c=active;
       if(!c?.project||!c.isConnected)return;
       const layer='gridatlas-offtakers-neon-dc-node';
       try{
         if(!m.getLayer(layer))return;
         const features=m.queryRenderedFeatures(e.point,{layers:[layer]});
         const key=features?.[0]?.properties?.id;
         const hit=/^([srv])(\d+)$/.exec(String(key||''));
         if(hit){navigate(c,hit[1],Number(hit[2]));e.preventDefault?.()}
       }catch(_){}
     });
   }
 }
 const timer=setInterval(sync,250);
 D.addEventListener('visibilitychange',sync);
 W.addEventListener('pagehide',()=>{shutdown=true;clearInterval(timer);observing?.disconnect();ROOT.removeAttribute('data-vicinity-focus')},{once:true});
 sync();
})();