GLOBALGRID2050 / EXPLORE CODE

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

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

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 403 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 4201–4900

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 4201–4900 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
addCardBar, move, up, if, resetCardGeometry, renderComputeReceipt, injectIntoCard, removeArrivalFallback, markArrivalIdentityState, ensureArrivalCard, injectDeclaredOnly, armCardKeeper, disarmCardKeeper, removeCardBlock, emptyCollection, ensureLayers, stopAnimation, startAnimation, step, recordArrivalEngine, clearArrivalEngine, clearLinks, drawLinks
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:4201-4900 · 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
      if (sheetTarget()) { dockAsSheet(popup, content); return; }
      undockSheet();
      if (popup.classList.contains('gridatlas-free')) {
        // A freed card is wherever the user put it, and the same
        // anchor-blindness applies: dragging it low while minimised and then
        // restoring it made it 277px tall starting 88px above the bottom of
        // the map, so it hung 189px underneath. Cap to the room below where it
        // now sits, and if that is not enough, lift it rather than shrink it
        // into a slot.
        const rect = popup.getBoundingClientRect();
        let available = map.bottom - rect.top - 12;
        if (available < MIN_ANCHORED_CARD) {
          const lifted = Math.max(map.top + 12, map.bottom - MIN_ANCHORED_CARD - 12);
          popup.style.setProperty('--gy', lifted + 'px');
          available = map.bottom - lifted - 12;
        }
        content.style.setProperty('max-height', Math.max(120, Math.min(available, map.height - 48)) + 'px', 'important');
        return;
      }
      const rect = popup.getBoundingClientRect();
      const available = map.bottom - rect.top - 12;
      if (rect.top < map.top + 12 || rect.right > map.right - 12 || rect.left < map.left + 12 || available < MIN_ANCHORED_CARD) {
        popup.classList.add('gridatlas-free');
        const parked = parkingSpot(map);
        popup.style.setProperty('--gx', parked.x + 'px');
        popup.style.setProperty('--gy', parked.y + 'px');
        content.style.setProperty('max-height', Math.max(160, map.height - 48) + 'px', 'important');
        return;
      }
      content.style.setProperty('max-height', Math.min(available, map.height - 48) + 'px', 'important');
    } catch (_) { /* leave the CSS default */ }
  }

  function addCardBar(content) {
    if (!content) return;
    // The bar is built once and kept, but the fit is not: a card that already
    // has a bar is a card being reused for a different project, and its height
    // is the one thing that must be measured again.
    if (content.querySelector('.gridatlas-card-bar')) { boundCardToMap(); return; }
    const popup = content.closest('.maplibregl-popup');
    if (!popup) return;
    boundCardToMap();

    // Carry the card's own title into the bar. Minimised, the bar is all that
    // is left, and a nameless strip on a map is a puzzle rather than a card you
    // put down on purpose.
    const heading = content.querySelector('b, strong, h1, h2, h3');
    const title = (heading?.textContent || 'Card').replace(/\s+/g, ' ').trim();

    const bar = document.createElement('div');
    bar.className = 'gridatlas-card-bar';
    bar.innerHTML = '<span class="grip">&#8942;&#8942;</span>'
      + `<span class="label">${escapeHtml(title)}</span>`
      + '<span class="spacer"></span>'
      + '<button type="button" class="min" title="Minimise">&minus;</button>'
      + '<button type="button" class="close" title="Close">&times;</button>';
    content.insertBefore(bar, content.firstChild);

    bar.querySelector('.min').addEventListener('click', (event) => {
      event.stopPropagation();
      popup.classList.toggle('gridatlas-min');
      cardPreference = { key: cardPreferenceKey(), minimised: popup.classList.contains('gridatlas-min') };
      bar.querySelector('.min').innerHTML = popup.classList.contains('gridatlas-min')
        ? '&plus;' : '&minus;';
      // Restoring gives the card its height back, which is exactly when it can
      // fall off the bottom of the map again.
      requestAnimationFrame(boundCardToMap);
    });
    bar.querySelector('.close').addEventListener('click', (event) => {
      event.stopPropagation();
      clearLinks();
      popup.remove();
      // The sheet is what lifted the control stack and hid the credit strip.
      // Closing the card has to put the map back exactly as it was, or the
      // reader is left with a gap where a card used to be.
      undockSheet();
    });

    // Dragging frees the popup from its anchor. Fixed positioning with an
    // explicit left/top beats MapLibre's transform, which it rewrites on every
    // map move; without that the card would snap back the moment you panned.
    let dragging = null;
    bar.addEventListener('pointerdown', (event) => {
      if (event.target.closest('button')) return;
      /* A docked sheet is not dragged. Dragging the bar was the only route
         to the measurement, and it slid the bar - with the minus and the
         close on it - under the map's search box: tapping the close focused
         the search field and opened the keyboard, 3 times out of 3. On a
         sheet the answer is already on screen, so there is nothing to drag
         for, and the bar is pinned where nothing can be laid over it. */
      if (popup.classList.contains('gridatlas-sheet')) return;
      event.stopPropagation();
      event.preventDefault();
      const rect = popup.getBoundingClientRect();
      dragging = {
        pointerId: event.pointerId,
        dx: event.clientX - rect.left,
        dy: event.clientY - rect.top,
      };
      bar.setPointerCapture?.(event.pointerId);
      popup.classList.add('gridatlas-free');
      popup.style.setProperty('--gx', rect.left + 'px');
      popup.style.setProperty('--gy', rect.top + 'px');
    });
    const move = (event) => {
      if (!dragging || event.pointerId !== dragging.pointerId) return;
      event.preventDefault();
      const map = capturedMap?.getContainer()?.getBoundingClientRect()
        || { left: 0, top: 0, right: window.innerWidth, bottom: window.innerHeight };
      const card = popup.getBoundingClientRect();
      const minX = map.left + 4;
      const maxX = Math.max(minX, map.right - card.width - 4);
      const minY = map.top + 4;
      // Keep the whole width and at least the 44px drag bar inside the map.
      const maxY = Math.max(minY, map.bottom - Math.min(44, Math.max(1, card.height)) - 4);
      const x = Math.max(minX, Math.min(maxX, event.clientX - dragging.dx));
      const y = Math.max(minY, Math.min(maxY, event.clientY - dragging.dy));
      popup.style.setProperty('--gx', x + 'px');
      popup.style.setProperty('--gy', y + 'px');
    };
    const up = (event) => {
      if (!dragging || event.pointerId !== dragging.pointerId) return;
      try { bar.releasePointerCapture?.(event.pointerId); } catch (_) { /* already released */ }
      if (dragging) requestAnimationFrame(boundCardToMap);
      dragging = null;
    };
    bar.addEventListener('pointermove', move);
    bar.addEventListener('pointerup', up);
    bar.addEventListener('pointercancel', up);
  }

  /* A second project gets a second card, not the first one's shape.
     ----------------------------------------------------------------------
     Reported: arrive from Pipeline News, then click another solar pixel, and
     the card is the wrong size.

     The popup element is reused between selections, and everything this
     cartridge does to a card was written onto it and never taken off -- the
     max-height computed for the previous card's contents, the gridatlas-free
     class if that one had been freed, the --gx/--gy it was parked at, and the
     minimised state. A card for Botley West would open at the height of the
     card before it, in the place the card before it had been dragged to.

     Worse, addCardBar returns early once the bar exists, and the only call to
     boundCardToMap on that path was inside it. So on every selection after the
     first, nothing measured anything: the stale numbers were not merely
     inherited, they were never recomputed.

     Geometry is per selection. The content is not: the bar, its listeners and
     the drag handlers are kept, because rebuilding them would drop the
     listeners and cost a card that could no longer be moved. */
  function resetCardGeometry(content, linksDrawn = null) {
    const popup = content?.closest?.('.maplibregl-popup');
    if (!popup) return;
    popup.classList.remove('gridatlas-free');
    /* GG-029, GG-027. On a phone the card docks as a full-width sheet over the
       bottom of the map, which is where the engine draws its lines and where
       the layers panel opens. Arriving expanded therefore hid both: the owner
       photographed the layers label flipping with nothing else changing,
       because the panel was opening behind this sheet.

       So on a sheet target the card arrives MINIMISED: its bar, its title and
       its restore control, and nothing else. The reader expands it when they
       want the numbers. Anywhere with room, the card opens as it always did. */
    /* But minimising assumes there is something on the map worth uncovering.
       When the engine answers from beyond the draw radius no lines are drawn,
       so the sheet covers an empty map and the card it hides is the ONLY place
       the answer exists. That is what "it didn't fire" looked like on the
       owner's phone for Berwick Bank: the camera moved, no neon appeared, and
       the one sentence carrying 52.0 km to Neart na Gaoithe was behind a
       collapsed bar. So: minimised when there are lines to see, open when the
       card is the whole answer. */
    const arriveMinimised = cardPreference?.key === cardPreferenceKey()
      ? cardPreference.minimised : (function () {
      /* v9.150 opened the card when nothing was drawn, on the reasoning that
         the card was then the whole answer. The owner's ruling: the card is
         minimised for a project, always - the map is the answer and the sheet
         is the footnote. v9.152 makes that true again by drawing the declared
         connection, so nothing is behind the plus sign that is not also on the
         map. `linksDrawn` is kept in the signature for the callers. */
      void linksDrawn;
      try { return Boolean(sheetTarget()); } catch (_) { return false; }
    })();
    if (arriveMinimised) popup.classList.add('gridatlas-min');
    else popup.classList.remove('gridatlas-min');
    popup.style.removeProperty('--gx');
    popup.style.removeProperty('--gy');
    content.style.removeProperty('max-height');
    content.style.removeProperty('display');
    // The bar's own control has to agree with the class it toggles, or a card
    // restored by this reset still shows a plus that no longer minimises
    // anything. The control is .min and it carries an HTML entity, not text.
    const toggle = content.querySelector('.gridatlas-card-bar .min');
    if (toggle) toggle.innerHTML = arriveMinimised ? '&plus;' : '&minus;';
  }

  function renderComputeReceipt() {
    const content = document.querySelector('.maplibregl-popup-content');
    if (!content || !link.compute_receipt) return;
    let node = content.querySelector('.gridatlas-compute-state');
    if (!node) { node = document.createElement('p'); node.className = 'gridatlas-compute-state'; content.appendChild(node); }
    const presentation = globalThis.VentusGridCompute.describeComputeReceipt(link.compute_receipt);
    node.dataset.status = presentation.status;
    node.dataset.entityId = link.compute_receipt.entity.id;
    node.setAttribute('aria-live', 'polite');
    node.textContent = 'Ventus Grid Engine distance calculation: ' + presentation.text
      + (presentation.reason ? ': ' + presentation.reason : '') + '. ' + presentation.scope;
  }

  function injectIntoCard(links, direction, layerLoaded = true) {
    const content = document.querySelector('.maplibregl-popup-content');
    if (!content) return false;
    resetCardGeometry(content, links.length);
    addCardBar(content);
    content.querySelectorAll(`.${BLOCK_CLASS}`).forEach(node => node.remove());
    const holder = document.createElement('div');
    holder.innerHTML = cardBlockHtml(links, direction, layerLoaded);
    if (link.neso_lookup?.status === 'failed') {
      const notice = document.createElement('p');
      notice.className = 'gridatlas-neso-lookup-status';
      notice.textContent = 'Declared connection lookup unavailable (' + link.neso_lookup.reason
        + '). Nearest distances below are geometric screening only; no electrical connection is inferred.';
      holder.firstElementChild?.appendChild(notice);
    }
    const block = holder.firstElementChild;
    if (!block) return false;
    // Straight onto the content, never onto firstElementChild. Once the grab
    // bar exists it IS the first element, and appending there put the whole
    // block inside the bar: measured live, a bar that should be 30px tall came
    // out at 401px with the card's contents crammed into a flex row.
    content.appendChild(block);
    renderComputeReceipt();
    // The card only has its real height once the block is in it.
    requestAnimationFrame(boundCardToMap);
    block.querySelector?.('.neon-pin')?.addEventListener('click', (event) => {
      event.stopPropagation();
      event.preventDefault();
      const shown = togglePin();
      const control = block.querySelector('.neon-pin');
      if (control) {
        control.textContent = `${shown ? 'Hide' : 'Show'} the project ring`;
        control.setAttribute('aria-pressed', String(shown));
      }
    });
    block.querySelector?.('.neon-layout')?.addEventListener('click', (event) => {
      // The card sits inside the map container, so without this the click
      // carries on to the map, lands on the substation underneath and the
      // substation handler overwrites the layout that was just opened.
      event.stopPropagation();
      event.preventDefault();
      if (!lastSelection || !capturedMap) return;
      // The array goes at the project and the cable runs to the nearest
      // substation found for it, which is the direction a scheme is actually
      // built: generation first, then the route to the network.
      openSldFromProject(capturedMap, lastSelection);
    });
    return true;
  }

  /* ── the card keeper ─────────────────────────────────────────────────
     The measurement block lives inside the popup, and the popup is not
     ours: the search lane creates it when identity resolution completes,
     which on a phone can be seconds after the links were drawn. Watched
     live on the Pipeline News MAP journey: five links on the map, and a
     card with no distances, because the popup that had been decorated was
     replaced by the one that arrived late. The lines live in map layers
     and survived; the block died with the popup.

     So the block is kept, not just written: while a selection is active,
     an observer re-attaches it whenever the current card lacks it. The
     payload is per selection - a new selection re-arms it, a cleared
     selection disarms it, so a radius or measure popup after deselection
     is never decorated with another project's distances. */
  /* ── the arrival card ────────────────────────────────────────────────
     The card on a deep-link arrival was the identity lane's popup, and the
     identity lane resolves against a register that deliberately excludes
     dead-pipeline statuses - Refused, Revised, Withdrawn, Expired,
     Abandoned. Pipeline News rightly reports on exactly those schemes. In
     the exact 0144 corpus, 2,430 of 8,743 unique clickable REPD refs are
     absent from the active snapshot while 6,313 match it; absent arrivals
     drew links and no card at all, which on a phone reads as nothing working.

     The link itself carries the project - name, technology, capacity,
     coordinates - so when no card has appeared by the end of the arrival,
     this cartridge opens one from those fields. It says where it came
     from, and if the register's own card lands later, the fallback yields
     to it rather than standing beside it. */
  let arrivalFallbackPopup = null;

  function removeArrivalFallback() {
    if (!arrivalFallbackPopup) return;
    try { arrivalFallbackPopup.remove(); } catch (_) { /* already gone */ }
    arrivalFallbackPopup = null;
  }

  function markArrivalIdentityState(status, repdRef, message = '') {
    const node = document.querySelector('.gridatlas-arrival-identity');
    if (!node) return;
    const ref = String(repdRef || '').trim();
    node.dataset.state = String(status || 'UNKNOWN');
    if (status === 'NOT_IN_ACTIVE_REGISTER') {
      node.textContent = 'REPD ' + ref + ' · not in the active-register snapshot; '
        + 'project details and point are from the arrival link.';
    } else if (status === 'FAILED') {
      node.textContent = 'REPD ' + ref + ' · active-register check failed'
        + (message ? ': ' + message : '') + '; supplied point retained.';
    } else if (status === 'RESOLVED' || status === 'VERIFIED') {
      node.textContent = 'REPD ' + ref + ' · verified in the active-register snapshot.';
    }
  }

  function ensureArrivalCard(lon, lat, name, tech, statedMw, repdRef, suppliedStatus) {
    if (document.querySelector('.maplibregl-popup-content')) return;
    const gl = window.maplibregl;
    if (!gl?.Popup || !capturedMap) return;
    try {
      const cap = Number.isFinite(statedMw) && statedMw > 0
        ? `${statedMw} MW` : '';
      const ref = String(repdRef || '').trim();
      const status = String(suppliedStatus || '').trim();
      arrivalFallbackPopup = new gl.Popup({ maxWidth: '340px', closeOnClick: false })
        .setLngLat([lon, lat])
        .setHTML('<div style="font-family:monospace;background:#000;padding:6px">'
          + `<b style="color:#00ffff;font-size:13px">${escapeHtml(name)}</b><br>`
          + `<span style="color:#888">${escapeHtml(tech)}</span>`
          + (cap ? `<br><span style="color:#ffae00">${escapeHtml(cap)}</span>` : '')
          + (ref ? `<br><span class="gridatlas-arrival-identity" data-state="PENDING" style="color:#8fb3b8;font-size:10px">REPD ${escapeHtml(ref)} · checking the active-register snapshot</span>` : '')
          + (status ? `<br><span class="gridatlas-arrival-status" style="color:#888;font-size:10px">Status supplied by arrival link: ${escapeHtml(status)}</span>` : '')
          + '<br><span style="color:#555;font-size:9px">Card and point built from the arrival link.</span></div>')
        .addTo(capturedMap);
      link.arrival_card = 'from-link-fields';
      link.arrival_card_identity = {
        repd_ref: ref || null,
        name: String(name || ''),
        technology: String(tech || ''),
        capacity_mw: Number.isFinite(statedMw) && statedMw > 0 ? statedMw : null,
        supplied_status: status || null,
        provenance: 'ARRIVAL_LINK'
      };
    } catch (error) {
      link.failures.push('arrival card: ' + String(error?.message || error));
    }
  }

  function injectDeclaredOnly() {
    const content = document.querySelector('.maplibregl-popup-content');
    if (!content || !currentDeclared) return false;
    if (content.querySelector(`.${BLOCK_CLASS}`)) return false;  // never over a measured block
    try {
      installStyles();
      /* A declared-only card carries no measured lines by definition, so it is
         the whole answer too. */
      resetCardGeometry(content, 0);
      addCardBar(content);
      const holder = document.createElement('div');
      holder.innerHTML = `<div class="${BLOCK_CLASS}">`
        + declaredBlockHtml(true) + caveatHtml() + `</div>`;
      const block = holder.firstElementChild;
      if (!block) return false;
      content.appendChild(block);
      requestAnimationFrame(boundCardToMap);
      link.declared_shown_before_measurement = true;
      return true;
    } catch (error) {
      link.failures.push('provisional card: ' + String(error?.message || error));
      return false;
    }
  }

  let cardKeeper = null;
  let cardKeeperPayload = null;

  function armCardKeeper(links, direction, layerLoaded) {
    cardKeeperPayload = { links, direction, layerLoaded };
    if (cardKeeper || typeof MutationObserver !== 'function') return;
    try {
      cardKeeper = new MutationObserver(() => {
        const payload = cardKeeperPayload;
        if (!payload) return;
        // If the register's own card has landed beside the fallback, the
        // fallback yields: one card, and the resolved one wins.
        if (arrivalFallbackPopup
            && document.querySelectorAll('.maplibregl-popup-content').length > 1) {
          removeArrivalFallback();
        }
        const content = document.querySelector('.maplibregl-popup-content');
        if (!content || content.querySelector(`.${BLOCK_CLASS}`)) return;
        injectIntoCard(payload.links, payload.direction, payload.layerLoaded);
      });
      cardKeeper.observe(document.body, { childList: true, subtree: true });
    } catch (error) {
      link.failures.push('card keeper: ' + String(error?.message || error));
      cardKeeper = null;
    }
  }

  function disarmCardKeeper() {
    cardKeeperPayload = null;
  }

  function removeCardBlock() {
    document.querySelectorAll(`.${BLOCK_CLASS}`).forEach(node => node.remove());
  }

  /* ── the map layers ──────────────────────────────────────────────────── */

  let capturedMap = null;
  let animationHandle = null;
  let dashPhase = 0;

  function emptyCollection() {
    return { type: 'FeatureCollection', features: [] };
  }

  function ensureLayers(map) {
    if (map.getSource(SRC)) return;

    map.addSource(SRC, { type: 'geojson', data: emptyCollection() });
    map.addSource(SRC_NODES, { type: 'geojson', data: emptyCollection() });

    // Three stacked strokes make the neon: a wide soft glow, a bright core, and
    // a dashed overlay whose offset is animated so the line reads as flowing
    // towards the substation.
    map.addLayer({
      id: L_GLOW, type: 'line', source: SRC,
      layout: { 'line-cap': 'round', 'line-join': 'round' },
      paint: {
        'line-color': ['get', 'colour'],
        'line-width': ['interpolate', ['linear'], ['zoom'], 6, 5, 12, 12],
        'line-opacity': 0.10,
        'line-blur': ['interpolate', ['linear'], ['zoom'], 6, 3, 12, 8]
      }
    });
    map.addLayer({
      id: L_CORE, type: 'line', source: SRC,
      layout: { 'line-cap': 'round', 'line-join': 'round' },
      paint: {
        'line-color': ['get', 'colour'],
        'line-width': ['interpolate', ['linear'], ['zoom'], 6, 0.9, 12, 1.8],
        'line-opacity': ['get', 'strength']
      }
    });
    // Two flow layers, half a period apart, so a link reads as a stream of
    // electrons rather than one dot going round.
    map.addLayer({
      id: L_FLOW, type: 'line', source: SRC,
      layout: { 'line-cap': 'round' },
      paint: {
        'line-color': FLOW_COLOUR,
        'line-width': ['interpolate', ['linear'], ['zoom'], 6, 1.2, 12, 2.4],
        'line-opacity': 0.8,
        'line-dasharray': [0.2, 3.2]
      }
    });
    map.addLayer({
      id: L_FLOW_B, type: 'line', source: SRC,
      layout: { 'line-cap': 'round' },
      paint: {
        'line-color': FLOW_COLOUR,
        'line-width': ['interpolate', ['linear'], ['zoom'], 6, 0.9, 12, 1.8],
        'line-opacity': 0.45,
        'line-dasharray': [0.2, 3.2]
      }
    });

    map.addLayer({
      id: L_NODE_RING, type: 'circle', source: SRC_NODES,
      paint: {
        'circle-radius': ['interpolate', ['linear'], ['zoom'], 6, 6, 12, 13],
        'circle-color': 'rgba(0,0,0,0)',
        'circle-stroke-color': SUBSTATION_COLOUR,
        'circle-stroke-width': 1,
        'circle-stroke-opacity': 0.4
      }
    });
    map.addLayer({
      id: L_NODE, type: 'circle', source: SRC_NODES,
      paint: {
        'circle-radius': ['interpolate', ['linear'], ['zoom'], 6, 2.2, 12, 4],
        'circle-color': SUBSTATION_COLOUR,
        'circle-opacity': 0.8
      }
    });
    const neonFont = styleTextFont(map);
    if (!neonFont) {
      link.labels_drawn = false;
      link.failures.push('the basemap serves no glyphs, so link labels are omitted');
    } else {
      // Defer until a glyph range actually comes back. Nothing waits on
      // labels: the links are already drawn and the distances are on the
      // card.
      addLabelLayerWhenDrawable(map, neonFont, {
          id: L_LABEL, type: 'symbol', source: SRC_NODES,
          layout: {
            'text-field': ['get', 'label'],
            'text-size': 10,
            'text-offset': [0, -1.5],
            'text-anchor': 'bottom',
            'text-allow-overlap': false,
            'text-font': neonFont
          },
          paint: {
            'text-color': '#a9c4c9',
            'text-halo-color': '#000c10',
            'text-halo-width': 1.5,
            'text-opacity': 0.9
          }
        }, 'link');
    }
        link.installed = true;
  }

  function stopAnimation() {
    forgetDashMemo();
    if (animationHandle !== null) {
      cancelAnimationFrame(animationHandle);
      animationHandle = null;
    }
  }

  function startAnimation(map) {
    stopAnimation();
    const reduced = window.matchMedia?.('(prefers-reduced-motion: reduce)')?.matches === true;
    link.reduced_motion = reduced;
    if (reduced) {
      // Motion is a preference, not a requirement. The lines, the nodes and
      // every number stay; only the travelling dash stops.
      try {
        map.setPaintProperty(L_FLOW, 'line-opacity', 0);
        map.setPaintProperty(L_FLOW_B, 'line-opacity', 0);
      } catch (_) { /* layer gone */ }
      return;
    }
    const step = () => {
      dashPhase = (dashPhase + FLOW_SPEED) % FLOW_PERIOD;
      const half = (dashPhase + FLOW_PERIOD / 2) % FLOW_PERIOD;
      try {
        setFlowDash(map, L_FLOW, dashPhase);
        setFlowDash(map, L_FLOW_B, half);
      } catch (_) {
        stopAnimation();
        return;
      }
      animationHandle = requestAnimationFrame(step);
    };
    animationHandle = requestAnimationFrame(step);
  }

  /* One writer for the sentinel, at module scope.
     ---------------------------------------------------------------------
     v9.148 introduced `arrival_engine` and wrote it from two places: a
     literal inside drawLinks() and a helper inside install(). Two writers of
     one record is a maintenance trap - an epoch added to one and not the
     other makes the success path and the failure paths disagree - and, worse,
     neither writer existed on the paths where the engine never installs at
     all, which is precisely the "it did not launch" case. So the record has
     one writer, it lives at module scope where every path can reach it, and
     install()'s answerArrival() delegates to it rather than duplicating it.

     It also mirrors to the DOM. A sentinel readable only from the JavaScript
     console is not a surface anyone can open, and the whole point of this
     record is that a person - not just a test - can tell a silent map from a
     broken one. */
  function recordArrivalEngine(engine, answered, reason, fallbackFrom, pending = false) {
    let epoch = null;
    try { epoch = arrivalGate.snapshot().epoch; } catch (_) { epoch = null; }
    /* `reason` is not "why it failed", it is "what happened", and it survives a
       true answer. An arrival answered from beyond the draw radius answered -
       there is a real distance and a real named substation - and it is also a
       materially different answer from one with five lines on the map. v9.148
       carried that distinction and nulling the reason on success would throw it
       away. An unanswered arrival with nothing to say is UNSTATED, which is a
       defect, not a state to be tolerated quietly. */
    /* `terminal` separates "this engine has finished with this arrival" from
       "this engine has taken the arrival and is still working". Without it a
       handover looks exactly like a refusal: an interconnector arrival is
       passed to the interconnector module in the first milliseconds, and a
       reader - or a test - that stops at the first record written would call
       every interconnector in the country unanswered while its measurement was
       still running. A non-terminal record is a receipt, not a verdict. */
    link.arrival_engine = {
      engine: engine || 'onshore',
      answered: Boolean(answered),
      reason: reason || (answered ? null : 'UNSTATED'),
      fallback_from: fallbackFrom || null,
      terminal: !pending,
      epoch,
      at: new Date().toISOString(),
    };
    try {
      capturedMap?.getContainer?.().setAttribute('data-gridatlas-arrival',
        link.arrival_engine.answered ? 'answered' : String(link.arrival_engine.reason));
      capturedMap?.getContainer?.().setAttribute('data-gridatlas-arrival-engine',
        String(link.arrival_engine.engine));
    } catch (_) { /* the object on window is the record; the attribute is a convenience */ }
    return link.arrival_engine;
  }
  link.measure.recordArrivalEngine = recordArrivalEngine;

  function clearArrivalEngine() {
    link.arrival_engine = null;
    try {
      capturedMap?.getContainer?.().removeAttribute('data-gridatlas-arrival');
      capturedMap?.getContainer?.().removeAttribute('data-gridatlas-arrival-engine');
    } catch (_) { /* nothing to clear */ }
  }

  function clearLinks() {
    invalidatePendingArrival('clear');
    stopAnimation();
    const map = capturedMap;
    if (map && map.getSource(SRC)) {
      setSourceData(map, SRC, emptyCollection());
      setSourceData(map, SRC_NODES, emptyCollection());
    }
    disarmCardKeeper();
    removeArrivalFallback();
    removeCardBlock();
    clearPin(capturedMap);
    link.links_drawn = 0;
    clearArrivalEngine();
    link.last_selection = null;
    currentRepdRef = null;
    currentDeclared = null;
    currentNeso = null;
    currentNearest400 = null;
  }

  function drawLinks(map, origin, name, tech, links, direction, statedMw, layerLoaded = true) {
    cardSelectionKey = JSON.stringify([origin, name, tech, direction]);
    ensureLayers(map);
    // A link takes the colour of the project end, whichever end was clicked.
    const colour = direction === 'from-substation'
      ? SUBSTATION_COLOUR
      : (TECH_COLOUR[tech] || SUBSTATION_COLOUR);

    const lines = links.map((l, index) => ({
      type: 'Feature',
      properties: {
        colour,
        // The nearest link burns brightest; the rest fade back in order, so
        // rank is legible without reading the numbers.
        strength: Math.max(0.20, 0.62 - index * 0.10),
        km: l.km
      },
      geometry: { type: 'LineString', coordinates: [origin, l.at] }
    }));

    const nodes = links.map(l => {
      const tail = l.kv && l.kv.length ? `${l.kv[0]} kV`
        : (l.mw != null ? `${l.mw} MW` : '');
      return {
        type: 'Feature',
        properties: {
          colour,
          label: tail ? `${l.km.toFixed(2)} km · ${tail}` : `${l.km.toFixed(2)} km`
        },
        geometry: { type: 'Point', coordinates: l.at }
      };
    });

    if (direction === 'to-substation' && currentDeclared?.at) {
      // The declared link is public record, drawn in its own colour so it
      // never reads as one more nearest-neighbour measurement.
      const unbuilt = currentDeclared.poc_status === 'not_built'
        || currentDeclared.poc_status === 'under_construction';
      const declaredColour = unbuilt ? DECLARED_UNBUILT_COLOUR : DECLARED_COLOUR;
      lines.push({ type: 'Feature',
        properties: { colour: declaredColour, strength: 0.85, km: currentDeclared.km },
        geometry: { type: 'LineString', coordinates: [origin, currentDeclared.at] } });
      nodes.push({ type: 'Feature',
        properties: { colour: declaredColour,
          label: `PoC \u00b7 ${currentDeclared.km.toFixed(2)} km \u00b7 ${currentDeclared.kv} kV` },
        geometry: { type: 'Point', coordinates: currentDeclared.at } });
    }
    /* THE DECLARED CONNECTION IS DRAWN, NOT ONLY PRINTED.
       ------------------------------------------------------------------
       v9.151 read the NESO register and put the connection site on the card,
       and the owner opened Berwick Bank on his phone and saw a dot in the sea
       with a collapsed sheet under it: "didn't fire". He was right. The engine
       had answered - Branxton, 80.57 km - and the answer was a sentence behind
       a plus sign while the map showed nothing at all, because the rule since
       v9.14x is that nothing beyond the 40 km draw radius is drawn.

       That rule exists so a 217 km straight line to whatever happens to be
       nearest is never mistaken for a cable. A declared connection is not
       that. It is the substation the connection authority has contracted this
       project to, so a line to it is a picture of a real thing - drawn in the
       declared gold rather than the neon of a measurement, and labelled as the
       declared connection, so it can never read as one more nearest-neighbour
       result. It stays a straight line and the card still says so. The owner
       then measured it himself along the water via Neart na Gaoithe: 88.56 km
       against this line's 80.57 km straight, which is the difference between a
       route and a chord, and the card names it as a chord. */
    let nesoDrawn = false;
    if (direction === 'to-substation' && currentNeso?.at && !currentDeclared?.at
        && Number.isFinite(currentNeso.km)) {
      lines.push({ type: 'Feature',
        properties: { colour: DECLARED_COLOUR, strength: 0.85, km: currentNeso.km },
        geometry: { type: 'LineString', coordinates: [origin, currentNeso.at] } });