GLOBALGRID2050 / EXPLORE CODE

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

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

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

586 lines of JavaScript from gridatlas, in 1 file. Topic: Grid network and substations. Section 409 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 8401–8986

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 8401–8986 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
openSldFromProject, keepLayersInFullscreen, onChange, installSld, answer, isInterconnectorArrival, rad, haversineKm, searchKm, esc, showLayers, endLine, openCard, arrive, go, measureGb, measureWhenReady, settle, label, measureEnd, paint, boot, ready, go, fit, schedule
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:8401-8986 · 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
    sld.routePins = [];
    redrawSld(map, { fit: true });
  }
  sld.openAt = openSldAt;

  // Opened from a project card. The scheme sits at the project and the export
  // cable runs to the nearest substation the links already found, which is the
  // order a scheme is actually built: generation first, then the route to the
  // network. Falls back to the project's own point if nothing was in range, so
  // the button never does nothing.
  function openSldFromProject(map, selection) {
    return false; // retired: no project-triggered layout
    const nearest = selection.links && selection.links[0];
    if (!nearest) {
      sld.active = false;
      link.failures.push('layout: no substation within '
        + `${MAX_LINK_KM} km of ${selection.name}`);
      return;
    }
    sld.active = true;
    sld.gridNode = nearest.at;
    sld.gridNodeName = nearest.name || 'Grid node';
    sld.gridNodeVoltage = nearest.kv && nearest.kv.length ? `${nearest.kv[0]} kV` : '';
    sld.projectName = selection.name;
    sld.targetMw = selection.statedMw || null;
    // Unstated until the user says. The register's figure is not self-describing
    // and the layout must not pretend otherwise.
    sld.targetBasis = 'unstated';
    // The array starts on the project, not offset from the substation, because
    // the project is the thing that exists.
    sld.arrayCentre = selection.origin;
    sld.rotationDeg = initialBearingDeg(
      nearest.at[0], nearest.at[1], selection.origin[0], selection.origin[1]);
    sld.routePins = [];
    enableSubstationLayer();
    redrawSld(map, { fit: true });
  }
  sld.openFromProject = openSldFromProject;

  /**
   * Keep the layer controls reachable in fullscreen.
   *
   * The shell fullscreens the map element alone, so on desktop every layer
   * checkbox -- the whole dashboard below the map -- vanishes the moment you
   * maximise, and there is no way to turn anything on until you come back out.
   * Mobile carries its own drop-down curtain inside #map-container. When that
   * container is already fullscreen, moving its dashboard ancestor into it
   * would create a DOM cycle and throw HierarchyRequestError.
   *
   * The dashboard node is MOVED into the fullscreen element and moved back on
   * exit, rather than cloned. A clone would look right and do nothing, because
   * every checkbox listener belongs to the original.
   */
  function keepLayersInFullscreen() {
    const dashboard = document.getElementById('dashboard')
      || document.querySelector('.dashboard');
    if (!dashboard) { link.failures.push('fullscreen: dashboard not found'); return; }
    let home = null;

    const onChange = () => {
      const full = document.fullscreenElement;
      /* Relocate only between disjoint trees. If either element contains the
         other, the dashboard is already represented in the fullscreen tree;
         appending an ancestor to its descendant is invalid DOM. */
      if (full && !full.contains(dashboard) && !dashboard.contains(full)) {
        home = { parent: dashboard.parentNode, next: dashboard.nextSibling };
        dashboard.classList.add('gridatlas-fs-layers');
        full.appendChild(dashboard);
      } else if (!full && home) {
        dashboard.classList.remove('gridatlas-fs-layers');
        home.parent.insertBefore(dashboard, home.next);
        home = null;
      }
      boundCardToMap();
    };
    document.addEventListener('fullscreenchange', onChange);
    document.addEventListener('webkitfullscreenchange', onChange);

    const style = document.createElement('style');
    style.textContent = SLD_STYLES.fullscreenLayers();
    document.head.appendChild(style);
  }

  function installSld(map) {
    // Preserve fullscreen layers and corridors, not Layout Sandbox UI.
    try { keepLayersInFullscreen(); }
    catch (error) { link.failures.push('fullscreen: ' + String(error?.message || error)); }
    try { armCorridorGestures(map); }
    catch (error) { link.failures.push('corridor sheet: ' + String(error?.message || error)); }
  }})();

