GLOBALGRID2050 / EXPLORE CODE

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

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

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 400 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 2101–2800

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 2101–2800 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
cardPreferenceKey, provisionalDeclaredConnection, resolveDeclaredConnection, loadNesoSites, finish, siteKey, resolveNesoConnection, nearestTransmission, corridorBeside, module, corridorTargets, corridorAction, installCorridorSheet, close, openCorridorSheet, module, armCorridorGestures, canvas, cancel, nearestScope, network, nesoBlockHtml, declaredBlockHtml, publishedUnits, published, publishedHtml
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:2101-2800 · 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
     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
       names. The sandbox asks; the substation cartridge answers from
       Ventusltd/data-grid-gb, which is ETYS restated. Absent is absent:
       no sentence at all rather than an empty one. */
    const networkName = currentDeclared?.kind !== 'circuit'
      ? (currentDeclared?.poc || currentNearest400?.name) : currentNearest400?.name;
    /* Tell it the voltage the connection is actually made at: the declared
       point of connection's class where there is one, otherwise the class
       of the substation being measured to. Without this the answer can
       only be a site-wide envelope. */
    const connectionKv = currentDeclared?.kind !== 'circuit'
      ? (currentDeclared?.kv || currentNearest400?.kv || null)
      : null;
    /* connection-points counts LANDINGS: a transformer's windings are both
       at the site, so Cowley's five read as ten and 484 of 525 sites were
       1.90x over. Only the node/branch model holds the pairs. */
    const publishedUnits = (() => {
      if (topology.state !== 'ready' || !topology.index) return null;
      try {
        const point = window.__GRIDATLAS_NETWORK__?.byName?.(networkName);
        if (!point?.site_code) return null;
        const facts = topology.index.at(point.site_code);
        if (!facts?.counts) return null;
        return { circuits: facts.counts.circuits,
          transformers: facts.counts.transformers };
      } catch (_) { return null; }
    })();
    const published = (() => {
      try {
        return window.__GRIDATLAS_NETWORK__?.summarise?.(
          networkName, { connectionKv, units: publishedUnits }) || null;
      } catch (_) { return null; }
    })();
    /* The envelope is built HERE and appended BELOW the measurement.
       ---------------------------------------------------------------------
       WHY THE ORDER CHANGED. Driven on a verified iPhone-class device
       (393x852, pointer:coarse, hover:none, 5 touch points), 101 MAP taps
       across all 25 technologies: the distance was on the page 99 times out
       of 99 and on the first screen zero times. Measured here, it landed at
       y=907 in an 852px viewport with about 270px of published-envelope
       detail above it. The envelope is neither deleted nor shortened; it
       moves below the answer it is context for. The measurement paragraph
       names the substation, so nothing above it is needed to read it. It is
       still built before the block is emitted, because link.network_published
       and the topology block both depend on it having been asked for. */
    const publishedHtml = (() => {
      if (!published) return '';
      link.network_published = { name: networkName, site: published.site_code };
      /* The scope label goes FIRST. A site-wide envelope printed under a
         400 kV declared connection reads as a 400 kV result unless the
         reader is told otherwise before the numbers, not after. */
      return `<div class="neon-hd">${escapeHtml(networkName)}`
        + (published.fault_scope === 'bus'
          ? `<span class="neon-beta" style="background:#12323a;color:#8fd8e0">`
            + `${published.fault_kv} kV bus</span>`
          : (published.site_wide
            ? `<span class="neon-beta" style="background:#3a3a2a;color:#d8c96a">Site-wide</span>`
            : ''))
        + `<span class="neon-beta">NESO published</span></div>`
        + `<p class="neon-caveat"><b>${escapeHtml(published.scope_label)}.</b></p>`
        + `<p class="neon-caveat">${escapeHtml(published.sentence)}.</p>`
        + `<p class="neon-caveat">${escapeHtml(published.metrics_not_interchangeable)} `
        + `${escapeHtml(published.attribution)}. `
        + `${escapeHtml(published.not_an_assessment)}</p>`;
    })();
    if (currentNearest400) {
      const n = currentNearest400;
      /* The measurement and everything that makes it honest are ONE element,
         which is why nearestScope(n) is inside the wrapper rather than
         appended after it. Whatever a layout does to this block - move it,
         dock it, put it in a sheet - the number cannot arrive without the
         word "straight", without the corridor estimate's own caveat, and
         without the sentence naming the sample the superlative searched. */
      out += `<div class="neon-answer">`
        + `<p class="neon-caveat"><b>Nearest 400 kV substation:</b> `
        + `${escapeHtml(n.name)} · ${n.km.toFixed(2)} km straight`
        + corridorBeside(n.km)
        + (n.works ? `. ${escapeHtml(n.works)}` : '')
        + (n.named
          ? ` (nearest named: ${escapeHtml(n.named.name)} · ${n.named.km.toFixed(2)} km`
            + (n.named.works ? `. ${escapeHtml(n.named.works)}` : '') + `)`
          : '')
        + `</p>`
        + nearestScope(n)
        + `</div>`;
    }
    out += publishedHtml;
    if (networkName) {
      out += topologyBlockHtml([{ name: networkName, kv: connectionKv }]);
    }
    out += corridorAction();
    return out;
  }

  /* ── the transmission network, on demand ─────────────────────────────
     Vikram: click anywhere and the neons should "look for cartridges and
     code". Until this generation the looking stopped at NESO's connection
     points - one row per site. The node/branch model behind them (ETYS
     Appendix B as Ventusltd/data-grid-gb's gb-transmission-network.v1) was
     indexed by the network-topology module, proven 47/47, and composed
     into nothing: the module was on disk and not in any served cartridge.
     The deep scan of 202609012230 listed it as alive; it was alive the way
     a book on a shelf is.

     The product is ten megabytes. It is NOT fetched at load: a phone on a
     hillside should not pay for it until a click asks a question it
     answers. Fetched once, indexed once by the module, every state on
     __GRIDATLAS_TOPOLOGY__ so the source registry can say whether this
     source answered, and the cards fill in when it arrives rather than
     waiting for it.

     The join from a mapped substation to a published site is BY NAME,
     through the connection-points cartridge's own join, and the block says
     which site it joined to - Codex's WBUR finding stands: exact text
     equality is not exact identity, so the reader is shown the identity. */
  /* Pinned; the table and the reasoning are in the pinned-products module. */
  const PINS = (window.__GRIDATLAS_MODULES__ || {}).pinnedProducts || null;
  const TOPOLOGY_ID = 'gb-transmission-network.v1';
  const TOPOLOGY_PRODUCT = PINS ? PINS.url(TOPOLOGY_ID) : null;
  const TOPOLOGY_BLOCK = 'gridatlas-topology';
  const topology = { state: 'idle', product: TOPOLOGY_PRODUCT, schema: null,
    schema_required: topologyModule()?.accepts || null,
    bytes: null, sites: null, index: null, error: null,
    started_at: null, ready_at: null, blocks_filled: 0 };
  window.__GRIDATLAS_TOPOLOGY__ = topology;

  /* Published so a reviewer can ask the page how many cards the traversal
     actually answered, and how many published branches it refused to walk.
     A refusal is a finding about the data, not a failure of the page. */
  const electrical = { answered: 0, refusals: 0 };
  window.__GRIDATLAS_ELECTRICAL__ = electrical;

  /* How many cards quoted a seasonal rating, and how many placeholder
     values the published record turned out to contain. */
  const rating = { answered: 0, flagged: 0 };
  window.__GRIDATLAS_RATINGS__ = rating;

  /* Published so a reviewer can ask the page whether any answer it gave
     failed its own conservation check. A solve that has not converged
     produces plausible-looking flows that are wrong, so the error is
     surfaced rather than trusted. */
  const powerflow = { answered: 0, refused: 0, worst_kirchhoff_error: 0 };
  window.__GRIDATLAS_POWERFLOW__ = powerflow;

  /* How many point queries the reader ran. A feature nobody can reach is
     indistinguishable from a feature that does not work, and this is the
     number that tells them apart. */
  const pointQuery = { answered: 0 };
  window.__GRIDATLAS_POINT_QUERY__ = pointQuery;

  /* How many cards reported published plans, and how many rows they came
     from. A count of zero where the product has 2,230 rows would mean the
     wiring is broken, not that nothing is planned. */
  const plannedState = { answered: 0, rows: 0 };
  window.__GRIDATLAS_PLANNED__ = plannedState;

  /* How many cards named an owner, and how many seams they found. */
  const ownerState = { answered: 0, seams: 0 };
  window.__GRIDATLAS_OWNERSHIP__ = ownerState;

  /* The layers dash collapses without entering fullscreen.
     ---------------------------------------------------------------------
     The dash is 816 px tall on a desktop and takes most of a phone, and
     the only way past it has been fullscreen - a different mode with a
     different layout, which is a large thing to ask of a reader who just
     wants to see the map. This collapses it in place and leaves a tab to
     bring it back.

     The choice is remembered per browser and every storage access is
     wrapped: a private window, cleared site data or a browser set to
     block storage all throw here, and a thrown error must not take the
     control with it. */
  (function dashCollapse() {
    const KEY = 'gridatlas.dash.collapsed';
    /* HIDE LAYERS collapsed `.dashboard`, which is the whole app: in the
       shipped shell it opens at index.html:22 and holds BOTH
       `.map-container` (line 36, containing #map) and `.scada-wrapper`
       (line 112, the layer keys and legend), so max-height:0 took the WebGL
       canvas down with the checkboxes - and the choice is remembered, so
       the reload a reader reaches for blanked the page again.