GLOBALGRID2050 / EXPLORE CODE

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

G203 Regional Native Viewport (part 9)

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 1 file. Topic: Maps, GIS and field navigation. Section 585 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 Regional Native Viewport geodesy · gridatlas / atlas/modules/g203-regional-native-viewport.js lines 6001–6700

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 6001–6700 of 8664 (continued from section 576) · 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
install, loudFailure, start, tidy, retire, watch, note, readRegisterSource, primeRegister, loadRegister, readSelection, near, collection, setSourceData, ensureLayers, escapeHtml, setVisibility, labelFor, paintLabels, refresh, buildGroup
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:6001-6700 · 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
    move(panels.Scope, doc.getElementById('btn-gridpoint'));

    var disclaimer = doc.querySelector('.disclaimer-box');
    var shoutout = doc.querySelector('.podcast-shoutout');
    move(panels.About, disclaimer);
    move(panels.About, shoutout);

    state.estate_links = appendEstateLinks(panels.About);
    appendEngineModules(panels.File);
    state.export_controls = appendExport(panels.File, doc);
    state.studies = appendStudies(panels.View);

    /* The map attribution moves off the map and into About, LAST, in small
       print.
       ----------------------------------------------------------------------
       Measured live at generation 202609042123, 2026-09-05: .custom-map-attrib
       rendered at x=15 y=47, 401x24 px -- a boxed band immediately under the
       menu bar, over the top-left of the map, which is where a reader arriving
       on a deep link looks first. On a 393x852 phone it wrapped to two lines
       and the architect photographed the consequence: opening EDIT drew
       "Status Colours" UNDERNEATH the attribution box, the two overlapping in
       the same space. His instruction, verbatim: "Attribution bar clashes move
       that to about and in small print at the bottom".

       The credit is owed and is not dropped: it is the same node, moved once,
       text intact, so OpenStreetMap, CARTO and Open Charge Map are still named
       on the page and one tap away. It is appended AFTER the estate links, and
       re-appended on every later adoption pass, so a late DOM rebuild cannot
       leave it above the controls again. appendChild on a node already in the
       panel moves it to the end rather than duplicating it. */
    var attrib = doc.querySelector('.custom-map-attrib');
    if (attrib) {
      if (!bar || !bar.contains(attrib)) move(panels.About, attrib);
      else if (panels.About.lastElementChild !== attrib) panels.About.appendChild(attrib);
      /* The `lastElementChild` test is not tidiness, it is the difference
         between this working and crashing the tab. adoptLate runs from a
         MutationObserver, so an unconditional appendChild here IS a mutation,
         which re-enters adoptLate, which appends again: a feedback loop that
         crashed the renderer outright under the 393x852 arrival gate, while
         the previous generation passed the same gate in the same harness.
         Once the node is already last, this is a no-op and the loop closes. */
    }

    /* The real .scada-brand (VENTUS, again) and .status-legend move once,
       into the restored SCADA panel's head, during install() below -- not
       hidden as a "duplicate" and not here, so a late DOM rebuild cannot
       repeatedly fight over one node's location. */

    /* The panel's own show/hide control stays REACHABLE. It was hidden here as
       "superseded; measured inert", and it is neither: the stylesheet rule
       above was hiding the panel it moved, so its effect could not be seen.
       With the panel restored this is the only control that opens and closes
       it, and hiding it would leave a phone with a collapsed panel and nothing
       to open it with -- which is the fault this generation exists to end. */
    var dashToggle = doc.getElementById('gridatlas-dash-toggle');
    if (dashToggle) dashToggle.hidden = false;

    var stack = doc.querySelector('.map-controls');
    if (stack) {
      var leftovers = array(stack.querySelectorAll('button,input,select,textarea,a'))
        .filter(function (node) { return !node.hidden; });
      if (leftovers.length === 0) stack.setAttribute('data-gridatlas-menu-emptied', '1');
    }

    MENUS.forEach(function (name) {
      state.panel_counts[name] = panels[name] ? panels[name].children.length : 0;
    });
  }

  function install(doc) {
    if (state.installed || doc.getElementById(BAR_ID)) return true;
    var ready = required(doc);
    state.engine_layer_controls = ready.found.engine.length;
    state.pipeline_layer_controls = ready.found.pipeline.length;
    state.layer_controls = ready.found.controls.length;
    if (ready.missing.length) {
      state.waiting_for = ready.missing.slice();
      return false;
    }

    installStyle(doc);
    bar = buildBar(doc);
    buildLayerControls(ready.found);

    /* The search bar is NOT moved. It is the one control a person needs before
       they know which menu to open, and File is closed on arrival -- so moving
       it here left it alive but measuring 0x0, which reads as "the address
       search bar disappears". Same fault the masthead comment below records:
       an always-needed node parked in a collapsed panel. It stays in
       .map-container, where every earlier published version kept it. */
    move(panels.File, ready.nodes.exportButton);
    move(panels.Edit, ready.nodes.statusButton);
    move(panels.View, ready.nodes.fullscreenButton);
    move(panels.Scope, ready.nodes.radiusButton);
    move(panels.Scope, ready.nodes.radiusAreaButton);
    move(panels.Scope, ready.nodes.zoneButton);
    move(panels.Scope, ready.nodes.measureButton);

    /* The VENTUS masthead: fused into the bar's own centre (see buildBar),
       never a closed panel -- the architect's "VENTUS branding has been
       lost" was this node being moved into a collapsed About panel, and
       the measured "flash then vanish" (present for ~1.5s, then torn out)
       was that same move happening after the raw v8 page had already
       painted it once. Moving it here, into brandSlot, keeps it visible
       through the whole transition: raw markup, then fused into the bar,
       never hidden in between. */
    move(brandSlot, ready.nodes.header);

    /* The restored SCADA panel's head: the real .scada-brand (VENTUS,
       again, exactly as v8 rendered it) and .status-legend, moved once --
       not cloned, not hidden as a duplicate. gridHead sits above gridBody
       (built by buildLayerControls) and never enters its column flow. */
    move(gridHead, doc.querySelector('.scada-brand'));
    move(gridHead, doc.querySelector('.status-legend'));

    ready.nodes.host.insertBefore(bar, ready.nodes.host.firstChild);
    doc.documentElement.classList.add('gridatlas-menu-hosted');
    syncAttribClearance(doc);
    if (typeof ResizeObserver === 'function') {
      var barResize = new ResizeObserver(function () {
        syncAttribClearance(doc);
        if (openPanelRefs) clampPanel(doc, openPanelRefs.menu, openPanelRefs.panel);
      });
      barResize.observe(bar);
      state.attrib_clearance_source = 'ResizeObserver';
    } else if (doc.defaultView && typeof doc.defaultView.addEventListener === 'function') {
      /* No ResizeObserver: a viewport resize is the only other way the
         bar's own height changes (the @media breakpoint), so fall back to
         watching that. */
      doc.defaultView.addEventListener('resize', function () {
        syncAttribClearance(doc);
        if (openPanelRefs) clampPanel(doc, openPanelRefs.menu, openPanelRefs.panel);
      });
      state.attrib_clearance_source = 'resize-listener';
    }

    /* One document click listener and one change listener, installed once.
       The retry path cannot multiply effects. */
    doc.addEventListener('click', function (event) {
      if (!bar.contains(event.target)) {
        if (!forwardingLayerChoice) closeAll();
      }
      else if (event.target && /^(BUTTON|INPUT)$/.test(event.target.tagName || '')) {
        if (event.target.type !== 'text'
          && !event.target.classList.contains('gm-title')
          && !event.target.hasAttribute('data-gridatlas-layer-proxy')) {
          window.setTimeout ? window.setTimeout(closeAll, 0) : closeAll();
        }
      }
    });
    doc.addEventListener('change', function (event) {
      var key = layerKey(event.target);
      if (key && layerProxies[key]) syncLayer(key);
    });
    state.listeners = 2;

    adoptLate(doc);
    closeAll();
    state.installed = true;
    state.waiting_for = [];
    state.failure = null;
    state.one_identity_surface = true;
    state.mobile_sheet_hit_target_guard = true;
    state.layer_status_mirrored = true;
    state.layer_menu_stays_open = true;

    if (typeof MutationObserver === 'function') {
      observer = new MutationObserver(function () {
        adoptLate(doc);
        syncAll();
      });
      observer.observe(doc.body, { childList: true, subtree: true, characterData: true });
    }
    return true;
  }

  state.install = function () { return install(document); };
  state.closeAll = closeAll;

  function loudFailure(doc) {
    if (state.installed || doc.getElementById(FAILURE_ID)) return;
    var found = inventory(doc);
    state.failure = 'menu not installed: expected 61 engine + 3 Pipeline News layer controls; found '
      + found.engine.length + ' + ' + found.pipeline.length;
    if (window.console && typeof window.console.error === 'function') {
      window.console.error('[GRIDATLAS MENU] ' + state.failure);
    }
    var alert = doc.createElement('div');
    alert.id = FAILURE_ID;
    alert.setAttribute('role', 'alert');
    alert.textContent = state.failure + '. Original controls remain available.';
    alert.style.cssText = 'position:fixed;left:8px;right:8px;top:8px;z-index:10030;'
      + 'padding:8px;background:#280b0b;color:#ffd0d0;border:1px solid #b44;'
      + 'font:11px/1.4 monospace';
    (doc.body || doc.documentElement).appendChild(alert);
  }

  function start() {
    /* Cartridge proofs and prerenderers can provide a deliberately partial
       document. Treat that exactly like any other missing dependency: publish
       the refusal and leave the owner's interface untouched. In particular,
       do not start the 40-second browser retry loop against a non-DOM stub. */
    if (!document.documentElement || typeof document.createElement !== 'function') {
      state.failure = 'menu not installed: full document unavailable';
      return;
    }
    var probe = document.createElement('div');
    if (!probe || typeof probe.setAttribute !== 'function' || !probe.classList) {
      state.failure = 'menu not installed: full DOM element API unavailable';
      return;
    }
    if (install(document)) return;
    if (typeof window.setInterval !== 'function'
      || typeof window.clearInterval !== 'function') return;
    timer = window.setInterval(function () {
      state.tries += 1;
      if (install(document)) {
        window.clearInterval(timer);
        timer = null;
      } else if (state.tries >= MAX_TRIES) {
        window.clearInterval(timer);
        timer = null;
        loudFailure(document);
      }
    }, 250);
  }

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', start, { once: true });
  } else {
    start();
  }
}());

