GLOBALGRID2050 / EXPLORE CODE

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

Regional Native and 3 more files

A JavaScript file in the atlas folder of GridAtlas that maps elizabeth line and london underground, using haversine and SHA-256, 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 541 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. SatNav Waypoint Map geodesy · gridatlas / atlas/modules/202611281800-satnav-waypoint-map.js lines 414–478
  2. Regional Card render · gridatlas / atlas/modules/202612012117-regional-card.js lines 1–73
  3. Regional Data storage · gridatlas / atlas/modules/202612012117-regional-data.js lines 1–164
  4. Regional Native geodesy · gridatlas / atlas/modules/202612012117-regional-native.js lines 1–398

SatNav Waypoint Map

A JavaScript file in the atlas folder of GridAtlas that refreshes guidance (`refreshGuidance`), sets pin (`setPin`) and restores local plan (`restoreLocalPlan`).

geodesygridatlas / atlas/modules/202611281800-satnav-waypoint-map.js · lines 414–478 of 478 · version 2026-11-28 18:00 (continued from section 540) · Not reached from any entry point (candidate for review) · pattern restoreLocalPlan (shared by 7 files)

What it does
It maps its content. Defines 25 functions or classes, including notify, updateText, distanceText, bearingText, collection. Side effects: changes the web page (DOM).
Why it exists in the grid workflow
Domain stage field_execution (path word 'satnav'): on-road and off-road field navigation to the farm gate (access gates, terrain slope, ground-bearing limits, electrical hazards), as Ventus Ltd describes its SatNav work.
What it achieves
It updates text (`updateText`), refreshes guidance (`refreshGuidance`) and sets pin (`setPin`). Based on the immutable PR113 compact map and GPS lifecycle. It responds to visibilitychange, offline and online 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
notify, updateText, distanceText, bearingText, collection, refreshGuidance, changePlan, edit, setPin, place, restoreLocalPlan, leaveExample
Defines here
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/202611281800-satnav-waypoint-map.js:414-478 · blob f965563e512aeb203ce5da6d3ef21c3cfa5d5aa5 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: field_execution · users: EPC_contractor, landowner_planner · canonical: unreached_review
  controls.stop.onclick = () => stopTracking('Location stopped');
  document.addEventListener('visibilitychange', () => {
    if (!document.hidden) resumedAt = Date.now();
    if (watch !== null) {
      setFix(null);
      notice = document.hidden ? 'GPS in background' : 'Waiting for a fresh GPS fix';
      render();
    }
  });
  window.addEventListener('offline', render);
  window.addEventListener('online', render);
  panel.addEventListener('keydown', event => {
    if (event.key === 'Escape') {picking = null; controls.editor.hidden = true; render();}
  });
  for (const element of [panel,access]) {
    for (const name of ['click','dblclick','mousedown','pointerdown','touchstart']) element.addEventListener(name, event => event.stopPropagation());
  }
  function refresh() {
    const host = document.fullscreenElement || document.webkitFullscreenElement || document.body;
    if (panel.parentElement !== host) host.append(panel,access);
    const next = window.__GRIDATLAS_V9_MAP__;
    if (next && next.getLayer('l-sat') && next !== map) {
      map?.off('click',mapClick);
      map = next;
      planDirty = positionDirty = true;
      map.on('click',mapClick);
      map.resize();
      notify('map',map);
    }
    if (fix && compass.fixQuality(fix) === 'stale') {setFix(null);notice = 'GPS fix is stale';}
    render();
  }
  panel.satnavSurvey = Object.freeze({
    getPins: () => snapshot.pins,
    getEndpoints: () => [roles.from ? snapshot.pins[0].coordinate : null, roles.to ? snapshot.pins.at(-1).coordinate : null],
    getMap: () => map,
    getFix: () => ['usable','poor'].includes(compass.fixQuality(fix)) ? fix : null,
    isTracking: () => watch !== null,
    maths,
    distanceKm: maths.distanceKm,
    fixQuality: compass.fixQuality,
    replacePlan,
    leaveExample,
    isExample: () => Boolean(localPlan),
    setDestination: at => { const changed = setPin('to', at); picking = null; render(); return changed; },
    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);
});

Regional Card

A JavaScript file in the atlas folder of GridAtlas covering transformers and substations, and uses data from UK Power Networks open data.

rendergridatlas / atlas/modules/202612012117-regional-card.js · lines 1–73 of 73 · version 2026-12-01 21:17 · Not reached from any entry point (candidate for review) · pattern augmentPopup (shared by 2 files)

