GLOBALGRID2050 / EXPLORE CODE

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

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

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 408 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 7701–8400

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 7701–8400 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
push, ensureSldLayers, animateSld, step, redrawSld, walk, attachSldDragging, beginDrag, moveDrag, release, installSldStyles, sldPanel, normalizeElectricalInput, electricalInputAttributes, financeFieldHtml, moneyText, renderSldPanel, finish, closeSld, openSldAt
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:7701-8400 · 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
    const features = [];
    const push = (geometry, properties) =>
      features.push({ type: 'Feature', geometry, properties });

    // Site boundary, and the grab surface for dragging.
    push({ type: 'Polygon', coordinates: rectPolygon(centre, gridW + SLD.BOUNDARY_BUFFER_KM, gridL + SLD.BOUNDARY_BUFFER_KM, axis) },
      { kind: 'boundary', colour: SLD_COLOUR.boundary });

    // Blocks, laid out from the north-west corner along the axis.
    const ptN = destinationPoint(centre[0], centre[1], gridL / 2, axis);
    const ptNW = destinationPoint(ptN[0], ptN[1], gridW / 2, axis - 90);
    const blocks = [];
    let placed = 0;
    for (let r = 0; r < rows && placed < N; r += 1) {
      for (let c = 0; c < cols && placed < N; c += 1) {
        const across = destinationPoint(ptNW[0], ptNW[1],
          c * blockW + c * gap + blockW / 2, axis + 90);
        const at = destinationPoint(across[0], across[1],
          r * blockL + r * gap + blockL / 2, axis + 180);
        push({ type: 'Polygon', coordinates: rectPolygon(at, blockW, blockL, axis) },
          { kind: 'block', colour: SLD_COLOUR.block });
        blocks.push(at);
        placed += 1;
      }
    }

    // 33 kV collectors: each block drops onto a trunk running up the axis
    // from the customer substation, and the trunk is clipped to the furthest
    // block rather than drawn to the far edge of nothing.
    if (blocks.length) {
      const trunkEnd = destinationPoint(customerSub[0], customerSub[1], gridL, axis);
      let furthest = 0;
      const branches = [];
      for (const at of blocks) {
        const foot = footOnSegment(at[0], at[1], customerSub, trunkEnd);
        furthest = Math.max(furthest,
          distanceKm(customerSub[0], customerSub[1], foot[0], foot[1]));
        branches.push([at, foot]);
      }
      if (furthest > 0) {
        const clipped = destinationPoint(customerSub[0], customerSub[1], furthest, axis);
        push({ type: 'LineString', coordinates: [customerSub, clipped] },
          { kind: 'radial', role: 'collector_trunk', colour: SLD_COLOUR.radial });
      }
      for (const [at, foot] of branches) {
        push({ type: 'LineString', coordinates: [at, foot] },
          { kind: 'radial', role: 'block_branch', colour: SLD_COLOUR.radial });
      }
    }

    // BESS compound alongside the customer substation.
    // The original drawing reads the same topology-local financial BESS MWh
    // that drives CAPEX and revenue. There is no second layout-BESS input.
    const bessMwh = financeNumber(sld.finance[sld.inputs.mode]?.bess_mwh);
    if (bessMwh > 0) {
      const areaKm2 = (bessMwh * SLD.BESS_M2_PER_MWH) / 1e6;
      const w = Math.sqrt(areaKm2 * SLD.BESS_ASPECT);
      const l = areaKm2 / w;
      const at = destinationPoint(customerSub[0], customerSub[1], w / 2 + 0.05, axis - 90);
      push({ type: 'Polygon', coordinates: rectPolygon(at, w, l, axis) },
        { kind: 'bess', colour: SLD_COLOUR.bess });
      push({ type: 'LineString', coordinates: [at, customerSub] },
        { kind: 'radial', role: 'bess_tie', colour: SLD_COLOUR.radial });
    }

    // Export cable: customer substation, through the user's vertices, to the
    // grid node. Measured along its own path, and against the straight line
    // so the detour is visible rather than implied.
    const route = [customerSub, ...sld.routePins, gridNode];
    sld.cableKm = pathLengthKm(route);
    sld.straightKm = distanceKm(customerSub[0], customerSub[1], gridNode[0], gridNode[1]);
    push({ type: 'LineString', coordinates: route },
      { kind: 'cable', colour: SLD_COLOUR.cable, km: sld.cableKm });

    sld.routePins.forEach((at, index) => {
      push({ type: 'Point', coordinates: at },
        { kind: 'pin', index, colour: SLD_COLOUR.pin });
    });

    push({ type: 'Point', coordinates: customerSub },
      { kind: 'node', role: 'customer_substation', colour: SLD_COLOUR.node,
        label: `CUSTOMER SUB · ${stats.production_substation_ac_mva.toFixed(2)} MVA` });
    push({ type: 'Point', coordinates: gridNode },
      { kind: 'node', role: 'grid_node', colour: SLD_COLOUR.node,
        label: `${sld.gridNodeName || 'GRID NODE'}${sld.gridNodeVoltage ? ` · ${sld.gridNodeVoltage}` : ''}` });

    // Rotation handle, off the far edge of the array.
    const handle = destinationPoint(centre[0], centre[1], gridL / 2 + 0.12, axis);
    push({ type: 'Point', coordinates: handle },
      { kind: 'handle', colour: SLD_COLOUR.handle });
    push({ type: 'LineString', coordinates: [centre, handle] },
      { kind: 'radial', role: 'handle_stem', colour: SLD_COLOUR.handle });

    sld.geometry = { centre, customerSub, gridW, gridL, axis, handle, blocks: blocks.length };
    return { type: 'FeatureCollection', features };
  }

  function ensureSldLayers(map) {
    if (map.getSource(SRC_SLD)) return;
    map.addSource(SRC_SLD, { type: 'geojson', data: { type: 'FeatureCollection', features: [] } });

    map.addLayer({ id: SLD_LAYERS.boundary, type: 'fill', source: SRC_SLD,
      filter: ['==', ['get', 'kind'], 'boundary'],
      paint: { 'fill-color': SLD_COLOUR.boundary, 'fill-opacity': 0.07 } });
    map.addLayer({ id: SLD_LAYERS.boundaryLine, type: 'line', source: SRC_SLD,
      filter: ['==', ['get', 'kind'], 'boundary'],
      paint: { 'line-color': SLD_COLOUR.boundary, 'line-width': 1.2, 'line-opacity': 0.65 } });
    map.addLayer({ id: SLD_LAYERS.block, type: 'fill', source: SRC_SLD,
      filter: ['==', ['get', 'kind'], 'block'],
      paint: { 'fill-color': SLD_COLOUR.block, 'fill-opacity': 0.16,
        'fill-outline-color': SLD_COLOUR.block } });
    map.addLayer({ id: SLD_LAYERS.bess, type: 'fill', source: SRC_SLD,
      filter: ['==', ['get', 'kind'], 'bess'],
      paint: { 'fill-color': SLD_COLOUR.bess, 'fill-opacity': 0.22,
        'fill-outline-color': SLD_COLOUR.bess } });

    map.addLayer({ id: SLD_LAYERS.radial, type: 'line', source: SRC_SLD,
      filter: ['==', ['get', 'kind'], 'radial'],
      layout: { 'line-cap': 'round' },
      paint: { 'line-color': ['get', 'colour'], 'line-width': 0.9, 'line-opacity': 0.5 } });
    // The electron flow, on the collectors.
    map.addLayer({ id: SLD_LAYERS.radialFlow, type: 'line', source: SRC_SLD,
      filter: ['all', ['==', ['get', 'kind'], 'radial'], ['!=', ['get', 'role'], 'handle_stem']],
      layout: { 'line-cap': 'round' },
      paint: { 'line-color': FLOW_COLOUR, 'line-width': 1.3, 'line-opacity': 0.65,
        'line-dasharray': [0.2, 3.2] } });

    map.addLayer({ id: SLD_LAYERS.cableGlow, type: 'line', source: SRC_SLD,
      filter: ['==', ['get', 'kind'], 'cable'],
      layout: { 'line-cap': 'round', 'line-join': 'round' },
      paint: { 'line-color': SLD_COLOUR.cable, 'line-width': 8, 'line-opacity': 0.12,
        'line-blur': 5 } });
    map.addLayer({ id: SLD_LAYERS.cable, type: 'line', source: SRC_SLD,
      filter: ['==', ['get', 'kind'], 'cable'],
      layout: { 'line-cap': 'round', 'line-join': 'round' },
      paint: { 'line-color': SLD_COLOUR.cable, 'line-width': 1.8, 'line-opacity': 0.85 } });
    map.addLayer({ id: SLD_LAYERS.cableFlow, type: 'line', source: SRC_SLD,
      filter: ['==', ['get', 'kind'], 'cable'],
      layout: { 'line-cap': 'round' },
      paint: { 'line-color': FLOW_COLOUR, 'line-width': 2.4, 'line-opacity': 0.9,
        'line-dasharray': [0.2, 3.2] } });
    map.addLayer({ id: SLD_LAYERS.cableFlowB, type: 'line', source: SRC_SLD,
      filter: ['==', ['get', 'kind'], 'cable'],
      layout: { 'line-cap': 'round' },
      paint: { 'line-color': FLOW_COLOUR, 'line-width': 1.6, 'line-opacity': 0.55,
        'line-dasharray': [0.2, 3.2] } });

    map.addLayer({ id: SLD_LAYERS.node, type: 'circle', source: SRC_SLD,
      filter: ['==', ['get', 'kind'], 'node'],
      paint: { 'circle-radius': 5, 'circle-color': SLD_COLOUR.node,
        'circle-stroke-color': '#000c10', 'circle-stroke-width': 1.5 } });
    map.addLayer({ id: SLD_LAYERS.pin, type: 'circle', source: SRC_SLD,
      filter: ['==', ['get', 'kind'], 'pin'],
      paint: { 'circle-radius': 5, 'circle-color': SLD_COLOUR.pin, 'circle-opacity': 0.9,
        'circle-stroke-color': '#04343a', 'circle-stroke-width': 1.5 } });
    map.addLayer({ id: SLD_LAYERS.handle, type: 'circle', source: SRC_SLD,
      filter: ['==', ['get', 'kind'], 'handle'],
      paint: { 'circle-radius': 6, 'circle-color': 'rgba(0,0,0,0)',
        'circle-stroke-color': SLD_COLOUR.handle, 'circle-stroke-width': 1.8 } });
    const sldFont = styleTextFont(map);
    if (!sldFont) {
      link.failures.push('the basemap serves no glyphs, so layout labels are omitted');
    } else {
      addLabelLayerWhenDrawable(map, sldFont, { id: SLD_LAYERS.label, type: 'symbol', source: SRC_SLD,
        filter: ['==', ['get', 'kind'], 'node'],
        layout: { 'text-field': ['get', 'label'], 'text-size': 9.5,
          'text-offset': [0, -1.4], 'text-anchor': 'bottom',
          'text-font': sldFont },
        paint: { 'text-color': '#a9c4c9', 'text-halo-color': '#000c10',
          'text-halo-width': 1.5 } }, 'layout');
    }
  }

  let sldFlowHandle = null;
  let sldPhase = 0;
  function animateSld(map) {
    if (sldFlowHandle !== null) cancelAnimationFrame(sldFlowHandle);
    if (window.matchMedia?.('(prefers-reduced-motion: reduce)')?.matches) {
      try {
        map.setPaintProperty(SLD_LAYERS.cableFlow, 'line-opacity', 0);
        map.setPaintProperty(SLD_LAYERS.cableFlowB, 'line-opacity', 0);
        map.setPaintProperty(SLD_LAYERS.radialFlow, 'line-opacity', 0);
      } catch (_) { /* layer gone */ }
      return;
    }
    const step = () => {
      sldPhase = (sldPhase + FLOW_SPEED) % FLOW_PERIOD;
      const half = (sldPhase + FLOW_PERIOD / 2) % FLOW_PERIOD;
      try {
        setFlowDash(map, SLD_LAYERS.cableFlow, sldPhase);
        setFlowDash(map, SLD_LAYERS.cableFlowB, half);
        setFlowDash(map, SLD_LAYERS.radialFlow, sldPhase);
      } catch (_) { sldFlowHandle = null; return; }
      sldFlowHandle = requestAnimationFrame(step);
    };
    sldFlowHandle = requestAnimationFrame(step);
  }

  function redrawSld(map, { fit = false } = {}) {
    ensureSldLayers(map);
    const data = buildLayout();
    setSourceData(map, SRC_SLD, data);
    renderSldPanel();
    if (data.features.length) animateSld(map);
    if (fit && data.features.length && sld.geometry) {
      const lons = []; const lats = [];
      for (const f of data.features) {
        const walk = (c) => {
          if (typeof c[0] === 'number') { lons.push(c[0]); lats.push(c[1]); return; }
          c.forEach(walk);
        };
        walk(f.geometry.coordinates);
      }
      map.fitBounds([[Math.min(...lons), Math.min(...lats)],
        [Math.max(...lons), Math.max(...lats)]], { padding: 70, duration: 700 });
    }
  }

  /* ── dragging ────────────────────────────────────────────────────────── */

  function attachSldDragging(map) {
    const canvas = map.getCanvas();
    const grabbable = [SLD_LAYERS.handle, SLD_LAYERS.pin, SLD_LAYERS.boundary];

    map.on('mousemove', (event) => {
      if (!sld.active || sld.dragging) return;
      const hits = map.queryRenderedFeatures(event.point, { layers: grabbable.filter(id => map.getLayer(id)) });
      canvas.style.cursor = hits.length ? 'grab' : '';
    });

    const beginDrag = (event) => {
      if (!sld.active || sld.dragging || fromOwnUi(event)) return;
      const layers = grabbable.filter(id => map.getLayer(id));
      if (!layers.length) return;
      const hits = map.queryRenderedFeatures(event.point, { layers });
      if (!hits.length) return;
      const kind = hits[0].properties?.kind;
      let nextDrag = null;
      if (kind === 'handle') nextDrag = { what: 'rotate' };
      else if (kind === 'pin') nextDrag = { what: 'pin', index: Number(hits[0].properties.index) };
      else if (kind === 'boundary') nextDrag = { what: 'array' };
      else return;
      nextDrag.dragPanWasEnabled = map.dragPan.isEnabled?.() !== false;
      nextDrag.touchWasEnabled = map.touchZoomRotate?.isEnabled?.() !== false;
      sld.dragging = nextDrag;
      event.preventDefault();
      map.dragPan.disable();
      map.touchZoomRotate?.disable();
      canvas.style.cursor = 'grabbing';
    };
    map.on('mousedown', beginDrag);
    map.on('touchstart', beginDrag);

    const moveDrag = (event) => {
      if (!sld.dragging) return;
      event.preventDefault();
      const at = [event.lngLat.lng, event.lngLat.lat];
      if (sld.dragging.what === 'array') {
        sld.arrayCentre = at;
      } else if (sld.dragging.what === 'rotate') {
        const c = sld.geometry?.centre;
        if (c) sld.rotationDeg = initialBearingDeg(c[0], c[1], at[0], at[1]);
      } else if (sld.dragging.what === 'pin') {
        sld.routePins[sld.dragging.index] = at;
      }
      redrawSld(map);
    };
    map.on('mousemove', moveDrag);
    map.on('touchmove', moveDrag);

    const release = () => {
      if (!sld.dragging) return;
      const finished = sld.dragging;
      sld.dragging = null;
      if (finished.dragPanWasEnabled) map.dragPan.enable();
      if (finished.touchWasEnabled) map.touchZoomRotate?.enable();
      canvas.style.cursor = '';
    };
    map.on('mouseup', release);
    map.on('touchend', release);
    map.on('mouseout', release);
    canvas.addEventListener?.('pointercancel', release);

    // Click the cable to insert a vertex where you clicked; double-click a
    // vertex to remove it. No modes, no commit step.
    map.on('click', (event) => {
      if (fromOwnUi(event)) return;
      if (!sld.active || !map.getLayer(SLD_LAYERS.cable)) return;
      const onPin = map.queryRenderedFeatures(event.point, { layers: [SLD_LAYERS.pin] });
      if (onPin.length) return;
      const onCable = map.queryRenderedFeatures(event.point, { layers: [SLD_LAYERS.cable] });
      if (!onCable.length) return;
      const at = [event.lngLat.lng, event.lngLat.lat];
      const route = [sld.geometry.customerSub, ...sld.routePins, sld.gridNode];
      let best = 0; let bestKm = Infinity;
      for (let i = 0; i < route.length - 1; i += 1) {
        const km = distanceToSegmentKm(at[0], at[1], route[i][0], route[i][1],
          route[i + 1][0], route[i + 1][1]).km;
        if (km < bestKm) { bestKm = km; best = i; }
      }
      sld.routePins.splice(best, 0, at);
      redrawSld(map);
    });

    map.on('dblclick', (event) => {
      if (!sld.active || !map.getLayer(SLD_LAYERS.pin)) return;
      const hits = map.queryRenderedFeatures(event.point, { layers: [SLD_LAYERS.pin] });
      if (!hits.length) return;
      event.preventDefault();
      sld.routePins.splice(Number(hits[0].properties.index), 1);
      redrawSld(map);
    });
  }

  /* ── the panel ───────────────────────────────────────────────────────── */

  const PANEL_ID = 'gridatlas-sld-panel';

  function installSldStyles() {
    if (document.getElementById('gridatlas-sld-css')) return;
    const style = document.createElement('style');
    style.id = 'gridatlas-sld-css';
    style.textContent = SLD_STYLES.sldPanel(PANEL_ID);
    document.head.appendChild(style);
  }

  function sldPanel() {
    let el = document.getElementById(PANEL_ID);
    if (el) return el;
    installSldStyles();
    el = document.createElement('div');
    el.id = PANEL_ID;
    (capturedMap?.getContainer() || document.body).appendChild(el);
    return el;
  }

  const ELECTRICAL_RULES = Object.freeze({
    mod_wp: { min: 1, step: 1, integer: true },
    mod_l: { min: 0.01, step: 0.01 },
    mod_w: { min: 0.01, step: 0.01 },
    gcr: { min: 0.01, max: 1, step: 0.01 },
    gross_factor: { min: 1, step: 0.05 },
    x_mods: { min: 1, step: 1, integer: true },
    z_strings: { min: 1, step: 1, integer: true },
    y_invs: { min: 1, step: 1, integer: true },
    s_subs: { min: 1, step: 1, integer: true },
    b_cols: { min: 1, step: 1, integer: true },
    string_inv_kva: { min: 1, step: 1 },
    string_skid_mva: { min: 0.1, step: 0.01 },
    dc_ac_ratio: { min: 0.01, step: 0.05 },
    mod_wp_c: { min: 1, step: 1, integer: true },
    mod_l_c: { min: 0.01, step: 0.01 },
    mod_w_c: { min: 0.01, step: 0.01 },
    gcr_c: { min: 0.01, max: 1, step: 0.01 },
    gross_factor_c: { min: 1, step: 0.05 },
    x_mods_c: { min: 1, step: 1, integer: true },
    str_per_cb_c: { min: 1, step: 1, integer: true },
    inv_ac_mw_c: { min: 0.1, max: 20, step: 0.01 },
    inv_dc_mw_c: { min: 0.1, max: 30, step: 0.01 },
    central_skid_mva_c: { min: 0.1, max: 25, step: 0.01 },
    inv_per_mv_c: { min: 1, step: 1, integer: true },
    mv_per_ring_c: { min: 1, step: 1, integer: true },
    rings_c: { min: 1, step: 1, integer: true },
  });

  function normalizeElectricalInput(key, rawValue) {
    const rule = ELECTRICAL_RULES[key];
    const value = Number(rawValue);
    if (!rule || !Number.isFinite(value)) return null;
    if (value < rule.min || (rule.max != null && value > rule.max)) return null;
    if (rule.integer && !Number.isInteger(value)) return null;
    return value;
  }

  function electricalInputAttributes(key) {
    const rule = ELECTRICAL_RULES[key];
    return `min="${rule.min}"${rule.max == null ? '' : ` max="${rule.max}"`} step="${rule.step}"`;
  }
  sld.normalizeElectricalInput = normalizeElectricalInput;

  const FIELDS_STRING = [
    ['mod_wp', 'Module rating Wp'], ['mod_l', 'Module length m'], ['mod_w', 'Module width m'],
    ['gcr', 'Ground cover ratio'], ['gross_factor', 'Gross site factor'],
    ['x_mods', 'Modules / string'], ['z_strings', 'Strings / inverter'],
    ['y_invs', 'Inverters / skid'], ['s_subs', 'Skids / ring main'], ['b_cols', 'Ring main circuits'],
    ['string_inv_kva', 'String inverter kVA'], ['string_skid_mva', 'Skid transformer MVA'],
    ['dc_ac_ratio', 'DC/AC ratio']
  ];
  const FIELDS_CENTRAL = [
    ['mod_wp_c', 'Module rating Wp'], ['mod_l_c', 'Module length m'], ['mod_w_c', 'Module width m'],
    ['gcr_c', 'Ground cover ratio'], ['gross_factor_c', 'Gross site factor'],
    ['x_mods_c', 'Modules / string'], ['str_per_cb_c', 'Strings / combiner'],
    ['inv_ac_mw_c', 'Inverter AC MW'], ['inv_dc_mw_c', 'Inverter DC MWp'],
    ['central_skid_mva_c', 'Skid MVA'], ['inv_per_mv_c', 'Inverters / MV'],
    ['mv_per_ring_c', 'MV / ring'], ['rings_c', 'Rings']
  ];

  const FINANCE_FIELDS = [
    ['@', 'Revenue and operating case'],
    ['price', 'Energy price GBP/MWh'], ['other', 'Other income GBP/MWh'],
    ['yield', 'Base yield kWh/kWp'], ['bifacial', 'Bifacial gain %'],
    ['losses', 'Base losses %'], ['deg', 'Degradation %'], ['opex', 'OPEX GBP/MWac/yr'],
    ['@', 'CAPEX'],
    ['modules', 'Modules GBP/Wp'], ['epc_ex', 'EPC ex modules GBP/Wp'],
    ['flood', 'Flood resilience', 'checkbox'], ['flood_rate', 'Flood adder GBP/Wp'],
    ['other_capex', 'Other CAPEX GBP/Wp'], ['fixed_capex', 'Fixed CAPEX GBP'],
    ['cont', 'Contingency %'],
    ['@', 'Electrical loss allowances'],
    ['loss_dc_string', 'DC string loss %'], ['loss_lv_dc', 'LV main DC loss %'],
    ['loss_lv_ac', 'LV AC loss %'], ['loss_tx', 'Transformer loss %'],
    ['loss_other', 'Other electrical loss %'],
    ['@', 'BESS finance'],
    ['bess_mw', 'BESS power MW'], ['bess_mwh', 'BESS energy MWh'],
    ['bess_capex', 'BESS CAPEX GBP/MWh'], ['bess_cycles', 'BESS cycles / year'],
    ['bess_spread', 'BESS revenue GBP/MWh'], ['bess_eff', 'BESS efficiency %'],
    ['@', 'Development case'],
    ['dev_stage', 'Development stage', 'stage'], ['dev_cost_mw', 'Development cost GBP/Wp'],
    ['dev_module_mwp', 'Module supply GBP/Wp'], ['dev_epc_mw', 'EPC cost GBP/Wp'],
    ['dev_owner_mw', 'Owner costs GBP/Wp'], ['dev_grid_mw', 'Grid connection GBP/Wp'],
    ['dev_exit_mwp', 'Target exit value GBP/Wp'], ['dev_npv_mwp', 'Operating NPV GBP/Wp'],
    ['dev_success', 'Success probability %'], ['dev_years', 'Development years'],
  ];

  const financeFieldHtml = (field, values) => {
    const [key, label, kind] = field;
    if (key === '@') return `<div class="sld-fin-section">${escapeHtml(label)}</div>`;
    if (kind === 'checkbox') {
      return `<label for="sld_fin_${key}">${escapeHtml(label)}</label>`
        + `<input id="sld_fin_${key}" data-fin-key="${key}" type="checkbox" ${values[key] ? 'checked' : ''}>`;
    }
    if (kind === 'stage') {
      const options = Object.entries(DEVELOPMENT_STAGES).map(([value, text]) =>
        `<option value="${value}" ${String(values[key]) === value ? 'selected' : ''}>${escapeHtml(text)}</option>`
      ).join('');
      return `<label for="sld_fin_${key}">${escapeHtml(label)}</label>`
        + `<select id="sld_fin_${key}" data-fin-key="${key}">${options}</select>`;
    }
    const maximum = key === 'bess_eff' || key === 'dev_success' ? ' max="100"' : '';
    return `<label for="sld_fin_${key}">${escapeHtml(label)}</label>`
      + `<input id="sld_fin_${key}" data-fin-key="${key}" type="number" min="0"${maximum} step="any" value="${values[key]}">`;
  };

  const moneyText = value => `GBP ${Math.round(financeNumber(value)).toLocaleString('en-GB')}`;

  function renderSldPanel() {
    return; // retired: layout panel never mounted
    const el = sldPanel();
    const s = sld.stats;
    const fields = sld.inputs.mode === 'string' ? FIELDS_STRING : FIELDS_CENTRAL;
    const financeInputs = sld.finance[sld.inputs.mode];
    const finance = s?.finance;
    const detour = sld.straightKm > 0 ? sld.cableKm / sld.straightKm : 1;
    const acres = s ? s.gross_site_area_m2 / SLD.M2_PER_ACRE : 0;

    el.innerHTML = `
      <h4 class="sld-drag">Layout sandbox<span class="sld-beta">Beta</span>
        <button class="sld-min" title="Minimise">&minus;</button>
        <button class="sld-close" title="Close">&times;</button></h4>
      <div class="sld-site">${escapeHtml(sld.projectName || sld.gridNodeName || 'Grid node')}</div>
      ${sld.projectName ? `<div class="sld-to">to ${escapeHtml(sld.gridNodeName || 'grid node')}`
        + `${sld.gridNodeVoltage ? ` &middot; ${escapeHtml(sld.gridNodeVoltage)}` : ''}</div>` : ''}
      <div class="sld-tabs">
        <button data-mode="string" data-on="${sld.inputs.mode === 'string'}">String</button>
        <button data-mode="central" data-on="${sld.inputs.mode === 'central'}">Central</button>
      </div>
      ${sld.targetMw ? `
      <div class="sld-target">
        <div class="sld-target-row"><span>Register states</span><b>${sld.targetMw} MW</b></div>
        <div class="sld-basis">
          <span>That figure is</span>
          <select id="sld_basis">
            <option value="unstated" ${sld.targetBasis === 'unstated' ? 'selected' : ''}>not stated</option>
            <option value="ac" ${sld.targetBasis === 'ac' ? 'selected' : ''}>AC export MW</option>
            <option value="dc" ${sld.targetBasis === 'dc' ? 'selected' : ''}>DC MWp</option>
          </select>
        </div>
        ${sld.targetBasis === 'unstated'
          ? `<div class="sld-danger">REPD does not reliably distinguish AC from DC.
               Its figure is nominally MWelec, but schemes report it both ways and the
               register does not carry the distinction. Nothing is fitted until you say
               which this is: matching AC when the figure was DC oversizes the
               connection by the DC/AC ratio, and that is the error that drives export
               limitation, curtailment and the size of the offer.</div>`
          : `<div class="sld-fitted">Fitted to ${sld.targetBasis === 'ac' ? 'AC export' : 'DC'} by
               ${sld.inputs.mode === 'string' ? 'ring main circuits' : 'rings'}
               ${sld.fitResidualPct != null
                 ? `&middot; <b class="${Math.abs(sld.fitResidualPct) > 5 ? 'sld-off' : ''}">${sld.fitResidualPct >= 0 ? '+' : ''}${sld.fitResidualPct.toFixed(1)}%</b> against the stated figure`
                 : ''}.
               Ratings, string length and module choice are untouched.</div>`}
      </div>` : ''}
      <div class="sld-grid">
        ${fields.map(([key, label]) =>
          `<label for="sld_${key}">${label}</label>`
          + `<input id="sld_${key}" data-key="${key}" type="number" ${electricalInputAttributes(key)} value="${sld.inputs[key]}">`
        ).join('')}
      </div>
      <div class="sld-out">
        <span>Array DC</span><b>${s ? s.dc_mwp.toFixed(1) : '0.0'} MWp</b>
        <span>Inverter AC</span><b>${s?.consistency?.inverter_ac_mw != null
          ? s.consistency.inverter_ac_mw.toFixed(1) : '0.0'} MW</b>
        <span>Export limit</span><b>${s?.consistency?.export_mva != null
          ? s.consistency.export_mva.toFixed(1) : '0.0'} MVA</b>
        <span>Design DC/AC</span><b>${s?.consistency?.design_dc_ac != null
          ? s.consistency.design_dc_ac.toFixed(2) : '0.00'}</b>
        <span>DC / export</span><b>${s?.consistency?.export_dc_ac != null
          ? s.consistency.export_dc_ac.toFixed(2) : '0.00'}</b>
        <span>Inverter / export</span><b>${s?.consistency?.inverter_to_export != null
          ? s.consistency.inverter_to_export.toFixed(2) : '0.00'}</b>
        <span>Modules</span><b>${s ? s.module_count.toLocaleString('en-GB') : '0'}</b>
        <span>Blocks</span><b>${s ? s.total_blocks : 0}</b>
        <span>Gross site</span><b>${acres.toFixed(0)} acres</b>
        <span>Ring main</span><b>${s ? s.ring_main_ac_mva.toFixed(2) : '0.00'} MVA</b>
        <span class="lit">Export cable</span><b class="lit">${sld.cableKm.toFixed(3)} km</b>
        <span>Straight line</span><b>${sld.straightKm.toFixed(3)} km</b>
        <span>Detour factor</span><b>${detour.toFixed(2)}&times;</b>
        <span>Route vertices</span><b>${sld.routePins.length}</b>
        <span>Rotation</span><b>${normBearing(sld.rotationDeg).toFixed(0)}&deg;</b>
      </div>
      ${(() => {
        const c = s?.consistency;
        if (!(c?.stated_dc_ac > 0) || !(c?.design_dc_ac > 0)) return '';
        if (Math.abs(c.design_dc_ac - c.stated_dc_ac) / c.stated_dc_ac <= 0.05) return '';
        return `<div class="sld-ratio-note">Entered DC/AC ${c.stated_dc_ac.toFixed(2)}; `
          + `the equipment counts and ratings shown give ${c.design_dc_ac.toFixed(2)}. `
          + `Both values remain visible and no input is changed automatically.</div>`;
      })()}
      ${s && s.warning ? `<div class="sld-warn">${escapeHtml(s.warning)}</div>` : ''}
      <details class="sld-finance" ${sld.financeOpen ? 'open' : ''}>
        <summary>Financial screening inputs and outputs</summary>
        <div class="sld-fin-out">
          <span>Year 1 revenue</span><b>${moneyText(finance?.annualRevenue)}</b>
          <span>25-year revenue</span><b>${moneyText(finance?.revenue25)}</b>
          <span>35-year revenue</span><b>${moneyText(finance?.revenue35)}</b>
          <span>Total CAPEX</span><b>${moneyText(finance?.totalCapex)}</b>
          <span>CAPEX / Wp</span><b>GBP ${financeNumber(finance?.capexPerWp).toFixed(2)}</b>
          <span>25-year surplus</span><b>${moneyText(finance?.surplus25)}</b>
          <span>35-year surplus</span><b>${moneyText(finance?.surplus35)}</b>
          <span>Development capital at risk</span><b>${moneyText(finance?.devCapitalAtRisk)}</b>
          <span>Total build cost</span><b>${moneyText(finance?.devTotalBuildCost)}</b>
          <span>Target exit value</span><b>${moneyText(finance?.devExitValue)}</b>
          <span>Operating NPV</span><b>${moneyText(finance?.devOperatingNpv)}</b>
          <span>Gross development margin</span><b>${moneyText(finance?.devGrossMargin)}</b>
          <span>Risk-adjusted value</span><b>${moneyText(finance?.devRiskAdjustedValue)}</b>
          <span>Equity money multiple</span><b>${financeNumber(finance?.devReturnMultiple).toFixed(2)}x</b>
        </div>
        <div class="sld-fin-grid">${FINANCE_FIELDS.map(field => financeFieldHtml(field, financeInputs)).join('')}</div>
        <div class="sld-fin-note"><b>Screening values only, not financial advice.</b> Revenue, CAPEX,
          OPEX, development value and BESS outputs depend entirely on the visible assumptions. They do
          not replace project-specific yield, degradation, route-to-market, tax, debt, grid, EPC,
          insurance, degradation, augmentation or investment-committee models.</div>
      </details>
      <div class="sld-hint">Drag the site to move it. Drag the handle to rotate. Click the
        cable to add a vertex, drag a vertex to shape the route, double-click one to remove it.</div>
      <div class="sld-caveat"><b>Beta analytics, not an actual grid connection.</b> A layout, not
        a design. Every length is straight-line between the points shown, with no wayleave,
        easement, right of way, crossing, terrain, ground condition or consent content, 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, and land control. A mapped substation does not confirm capacity, voltage
        suitability or acceptance by any network party.</div>`;

    el.dataset.open = 'true';
    // Optional throughout: a panel that cannot find its own controls must not
    // take the layout down with it. The geometry is the product; the panel is
    // how it is driven.
    el.querySelector?.('.sld-close')?.addEventListener('click', closeSld);
    el.querySelector?.('.sld-min')?.addEventListener('click', () => {
      const min = el.dataset.min === 'true';
      el.dataset.min = min ? 'false' : 'true';
      const button = el.querySelector('.sld-min');
      if (button) button.innerHTML = min ? '&minus;' : '&plus;';
    });
    // The panel is draggable by its heading for the same reason the card is:
    // on a map, anything fixed in a corner is eventually in the way.
    const heading = el.querySelector?.('h4.sld-drag');
    if (heading && !heading.dataset.bound) {
      heading.dataset.bound = '1';
      let drag = null;
      heading.addEventListener('pointerdown', (event) => {
        if (event.target.closest('button')) return;
        event.preventDefault();
        const rect = el.getBoundingClientRect();
        drag = {
          pointerId: event.pointerId,
          dx: event.clientX - rect.left,
          dy: event.clientY - rect.top,
        };
        heading.setPointerCapture?.(event.pointerId);
        el.style.right = 'auto';
        el.style.bottom = 'auto';
        el.style.left = rect.left + 'px';
        el.style.top = rect.top + 'px';
        const map = capturedMap?.getContainer()?.getBoundingClientRect();
        if (map) el.style.maxHeight = Math.max(120, map.bottom - rect.top - 8) + 'px';
      });
      heading.addEventListener('pointermove', (event) => {
        if (!drag || event.pointerId !== drag.pointerId) return;
        event.preventDefault();
        const map = capturedMap?.getContainer()?.getBoundingClientRect()
          || { left: 0, top: 0, right: window.innerWidth, bottom: window.innerHeight };
        const panel = el.getBoundingClientRect();
        const minX = map.left + 4;
        const maxX = Math.max(minX, map.right - panel.width - 4);
        const minY = map.top + 4;
        const maxY = Math.max(minY, map.bottom - 44 - 4);
        const left = Math.max(minX, Math.min(maxX, event.clientX - drag.dx));
        const top = Math.max(minY, Math.min(maxY, event.clientY - drag.dy));
        el.style.left = left + 'px';
        el.style.top = top + 'px';
        el.style.maxHeight = Math.max(120, map.bottom - top - 8) + 'px';
      });
      const finish = (event) => {
        if (!drag || event.pointerId !== drag.pointerId) return;
        try { heading.releasePointerCapture?.(event.pointerId); } catch (_) { /* already released */ }
        drag = null;
      };
      heading.addEventListener('pointerup', finish);
      heading.addEventListener('pointercancel', finish);
    }
    (el.querySelectorAll?.('.sld-tabs button') || []).forEach(button => {
      button.addEventListener('click', () => {
        sld.inputs.mode = button.dataset.mode;
        if (capturedMap) redrawSld(capturedMap);
      });
    });
    el.querySelector?.('#sld_basis')?.addEventListener('change', (event) => {
      sld.targetBasis = event.target.value;
      fitToStatedCapacity();
      if (capturedMap) redrawSld(capturedMap, { fit: true });
    });
    el.querySelector?.('details.sld-finance')?.addEventListener('toggle', (event) => {
      sld.financeOpen = Boolean(event.currentTarget.open);
    });
    (el.querySelectorAll?.('[data-fin-key]') || []).forEach(input => {
      input.addEventListener('change', () => {
        const values = sld.finance[sld.inputs.mode];
        if (input.type === 'checkbox') values[input.dataset.finKey] = Boolean(input.checked);
        else if (input.dataset.finKey === 'dev_stage') {
          applyDevelopmentStageDefaults(values, input.value);
        } else if (input.tagName === 'SELECT') values[input.dataset.finKey] = input.value;
        else {
          const value = Number(input.value);
          if (Number.isFinite(value)) values[input.dataset.finKey] = value;
        }
        if (capturedMap) redrawSld(capturedMap);
      });
    });
    (el.querySelectorAll?.('input[data-key]') || []).forEach(input => {
      input.addEventListener('change', () => {
        const key = input.dataset.key;
        const value = normalizeElectricalInput(key, input.value);
        if (value == null) {
          input.value = String(sld.inputs[key]);
          return;
        }
        sld.inputs[key] = value;
        if (key === 'gcr' || key === 'gcr_c') {
          applyMountingBifacial(sld.inputs.mode, value);
        }
        // Editing by hand wins. Re-fitting here would silently undo the change
        // the user just made; the residual simply moves and says so.
        if (sld.targetBasis === 'ac' || sld.targetBasis === 'dc') {
          const s = computeSldStats();
          const got = sld.targetBasis === 'ac' ? s.ac_mw : s.dc_mwp;
          sld.fitResidualPct = sld.targetMw > 0
            ? ((got - sld.targetMw) / sld.targetMw) * 100 : null;
        }
        if (capturedMap) redrawSld(capturedMap);
      });
    });
  }

  function closeSld() {
    sld.active = false;
    sld.projectName = null;
    sld.routePins = [];
    sld.arrayCentre = null;
    sld.rotationDeg = 0;
    if (sldFlowHandle !== null) { cancelAnimationFrame(sldFlowHandle); sldFlowHandle = null; }
    const el = document.getElementById(PANEL_ID);
    if (el) el.dataset.open = 'false';
    if (capturedMap && capturedMap.getSource(SRC_SLD)) {
      setSourceData(capturedMap, SRC_SLD, { type: 'FeatureCollection', features: [] });
    }
  }

  // Opened from the substation card the neon links already produce, so the
  // sandbox is one click from the thing it connects to.
  function openSldAt(map, gridNode, name, voltage) {
    return false; // retired: no substation-triggered layout
    sld.active = true;
    sld.projectName = null;
    sld.targetMw = null;
    sld.targetBasis = 'unstated';
    sld.fitResidualPct = null;
    sld.gridNode = gridNode;
    sld.gridNodeName = name;
    sld.gridNodeVoltage = voltage;
    sld.arrayCentre = null;
    sld.rotationDeg = 0;