/* Arrival tidy - the search machinery gets out of the way once it has answered.

   MEASURED, on v9.96 at 393x852, arriving at ?repd_ref=12588 the way a shared
   link arrives: the map canvas was topmost at 13 per cent of 3,200 sampled
   viewport points and the app's own controls at 87. Three of those controls
   were the SEARCH, not the answer - the results list still open at
   [40,136,302,92] holding the project the reader had already been taken to,
   the box holding "12588", a reference the reader never typed, and the
   identity repeated in the results row, the search bar and the card header.

   A deep link is not a search. The reader asked for one project by name and
   got it; the list of how it was found is scaffolding, and scaffolding left
   up is clutter. So on a RESOLVED arrival the list is dismissed and the box
   is emptied back to its placeholder.

   WHAT THIS DELIBERATELY DOES NOT DO

   - It does not touch a FAILED arrival. When the identity could not be
     resolved the results are the only thing on screen that explains why, and
     hiding them would leave a reader with a map and no account of it.
   - It does not clear a box the reader has touched. Focus or a keystroke
     retires this permanently, so a reader who starts typing while the
     arrival is still resolving never has their text taken away.
   - It does not clear a box holding something other than the ref, which is
     the same rule stated for the case where another lane wrote there first.
   - It hides with `style.display = 'none'`, which is what the shell's own
     Escape key and map click do. This is the product's mechanism, not a new
     one, so nothing has to be taught how to bring it back.

   It runs only where there is a MutationObserver. The cartridge proofs
   execute composed cartridges under node:vm against a window stub that has
   neither observers nor timers, and a module that throws there takes the
   whole cartridge down with it - which is exactly how v9.92 shipped a menu
   bar that broke the sandbox proof. Where there is no observer there is no
   arrival either, so doing nothing is the correct answer rather than a
   degraded one. */
