GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Grid network and substations / globalgrid2050 / testcode/202609060300/atlas/cartridges

Single-Line Diagram (SLD) Sandbox (part 6)

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

700 lines of JavaScript from globalgrid2050, in 1 file. Topic: Grid network and substations. Section 355 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 geodesy · globalgrid2050 / testcode/202609060300/atlas/cartridges/202609060300-sld-sandbox.js lines 3501–4200

Single-Line Diagram (SLD) Sandbox

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

geodesyglobalgrid2050 / testcode/202609060300/atlas/cartridges/202609060300-sld-sandbox.js · lines 3501–4200 of 7736 · version 2026-09-06 03:00 (continued from section 350) · Not reached from any entry point (candidate for review) · pattern widerFleetBuckets (shared by 6 files)

What it does
It maps grid substations, connection points, GB transmission network and price decade rollup. Defines 233 functions or classes, including distanceKm, representativePoint, voltagesKv, destinationPoint, initialBearingDeg. 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: GeoJSON file grid_substations.geojson; JSON file connection-points.v3.json; JSON file gb-transmission-network.v1.json; JSON file price-decade-rollup.json; browser storage (getItem); DuckDB queries; form fields (user input). 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`), builds stats (`buildStats`) and applies development stage defaults (`applyDevelopmentStageDefaults`). Its `distanceKm` function gives distance km from two coordinate pairs (VEDIC: measure). 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
globalgrid2050 · testcode/202609060300/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, representativePoint, voltagesKv, destinationPoint, initialBearingDeg, copy, finite, located, sameLocation, sameEntity, createComputeObserver, publish
Defines here
createArrivalGate, continueVerifiedArrival, arrivalKey, claimPendingArrival, invalidatePendingArrival, loadSubstations, nearestSubstations, nearestProjects, installStyles, escapeHtml, caveatHtml, kvContext, policyNotesHtml, cardBlockHtml, offshoreNamed, parkingSpot, sheetTarget, dockAsSheet, undockSheet, boundCardToMap, addCardBar, move, up, if, resetCardGeometry, injectIntoCard
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 testcode/202609060300/atlas/cartridges/202609060300-sld-sandbox.js:3501-4200 · blob b9451a6d240116dae04211c0cc8216a75da78ad1 · GitHub at these lines
State
achieves: code · context: readme_derived · stage: output · effects: dom, filesystem, network, storage · domain stage: experimental · users: none · canonical: unreached_review
      && Math.abs(longitude) <= 180 && Math.abs(latitude) <= 90
      && !(Math.abs(longitude) < 1e-9 && Math.abs(latitude) < 1e-9);
    return Object.freeze({
      longitude, latitude, repd_ref: repdRef, coordinates_usable: coordinatesUsable,
      route: coordinatesUsable ? 'MEASURE_LINK_FIRST'
        : (repdRef ? 'WAIT_FOR_REGISTER' : 'NO_USABLE_POINT')
    });
  }
  link.measure.deepLinkPlan = deepLinkPlan;

  /* A resolved register identity is an asynchronous continuation of one
     particular arrival, not permission to take the map back later. User
     selection and clear paths invalidate the token. The same coordinator is
     exported so the generation proof can resolve a deliberately late promise
     through the production gate rather than restating this race in a mock. */
  function createArrivalGate() {
    let epoch = 0;
    let activeKey = null;
    const invalidations = [];
    return Object.freeze({
      begin(key = null) {
        const candidate = key == null ? null : String(key);
        /* The search owner and the measurement owner claim the same URL
           independently as their scripts boot. A keyed claim is idempotent,
           so whichever starts first gives both halves one cancellation
           epoch rather than making the second half stale immediately. */
        if (candidate && candidate === activeKey) return epoch;
        epoch += 1;
        activeKey = candidate;
        return epoch;
      },
      invalidate(reason) {
        epoch += 1;
        activeKey = null;
        invalidations.push({ epoch, reason: String(reason || 'unspecified') });
        return epoch;
      },
      isCurrent(candidate) { return candidate === epoch; },
      snapshot() { return Object.freeze({ epoch, activeKey,
        invalidations: [...invalidations] }); }
    });
  }
  async function continueVerifiedArrival(gate, epoch, verification, apply) {
    const result = await verification;
    if (!gate.isCurrent(epoch)) return false;
    await apply(result);
    return gate.isCurrent(epoch);
  }
  const arrivalGate = createArrivalGate();
  function arrivalKey(search = window.location.search) {
    return 'deep-link:' + String(search || '');
  }
  function claimPendingArrival(search = window.location.search) {
    return arrivalGate.begin(arrivalKey(search));
  }
  function invalidatePendingArrival(reason) {
    const epoch = arrivalGate.invalidate(reason);
    link.arrival_reconciliation = { status: 'INVALIDATED', reason, epoch };
    try {
      window.dispatchEvent(new CustomEvent('gridatlas:arrival-invalidated', {
        detail: { reason: String(reason || 'unspecified'), epoch }
      }));
    } catch (_) { /* cancellation still lives in the shared gate */ }
    return epoch;
  }
  link.measure.createArrivalGate = createArrivalGate;
  link.measure.continueVerifiedArrival = continueVerifiedArrival;
  link.measure.arrivalGate = arrivalGate;
  link.measure.arrivalKey = arrivalKey;
  link.measure.claimPendingArrival = claimPendingArrival;
  link.measure.invalidatePendingArrival = invalidatePendingArrival;
  link.enableSubstationLayer = () => enableSubstationLayer();
  link.armGridScope = (on) => { scopeArmed = Boolean(on); return scopeArmed; };
  link.clearGridScope = () => clearScope();
  link.noteFailure = (message) => noteFailure(message);

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

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

  function nearestSubstations(lon, lat, subs) {
    const scored = [];
    for (const sub of subs) {
      const km = distanceKm(lon, lat, sub.at[0], sub.at[1]);
      if (km > MAX_LINK_KM) continue;
      scored.push({ ...sub, km });
    }
    scored.sort((a, b) => a.km - b.km);
    return scored.slice(0, LINK_COUNT);
  }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  function cardBlockHtml(links, direction, layerLoaded = true) {
    installStyles();
    const toSubstations = direction !== 'from-substation';
    const title = toSubstations
      ? `Nearest substations &ge;${MIN_KV} kV`
      : 'Nearest projects';
    const fallbackName = toSubstations ? 'Unnamed substation' : 'Unnamed project';
    const head = `<div class="neon-hd">${title}<span class="neon-beta">Beta</span></div>`;
    const declaredHtml = declaredBlockHtml(toSubstations);
    if (!links.length) {
      const nothing = toSubstations
        ? `No mapped substation at ${MIN_KV} kV or above within ${MAX_LINK_KM} km of this point.`
        : (layerLoaded
          ? `No mapped project within ${MAX_LINK_KM} km of this substation.`
          : `The project layers are switched off, so there is nothing to measure `
            + `against. Turn on Solar PV, Wind or Battery Storage and click again. `
            + `This is not a statement that no project is here.`);
      return `<div class="${BLOCK_CLASS}">${declaredHtml}${head}`
        + `<div class="neon-caveat">${nothing}</div>${policyNotesHtml()}`
        + `${caveatHtml()}</div>`;
    }
    const rows = links.map(l => {
      const kv = l.kv && l.kv.length ? l.kv[0] : null;
      const tail = kv != null ? `${kv} kV`
        : (l.mw != null ? `${l.mw} MW` : '');
      // What the class generally IS, on hover, beside the number. A distance
      // to 132 kV is not the same proposition as a distance to 66 kV, and the
      // reader of a register usually knows that while the map does not say it.
      const context = kvContext(kv);
      const titled = context
        ? ` title="${escapeHtml(kv + ' kV: ' + context)}"` : '';
      /* A result that is ITSELF named as an offshore substation is marked,
         never removed. The product has no field that separates a platform at
         sea from the onshore substation for an offshore farm, so the honest
         move is to hand the reader the name and the flag rather than to
         filter on a predicate that is wrong four times in fourteen. */
      const offshoreNamed = (() => {
        try { return Boolean(coverage.namedOffshore(l.name)); }
        catch (_) { return false; }
      })();
      const flag = offshoreNamed
        ? `<span class="neon-kv" title="Named as an offshore substation in the `
          + `mapped product. That product carries no field saying whether this `
          + `is a platform at sea or the onshore substation for an offshore `
          + `farm, so it is marked rather than filtered.">named offshore</span>`
        : '';
      return `<li><span class="neon-km">${l.km.toFixed(2)} km</span>`
        + `<span class="neon-name">${escapeHtml(l.name || fallbackName)}</span>`
        + (tail ? `<span class="neon-kv"${titled}>${escapeHtml(tail)}</span>` : '')
        + flag
        + `</li>`;
    }).join('');

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

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

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

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

  function boundCardToMap() {
    if (document.documentElement.classList.contains("testcode-arrival")) return;
    try {
      const container = capturedMap?.getContainer();
      if (!container) return;
      const map = container.getBoundingClientRect();
      const popup = document.querySelector('.maplibregl-popup');
      const content = popup?.querySelector('.maplibregl-popup-content');
      if (!popup || !content) {
        undockSheet();
        document.documentElement.style.setProperty(
          '--gridatlas-card-max', Math.max(160, map.height - 60) + 'px');
        return;
      }
      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.maxHeight = Math.max(120, Math.min(available, map.height - 48)) + 'px';
        return;
      }
      const rect = popup.getBoundingClientRect();
      const available = map.bottom - rect.top - 12;
      if (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.maxHeight = Math.max(160, map.height - 48) + 'px';
        return;
      }
      content.style.maxHeight = available + 'px';
    } 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');
      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) {
    const popup = content?.closest?.('.maplibregl-popup');
    if (!popup) return;
    popup.classList.remove('gridatlas-free');
    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 = '&minus;';
  }

  function injectIntoCard(links, direction, layerLoaded = true) {
    const content = document.querySelector('.maplibregl-popup-content');
    if (!content) return false;
    resetCardGeometry(content);
    addCardBar(content);
    content.querySelector('.testcode-location-source')?.remove();
    const provenance=window.__GRIDATLAS_PLACE_SEARCH__?.deep_link?.location_provenance;
    if(provenance && content.textContent.includes(window.__GRIDATLAS_PLACE_SEARCH__.deep_link.name)){
      const note=document.createElement('p');note.className='testcode-location-source';note.style.cssText='color:#ffd18a;padding:8px;border:1px solid #97783f';note.textContent=provenance.notice+' ';
      const a=document.createElement('a');a.href=provenance.source_item;a.target='_blank';a.rel='noopener';a.textContent='Source';note.append(a);content.insertBefore(note,content.children[1]||null);
    }
    content.querySelectorAll(`.${BLOCK_CLASS}`).forEach(node => node.remove());
    const holder = document.createElement('div');
    holder.innerHTML = cardBlockHtml(links, direction, layerLoaded);
    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);
    // 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