What it does
It draws transformers and substations. Defines 6 functions or classes, including visible, augmentPopup, line, current, add. Side effects: changes the web page (DOM).
Why it exists in the grid workflow
Domain stage upstream_foresight (path word 'atlas'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: transformers, substations.
What it achieves
It is built from the visible step (`visible`), the augment popup helper (`augmentPopup`) and the line step (`line`). Interface-owned selected asset card. No menu mutation.
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
visible, augmentPopup, line, current, add, attach
Defines here
visible, augmentPopup, line, current, add, attach
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/202612012117-regional-card.js:1-73 · blob a3b904b4ff8f3c3126276a93b2e76fc2d1632350 · 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: unreached_review
/* Interface-owned selected asset card. No menu mutation. */
(() => {
  'use strict';
  const W=window, doc=W.document, ID='ukpn_secondary';
  const data=W.__GRIDATLAS_MODULES__?.ukpnSecondary;
  if(!data)throw Error('UKPN data adapter must load before card');
  let map=null;
  const visible=()=>map?.getLayer('l-'+ID) && map.getLayoutProperty('l-'+ID,'visibility')==='visible';
    function augmentPopup() {
      const popup=map?.getContainer().querySelector('.maplibregl-popup-content');
      if (!popup) return;
      const heading=popup.querySelector('b');
      if (!heading || !popup.textContent.includes('Secondary substation (transformer register)')) return;
      if (map.getZoom()<7 || !visible()) {W._closePopupKeepShape?.();return;}
      const feature=map.getSource('src-'+ID)?.serialize().data?.features?.find(f=>f.id===heading.textContent);
      if (!feature) return;
      let card=popup.querySelector('[data-ukpn-detail]');
      if (!card) {
        card=doc.createElement('section');card.dataset.ukpnDetail='1';
        card.style.cssText='font:12px/1.4 monospace;color:#ddd;background:#000;padding:6px;max-height:min(32vh,180px);overflow:auto;overflow-wrap:anywhere';
        card.setAttribute('aria-label','UKPN substation information');
        popup.appendChild(card);
      }
      const detailLevel=map.getZoom()>=16?'full':'summary';
      if (card.dataset.level===detailLevel && card.dataset.site===feature.id) return;
      card.dataset.level=detailLevel;card.dataset.site=feature.id;
      card.replaceChildren();
      const line=(label,value)=>{
        const item=doc.createElement('div');item.textContent=label+': '+(value??'Not supplied');card.appendChild(item);
      };
      const p=feature.properties;
      line('Transformer count',p.transformer_count);
      line('Location',feature.geometry.coordinates.map(v=>v.toFixed(6)).join(', ')+' (longitude, latitude)');
      if (detailLevel==='full') {
        const detailBox=doc.createElement('div');
        detailBox.textContent='Loading transformer records…';card.appendChild(detailBox);
        const current=()=>card.isConnected && card.dataset.level==='full' && card.dataset.site===feature.id && detailBox.isConnected && map.getZoom()>=16 && visible();
        data.detailsFor(feature.id).then(details=>{
          if(!current())return;
          if(new Set(details.map(row=>row[0])).size!==p.transformer_count)throw Error('UKPN transformer count mismatch');
          detailBox.replaceChildren();
          const add=(label,value)=>{const item=doc.createElement('div');item.textContent=label+': '+(value??'Not supplied');detailBox.appendChild(item);};
          const groups=new Map();
          for(const row of details){if(!groups.has(row[0]))groups.set(row[0],[]);groups.get(row[0]).push(row);}
          for(const [id,rows] of groups){
            add('Transformer FLOC',id);
            if(rows.length>1)add('Source records','Conflicting published values retained');
            for(const [,primary,secondary,rating,operating] of rows){
              add('Primary winding (source value)',primary);
              add('Secondary winding (source value)',secondary);
              add('ONAN rating (source value)',rating);
              add('Operating voltage (source value)',operating);
            }
          }
        }).catch(error=>{if(current())detailBox.textContent='Transformer details unavailable: '+String(error.message||error);});
      } else line('Transformer details','Zoom to 16 or higher');
      const credit=doc.createElement('a');
      credit.href='https://ukpowernetworks.opendatasoft.com/explore/assets/ukpn-secondary-site-transformers/';
      credit.target='_blank';credit.rel='noopener noreferrer';credit.style.color='#7eead0';
      credit.textContent='UK Power Networks · 27 Nov 2025 · CC BY 4.0';
      card.appendChild(credit);
      line('Interpretation','Installed ratings are not available capacity');
    }

  let frames=0;
  function attach(){
    map=W.__GRIDATLAS_V9_MAP__ || null;
    if(!map){if(++frames<1200)W.requestAnimationFrame(attach);return;}
    map.on('zoomend',augmentPopup);
    map.on('click',()=>W.setTimeout(augmentPopup,0));
  }
  attach();
})();

Regional Data

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/202612012117-regional-data.js · lines 1–164 of 164 · version 2026-12-01 21:17 · Not reached from any entry point (candidate for review) · pattern registerPinned (shared by 3 files)

What it does
It loads grid UKPN secondary, UKPN transformers and 11kV. Defines 9 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.
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
sharedDatabase, registerPinned, detailsFor, scalar, normalize, scalar, unpack, extend, load
Defines here
sharedDatabase, registerPinned, detailsFor, scalar, normalize, scalar, unpack, extend, load
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/202612012117-regional-data.js:1-164 · blob d3f8d03df8bee9e808e740abad46a17de24add6b · 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'}});
  };
  W.__GRIDATLAS_MODULES__ ||= {};
  W.__GRIDATLAS_MODULES__.ukpnSecondary = Object.freeze({normalize,unpack,extend,detailsFor,archive:ARCHIVE,sha256:SHA,source:SOURCE});
})();

Regional Native

A JavaScript file in the atlas folder of GridAtlas that maps elizabeth line and london underground, using haversine and SHA-256, 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). 99% 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.994 to gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 atlas/cartridges/202611180026-substation-intelligence-v9-63.js:1-8609 c6f9632fdb6e803baae03a54a542fe508431d153
  • sha256 6350426294d6ee73ee6b6475003b30b79be79ae5a1e4a5a15de1a780fe517ce0
  • 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/202612012117-regional-native.js · lines 1–398 of 8607 · version 2026-12-01 21:17 · Not reached from any entry point (candidate for review) · pattern regionalEligible (shared by 3 files)

What it does
It maps elizabeth line, london underground, UK metros trams and hs2. Defines 239 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.
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
No other file in the estate was found to import it.
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
none found
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/202612012117-regional-native.js:1-398 · blob e01079f148704c08dfda3ccf7ae8239e3d77a00a · 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: unreached_review
/**
 * 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;
        }