/* ---------------------------------------------------------------------------
   INTERCONNECTORS

   An interconnector is not a generator and it does not arrive anywhere. It has
   two ends, and its connection is already known: it is the thing at the other
   end of its own cable. So this module does not reuse the project arrival at
   all - measured, a BritNed midpoint sits 59.2 km from the nearest substation
   and the far end resolves to Lowestoft at 165.9 km, because our substation
   payload is GB only. Firing the project engine from a midpoint would have
   reported nothing on every link, and matching a Dutch converter to Suffolk
   would have been worse than nothing.

   The model instead is a span with a search budget at each end:

       40km <- Grain --[ BritNed 234.9 km ]-- Maasvlakte -> 40km

   The span is unbounded. The per-end search keeps the ordinary onshore limit
   unless the user widens it with the radius box, and each end states its own
   data coverage so "no substation data for the Netherlands" can never be read
   as "no connection".
   --------------------------------------------------------------------------- */
(function interconnectors() {
  'use strict';

  const SOURCE_ID = 'src-interconnectors';
  const LINE_LAYER = 'l-interconnectors';
  const NODE_LAYER = 'l-interconnector-nodes';
  const DATA_URL = '../../data/interconnectors.geojson';
  const DEFAULT_SEARCH_KM = 40;

  const state = {
    schema: 'gridatlas.interconnectors.v1',
    loaded: false,
    links: [],
    error: null,
    search_km: DEFAULT_SEARCH_KM,
    search_source: 'default',
  };
  window.__GRIDATLAS_INTERCONNECTORS__ = state;

  /* The connection v9.148 built and left unplugged.
     -------------------------------------------------------------------------
     The neon-links lane publishes measure.answerArrival specifically so this
     module can name itself, and nothing ever called it. The project lane
     stands down at the interconnector guard and this lane owns the arrival
     from there, so if this module says nothing, nothing does: an
     interconnector arrival left arrival_engine null in every branch, which is
     the exact signature of an engine that never ran.

     Written through the published surface rather than by reaching into the
     other module's internals, and every call is best-effort: an engine that
     cannot record its answer must still give it. */
  function answer(ok, reason, fallbackFrom) {
    try {
      window.__GRIDATLAS_NEON_LINKS__?.measure?.answerArrival?.(
        'interconnector', Boolean(ok), reason || null, fallbackFrom || null);
    } catch (_) { /* the state object below is still the record */ }
    state.answered = { answered: Boolean(ok), reason: reason || null,
      fallback_from: fallbackFrom || null, at: new Date().toISOString() };
    return state.answered;
  }

  /* Is this arrival ours at all? A page opened with no interconnector in the
     query is not an interconnector arrival, and writing a reason for it would
     overwrite whatever the project engine is doing. */
  function isInterconnectorArrival() {
    try {
      const q = new URLSearchParams(window.location.search);
      return Boolean(q.get('interconnector'))
        || String(q.get('technology') || '') === 'interconnector';
    } catch (_) { return false; }
  }

  const EARTH_KM = 6371.0088;
  const rad = (d) => (d * Math.PI) / 180;
  function haversineKm(lon1, lat1, lon2, lat2) {
    const p1 = rad(lat1), p2 = rad(lat2);
    const dp = rad(lat2 - lat1), dl = rad(lon2 - lon1);
    const a = Math.sin(dp / 2) ** 2 + Math.cos(p1) * Math.cos(p2) * Math.sin(dl / 2) ** 2;
    return 2 * EARTH_KM * Math.asin(Math.sqrt(a));
  }

  /* The radius box is the override, so a widened search is a deliberate and
     attributable choice rather than a different physics applied silently to one
     technology. Onshore keeps its limit until someone types past it. */
  function searchKm() {
    const input = document.getElementById('radius-input');
    const typed = input ? parseFloat(input.value) : NaN;
    if (Number.isFinite(typed) && typed > 0) {
      state.search_km = typed;
      state.search_source = 'radius box';
      return typed;
    }
    state.search_km = DEFAULT_SEARCH_KM;
    state.search_source = 'default';
    return DEFAULT_SEARCH_KM;
  }

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

  function showLayers(map) {
    for (const id of [LINE_LAYER, NODE_LAYER]) {
      try { if (map.getLayer(id)) map.setLayoutProperty(id, 'visibility', 'visible'); } catch (_) { /* style not ready */ }
    }
  }

  function endLine(end, km) {
    if (!end) return 'not held';
    if (end.coverage === 'NONE') return end.statement;
    if (end.nearest_km === null) return 'no substation within the payload';
    return (end.nearest_name || 'nearest substation') + ' at ' + end.nearest_km + ' km'
      + (end.nearest_beyond_search ? ' (beyond the ' + km + ' km search)' : '')
      + ' · ' + end.within + ' within ' + km + ' km';
  }

  function openCard(map, link, at) {
    const gl = window.maplibregl;
    if (!gl || !gl.Popup) { state.arrival.card = 'no maplibregl.Popup'; return; }
    const km = state.search_km;
    const gb = link.ends[0], far = link.ends[1];
    const html = '<div style="font-family:monospace;background:#000;color:#fff;padding:8px 10px;min-width:280px;max-width:420px;font-size:12px;line-height:1.5">'
      + '<div style="font-size:14px"><b>' + esc(link.link) + '</b> · ' + esc(link.bmrs) + ' · interconnector</div>'
      + '<div style="color:#ffae00">' + esc(link.label) + '</div>'
      + '<div><b>GB end</b> ' + esc(endLine(gb, km)) + '</div>'
      + '<div><b>Far end</b> ' + esc(endLine(far, km)) + '</div>'
      + '<div style="color:#a6adbb">straight line converter to converter, ' + esc(link.span_km) + ' km'
      + (link.known_submarine_cable_km ? '; known submarine cable ' + esc(link.known_submarine_cable_km) + ' km' : '')
      + (link.route_factor ? '; route factor ' + esc(link.route_factor) : '') + '</div>'
      + (link.net_direction ? '<div style="color:#a6adbb">' + esc(link.net_direction) + '</div>' : '')
      + '<div style="color:#a6adbb">search budget ' + esc(km) + ' km at each end (' + esc(state.search_source) + '); widen it in the radius box</div>'
      + '</div>';
    try {
      state.arrival.popup = new gl.Popup({ closeOnClick: false, maxWidth: '440px' }).setLngLat(at).setHTML(html).addTo(map);
      state.arrival.card = 'OPEN';
    } catch (error) {
      state.arrival.card = 'popup failed: ' + String(error && error.message || error);
    }
  }

  /* A MAP button on Pipeline News' INTERCONNECTORS tab sends
       ?interconnector=INTNED&technology=interconnector&anchor=midpoint|gb_converter
     with the anchor's coordinate. The project arrival lane hands this over.
     The link is looked up by BMRS code; the span is framed after the shell's
     own flyTo has settled (racing it is a fight the shell wins); the card
     opens on the drawn node with each converter measured within the per-end
     search budget. A link whose far converter is not yet held has no line to
     frame: the map stays at the GB end the link opened on, and the state says
     why rather than measuring anything from anywhere else. */
  function arrive(map, geojson) {
    let q;
    try { q = new URLSearchParams(window.location.search); } catch (_) {
      if (isInterconnectorArrival()) answer(false, 'QUERY_UNREADABLE', null);
      return;
    }
    const code = String(q.get('interconnector') || '').trim().toUpperCase();
    if (!code) {
      /* technology=interconnector with no BMRS code was total silence: the
         project lane stands down at its guard, this lane stands down here, and
         nothing on the page had asked a question or refused one. */
      if (String(q.get('technology') || '') === 'interconnector') {
        answer(false, 'NO_BMRS_CODE', null);
      }
      return;
    }
    state.arrival = { requested: code, anchor: q.get('anchor') || null, status: 'PENDING', card: null };
    showLayers(map);
    const link = state.links.find((l) => String(l.bmrs || '').toUpperCase() === code
      || String(l.link || '').toUpperCase() === code);
    const line = (geojson.features || []).find((f) => f.properties
      && f.properties.feature_role === 'link-line'
      && String(f.properties.bmrs_code || '').toUpperCase() === code);
    const node = (geojson.features || []).find((f) => f.properties
      && f.properties.feature_role === 'midpoint'
      && String(f.properties.bmrs_code || '').toUpperCase() === code);
    if (!link || !line) {
      /* No far converter held, so no line and no span. The link still names
         a GB converter and sends its coordinate: fly there, measure that one
         end against the payload when it arrives, and say plainly that the
         other end is not located. Measured on v9.146's first cut: without
         this the map stayed at zoom 4.2 while the state claimed it had moved. */
      state.arrival.status = 'NOT_DRAWABLE';
      state.arrival.statement = 'No drawable line is held for ' + code
        + ': its far converter is not located yet. Only the GB converter is shown and measured.';
      const lon = Number(q.get('longitude')), lat = Number(q.get('latitude')), z = Number(q.get('zoom'));
      const usable = Number.isFinite(lon) && Number.isFinite(lat) && Math.abs(lon) <= 180 && Math.abs(lat) <= 90
        && !(Math.abs(lon) < 1e-9 && Math.abs(lat) < 1e-9);
      if (!usable) {
        state.arrival.framed = false;
        answer(false, 'FAR_END_NOT_LOCATED_AND_NO_ANCHOR_COORDINATE', 'far_end_converter');
        return;
      }
      const name = q.get('project') || code;
      const go = () => {
        try {
          map.flyTo({ center: [lon, lat], zoom: Number.isFinite(z) ? Math.min(14, Math.max(5, z)) : 10, duration: 600 });
          state.arrival.framed = 'gb_converter';
        } catch (error) { state.arrival.framed = false; state.arrival.frame_error = String(error && error.message || error); }
        const measureGb = (attempt) => {
          const subs = (window.__GRIDATLAS_NEON_LINKS__ || {}).substations || window.__GRIDATLAS_SUBSTATIONS__ || [];
          if (!subs.length && attempt < 120) { setTimeout(() => measureGb(attempt + 1), 500); return; }
          const budget = searchKm();
          const gb = measureEnd('gb', lon, lat, budget, subs);
          state.arrival.ends = [gb, null];
          state.arrival.search_km = budget;
          state.arrival.substations_seen = subs.length;
          state.arrival.waited_ms = attempt * 500;
          /* The GB end has been measured against the published payload. That
             is the answer, and it stands whether or not a popup can be drawn;
             the far converter is a fallback that is named, not a failure. */
          answer(true, 'FAR_END_NOT_LOCATED', 'far_end_converter');
          const gl = window.maplibregl;
          if (!gl || !gl.Popup) { state.arrival.card = 'no maplibregl.Popup'; return; }
          const html = '<div style="font-family:monospace;background:#000;color:#fff;padding:8px 10px;min-width:280px;max-width:420px;font-size:12px;line-height:1.5">'
            + '<div style="font-size:14px"><b>' + esc(name) + '</b> · ' + esc(code) + ' · interconnector</div>'
            + '<div><b>GB end</b> ' + esc(endLine(gb, budget)) + '</div>'
            + '<div style="color:#ffae00">Far converter not located yet: no line is drawn and nothing is measured at that end.</div>'
            + '<div style="color:#a6adbb">search budget ' + esc(budget) + ' km (' + esc(state.search_source) + '); widen it in the radius box</div>'
            + '</div>';
          try {
            state.arrival.popup = new gl.Popup({ closeOnClick: false, maxWidth: '440px' }).setLngLat([lon, lat]).setHTML(html).addTo(map);
            state.arrival.card = 'OPEN';
          } catch (error) { state.arrival.card = 'popup failed: ' + String(error && error.message || error); }
        };
        measureGb(0);
      };
      setTimeout(go, 1200);
      return;
    }
    const [a, b] = line.geometry.coordinates;
    const at = node ? node.geometry.coordinates : [(a[0] + b[0]) / 2, (a[1] + b[1]) / 2];
    let done = false;
    /* The substation payload is 1.2 MB and arrives after the map does; the
       module used to measure at boot against an empty list, so the GB end
       always read "no payload" - measured on v9.143. Wait for the lane's
       published list (up to 60 s), measure both ends, then frame and open. */
    const measureWhenReady = (attempt) => {
      const subs = (window.__GRIDATLAS_NEON_LINKS__ || {}).substations || window.__GRIDATLAS_SUBSTATIONS__ || [];
      if (!subs.length && attempt < 120) { setTimeout(() => measureWhenReady(attempt + 1), 500); return; }
      const budget = searchKm();
      link.ends = [measureEnd('gb', a[0], a[1], budget, subs), measureEnd('far', b[0], b[1], budget, [])];
      link.label = label({ gb_converter: link.gb_converter, far_converter: link.far_converter, link: link.link, straight_line_km: link.span_km }, budget);
      state.arrival.ends = link.ends;
      state.arrival.search_km = budget;
      state.arrival.substations_seen = subs.length;
      state.arrival.waited_ms = attempt * 500;
      try { map.once('idle', settle); } catch (_) { /* shimmed map */ }
      setTimeout(settle, 1500);
    };
    const settle = () => {
      if (done) return;
      done = true;
      try { map.off('idle', settle); } catch (_) { /* shimmed map */ }
      try {
        map.fitBounds([[Math.min(a[0], b[0]), Math.min(a[1], b[1])], [Math.max(a[0], b[0]), Math.max(a[1], b[1])]],
          { padding: 90, duration: 600, maxZoom: 9 });
        state.arrival.framed = true;
      } catch (error) {
        state.arrival.framed = false;
        state.arrival.frame_error = String(error && error.message || error);
      }
      openCard(map, link, at);
      /* Both converters measured, the span framed and the card open. The far
         end is measured against an empty substation set by construction - the
         contract is absent coverage, never absence of connection - so that is
         named as the fallback rather than passed over. */
      const gbEnd = Array.isArray(link.ends) ? link.ends[0] : null;
      answer(true, gbEnd && gbEnd.coverage === 'NONE' ? 'GB_SUBSTATION_PAYLOAD_ABSENT' : null,
        'far_end_substation_coverage');
    };
    measureWhenReady(0);
    state.arrival.status = 'RESOLVED';
    state.arrival.link = link.link;
    state.arrival.bmrs = link.bmrs;
    state.arrival.span_km = link.span_km;
    state.arrival.search_km = state.search_km;
    state.arrival.ends = link.ends;
    state.arrival.at = at;
  }

  // 40km <- Grain --[ BritNed 234.9 km ]-- Maasvlakte -> 40km
  function label(link, km) {
    const gb = String(link.gb_converter || 'GB end').replace(/ (Static Inverter Plant|Converter Station|Substation)$/i, '');
    const far = String(link.far_converter || 'far end').replace(/^HVDC /i, '');
    return `${km}km ← ${gb} ──[ ${link.link} ${link.straight_line_km} km ]── ${far} → ${km}km`;
  }

  /* Each end is measured against the substations we actually hold. The GB end
     is a converter inside a substation compound and scores ~0 km. The far end
     has no payload at all, and that is reported as absent coverage rather than
     as an empty result. */
  function measureEnd(role, lon, lat, km, subs) {
    if (!subs || !subs.length) {
      return { role, lon, lat, search_km: km, coverage: 'NONE',
               statement: 'No substation payload for this end, so nothing can be measured here. This is missing data, not an absence of connection.',
               nearest_km: null, nearest_name: null, within: 0 };
    }
    let nearest = null, within = 0;
    for (const sub of subs) {
      const at = sub.at || sub.coordinates;
      if (!at) continue;
      const d = haversineKm(lon, lat, +at[0], +at[1]);
      if (d <= km) within += 1;
      if (!nearest || d < nearest.km) nearest = { km: d, name: sub.name || null };
    }
    return {
      role, lon, lat, search_km: km, coverage: 'GB_SUBSTATIONS',
      nearest_km: nearest ? Number(nearest.km.toFixed(3)) : null,
      nearest_name: nearest ? nearest.name : null,
      nearest_beyond_search: nearest ? nearest.km > km : null,
      within,
    };
  }

  function paint(map, geojson) {
    if (!map.getSource(SOURCE_ID)) {
      map.addSource(SOURCE_ID, { type: 'geojson', data: geojson });
    } else {
      map.getSource(SOURCE_ID).setData(geojson);
    }
    if (!map.getLayer(LINE_LAYER)) {
      map.addLayer({
        id: LINE_LAYER, type: 'line', source: SOURCE_ID,
        filter: ['==', ['get', 'feature_role'], 'link-line'],
        layout: { visibility: 'none', 'line-cap': 'round' },
        paint: { 'line-color': '#ffae00', 'line-width': 2, 'line-opacity': 0.9, 'line-dasharray': [3, 2] },
      });
    }
    if (!map.getLayer(NODE_LAYER)) {
      map.addLayer({
        id: NODE_LAYER, type: 'circle', source: SOURCE_ID,
        filter: ['==', ['get', 'feature_role'], 'midpoint'],
        layout: { visibility: 'none' },
        paint: { 'circle-radius': 5, 'circle-color': '#ffae00', 'circle-stroke-width': 1, 'circle-stroke-color': '#0b0d10' },
      });
    }
  }

  async function boot(map) {
    let geojson;
    try {
      const absolute = new URL(DATA_URL, document.baseURI).href;
      const body = await new Promise((resolve, reject) => {
        const xhr = new XMLHttpRequest();
        xhr.open("GET", absolute);
        xhr.onload = () => (xhr.status >= 200 && xhr.status < 300)
          ? resolve(xhr.responseText)
          : reject(new Error("HTTP " + xhr.status));
        xhr.onerror = () => reject(new Error("transport failed"));
        xhr.send();
      });
      geojson = JSON.parse(body);
    } catch (error) {
      state.error = 'interconnector data not served: ' + String(error && error.message || error);
      /* arrive() is never reached, so without this an interconnector arrival on
         a page whose data file did not serve is completely silent: the project
         lane stood down at its guard and this lane never started. */
      if (isInterconnectorArrival()) answer(false, 'INTERCONNECTOR_DATA_NOT_SERVED', null);
      return;
    }

    const subs = (window.__GRIDATLAS_NEON_LINKS__ || {}).substations
      || (window.__GRIDATLAS_SUBSTATIONS__ || []);
    const km = searchKm();

    state.links = (geojson.features || [])
      .filter((f) => f.properties && f.properties.feature_role === 'link-line')
      .map((f) => {
        const p = f.properties;
        const [a, b] = f.geometry.coordinates;
        return {
          link: p.link, bmrs: p.bmrs_code, gb_converter: p.gb_converter, far_converter: p.far_converter,
          span_km: p.straight_line_km,
          geometry_kind: p.geometry_kind,
          route_factor: p.route_factor ?? null,
          known_submarine_cable_km: p.known_submarine_cable_km ?? null,
          net_mwh: p.net_mwh ?? null,
          net_direction: p.net_direction ?? null,
          label: label(p, km),
          ends: [
            measureEnd('gb', a[0], a[1], km, subs),
            measureEnd('far', b[0], b[1], km, []),
          ],
        };
      });

    state.loaded = true;
    state.search_km = km;
    paint(map, geojson);
    try { arrive(map, geojson); }
    catch (error) {
      state.error = 'interconnector arrival threw: ' + String(error && error.message || error);
      if (isInterconnectorArrival()) answer(false, 'INTERCONNECTOR_ARRIVAL_THREW', null);
    }
  }

  function ready(map) {
    if (!map) return;
    if (map.loaded && map.loaded()) { boot(map); return; }
    let started = false;
    const go = () => { if (!started) { started = true; boot(map); } };
    map.once('load', go);
    map.once('idle', go);
    const settle = setInterval(() => {
      if (map.loaded && map.loaded()) { clearInterval(settle); go(); }
    }, 500);
    setTimeout(() => clearInterval(settle), 60000);
  }

  const timer = setInterval(() => {
    const map = window.__GRIDATLAS_V9_MAP__;
    if (!map) return;
    clearInterval(timer);
    try { ready(map); }
    catch (error) {
      state.error = String(error && error.message || error);
      if (isInterconnectorArrival()) answer(false, 'INTERCONNECTOR_MODULE_THREW', null);
    }
  }, 400);
  setTimeout(() => {
    clearInterval(timer);
    /* Ninety seconds and no map ever appeared on the window. The module never
       got as far as loading, so nothing below it can speak for it. */
    if (!state.loaded && isInterconnectorArrival()) answer(false, 'NO_MAP_WITHIN_90S', null);
  }, 90000);
})();