(function arrivalTidy() {
  if (typeof document === 'undefined' || typeof window === 'undefined') return;
  if (typeof MutationObserver !== 'function') return;

  var ref = '';
  try {
    ref = String(new URLSearchParams(window.location.search).get('repd_ref') || '').trim();
  } catch (_) { return; }
  if (!ref) return;

  var typed = false;
  var done = false;

  function tidy() {
    if (done) return true;
    var state = document.body && document.body.dataset
      ? document.body.dataset.gridatlasRepdDeepLink : '';
    if (state !== 'resolved') return state === 'failed';   /* failed: stop watching, change nothing */
    var results = document.getElementById('search-results');
    var input = document.getElementById('search-input');
    if (!results || !input) return false;
    if (!typed) {
      results.style.display = 'none';
      if (input.value === ref) input.value = '';
    }
    done = true;
    return true;
  }

  function retire() { typed = true; }

  function watch() {
    var input = document.getElementById('search-input');
    if (input) {
      input.addEventListener('focus', retire, { once: true });
      input.addEventListener('input', retire, { once: true });
    }
    if (tidy()) return;
    var observer = new MutationObserver(function () {
      if (tidy()) observer.disconnect();
    });
    observer.observe(document.body, {
      attributes: true, attributeFilter: ['data-gridatlas-repd-deep-link']
    });
    window.__GRIDATLAS_ARRIVAL_TIDY__ = {
      installed: true,
      repd_ref: ref,
      get dismissed() { return done; },
      get retired_by_reader() { return typed; }
    };
  }

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', watch, { once: true });
  } else {
    watch();
  }
}());

