In this section
- Single-Line Diagram (SLD) Sandbox V9 8 geodesy · globalgrid2050 / testcode/202609051152/atlas/cartridges/202609050354-sld-sandbox-v9-8.js lines 4201–4900
Single-Line Diagram (SLD) Sandbox V9 8
A JavaScript file in the cartridges folder of GlobalGrid2050 that maps connection points, GB transmission network, price decade rollup and grid substations, using haversine.
Set aside from the main view: 95% of its lines are the same as testcode/202609060300/atlas/cartridges/202609060300-sld-sandbox.js (globalgrid2050), which stays. (near-copy-of, proposed by families.py). 95% of lines shared with Single-Line Diagram (SLD) Sandbox; read that one first. All set-aside files, with reasons. Nothing was deleted.
Evidence
- line-jaccard 0.9509 to globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 testcode/202609060300/atlas/cartridges/202609060300-sld-sandbox.js:1-7736 b9451a6d240116dae04211c0cc8216a75da78ad1
- sha256 7c2df5dabb0082d4cef941b98bf31e92161d1e79a7d22bd6c84e81b171507022
- target sha256 93d81bebf3d1cf8f799ccf6f117f1565777ed88110481c284713589539586605
- group of 2 (identity.json near-copy edges >= 0.9)
- canonical rule: reachable, newest stamp, core repo, most lines
geodesyglobalgrid2050 / testcode/202609051152/atlas/cartridges/202609050354-sld-sandbox-v9-8.js · lines 4201–4900 of 7382 · version 2026-09-05 03:54 (continued from section 339) · Not reached from any entry point (candidate for review) · pattern widerFleetBuckets (shared by 6 files)
- What it does
- It maps connection points, GB transmission network, price decade rollup and grid substations. Defines 217 functions or classes, including classOf, scope, survey, ready, worksAt. Side effects: changes the web page (DOM); reads or writes files; makes network requests; uses storage (browser storage, DuckDB or Parquet).
- Why it exists in the grid workflow
- Domain stage experimental (path word 'sandbox'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow. Domain terms in the code: 750kV, 415kV, 400kV, 275kV, 220kV, 132kV.
- Inputs & outputs
- In: JSON file connection-points.v3.json; JSON file gb-transmission-network.v1.json; JSON file price-decade-rollup.json; 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, 110kV, 66kV.
- What it achieves
- It builds stats (`buildStats`), applies development stage defaults (`applyDevelopmentStageDefaults`) and applies mounting bifacial (`applyMountingBifacial`). ASSEMBLED by `tools/build-cartridge.mjs` from the parts below. Its code works with 400 kV, 132 kV and 33 kV. It responds to click, keydown and touchstart events.
- Why it matters
- No other file in the estate was found to import it.
- Application
- globalgrid2050 · testcode/202609051152/atlas/cartridges · 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
- mentioned in Standalone (comment link)
- Produces
- classOf, scope, survey, ready, worksAt, provisional, resolve, nearestTransmission, physicalInputs, buildStats, consistency, stringStats
- Defines here
- enableSubstationLayer, fromOwnUi, statusHost, showStatus, clearStatus, retryArrival, retryIdentityOwnerThenArrival, injectStatusStyle, watchForLayerControls, waitForLayerControls, enableTechnologyLayer, ensurePinLayers, setPin, clearPin, togglePin, styleTextFont, glyphsReachable, addLabelLayerWhenDrawable, gbNumber, gbRow, gbProductError
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 testcode/202609051152/atlas/cartridges/202609050354-sld-sandbox-v9-8.js:4201-4900 · blob f66bb0bcbf98ce7cd519581375865ca92f816b61 · 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
type: 'Feature',
properties: {
colour,
// The nearest link burns brightest; the rest fade back in order, so
// rank is legible without reading the numbers.
strength: Math.max(0.20, 0.62 - index * 0.10),
km: l.km
},
geometry: { type: 'LineString', coordinates: [origin, l.at] }
}));
const nodes = links.map(l => {
const tail = l.kv && l.kv.length ? `${l.kv[0]} kV`
: (l.mw != null ? `${l.mw} MW` : '');
return {
type: 'Feature',
properties: {
colour,
label: tail ? `${l.km.toFixed(2)} km · ${tail}` : `${l.km.toFixed(2)} km`
},
geometry: { type: 'Point', coordinates: l.at }
};
});
if (direction === 'to-substation' && currentDeclared?.at) {
// The declared link is public record, drawn in its own colour so it
// never reads as one more nearest-neighbour measurement.
const unbuilt = currentDeclared.poc_status === 'not_built'
|| currentDeclared.poc_status === 'under_construction';
const declaredColour = unbuilt ? DECLARED_UNBUILT_COLOUR : DECLARED_COLOUR;
lines.push({ type: 'Feature',
properties: { colour: declaredColour, strength: 0.85, km: currentDeclared.km },
geometry: { type: 'LineString', coordinates: [origin, currentDeclared.at] } });
nodes.push({ type: 'Feature',
properties: { colour: declaredColour,
label: `PoC \u00b7 ${currentDeclared.km.toFixed(2)} km \u00b7 ${currentDeclared.kv} kV` },
geometry: { type: 'Point', coordinates: currentDeclared.at } });
}
setSourceData(map, SRC, { type: 'FeatureCollection', features: lines });
setSourceData(map, SRC_NODES, { type: 'FeatureCollection', features: nodes });
// The popup is built by the engine and rendered synchronously in its own
// click handler, but MapLibre attaches it on the next frame in some paths.
// One retry covers that without polling forever.
armCardKeeper(links, direction, layerLoaded);
if (!injectIntoCard(links, direction, layerLoaded)) {
requestAnimationFrame(() => injectIntoCard(links, direction, layerLoaded));
}
startAnimation(map);
link.links_drawn = links.length;
link.last_selection = { name, tech, direction, count: links.length,
nearest_km: links.length ? Number(links[0].km.toFixed(3)) : null };
lastSelection = { origin, name, tech, direction, links, statedMw: statedMw || null };
if (direction !== 'from-substation') setPin(map, origin, name, tech);
}
/* ── selection ───────────────────────────────────────────────────────── */
// Tick the engine's own Subs control. Going through the checkbox means the
// engine hydrates the layer, updates its UI state and stays the owner of it;
// adding the source here instead would leave its panel lying about what is on.
function enableSubstationLayer() {
try {
/* The engine tags its own controls with data-layer-id, and that is
what enableTechnologyLayer and the mobile tray have both used for
generations. This searched LABEL TEXT for "subs " instead, which
is the one part of a control guaranteed to change: the labels
carry live counts and a [WAIT]/[OK]/[LOAD] state. Attribute
first; the label stays only as a fallback for a control that
somehow lacks it. Codex, 202609011823. */
const box = document.querySelector('input[type=checkbox][data-layer-id="subs"]')
|| [...document.querySelectorAll('input[type=checkbox]')].find((input) => {
const label = (input.closest('label') || input.parentElement)?.textContent || '';
return label.replace(/\s+/g, ' ').trim().toLowerCase().startsWith('subs ');
});
if (!box) { noteFailure('subs: control not found'); return false; }
if (!box.checked) box.click();
link.substation_layer_enabled = true;
recoverFailures(/^subs: control not found$/);
return true;
} catch (error) {
link.failures.push('subs: ' + String(error?.message || error));
return false;
}
}
// True when a click came from one of our own surfaces -- the card block or
// the layout panel -- rather than from the map itself. MapLibre delivers
// container clicks as map clicks, so without this every button we add fires
// whatever is under it.
function fromOwnUi(event) {
const target = event?.originalEvent?.target;
if (!target || typeof target.closest !== 'function') return false;
return Boolean(target.closest('.maplibregl-popup')
|| target.closest('#gridatlas-sld-panel'));
}
// The engine's own layer control for a technology. Arriving from Pipeline
// News the project itself was invisible: the deep link switched the
// substations on and left the project's layer off, so the card described a
// scheme with no pixel under it and the links appeared to start from nowhere.
// The engine tags each layer control with the layer it drives:
// <input type=checkbox data-layer-id="solar">
// so the technology IS the hook, and no mapping table is needed. Matching on
// the label text worked, but the labels carry live counts -- "Solar PV [2819
// | 52.3GW]" -- so it was matching prose that changes with the data. The
// label match stays as a fallback for a control the engine has not tagged.
const TECH_LABEL_FALLBACK = {
solar: "Solar PV [", solar_operational: "Solar PV (Operational",
solar_roof: "Solar Roof [",
bess: "Battery Storage [", bess_operational: "Battery Storage (Operational",
wind: "Wind [", wind_onshore_operational: "Onshore Wind (Operational",
};
/* ── say what is happening ────────────────────────────────────────────
Vikram, tonight: "the map feature from pipelinenews doesnt load on
iphone". Reproduced in kind on the desktop: a black rectangle, no
controls, and a deep link waiting for substations that could not arrive.
Nothing on screen said so. A black map is indistinguishable from a broken
one, and the reader is left to guess which they have.
The Atlas boots a 35.7 MB query engine before it can answer anything. On
a phone over cellular that is a long wait and sometimes not a wait at all,
and the honest thing is to say which. This chip says what is being waited
for, and when the wait has failed it says that too, with a way to try
again -- because a retry after the network recovers is usually all it
needs, and a reload throws away the deep link.
It removes itself the moment the controls arrive, so a working Atlas is
never decorated with news about itself. */
const STATUS_ID = 'gridatlas-boot-status';
function statusHost() {
return document.querySelector('.maplibregl-map') || document.body;
}
function showStatus(message, kind) {
try {
let el = document.getElementById(STATUS_ID);
if (!el) {
el = document.createElement('div');
el.id = STATUS_ID;
el.setAttribute('role', 'status');
el.setAttribute('aria-live', 'polite');
statusHost().appendChild(el);
}
el.dataset.kind = kind || 'waiting';
el.textContent = message;
if (kind === 'failed') {
const again = document.createElement('button');
again.type = 'button';
again.textContent = 'Try again';
again.addEventListener('click', (event) => {
event.stopPropagation();
event.preventDefault();
retryArrival();
});
el.appendChild(again);
}
link.status_message = message;
} catch (error) {
link.failures.push('status: ' + String(error?.message || error));
}
}
function clearStatus() {
document.getElementById(STATUS_ID)?.remove();
link.status_message = null;
}
// Re-run the arrival rather than reloading: a reload on a phone repeats the
// whole 35.7 MB boot, and the deep link is in the URL either way.
let retryArrival = () => {};
let rerunDeepLink = null;
async function retryIdentityOwnerThenArrival() {
clearStatus();
const owner = window.__GRIDATLAS_PLACE_SEARCH__;
if (typeof owner?.retry_exact_deep_link !== 'function') {
showStatus('The active-register identity owner cannot retry in this composition.',
'failed');
return false;
}
const invalidatedEpoch = invalidatePendingArrival('identity-retry');
const retryEpoch = claimPendingArrival(window.location.search);
link.arrival_retry = {
status: 'OWNER_PENDING', invalidated_epoch: invalidatedEpoch,
owner_epoch: retryEpoch, measurement_epoch: retryEpoch
};
try {
await owner.retry_exact_deep_link(retryEpoch);
} catch (error) {
link.arrival_retry.status = 'FAILED';
showStatus('The active-register identity retry failed: '
+ String(error?.message || error), 'failed');
return false;
}
const terminal = window.__GRIDATLAS_PLACE_SEARCH__?.deep_link;
if (!arrivalGate.isCurrent(retryEpoch)
|| terminal?.owner_epoch !== retryEpoch
|| terminal?.status === 'CANCELLED') {
link.arrival_retry.status = 'CANCELLED';
return false;
}
if (terminal?.status === 'FAILED') {
link.arrival_retry.status = 'FAILED';
showStatus('The active-register identity check failed: '
+ String(terminal.message || 'identity loader unavailable'), 'failed');
return false;
}
if (typeof rerunDeepLink !== 'function') {
link.arrival_retry.status = 'FAILED';
showStatus('The grid measurement owner cannot retry in this composition.',
'failed');
return false;
}
link.arrival_retry.status = 'MEASUREMENT_PENDING';
const completed = await rerunDeepLink(retryEpoch);
if (!arrivalGate.isCurrent(retryEpoch)) {
link.arrival_retry.status = 'CANCELLED';
return false;
}
link.arrival_retry.status = terminal.status === 'NOT_IN_ACTIVE_REGISTER'
? 'NOT_IN_ACTIVE_REGISTER' : (completed === false ? 'FAILED' : 'RESOLVED');
return completed !== false;
}
function injectStatusStyle() {
if (document.getElementById(STATUS_ID + '-style')) return;
const style = document.createElement('style');
style.id = STATUS_ID + '-style';
style.textContent = SLD_STYLES.bootStatus(STATUS_ID);
document.head.appendChild(style);
}
// Resolve when the engine has rendered its layer dashboard, or when the
// wait is up. Returning false is a fact worth having, not an error: it says
// the engine had not finished, which is a different problem from the layer
// being missing.
/* Watch for the controls; do not guess how long they will take.
----------------------------------------------------------------------
A fixed budget is always the wrong number. Twelve seconds was generous on
one load and hopeless on the next: the engine builds its layer dashboard
from its own data, and that has been measured arriving in two seconds and
not arriving at all in eighty-six.
Giving up after a budget also gave up permanently. If the dashboard
appeared at thirteen seconds -- which it often does -- the layers the
arrival depends on stayed off for the rest of the session, with a card on
screen saying the grid data had not loaded while the controls sat there.
So: the wait still bounds how long the user is asked to look at a spinner,
because that is a promise about the interface. But an observer keeps
watching afterwards, and switches the layers on whenever they arrive,
however late. The status line is cleared at the same moment, because a
failure notice that outlives the failure is its own bug.
The observer disconnects the first time it fires. It is not a subscription
to the page; it is one deferred question. */
const LAYER_CONTROL = 'input[type=checkbox][data-layer-id]';
let layerWatcher = null;
function watchForLayerControls(onReady) {
if (layerWatcher || typeof MutationObserver !== 'function') return;
try {
layerWatcher = new MutationObserver(() => {
if (!document.querySelector(LAYER_CONTROL)) return;
layerWatcher.disconnect();
layerWatcher = null;
link.layer_controls_arrived_late = true;
recoverFailures(/^the engine had not rendered its layer controls within/);
clearStatus();
try { onReady(); } catch (error) {
link.failures.push('late layers: ' + String(error?.message || error));
}
});
layerWatcher.observe(document.body, { childList: true, subtree: true });
} catch (error) {
link.failures.push('layer watcher: ' + String(error?.message || error));
layerWatcher = null;
}
}
/* iOS Safari, reported live by the architect and reproduced independently
against a page opened hidden: this budget used to be charged in WALL
CLOCK time regardless of whether anyone could see the result of
spending it. Pipeline News' MAP control opens on touch devices with
target="_blank", and on iOS Safari a background tab is not guaranteed
to be composited while the reader is still looking at the page they
tapped from -- requestAnimationFrame does not tick there, so the
engine's own dashboard build (which the boot trigger gates behind
style.load/load, both paint-driven) can stall for the WHOLE budget
without ever having had a real chance. Elapsed time while hidden buys
nothing observable and is not charged against the budget; only time
the tab was actually visible counts down. */
async function waitForLayerControls(budgetMs) {
let elapsed = 0;
const started = Date.now();
/* Visible time governs the BUDGET; wall clock still bounds the WAIT.
----------------------------------------------------------------------
Charging the budget in visible time is what stops a background tab
spending it before anyone can see the result. But a tab that is never
made visible would then poll every 200ms forever, which is a hang by any
honest definition and costs battery on the device least able to afford
it. So an absolute ceiling backstops the visible-time budget: whichever
runs out first ends the wait. Ten minutes matches the last-resort stop
the arrival lane already uses for a lane that died silently. */
const HARD_CEILING_MS = 600000;
if (!document.querySelector(LAYER_CONTROL)) {
injectStatusStyle();
showStatus('Switching the grid layers on as soon as the map\u2019s own '
+ 'controls appear. The distances do not wait for them.', 'waiting');
}
while (elapsed < budgetMs && Date.now() - started < HARD_CEILING_MS) {
if (document.querySelector(LAYER_CONTROL)) {
/* Both clocks are published, because they answer different questions:
visible time is what the budget was actually spent from, wall time
is what the reader sat through. Reporting only one of them makes a
background arrival look instant or a foreground one look slow. */
link.layer_controls_ready_ms = Date.now() - started;
link.layer_controls_ready_visible_ms = elapsed;
clearStatus();
return true;
}
await new Promise(resolve => setTimeout(resolve, 200));
if (document.visibilityState === 'visible') elapsed += 200;
}
link.layer_controls_ready_ms = null;
link.failures.push(
'the engine had not rendered its layer controls within '
+ Math.round(budgetMs / 1000) + 's; still watching, and the layers will '
+ 'be switched on if they arrive');
if (link.links_drawn > 0) {
// The answer is already on the map. Late layers are not a failure the
// reader has to act on, and a red notice over a working map is noise.
clearStatus();
} else {
injectStatusStyle();
showStatus('The grid data has not finished loading yet. The distances '
+ 'below are already measured; the layers will switch on by themselves '
+ 'if it arrives.', 'failed');
}
return false;
}
function enableTechnologyLayer(tech) {
if (!tech) return false;
// Resolved through the ONE table above. 'wind_onshore' and
// 'wind_offshore' are Pipeline buckets, not layer ids -- searching the
// DOM for a control literally named that always failed. 'other' has no
// layer at all, and is said plainly rather than searched for.
const layerId = layerIdForBucket(tech);
if (layerId === null) {
link.technology_layer = Object.assign({}, link.technology_layer, {
requested: tech, layer_id: null, enabled: false,
reason: 'GridAtlas has no map layer for the "' + tech + '" technology; '
+ 'nothing to switch on. The card and the distances above it are '
+ 'unaffected.'
});
return false;
}
try {
const boxes = [...document.querySelectorAll('input[type=checkbox]')];
let box = boxes.find((input) => input.dataset?.layerId === layerId);
if (!box) {
const label = TECH_LABEL_FALLBACK[layerId];
if (label) {
box = boxes.find((input) => {
const text = (input.closest('label') || input.parentElement)?.textContent || "";
return text.replace(/\s+/g, " ").trim().toLowerCase()
.startsWith(label.toLowerCase());
});
}
}
if (!box) { noteFailure('layer control not found: ' + layerId); return false; }
if (!box.checked) box.click();
link.project_layer_enabled = layerId;
// The field a reader (and every prior proof) actually trusted must
// say what happened, not what the request's bucket merely belonged
// to. Set here, on the ONE path that turns a control on, rather than
// synthesised from set membership before this ever ran.
link.technology_layer = Object.assign({}, link.technology_layer, {
requested: tech, layer_id: layerId, enabled: true, reason: null
});
recoverFailures(new RegExp('^layer control not found: '
+ String(layerId).replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '$'));
return true;
} catch (error) {
link.failures.push('layer: ' + String(error?.message || error));
return false;
}
}
/* ── the project pin ─────────────────────────────────────────────────
A marker for the selected project, drawn by this cartridge rather than
borrowed from a layer.
The engine's technology layers are hydrated on demand and can be switched
off by the user, so a project arriving by deep link may have no pixel at
all. This one does not depend on any of that: it is the thing the card is
about, and while a card is open its subject should be visible on the map.
It toggles, because a pin over the site is exactly what you want out of the
way when you are looking at the site. */
const SRC_PIN = 'gridatlas-project-pin';
const L_PIN_HALO = 'l-project-pin-halo';
const L_PIN = 'l-project-pin';
let pinVisible = true;
function ensurePinLayers(map) {
// addSource throws if the style is not loaded, and a source that failed to
// add reads back as null. The pin is a convenience: it may not be the
// reason a card fails to open.
if (!map || typeof map.addSource !== 'function') return false;
if (map.getSource(SRC_PIN)) return true;
try {
map.addSource(SRC_PIN, { type: 'geojson', data: { type: 'FeatureCollection', features: [] } });
/* A ring around the site, not a dot on it.
------------------------------------------------------------------
A filled dot in the technology colour was invisible: it sat under the
engine's own pixel for the same project, and the neon links converging
on it are drawn in that same colour, so it disappeared into its own
arrival point. Seen in Chrome at zoom 12 on Botley West -- position
exactly right, nothing to look at.
A ring solves all three. It does not duplicate the engine's pixel,
because it surrounds it. It reads against the links, because it crosses
them rather than joining them. And it answers the question the marker
exists for -- which of these is the one the card is about -- which a
second dot among dots cannot. */
map.addLayer({
id: L_PIN_HALO, type: 'circle', source: SRC_PIN,
paint: {
'circle-radius': ['interpolate', ['linear'], ['zoom'], 6, 11, 14, 26],
'circle-color': 'rgba(0,0,0,0)',
'circle-stroke-color': ['get', 'colour'],
'circle-stroke-width': 6,
'circle-stroke-opacity': 0.13,
'circle-blur': 0.4,
},
});
map.addLayer({
id: L_PIN, type: 'circle', source: SRC_PIN,
paint: {
'circle-radius': ['interpolate', ['linear'], ['zoom'], 6, 11, 14, 26],
// Hollow: whatever the engine draws for this project stays readable
// inside it.
'circle-color': 'rgba(0,0,0,0)',
// Pale, not white. It has to separate from the technology colour it
// encircles without becoming the loudest thing on a dark map.
'circle-stroke-color': '#cfe9ed',
'circle-stroke-width': 1.6,
'circle-stroke-opacity': 0.85,
},
});
} catch (error) {
link.failures.push('pin: ' + String(error?.message || error));
return false;
}
return Boolean(map.getSource(SRC_PIN));
}
function setPin(map, origin, name, tech) {
if (!ensurePinLayers(map)) return;
const source = map.getSource(SRC_PIN);
if (!source || typeof source.setData !== 'function') return;
const colour = TECH_COLOUR[tech] || SUBSTATION_COLOUR;
source.setData({
type: 'FeatureCollection',
features: origin && pinVisible ? [{
type: 'Feature',
properties: { colour, name: name || '' },
geometry: { type: 'Point', coordinates: origin },
}] : [],
});
link.project_pin = { shown: Boolean(origin && pinVisible), name: name || null };
}
function clearPin(map) {
const source = map && map.getSource && map.getSource(SRC_PIN);
if (source && typeof source.setData === 'function') {
source.setData({ type: 'FeatureCollection', features: [] });
}
link.project_pin = { shown: false, name: null };
}
function togglePin() {
pinVisible = !pinVisible;
if (capturedMap && lastSelection) {
setPin(capturedMap, lastSelection.origin, lastSelection.name, lastSelection.tech);
}
return pinVisible;
}
link.togglePin = togglePin;
/* ── labels need glyphs, and glyphs can be absent ─────────────────────
A symbol layer cannot draw text without a glyph atlas, and maplibre does
not degrade when it cannot build one: it throws reading `width` off a null
atlas, and it does it again on the NEXT frame, and the next. Both of us
watching this estate tonight found the same storm from different ends --
Codex counted 50+ in about 20 seconds on mounting the layout, and a cold
load here produced 4,218. Same exception, and the two symbol layers in
this cartridge are the only text it draws.
Two ways to have no atlas: the style carries no `glyphs` endpoint at all,
or it has one and the named font is not served by it. The font name here
was assumed -- 'Open Sans Bold' -- rather than taken from the style that
has to serve it, so a basemap with a different font family produced text
that could never resolve.
So: ask the style. No glyphs endpoint means no labels, which is a quiet
map rather than a broken one. Otherwise use a font the style already uses
for its own labels, because that one is definitely served.
This matters most on a phone. An exception per frame is a main thread that
never idles, and on a phone that is heat, battery and a page that stops
answering touches. */
function styleTextFont(map) {
try {
const style = map.getStyle?.();
if (!style || !style.glyphs) return null;
for (const layer of style.layers || []) {
const font = layer?.layout?.['text-font'];
if (Array.isArray(font) && font.length && typeof font[0] === 'string') {
return font;
}
}
// A glyph endpoint with no symbol layer to learn from. This is the
// Mapbox/MapLibre default family and the one CARTO serves.
return ['Open Sans Bold', 'Arial Unicode MS Bold'];
} catch (error) {
link.failures.push('glyphs: ' + String(error?.message || error));
return null;
}
}
/* Having a glyphs endpoint is not the same as being able to reach it.
----------------------------------------------------------------------
Naming a font the style serves fixed one half. The other half was watched
live and is worse: the style declared
https://tiles.basemaps.cartocdn.com/fonts/{fontstack}/{range}.pbf
on the same CDN that had just returned 200 for style.json and then served
no vector tiles at all. A declared endpoint that cannot be reached gives
exactly the same null atlas as no endpoint, and 5,362 exceptions in thirty
seconds. Checking that the property exists proves nothing; the only honest
test is to ask for a range and see.
So fetch one - the first 256 codepoints, a few kilobytes, the same request
the renderer would make. If it does not come back, there are no labels.
That is a map without text, which is a great deal better than a map that
throws on every frame it ever draws.
Deferring the labels costs nothing: they are decoration over links that
are already on screen, and the distances they annotate are on the card. */
async function glyphsReachable(map, font) {
let template;
try { template = map.getStyle?.()?.glyphs; } catch (error) { template = null; }
if (!template || !font) return false;
const url = String(template)
.replace('{fontstack}', encodeURIComponent(font.join(',')))
.replace('{range}', '0-255');
try {
const response = await fetch(url, { cache: 'force-cache' });
if (!response.ok) {
link.failures.push('glyph range ' + response.status + '; labels omitted');
return false;
}
return true;
} catch (error) {
link.failures.push('glyph range unreachable; labels omitted');
return false;
}
}
// Add a symbol layer only once its text can actually be drawn. Callers do
// not await this: the labels arrive when they arrive, or never, and nothing
// else waits on them.
function addLabelLayerWhenDrawable(map, font, spec, what) {
glyphsReachable(map, font).then((ok) => {
link.labels_drawn = ok;
if (!ok) return;
try {
if (!map.getLayer(spec.id)) map.addLayer(spec);
} catch (error) {
link.failures.push(what + ' labels: ' + String(error?.message || error));
}
});
}
/* ── GB grid conditions, from the tracker that already measures them ───
The estate already has an application that tracks GB electricity:
globalgrid2050.com/uk_energy_tracking_v6, backed by Ventusltd/
data-gb-electricity. The Atlas had no idea it existed, so a map of where
the country is building generation could not tell you what the system was
doing.
This does not port that application. It is 49 MB, and the Atlas already
boots a 35.7 MB query engine before it can answer anything -- adding a
second one would be a way of making both worse. It reads the small
published feeds the tracker writes, one to four kilobytes each, and links
to the full application for everything else. The tracker stays the place
the analysis lives.
HONESTY ABOUT AGE. Measured when this was written, those feeds were
stamped 2026-06-18: about ten weeks old. A panel that prints a price with
no date implies it is current, and a stale number presented as live is
worse than no number. So the age is always shown, and past a day it is
labelled as not current rather than merely dated. If the feeds start
updating again the same panel gets better on its own.
Mobile first: it opens collapsed, sized against the viewport, and is a
single column on a narrow screen. */
/* What a megawatt hour has been worth in the available historic record.
----------------------------------------------------------------------
A map of where the country is building generation should be able to say
what the system has been doing while it was built.
IT READS THE DATA REPOSITORY, NOT A COPY. The governing rule in the
estate's migration scope is "data before charts": a consumer must read a
data product that already sits clean, and must never own source data or
become a second source of truth. So this reads
Ventusltd/data-gb-electricity, which owns the Parquet and publishes a
browser-sized rollup derived from it. An earlier version of this panel read a
copy derived inside globalgrid2050; that copy was a second definition of
the same numbers and has been retired in favour of this one.
A ROLLUP, NOT A HUNDRED MEGABYTES. Settlement-period history is the right
size for a chart someone chose to open and the wrong size for a panel
inside a map on a phone, which is where most readers arrive.
THE MEASUREMENT STOPS WHERE THE PRODUCT STOPS. A negative system price is
an observed market value. It does not by itself establish a local network
constraint, curtailment, connection capacity, a usable charging window or
the economics of any project on this map.
SOLAR IS ABSENT, AND SAYS SO. PVLive has not been decided into the data
repository, so the product declares solar absent rather than carrying a
series from somewhere else. A panel that quietly filled that gap from a
second source would be the exact thing the discipline forbids. */
const GB_PIN_ID = 'price-decade-rollup';
const GB_ROLLUP = PINS ? PINS.url(GB_PIN_ID) : null;
const GB_APP = 'https://globalgrid2050.com/uk_energy_tracking_v6/';
const GB_ID = 'gridatlas-gb-conditions';
const GB_SCHEMA = 'data-gb-electricity.price-decade-rollup.v2';
/* Loader state on the window, as the topology loader's is, so the source
registry can say whether this product answered, was withheld (reached,
not the schema this consumer answers) or failed - generation 202609012217. */
const gbLoader = { state: 'idle', product: GB_ROLLUP, schema_required: GB_SCHEMA,
schema: null, reason: null, error: null, renders: 0 };
window.__GRIDATLAS_GB_CONDITIONS__ = gbLoader;
const gbNumber = (value, digits) =>
Number.isFinite(Number(value)) ? Number(value).toFixed(digits) : '--';
function gbRow(label, value, unit) {
return `<div class="gb-row"><span class="gb-k">${label}</span>`
+ `<span class="gb-v">${value}<em>${unit || ''}</em></span></div>`;
}
function gbProductError(product) {
if (!product || product.schema !== GB_SCHEMA) return 'owner product v2 is not available';
const price = product.price || {};
const derived = product.derived_from || {};
const years = Array.isArray(price.by_year) ? price.by_year : [];
if (!years.length) return 'year rows are absent';
const included = years.reduce((sum, row) => sum + Number(row.days_included), 0);
const negative = years.reduce((sum, row) =>
sum + Number(row.days_with_a_negative_settlement_period), 0);
if (included !== Number(derived.included_days)) return 'included-date total disagrees';
if (negative !== Number(price.days_with_a_negative_settlement_period)) {
return 'negative-date total disagrees';
}
const validYears = years.every(row => {
const days = Number(row.days_included);
const calendarDays = Number(row.calendar_days);
const status = days === calendarDays ? 'FULL_DATE_COVERAGE' : 'PARTIAL_DATE_COVERAGE';
const coverage = 100 * days / calendarDays;
const share = 100 * Number(row.days_with_a_negative_settlement_period) / days;
return days === Number(row.days)
&& calendarDays >= days
&& row.calendar_date_coverage === status
&& Math.abs(Number(row.calendar_date_coverage_pct) - coverage) < 0.011
&& Math.abs(Number(row.negative_period_day_share_pct) - share) < 0.011;
});
if (!validYears) return 'year coverage or share disagrees';
if (Math.abs(Number(price.negative_period_day_share_pct)
- (100 * negative / included)) >= 0.011) return 'record share disagrees';
for (const extreme of [price.lowest_settlement_period, price.highest_settlement_period]) {
if (!Number.isInteger(extreme?.settlement_period)
|| !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/u.test(extreme?.period_start_utc)) {
return 'extreme-period identity is incomplete';
}
}