GLOBALGRID2050 / EXPLORE CODE

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

Single-Line Diagram (SLD) Sandbox V9 8 (part 14)

A JavaScript file in the cartridges 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 373 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) Sandbox V9 8 geodesy · gridatlas / atlas/cartridges/202611180026-sld-sandbox-v9-8.js lines 1922–2621

Single-Line Diagram (SLD) Sandbox V9 8

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

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

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

geodesygridatlas / atlas/cartridges/202611180026-sld-sandbox-v9-8.js · lines 1922–2621 of 9047 · version 2026-11-18 00:26 (continued from section 370) · 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 276 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 experimental (path word 'sandbox'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow. 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/cartridges · 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
mentioned in Standalone (comment link)
Produces
distanceKm, distanceKm, representativePoint, voltagesKv, destinationPoint, initialBearingDeg, copy, finite, located, sameLocation, sameEntity, createComputeObserver
Defines here
coverage, isProjectTech, layerIdForBucket, cardPreferenceKey, provisionalDeclaredConnection, resolveDeclaredConnection, loadNesoSites, finish, siteKey, resolveNesoConnection, nearestTransmission, corridorBeside, module, corridorTargets, corridorAction, installCorridorSheet, close, openCorridorSheet, module, armCorridorGestures, canvas, cancel, nearestScope, network, nesoBlockHtml, declaredBlockHtml
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/cartridges/202611180026-sld-sandbox-v9-8.js:1922-2621 · blob 4336ae8ea8d1eafcf57a97906bbb6c661f9c8318 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, network, storage · domain stage: experimental · users: none · canonical: unreached_review
     This file used to declare R_ATLAS = 6378.137 and its own distanceKm,
     four hundred lines from a second geodesy section, while the assembled
     cartridge ALSO carried the geodesy module in front of it. Two radii and
     two haversines in one served file, agreeing only because nobody had
     changed one of them yet - and on 1 Sep 2026 the all-versions proof
     found that they had in fact stopped agreeing in the last bit.

     The Grid Finding Scope already did this correctly: it calls its module
     and computes nothing itself. Geodesy was the exception. It is not now.
     A missing module is a hard failure at load, not a fallback: a fallback
     would silently restore exactly the duplication this removes. */
  const GEODESY = (window.__GRIDATLAS_MODULES__ || {}).geodesy;
  if (!GEODESY) throw new Error('sld-sandbox requires the geodesy module');
  const R_ATLAS = GEODESY.EARTH_RADIUS_KM;
  const DEG = Math.PI / 180;
  const MIN_KV = 33;
  const LINK_COUNT = 5;              // how many substations to reach for
  const MAX_LINK_KM = 40;            // beyond this, silence is more honest
  const SUBS_URL = 'data/grid_substations.geojson';
  const SUBS_LAYER_ID = 'l-subs';    // engine convention: layer `l-<id>`, source `src-<id>`

  // Project technologies this fires for. Onshore only: an offshore turbine's
  // export route is nothing like a straight line to the nearest onshore
  // substation, so drawing one would be a picture of a lie.
  /* Every technology the register actually uses, and then some.
     ----------------------------------------------------------------------
     This set was solar, bess and two spellings of wind, and it silently
     rejected the rest. Counted against the shipped register: 2,399 onshore
     wind projects and 109 offshore, so 2,508 of 7,680 — a third of the
     register — had a MAP button that did nothing at all. Not an error, not a
     message, nothing: the deep link tested membership and returned.

     The register writes `wind_onshore`. The engine has had a `wind_onshore`
     layer the whole time. Only this list disagreed with both.

     So it no longer decides alone. The list below is the fast path, and
     anything the ENGINE has a layer control for is accepted too — the engine
     owns the layers, so the engine's vocabulary is the authority and this
     stops being a place a technology can be forgotten. */
  const PROJECT_TECHS = new Set([
    'solar', 'solar_operational', 'solar_roof',
    'bess', 'bess_operational',
    'wind', 'wind_onshore', 'wind_onshore_operational',
    'wind_offshore', 'wind_offshore_operational',
    // The rest of the engine's own generation and storage dashboard, read off
    // the live page rather than guessed. Note wind_onshore is NOT among the
    // engine's layer ids -- it has `wind` and `wind_onshore_operational` --
    // yet the register writes wind_onshore for 2,399 projects. Asking the
    // engine alone would still have missed every one of them, which is why the
    // explicit entry above is not redundant with the lookup below.
    'biomass', 'hydro', 'hydrogen', 'tidal', 'geothermal',
    'flywheel', 'caes', 'act',
    /* `other` is what the register writes for a category it has no
       bucket for. Over the 11,069-row REPD product this Atlas's search
       lane reads, 25 DESNZ categories normalise to 14 ids and `other` was
       the only one missing here - 4 projects, 2 Unknown and 2 Air Source
       Heat Pumps. Not many; not zero; and written again the next time the
       register gains a category. */
    'other'
  ]);

  /* Which technologies measure, and what each measurement is OF, is owned by
     the technology-coverage module rather than by this file. It is assembled
     into this cartridge ahead of this part, so it is here by the time any of
     this runs; the fallback below exists only so a proof can load this part
     alone, and it reproduces the module's answer rather than a different one.

     Offshore NO LONGER WITHHOLDS. It used to open a card and draw nothing, on
     reasoning about export cables and landfalls that was right about routes
     and wrong about whether to measure at all. An offshore project's export
     cable does land at an onshore substation, so the distance is a
     measurement of something real. What changed is the answer; what did not
     change is a single word of the route reasoning, which the module now
     prints beside the number instead of instead of it. */
  const coverage = (() => {
    try {
      const module = window.__GRIDATLAS_MODULES__?.technologyCoverage;
      if (module && typeof module.policy === 'function') return module;
    } catch (_) { /* fall through to the local reproduction */ }
    const OFF = new Set(['wind_offshore', 'wind_offshore_operational']);
    return {
      policy: (tech) => ({ technology: tech || null, measure: true,
        offshore: OFF.has(String(tech || '')),
        sample: 'nearest of the mapped substations at or above the voltage '
          + 'floor that this search could see',
        notes: [] }),
      namedOffshore: () => false
    };
  })();
  const OFFSHORE_TECHS = new Set(['wind_offshore', 'wind_offshore_operational']);

  function isProjectTech(tech) {
    if (!tech) return false;
    if (PROJECT_TECHS.has(tech)) return true;
    // Ask the engine. If it has a control for this layer, it is a technology
    // this map knows about, whatever this cartridge was written knowing.
    try {
      return Boolean(document.querySelector(
        'input[type=checkbox][data-layer-id="' + String(tech).replace(/"/g, '') + '"]'));
    } catch (error) {
      return false;
    }
  }

  /* Pipeline News' MAP link sends a technology BUCKET, not a layer id, and
     the two are not the same vocabulary. There are exactly thirteen buckets
     it can send -- the four-member spine solar/bess/wind_onshore/
     wind_offshore, plus the nine wider-fleet buckets biomass/hydro/
     hydrogen/act/tidal/geothermal/caes/flywheel/other -- see
     atlas/modules/202609031310-technology-coverage.js SPINE and
     widerFleetBuckets(), which is the one place that list is owned.

     isProjectTech() above tests membership of PROJECT_TECHS, which
     deliberately contains wind_onshore, wind_offshore and other so that an
     arrival for one of them is not abandoned. That membership test answers
     "is this a technology the map recognises", not "is there a layer
     control with this exact id" -- and those are different questions here:

       - wind_onshore and wind_offshore are not layer ids. The engine
         publishes one combined `wind` layer, filtered on tech === 'wind',
         which is inclusive of both orientations and every status (see
         ukConfig's REPD layer group); wind_onshore_operational and
         wind_offshore_operational are narrower operational-only subsets,
         not the general layer. A deep link for either bucket wants the
         general layer switched on, so both resolve to 'wind'.
       - other has never had a layer control at all. 25 DESNZ categories
         normalise to 14 register ids and `other` is the one bucket that
         genuinely has nothing to switch on -- not a bug to retry, a fact
         to state.

     Measured live on v9.107: because isProjectTech('wind_onshore') is
     true, the arrival's own technology_layer.enabled read true while the
     DOM search for a control literally named "wind_onshore" failed every
     time -- 2,508 of 7,680 register rows, a third of it. One table here,
     consulted at the one place a control is actually looked up, so a
     bucket cannot go missing from it the way these three did while still
     passing the membership test that was supposed to catch that. */
  const LAYER_ID_FOR_BUCKET = Object.freeze({
    wind_onshore: 'wind',
    wind_offshore: 'wind',
    other: null   // no layer exists; the caller must say so, not search for one
  });

  function layerIdForBucket(tech) {
    const id = String(tech == null ? '' : tech);
    return Object.prototype.hasOwnProperty.call(LAYER_ID_FOR_BUCKET, id)
      ? LAYER_ID_FOR_BUCKET[id] : id;
  }

  // SCADA on a dark map, not arcade neon. These are the muted siblings of the
  // engine's own layer colours: enough saturation to read as live, low enough
  // not to shout over the basemap or the grid layers underneath.
  const TECH_COLOUR = {
    solar: '#d8c96a', solar_operational: '#d8c96a', solar_roof: '#d8c96a',
    bess: '#d9963c', bess_operational: '#d9963c',
    wind: '#6fb582', wind_onshore: '#6fb582', wind_onshore_operational: '#6fb582',
    // Offshore reads cooler than onshore: it is the one technology here whose
    // links are deliberately not drawn, and it should not look like the others.
    wind_offshore: '#5f9fb5', wind_offshore_operational: '#5f9fb5',
    biomass: '#b58f6f', hydro: '#6f9fd8', hydrogen: '#a98fd8',
    tidal: '#5fb5a8', geothermal: '#b57f6f',
    flywheel: '#9f9fb5', caes: '#9f9fb5', act: '#9f9fb5'
  };
  const SUBSTATION_COLOUR = '#5fbdc2';   // teal, the substation end of a link

  /* ── the 400 kV public record ────────────────────────────────────────
     The nearest-substations list is a measurement and nothing more. But
     the DCO-scale schemes each carry a PUBLIC declared point of connection
     at 400 kV - usually through a new customer substation consented within
     the scheme itself - and this card used to say nothing about it while
     listing closer 33 and 132 kV points, which read as connecting them to
     the wrong network. The rule holds: bind to the public record or say
     nothing. Every entry below is sourced from Development Consent Orders,
     Planning Inspectorate documents, or public project statements; the
     table binds a register identity to a NAMED substation in the served
     payload, and the distance shown is measured, never asserted. */
  const DECLARED_COLOUR = '#d8b64a';   // gold: declared, and the far end exists today
  /* Pink: declared, and the thing at the far end has not been built. One
     Earth's point of connection is a National Grid substation that does not
     exist yet; Thorpe Marsh's is under construction. Drawing those in the
     same gold as a connection into a live substation would say something
     untrue about the network, so they get their own colour and the card
     says which it is. The distinction is taken from the public record, not
     from the map: an unbuilt substation can be absent from OSM, or present
     because someone mapped the consented site. */
  const DECLARED_UNBUILT_COLOUR = '#d87aa8';
  /* The table itself, and the three functions that bind it to the payload,
     moved to the declared-connections module at generation 202609012128.
     The body keeps the colours (rendering) and the state; the record is
     read from the module, which a proof can open on its own and a cut
     hashes on its own. A missing module is a hard failure at load, for
     the same reason as geodesy: a fallback would quietly restore a second
     copy of the table. */
  const DECLARED = (window.__GRIDATLAS_MODULES__ || {}).declaredConnections;
  if (!DECLARED) throw new Error('sld-sandbox requires the declared-connections module');

  let currentRepdRef = null;
  let cardSelectionKey = '';
  let cardPreference = null;
  function cardPreferenceKey() { return currentRepdRef ? 'repd:' + currentRepdRef : cardSelectionKey; }
  let currentDeclared = null;
  let currentNeso = null;
  let declaredFrameGuard = null;   // detaches the frame guard; see drawLinks
  let currentNearest400 = null;
  /* The coverage policy for the CURRENT selection. It carries no arithmetic
     and changes no result - it decides only which sentences go under the
     distances. The measurement itself is coordinates, a candidate set and a
     distance, and reads no technology at all. */
  let currentPolicy = null;
  /* The capacity Pipeline News sent, kept where the network card can
     reach it. Without this the powerflow answer would have to invent a
     figure, and an invented megawatt is exactly the kind of number that
     gets quoted back as the project's own. */
  let currentCapacityMw = null;

  /* What the Order says is known the moment the identity is known: the
     substation, the voltage class, the route, the consented works and the
     citation need no payload, no fetch and no map. On a phone that is the
     difference between a card that answers and a card that waits. The
     distance is the one part that must be measured, so it is the one part
     marked pending until it has been. */
  function provisionalDeclaredConnection(repdRef) {
    return DECLARED.provisional(repdRef);
  }

  function resolveDeclaredConnection(repdRef, origin, subs) {
    return DECLARED.resolve(repdRef, origin, subs);
  }

  /* THE CONNECTION AUTHORITY'S OWN ANSWER.
     ---------------------------------------------------------------------
     An offshore wind farm has to make landfall. Its export cable comes
     ashore and connects at an onshore substation, and this engine had no
     idea which one - so it answered the only question it could, "what is
     the nearest mapped substation to the array", and for an array sitting
     60 km out at sea that returns another company's offshore platform.
     Berwick Bank was told its nearest substation is the Neart na Gaoithe
     platform. Hornsea 3 was told Sheringham Shoal's. At least 15 of the 82
     located offshore rows got an answer that is a structure in the water.

     Those are not distant answers, they are answers to the wrong question,
     and no search radius fixes a wrong question - a bigger circle finds
     more sea.

     NESO publishes the right one. Its Transmission Entry Capacity register
     carries a Connection Site per contracted project and the Embedded
     register does the same for the distribution-connected ones. Hornsea 3
     connects at Norwich Main. Hornsea 4 at Creyke Beck. Sofia and Dogger
     Bank C at Lackenby. Berwick Bank at Branxton. Marram at Longside.

     This is a CONTRACTUAL fact from the body that issues connections, not
     a measurement and not a route. It is printed as that, above the
     measurement, and it never replaces the measurement - both are true and
     they answer different questions.

     XMLHttpRequest, not fetch, and deliberately: the composer executes
     cartridges from a blob: origin where fetch resolves 200 and then throws
     TypeError reading the body. Measured in this Atlas, twice. */
  let nesoPromise = null;
  function loadNesoSites() {
    if (nesoPromise) return nesoPromise;
    link.neso_lookup = { status: 'loading', reason: null };
    nesoPromise = new Promise((resolve) => {
      const finish = (sites, reason = null) => {
        link.neso_lookup = { status: reason ? 'failed' : 'complete', reason };
        resolve(sites);
      };
      try {
        const url = new URL('../../data/neso-connection-sites.lean.json', document.baseURI).href;
        const xhr = new XMLHttpRequest();
        xhr.open('GET', url);
        xhr.timeout = 4000;
        xhr.onload = () => {
          if (xhr.status < 200 || xhr.status >= 300) { finish({}, 'HTTP_' + xhr.status); return; }
          try {
            const payload = JSON.parse(xhr.responseText);
            link.neso_sites_loaded = Object.keys(payload.sites || {}).length;
            finish(payload.sites || {});
          } catch (_) { finish({}, 'INVALID_JSON'); }
        };
        // An absent file means no declared connection is known, which is a
        // state this engine already knows how to say out loud.
        xhr.onerror = () => finish({}, 'NETWORK_ERROR');
        xhr.ontimeout = () => finish({}, 'TIMEOUT');
        xhr.onabort = () => finish({}, 'ABORTED');
        xhr.send();
      } catch (_) { finish({}, 'LOOKUP_ERROR'); }
    });
    return nesoPromise;
  }

  /* A connection site is a place name wearing a voltage and the word
     substation. Both sides are reduced the same way or "Norwich Main
     Substation" in the payload never meets "Norwich Main 400kV Substation"
     in the register - which was a real bug in the join that built this
     file, and it made 30 placeable sites look unplaceable. */
  function siteKey(value) {
    return String(value || '')
      .toLowerCase()
      .replace(/\d+\s*\/?\s*\d*\s*kv/g, ' ')
      .replace(/[^a-z0-9 ]/g, ' ')
      .replace(/\b(substation|substations|gsp|grid supply point|node|platform|offshores?|the)\b/g, ' ')
      .replace(/\s+/g, ' ')
      .trim();
  }

  async function resolveNesoConnection(repdRef, origin, subs) {
    if (!repdRef) return null;
    let sites = {};
    try { sites = await loadNesoSites(); } catch (_) { return null; }
    const entry = sites[String(repdRef)];
    if (!entry || !entry.site) return null;
    const key = siteKey(entry.site);
    let bound = null;
    if (key) {
      for (const sub of subs || []) {
        if (siteKey(sub.name) !== key) continue;
        // Prefer the highest-voltage feature carrying the name: a named site
        // often has several, and the connection is made at the top class.
        if (!bound || (sub.kv?.[0] || 0) > (bound.kv?.[0] || 0)) bound = sub;
      }
    }
    const out = {
      site: entry.site,
      neso_name: entry.neso_name || null,
      register: entry.register || null,
      confidence: entry.confidence || null,
      mw: Number.isFinite(Number(entry.mw)) ? Number(entry.mw) : null,
      status: entry.status || null,
      sites: Array.isArray(entry.sites) ? entry.sites : null,
      at: bound ? bound.at : null,
      kv: bound && bound.kv && bound.kv.length ? bound.kv[0] : null,
      km: null,
    };
    if (bound && origin) out.km = distanceKm(origin[0], origin[1], bound.at[0], bound.at[1]);
    return out;
  }

  function nearestTransmission(origin, subs) {
    return DECLARED.nearestTransmission(origin, subs);
  }

  /* EVERY SUPERLATIVE CARRIES ITS SAMPLE.
     --------------------------------------------------------------------
     "Nearest 400 kV substation" is nearest among what this search could
     see, and two different things limit that. The search runs over the
     substation features the map has loaded, so the first number is how
     many of them were actually eligible - counted by the measurement
     itself, not assumed. And the operator's own published list is only
     partly located: ETYS names substations and does not place them, so
     the geometry comes from OpenStreetMap through a GridAtlas release and
     a fraction of the network is invisible to any search by distance.

     Both numbers are COMPUTED at render time from what was fetched. A
     literal would go quietly false the day the pinned product moves -
     Codex's join correction alone takes located points from 502 to 489 -
     and a stale denominator under the word "nearest" is worse than none.

     It states the sample. It does not grade the result. */
  /* A straight line is not a route, and the card said nothing about it.
     --------------------------------------------------------------------
     ADDITIVE. The straight-line distance is unchanged, still first, still
     the measurement; the corridor figure sits beside it and is labelled an
     estimate every time it appears.

     Only for a CABLE question. The factor is calibrated on cable circuits,
     which follow the highway network; overhead line crosses open country
     and measures 1.13. The module publishes that number and deliberately
     offers no forOverhead(), so this cannot quietly become the answer to a
     question it was not measured on.

     Under about a kilometre the module withholds the estimate rather than
     scaling, and the card says why: at that separation the straight line
     between two site centroids is not measuring route factor at all. */
  function corridorBeside(km) {
    const module = (() => {
      try { return window.__GRIDATLAS_MODULES__?.corridorEstimate || null; }
      catch (_) { return null; }
    })();
    if (!module) return '';
    const estimate = module.forCable(km);
    if (!estimate) return '';
    const basis = module.basis;
    if (estimate.withheld) {
      return ` <span class="neon-caveat">No corridor estimate at this `
        + `separation: ${escapeHtml(estimate.withheld)}.</span>`;
    }
    return ` &middot; ~${estimate.km.toFixed(1)} km corridor estimate `
      + `(&times;${estimate.factor}, ${basis.within_15_pct}% of GB transmission `
      + `cable circuits within 15% of published length, `
      + `${basis.distinct_site_pairs} distinct site pairs). `
      + `<span class="neon-caveat">${escapeHtml(module.caveat)} `
      + `${escapeHtml(module.not_for_overhead)}</span>`;
  }

  /* A 44 px action, and a sheet that is the corridor figures in full.
     --------------------------------------------------------------------
     The card line beside each distance is one sentence. A reader who wants
     the basis - what the factor was calibrated on, how wrong it typically
     is, and what it is not for - should not have to take that from a
     sentence, and on a phone there is no room to print it inline.

     44 px because that is the smallest target a thumb hits reliably; the
     estate's own layers toggle was widened to the same at 202609030116.

     The sheet is opened three ways and all of them end in one function:
     the button, a right-click on the map (the engine binds no contextmenu
     - measured, zero occurrences in the shell, in index.html and in every
     composed part), and a long press.

     THE LONG PRESS DEFERS TO EVERYTHING. It arms on touchstart, and it is
     cancelled by a movement of more than 10 px, by a second finger, by
     touchend, and by an SLD drag already being in progress - the sandbox
     binds its own touchstart for dragging the array, its handle and its
     route pins, so this must never fire during one. A pan is a movement;
     a pinch is a second finger; both cancel before the 500 ms is up. */
  const CORRIDOR_SHEET = 'gridatlas-corridor-sheet';
  let corridorSheetInstalled = false;

  function corridorTargets() {
    const rows = [];
    if (currentDeclared && currentDeclared.kind !== 'circuit'
      && Number.isFinite(currentDeclared.km)) {
      rows.push({ name: currentDeclared.poc, km: currentDeclared.km,
        note: 'declared point of connection, from the public record' });
    }
    if (currentNearest400) {
      rows.push({ name: currentNearest400.name, km: currentNearest400.km,
        note: 'nearest mapped substation at 400 kV or above' });
      if (currentNearest400.named && currentNearest400.named.name !== currentNearest400.name) {
        rows.push({ name: currentNearest400.named.name, km: currentNearest400.named.km,
          note: 'nearest NAMED substation at 400 kV or above' });
      }
    }
    return rows;
  }

  function corridorAction() {
    if (!corridorTargets().length) return '';
    /* The card can render before the map is wired, and the button is
       useless without the delegated listener. Installing here as well is
       idempotent and removes the ordering dependency entirely. */
    installCorridorSheet();
    return `<button type="button" class="gridatlas-corridor-open" `
      + `data-gridatlas-corridor="1" `
      + `aria-haspopup="dialog">Explore route corridors \u203a</button>`;
  }

  function installCorridorSheet() {
    if (corridorSheetInstalled) return;
    corridorSheetInstalled = true;

    const style = document.createElement('style');
    style.textContent =
      '.gridatlas-corridor-open{display:block;width:100%;min-height:44px;margin:8px 0 2px;'
      + 'font:600 12px/1.2 ui-monospace,SFMono-Regular,Menlo,monospace;letter-spacing:.06em;'
      + 'text-align:left;padding:12px 14px;border-radius:6px;cursor:pointer;'
      + 'background:#0d1117;color:#7fe3d0;border:1px solid #2b3a44;}'
      + '.gridatlas-corridor-open:focus-visible{outline:2px solid #7fe3d0;outline-offset:2px;}'
      + '#' + CORRIDOR_SHEET + '{position:fixed;left:0;right:0;bottom:0;z-index:10000;'
      + 'max-height:min(70vh,560px);overflow:auto;transform:translateY(101%);'
      + 'transition:transform .18s ease-out;background:#070d11;color:#cfe6e8;'
      + 'border-top:1px solid #0b5f63;padding:14px 16px calc(16px + env(safe-area-inset-bottom));'
      + 'font:12px/1.5 ui-monospace,SFMono-Regular,Menlo,monospace;}'
      + '#' + CORRIDOR_SHEET + '[data-open="1"]{transform:translateY(0);}'
      + '#' + CORRIDOR_SHEET + ' h4{margin:0 0 8px;font-size:13px;color:#7fe3d0;}'
      + '#' + CORRIDOR_SHEET + ' .r{padding:8px 0;border-top:1px solid #14252b;}'
      + '#' + CORRIDOR_SHEET + ' .c{color:#8fa6ab;}'
      + '#' + CORRIDOR_SHEET + ' button{min-height:44px;min-width:44px;cursor:pointer;'
      + 'background:#0d1117;color:#7fe3d0;border:1px solid #2b3a44;border-radius:6px;'
      + 'padding:10px 14px;font:600 12px/1 ui-monospace,monospace;}'
      + '@media (prefers-reduced-motion:reduce){#' + CORRIDOR_SHEET + '{transition:none;}}';
    document.head.appendChild(style);

    const sheet = document.createElement('div');
    sheet.id = CORRIDOR_SHEET;
    sheet.setAttribute('role', 'dialog');
    sheet.setAttribute('aria-label', 'Route corridor estimates');
    sheet.dataset.open = '0';
    sheet.hidden = true;
    document.body.appendChild(sheet);

    const close = () => { sheet.dataset.open = '0'; sheet.hidden = true; };

    window.__GRIDATLAS_CORRIDOR_SHEET__ = {
      get open() { return sheet.dataset.open === '1'; },
      close,
      open: () => openCorridorSheet(sheet)
    };

    document.addEventListener('click', (event) => {
      const opener = event.target?.closest?.('[data-gridatlas-corridor]');
      if (opener) { event.preventDefault(); openCorridorSheet(sheet); return; }
      if (event.target?.closest?.('[data-gridatlas-corridor-close]')) close();
    });
    document.addEventListener('keydown', (event) => {
      if (event.key === 'Escape' && sheet.dataset.open === '1') close();
    });
  }

  function openCorridorSheet(sheet) {
    const module = (() => {
      try { return window.__GRIDATLAS_MODULES__?.corridorEstimate || null; }
      catch (_) { return null; }
    })();
    const rows = corridorTargets();
    if (!rows.length) return;
    const body = rows.map(row => {
      const estimate = module ? module.forCable(row.km) : null;
      const corridor = estimate && estimate.km !== null
        ? `~${estimate.km.toFixed(1)} km corridor estimate`
        : (estimate ? 'no corridor estimate at this separation' : '');
      return `<div class="r"><b>${escapeHtml(row.name)}</b><br>`
        + `${row.km.toFixed(2)} km straight`
        + (corridor ? ` &middot; ${corridor}` : '')
        + `<br><span class="c">${escapeHtml(row.note)}`
        + (estimate && estimate.withheld
          ? `. ${escapeHtml(estimate.withheld)}` : '')
        + `</span></div>`;
    }).join('');
    const basis = module ? module.basis : null;
    sheet.innerHTML = `<h4>Route corridors</h4>${body}`
      + (basis
        ? `<div class="r c">Straight-line distance is measured. The corridor `
          + `figure is that distance times ${basis.factor}, calibrated on the `
          + `${basis.source}: median absolute error `
          + `${basis.median_absolute_error_pct}%, `
          + `${basis.within_15_pct}% within 15%, over `
          + `${basis.distinct_site_pairs} distinct site pairs. `
          + `${escapeHtml(module.caveat)} ${escapeHtml(module.not_for_overhead)} `
          + `${escapeHtml(module.not_an_assessment)}</div>`
        : `<div class="r c">The corridor module is not loaded, so only the `
          + `measured straight-line distances are shown.</div>`)
      + `<div class="r"><button type="button" data-gridatlas-corridor-close="1">`
      + `Close</button></div>`;
    sheet.hidden = false;
    sheet.dataset.open = '1';
  }

  /* Right-click on desktop, long press on touch. Both end in the sheet. */
  function armCorridorGestures(map) {
    installCorridorSheet();
    try {
      map.on('contextmenu', (event) => {
        if (!corridorTargets().length) return;
        event.preventDefault?.();
        openCorridorSheet(document.getElementById(CORRIDOR_SHEET));
      });
    } catch (_) { /* a shimmed map in a proof */ }

    const canvas = (() => {
      try { return map.getCanvas ? map.getCanvas() : null; } catch (_) { return null; }
    })();
    if (!canvas) return;
    let timer = null;
    let from = null;
    const cancel = () => { if (timer) clearTimeout(timer); timer = null; from = null; };
    canvas.addEventListener('touchstart', (event) => {
      cancel();
      /* Never during an SLD drag: this cartridge binds its own touchstart
         for the array, the rotate handle and the route pins. */
      if (sld && sld.dragging) return;
      if (event.touches.length !== 1) return;
      if (!corridorTargets().length) return;
      from = { x: event.touches[0].clientX, y: event.touches[0].clientY };
      timer = setTimeout(() => {
        timer = null;
        if (sld && sld.dragging) return;
        openCorridorSheet(document.getElementById(CORRIDOR_SHEET));
      }, 500);
    }, { passive: true });
    canvas.addEventListener('touchmove', (event) => {
      if (!timer || !from) return;
      const touch = event.touches[0];
      if (!touch) { cancel(); return; }
      /* A pan is a movement. Ten pixels is below the threshold a deliberate
         press produces and above the jitter a still thumb produces. */
      if (Math.abs(touch.clientX - from.x) > 10
        || Math.abs(touch.clientY - from.y) > 10) cancel();
    }, { passive: true });
    canvas.addEventListener('touchend', cancel, { passive: true });
    canvas.addEventListener('touchcancel', cancel, { passive: true });
  }

  function nearestScope(n) {
    const considered = Number(n && n.considered);
    const network = (() => {
      try { return window.__GRIDATLAS_NETWORK__?.coverage?.(400) || null; }
      catch (_) { return null; }
    })();
    if (!Number.isFinite(considered) && !network) return '';
    const said = [];
    if (Number.isFinite(considered)) {
      said.push(`nearest of the ${considered.toLocaleString('en-GB')} mapped `
        + `substation${considered === 1 ? '' : 's'} at 400 kV or above that this `
        + `search could see`);
    }
    if (network && network.published) {
      said.push(`the operator publishes ${network.published.toLocaleString('en-GB')} `
        + `connection point${network.published === 1 ? '' : 's'} at that class and `
        + `${network.located.toLocaleString('en-GB')} of them carry coordinates, so `
        + `${network.unlocated.toLocaleString('en-GB')} cannot be measured to at all`);
    }
    return `<p class="neon-caveat">Scope: ${said.join('; ')}. A nearer one may `
      + `exist that nothing here can see.</p>`;
  }

  /* The connection site, printed as the contractual fact it is.
     ---------------------------------------------------------------------
     First on the card, because for an offshore project it is the answer to
     the question the reader actually asked, and every distance below it is
     a different question. It never replaces a measurement: where the site
     is in the payload the straight-line distance to it is given, and where
     it is not the card says the substation is not in this map's data rather
     than quietly substituting the nearest thing that is. Several of the
     misses are substations that do not exist yet - Longside, Friston,
     Birkhill Wood, Hurlie, Banniskirk, Brechin - which is a fact about the
     grid, not a gap in the map. */
  function nesoBlockHtml() {
    const n = currentNeso;
    if (!n || !n.site) return '';
    const many = Array.isArray(n.sites) && n.sites.length > 1;
    const measured = n.at && Number.isFinite(n.km);
    return `<div class="neon-hd">Declared connection`
      + (n.confidence === 'MEDIUM'
        ? `<span class="neon-beta" style="background:#d87aa8;color:#1a0b13">Named by inference</span>` : '')
      + `<span class="neon-beta">NESO register</span></div>`
      + `<ol><li>`
      + (measured ? `<span class="neon-km">${n.km.toFixed(2)} km</span>` : '')
      + `<span class="neon-name">${escapeHtml(n.site)}</span>`
      + (n.kv ? `<span class="neon-kv">${n.kv} kV</span>` : '')
      + `</li></ol>`
      + `<p class="neon-caveat">`
      + `The substation this project is contracted to connect at, from NESO's `
      + `${escapeHtml(n.register === 'EMBEDDED' ? 'Embedded' : 'Transmission Entry Capacity')} register`
      + (n.neso_name && siteKey(n.neso_name) !== siteKey(n.site)
        ? `, which lists it as ${escapeHtml(n.neso_name)}` : '')
      + `. This is a contractual fact from the connection authority, not a `
      + `measurement and not a cable route.`
      + (n.mw ? ` Contracted capacity ${n.mw.toLocaleString('en-GB')} MW`
        + (n.status ? `, ${escapeHtml(String(n.status).toLowerCase())}` : '') + '.' : '')
      + (measured
        ? ` The distance shown is a straight line from this project to that `
          + `substation, not the length of any cable.`
        : ` That substation is not in this map's substation data, so no `
          + `distance is measured to it and no line is drawn. Several declared `
          + `connection points are substations that have not been built yet.`)
      + (many
        ? ` The register holds more than one connection site for this project: `
          + `${escapeHtml(n.sites.join('; '))}.` : '')
      + (n.confidence === 'MEDIUM'
        ? ` The register names this project differently from the register of `
          + `planning applications, so the two were paired by name and capacity `
          + `rather than by a shared identifier.` : '')
      + `</p>`;
  }

  function declaredBlockHtml(toSubstations) {
    if (!toSubstations) return '';
    let out = nesoBlockHtml();
    if (currentDeclared) {
      const d = currentDeclared;
      const unbuiltPoc = d.poc_status === 'not_built'
        || d.poc_status === 'under_construction';
      const stateLabel = d.poc_status === 'not_built' ? 'Not built yet'
        : (d.poc_status === 'under_construction' ? 'Under construction' : '');
      out += `<div class="neon-hd">Declared connection`
        + (stateLabel ? `<span class="neon-beta" style="background:#d87aa8;color:#1a0b13">`
          + `${stateLabel}</span>` : '')
        + `<span class="neon-beta">Public record</span></div>`
        + `<ol><li>`
        + (d.at ? `<span class="neon-km">${d.km.toFixed(2)} km</span>` : '')
        + `<span class="neon-name">${escapeHtml(d.poc)}</span>`
        + (d.kv ? `<span class="neon-kv">${d.kv} kV</span>` : '')
        + `</li></ol>`
        + `<p class="neon-caveat">Via ${escapeHtml(d.via)}. `
        + `Source: ${escapeHtml(d.source)}.`
        + (d.works ? ` ${escapeHtml(d.works)}` : '')
        + (d.poc_status_note ? ` This point of connection is not yet in service: `
          + `${escapeHtml(d.poc_status_note)}.` : '')
        + (d.at ? ''
          : (d.kind === 'circuit'
            ? ' The point of connection is a circuit rather than a substation, so no line is drawn and no distance is measured.'
            : (d.pending
              ? ' The distance is being measured now.'
              : ' This substation is not in the mapped payload, so no distance is measured.')))
        + `</p>`;
      // Quotations of consented works from the made Order or Environmental
      // Statement - the DCO's own illustration of the customer substation
      // and the interface at the point of connection. Never design advice.
      if (d.customer_works) {
        out += `<p class="neon-caveat"><b>Customer substation (consented):</b> `
          + `${escapeHtml(d.customer_works)}</p>`;
      }
      if (d.poc_works) {
        out += `<p class="neon-caveat"><b>Works at the point of connection:</b> `
          + `${escapeHtml(d.poc_works)}</p>`;
      }
    }
    /* What the system operator publishes about the substation this card