/**
 * Module: pipeline-news-layers
 *
 * A PIPELINE NEWS (REPD) section in the layer dashboard, beside TOPOLOGY,
 * ASSETS and TRANSIT, that summons the rest of the pipeline around whatever
 * project is currently selected.
 *
 * Vikram: "summon other pipeline items within the atlas after clicking the
 * map ... under REPD pipelinenews under its own section like topology, assets
 * etc". Arriving from Pipeline News you land on one project with five links to
 * substations and nothing else of the pipeline in view. These three controls
 * put the neighbours back: what else is being built within reach, of the same
 * technology, of the twenty technologies Pipeline News' own spine does not
 * carry, or of anything at all.
 *
 * WHY IT DOES NOT USE data-layer-id
 * ---------------------------------
 * The engine delegates a `change` listener on #scada-ui-container and on
 * #fs-curtain-keys, and any checkbox carrying `data-layer-id` is routed to its
 * own handleLayerToggle -- which would be handed an id it has no config for.
 * These controls carry `data-pn-layer` instead and are handled here. Same
 * lesson as the wider-fleet tabs in Pipeline News: borrow the styling, never
 * the attribute that another owner dispatches on.
 *
 * WHAT IT IS NOT
 * --------------
 * It draws register points near a selection. It does not measure them, rank
 * them, bind them to the selected project, or imply any relationship between
 * them. Two projects near each other share a map square and nothing else --
 * not a circuit, not a connection, not a queue position. The labels say
 * "within 25 km" and stop there.
 *
 * Depends on: geodesy.
 */
