GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Grid network and substations / gridatlas / atlas/modules

Single-Line Diagram (SLD) Without Layout (part 6)

A JavaScript file in the atlas folder of GridAtlas that maps connection points, GB transmission network, price decade rollup and grid substations, using haversine.

700 lines of JavaScript from gridatlas, in 1 file. Topic: Grid network and substations. Section 402 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. Single-Line Diagram (SLD) Without Layout geodesy · gridatlas / atlas/modules/202611222130-sld-without-layout.js lines 3501–4200

Single-Line Diagram (SLD) Without Layout

A JavaScript file in the atlas folder of GridAtlas that maps connection points, GB transmission network, price decade rollup and grid substations, using haversine.

Set aside from the main view: 100% of its lines are the same as atlas/modules/202612020205-secondary-neon-engine.js (gridatlas), which stays. (near-copy-of, proposed by families.py). 99% of lines shared with Secondary Neon Engine; read that one first. All set-aside files, with reasons. Nothing was deleted.

Evidence
  • line-jaccard 0.9961 to gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 atlas/modules/202612020205-secondary-neon-engine.js:1-9008 26e5045a356c11088820207d3cbe95eb4b89374f
  • sha256 6870cfb365c18b90363b664f89623c9217c3d0111a67b87fdd1b6b3a26aeba6b
  • target sha256 b9e2b3ce36d3f46184c4a0f0416d70892feb49507d1c93833d3ab00a27c84263
  • group of 3 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines

geodesygridatlas / atlas/modules/202611222130-sld-without-layout.js · lines 3501–4200 of 8986 · version 2026-11-22 21:30 (continued from section 397) · Not reached from any entry point (candidate for review) · pattern isInterconnectorArrival (shared by 3 files)