/** Keep ordinary feature cards clear of the fixed search/menu controls.
 * Project cards have their own draggable bar and mobile sheet; preserve it.
 */
(() => {
  let queued = false;
  const ordinaryStyles = new WeakMap();
  function fit() {
    queued = false;
    const container = window.__GRIDATLAS_V9_MAP__?.getContainer();
    if (!container) return;
    const map = container.getBoundingClientRect();
    const menu = document.getElementById('gridatlas-menu-bar')?.getBoundingClientRect();
    const search = document.querySelector('.search-bar-wrapper')?.getBoundingClientRect();
    for (const popup of container.querySelectorAll('.maplibregl-popup')) {
      const content = popup.querySelector('.maplibregl-popup-content');
      const close = popup.querySelector('.maplibregl-popup-close-button');
      if (!content || !close) continue;
      if (popup.querySelector('.gridatlas-card-bar') || popup.classList.contains('gridatlas-sheet')) {
        // Arrival cards gain their project bar asynchronously. Give back only
        // styles we still own; do not leave a second decorated close button or
        // an extra 44px header above the project's own controls.
        for (const saved of ordinaryStyles.get(content) || []) {
          if (saved.element.style.getPropertyValue(saved.property) === saved.written) {
            if (saved.previous) saved.element.style.setProperty(saved.property, saved.previous, saved.priority);
            else saved.element.style.removeProperty(saved.property);
          }
        }
        ordinaryStyles.delete(content);
        continue;
      }
      if (!ordinaryStyles.has(content)) {
        ordinaryStyles.set(content, [
          ...['min-width', 'min-height', 'color', 'background', 'border'].map(property => ({element: close, property})),
          {element: content, property: 'padding-top'}
        ].map(saved => ({...saved, previous: saved.element.style.getPropertyValue(saved.property),
          priority: saved.element.style.getPropertyPriority(saved.property)})));
      }
      // A normal feature popup's close control otherwise measures only 20px.
      close.style.minWidth = '44px';
      close.style.minHeight = '44px';
      close.style.color = '#bfe9ee';
      close.style.background = '#0a1a1d';
      close.style.border = '1px solid #2f6f75';
      content.style.paddingTop = '44px';
      for (const saved of ordinaryStyles.get(content)) saved.written = saved.element.style.getPropertyValue(saved.property);
      const top = Math.max(map.top, menu?.bottom || 0, search?.bottom || 0) + 8;
      const bottom = Math.min(map.bottom, window.innerHeight) - 8;
      content.style.setProperty('max-height', Math.max(44, bottom - top - 20) + 'px', 'important');
      const rect = popup.getBoundingClientRect();
      const left = Math.max(map.left + 8, Math.min(rect.left, map.right - rect.width - 8));
      const y = Math.max(top, Math.min(rect.top, bottom - rect.height));
      if (rect.top < top || rect.bottom > bottom || rect.left < map.left || rect.right > map.right) {
        popup.classList.add('gridatlas-free');
        popup.style.setProperty('--gx', left + 'px');
        popup.style.setProperty('--gy', y + 'px');
      }
    }
  }
  function schedule() {
    if (!queued) { queued = true; requestAnimationFrame(fit); }
  }
  // Observe content insertion, not our own style writes.
  new MutationObserver(schedule).observe(document.documentElement, {childList: true, subtree: true});
  window.addEventListener('resize', schedule);
  window.visualViewport?.addEventListener('resize', schedule);
  schedule();
})();