In this section
- Single-Line Diagram (SLD) Sandbox Technology Buckets geodesy · gridatlas / atlas/parts/202609041234-sld-sandbox-technology-buckets.js lines 3409–4108
Single-Line Diagram (SLD) Sandbox Technology Buckets
A JavaScript file in the parts folder of GridAtlas that maps grid substations, solar, wind and transformers, using haversine.
geodesygridatlas / atlas/parts/202609041234-sld-sandbox-technology-buckets.js · lines 3409–4108 of 5885 · version 2026-09-04 12:34 (continued from section 436) · pattern coarse (shared by 6 files)
- What it does
- It maps grid substations, solar, wind and transformers. Defines 191 functions or classes, including coverage, isProjectTech, layerIdForBucket, provisionalDeclaredConnection, resolveDeclaredConnection. 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, wind, transformers, 750kV, 415kV, 400kV.
- 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.
- Downstream impact
- Used directly by 2 files: Build Graph (ventus-grid-engine, https://ventusltd.github.io/ventus-grid-engine/genome/); Ventus Grid Engine — Genome Page (ventus-grid-engine, https://ventusltd.github.io/ventus-grid-engine/genome/). Reached from 1 other entry point, including Genome Workflow (ventus-grid-engine).
- 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
- Loaded by the Genome page in Ventus Grid Engine at https://ventusltd.github.io/ventus-grid-engine/genome/. Also imported by Build Graph, from Ventus Grid Engine.
- 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
- named by URL in Build Graph (estate URL), named by URL in Ventus Grid Engine — Genome Page (estate URL)
- Produces
- coverage, isProjectTech, layerIdForBucket, provisionalDeclaredConnection, resolveDeclaredConnection, nearestTransmission, corridorBeside, module, corridorTargets, corridorAction, installCorridorSheet, close
- Defines here
- ledgerStamp, installVersionLedger, scopeModule, ensureScopeLayers, clearScope, scopeHtml, runGridScope, trayTarget, engineLayerBox, installMobileTray, quickChip, reflect, installGbConditions, setSourceData, interactiveLayerIds, install, selectAt
- 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/202609041234-sld-sandbox-technology-buckets.js:3409-4108 · blob adc00df9e0bc8a73f1c4f5a040f532ebe0a51398 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, network, storage · domain stage: experimental · users: none · canonical: production_core
} catch (error) {
product = null;
gbLoader.error = String(error && error.message || error);
}
if (!product) {
gbLoader.state = 'failed';
body.innerHTML = '<p class="gb-note">The price rollup could not be '
+ 'reached. This says nothing about the grid, only about the network '
+ 'between here and the data repository.</p>';
link.gb_conditions = { reached: false };
return;
}
const productError = gbProductError(product);
if (productError) {
gbLoader.state = 'withheld';
gbLoader.reason = productError;
gbLoader.schema = product.schema || null;
body.innerHTML = '<p class="gb-note">The owner price product did not pass '
+ `the v2 evidence gate (${productError}), so no values are shown.</p>`;
link.gb_conditions = { reached: true, schema_supported: false,
source: 'data-gb-electricity', reason: productError, project_bindings: 0 };
return;
}
const price = product.price || {};
const years = Array.isArray(price.by_year) ? price.by_year : [];
const latest = years.length ? years[years.length - 1] : null;
const low = price.lowest_settlement_period || null;
const includedDays = Number((product.derived_from || {}).included_days);
const negativeDays = Number(price.days_with_a_negative_settlement_period);
const partialYears = years.filter(row =>
row.calendar_date_coverage === 'PARTIAL_DATE_COVERAGE');
const rows = [];
rows.push(gbRow('Available-record daily mean',
gbNumber(price.available_record_daily_mean, 2), ' £/MWh'));
rows.push(gbRow('Dates with a negative period',
gbNumber(price.negative_period_day_share_pct, 2) + '%',
` ${negativeDays} of ${includedDays}`));
if (latest) {
const partial = latest.calendar_date_coverage === 'PARTIAL_DATE_COVERAGE';
rows.push(gbRow(latest.year + (partial ? ' partial' : ''),
gbNumber(latest.mean_gbp_per_mwh, 2), ' £/MWh'));
}
const lowLine = low && Number.isFinite(Number(low.value))
? '<p class="gb-note gb-point">Lowest observed settlement price: '
+ `<b>${gbNumber(low.value, 2)} £/MWh</b>, SP ${low.settlement_period}, `
+ `${low.period_start_utc}. This is a historic GB system-price `
+ 'observation, not evidence about a project on this map.</p>'
: '';
// Absent by decision, so it is stated rather than left as a silent gap.
const solarLine = product.solar && product.solar.present === false
? '<p class="gb-note">Solar is not in this product yet: the data '
+ 'repository has not taken PVLive, and filling the gap from somewhere '
+ 'else would make a second source of truth.</p>'
: '';
const span = Array.isArray(price.span) ? price.span.join('–') : '';
body.innerHTML = rows.join('')
+ lowLine
+ solarLine
+ `<p class="gb-note">GB system sell price ${span}, included daily means `
+ `from dates with at least ${product.grain.minimum_periods_per_day} available `
+ 'settlement periods. Included does not mean all 48 are present. '
+ `${partialYears.length} year${partialYears.length === 1 ? '' : 's'} have `
+ 'partial calendar-date coverage. Elexon, via Ventusltd/data-gb-electricity. '
+ 'Historic system conditions only: not a forecast, not a price '
+ 'expectation, and not a statement about any project on this map. The '
+ 'count and share do not measure local network constraint, curtailment, '
+ 'connection capacity, a usable charging window or project revenue.</p>'
+ `<a class="gb-more" href="${GB_APP}" target="_blank" rel="noopener">`
+ 'Open the full GB energy tracker ↗</a>';
gbLoader.state = 'ready';
gbLoader.schema = product.schema;
gbLoader.renders += 1;
link.gb_conditions = {
reached: true,
schema_supported: true,
source: 'data-gb-electricity',
schema: product.schema,
span: price.span || null,
available_record_daily_mean: price.available_record_daily_mean ?? null,
negative_date_share_pct: price.negative_period_day_share_pct ?? null,
negative_dates: negativeDays,
included_dates: includedDays,
lowest: low ? { value: low.value, settlement_period: low.settlement_period,
period_start_utc: low.period_start_utc } : null,
solar_present: product.solar ? product.solar.present : null,
project_bindings: 0,
};
}
/* ── the version ledger, on the page ──────────────────────────────────
The estate's whole method is sealed, timestamped compositions - build a
new one, never edit the last - and in one overnight session that produced
twenty-four of them, each a correction with a one-line scope. Pipeline
News ledgers its releases on the homepage; the Atlas's generations were
visible only in git, which a visitor does not have.
The ledger below is extracted from git at BUILD time: every composition
manifest that ever existed, read at its last commit. It is pinned history
carried by the page, not prose about it, and nothing is fetched at
runtime. Rollback doctrine, stated where the versions are: a bad
composition is never repaired in place - an earlier one is composed
again under a new timestamp.
Mobile first, like everything since Vikram said the link travels by
WhatsApp: a collapsed chip, viewport-sized body, newest first. */
/* The ledger itself is a module now, in the cartridge with room for it -
see atlas/modules/202609030157-version-ledger.js. The name is kept so
every reader below is unchanged, and an absent module gives an empty
ledger the panel reports rather than a throw that costs the session. */
const VERSION_LEDGER =
(window.__GRIDATLAS_MODULES__ || {}).versionLedger?.entries || [];
const PRE_SCOPE_COMPOSITIONS = 16;
const LEDGER_ID = 'gridatlas-version-ledger';
const LEDGER_DOCTRINE = 'Each row is immutable audit evidence, not a promise '
+ 'that it was live. REJECTED_PRE_PROMOTION entries were never live and are '
+ 'not rollback targets. A deployed bad composition is never repaired in place; '
+ 'an earlier deployed one is composed again under a new timestamp.';
function ledgerStamp(generation) {
return generation.slice(0, 4) + '-' + generation.slice(4, 6) + '-'
+ generation.slice(6, 8) + ' ' + generation.slice(8, 10) + ':'
+ generation.slice(10, 12) + ' UTC';
}
function installVersionLedger() {
if (document.getElementById(LEDGER_ID)) return;
const stack = document.querySelector('.map-controls');
if (!stack) { link.failures.push('no map-controls for the ledger'); return; }
const style = document.createElement('style');
style.id = LEDGER_ID + '-style';
style.textContent = SLD_STYLES.versionLedger(LEDGER_ID);
document.head.appendChild(style);
const panel = document.createElement('div');
panel.id = LEDGER_ID;
panel.dataset.open = '0';
const button = document.createElement('button');
button.type = 'button';
const newest = VERSION_LEDGER[VERSION_LEDGER.length - 1];
button.textContent = 'Versions \u00b7 ' + newest.v + ' \u25b8';
button.setAttribute('aria-expanded', 'false');
const body = document.createElement('div');
body.className = 'vl-body';
const rows = [...VERSION_LEDGER].reverse().map(entry =>
'<div class="vl-row"><div class="vl-head">'
+ '<span class="vl-ver">' + entry.v
+ (entry.status ? '<span class="vl-status">' + entry.status + '</span>' : '')
+ '</span>'
+ '<span class="vl-when">' + ledgerStamp(entry.g) + '</span></div>'
+ '<div class="vl-scope">' + entry.s + '</div>'
+ (entry.reason ? '<div class="vl-reason">' + entry.reason + '</div>' : '')
+ '</div>').join('');
body.innerHTML = rows
+ '<p class="vl-note">' + LEDGER_DOCTRINE + ' ' + PRE_SCOPE_COMPOSITIONS
+ ' earlier compositions predate '
+ 'the scope line. Extracted from the repository history at build time; '
+ 'nothing here is fetched or editable at runtime.</p>';
panel.appendChild(button);
panel.appendChild(body);
button.addEventListener('click', (event) => {
event.stopPropagation();
event.preventDefault();
const open = panel.dataset.open === '1';
panel.dataset.open = open ? '0' : '1';
button.textContent = 'Versions \u00b7 ' + newest.v + (open ? ' \u25b8' : ' \u25be');
button.setAttribute('aria-expanded', String(!open));
});
panel.addEventListener('click', (event) => event.stopPropagation());
stack.appendChild(panel);
link.version_ledger = { entries: VERSION_LEDGER.length, newest: newest.v,
rejected_pre_promotion: VERSION_LEDGER
.filter(entry => entry.status === 'REJECTED_PRE_PROMOTION').map(entry => entry.v) };
}
/* ── the Grid Finding Scope ───────────────────────────────────────────
Vikram: clicking blank space should show what grid is in the
vicinity. Until v9.62 a blank click cleared the map, which treated
everywhere that is not a consented project as empty. It is not empty;
it is unexamined.
The computation is the grid-scope module: this half only arms it,
draws it and writes it down. The neon project path is untouched and
remains the anchor - a scope never runs where a project or substation
was hit. */
const SCOPE_SRC = 'gridatlas-scope-src';
const SCOPE_RING_LAYER = 'gridatlas-scope-rings';
const SCOPE_DOT_LAYER = 'gridatlas-scope-dots';
const SCOPE_COLOUR = '#7fb5d8'; // cool blue: neither project nor declared
let scopeArmed = false;
/* Armed explicitly, like the scope. Published on the link object so a
reviewer can ask the page which modes are live. */
let pointArmed = false;
let scopeResult = null;
function scopeModule() {
try { return window.__GRIDATLAS_MODULES__?.gridScope || null; }
catch (_) { return null; }
}
function ensureScopeLayers(map) {
if (map.getSource(SCOPE_SRC)) return true;
if (!guardedAddSource(map, SCOPE_SRC, { type: 'geojson', data: emptyCollection() })) {
return false;
}
map.addLayer({ id: SCOPE_RING_LAYER, type: 'circle', source: SCOPE_SRC,
filter: ['==', ['get', 'kind'], 'band'],
paint: { 'circle-radius': ['get', 'pixels'], 'circle-color': 'transparent',
'circle-stroke-color': SCOPE_COLOUR, 'circle-stroke-width': 1,
'circle-stroke-opacity': 0.5 } });
map.addLayer({ id: SCOPE_DOT_LAYER, type: 'circle', source: SCOPE_SRC,
filter: ['==', ['get', 'kind'], 'site'],
paint: { 'circle-radius': 4, 'circle-color': SCOPE_COLOUR,
'circle-stroke-color': '#04141c', 'circle-stroke-width': 1 } });
return true;
}
function clearScope() {
scopeResult = null;
const map = capturedMap;
if (map && map.getSource(SCOPE_SRC)) setSourceData(map, SCOPE_SRC, emptyCollection());
document.querySelectorAll('.' + SCOPE_BLOCK).forEach(node => node.remove());
link.grid_scope = null;
}
const SCOPE_BLOCK = 'gridatlas-scope-block';
function scopeHtml(result) {
const bands = result.bands.map(band => {
const classes = Object.keys(band.by_class_kv)
.map(Number).sort((a, b) => b - a)
.map(kv => `${band.by_class_kv[kv]} \u00d7 ${kv} kV`).join(', ');
return `<li><span class="neon-km">${band.within_km} km</span>`
+ `<span class="neon-name">${band.substations
? escapeHtml(classes) : 'nothing mapped'}</span></li>`;
}).join('');
const nearest = result.nearest_named.slice(0, 3).map(entry =>
`<li><span class="neon-km">${entry.km.toFixed(2)} km</span>`
+ `<span class="neon-name">${escapeHtml(entry.name)}</span>`
+ `<span class="neon-kv">${entry.kv} kV</span></li>`).join('');
/* Which cartridges answered, on the card, not in a console.
------------------------------------------------------------------
Vikram: a click anywhere should make the neons "look for cartridges
and code". The looking is the source-registry module; this prints
what it found. A reader told that five of six sources answered and
which one did not can judge the answer in front of them. A reader
shown a quietly shorter answer cannot, and will reasonably assume
the map has told them everything it knows. */
const survey = result.sources || null;
const sourcesLine = survey
? `<p class="neon-caveat"><b>Sources:</b> ${escapeHtml(survey.sentence)}</p>`
: '';
return `<div class="${SCOPE_BLOCK} ${BLOCK_CLASS}">`
+ `<div class="neon-hd">Grid finding scope<span class="neon-beta">Beta</span></div>`
+ `<p class="neon-caveat">${escapeHtml(result.what_this_is)}</p>`
+ `<ol>${bands}</ol>`
+ (nearest ? `<div class="neon-hd">Nearest named</div><ol>${nearest}</ol>` : '')
+ topologyBlockHtml(result.nearest_named.slice(0, 3).map(entry => ({ name: entry.name, kv: entry.kv })))
+ `<p class="neon-caveat"><b>${escapeHtml(result.what_this_is_not)}</b></p>`
+ sourcesLine
+ `<p class="neon-caveat">${escapeHtml(result.method)}. `
+ `Substations as mapped in this release's payload; an absence here is `
+ `an absence from the map, not from the ground.</p></div>`;
}
async function runGridScope(map, origin) {
const scope = scopeModule();
if (!scope) { noteFailure('grid scope: module unavailable'); return; }
if (!link.substations_qualifying) {
injectStatusStyle();
showStatus('Reading the substation data for this area.', 'waiting');
}
const subs = await loadSubstations();
if (!subs.length) {
injectStatusStyle();
showStatus('The substation data did not load, so nothing can be counted '
+ 'here. This is usually the network rather than the place.', 'failed');
return;
}
clearStatus();
const result = scope.scope(origin, subs, { nearestCount: 5 });
/* Ask what could have answered, before saying what did.
------------------------------------------------------------------
The deep scan of 202609012230 found this path reporting only what
OpenStreetMap has mapped while the cartridge holding NESO's 886
published connection points sat loaded in the same page. The scope
still counts only what it can count - widening the computation is a
separate, provable change - but it no longer stays silent about the
sources it did not use. */
const registry = window.__GRIDATLAS_MODULES__?.sourceRegistry || null;
if (registry) {
try { result.sources = registry.survey(window); }
catch (error) { noteFailure('source registry: ' + String(error?.message || error)); }
}
scopeResult = result;
link.grid_scope = { counted: result.counted, radius_km: result.radius_km,
nearest_km: result.nearest[0]?.km ?? null,
sources_ready: result.sources?.ready || null,
sources_missing: result.sources?.missing || null };
if (ensureScopeLayers(map)) {
/* The bands are drawn in metres-per-pixel at the current zoom, so a
ring means the distance it says at the zoom it was drawn. */
const metresPerPixel = 156543.03392
* Math.cos(origin[1] * Math.PI / 180) / Math.pow(2, map.getZoom());
const features = result.bands.map(band => ({
type: 'Feature',
properties: { kind: 'band', pixels: (band.within_km * 1000) / metresPerPixel },
geometry: { type: 'Point', coordinates: origin }
})).concat(result.nearest.map(entry => ({
type: 'Feature', properties: { kind: 'site' },
geometry: { type: 'Point', coordinates: entry.at }
})));
setSourceData(map, SCOPE_SRC, { type: 'FeatureCollection', features });
}
const gl = window.maplibregl;
if (gl?.Popup) {
try {
new gl.Popup({ maxWidth: '360px', closeOnClick: false })
.setLngLat(origin)
.setHTML(scopeHtml(result))
.addTo(map);
} catch (error) {
noteFailure('grid scope card: ' + String(error?.message || error));
}
}
}
/* ── the mobile tray ──────────────────────────────────────────────────
Vikram's phone acceptance, 2026-09-01: the six shell tool buttons at
44px touch height are the right size to hit and the wrong size to keep
on screen - a third of a portrait map behind buttons - and the switches
that turn the grid lines and substations on live below the map, where a
phone never looks. Both are composition faults, not engine faults: the
44px rule is this cartridge's own coarse-pointer override, and the
engine's switches work - toggled live in Chrome, the lines drew at once.
So on a touch screen or a narrow window the six tool buttons collapse
behind one chip, and two first-class chips - GRID and SUBS - stand on
the map itself. They drive the engine's own checkboxes with real
clicks, the same path enableTechnologyLayer has used all along, so the
scada panel, the fullscreen curtain and these chips cannot disagree. */
const TRAY_ID = 'gridatlas-mobile-tray';
const GRID_LINE_LAYERS = ['400', '275', '220', '132', '66'];
function trayTarget() {
try {
return matchMedia('(pointer: coarse)').matches || window.innerWidth <= 700;
} catch (_) { return false; }
}
function engineLayerBox(id) {
return document.querySelector(
'#scada-ui-container input[type=checkbox][data-layer-id="' + id + '"]');
}
function installMobileTray() {
if (document.getElementById(TRAY_ID)) return;
/* GRID AND SUBS ON DESKTOP TOO.
---------------------------------------------------------------------
"in mobile view the Grid and subs buttons are nice show them on desktop
TOO" -- the architect, 2026-09-05. This used to return here, so on a
fine pointer the two chips were never CREATED at all; a later attempt to
fix this by changing where the menu bar hoists tray buttons did nothing,
because there was nothing to hoist.
What stays phone-only is the COLLAPSE: folding the six tool buttons
behind one chip exists because on a 393px portrait map they cover a
third of the screen, which is not true on a desktop and would be a
regression there. So `collapse` gates the tray behaviour, and the two
chips are built either way. */
const collapse = trayTarget();
link.mobile_tray = { installed: true, collapsed: collapse,
reason: collapse ? 'coarse pointer or narrow window' : 'chips only, fine pointer' };
const stack = document.querySelector('.map-controls');
if (!stack) { link.failures.push('no map-controls for the tray'); return; }
const style = document.createElement('style');
style.id = TRAY_ID + '-style';
style.textContent = SLD_STYLES.mobileTray(TRAY_ID);
document.head.appendChild(style);
if (collapse) stack.classList.add('gm-tools-collapsed');
const tray = document.createElement('div');
tray.id = TRAY_ID;
const tools = document.createElement('button');
tools.type = 'button';
tools.textContent = 'Tools \u25b8';
tools.setAttribute('aria-expanded', 'false');
tools.addEventListener('click', (event) => {
event.stopPropagation();
const collapsed = stack.classList.toggle('gm-tools-collapsed');
tools.textContent = collapsed ? 'Tools \u25b8' : 'Tools \u25be';
tools.setAttribute('aria-expanded', String(!collapsed));
});
function quickChip(labelText, ids) {
const chip = document.createElement('button');
chip.type = 'button';
chip.textContent = labelText;
chip.disabled = true;
chip.setAttribute('aria-pressed', 'false');
function reflect() {
const boxes = ids.map(engineLayerBox).filter(Boolean);
chip.disabled = boxes.length === 0;
chip.setAttribute('aria-pressed',
String(boxes.length > 0 && boxes.every((box) => box.checked)));
}
chip.addEventListener('click', (event) => {
event.stopPropagation();
const boxes = ids.map(engineLayerBox).filter(Boolean);
if (!boxes.length) return;
const turnOn = boxes.some((box) => !box.checked);
boxes.forEach((box) => { if (box.checked !== turnOn) box.click(); });
reflect();
});
chip.gmReflect = reflect;
return chip;
}
/* The tray tool. The shell owns .map-controls and the shell is
immutable, so the button is added by this cartridge at runtime and
removed again if the cartridge is not composed - there is no orphan
control left behind claiming a feature that is not present. */
(function addGridPointTool() {
const tray = document.querySelector('.map-controls');
if (!tray || document.getElementById('btn-gridpoint')) return;
const button = document.createElement('button');
button.className = 'map-ctrl-btn';
button.id = 'btn-gridpoint';
button.type = 'button';
button.textContent = '\u25c8 Grid At Point';
button.setAttribute('aria-pressed', 'false');
button.title = 'Click anywhere on the map for the published network at the nearest mapped connection point';
button.addEventListener('click', (event) => {
event.stopPropagation();
pointArmed = !pointArmed;
button.setAttribute('aria-pressed', String(pointArmed));
button.style.outline = pointArmed ? '1px solid currentColor' : '';
link.grid_point_armed = pointArmed;
if (!pointArmed) clearScope();
});
tray.appendChild(button);
}());
const grid = quickChip('\u26a1 Grid', GRID_LINE_LAYERS);
const subs = quickChip('\u25c9 Subs', ['subs']);
/* Arming is explicit. A map that analysed every stray tap would put a
card over the thing the reader was trying to look at. */
const scopeChip = document.createElement('button');
scopeChip.type = 'button';
scopeChip.textContent = '\u25ce Scope';
scopeChip.setAttribute('aria-pressed', 'false');
scopeChip.addEventListener('click', (event) => {
event.stopPropagation();
scopeArmed = !scopeArmed;
scopeChip.setAttribute('aria-pressed', String(scopeArmed));
if (!scopeArmed) clearScope();
link.grid_scope_armed = scopeArmed;
});
const clearChip = document.createElement('button');
clearChip.type = 'button';
clearChip.textContent = '\u2715 Clear';
clearChip.addEventListener('click', (event) => {
event.stopPropagation();
clearScope();
clearLinks();
});
/* Only GRID and SUBS cross to the desktop. The tools chip is the collapse
itself, and Scope and Clear are already one visible click away in the
menu there -- adding them would be redoing the desktop toolbar, which is
not what was asked for. */
if (collapse) tray.appendChild(tools);
tray.appendChild(grid);
tray.appendChild(subs);
if (collapse) tray.appendChild(scopeChip);
if (collapse) tray.appendChild(clearChip);
tray.addEventListener('click', (event) => event.stopPropagation());
stack.insertBefore(tray, stack.firstChild);
// The engine builds its switches only after the map loads; the chips
// wake when the switches exist and follow them wherever they are
// toggled from - scada panel, fullscreen curtain, or a deep link.
document.addEventListener('change', (event) => {
if (event.target?.dataset?.layerId) { grid.gmReflect(); subs.gmReflect(); }
});
let polls = 0;
const poll = setInterval(() => {
grid.gmReflect(); subs.gmReflect(); polls += 1;
if (!grid.disabled || polls > 200) clearInterval(poll);
}, 300);
link.mobile_tray = {
installed: true,
tools_collapsed: true,
grid_quick_layers: GRID_LINE_LAYERS.length,
subs_quick: true
};
}
function installGbConditions() {
if (document.getElementById(GB_ID)) return;
const stack = document.querySelector('.map-controls');
if (!stack) { link.failures.push('no map-controls for the GB panel'); return; }
const style = document.createElement('style');
style.id = GB_ID + '-style';
style.textContent = SLD_STYLES.gbConditions(GB_ID);
document.head.appendChild(style);
const panel = document.createElement('div');
panel.id = GB_ID;
panel.dataset.open = '0';
const button = document.createElement('button');
button.type = 'button';
button.textContent = 'GB prices · historic ▸';
button.setAttribute('aria-expanded', 'false');
const body = document.createElement('div');
body.className = 'gb-body';
panel.appendChild(button);
panel.appendChild(body);
let loaded = false;
button.addEventListener('click', (event) => {
// The panel lives inside the map container, so without this the click
// carries on to the map underneath and selects whatever is there.
event.stopPropagation();
event.preventDefault();
const open = panel.dataset.open === '1';
panel.dataset.open = open ? '0' : '1';
button.textContent = open ? 'GB prices · historic ▸' : 'GB prices · historic ▾';
button.setAttribute('aria-expanded', String(!open));
// Fetched on first open, never at boot: nothing about the map should
// wait on a third party, and most sessions never open this.
if (!open && !loaded) {
loaded = true;
body.innerHTML = '<p class="gb-note">Reading the decade…</p>';
renderGbConditions(body);
}
});
panel.addEventListener('click', (event) => event.stopPropagation());
stack.appendChild(panel);
link.gb_panel_installed = true;
}
/* Never dereference a source without checking it is there.
----------------------------------------------------------------------
addSource throws if the style is not loaded, and a source that failed to
add reads back as null. Both happen: the basemap CDN served style.json and
then no tiles at all on this estate tonight, and the cartridge now boots on
the style rather than a painted frame precisely so it can work in that
condition.
The pin was guarded when that was found. Five call sites were not, and
they are the ones that draw the links, the nodes and the whole layout — so
the guarded convenience survived while the substance would have thrown.
Codex's gate has been finding this class all night; this is the last of it
in this file.
Returning false rather than throwing means a missing source costs the
drawing, not the card, the distances or the session. */
function setSourceData(map, id, data) {
try {
const source = map?.getSource?.(id);
if (!source || typeof source.setData !== 'function') {
link.failures.push('source missing, nothing drawn: ' + id);
return false;
}
source.setData(data);
return true;
} catch (error) {
link.failures.push('source ' + id + ': ' + String(error?.message || error));
return false;
}
}
function interactiveLayerIds(map) {
// Whatever the engine has made visible and interactive. Reading the style
// rather than hard-coding ids keeps this working as layers come and go.
try {
return map.getStyle().layers
.filter(layer => /^l-/.test(layer.id) && layer.type !== 'background')
.map(layer => layer.id)
.filter(id => {
try { return map.getLayoutProperty(id, 'visibility') !== 'none'; }
catch (_) { return false; }
});
} catch (_) {
return [];
}
}
function install(map) {
installStyles();
ensureLayers(map);
/* Warm the substation payload immediately. It is 1.2 MB and every
measurement needs it; until v9.54 it was first requested only after
the arrival had finished waiting for the engine's layer controls,
so a phone paid for the wait AND the fetch in series. The promise is
cached, so the arrival reuses whatever this started. */
try { loadSubstations(); } catch (_) { /* the arrival will retry */ }
// The lines belong to the card. When the card closes, they go with it --
// leaving neon on the map with nothing explaining it is how a screenshot
// ends up quoted without its caveat.
const popupWatcher = new MutationObserver(() => {
if (link.links_drawn > 0 && !document.querySelector('.maplibregl-popup')) clearLinks();
});
try {
popupWatcher.observe(map.getContainer(), { childList: true, subtree: true });
} catch (error) {
link.failures.push(String(error?.message || error));
}
// Registered after the engine's own click handler, so the engine's popup
// opens first and this decorates it rather than racing it.
// Measure and draw for one selection. Split out of the click handler so a
// deep link, which opens a card without anybody clicking, goes through
// exactly the same path.
async function selectAt(origin, name, tech, fromSubstation, statedMw,
expectedArrivalEpoch = null) {
const fromCurrentArrival = Number.isInteger(expectedArrivalEpoch);
if (fromCurrentArrival) {
if (!arrivalGate.isCurrent(expectedArrivalEpoch)) return false;
} else {
invalidatePendingArrival('new-selection');
}
clearScope();
// Keep a provisional declared block standing until the measured one
// replaces it; clearing here would blank the card mid-arrival.
if (!currentDeclared?.pending) currentDeclared = null;
currentNearest400 = null;
currentPolicy = null;
if (fromSubstation) {
// No fetch needed: the projects are already in the engine's own
// source, and reading them there keeps one set of coordinates.
const found = nearestProjects(map, origin[0], origin[1]);
drawLinks(map, origin, name, tech, found.links, 'from-substation',
null, found.loaded);
return;
}
/* OFFSHORE MEASURES NOW.
--------------------------------------------------------------------
This used to return here with an empty link list and a card that
explained why nothing was measured. It measures instead. An offshore
project reaches an offshore substation, an export cable and a
landfall before anything onshore - every word of that is still true
and still printed - but the export cable does land at an onshore
substation, so the distance to the nearest mapped one is a
measurement of a real thing rather than a number with nothing behind
it. Withholding it was over-caution.
The route reasoning is not deleted; it moves from being the reason
there is no number to being the caveat beside the number, which is
where the estate puts every other thing a distance cannot answer.
No onshore-only filter is applied, and the card says so. The pinned
substation product carries the OSM `location` tag on zero of its
5,800 features, and of the 14 whose NAME contains "offshore" at least
4 are onshore substations serving an offshore farm - Hornsea at
400/220 kV among them, which is exactly a landfall connection. A
name-based filter would drop those four from the search it was meant
to sharpen. Measured, not assumed; the module carries the counts. */
const policy = coverage.policy(tech);
currentPolicy = policy;
if (!link.substations_qualifying) {
injectStatusStyle();
showStatus('Loading the substation data \u2014 the links need it.',
'waiting');
}
const subs = await loadSubstations();
if (fromCurrentArrival && !arrivalGate.isCurrent(expectedArrivalEpoch)) return false;
if (!subs.length) {
/* The register carries 5,800 substations; zero qualifying means the
payload did not arrive, not that the map is empty here. Drawing
nothing silently is how this looked broken on a phone. */
injectStatusStyle();
showStatus('The substation data did not load, so no links can be '
+ 'drawn. This is usually the network rather than the project.',