What it does
It maps connection points, GB transmission network, price decade rollup and grid substations. Defines 273 functions or classes, including distanceKm, distanceKm, representativePoint, voltagesKv, destinationPoint. Side effects: changes the web page (DOM); reads or writes files; makes network requests; uses storage (browser storage, DuckDB or Parquet).
Why it exists in the grid workflow
Domain stage sub33kv_design (path word 'layout'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. Domain terms in the code: 750kV, 415kV, 400kV, 275kV, 220kV, 132kV.
Inputs & outputs
In: JSON file connection-points.v3.json; JSON file gb-transmission-network.v1.json; JSON file price-decade-rollup.json; GeoJSON file grid_substations.geojson; JSON file neso-connection-sites.lean.json; GeoJSON file interconnectors.geojson; browser storage (getItem); DuckDB queries. Out: browser storage (setItem); interactive map. Coordinate systems named: WGS84 / EPSG:4326. Voltage levels named: 750kV, 415kV, 400kV, 275kV, 220kV, 132kV, 110kV, 66kV.
What it achieves
It creates compute observer (`createComputeObserver`), describes compute receipt (`describeComputeReceipt`) and builds stats (`buildStats`). Receipt and distance owner: Ventusltd/ventus-grid-engine. Its code works with 400 kV, 132 kV and 33 kV. It responds to click, keydown and touchstart events.
Why it matters
No other file in the estate was found to import it.
Application
gridatlas · atlas/modules · script
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
VEDIC
VOLTAGE (GG2050-VEDIC-000003): GridAtlas / Geodesy · Computer science / Data normalisation. voltage_properties → kilovolt_list
Uses
none found
Used by
none found
Produces
distanceKm, distanceKm, representativePoint, voltagesKv, destinationPoint, initialBearingDeg, copy, finite, located, sameLocation, sameEntity, createComputeObserver
Defines here
noteFailure, recoverFailures, distanceKm, voltagesKv, push, representativePoint, deepLinkPlan, createArrivalGate, continueVerifiedArrival, arrivalKey, claimPendingArrival, invalidatePendingArrival, loadSubstations, nearestSubstations, nearestProjects, installStyles, escapeHtml, caveatHtml, kvContext, policyNotesHtml, cardBlockHtml, offshoreNamed, parkingSpot, sheetTarget, dockAsSheet, undockSheet, boundCardToMap
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/202611222130-sld-without-layout.js:3501-4200 · blob ab6fc6992aa26e51a3c82d7e2d26172a50798c60 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, network, storage · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: unreached_review
    return FLOW_PATTERNS[flowIndex(phase)];
  }
  flowDash.patterns = FLOW_PATTERNS;

  const SRC = 'gridatlas-neon-links';
  const SRC_NODES = 'gridatlas-neon-nodes';
  const L_GLOW = 'l-neon-glow';
  const L_CORE = 'l-neon-core';
  const L_FLOW = 'l-neon-flow';
  const L_FLOW_B = 'l-neon-flow-b';
  const L_NODE = 'l-neon-node';
  const L_NODE_RING = 'l-neon-node-ring';
  const L_LABEL = 'l-neon-label';

  const link = {
    schema: 'gridatlas.neon-substation-links.v1',
    generation: GENERATION,
    minimum_kv: MIN_KV,
    map_captured: false,
    installed: false,
    substations_loaded: 0,
    substations_qualifying: 0,
    last_selection: null,
    /* Which cable engine answered this arrival, whether it answered, and what
       it fell back from. Present from boot so a reader can tell "not yet
       asked" from "asked and silent". */
    arrival_engine: null,
    links_drawn: 0,
    deep_linked: false,
    boot_trigger: null,
    layer_controls_ready_ms: null,
    layer_controls_arrived_late: false,
    status_message: null,
    labels_drawn: null,
    gb_panel_installed: false,
    version_ledger: null,
    gb_conditions: null,
    project_layer_enabled: null,
    // iOS Safari background-tab fix: the arrival never starts until the
    // document is visible, and is re-run on visibilitychange if it has not
    // yet produced a visible outcome (see attemptArrival below).
    arrival_deferred_for_visibility: false,
    arrival_attempts: 0,
    arrival_resumed_on_visibility: 0,
    project_pin: { shown: false, name: null },
    substation_layer_enabled: false,
    reduced_motion: false,
    failures: [],
    /* Codex supervision, 202609011446: entries that later recovered stayed
       in `failures`, making a recovered event indistinguishable from a
       terminal fault. Recovery moves an entry here, at the moment the late
       control actually arrives - the entry is preserved as history, and
       `failures` speaks only for what is still failing. */
    recovered: [],
    grid_scope: null,
    grid_scope_armed: false
  };
  window.__GRIDATLAS_NEON_LINKS__ = link;

  /* One entry per distinct active failure. A retry loop used to append the
     same sentence on every attempt, so three tries read as three faults
     and a reader could not tell repetition from spread. Deduplicated
     against what is CURRENTLY failing, never against what has already
     recovered - a fault that comes back deserves to be recorded again. */
  function noteFailure(message) {
    if (!link.failures.includes(message)) link.failures.push(message);
    return false;
  }

  function recoverFailures(pattern) {
    const kept = [];
    for (const entry of link.failures) {
      if (pattern.test(entry)) link.recovered.push(entry);
      else kept.push(entry);
    }
    link.failures = kept;
  }

  /* ── geodesy ─────────────────────────────────────────────────────────── */

  /* Delegated, not reimplemented. Kept as a function declaration rather
     than a const binding so that hoisting behaves exactly as it did before
     - callers earlier in the file are unchanged. */
  function distanceKm(lon1, lat1, lon2, lat2) {
    return GEODESY.distanceKm(lon1, lat1, lon2, lat2);
  }

  /* ── substation layer ────────────────────────────────────────────────── */

  // `33000`, `33000;11000` (two voltages) and `33000:11000` (a transformer
  // ratio) all mean 33 kV is present. Splitting only on ';' drops the ratios.
  /* The unit comes from the property, never from the size of the number.
     ----------------------------------------------------------------------
     This guessed: anything over 1,000 was volts, anything under was already
     kilovolts. That is not what the source says. OSM's `voltage` tag is in
     VOLTS throughout, including its small values, while an explicit `kv`
     property is already kilovolts. Magnitude is not the unit.

     Audited by the Codex session against the pinned 5,800-feature substation
     payload: all 5,800 use `voltage`, 229 of them (3.95%) carry a token below
     1,000, and every one of those was misread. 204 then displayed a primary
     voltage ABOVE 400 kV, which does not exist anywhere on this network. The
     low tokens are 230 (10), 240 (1), 400 (14), 415 (2) and 750 (202) volts —
     the 750s are DC traction supplies at railway depots, so a depot's third
     rail was being shown as a 750 kV substation.

     Measured project impact, from that audit:

       19709  Selhurst Traincare Depot     33000;750       750 kV  ->  33 kV
       18128  Thames Way, Northfleet       33000;750       750 kV  ->  33 kV
       14596  Ford Halewood Transmissions  33000;11000;415 415 kV  ->  33 kV

     Each of those is a real project whose nearest displayed candidate carried
     an impossible voltage, on a card that also carries a distance. A wrong
     voltage beside a right distance is worse than either alone, because the
     distance lends it credibility.

     A bare `33` under `voltage` is therefore 33 volts and correctly falls out
     of a 33 kV-and-above scope. That reads oddly until you remember it is the
     source's own unit; and Codex confirmed the pinned payload contains no such
     token, so nothing real is lost by obeying the contract rather than
     second-guessing it. */
  function voltagesKv(properties) {
    const out = [];
    const push = (raw, divisor) => {
      for (const token of String(raw ?? '').split(/[;,|:\s]+/)) {
        if (!token) continue;
        const value = Number(token);
        if (!Number.isFinite(value) || value <= 0) continue;
        out.push(value / divisor);
      }
    };
    // OSM `voltage` is volts. Always, at every magnitude.
    push(properties?.voltage, 1000);
    // An explicit `kv` is already kilovolts.
    if (!out.length) push(properties?.kv, 1);
    return out;
  }

  // A polygon's first ring vertex is a corner, not the site.
  function representativePoint(geometry) {
    if (!geometry) return null;
    const { type, coordinates } = geometry;
    if (type === 'Point') return [coordinates[0], coordinates[1]];
    const ring = type === 'Polygon' ? coordinates[0]
      : type === 'MultiPolygon' ? coordinates[0]?.[0] : null;
    if (!Array.isArray(ring) || !ring.length) return null;
    let x = 0; let y = 0;
    for (const p of ring) { x += p[0]; y += p[1]; }
    return [x / ring.length, y / ring.length];
  }

  // Exposed so a proof can check this arithmetic against
  // Ventusltd/grid-distance-maths rather than trusting the comment above it.
  // Pure functions only; nothing here touches the map or the DOM.
  link.measure = { distanceKm, voltagesKv, representativePoint };

  /* The receiver decision is pure and exported because Pipeline News owns
     the complete link corpus. The product path below consumes this exact
     plan; the corpus proof can therefore pass all 8,756 derived source
     points (8,753 served coordinate rows and 8,743 clickable actions)
     through the same decision without booting a map or a 35.7 MB register. */
  function deepLinkPlan(rawLon, rawLat, rawRepdRef) {
    const longitude = rawLon === null ? NaN : Number(rawLon);
    const latitude = rawLat === null ? NaN : Number(rawLat);
    const repdRef = String(rawRepdRef || '').trim();
    const coordinatesUsable = Number.isFinite(longitude) && Number.isFinite(latitude)
      && Math.abs(longitude) <= 180 && Math.abs(latitude) <= 90
      && !(Math.abs(longitude) < 1e-9 && Math.abs(latitude) < 1e-9);
    return Object.freeze({
      longitude, latitude, repd_ref: repdRef, coordinates_usable: coordinatesUsable,
      route: coordinatesUsable ? 'MEASURE_LINK_FIRST'
        : (repdRef ? 'WAIT_FOR_REGISTER' : 'NO_USABLE_POINT')
    });
  }
  link.measure.deepLinkPlan = deepLinkPlan;

  /* A resolved register identity is an asynchronous continuation of one
     particular arrival, not permission to take the map back later. User
     selection and clear paths invalidate the token. The same coordinator is
     exported so the generation proof can resolve a deliberately late promise
     through the production gate rather than restating this race in a mock. */
  function createArrivalGate() {
    let epoch = 0;
    let activeKey = null;
    const invalidations = [];
    return Object.freeze({
      begin(key = null) {
        const candidate = key == null ? null : String(key);
        /* The search owner and the measurement owner claim the same URL
           independently as their scripts boot. A keyed claim is idempotent,
           so whichever starts first gives both halves one cancellation
           epoch rather than making the second half stale immediately. */
        if (candidate && candidate === activeKey) return epoch;
        epoch += 1;
        activeKey = candidate;
        return epoch;
      },
      invalidate(reason) {
        epoch += 1;
        activeKey = null;
        invalidations.push({ epoch, reason: String(reason || 'unspecified') });
        return epoch;
      },
      isCurrent(candidate) { return candidate === epoch; },
      snapshot() { return Object.freeze({ epoch, activeKey,
        invalidations: [...invalidations] }); }
    });
  }
  async function continueVerifiedArrival(gate, epoch, verification, apply) {
    const result = await verification;
    if (!gate.isCurrent(epoch)) return false;
    await apply(result);
    return gate.isCurrent(epoch);
  }
  const arrivalGate = createArrivalGate();
  function arrivalKey(search = window.location.search) {
    return 'deep-link:' + String(search || '');
  }
  function claimPendingArrival(search = window.location.search) {
    return arrivalGate.begin(arrivalKey(search));
  }
  function invalidatePendingArrival(reason) {
    const epoch = arrivalGate.invalidate(reason);
    link.arrival_reconciliation = { status: 'INVALIDATED', reason, epoch };
    /* The gate has moved, so the standing answer belongs to an arrival that is
       no longer the one on screen. Leaving it was the difference between a
       silent map and a map that reports the previous project's answer as this
       project's: click A, get an answer; click B while the substation payload
       is failing, and A's green sentinel is still sitting there. Every path
       that moves the gate comes through here - clear, history navigation,
       new selection, identity retry - so this is the one place it belongs. */
    try { clearArrivalEngine(); } catch (_) { link.arrival_engine = null; }
    // The declared frame belongs to the arrival that drew it, and no other.
    if (typeof declaredFrameGuard === 'function') { try { declaredFrameGuard(); } catch (_) {} }
    link.declared_connection_framed = false;
    try {
      window.dispatchEvent(new CustomEvent('gridatlas:arrival-invalidated', {
        detail: { reason: String(reason || 'unspecified'), epoch }
      }));
    } catch (_) { /* cancellation still lives in the shared gate */ }
    return epoch;
  }
  link.measure.createArrivalGate = createArrivalGate;
  link.measure.continueVerifiedArrival = continueVerifiedArrival;
  link.measure.arrivalGate = arrivalGate;
  link.measure.arrivalKey = arrivalKey;
  link.measure.claimPendingArrival = claimPendingArrival;
  link.measure.invalidatePendingArrival = invalidatePendingArrival;
  link.enableSubstationLayer = () => enableSubstationLayer();
  link.armGridScope = (on) => { scopeArmed = Boolean(on); return scopeArmed; };
  link.clearGridScope = () => clearScope();
  link.noteFailure = (message) => noteFailure(message);

  /* A browser-history move is a user navigation, not permission for the
     asynchronous identity query from the URL being left to reclaim the map.
     replaceState used by the owner does not emit these events. */
  window.addEventListener('popstate', () => invalidatePendingArrival('history-navigation'));
  window.addEventListener('hashchange', () => invalidatePendingArrival('history-navigation'));

  let substationsPromise = null;
  function loadSubstations() {
    if (substationsPromise) return substationsPromise;
    substationsPromise = (async () => {
      // The engine may already hold the layer; prefer that over a second fetch.
      const response = await fetch(new URL(SUBS_URL, document.baseURI), { cache: 'force-cache' });
      if (!response.ok) throw new Error(`substations HTTP ${response.status}`);
      const collection = await response.json();
      const features = Array.isArray(collection?.features) ? collection.features : [];
      link.substations_loaded = features.length;
      const out = [];
      for (const feature of features) {
        const kv = voltagesKv(feature.properties);
        if (!kv.length || Math.max(...kv) < MIN_KV - 0.5) continue;
        const at = representativePoint(feature.geometry);
        if (!at) continue;
        out.push({
          at,
          kv: kv.filter(v => v >= MIN_KV - 0.5).sort((a, b) => b - a),
          name: feature.properties?.name || '',
          operator: feature.properties?.operator
            || feature.properties?.['operator:short'] || ''
        });
      }
      link.substations_qualifying = out.length;
      // published so the interconnectors module can measure the GB converter
      // against the same list the project arrival uses
      link.substations = out;
      return out;
    })().catch(error => {
      link.failures.push(String(error?.message || error));
      substationsPromise = null;
      return [];
    });
    return substationsPromise;
  }

  function nearestSubstations(lon, lat, subs) {
    const scored = [];
    /* Beyond MAX_LINK_KM nothing is drawn, and that stays true. What changes is
       that the nearest one is still measured. Returning an empty list with a
       null distance says "no grid data here", when the fact is "the nearest
       mapped substation is further than the draw radius" - a different
       statement, and the only true one. Measured on Bowdun, Hornsea 3 and
       Berwick Bank, which each resolve and map correctly and then report
       nothing at all.

       This follows the reasoning already written into the offshore branch of
       this file: the distance to the nearest mapped substation is a measurement
       of a real thing, and withholding it was over-caution. */
    let beyond = null;
    for (const sub of subs) {
      const km = globalThis.VentusGridCompute.distanceKm(lon, lat, sub.at[0], sub.at[1]);
      if (km > MAX_LINK_KM) {
        if (!beyond || km < beyond.km) beyond = { ...sub, km };
        continue;
      }
      scored.push({ ...sub, km });
    }
    scored.sort((a, b) => a.km - b.km);
    const result = scored.slice(0, LINK_COUNT);
    // Carried on the array so no caller has to change shape to read it.
    result.beyondRadiusNearest = result.length ? null : beyond;
    result.radiusKm = MAX_LINK_KM;
    return result;
  }

  // The mirror of nearestSubstations: given a substation, the projects around
  // it. Read from the loaded source rather than the viewport, so panning the
  // map does not change the answer -- querySourceFeatures returns what the
  // GeoJSON source holds, queryRenderedFeatures returns only what is on screen.
  function nearestProjects(map, lon, lat) {
    let features = [];
    try { features = map.querySourceFeatures('src-repd') || []; }
    catch (_) { return { loaded: false, links: [] }; }
    // querySourceFeatures reads loaded tiles. With every project layer switched
    // off there are none, and returning an empty list here made the card say
    // "no mapped project within 40 km" of a substation with a 840 MW scheme
    // beside it. Absence from a layer that is not loaded is not absence on the
    // ground, and this is exactly where that rule has to hold.
    if (!features.length) return { loaded: false, links: [] };
    const seen = new Set();
    const scored = [];
    for (const feature of features) {
      const properties = feature.properties || {};
      const tech = String(properties.tech || properties.type || '');
      if (!isProjectTech(tech)) continue;
      const at = representativePoint(feature.geometry);
      if (!at) continue;
      // One source, many tiles: the same project surfaces more than once.
      const key = properties.repd_ref || properties.repdRef
        || `${at[0].toFixed(5)},${at[1].toFixed(5)}`;
      if (seen.has(key)) continue;
      seen.add(key);
      const km = distanceKm(lon, lat, at[0], at[1]);
      if (km > MAX_LINK_KM) continue;
      const capacity = parseFloat(properties.capacity);
      scored.push({
        at, km, tech,
        kv: [],
        name: properties.name || properties.SiteName || properties['Site Name'] || '',
        mw: Number.isFinite(capacity) ? capacity : null
      });
    }
    scored.sort((a, b) => a.km - b.km);
    return { loaded: true, links: scored.slice(0, LINK_COUNT) };
  }

  link.measure.nearestSubstations = nearestSubstations;
  link.measure.MIN_KV = MIN_KV;
  link.measure.MAX_LINK_KM = MAX_LINK_KM;
  link.measure.LINK_COUNT = LINK_COUNT;
  link.measure.PROJECT_TECHS = PROJECT_TECHS;
  link.measure.flowDash = flowDash;
  link.measure.flowIndex = flowIndex;
  link.measure.OFFSHORE_TECHS = OFFSHORE_TECHS;
  link.measure.isProjectTech = isProjectTech;
  link.measure.LAYER_ID_FOR_BUCKET = LAYER_ID_FOR_BUCKET;
  link.measure.layerIdForBucket = layerIdForBucket;
  /* Exposed so a proof can hold the coordinates constant, vary the technology
     and assert the measurement does not move. nearestSubstations() takes a
     longitude, a latitude and a candidate set and reads no technology at all;
     coverage.policy() takes a technology and produces only sentences. That
     separation IS the invariant, and it is checkable from here. */
  link.measure.coverage = coverage;

  /* ── the project card ────────────────────────────────────────────────── */

  const BLOCK_CLASS = 'gridatlas-neon-block';
  const CSS_ID = 'gridatlas-neon-css';

  // The distances belong ON the card the user just opened, not in a separate
  // panel they have to notice. The engine builds that card with openPopup(),
  // which is a closure, so this appends to the rendered popup instead --
  // matching the engine's own idiom: monospace on black, cyan heading, amber
  // for a figure, grey for provenance.
  function installStyles() {
    if (document.getElementById(CSS_ID)) return;
    const style = document.createElement('style');
    style.id = CSS_ID;
    style.textContent = SLD_STYLES.neonBlock(BLOCK_CLASS);
    document.head.appendChild(style);
  }

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

  // BETA here marks SCOPE, not doubt about the arithmetic. The measurement is
  // published and checked; what it does not cover is stated, and the things a
  // distance cannot answer at any precision are named rather than implied.
  function caveatHtml() {
    return `<div class="neon-caveat">`
      + `<b>Beta analytics, not an actual grid connection.</b> Straight-line distance to mapped `
      + `geometry &mdash; not a cable route, not a connection length, and no route has been `
      + `walked. A real connection depends on factors that must be studied: network impedance `
      + `and fault level, thermal headroom, existing committed connections and queue position, `
      + `right of way, wayleaves and easements, crossings, terrain, land control and consent. `
      + `None of those can be inferred from a distance. A mapped substation does not confirm `
      + `capacity, voltage suitability or acceptance by any network party, and absence from a `
      + `mapped layer is not absence on the ground.`
      + `</div>`;
  }

  // Remembered so the LAYOUT button knows what it was opened from.
  let lastSelection = null;

  /* The offshore note used to live here and to be the reason there was no
     number. It now lives in the technology-coverage module and is the caveat
     BESIDE the number. Nothing was deleted: the route reasoning is quoted
     there in full, and the module adds the second sentence this file could
     not have written - what the candidate set does and does not say about
     onshore, counted over the pinned product rather than assumed. */
  const OFFSHORE_NOTE = null;

  /* What a voltage class means, on the card, beside the number.
     ----------------------------------------------------------------------
     A distance to a "132 kV" substation is not the same proposition as a
     distance to a "66 kV" one, and the register's reader usually knows that
     while the map does not say it. These are descriptions of the network as it
     is, not advice about any scheme:

       400 / 275 kV  transmission, bulk power
       220 kV        transmission, and the class being built out for offshore
                     wind landfalls
       132 kV        distribution in England and Wales, transmission in
                     Scotland - the same number meaning two different things
                     depending on where you are standing
       66 kV         largely legacy industrial distribution, much of it being
                     reinforced to 132 kV and above as old heavy load is
                     replaced and offshore wind arrives
       33 kV         primary distribution, and the usual class for a
                     utility-scale solar or storage connection

     Deliberately descriptive. It says what a class generally is, never what a
     particular project should do with it, because the estate's rule is that
     the maths and the tools do the talking. */
  const KV_CONTEXT = {
    400: 'transmission, bulk power',
    275: 'transmission, bulk power',
    220: 'transmission; the class being built out for offshore wind landfalls',
    132: 'distribution in England and Wales, transmission in Scotland',
    66: 'largely legacy industrial distribution, much of it being reinforced '
        + 'to 132 kV and above',
    33: 'primary distribution; the usual class for a utility-scale solar or '
        + 'storage connection',
  };

  function kvContext(kv) {
    const n = Number(kv);
    return Number.isFinite(n) ? (KV_CONTEXT[n] || null) : null;
  }

  /* The sentences a policy adds under the distances.
     ----------------------------------------------------------------------
     ADDITIVE ONLY, and deliberately so. These change no number, no ordering
     and no candidate set; they say what the number is a measurement OF. The
     card printed nothing here for every technology until offshore stopped
     withholding, and an offshore straight line is the one that most needs
     saying out loud - it crosses water. */
  function policyNotesHtml() {
    const notes = (currentPolicy && Array.isArray(currentPolicy.notes))
      ? currentPolicy.notes : [];
    if (!notes.length) return '';
    return notes.map(text => `<p class="neon-caveat">${escapeHtml(text)}</p>`)
      .join('');
  }

  function cardBlockHtml(links, direction, layerLoaded = true) {
    installStyles();
    const toSubstations = direction !== 'from-substation';
    const title = toSubstations
      ? `Nearest substations &ge;${MIN_KV} kV`
      : 'Nearest projects';
    const fallbackName = toSubstations ? 'Unnamed substation' : 'Unnamed project';
    const head = `<div class="neon-hd">${title}<span class="neon-beta">Beta</span></div>`;
    const declaredHtml = declaredBlockHtml(toSubstations);
    if (!links.length) {
      /* THE MEASUREMENT EXISTS; PRINT IT.
         ------------------------------------------------------------------
         nearestSubstations() already carries the nearest substation OUTSIDE
         the draw radius on `links.beyondRadiusNearest`, and until now it went
         only into telemetry: arrival_engine said answered, last_selection
         carried the kilometres and the name, and the card said "no mapped
         substation within 40 km" - so the record and the reader disagreed
         about the same arrival, and the reader was told the smaller truth.

         It also contradicted the block directly above it, which prints an
         unbounded nearest 400 kV line: "no substation within 40 km" sitting
         over "nearest 400 kV substation: Peterhead, 222.9 km" reads as a
         broken map rather than a bounded one.

         This is the whole of the offshore silence. Fourteen of the eighty-two
         located offshore wind rows have nothing at all inside 40 km - Dogger
         Bank, Hornsea 1-4, Berwick Bank, Bowdun, Sofia, Culzean among them -
         and every one of them had a real distance to a real named substation
         sitting in memory while the card claimed there was nothing.

         The radius is NOT widened. A 217 km animated line from Dogger Bank to
         Denwick would be a picture of a cable that does not exist. The number
         is given, the line is not drawn, and the card says which. */
      const beyond = toSubstations ? (links.beyondRadiusNearest || null) : null;
      const nothing = toSubstations
        ? (beyond
          ? `Nothing within ${MAX_LINK_KM} km, so no line is drawn. The nearest `
            + `mapped substation at ${MIN_KV} kV or above is `
            + `${escapeHtml(beyond.name || 'unnamed')}`
            + `${beyond.kv && beyond.kv.length ? ` (${beyond.kv[0]} kV)` : ''}, `
            + `${beyond.km.toFixed(1)} km straight line.`
          : `No mapped substation at ${MIN_KV} kV or above within ${MAX_LINK_KM} km of this point.`)
        : (layerLoaded
          ? `No mapped project within ${MAX_LINK_KM} km of this substation.`
          : `The project layers are switched off, so there is nothing to measure `
            + `against. Turn on Solar PV, Wind or Battery Storage and click again. `
            + `This is not a statement that no project is here.`);
      /* An offshore project's export cable lands somewhere before it reaches
         any of this, and where it lands is a published fact this estate does
         not yet hold. Say that, rather than letting a straight line over water
         be read as a route. */
      const offshoreRoute = (toSubstations && beyond && currentPolicy?.offshore)
        ? `<p class="neon-caveat">This is a straight line from the array, not a `
          + `route. An export cable lands at a declared onshore point, and that `
          + `declaration is not in this estate's data, so the landfall is not `
          + `measured and no connection is claimed.</p>`
        : '';
      return `<div class="${BLOCK_CLASS}">${declaredHtml}${head}`
        + `<div class="neon-caveat">${nothing}</div>${offshoreRoute}${policyNotesHtml()}`
        + `${caveatHtml()}</div>`;
    }
    const rows = links.map(l => {
      const kv = l.kv && l.kv.length ? l.kv[0] : null;
      const tail = kv != null ? `${kv} kV`
        : (l.mw != null ? `${l.mw} MW` : '');
      // What the class generally IS, on hover, beside the number. A distance
      // to 132 kV is not the same proposition as a distance to 66 kV, and the
      // reader of a register usually knows that while the map does not say it.
      const context = kvContext(kv);
      const titled = context
        ? ` title="${escapeHtml(kv + ' kV: ' + context)}"` : '';
      /* A result that is ITSELF named as an offshore substation is marked,
         never removed. The product has no field that separates a platform at
         sea from the onshore substation for an offshore farm, so the honest
         move is to hand the reader the name and the flag rather than to
         filter on a predicate that is wrong four times in fourteen. */
      const offshoreNamed = (() => {
        try { return Boolean(coverage.namedOffshore(l.name)); }
        catch (_) { return false; }
      })();
      const flag = offshoreNamed
        ? `<span class="neon-kv" title="Named as an offshore substation in the `
          + `mapped product. That product carries no field saying whether this `
          + `is a platform at sea or the onshore substation for an offshore `
          + `farm, so it is marked rather than filtered.">named offshore</span>`
        : '';
      return `<li><span class="neon-km">${l.km.toFixed(2)} km</span>`
        + `<span class="neon-name">${escapeHtml(l.name || fallbackName)}</span>`
        + (tail ? `<span class="neon-kv"${titled}>${escapeHtml(tail)}</span>` : '')
        + flag
        + `</li>`;
    }).join('');

    /* One line naming the classes actually present, rather than a legend for
       classes that are not. If every substation found is 33 kV, a paragraph
       about 400 kV transmission is noise. */
    const classes = [...new Set(links
      .map(l => (l.kv && l.kv.length ? Number(l.kv[0]) : null))
      .filter(kv => Number.isFinite(kv) && kvContext(kv)))]
      .sort((a, b) => b - a);
    const classNote = classes.length
      ? `<p class="neon-caveat neon-kvnote">`
        + classes.map(kv => `<b>${kv} kV</b> ${escapeHtml(kvContext(kv))}`).join('. ')
        + '. Descriptions of the network, not advice about this scheme.</p>'
      : '';
    // The way into the layout. Without this there is no route from a project
    // to the sandbox at all, which is exactly how it felt to use.
    const kvNoteHtml = classNote;
    const button = toSubstations
      ? `<button class="neon-pin" type="button" aria-pressed="${pinVisible}">`
        + `${pinVisible ? 'Hide' : 'Show'} the project ring</button>`
      : '';
    return `<div class="${BLOCK_CLASS}">${declaredHtml}${head}<ol>${rows}</ol>${kvNoteHtml}`
      + `${policyNotesHtml()}${button}${caveatHtml()}</div>`;
  }

  // The engine opens its popup in its own click handler. This one is registered
  // afterwards, so by the time it runs the popup is in the DOM and can be
  // extended rather than replaced.
  // A grab bar with a minimise and a close, added to whatever card is open.
  // MapLibre gives a popup one hairline cross and no way to move it, which on a
  // map is the difference between a card and an obstruction.
  // Bound the card to the map it lives in. The Atlas gives the map roughly a
  // third of a desktop window, so a viewport-relative cap is not enough.
  /**
   * Fit the open card to the room it actually has.
   *
   * The container height is the wrong number: a card anchored two thirds of
   * the way down a 319px map has 159px beneath it, not 319. Measured live, a
   * cap taken from the container still left 127px hanging below the map.
   *
   * So the cap is the distance from where the card is anchored to the bottom
   * of the map. Where that is too small to be usable the card is freed from
   * its anchor instead and parked at the top of the map, which is the honest
   * answer: a 90px scrolling window is not a card, it is a slot.
   */
  const MIN_ANCHORED_CARD = 200;

  /**
   * Where to put a card that has been freed from its anchor.
   *
   * Not the map's top left. The Atlas keeps its own tool stack there -- Export
   * CSV, Radius Search, Radius Area, Poly Zone, Status Colours, Measure --
   * measured live at x 15 to 137, and parking on top of it trades one
   * obstruction for another. The stack is queried rather than assumed, so the
   * card still lands correctly if those buttons move or change.
   */
  function parkingSpot(map) {
    let x = map.left + 12;
    try {
      const controls = document.querySelector('.map-controls');
      if (controls) {
        const rect = controls.getBoundingClientRect();
        if (rect.width > 0 && rect.right > x) x = rect.right + 12;
      }
    } catch (_) { /* the default is still inside the map */ }
    return { x, y: map.top + 12 };
  }

  /* The sheet height is not a taste. Measured live at 393x852 with the
     answer at the top of the block: grab bar 55px, the identity the engine
     renders 134px, the measurement paragraph with the corridor estimate and
     its caveat 108px, the scope sentence with the coverage denominator 67px.
     364px that must arrive together or not at all, because a measurement may
     not appear without the sample its superlative searched or without the
     word "straight". 58dvh is 494px at 852 and 464px at 800, so all of it
     clears the fold; capped in pixels too, because 58dvh of a tall tablet is
     most of the screen and the map is what the sheet stands on. */
  const SHEET_MIN = 320;
  function sheetTarget() {
    try { return trayTarget(); } catch (_) { return false; }
  }
  function dockAsSheet(popup, content) {
    const viewport = window.visualViewport?.height || window.innerHeight || 0;
    /* Minimised, the sheet is its bar and nothing else, so the stack on it
       comes back down. Measured off the bar, not assumed: it is 55px with a
       44px control in it, and a hard-coded 44 would overlap by eleven. */
    const height = popup.classList.contains('gridatlas-min')
      ? Math.max(44, Math.round(
        popup.querySelector('.gridatlas-card-bar')?.getBoundingClientRect().height || 55) + 12)
      : Math.max(SHEET_MIN, Math.min(520, Math.round(viewport * 0.58)));
    popup.classList.add('gridatlas-sheet');
    popup.classList.remove('gridatlas-free');
    popup.style.removeProperty('--gx');
    popup.style.removeProperty('--gy');
    content.style.removeProperty('max-height');
    document.documentElement.classList.add('gridatlas-sheet-open');
    document.documentElement.style.setProperty('--gridatlas-sheet-h', height + 'px');
  }
  function undockSheet() {
    document.documentElement.classList.remove('gridatlas-sheet-open');
    document.documentElement.style.removeProperty('--gridatlas-sheet-h');
    document.querySelectorAll('.maplibregl-popup.gridatlas-sheet')
      .forEach(node => node.classList.remove('gridatlas-sheet'));
  }

  function boundCardToMap() {
    try {
      const container = capturedMap?.getContainer();
      if (!container) return;
      const bounds = container.getBoundingClientRect();
      const top = Math.max(bounds.top, document.getElementById('gridatlas-menu-bar')?.getBoundingClientRect().bottom || 0);
      const map = { left: bounds.left, right: bounds.right, top, bottom: bounds.bottom, width: bounds.width, height: bounds.bottom - top };
      const popup = document.querySelector('.maplibregl-popup');
      const content = popup?.querySelector('.maplibregl-popup-content');
      if (!popup || !content) {
        undockSheet();
        document.documentElement.style.setProperty(
          '--gridatlas-card-max', Math.max(160, map.height - 60) + 'px');
        return;
      }