GLOBALGRID2050 / EXPLORE CODE

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

G203 Regional Native Viewport and 3 more files

A JavaScript file in the atlas folder of GridAtlas that maps elizabeth line and london underground, using haversine, and uses data from the ventus-grid-engine, data-federation-map-for-GlobalGrid2050-all-repos and spiders repositories.

700 lines of JavaScript from gridatlas, in 4 files. Topic: Maps, GIS and field navigation. Section 576 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. G203 03 Gps Camera Candidate geodesy · gridatlas / atlas/modules/g203-03-gps-camera-candidate.js lines 701–735
  2. G203 Compact Dock interaction · gridatlas / atlas/modules/g203-compact-dock.js lines 1–46
  3. G203 Regional Data Viewport storage · gridatlas / atlas/modules/g203-regional-data-viewport.js lines 1–219
  4. G203 Regional Native Viewport geodesy · gridatlas / atlas/modules/g203-regional-native-viewport.js lines 1–400

G203 03 Gps Camera Candidate

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`).

geodesygridatlas / atlas/modules/g203-03-gps-camera-candidate.js · lines 701–735 of 735 (continued from section 575) · 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 field_execution (path word 'gps'): 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: substations, 11kV, 33kV.
Inputs & outputs
Voltage levels named: 33kV, 11kV.
Downstream impact
Used directly by 1 file: G203 03 Gps Camera Test (gridatlas). Reached from 1 other entry point, including GridAtlas PR File Size Guard Workflow (gridatlas).
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
Checked by G203 03 Gps Camera Test.
Application
gridatlas · atlas/modules · script
Uses
none found
Used by
referenced by G203 03 Gps Camera Test (new URL import.meta.url)
Produces
setPanelOpen, notify, updateText, distanceText, bearingText, collection, cameraTarget, shouldAcceptCameraFix, pauseFollow, pauseGesture, refreshGuidance, changePlan
Defines here
none
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/g203-03-gps-camera-candidate.js:701-735 · blob e48c743713123f1c7d099641118d83aa4886286d · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: field_execution · users: EPC_contractor, landowner_planner · canonical: production_core
        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 !== 'ok') 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', () => {clearInterval(timer); stopTracking('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);
});

G203 Compact Dock

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

interactiongridatlas / atlas/modules/g203-compact-dock.js · lines 1–46 of 46 · Entry point · pattern ready (shared by 44 files)

What it does
It draws its content. Defines mount, ready. 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.
Downstream impact
Used directly by 1 file: GridAtlas PR File Size Guard Workflow (gridatlas).
What it achieves
G203-01: one native layout owner; original controls and listeners retained. It responds to satnav, pageshow and pagehide events.
Why it matters
Run by GridAtlas PR File Size Guard Workflow.
Application
gridatlas · atlas/modules · script
Uses
none found
Used by
run by GridAtlas PR File Size Guard Workflow (workflow run)
Produces
mount, ready
Defines here
mount, ready
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/g203-compact-dock.js:1-46 · blob 1670e7ea0f8aaff8d59d36067ccf537525ecd1ad · 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: production_core
/* G203-01: one native layout owner; original controls and listeners retained. */
(function(){
 'use strict';
 const D=document,W=window,R=D.documentElement;
 if(D.getElementById('g203-native-dock-style'))return;
 const css=D.createElement('style');css.id='g203-native-dock-style';
 css.textContent=`
 #g203-native-dock{position:fixed!important;left:max(8px,env(safe-area-inset-left,0px))!important;bottom:max(8px,env(safe-area-inset-bottom,0px))!important;top:auto!important;right:auto!important;z-index:10031!important;display:grid!important;grid-template-columns:repeat(4,minmax(44px,1fr));grid-template-rows:44px 44px;gap:4px;width:min(284px,calc(100vw - 16px - env(safe-area-inset-left,0px) - env  … [line shortened here: 450 characters; full line on GitHub]
 #g203-native-dock #gridatlas-mobile-tray{display:contents!important;position:static!important}
 #g203-native-dock :is(#satnav-toggle,#gridatlas-dash-toggle,#gridatlas-mobile-tray>button){position:static!important;inset:auto!important;float:none!important;transform:none!important;margin:0!important;box-sizing:border-box!important;width:100%!important;min-width:44px!important;max-width:none!important;height:44px!important;min-height:44px!important;padding:0 3px!important;font:600 11px/1 syste  … [line shortened here: 501 characters; full line on GitHub]
 #g203-native-dock #satnav-toggle{grid-area:2/1}
 #g203-native-dock #gridatlas-mobile-tray>button:nth-child(2){grid-area:2/2}
 #g203-native-dock #gridatlas-mobile-tray>button:nth-child(3){grid-area:2/3}
 #g203-native-dock #gridatlas-dash-toggle{grid-area:2/4}
 #g203-native-dock #gridatlas-mobile-tray>button:nth-child(1){grid-area:1/1}
 #g203-native-dock #gridatlas-mobile-tray>button:nth-child(4){grid-area:1/2}
 #g203-native-dock #gridatlas-mobile-tray>button:nth-child(5){grid-area:1/3}
 #g203-native-dock :is(#satnav-toggle,#gridatlas-dash-toggle,#gridatlas-mobile-tray>button:nth-child(2),#gridatlas-mobile-tray>button:nth-child(3)){font-size:0!important}
 #g203-native-dock :is(#satnav-toggle,#gridatlas-dash-toggle,#gridatlas-mobile-tray>button:nth-child(2),#gridatlas-mobile-tray>button:nth-child(3))::after{font:600 11px/1 system-ui,sans-serif}
 #g203-native-dock #satnav-toggle::after{content:'SATNAV'}
 #g203-native-dock #satnav-toggle[aria-expanded=true]::after{content:'SATNAV ▴'}
 #g203-native-dock #satnav-toggle[aria-label*="GPS active"]::after{content:'SATNAV •'}
 #g203-native-dock #gridatlas-mobile-tray>button:nth-child(2)::after{content:'GRID'}
 #g203-native-dock #gridatlas-mobile-tray>button:nth-child(3)::after{content:'SUBS'}
 #g203-native-dock #gridatlas-dash-toggle::after{content:'LAYERS'}
 html[data-g203-compact-dock]{--g203-dock-clearance:104px}
 `;
 D.head.append(css);
 const dock=D.createElement('div');dock.id='g203-native-dock';dock.setAttribute('role','group');dock.setAttribute('aria-label','GridAtlas map controls');
 function mount(){
   const host=D.fullscreenElement||D.webkitFullscreenElement||D.body;
   const toggle=D.getElementById('satnav-toggle'),tray=D.getElementById('gridatlas-mobile-tray'),layers=D.getElementById('gridatlas-dash-toggle');
   if(!host||!toggle||!tray||!layers)return false;
   if(dock.parentElement!==host)host.append(dock);
   for(const el of [toggle,tray,layers])if(el.parentElement!==dock)dock.append(el);
   for(const key of ['position','top','bottom','right','left','z-index','pointer-events','touch-action','min-height'])if(layers.style.getPropertyPriority(key)==='important')layers.style.removeProperty(key);
   layers.hidden=false;R.setAttribute('data-g203-compact-dock','');return true;
 }
 const ready=()=>{if(mount())observer.disconnect()};
 const observer=new MutationObserver(ready);
 if(!mount())observer.observe(D.documentElement,{childList:true,subtree:true});
 D.addEventListener('satnav:ready',ready);
 for(const event of ['fullscreenchange','webkitfullscreenchange'])D.addEventListener(event,mount);
 W.addEventListener('pageshow',mount);
 W.addEventListener('pagehide',()=>observer.disconnect(),{once:true});
}());

G203 Regional Data Viewport

A JavaScript file in the atlas folder of GridAtlas that reads grid UK Power Networks (UKPN) secondary, UKPN transformers and 11kV, using SHA-256 from the data-grid-GB repository.

storagegridatlas / atlas/modules/g203-regional-data-viewport.js · lines 1–219 of 219 · Not reached from any entry point (candidate for review) · pattern viewportBounds (shared by 2 files)

What it does
It loads grid UKPN secondary, UKPN transformers and 11kV. Defines 14 functions or classes, including sharedDatabase, registerPinned, detailsFor, scalar, normalize. Side effects: uses storage (browser storage, DuckDB or Parquet).
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: 11kV, 400kV.
Inputs & outputs
In: data source: data-grid-gb data; Parquet file grid_ukpn_secondary.parquet; Parquet file ukpn_transformers.parquet; DuckDB queries. Voltage levels named: 400kV, 11kV.
What it achieves
It registers pinned (`registerPinned`) and is built from the shared database helper (`sharedDatabase`) and the details for helper (`detailsFor`). Native `ukConfig` extension, pinned UKPN transformer archive. Its code works with 11 kV and 400 kV. It reads `grid_ukpn_secondary.parquet`.
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
sharedDatabase, registerPinned, detailsFor, scalar, normalize, scalar, unpack, extend, load, viewportBounds, outward, viewportSQL
Defines here
sharedDatabase, registerPinned, detailsFor, scalar, normalize, scalar, unpack, extend, load, viewportBounds, outward, viewportSQL, includesPoint, viewportFeatures
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/g203-regional-data-viewport.js:1-219 · blob d621ffe7b3fd36a9560ea0ecdacd752a4f95ef83 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: storage · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
/* Native ukConfig extension, pinned UKPN transformer archive. No synthetic data. */
(() => {
  'use strict';
  const W = window;
  const ID = 'ukpn_secondary', ROUTE = '/gridatlas/ukpn-secondary-sites.map-ready';
  const ARCHIVE = 'https://raw.githubusercontent.com/Ventusltd/data-grid-gb/2502549fed826106c70865047a540a170dd68919/ukpn-secondary/ukpn-secondary-site-transformers.zip';
  const SHA = 'c75933d86f4872a5f54712c0a945c283bb9038323a2ae9567df51ba3ce1b75c5';
  const SOURCE = 'UK Power Networks secondary site transformers';
  // Published, immutable Parquet derivatives; source ZIP remains the independent oracle.
  const DATA = 'https://raw.githubusercontent.com/Ventusltd/data-grid-gb/1fd3185a258f528768ca9137b721e6ec65ea3551/ukpn-secondary/202612010912/';
  const MAP_FILE = 'grid_ukpn_secondary.parquet', DETAIL_FILE = 'ukpn_transformers.parquet';
  const pins = {
    [MAP_FILE]: {bytes:870439,sha:'32cb071845049e6955421baa31d59799f5e4c8a24d07271cca01f3833f644991'},
    [DETAIL_FILE]: {bytes:3930813,sha:'3c55aeebd0a92cee6fc53d4a13a99de3faf431565832c4dce1e513599fcf0c7e'}
  };
  const metrics = W.__GRIDATLAS_UKPN_DATA__ = {mapRequests:0,detailRequests:0,mapMs:null,detailMs:null,mapRows:null,sharedRuntime:false};
  async function sharedDatabase() {
    // The immutable bridge starts the one page-wide runtime after 400 kV readiness.
    // Do not instantiate another worker or WASM heap here.
    const until=performance.now()+30000;
    while(!W.__GRIDATLAS_DUCKDB_RUNTIME__?.promise && performance.now()<until)
      await new Promise(resolve=>W.setTimeout(resolve,50));
    const held=W.__GRIDATLAS_DUCKDB_RUNTIME__;
    if(!held?.promise)throw Error('UKPN shared DuckDB runtime unavailable');
    const {database}=await held.promise;
    metrics.sharedRuntime=true;
    return database;
  }
  async function registerPinned(database,name) {
    const pin=pins[name];
    if(name===MAP_FILE)metrics.mapRequests++;else metrics.detailRequests++;
    const response=await previousFetch(DATA+name,{cache:'force-cache',redirect:'error',credentials:'omit',signal:AbortSignal.timeout(30000)});
    if(!response.ok)throw Error('UKPN Parquet HTTP '+response.status);
    const bytes=new Uint8Array(await response.arrayBuffer());
    const digest=[...new Uint8Array(await W.crypto.subtle.digest('SHA-256',bytes))].map(n=>n.toString(16).padStart(2,'0')).join('');
    if(bytes.byteLength!==pin.bytes||digest!==pin.sha)throw Error('UKPN Parquet integrity mismatch: '+name);
    await database.registerFileBuffer(name,bytes);
  }
  let registeredDetails=null;
  async function detailsFor(site) {
    const start=performance.now(), database=await sharedDatabase();
    // Only acquire the full transformer register after a real high-zoom card selection.
    // Query one exact FLOC; never add the entire register to MapLibre properties.
    registeredDetails ||= registerPinned(database,DETAIL_FILE).catch(error=>{registeredDetails=null;throw error;});
    await registeredDetails;
    const connection=await database.connect();
    try {
      const escaped=String(site).replaceAll("'","''");
      const table=await connection.query("SELECT feature_json FROM read_parquet('"+DETAIL_FILE+"') WHERE site_id = '"+escaped+"' ORDER BY source_row");
      const scalar=v=>typeof v==='number'&&Number.isFinite(v)||typeof v==='string'&&v.trim()?v:null;
      const distinct=new Map();
      for(const raw of table.toArray()){
        const row=typeof raw.toJSON==='function'?raw.toJSON():raw;
        const p=JSON.parse(String(row.feature_json)).properties;
        if(p.secondarysitefunctionallocation!==site)throw Error('UKPN detail identity mismatch');
        const detail=[p.transformerfunctionallocation,scalar(p.primarywinding),scalar(p.secondarywinding),scalar(p.onanrating),scalar(p.opvolts)];
        distinct.set(JSON.stringify(detail),detail);
      }
      metrics.detailMs=performance.now()-start;
      return [...distinct.values()];
    } finally {await connection.close();}
  }
  function normalize(raw) {
    if (raw?.type !== 'FeatureCollection' || raw.features?.length !== 74719)
      throw Error('UKPN source row count mismatch');
    const sites = new Map(), transformers = new Set();
    let points = 0;
    for (const f of raw.features) {
      const p = f.properties || {}, site = p.secondarysitefunctionallocation;
      if (typeof site !== 'string' || !site || typeof p.transformerfunctionallocation !== 'string' ||
          !['EPN','SPN','LPN'].includes(p.dno)) throw Error('UKPN identity invalid');
      transformers.add(p.transformerfunctionallocation);
      let s = sites.get(site);
      if (!s) {s = {site, dno:p.dno, coords:null, ids:new Set(), voltages:new Set(), details:new Map()}; sites.set(site,s);}
      if (s.dno !== p.dno) throw Error('UKPN conflicting network');
      s.ids.add(p.transformerfunctionallocation);
      // Retain distinct published values, not an arbitrary winner for duplicate FLOCs.
      const scalar=v=>typeof v==='number'&&Number.isFinite(v)||typeof v==='string'&&v.trim()?v:null;
      const detail=[p.transformerfunctionallocation,scalar(p.primarywinding),scalar(p.secondarywinding),scalar(p.onanrating),scalar(p.opvolts)];
      s.details.set(JSON.stringify(detail),detail);
      if (typeof p.primarywinding === 'number' && p.primarywinding > 0) s.voltages.add(p.primarywinding);
      if (f.geometry === null) continue;
      const c = f.geometry?.coordinates;
      if (f.geometry?.type !== 'Point' || !Array.isArray(c) || c.length !== 2 ||
          !c.every(Number.isFinite) || c[0] < -11 || c[0] > 3 || c[1] < 49.5 || c[1] > 61.5)
        throw Error('UKPN invalid point');
      points++;
      if (s.coords && (s.coords[0] !== c[0] || s.coords[1] !== c[1])) throw Error('UKPN conflicting site points');
      s.coords = c;
    }
    const features = [...sites.values()].filter(s=>s.coords).sort((a,b)=>a.site < b.site ? -1 : a.site > b.site ? 1 : 0).map(s=>({
      type:'Feature', id:s.site, geometry:{type:'Point',coordinates:s.coords},
      properties:{name:s.site, type:'Secondary substation (transformer register)', operator:'UK Power Networks ('+s.dno+')',
        voltage:[...s.voltages].sort((a,b)=>a-b).map(v=>v+' kV primary').join(', '),
        transformer_count:s.ids.size, ukpn_transformers:JSON.stringify([...s.details.values()]), source:'UK Power Networks secondary site transformers', asset_class:'secondary_substation'}
    }));
    if (sites.size !== 56309 || features.length !== 54558 || points !== 56685 || transformers.size !== 74712)
      throw Error('UKPN source closure mismatch');
    return {type:'FeatureCollection',features};
  }
  async function unpack(bytes) {
    const v = new DataView(bytes);
    if (bytes.byteLength !== 2068796 || v.getUint32(0,true) !== 0x04034b50 ||
        v.getUint16(6,true) !== 0 || v.getUint16(8,true) !== 8 ||
        v.getUint32(18,true) !== 2068618 || v.getUint32(22,true) !== 33070781)
      throw Error('UKPN archive structure mismatch');
    const start = 30 + v.getUint16(26,true) + v.getUint16(28,true);
    const stream = new Blob([bytes.slice(start,start+2068618)]).stream().pipeThrough(new DecompressionStream('deflate-raw'));
    const raw = await new Response(stream).arrayBuffer();
    if (raw.byteLength !== 33070781) throw Error('UKPN unpacked size mismatch');
    return normalize(JSON.parse(new TextDecoder().decode(raw)));
  }
  function extend(options) {
    if (!Array.isArray(options.config)) throw Error('GridAtlas ukConfig absent');
    if (options.config.flatMap(g=>g.layers).some(l=>l.id===ID)) return options;
    let found = false;
    const layer = {id:ID,label:'Secondary subs (UKPN)',color:'#35e6bb',type:'point',
      radius:['interpolate',['linear'],['zoom'],7,1,9,1.5,12,2.5,14,4,16,6,18,8],url:ROUTE,minzoom:7,acquireMinZoom:7,preload:false};
    const config = options.config.map(g=>{
      if (!g.layers.some(l=>l.id==='11kv')) return g;
      found=true; return {...g,layers:[...g.layers.map(l=>l.id==='11kv'?{...l,minzoom:7,acquireMinZoom:7,preload:false,label:'11 kV (OSM)',radius:['interpolate',['linear'],['zoom'],7,1,9,1.5,12,2.5,14,4,16,6,18,8]}:l),layer]};
    });
    if (!found) throw Error('GridAtlas UK topology group absent');
    return {...options,config};
  }
  const originalInit = W.initVentusMap;
  if (typeof originalInit !== 'function') throw Error('GridAtlas native init unavailable');
  W.initVentusMap = function(options) {return originalInit.call(this,extend(options));};
  const previousFetch = W.fetch.bind(W);
  let pending = null;
  async function load() {
    const started=performance.now(), database=await sharedDatabase();
    await registerPinned(database,MAP_FILE);
    let connection;
    try {
      connection=await database.connect();
      const table=await connection.query("SELECT feature_id, geometry_json, properties_json FROM read_parquet('"+MAP_FILE+"') ORDER BY feature_index");
      const features=table.toArray().map(raw=>{
        const row=typeof raw.toJSON==='function'?raw.toJSON():raw;
        const id=String(row.feature_id), geometry=JSON.parse(String(row.geometry_json)), properties=JSON.parse(String(row.properties_json));
        if(!id||properties.name!==id||geometry.type!=='Point'||!geometry.coordinates?.every(Number.isFinite))throw Error('UKPN map row invalid');
        return {type:'Feature',id,geometry,properties};
      });
      if(features.length!==54558||new Set(features.map(f=>f.id)).size!==54558)throw Error('UKPN map closure mismatch');
      metrics.mapRows=features.length;metrics.mapMs=performance.now()-started;
      return {type:'FeatureCollection',features};
    } finally {
      try {if(connection)await connection.close();} finally {await database.dropFile(MAP_FILE);}
    }
  }
  W.fetch = async function(input,init) {
    const url = new URL(typeof input==='string'?input:input.url||input.href,W.location.href);
    if (url.origin!==W.location.origin || url.pathname!==ROUTE) return previousFetch(input,init);
    if (init?.signal?.aborted) throw new DOMException('Aborted','AbortError');
    // Headers first, as in the streaming Parquet bridge; native hydrateLayer owns the UI.
    return new Response(new ReadableStream({start(controller){
      pending ||= load().finally(()=>{pending=null;});
      pending.then(fc=>{controller.enqueue(new TextEncoder().encode(JSON.stringify(fc)));controller.close();},
        error=>controller.error(error));
    }}),{headers:{'Content-Type':'application/geo+json','X-GridAtlas-Data-Plane':'PINNED_UKPN_PARQUET'}});
  };
  // G203: validated numeric viewport predicates; existing pinned Parquet only.
// G203-05: bounded query candidate for the existing pinned map parquet.
// Not wired to native hydration: the native source/cache lifecycle must be validated first.
// Numeric-only validated predicates; no invented coordinates, LIMIT or source replacement.
function viewportBounds(west,south,east,north,padding=0.15) {
  if (![west,south,east,north,padding].every(Number.isFinite) || south>north || south < -90 || north > 90 || padding<0 || padding>1) throw new RangeError('Invalid viewport');
  let width=east-west;
  if(width<0) width=((width%360)+360)%360;
  const latitudePad=(north-south)*padding;
  const lo=Math.max(-90,south-latitudePad), hi=Math.min(90,north+latitudePad);
  const padded=width*(1+2*padding);
  if(padded>=360) return {south:lo,north:hi,intervals:[[-180,180]]};
  const rawStart=west-width*padding;
  const start=rawStart>=-180&&rawStart<180?rawStart:(((rawStart+180)%360)+360)%360-180;
  const end=start+padded;
  // Round outward to avoid excluding boundary points through longitude wrapping.
  const outward=(a,z)=>[Math.max(-180,Math.floor((a-1e-12)*1e9)/1e9),Math.min(180,Math.ceil((z+1e-12)*1e9)/1e9)];
  return {south:lo,north:hi,intervals:end<=180?[outward(start,end)]:[outward(start,180),outward(-180,end-360)]};
}
function viewportSQL(west,south,east,north,padding=0.15) {
  const b=viewportBounds(west,south,east,north,padding);
  const lng=b.intervals.map(([a,z])=>`(lon BETWEEN ${a} AND ${z})`).join(' OR ');
  return `WITH points AS (SELECT feature_index, feature_id, geometry_json, properties_json,
  TRY_CAST(json_extract(geometry_json,'$.coordinates[0]') AS DOUBLE) AS lon,
  TRY_CAST(json_extract(geometry_json,'$.coordinates[1]') AS DOUBLE) AS lat
  FROM read_parquet('grid_ukpn_secondary.parquet'))