(() => {
  'use strict';

  const NS = (window.__GRIDATLAS_MODULES__ = window.__GRIDATLAS_MODULES__ || {});
  if (NS.pipelineNewsLayers) return;

  const geodesy = NS.geodesy;
  if (!geodesy) {
    throw new Error('pipeline-news-layers requires the geodesy module');
  }

  const GENERATION = '202609030048';
  const RADIUS_KM = 25;
  const GROUP_TITLE = 'PIPELINE NEWS (REPD)';

  /* The register comes from the engine, not from a URL.
     ----------------------------------------------------------------------
     dist/repd_master.json is NOT a served file. Fetching it 404s on the live
     host and in a local checkout alike -- measured both ways -- because the
     streaming bridge reconstructs the register from parquet and hands it
     straight to MapLibre. Every REPD layer the engine draws (l-solar, l-wind,
     l-bess, l-biomass and the rest) is a filter over ONE shared source, and
     that source holds all 10,784 rows once any one of those layers has been
     switched on.
     So this reads src-repd. It is the engine's register, hydrated by the
     engine, and there is no second copy and no second fetch. If nothing has
     hydrated it yet, ticking the engine's own control is what fills it --
     the same move enableTechnologyLayer makes, for the same reason. */
  const REGISTER_SOURCE = 'src-repd';
  const REGISTER_PRIMER = 'biomass';   // any REPD control hydrates the shared source

  /* Pipeline News' spine carries four REPD technology types. Everything else
     in the register is the wider fleet -- the 1,104 projects its own product
     could not admit without changing what it is. Named by the register's own
     `tech` classification, not by a nickname. */
  const SPINE_TECHS = new Set(['solar', 'solar_roof', 'bess', 'wind']);

  /* The engine's own technology colours, so a point reads the same here as it
     does on the layer it belongs to. */
  const TECH_COLOUR = {
    solar: '#ffff00', solar_roof: '#ffcc00', bess: '#ffae00', wind: '#00ffff',
    biomass: '#39ff14', hydro: '#00aaff', hydrogen: '#ffffff', tidal: '#00bfff',
    act: '#ff6600', geothermal: '#ff3300', flywheel: '#ff69b4', caes: '#88aaff',
    other: '#888888'
  };

  const CONTROLS = [
    {
      id: 'same',
      label: 'Same technology',
      colour: '#5fbdc2',
      keep: (row, selection) => row.tech === selection.tech
    },
    {
      id: 'wider',
      label: 'Wider fleet',
      colour: '#39ff14',
      keep: (row) => !SPINE_TECHS.has(row.tech)
    },
    {
      id: 'all',
      label: 'All pipeline',
      colour: '#d8b64a',
      keep: () => true
    }
  ];

  const state = {
    schema: 'gridatlas.pipeline-news-layers.v1',
    generation: GENERATION,
    installed: false,
    register_rows: 0,
    register_url: null,
    radius_km: RADIUS_KM,
    selection: null,
    counts: {},
    active: [],
    failures: []
  };
  window.__GRIDATLAS_PIPELINE_LAYERS__ = state;

  function note(message) {
    const text = String(message && message.message ? message.message : message);
    if (!state.failures.includes(text)) state.failures.push(text);
  }

  let register = null;         // the engine's rows, read once and kept

  function readRegisterSource(map) {
    try {
      const source = map.getSource(REGISTER_SOURCE);
      const features = source && source._data && source._data.features;
      if (!Array.isArray(features) || !features.length) return null;
      return features.map((feature) => {
        const properties = feature.properties || {};
        const coordinates = (feature.geometry || {}).coordinates || [];
        return {
          name: properties.name || '',
          operator: properties.operator || '',
          tech: properties.tech || 'other',
          raw: properties.raw_tech || '',
          status: properties.status || '',
          mw: Number(properties.capacity) || 0,
          lon: Number(coordinates[0]),
          lat: Number(coordinates[1])
        };
      }).filter((row) => Number.isFinite(row.lon) && Number.isFinite(row.lat));
    } catch (error) {
      note('register: ' + String(error && error.message || error));
      return null;
    }
  }

  /* Ask the engine to hydrate its own register, by ticking the control it
     owns rather than reaching past it into the map. The panel then tells the
     truth about what is on, which it would not if this added a source itself. */
  function primeRegister() {
    const box = document.querySelector(
      '#scada-ui-container input[type=checkbox][data-layer-id="' + REGISTER_PRIMER + '"]');
    if (!box) { note('register: no ' + REGISTER_PRIMER + ' control to prime with'); return false; }
    if (!box.checked) box.click();
    state.primed_with = REGISTER_PRIMER;
    return true;
  }

  async function loadRegister(map) {
    if (register) return register;
    register = readRegisterSource(map);
    if (register) { state.register_rows = register.length; return register; }

    if (!primeRegister()) throw new Error('register unavailable');
    for (let attempt = 0; attempt < 40; attempt += 1) {
      await new Promise((resolve) => setTimeout(resolve, 250));
      register = readRegisterSource(map);
      if (register) { state.register_rows = register.length; return register; }
    }
    note('register: ' + REGISTER_SOURCE + ' did not hydrate within 10 s');
    throw new Error('register unavailable');
  }

  /* The selected project, read from the pin the sld-sandbox cartridge draws.
     There is no public selection surface carrying coordinates -- last_selection
     has the name, the technology and the nearest distance, but not the origin
     -- so this reads the pin source and corroborates it against the public
     project_pin.name before trusting it. If the cartridge ever publishes the
     origin properly, delete this and read that. */
  function readSelection(map) {
    try {
      const source = map.getSource('gridatlas-project-pin');
      const features = source && source._data && source._data.features;
      if (!features || !features.length) return null;
      const [lon, lat] = features[0].geometry.coordinates || [];
      if (!Number.isFinite(lon) || !Number.isFinite(lat)) return null;
      const links = window.__GRIDATLAS_NEON_LINKS__ || {};
      const name = (features[0].properties || {}).name
        || (links.project_pin || {}).name || '';
      return { lon, lat, name, tech: (links.last_selection || {}).tech || '' };
    } catch (error) {
      note('selection: ' + String(error && error.message || error));
      return null;
    }
  }

  function near(rows, selection) {
    const found = [];
    for (const row of rows) {
      const km = geodesy.distanceKm(selection.lon, selection.lat, row.lon, row.lat);
      if (km > RADIUS_KM) continue;
      // The selected project is not one of its own neighbours.
      if (km < 0.0005 && row.name === selection.name) continue;
      found.push({ ...row, km });
    }
    found.sort((a, b) => a.km - b.km);
    return found;
  }

  function collection(rows) {
    return {
      type: 'FeatureCollection',
      features: rows.map((row) => ({
        type: 'Feature',
        geometry: { type: 'Point', coordinates: [row.lon, row.lat] },
        properties: {
          name: row.name, operator: row.operator, tech: row.tech,
          raw_tech: row.raw, status: row.status, mw: row.mw,
          km: Number(row.km.toFixed(3)),
          colour: TECH_COLOUR[row.tech] || TECH_COLOUR.other
        }
      }))
    };
  }

  /* addSource throws if the style is not loaded, and a source that failed to
     add reads back as null. The sld-sandbox body learned this the night the
     basemap CDN served style.json and then no tiles at all, and its proof now
     refuses any unguarded setData call site anywhere in the served
     cartridge -- including, as it turns out, one written inside a comment.
     This section is drawing, not plumbing: a missing source costs the drawing,
     not the session. */
  function setSourceData(map, id, data) {
    try {
      const source = map.getSource(id);
      if (!source || typeof source.setData !== 'function') {
        note('source missing, nothing drawn: ' + id);
        return false;
      }
      source.setData(data);
      return true;
    } catch (error) {
      note('source ' + id + ': ' + String(error && error.message || error));
      return false;
    }
  }

  function ensureLayers(map, control) {
    const sourceId = 'pn-src-' + control.id;
    const ringId = 'l-pn-' + control.id + '-ring';
    const dotId = 'l-pn-' + control.id;
    if (map.getSource(sourceId)) return { sourceId, ringId, dotId };
    try {
      map.addSource(sourceId, { type: 'geojson', data: collection([]) });
    } catch (error) {
      note('addSource ' + sourceId + ': ' + String(error && error.message || error));
      return { sourceId, ringId, dotId };
    }
    // A ring in the control's colour, a dot in the technology's own. The ring
    // says which control summoned it; the dot says what it is.
    map.addLayer({
      id: ringId, type: 'circle', source: sourceId,
      paint: {
        'circle-radius': ['interpolate', ['linear'], ['zoom'], 6, 4, 12, 8, 16, 13],
        'circle-color': 'rgba(0,0,0,0)',
        'circle-stroke-color': control.colour,
        'circle-stroke-width': 1.4,
        'circle-stroke-opacity': 0.9
      }
    });
    map.addLayer({
      id: dotId, type: 'circle', source: sourceId,
      paint: {
        'circle-radius': ['interpolate', ['linear'], ['zoom'], 6, 1.8, 12, 3.4, 16, 5.5],
        'circle-color': ['coalesce', ['get', 'colour'], '#888888'],
        'circle-opacity': 0.95
      }
    });
    map.on('click', dotId, (event) => {
      const properties = (event.features && event.features[0] || {}).properties || {};
      try {
        new window.maplibregl.Popup({ closeButton: true })
          .setLngLat(event.lngLat)
          .setHTML(
            '<div style="font-family:monospace;background:#000;padding:6px;max-width:260px">'
            + '<b style="color:#5fbdc2;font-size:12px">' + escapeHtml(properties.name || 'Project') + '</b><br>'
            + '<span style="color:#888">' + escapeHtml(properties.raw_tech || properties.tech || '') + '</span><br>'
            + '<span style="color:#ffae00">' + escapeHtml(String(properties.mw || 0)) + ' MW</span> · '
            + '<span style="color:#aaa">' + escapeHtml(properties.status || '') + '</span><br>'
            + '<span style="color:#555;font-size:10px">' + escapeHtml(String(properties.km)) + ' km from the selected project. '
            + 'Proximity only — not a connection, a circuit or a queue position.</span></div>')
          .addTo(map);
      } catch (error) {
        note('popup: ' + String(error && error.message || error));
      }
    });
    map.on('mouseenter', dotId, () => { map.getCanvas().style.cursor = 'pointer'; });
    map.on('mouseleave', dotId, () => { map.getCanvas().style.cursor = ''; });
    return { sourceId, ringId, dotId };
  }

  function escapeHtml(value) {
    return String(value == null ? '' : value)
      .replace(/[&<>"]/g, (character) => ({
        '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;'
      }[character]));
  }

  function setVisibility(map, control, visible) {
    for (const id of ['l-pn-' + control.id + '-ring', 'l-pn-' + control.id]) {
      if (map.getLayer(id)) map.setLayoutProperty(id, 'visibility', visible ? 'visible' : 'none');
    }
  }

  function labelFor(control, count, selection) {
    if (!selection) return control.label + ' [SELECT A PROJECT]';
    if (count === null || count === undefined) return control.label + ' [WAIT]';
    return control.label + ' [' + count.toLocaleString('en-GB') + ' within ' + RADIUS_KM + ' km]';
  }

  function paintLabels(selection) {
    for (const control of CONTROLS) {
      const text = labelFor(control, state.counts[control.id], selection);
      for (const span of document.querySelectorAll('[data-pn-label="' + control.id + '"]')) {
        span.textContent = text;
      }
    }
  }

  async function refresh(map, control) {
    const selection = state.selection;
    if (!selection) return;
    const rows = await loadRegister(map);
    const found = near(rows.filter((row) => control.keep(row, selection)), selection);
    state.counts[control.id] = found.length;
    const { sourceId } = ensureLayers(map, control);
    setSourceData(map, sourceId, collection(found));
    paintLabels(selection);
  }

  function buildGroup(container, isFullscreen) {
    if (container.querySelector('[data-pn-group]')) return;
    const group = document.createElement('div');
    group.className = 'key-group';
    group.setAttribute('data-pn-group', '1');
    const title = document.createElement('div');
    title.className = 'key-title';
    title.textContent = GROUP_TITLE;
    group.appendChild(title);

    for (const control of CONTROLS) {
      const label = document.createElement('label');
      label.className = 'key-item';
      const input = document.createElement('input');
      input.type = 'checkbox';
      // NOT data-layer-id: the engine dispatches on that attribute.
      input.setAttribute('data-pn-layer', control.id);
      input.dataset.pnLayer = control.id;
      const span = document.createElement('span');
      span.setAttribute('data-pn-label', control.id);
      span.style.color = control.colour;
      span.textContent = labelFor(control, state.counts[control.id], state.selection);
      label.appendChild(input);
      label.appendChild(document.createTextNode(' '));
      label.appendChild(span);
      group.appendChild(label);
    }
    container.appendChild(group);
    state[isFullscreen ? 'installed_fullscreen' : 'installed_main'] = true;
  }