In this section
- Single-Line Diagram (SLD) Sandbox Style Hoist geodesy · gridatlas / atlas/parts/202609040400-sld-sandbox-style-hoist.js lines 1–700
Single-Line Diagram (SLD) Sandbox Style Hoist
A JavaScript file in the parts folder of GridAtlas that maps grid substations, solar, transformers and 400kV, using haversine.
Set aside from the main view: 96% of its lines are the same as atlas/parts/202609041234-sld-sandbox-technology-buckets.js (gridatlas), which stays. (near-copy-of, proposed by families.py). 95% of lines shared with Single-Line Diagram (SLD) Sandbox Technology Buckets; read that one first. All set-aside files, with reasons. Nothing was deleted.
Evidence
- line-jaccard 0.9552 to gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 atlas/parts/202609041234-sld-sandbox-technology-buckets.js:1-5885 adc00df9e0bc8a73f1c4f5a040f532ebe0a51398
- sha256 2522499d156ff06209c4b88b2772779f6bb8d310dfd8579255f01c002bdc1a77
- target sha256 053e2ff9c0b4f583b9d305911ef9e5377fddc86c1d474b4a70cb041f4f8ede00
- group of 2 (identity.json near-copy edges >= 0.9)
- canonical rule: reachable, newest stamp, core repo, most lines
geodesygridatlas / atlas/parts/202609040400-sld-sandbox-style-hoist.js · lines 1–700 of 5692 · version 2026-09-04 04:00 · Not reached from any entry point (candidate for review) · pattern retryIdentityOwnerThenArrival (shared by 8 files)
- What it does
- It maps grid substations, solar, transformers and 400kV. Defines 187 functions or classes, including coverage, isProjectTech, provisionalDeclaredConnection, resolveDeclaredConnection, nearestTransmission. 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: solar, transformers, 400kV, 750kV, 415kV, 275kV.
- Inputs & outputs
- In: GeoJSON file grid_substations.geojson; 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, 66kV, 33kV.
- What it achieves
- It resolves declared connection (`resolveDeclaredConnection`), opens corridor sheet (`openCorridorSheet`) and runs grid point (`runGridAtPoint`). GridAtlas cartridge — neon substation links and the SLD layout sandbox. Its code works with 400 kV, 33 kV and 132 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/parts · script
- VEDIC
- MEASURE (GG2050-VEDIC-000001): GridAtlas / Geodesy · Mathematics / Spherical geometry. coordinate_pair, coordinate_pair → distance_km
- VEDIC
- VOLTAGE (GG2050-VEDIC-000003): GridAtlas / Geodesy · Computer science / Data normalisation. voltage_properties → kilovolt_list
- VEDIC
- REPRESENT (GG2050-VEDIC-000002): GridAtlas / Geodesy · Computer science / Geometry processing. geojson_geometry → coordinate_pair_or_null
- Uses
- none found
- Used by
- none found
- Produces
- coverage, isProjectTech, provisionalDeclaredConnection, resolveDeclaredConnection, nearestTransmission, corridorBeside, module, corridorTargets, corridorAction, installCorridorSheet, close, openCorridorSheet
- Defines here
- coverage, isProjectTech, provisionalDeclaredConnection, resolveDeclaredConnection, nearestTransmission, corridorBeside, module, corridorTargets, corridorAction, installCorridorSheet, close, openCorridorSheet, module, armCorridorGestures, canvas, cancel, nearestScope, network, declaredBlockHtml, publishedUnits, published, publishedHtml
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 atlas/parts/202609040400-sld-sandbox-style-hoist.js:1-700 · blob 102b7ebf3b30861da927410e027a9d1648d73564 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, network, storage · domain stage: experimental · users: none · canonical: unreached_review
/**
* GridAtlas cartridge — neon substation links and the SLD layout sandbox.
*
* Assembled under the generation named in the header above; this part
* states no generation of its own, because a second identity inside the
* same file is one that can disagree with the first. Slot: replace-script for
* 202608292126-pre-snapped-config-adapter.js.
*
* WHAT IT DOES
* ------------
* Select a solar, battery or onshore wind project and the map draws animated
* neon lines from it to the nearest substations at 33 kV and above. The same
* distances are written onto the project card the engine has just opened,
* marked BETA, with the reasons a distance is not a connection stated on the
* card itself rather than hidden in a tooltip.
*
* WHY IT REPLACES THE CONFIG ADAPTER RATHER THAN ADDING A SCRIPT
* -------------------------------------------------------------
* The composer in atlas/index.html supports exactly one slot, `replace-script`.
* There is no append slot, and inventing one would mean changing the composer,
* which is a larger contract change than this feature is worth. So this
* cartridge carries the pre-snapped config adapter's behaviour VERBATIM -- same
* layer ids, same closure assertion, same failure mode, same public state
* object -- and adds the link layer beside it. The immutable shell is not
* touched, and `__GRIDATLAS_PRE_SNAPPED_CONFIG__` still reports exactly what it
* reported before, so anything asserting on it keeps working.
*
* HOW IT HOOKS IN WITHOUT SHELL MUTATION
* --------------------------------------
* Two decorators, both of things the engine has already published by the time
* this script runs:
*
* window.initVentusMap wrapped for the pre-snap config, as before.
* maplibregl.Map wrapped to capture the instance, because the engine
* keeps `map` in a closure and returns nothing. The
* engine constructs its map inside initVentusMap, which
* runs after this file, so the constructor is still
* ours to wrap.
*
* THE MEASUREMENT
* ---------------
* Haversine on R = 6378.137 km, the same constant as ventus-corev8engine.js,
* pipelinenews and Ventusltd/grid-distance-maths, so a distance read here
* equals the same distance read there. Substations are mapped as points AND as
* polygons; a polygon is reduced to its ring mean, because its first vertex is
* a corner rather than the site.
*
* Scope is 33 kV and above. 11 kV is rare for utility-scale export and where it
* occurs is often a private network behind the meter, so it is not a screening
* signal. `voltage` is written `33000`, `33000;11000` for two voltages, and
* `33000:11000` for a transformer ratio -- a 33/11 primary still carries 33 kV.
*
* WHAT A LINE IS NOT
* ------------------
* A straight line to mapped geometry. Not a cable route, not a connection
* length, no wayleave, crossing, terrain or consent content. A mapped
* substation does not confirm capacity, voltage suitability or connection
* rights, and fault level and thermal headroom cannot be inferred from distance
* at all -- they need DNO network data such as source impedance and a
* connection study, alongside right of way, wayleaves and easements, land
* control and consent. The card says all of that on screen.
*/
(() => {
'use strict';
const SLD_STYLES = (window.__GRIDATLAS_MODULES__ || {}).sldStyles;
if (SLD_STYLES?.schema !== 'gridatlas.module.sld-styles.v1') {
throw new Error('sld-sandbox requires the sld-styles module');
}
const GENERATION = '202609012045';
/* ══════════════════════════════════════════════════════════════════════
PART 1 — the pre-snapped config adapter, carried forward unchanged.
══════════════════════════════════════════════════════════════════════ */
const PRE_SNAPPED_LAYER_IDS = new Set(['400', '275', '220', '132', '66']);
const originalInit = window.initVentusMap;
if (typeof originalInit !== 'function') {
throw new Error('V8 engine init function is unavailable before map-ready adapter');
}
const state = {
schema: 'gridatlas.pre-snapped-config-adapter.v1',
generation: '202608292126',
applied: false,
changed_layer_ids: [],
preserved_preload_flags: true,
failures: []
};
window.__GRIDATLAS_PRE_SNAPPED_CONFIG__ = state;
window.initVentusMap = function gridAtlasMapReadyInit(options) {
try {
const changed = [];
const config = options.config.map(group => ({
...group,
layers: group.layers.map(layer => {
if (!PRE_SNAPPED_LAYER_IDS.has(String(layer.id))) return layer;
if (layer.snap !== true) {
throw new Error(`expected V8 snap=true for topology layer ${layer.id}`);
}
changed.push(String(layer.id));
return { ...layer, snap: false };
})
}));
const expected = [...PRE_SNAPPED_LAYER_IDS].sort();
if (JSON.stringify([...changed].sort()) !== JSON.stringify(expected)) {
throw new Error(`pre-snapped layer closure mismatch: ${JSON.stringify(changed)}`);
}
state.applied = true;
state.changed_layer_ids = changed;
return originalInit({ ...options, config });
} catch (error) {
state.failures.push(String(error?.message || error));
throw error;
}
};
/* ══════════════════════════════════════════════════════════════════════
PART 2 — neon substation links.
══════════════════════════════════════════════════════════════════════ */
/* ONE geodesy, and it is the module's.
----------------------------------------------------------------------
This file used to declare R_ATLAS = 6378.137 and its own distanceKm,
four hundred lines from a second geodesy section, while the assembled
cartridge ALSO carried the geodesy module in front of it. Two radii and
two haversines in one served file, agreeing only because nobody had
changed one of them yet - and on 1 Sep 2026 the all-versions proof
found that they had in fact stopped agreeing in the last bit.
The Grid Finding Scope already did this correctly: it calls its module
and computes nothing itself. Geodesy was the exception. It is not now.
A missing module is a hard failure at load, not a fallback: a fallback
would silently restore exactly the duplication this removes. */
const GEODESY = (window.__GRIDATLAS_MODULES__ || {}).geodesy;
if (!GEODESY) throw new Error('sld-sandbox requires the geodesy module');
const R_ATLAS = GEODESY.EARTH_RADIUS_KM;
const DEG = Math.PI / 180;
const MIN_KV = 33;
const LINK_COUNT = 5; // how many substations to reach for
const MAX_LINK_KM = 40; // beyond this, silence is more honest
const SUBS_URL = 'data/grid_substations.geojson';
const SUBS_LAYER_ID = 'l-subs'; // engine convention: layer `l-<id>`, source `src-<id>`
// Project technologies this fires for. Onshore only: an offshore turbine's
// export route is nothing like a straight line to the nearest onshore
// substation, so drawing one would be a picture of a lie.
/* Every technology the register actually uses, and then some.
----------------------------------------------------------------------
This set was solar, bess and two spellings of wind, and it silently
rejected the rest. Counted against the shipped register: 2,399 onshore
wind projects and 109 offshore, so 2,508 of 7,680 — a third of the
register — had a MAP button that did nothing at all. Not an error, not a
message, nothing: the deep link tested membership and returned.
The register writes `wind_onshore`. The engine has had a `wind_onshore`
layer the whole time. Only this list disagreed with both.
So it no longer decides alone. The list below is the fast path, and
anything the ENGINE has a layer control for is accepted too — the engine
owns the layers, so the engine's vocabulary is the authority and this
stops being a place a technology can be forgotten. */
const PROJECT_TECHS = new Set([
'solar', 'solar_operational', 'solar_roof',
'bess', 'bess_operational',
'wind', 'wind_onshore', 'wind_onshore_operational',
'wind_offshore', 'wind_offshore_operational',
// The rest of the engine's own generation and storage dashboard, read off
// the live page rather than guessed. Note wind_onshore is NOT among the
// engine's layer ids -- it has `wind` and `wind_onshore_operational` --
// yet the register writes wind_onshore for 2,399 projects. Asking the
// engine alone would still have missed every one of them, which is why the
// explicit entry above is not redundant with the lookup below.
'biomass', 'hydro', 'hydrogen', 'tidal', 'geothermal',
'flywheel', 'caes', 'act',
/* `other` is what the register writes for a category it has no
bucket for. Over the 11,069-row REPD product this Atlas's search
lane reads, 25 DESNZ categories normalise to 14 ids and `other` was
the only one missing here - 4 projects, 2 Unknown and 2 Air Source
Heat Pumps. Not many; not zero; and written again the next time the
register gains a category. */
'other'
]);
/* Which technologies measure, and what each measurement is OF, is owned by
the technology-coverage module rather than by this file. It is assembled
into this cartridge ahead of this part, so it is here by the time any of
this runs; the fallback below exists only so a proof can load this part
alone, and it reproduces the module's answer rather than a different one.
Offshore NO LONGER WITHHOLDS. It used to open a card and draw nothing, on
reasoning about export cables and landfalls that was right about routes
and wrong about whether to measure at all. An offshore project's export
cable does land at an onshore substation, so the distance is a
measurement of something real. What changed is the answer; what did not
change is a single word of the route reasoning, which the module now
prints beside the number instead of instead of it. */
const coverage = (() => {
try {
const module = window.__GRIDATLAS_MODULES__?.technologyCoverage;
if (module && typeof module.policy === 'function') return module;
} catch (_) { /* fall through to the local reproduction */ }
const OFF = new Set(['wind_offshore', 'wind_offshore_operational']);
return {
policy: (tech) => ({ technology: tech || null, measure: true,
offshore: OFF.has(String(tech || '')),
sample: 'nearest of the mapped substations at or above the voltage '
+ 'floor that this search could see',
notes: [] }),
namedOffshore: () => false
};
})();
const OFFSHORE_TECHS = new Set(['wind_offshore', 'wind_offshore_operational']);
function isProjectTech(tech) {
if (!tech) return false;
if (PROJECT_TECHS.has(tech)) return true;
// Ask the engine. If it has a control for this layer, it is a technology
// this map knows about, whatever this cartridge was written knowing.
try {
return Boolean(document.querySelector(
'input[type=checkbox][data-layer-id="' + String(tech).replace(/"/g, '') + '"]'));
} catch (error) {
return false;
}
}
// SCADA on a dark map, not arcade neon. These are the muted siblings of the
// engine's own layer colours: enough saturation to read as live, low enough
// not to shout over the basemap or the grid layers underneath.
const TECH_COLOUR = {
solar: '#d8c96a', solar_operational: '#d8c96a', solar_roof: '#d8c96a',
bess: '#d9963c', bess_operational: '#d9963c',
wind: '#6fb582', wind_onshore: '#6fb582', wind_onshore_operational: '#6fb582',
// Offshore reads cooler than onshore: it is the one technology here whose
// links are deliberately not drawn, and it should not look like the others.
wind_offshore: '#5f9fb5', wind_offshore_operational: '#5f9fb5',
biomass: '#b58f6f', hydro: '#6f9fd8', hydrogen: '#a98fd8',
tidal: '#5fb5a8', geothermal: '#b57f6f',
flywheel: '#9f9fb5', caes: '#9f9fb5', act: '#9f9fb5'
};
const SUBSTATION_COLOUR = '#5fbdc2'; // teal, the substation end of a link
/* ── the 400 kV public record ────────────────────────────────────────
The nearest-substations list is a measurement and nothing more. But
the DCO-scale schemes each carry a PUBLIC declared point of connection
at 400 kV - usually through a new customer substation consented within
the scheme itself - and this card used to say nothing about it while
listing closer 33 and 132 kV points, which read as connecting them to
the wrong network. The rule holds: bind to the public record or say
nothing. Every entry below is sourced from Development Consent Orders,
Planning Inspectorate documents, or public project statements; the
table binds a register identity to a NAMED substation in the served
payload, and the distance shown is measured, never asserted. */
const DECLARED_COLOUR = '#d8b64a'; // gold: declared, and the far end exists today
/* Pink: declared, and the thing at the far end has not been built. One
Earth's point of connection is a National Grid substation that does not
exist yet; Thorpe Marsh's is under construction. Drawing those in the
same gold as a connection into a live substation would say something
untrue about the network, so they get their own colour and the card
says which it is. The distinction is taken from the public record, not
from the map: an unbuilt substation can be absent from OSM, or present
because someone mapped the consented site. */
const DECLARED_UNBUILT_COLOUR = '#d87aa8';
/* The table itself, and the three functions that bind it to the payload,
moved to the declared-connections module at generation 202609012128.
The body keeps the colours (rendering) and the state; the record is
read from the module, which a proof can open on its own and a cut
hashes on its own. A missing module is a hard failure at load, for
the same reason as geodesy: a fallback would quietly restore a second
copy of the table. */
const DECLARED = (window.__GRIDATLAS_MODULES__ || {}).declaredConnections;
if (!DECLARED) throw new Error('sld-sandbox requires the declared-connections module');
let currentRepdRef = null;
let currentDeclared = null;
let currentNearest400 = null;
/* The coverage policy for the CURRENT selection. It carries no arithmetic
and changes no result - it decides only which sentences go under the
distances. The measurement itself is coordinates, a candidate set and a
distance, and reads no technology at all. */
let currentPolicy = null;
/* The capacity Pipeline News sent, kept where the network card can
reach it. Without this the powerflow answer would have to invent a
figure, and an invented megawatt is exactly the kind of number that
gets quoted back as the project's own. */
let currentCapacityMw = null;
/* What the Order says is known the moment the identity is known: the
substation, the voltage class, the route, the consented works and the
citation need no payload, no fetch and no map. On a phone that is the
difference between a card that answers and a card that waits. The
distance is the one part that must be measured, so it is the one part
marked pending until it has been. */
function provisionalDeclaredConnection(repdRef) {
return DECLARED.provisional(repdRef);
}
function resolveDeclaredConnection(repdRef, origin, subs) {
return DECLARED.resolve(repdRef, origin, subs);
}
function nearestTransmission(origin, subs) {
return DECLARED.nearestTransmission(origin, subs);
}
/* EVERY SUPERLATIVE CARRIES ITS SAMPLE.
--------------------------------------------------------------------
"Nearest 400 kV substation" is nearest among what this search could
see, and two different things limit that. The search runs over the
substation features the map has loaded, so the first number is how
many of them were actually eligible - counted by the measurement
itself, not assumed. And the operator's own published list is only
partly located: ETYS names substations and does not place them, so
the geometry comes from OpenStreetMap through a GridAtlas release and
a fraction of the network is invisible to any search by distance.
Both numbers are COMPUTED at render time from what was fetched. A
literal would go quietly false the day the pinned product moves -
Codex's join correction alone takes located points from 502 to 489 -
and a stale denominator under the word "nearest" is worse than none.
It states the sample. It does not grade the result. */
/* A straight line is not a route, and the card said nothing about it.
--------------------------------------------------------------------
ADDITIVE. The straight-line distance is unchanged, still first, still
the measurement; the corridor figure sits beside it and is labelled an
estimate every time it appears.
Only for a CABLE question. The factor is calibrated on cable circuits,
which follow the highway network; overhead line crosses open country
and measures 1.13. The module publishes that number and deliberately
offers no forOverhead(), so this cannot quietly become the answer to a
question it was not measured on.
Under about a kilometre the module withholds the estimate rather than
scaling, and the card says why: at that separation the straight line
between two site centroids is not measuring route factor at all. */
function corridorBeside(km) {
const module = (() => {
try { return window.__GRIDATLAS_MODULES__?.corridorEstimate || null; }
catch (_) { return null; }
})();
if (!module) return '';
const estimate = module.forCable(km);
if (!estimate) return '';
const basis = module.basis;
if (estimate.withheld) {
return ` <span class="neon-caveat">No corridor estimate at this `
+ `separation: ${escapeHtml(estimate.withheld)}.</span>`;
}
return ` · ~${estimate.km.toFixed(1)} km corridor estimate `
+ `(×${estimate.factor}, ${basis.within_15_pct}% of GB transmission `
+ `cable circuits within 15% of published length, `
+ `${basis.distinct_site_pairs} distinct site pairs). `
+ `<span class="neon-caveat">${escapeHtml(module.caveat)} `
+ `${escapeHtml(module.not_for_overhead)}</span>`;
}
/* A 44 px action, and a sheet that is the corridor figures in full.
--------------------------------------------------------------------
The card line beside each distance is one sentence. A reader who wants
the basis - what the factor was calibrated on, how wrong it typically
is, and what it is not for - should not have to take that from a
sentence, and on a phone there is no room to print it inline.
44 px because that is the smallest target a thumb hits reliably; the
estate's own layers toggle was widened to the same at 202609030116.
The sheet is opened three ways and all of them end in one function:
the button, a right-click on the map (the engine binds no contextmenu
- measured, zero occurrences in the shell, in index.html and in every
composed part), and a long press.
THE LONG PRESS DEFERS TO EVERYTHING. It arms on touchstart, and it is
cancelled by a movement of more than 10 px, by a second finger, by
touchend, and by an SLD drag already being in progress - the sandbox
binds its own touchstart for dragging the array, its handle and its
route pins, so this must never fire during one. A pan is a movement;
a pinch is a second finger; both cancel before the 500 ms is up. */
const CORRIDOR_SHEET = 'gridatlas-corridor-sheet';
let corridorSheetInstalled = false;
function corridorTargets() {
const rows = [];
if (currentDeclared && currentDeclared.kind !== 'circuit'
&& Number.isFinite(currentDeclared.km)) {
rows.push({ name: currentDeclared.poc, km: currentDeclared.km,
note: 'declared point of connection, from the public record' });
}
if (currentNearest400) {
rows.push({ name: currentNearest400.name, km: currentNearest400.km,
note: 'nearest mapped substation at 400 kV or above' });
if (currentNearest400.named && currentNearest400.named.name !== currentNearest400.name) {
rows.push({ name: currentNearest400.named.name, km: currentNearest400.named.km,
note: 'nearest NAMED substation at 400 kV or above' });
}
}
return rows;
}
function corridorAction() {
if (!corridorTargets().length) return '';
/* The card can render before the map is wired, and the button is
useless without the delegated listener. Installing here as well is
idempotent and removes the ordering dependency entirely. */
installCorridorSheet();
return `<button type="button" class="gridatlas-corridor-open" `
+ `data-gridatlas-corridor="1" `
+ `aria-haspopup="dialog">Explore route corridors \u203a</button>`;
}
function installCorridorSheet() {
if (corridorSheetInstalled) return;
corridorSheetInstalled = true;
const style = document.createElement('style');
style.textContent =
'.gridatlas-corridor-open{display:block;width:100%;min-height:44px;margin:8px 0 2px;'
+ 'font:600 12px/1.2 ui-monospace,SFMono-Regular,Menlo,monospace;letter-spacing:.06em;'
+ 'text-align:left;padding:12px 14px;border-radius:6px;cursor:pointer;'
+ 'background:#0d1117;color:#7fe3d0;border:1px solid #2b3a44;}'
+ '.gridatlas-corridor-open:focus-visible{outline:2px solid #7fe3d0;outline-offset:2px;}'
+ '#' + CORRIDOR_SHEET + '{position:fixed;left:0;right:0;bottom:0;z-index:10000;'
+ 'max-height:min(70vh,560px);overflow:auto;transform:translateY(101%);'
+ 'transition:transform .18s ease-out;background:#070d11;color:#cfe6e8;'
+ 'border-top:1px solid #0b5f63;padding:14px 16px calc(16px + env(safe-area-inset-bottom));'
+ 'font:12px/1.5 ui-monospace,SFMono-Regular,Menlo,monospace;}'
+ '#' + CORRIDOR_SHEET + '[data-open="1"]{transform:translateY(0);}'
+ '#' + CORRIDOR_SHEET + ' h4{margin:0 0 8px;font-size:13px;color:#7fe3d0;}'
+ '#' + CORRIDOR_SHEET + ' .r{padding:8px 0;border-top:1px solid #14252b;}'
+ '#' + CORRIDOR_SHEET + ' .c{color:#8fa6ab;}'
+ '#' + CORRIDOR_SHEET + ' button{min-height:44px;min-width:44px;cursor:pointer;'
+ 'background:#0d1117;color:#7fe3d0;border:1px solid #2b3a44;border-radius:6px;'
+ 'padding:10px 14px;font:600 12px/1 ui-monospace,monospace;}'
+ '@media (prefers-reduced-motion:reduce){#' + CORRIDOR_SHEET + '{transition:none;}}';
document.head.appendChild(style);
const sheet = document.createElement('div');
sheet.id = CORRIDOR_SHEET;
sheet.setAttribute('role', 'dialog');
sheet.setAttribute('aria-label', 'Route corridor estimates');
sheet.dataset.open = '0';
sheet.hidden = true;
document.body.appendChild(sheet);
const close = () => { sheet.dataset.open = '0'; sheet.hidden = true; };
window.__GRIDATLAS_CORRIDOR_SHEET__ = {
get open() { return sheet.dataset.open === '1'; },
close,
open: () => openCorridorSheet(sheet)
};
document.addEventListener('click', (event) => {
const opener = event.target?.closest?.('[data-gridatlas-corridor]');
if (opener) { event.preventDefault(); openCorridorSheet(sheet); return; }
if (event.target?.closest?.('[data-gridatlas-corridor-close]')) close();
});
document.addEventListener('keydown', (event) => {
if (event.key === 'Escape' && sheet.dataset.open === '1') close();
});
}
function openCorridorSheet(sheet) {
const module = (() => {
try { return window.__GRIDATLAS_MODULES__?.corridorEstimate || null; }
catch (_) { return null; }
})();
const rows = corridorTargets();
if (!rows.length) return;
const body = rows.map(row => {
const estimate = module ? module.forCable(row.km) : null;
const corridor = estimate && estimate.km !== null
? `~${estimate.km.toFixed(1)} km corridor estimate`
: (estimate ? 'no corridor estimate at this separation' : '');
return `<div class="r"><b>${escapeHtml(row.name)}</b><br>`
+ `${row.km.toFixed(2)} km straight`
+ (corridor ? ` · ${corridor}` : '')
+ `<br><span class="c">${escapeHtml(row.note)}`
+ (estimate && estimate.withheld
? `. ${escapeHtml(estimate.withheld)}` : '')
+ `</span></div>`;
}).join('');
const basis = module ? module.basis : null;
sheet.innerHTML = `<h4>Route corridors</h4>${body}`
+ (basis
? `<div class="r c">Straight-line distance is measured. The corridor `
+ `figure is that distance times ${basis.factor}, calibrated on the `
+ `${basis.source}: median absolute error `
+ `${basis.median_absolute_error_pct}%, `
+ `${basis.within_15_pct}% within 15%, over `
+ `${basis.distinct_site_pairs} distinct site pairs. `
+ `${escapeHtml(module.caveat)} ${escapeHtml(module.not_for_overhead)} `
+ `${escapeHtml(module.not_an_assessment)}</div>`
: `<div class="r c">The corridor module is not loaded, so only the `
+ `measured straight-line distances are shown.</div>`)
+ `<div class="r"><button type="button" data-gridatlas-corridor-close="1">`
+ `Close</button></div>`;
sheet.hidden = false;
sheet.dataset.open = '1';
}
/* Right-click on desktop, long press on touch. Both end in the sheet. */
function armCorridorGestures(map) {
installCorridorSheet();
try {
map.on('contextmenu', (event) => {
if (!corridorTargets().length) return;
event.preventDefault?.();
openCorridorSheet(document.getElementById(CORRIDOR_SHEET));
});
} catch (_) { /* a shimmed map in a proof */ }
const canvas = (() => {
try { return map.getCanvas ? map.getCanvas() : null; } catch (_) { return null; }
})();
if (!canvas) return;
let timer = null;
let from = null;
const cancel = () => { if (timer) clearTimeout(timer); timer = null; from = null; };
canvas.addEventListener('touchstart', (event) => {
cancel();
/* Never during an SLD drag: this cartridge binds its own touchstart
for the array, the rotate handle and the route pins. */
if (sld && sld.dragging) return;
if (event.touches.length !== 1) return;
if (!corridorTargets().length) return;
from = { x: event.touches[0].clientX, y: event.touches[0].clientY };
timer = setTimeout(() => {
timer = null;
if (sld && sld.dragging) return;
openCorridorSheet(document.getElementById(CORRIDOR_SHEET));
}, 500);
}, { passive: true });
canvas.addEventListener('touchmove', (event) => {
if (!timer || !from) return;
const touch = event.touches[0];
if (!touch) { cancel(); return; }
/* A pan is a movement. Ten pixels is below the threshold a deliberate
press produces and above the jitter a still thumb produces. */
if (Math.abs(touch.clientX - from.x) > 10
|| Math.abs(touch.clientY - from.y) > 10) cancel();
}, { passive: true });
canvas.addEventListener('touchend', cancel, { passive: true });
canvas.addEventListener('touchcancel', cancel, { passive: true });
}
function nearestScope(n) {
const considered = Number(n && n.considered);
const network = (() => {
try { return window.__GRIDATLAS_NETWORK__?.coverage?.(400) || null; }
catch (_) { return null; }
})();
if (!Number.isFinite(considered) && !network) return '';
const said = [];
if (Number.isFinite(considered)) {
said.push(`nearest of the ${considered.toLocaleString('en-GB')} mapped `
+ `substation${considered === 1 ? '' : 's'} at 400 kV or above that this `
+ `search could see`);
}
if (network && network.published) {
said.push(`the operator publishes ${network.published.toLocaleString('en-GB')} `
+ `connection point${network.published === 1 ? '' : 's'} at that class and `
+ `${network.located.toLocaleString('en-GB')} of them carry coordinates, so `
+ `${network.unlocated.toLocaleString('en-GB')} cannot be measured to at all`);
}
return `<p class="neon-caveat">Scope: ${said.join('; ')}. A nearer one may `
+ `exist that nothing here can see.</p>`;
}
function declaredBlockHtml(toSubstations) {
if (!toSubstations) return '';
let out = '';
if (currentDeclared) {
const d = currentDeclared;
const unbuiltPoc = d.poc_status === 'not_built'
|| d.poc_status === 'under_construction';
const stateLabel = d.poc_status === 'not_built' ? 'Not built yet'
: (d.poc_status === 'under_construction' ? 'Under construction' : '');
out += `<div class="neon-hd">Declared connection`
+ (stateLabel ? `<span class="neon-beta" style="background:#d87aa8;color:#1a0b13">`
+ `${stateLabel}</span>` : '')
+ `<span class="neon-beta">Public record</span></div>`
+ `<ol><li>`
+ (d.at ? `<span class="neon-km">${d.km.toFixed(2)} km</span>` : '')
+ `<span class="neon-name">${escapeHtml(d.poc)}</span>`
+ (d.kv ? `<span class="neon-kv">${d.kv} kV</span>` : '')
+ `</li></ol>`
+ `<p class="neon-caveat">Via ${escapeHtml(d.via)}. `
+ `Source: ${escapeHtml(d.source)}.`
+ (d.works ? ` ${escapeHtml(d.works)}` : '')
+ (d.poc_status_note ? ` This point of connection is not yet in service: `
+ `${escapeHtml(d.poc_status_note)}.` : '')
+ (d.at ? ''
: (d.kind === 'circuit'
? ' The point of connection is a circuit rather than a substation, so no line is drawn and no distance is measured.'
: (d.pending
? ' The distance is being measured now.'
: ' This substation is not in the mapped payload, so no distance is measured.')))
+ `</p>`;
// Quotations of consented works from the made Order or Environmental
// Statement - the DCO's own illustration of the customer substation
// and the interface at the point of connection. Never design advice.
if (d.customer_works) {
out += `<p class="neon-caveat"><b>Customer substation (consented):</b> `
+ `${escapeHtml(d.customer_works)}</p>`;
}
if (d.poc_works) {
out += `<p class="neon-caveat"><b>Works at the point of connection:</b> `
+ `${escapeHtml(d.poc_works)}</p>`;
}
}
/* What the system operator publishes about the substation this card
names. The sandbox asks; the substation cartridge answers from
Ventusltd/data-grid-gb, which is ETYS restated. Absent is absent:
no sentence at all rather than an empty one. */
const networkName = currentDeclared?.kind !== 'circuit'
? (currentDeclared?.poc || currentNearest400?.name) : currentNearest400?.name;
/* Tell it the voltage the connection is actually made at: the declared
point of connection's class where there is one, otherwise the class
of the substation being measured to. Without this the answer can
only be a site-wide envelope. */
const connectionKv = currentDeclared?.kind !== 'circuit'
? (currentDeclared?.kv || currentNearest400?.kv || null)
: null;
/* connection-points counts LANDINGS: a transformer's windings are both
at the site, so Cowley's five read as ten and 484 of 525 sites were
1.90x over. Only the node/branch model holds the pairs. */
const publishedUnits = (() => {
if (topology.state !== 'ready' || !topology.index) return null;
try {
const point = window.__GRIDATLAS_NETWORK__?.byName?.(networkName);
if (!point?.site_code) return null;
const facts = topology.index.at(point.site_code);
if (!facts?.counts) return null;
return { circuits: facts.counts.circuits,
transformers: facts.counts.transformers };
} catch (_) { return null; }
})();
const published = (() => {
try {
return window.__GRIDATLAS_NETWORK__?.summarise?.(
networkName, { connectionKv, units: publishedUnits }) || null;
} catch (_) { return null; }
})();
/* The envelope is built HERE and appended BELOW the measurement.
---------------------------------------------------------------------
WHY THE ORDER CHANGED. Driven on a verified iPhone-class device
(393x852, pointer:coarse, hover:none, 5 touch points), 101 MAP taps
across all 25 technologies: the distance was on the page 99 times out
of 99 and on the first screen zero times. Measured here, it landed at
y=907 in an 852px viewport with about 270px of published-envelope
detail above it. The envelope is neither deleted nor shortened; it
moves below the answer it is context for. The measurement paragraph
names the substation, so nothing above it is needed to read it. It is
still built before the block is emitted, because link.network_published
and the topology block both depend on it having been asked for. */
const publishedHtml = (() => {
if (!published) return '';
link.network_published = { name: networkName, site: published.site_code };
/* The scope label goes FIRST. A site-wide envelope printed under a
400 kV declared connection reads as a 400 kV result unless the
reader is told otherwise before the numbers, not after. */
return `<div class="neon-hd">${escapeHtml(networkName)}`
+ (published.fault_scope === 'bus'
? `<span class="neon-beta" style="background:#12323a;color:#8fd8e0">`
+ `${published.fault_kv} kV bus</span>`
: (published.site_wide
? `<span class="neon-beta" style="background:#3a3a2a;color:#d8c96a">Site-wide</span>`
: ''))
+ `<span class="neon-beta">NESO published</span></div>`
+ `<p class="neon-caveat"><b>${escapeHtml(published.scope_label)}.</b></p>`
+ `<p class="neon-caveat">${escapeHtml(published.sentence)}.</p>`
+ `<p class="neon-caveat">${escapeHtml(published.metrics_not_interchangeable)} `
+ `${escapeHtml(published.attribution)}. `
+ `${escapeHtml(published.not_an_assessment)}</p>`;
})();
if (currentNearest400) {
const n = currentNearest400;
/* The measurement and everything that makes it honest are ONE element,
which is why nearestScope(n) is inside the wrapper rather than
appended after it. Whatever a layout does to this block - move it,
dock it, put it in a sheet - the number cannot arrive without the
word "straight", without the corridor estimate's own caveat, and
without the sentence naming the sample the superlative searched. */
out += `<div class="neon-answer">`
+ `<p class="neon-caveat"><b>Nearest 400 kV substation:</b> `
+ `${escapeHtml(n.name)} · ${n.km.toFixed(2)} km straight`
+ corridorBeside(n.km)
+ (n.works ? `. ${escapeHtml(n.works)}` : '')
+ (n.named
? ` (nearest named: ${escapeHtml(n.named.name)} · ${n.named.km.toFixed(2)} km`
+ (n.named.works ? `. ${escapeHtml(n.named.works)}` : '') + `)`
: '')