SELECT feature_id, geometry_json, properties_json FROM points
WHERE lat BETWEEN ${b.south} AND ${b.north} AND (${lng})
ORDER BY feature_index`;
}
function includesPoint(b,lon,lat) { return lat>=b.south && lat<=b.north && b.intervals.some(([a,z])=>lon>=a && lon<=z); }

  let registeredMap=null;
  async function viewportFeatures(west,south,east,north) {
    const started=performance.now(), database=await sharedDatabase();
    // Keep only the small compressed map file registered, not a global GeoJSON collection.
    registeredMap ||= registerPinned(database,MAP_FILE).catch(error=>{registeredMap=null;throw error;});
    await registeredMap;
    const connection=await database.connect();
    try {
      const bounds=viewportBounds(west,south,east,north);
      const table=await connection.query(viewportSQL(west,south,east,north));
      const features=[],seen=new Set();
      for(const raw of table.toArray()){
        const row=typeof raw.toJSON==='function'?raw.toJSON():raw;
        const id=String(row.feature_id),geometry=JSON.parse(String(row.geometry_json)),properties=JSON.parse(String(row.properties_json));
        if(!id||seen.has(id)||properties.name!==id||geometry.type!=='Point'||!geometry.coordinates?.every(Number.isFinite)||!includesPoint(bounds,...geometry.coordinates))throw Error('UKPN viewport row invalid');
        seen.add(id);features.push({type:'Feature',id,geometry,properties});
      }
      if(features.length>54558)throw Error('UKPN viewport row closure exceeded');
      metrics.mapRows=features.length;metrics.mapMs=performance.now()-started;
      metrics.viewportQueries=(metrics.viewportQueries||0)+1;metrics.maxViewportRows=Math.max(metrics.maxViewportRows||0,features.length);
      return features;
    } finally {await connection.close();}
  }
  W.__GRIDATLAS_MODULES__ ||= {};
  W.__GRIDATLAS_MODULES__.ukpnSecondary = Object.freeze({normalize,unpack,extend,detailsFor,viewportFeatures,archive:ARCHIVE,sha256:SHA,source:SOURCE});
})();

G203 Regional Native Viewport

A JavaScript file in the atlas folder of GridAtlas that maps elizabeth line and london underground, using haversine, and uses data from the ventus-grid-engine, data-federation-map-for-GlobalGrid2050-all-repos and spiders repositories.

Set aside from the main view: 99% of its lines are the same as atlas/cartridges/202611180026-substation-intelligence-v9-63.js (gridatlas), which stays. (near-copy-of, proposed by families.py). 98% of lines shared with Substation Intelligence V9 63; read that one first. All set-aside files, with reasons. Nothing was deleted.

Evidence
  • line-jaccard 0.987 to gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 atlas/cartridges/202611180026-substation-intelligence-v9-63.js:1-8609 c6f9632fdb6e803baae03a54a542fe508431d153
  • sha256 7645828021ee561333c34c0ecaad2b46bd87029ca9101601714d7e520bb680b1
  • target sha256 88c538b97bf426776cda436151741f17500a2136867d28362407550d72f9038f
  • group of 4 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines

geodesygridatlas / atlas/modules/g203-regional-native-viewport.js · lines 1–400 of 8664 · pattern regionalEligible (shared by 3 files)

What it does
It maps elizabeth line, london underground, UK metros trams and hs2. Defines 241 functions or classes, including deepFreeze, escapeHTML, normalizeStatus, fmt, haversine. Side effects: changes the web page (DOM); makes network requests.
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: 750kV, 400kV, 275kV, 132kV, 66kV, 33kV.
Inputs & outputs
In: data source: ventus-grid-engine data; data source: data-federation-map-for-globalgrid2050-all-repos data; data source: spiders data; data source: npm data; GeoJSON file elizabeth_line.geojson; GeoJSON file london_underground.geojson; GeoJSON file uk_metros_trams.geojson; GeoJSON file hs2.geojson. Out: downloaded file gridatlas-; downloaded file globalgrid2050-grid-atlas-; interactive map; canvas drawing; SVG drawing. Voltage levels named: 750kV, 400kV, 275kV, 132kV, 66kV, 33kV, 11kV.
Downstream impact
Used directly by 1 file: G203 Swarm 06 Viewport Lifecycle Test (gridatlas). Reached from 1 other entry point, including GridAtlas PR File Size Guard Workflow (gridatlas).
What it achieves
It normalizes status (`normalizeStatus`), toggles zone draw mode (`toggleZoneDrawMode`) and opens popup (`openPopup`). ASSEMBLED by `tools/build-cartridge.mjs` from the parts below. Its code works with 400 kV, 100 MVA and 132 kV. It responds to fullscreenchange, webkitfullscreenchange and click events.
Why it matters
Checked by G203 Swarm 06 Viewport Lifecycle Test.
Application
gridatlas · atlas/modules · script
VEDIC
SNAP LINE ENDS TO SUBSTATIONS (GG2050-VEDIC-000106): GridAtlas / Substations · Geospatial data processing. line_features, substation_point_features → Line features whose first and last vertices are moved onto the nearest substation point within tolerance; other geometry unchanged.
VEDIC
MEASURE (GG2050-VEDIC-000001): GridAtlas / Geodesy · Mathematics / Spherical geometry. coordinate_pair, coordinate_pair → distance_km
VEDIC
REPRESENT (GG2050-VEDIC-000002): GridAtlas / Geodesy · Computer science / Geometry processing. geojson_geometry → coordinate_pair_or_null
Uses
Spider Full Po Test (estate URL), Data — Grid Studies Public Page (estate URL)
Used by
referenced by G203 Swarm 06 Viewport Lifecycle Test (new URL import.meta.url)
Produces
deepFreeze, escapeHTML, normalizeStatus, fmt, haversine, _zoneDrawGetRadius, _zoneDrawCirclePoints, _zoneDrawCalcArea, _zoneDrawUpdateLayers, _zoneDrawShowPopup, _zoneDrawShowPopupDebounced, _zoneDrawClear
Defines here
deepFreeze, escapeHTML, normalizeStatus, fmt, haversine, _zoneDrawGetRadius, _zoneDrawCirclePoints, _zoneDrawCalcArea, _zoneDrawUpdateLayers, _zoneDrawShowPopup, _zoneDrawShowPopupDebounced, _zoneDrawClear, zoneDrawUndo, toggleZoneDrawMode, _zoneDrawNearVertex, _zoneDrawEdgeDots, _zoneDrawNearEdgeDot, _zoneDrawOnClick, _zoneDrawOnMouseDown, _zoneDrawOnMouseMove
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/g203-regional-native-viewport.js:1-400 · blob 013cf98a02bb6c09199c357ac96a2b588892c0f4 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, network · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
/**
 * substation-intelligence-v9-63, generation 202609060259 (UTC).
 *
 * ASSEMBLED by tools/build-cartridge.mjs from the parts below. Do not edit
 * this file: edit a part and rebuild under a new generation. Each part is
 * hashed in manifests/202609060259-substation-intelligence-v9-63-parts.json.
 *
 *   carried_shell_script   atlas/parts/202609060254-ventus-corev8engine-polyzone-grabbable.js
 *   module                 atlas/modules/202609011950-geodesy.js
 *   module                 atlas/modules/202609012245-network-topology.js
 *   module                 atlas/modules/202609012245-electrical-distance.js
 *   module                 atlas/modules/202609012250-rating-envelope.js
 *   module                 atlas/modules/202609020015-injection-response.js
 *   module                 atlas/modules/202609012345-planned-change.js
 *   module                 atlas/modules/202609012350-owner-boundary.js
 *   module                 atlas/modules/202609030137-pinned-products.js
 *   module                 atlas/modules/202609030157-version-ledger.js
 *   module                 atlas/modules/202609030205-corridor-estimate.js
 *   module                 atlas/modules/202609031958-menu-bar.js
 *   module                 atlas/modules/202609032220-arrival-tidy.js
 *   module                 atlas/modules/202609030048-pipeline-news-layers.js
 *   module                 atlas/modules/202609040400-sld-styles.js
 *   module                 atlas/modules/202609051624-teleprint-controls.js
 *   part                   atlas/parts/202609012350-substation-intelligence-body.js
 */

'use strict';

window.initVentusMap = function({ config, center, zoom }) {
    if (typeof maplibregl === 'undefined') {
        document.getElementById('fatal-banner').style.display = 'block';
        throw new Error('CRITICAL: MapLibre failed to load.');
    }

    // ── Utilities ────────────────────────────────────────────────────────────────
    function deepFreeze(obj) {
        Object.keys(obj).forEach(prop => {
            if (typeof obj[prop] === 'object' && obj[prop] !== null) deepFreeze(obj[prop]);
        });
        return Object.freeze(obj);
    }

    function escapeHTML(value) {
        return String(value ?? '')
            .replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
            .replace(/"/g, '&quot;').replace(/'/g, '&#39;');
    }

    function normalizeStatus(status) {
        return String(status ?? '').trim().toLowerCase();
    }

    function fmt(n, decimals) {
        return n.toLocaleString('en-GB', { maximumFractionDigits: decimals, minimumFractionDigits: decimals });
    }

    // ── Earth model ───────────────────────────────────────────────────────────────
    const EARTH_RADIUS_KM = 6378.137;
    const MAX_RADIUS_KM   = Math.PI * EARTH_RADIUS_KM; // 20037.508 km

    // ── V5.1: Named constants ────────────────────────────────────────────────────
    const DEG_TO_RAD          = Math.PI / 180;
    const HIT_RADIUS_VERTEX_PX = 22;   
    const HIT_RADIUS_EDGE_PX   = 16;   
    /* How much clear screen space an add-a-point dot needs beyond a corner's
       own grab radius before it is allowed to exist on that edge. */
    const EDGE_DOT_CLEARANCE_PX = 10;  
    const CLICK_DEBOUNCE_MS    = 220;  
    const HOVER_THROTTLE_MS    = 100;  
    const POPUP_MAX_WIDTH      = '300px';
    const ZONE_DRAW_VERTICES   = 24;   
    const ZONE_DRAW_DEFAULT_KM = 0.337; 

    function haversine(lon1, lat1, lon2, lat2) {
        const R = EARTH_RADIUS_KM, r = Math.PI / 180;
        const dLat = (lat2 - lat1) * r, dLon = (lon2 - lon1) * r;
        const a = Math.sin(dLat / 2) ** 2 + Math.cos(lat1 * r) * Math.cos(lat2 * r) * Math.sin(dLon / 2) ** 2;
        return R * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    }

    // ── Config Loading ────────────────────────────────────────────────────────────
    const GRID_CONFIG = deepFreeze(config);
    const RUNTIME_STATE = {};
    GRID_CONFIG.forEach(group => {
        group.layers.forEach(layer => {
            RUNTIME_STATE[layer.id] = { status: 'WAIT', loading: false, loaded: false };
        });
    });

    const layerConfigById = new Map(
        GRID_CONFIG.flatMap(g => g.layers).map(l => [l.id, l])
    );

    // Removed naei_co2 from here so it gets its own dedicated source
    const REPD_IDS    = ['solar','solar_operational','solar_roof','wind','wind_onshore_operational','wind_offshore_operational','bess','bess_operational','biomass','tidal','hydrogen','hydro','flywheel','act','geothermal','caes'];
    const TRANSIT_IDS = ['elizabeth','lu','dlr','metro','tram','hs2'];
    const TRANSIT_SOURCE_MAP = { 'elizabeth':'src-elizabeth','lu':'src-lu','dlr':'src-metros','metro':'src-metros','tram':'src-metros','hs2':'src-hs2' };
    const TRANSIT_URLS = { 'src-elizabeth':'/elizabeth_line.geojson','src-lu':'/london_underground.geojson','src-metros':'/uk_metros_trams.geojson','src-hs2':'/hs2.geojson' };

    const SEARCH_THRESHOLD = {
        'solar':50,'solar_roof':0.5,'wind':50,'bess':50,'biomass':50,
        'tidal':10,'hydrogen':10,'hydro':10,'flywheel':1,'act':10,'geothermal':1,'caes':1
    };

    const TECH_TERMS = new Map([
        ['solar','solar farm'],['solar_roof','rooftop solar'],['wind','wind farm'],
        ['bess','battery storage'],['biomass','biomass plant'],['tidal','tidal energy'],
        ['hydrogen','hydrogen plant'],['hydro','hydro power'],['flywheel','flywheel storage'],
        ['act','advanced conversion energy'],['geothermal','geothermal energy'],['caes','compressed air energy storage']
    ]);

    const TECH_COLOURS = new Map([
        ['solar','#ffff00'],['solar_roof','#ffcc00'],['wind','#00ffff'],['bess','#ffae00'],
        ['biomass','#39ff14'],['tidal','#00bfff'],['hydrogen','#ffffff'],['hydro','#00aaff'],
        ['flywheel','#ff69b4'],['act','#ff6600'],['geothermal','#ff3300'],['caes','#88aaff']
    ]);

    const STATUS_COLOURS = {
        'operational':'#00ff88','under construction':'#ffcc00','awaiting construction':'#ffaa00',
        'consented':'#ff8800','planning permission granted':'#ff8800','planning approved':'#ff8800',
        'application submitted':'#8888ff','pre-construction':'#aaaaff'
    };

    let statusMode  = false;
    let radiusMode  = false;
    let radiusMarker  = null;
    let radiusCenter  = null;
    
    let radiusAreaMode = false;
    let radiusAreaMarker = null;
    let radiusAreaCenter = null;

    // ── ZONE DRAW STATE ───────────────────────────────────────────────────────────
    const ZONE_DRAW_MAX_KM      = MAX_RADIUS_KM;
    let zoneDrawMode      = false;
    let zoneDrawPoints    = [];   
    let zoneDrawDragging  = false;
    let zoneDrawDragIdx   = -1;
    let zoneDrawJustDragged = false;
    let _zoneDrawCollapsed = false;

    function _zoneDrawGetRadius() {
        const input = document.getElementById('zonedraw-radius-input');
        if (!input) return ZONE_DRAW_DEFAULT_KM;
        const v = parseFloat(input.value);
        if (isNaN(v) || v <= 0) return ZONE_DRAW_DEFAULT_KM;
        if (v > ZONE_DRAW_MAX_KM) return ZONE_DRAW_MAX_KM;
        return v;
    }

    function _zoneDrawCirclePoints(lon, lat, radiusKm, n) {
        const R = EARTH_RADIUS_KM, DEG = Math.PI / 180;
        const ad = radiusKm / R;
        const lat1 = lat * DEG;
        return Array.from({ length: n }, (_, i) => {
            const b = (i / n) * 2 * Math.PI;
            const lat2 = Math.asin(Math.sin(lat1) * Math.cos(ad) + Math.cos(lat1) * Math.sin(ad) * Math.cos(b));
            const lon2 = lon * DEG + Math.atan2(Math.sin(b) * Math.sin(ad) * Math.cos(lat1), Math.cos(ad) - Math.sin(lat1) * Math.sin(lat2));
            return [lon2 / DEG, lat2 / DEG];
        });
    }

    function _zoneDrawCalcArea(pts) {
        if (pts.length < 3) return { areaKm2: 0, areaHa: 0, areaAc: 0, areaMi2: 0, areaM2: 0, perimKm: 0, pitches: 0 };
        let area = 0;
        const R = EARTH_RADIUS_KM;
        for (let i = 0; i < pts.length; i++) {
            const j  = (i + 1) % pts.length;
            const xi = pts[i][0] * Math.PI / 180, yi = pts[i][1] * Math.PI / 180;
            const xj = pts[j][0] * Math.PI / 180, yj = pts[j][1] * Math.PI / 180;
            area += (xj - xi) * (2 + Math.sin(yi) + Math.sin(yj));
        }
        const areaKm2 = Math.abs(area) * R * R / 2;
        let perimKm = 0;
        for (let i = 0; i < pts.length; i++) perimKm += haversine(pts[i][0], pts[i][1], pts[(i+1)%pts.length][0], pts[(i+1)%pts.length][1]);
        const areaM2 = areaKm2 * 1e6;
        return { areaKm2, areaHa: areaM2 / 10000, areaAc: areaM2 / 4046.85642, areaMi2: areaKm2 * 0.386102, areaM2, perimKm, pitches: areaM2 / 7140 };
    }

    function _zoneDrawUpdateLayers(dragOnly) {
        if (!map.getSource('src-zonedraw-fill')) return;
        const n = zoneDrawPoints.length;
        if (n < 3) {
            ['fill','line','points'].forEach(s => map.getSource(`src-zonedraw-${s}`).setData({ type: 'FeatureCollection', features: [] }));
            return;
        }
        const ring = [...zoneDrawPoints, zoneDrawPoints[0]];
        map.getSource('src-zonedraw-fill').setData({ type: 'FeatureCollection', features: [{ type: 'Feature', geometry: { type: 'Polygon', coordinates: [ring] } }] });
        map.getSource('src-zonedraw-line').setData({ type: 'FeatureCollection', features: [{ type: 'Feature', geometry: { type: 'LineString', coordinates: ring } }] });
        if (dragOnly) {
            map.getSource('src-zonedraw-points').setData({ type: 'FeatureCollection', features:
                zoneDrawPoints.map((c, i) => ({ type: 'Feature', properties: { kind: 'vertex', idx: i }, geometry: { type: 'Point', coordinates: c } }))
            });
        } else {
            const vFeatures = zoneDrawPoints.map((c, i) => ({ type: 'Feature', properties: { kind: 'vertex', idx: i }, geometry: { type: 'Point', coordinates: c } }));
            const mFeatures = [];
            zoneDrawPoints.forEach((c, i) => {
                /* Same rule as the hit test, so a dot is never drawn where it
                   cannot be pressed and never pressable where it is not drawn. */
                _zoneDrawEdgeDots(i).forEach(d => {
                    mFeatures.push({ type: 'Feature', properties: { kind: 'mid', edgeIdx: i, t: d.t }, geometry: { type: 'Point', coordinates: d.dot } });
                });
            });
            map.getSource('src-zonedraw-points').setData({ type: 'FeatureCollection', features: [...vFeatures, ...mFeatures] });
        }
    }

    let _zoneDrawPopupRaf = null;

    function _zoneDrawShowPopup() {
        if (zoneDrawPoints.length < 3) return;
        const { areaKm2, areaHa, areaAc, areaMi2, areaM2, perimKm, pitches } = _zoneDrawCalcArea(zoneDrawPoints);
        const centLon = zoneDrawPoints.reduce((s, p) => s + p[0], 0) / zoneDrawPoints.length;
        const centLat = zoneDrawPoints.reduce((s, p) => s + p[1], 0) / zoneDrawPoints.length;
        if (_zoneDrawCollapsed) {
            openPopup([centLon, centLat], `
                <div onclick="window._zdExpand&&window._zdExpand()" style="font-family:monospace;background:#000;padding:5px 10px;border:1px solid #ff6600;border-radius:4px;cursor:pointer;color:#ff6600;font-size:11px;white-space:nowrap;">
                    ◉ ${fmt(areaKm2,3)} km² · ⚽ ${fmt(pitches,0)} pitches &nbsp;▾
                </div>`);
            window._zdExpand = () => { _zoneDrawCollapsed = false; _zoneDrawShowPopup(); };
        } else {
            openPopup([centLon, centLat], `
                <div style="font-family:monospace;background:#000;padding:10px 12px;border:1px solid #ff6600;border-radius:4px;min-width:230px;">
                    <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:8px;">
                        <b style="color:#ff6600;font-size:13px;">◉ Zone Draw</b>
                        <span onclick="window._zdCollapse&&window._zdCollapse()" style="color:#555;font-size:12px;cursor:pointer;padding:0 4px;user-select:none;" title="Collapse">▴ hide</span>
                    </div>
                    <div style="color:#ffae00;font-size:13px;margin-bottom:10px;">⚽ ${fmt(pitches,1)} football pitches</div>
                    <div style="display:grid;grid-template-columns:auto 1fr;gap:4px 14px;font-size:12px;">
                        <span style="color:#888;">Square Metres</span><span style="color:#fff;">${fmt(areaM2,0)}</span>
                        <span style="color:#888;">Hectares</span><span style="color:#fff;">${fmt(areaHa,2)}</span>
                        <span style="color:#888;">Acres</span><span style="color:#fff;">${fmt(areaAc,2)}</span>
                        <span style="color:#888;">Square Kilometres</span><span style="color:#fff;">${fmt(areaKm2,4)}</span>
                        <span style="color:#888;">Square Miles</span><span style="color:#fff;">${fmt(areaMi2,3)}</span>
                        <span style="color:#888;">Perimeter</span><span style="color:#fff;">${fmt(perimKm,2)} km</span>
                    </div>
                    <div style="color:#555;font-size:10px;margin-top:8px;line-height:1.4;">
                        <b style="color:#ff6600;">HOW TO USE:</b><br>
                        • <b>Drag orange dots</b> to reshape polygon<br>
                        • <b>Click light dots</b> on edges to add points<br>
                        • <b>Undo button</b> in top-left removes last point<br>
                        • <b>Click elsewhere</b> to start new zone
                    </div>
                </div>`);
            window._zdCollapse = () => { _zoneDrawCollapsed = true; _zoneDrawShowPopup(); };
        }
    }

    function _zoneDrawShowPopupDebounced() {
        if (_zoneDrawPopupRaf) return;
        _zoneDrawPopupRaf = requestAnimationFrame(() => { _zoneDrawPopupRaf = null; _zoneDrawShowPopup(); });
    }

    function _zoneDrawClear() {
        zoneDrawPoints    = [];
        zoneDrawDragging  = false;
        zoneDrawDragIdx   = -1;
        zoneDrawJustDragged = false;
        _zoneDrawCollapsed  = false;
        window._zdExpand    = null;
        window._zdCollapse  = null;
        closeActivePopup();
        _zoneDrawUpdateLayers(false);
        const el = document.getElementById('zonedraw-display');
        if (el) el.style.display = 'none';
    }

    function zoneDrawUndo() {
        if (zoneDrawPoints.length <= 3) { _zoneDrawClear(); return; }
        zoneDrawPoints.pop();
        _zoneDrawUpdateLayers(false);
        _zoneDrawShowPopup();
    }

    function toggleZoneDrawMode() {
        zoneDrawMode = !zoneDrawMode;
        const btn = document.getElementById('btn-zonedraw');
        if (btn) { btn.classList.toggle('active', zoneDrawMode); btn.setAttribute('aria-pressed', zoneDrawMode); }
        map.getCanvas().style.cursor = zoneDrawMode ? 'crosshair' : '';
        if (zoneDrawMode) {
            if (radiusMode)     toggleRadiusMode();
            if (radiusAreaMode) toggleRadiusAreaMode();
            if (measureMode)    toggleMeasureMode();
            const el = document.getElementById('zonedraw-display');
            if (el) el.style.display = 'block';
        } else {
            _zoneDrawClear();
        }
    }

    function _zoneDrawNearVertex(px) {
        for (let i = 0; i < zoneDrawPoints.length; i++) {
            const vpx = map.project(zoneDrawPoints[i]);
            const dx = px.x - vpx.x, dy = px.y - vpx.y;
            if (Math.sqrt(dx*dx + dy*dy) < HIT_RADIUS_VERTEX_PX) return i;
        }
        return -1;
    }

    /* An edge is only long enough to carry add-a-point dots when its ends are
       far enough apart on screen. A 24-gon zoomed out puts three dots inside
       the corner's own hit radius, so the dots crowd out the corners and the
       polygon becomes uneditable. One rule, used by both the hit test and the
       drawing, so what you can press is always what you can see. */
    function _zoneDrawEdgeDots(i) {
        const j = (i + 1) % zoneDrawPoints.length;
        const a = zoneDrawPoints[i], b = zoneDrawPoints[j];
        const apx = map.project(a), bpx = map.project(b);
        const lenPx = Math.hypot(bpx.x - apx.x, bpx.y - apx.y);
        const clearance = HIT_RADIUS_VERTEX_PX + EDGE_DOT_CLEARANCE_PX;
        const out = [];
        for (const t of [0.33, 0.5, 0.66]) {
            if (t * lenPx < clearance || (1 - t) * lenPx < clearance) continue;
            out.push({ insertIdx: j, t, dot: [a[0]+(b[0]-a[0])*t, a[1]+(b[1]-a[1])*t] });
        }
        return out;
    }

    function _zoneDrawNearEdgeDot(px) {
        for (let i = 0; i < zoneDrawPoints.length; i++) {
            for (const d of _zoneDrawEdgeDots(i)) {
                const dpx = map.project(d.dot);
                const dx = px.x - dpx.x, dy = px.y - dpx.y;
                if (Math.sqrt(dx*dx + dy*dy) < HIT_RADIUS_EDGE_PX) return { insertIdx: d.insertIdx, dot: d.dot };
            }
        }
        return null;
    }

    function _zoneDrawOnClick(e) {
        if (zoneDrawDragging) return;
        if (zoneDrawJustDragged) { zoneDrawJustDragged = false; return; }
        const lon = e.lngLat.lng, lat = e.lngLat.lat;

        if (zoneDrawPoints.length === 0) {
            const km = _zoneDrawGetRadius();
            zoneDrawPoints = _zoneDrawCirclePoints(lon, lat, km, ZONE_DRAW_VERTICES);
            _zoneDrawCollapsed = false;

            const mpp = (km * 2000) / (window.innerWidth * 0.6);
            const lat1 = lat * Math.PI / 180;
            const targetZoom = Math.log2(156543 * Math.cos(lat1) / mpp);
            const clampedZoom = Math.max(8, Math.min(19, targetZoom));
            map.easeTo({ center: [lon, lat], zoom: clampedZoom, duration: 600 });

            _zoneDrawUpdateLayers(false); _zoneDrawShowPopup();
            return;
        }

        const px = map.project([lon, lat]);
        if (_zoneDrawNearVertex(px) >= 0) return;

        const edgeHit = _zoneDrawNearEdgeDot(px);
        if (edgeHit) {
            zoneDrawPoints.splice(edgeHit.insertIdx, 0, [edgeHit.dot[0], edgeHit.dot[1]]);
            _zoneDrawUpdateLayers(false); _zoneDrawShowPopup();
            return;
        }

        const km = _zoneDrawGetRadius();
        zoneDrawPoints = _zoneDrawCirclePoints(lon, lat, km, ZONE_DRAW_VERTICES);
        _zoneDrawCollapsed = false;
        const mpp = (km * 2000) / (window.innerWidth * 0.6);
        const lat1 = lat * Math.PI / 180;
        const targetZoom = Math.log2(156543 * Math.cos(lat1) / mpp);
        map.easeTo({ center: [lon, lat], zoom: Math.max(8, Math.min(19, targetZoom)), duration: 600 });
        _zoneDrawUpdateLayers(false); _zoneDrawShowPopup();
    }

    function _zoneDrawOnMouseDown(e) {
        if (!zoneDrawMode || zoneDrawPoints.length < 3) return;
        const px = map.project(e.lngLat);
        /* A CORNER ALWAYS WINS A PRESS.
           This used to test the edge dot first and return, while the hover
           handler tested the vertex first. So the cursor promised a grab and
           the press silently refused, which is what "cannot select the elastic
           bands" was. Measured on the live map at Cleve Hill: at the drawn zoom
           the nearest midpoint sits 57.7 px from a corner and all 24 corners
           drag; two zoom steps out it sits 14.4 px away and none of them do.
           Hover and press now ask the same question in the same order. */
        const vi = _zoneDrawNearVertex(px);
        if (vi < 0 && _zoneDrawNearEdgeDot(px)) return;
        if (vi >= 0) {
            zoneDrawDragging = true; zoneDrawDragIdx = vi;
            map.dragPan.disable();
            map.getCanvas().style.cursor = 'grabbing';
            e.preventDefault();
        }
    }

    function _zoneDrawOnMouseMove(e) {
        if (!zoneDrawMode || zoneDrawPoints.length < 3) return;
        if (zoneDrawDragging && zoneDrawDragIdx >= 0) {
            zoneDrawPoints[zoneDrawDragIdx] = [e.lngLat.lng, e.lngLat.lat];
            _zoneDrawUpdateLayers(true);
            _zoneDrawShowPopupDebounced();
            return;
        }
        const px = map.project(e.lngLat);
        const vi = _zoneDrawNearVertex(px);