In this section
- Single-Line Diagram (SLD) Without Layout geodesy · gridatlas / atlas/modules/202611222130-sld-without-layout.js lines 4901–5600
Single-Line Diagram (SLD) Without Layout
A JavaScript file in the atlas folder of GridAtlas that maps connection points, GB transmission network, price decade rollup and grid substations, using haversine.
Set aside from the main view: 100% of its lines are the same as atlas/modules/202612020205-secondary-neon-engine.js (gridatlas), which stays. (near-copy-of, proposed by families.py). 99% of lines shared with Secondary Neon Engine; read that one first. All set-aside files, with reasons. Nothing was deleted.
Evidence
- line-jaccard 0.9961 to gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 atlas/modules/202612020205-secondary-neon-engine.js:1-9008 26e5045a356c11088820207d3cbe95eb4b89374f
- sha256 6870cfb365c18b90363b664f89623c9217c3d0111a67b87fdd1b6b3a26aeba6b
- target sha256 b9e2b3ce36d3f46184c4a0f0416d70892feb49507d1c93833d3ab00a27c84263
- group of 3 (identity.json near-copy edges >= 0.9)
- canonical rule: reachable, newest stamp, core repo, most lines
geodesygridatlas / atlas/modules/202611222130-sld-without-layout.js · lines 4901–5600 of 8986 · version 2026-11-22 21:30 (continued from section 397) · Not reached from any entry point (candidate for review) · pattern isInterconnectorArrival (shared by 3 files)
- What it does
- It maps connection points, GB transmission network, price decade rollup and grid substations. Defines 273 functions or classes, including distanceKm, distanceKm, representativePoint, voltagesKv, destinationPoint. Side effects: changes the web page (DOM); reads or writes files; makes network requests; uses storage (browser storage, DuckDB or Parquet).
- Why it exists in the grid workflow
- Domain stage sub33kv_design (path word 'layout'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. Domain terms in the code: 750kV, 415kV, 400kV, 275kV, 220kV, 132kV.
- Inputs & outputs
- In: JSON file connection-points.v3.json; JSON file gb-transmission-network.v1.json; JSON file price-decade-rollup.json; GeoJSON file grid_substations.geojson; JSON file neso-connection-sites.lean.json; GeoJSON file interconnectors.geojson; browser storage (getItem); DuckDB queries. Out: browser storage (setItem); interactive map. Coordinate systems named: WGS84 / EPSG:4326. Voltage levels named: 750kV, 415kV, 400kV, 275kV, 220kV, 132kV, 110kV, 66kV.
- What it achieves
- It creates compute observer (`createComputeObserver`), describes compute receipt (`describeComputeReceipt`) and builds stats (`buildStats`). Receipt and distance owner: Ventusltd/ventus-grid-engine. Its code works with 400 kV, 132 kV and 33 kV. It responds to click, keydown and touchstart events.
- Why it matters
- No other file in the estate was found to import it.
- Application
- gridatlas · atlas/modules · script
- VEDIC
- MEASURE (GG2050-VEDIC-000001): GridAtlas / Geodesy · Mathematics / Spherical geometry. coordinate_pair, coordinate_pair → distance_km
- VEDIC
- REPRESENT (GG2050-VEDIC-000002): GridAtlas / Geodesy · Computer science / Geometry processing. geojson_geometry → coordinate_pair_or_null
- VEDIC
- VOLTAGE (GG2050-VEDIC-000003): GridAtlas / Geodesy · Computer science / Data normalisation. voltage_properties → kilovolt_list
- Uses
- none found
- Used by
- none found
- Produces
- distanceKm, distanceKm, representativePoint, voltagesKv, destinationPoint, initialBearingDeg, copy, finite, located, sameLocation, sameEntity, createComputeObserver
- Defines here
- holds, noteInput, onStart, onEnd, enableSubstationLayer, fromOwnUi, statusHost, showStatus, placeStatus, clear, settle, clearStatus, retryArrival, retryIdentityOwnerThenArrival, injectStatusStyle, watchForLayerControls, waitForLayerControls, enableTechnologyLayer, ensurePinLayers, setPin, clearPin, togglePin, styleTextFont, glyphsReachable
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 atlas/modules/202611222130-sld-without-layout.js:4901-5600 · blob ab6fc6992aa26e51a3c82d7e2d26172a50798c60 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, network, storage · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: unreached_review
nodes.push({ type: 'Feature',
properties: { colour: DECLARED_COLOUR,
label: 'Declared \u00b7 ' + currentNeso.km.toFixed(2) + ' km'
+ (currentNeso.kv ? ' \u00b7 ' + currentNeso.kv + ' kV' : '') },
geometry: { type: 'Point', coordinates: currentNeso.at } });
nesoDrawn = true;
}
setSourceData(map, SRC, { type: 'FeatureCollection', features: lines });
setSourceData(map, SRC_NODES, { type: 'FeatureCollection', features: nodes });
/* And framed. A line whose far end is 80 km outside the viewport is as
invisible as no line. When the declared connection is the only thing
drawn, the camera fits both ends; when nearest links are drawn too the
reader already has something in view and the camera is left alone. The
bottom padding keeps the far end above a phone's docked card. */
if (nesoDrawn && !links.length) {
try {
let sheet = false;
try { sheet = Boolean(sheetTarget()); } catch (_) { sheet = false; }
map.fitBounds(
[[Math.min(origin[0], currentNeso.at[0]), Math.min(origin[1], currentNeso.at[1])],
[Math.max(origin[0], currentNeso.at[0]), Math.max(origin[1], currentNeso.at[1])]],
{ padding: { top: 90, left: 40, right: 40, bottom: sheet ? 220 : 90 },
maxZoom: 10, duration: 900, essential: true });
link.declared_connection_framed = true;
/* And kept. The identity lane resolves the project against the
register over the network and flies to it at zoom 12 when it does -
1.2 s, essential - and on a real connection that lands AFTER this
frame, not before. Measured on Hornsea 3 in Chromium on the live
root: framed at zoom 7.06, then carried to 11.17 on the array with
Norwich Main gone off the bottom. Locally the register answered first
and the race never showed, which is the usual way a race hides.
So the frame re-asserts itself, at most twice and only within the
arrival window, if the camera leaves it without a person touching the
map. MapLibre sets originalEvent on user-initiated moves and leaves
it undefined on programmatic ones, and that is the whole test: a
reader who drags or pinches owns the camera from that moment on. */
const both = [
[Math.min(origin[0], currentNeso.at[0]), Math.min(origin[1], currentNeso.at[1])],
[Math.max(origin[0], currentNeso.at[0]), Math.max(origin[1], currentNeso.at[1])]];
const holds = () => {
try { const b = map.getBounds(); return b.contains(both[0]) && b.contains(both[1]); }
catch (_) { return true; }
};
/* v9.153 held this guard for twelve seconds and it never fired on the
live root: a cold DuckDB identity boot over a real connection takes
longer than that, so the late flight landed after the listeners were
gone. Measured in Chromium on Berwick Bank and Hornsea 3, both ending
at zoom 11 on the array with the far end lost. A clock is the wrong
shape for this. The guard now lives as long as the arrival does - it
is detached when the arrival gate moves, by clearLinks or a new
selection - and stands down the moment a person takes the map.
Two kinds of person. A drag or a pinch arrives with originalEvent on
the map's movestart. A tap on a control that then moves the camera
programmatically - the layout button, the scope tools - does not, so
any pointer, touch, key or wheel anywhere in the document within the
last three seconds is also read as the reader taking over. Otherwise
the frame would win a fight against a button the reader just
pressed, and that is the one fight it must lose. */
if (typeof declaredFrameGuard === 'function') { try { declaredFrameGuard(); } catch (_) {} }
let userOwned = false, reasserted = 0, lastInput = 0;
const noteInput = () => { lastInput = Date.now(); };
const onStart = (e) => { if (e && e.originalEvent) userOwned = true; };
const onEnd = () => {
if (userOwned || Date.now() - lastInput < 3000 || reasserted >= 2 || holds()) return;
reasserted += 1;
link.declared_frame_reasserted = reasserted;
try {
map.fitBounds(both, { padding: { top: 90, left: 40, right: 40, bottom: sheet ? 220 : 90 },
maxZoom: 10, duration: 600, essential: true });
} catch (_) { /* the first frame stands */ }
};
const inputEvents = ['pointerdown', 'touchstart', 'keydown', 'wheel'];
inputEvents.forEach(t => document.addEventListener(t, noteInput, { capture: true, passive: true }));
map.on('movestart', onStart);
map.on('moveend', onEnd);
declaredFrameGuard = () => {
try { map.off('movestart', onStart); map.off('moveend', onEnd); } catch (_) { /* gone */ }
inputEvents.forEach(t => { try { document.removeEventListener(t, noteInput, { capture: true }); } catch (_) {} });
declaredFrameGuard = null;
};
} catch (error) {
link.failures.push('declared frame: ' + String(error?.message || error));
}
}
// 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;
/* The engine has finished. Offshore is a different question from onshore -
an export cable lands at a declared point - and until that declaration
exists offshore is answered by the onshore engine. That is a legitimate
fallback and it is named as one rather than passed off as the answer. */
if (direction !== 'from-substation') {
let offshore = false;
try { offshore = Boolean(coverage.policy(tech)?.offshore); } catch (_) { offshore = false; }
recordArrivalEngine(
offshore ? 'offshore' : 'onshore',
links.length > 0 || Boolean(links.beyondRadiusNearest),
links.length ? null
: (nesoDrawn ? 'DECLARED_CONNECTION_DRAWN'
: (links.beyondRadiusNearest ? 'NEAREST_BEYOND_' + MAX_LINK_KM + '_KM' : 'NO_SUBSTATION_DATA')),
/* Only a fallback while nothing declares the connection. Now that the
NESO register is read, an offshore project with a connection site is
answered by its declared point and says so, and only a project with
neither is falling back to a nearest-substation search. */
offshore && !currentDeclared && !currentNeso?.site ? 'declared_connection_point' : null
);
}
/* Two different facts, never collapsed into one null. `nearest_km` is the
nearest mapped substation whether or not it was close enough to draw;
`nearest_beyond_radius` says which of the two it is, so a reader can tell
"nothing within the draw radius" from "no substation data at all". */
const beyond = links.length ? null : (links.beyondRadiusNearest || null);
link.last_selection = {
name, tech, direction, count: links.length,
nearest_km: links.length
? Number(links[0].km.toFixed(3))
: (beyond ? Number(beyond.km.toFixed(3)) : null),
nearest_beyond_radius: links.length ? false : Boolean(beyond),
nearest_name: links.length ? (links[0].name || null) : (beyond ? (beyond.name || null) : null),
draw_radius_km: links.radiusKm != null ? links.radiusKm : 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;
placeStatus(el);
} catch (error) {
link.failures.push('status: ' + String(error?.message || error));
}
}
/* THE STATUS BOX IS READ, OR IT IS NOT A STATUS. It sat at a fixed top:14px inside the map, and the menu bar, the
search box and the search results all lie over the top of the map: on a phone the placeholder sentence was printed
underneath three other things and a reader got its last line. It was also 195 px wide on a 390 px screen, because
a box centred with left:50% can only ever be as wide as the half of the map to its right.
So it is given the width of the screen less a margin, and it finds its own height: it starts where it always did
and moves down until the page itself says that a finger on its centre and on each of its corners would touch the
box and nothing else. No selector is named, because the furniture above it has changed before and will again. It
asks again after the search results have had time to appear, and when the window changes shape. */
function placeStatus(el) {
try {
if (!document.getElementById(STATUS_ID + '-place')) {
const style = document.createElement('style');
style.id = STATUS_ID + '-place';
style.textContent = '#' + STATUS_ID + '{left:4vw;right:4vw;transform:none;margin:0 auto;'
+ 'width:fit-content;max-width:min(92vw,420px);box-sizing:border-box}';
document.head.appendChild(style);
}
const clear = () => {
const r = el.getBoundingClientRect();
if (r.width < 2 || r.height < 2) return true;
/* A GRID of points, not the centre and the corners: the search box lies across the lower middle of this
box, between all five of those, and the first version of this rule declared the box clear with a text
field printed straight over its sentence. Nine columns by five rows leaves no gap a control can hide in. */
const points = [];
for (let i = 0; i < 9; i++) for (let j = 0; j < 5; j++) {
points.push([r.left + 3 + (r.width - 6) * i / 8, r.top + 3 + (r.height - 6) * j / 4]);
}
return points.every(([x, y]) => {
const hit = document.elementFromPoint(Math.min(Math.max(x, 1), innerWidth - 1),
Math.min(Math.max(y, 1), innerHeight - 1));
return !hit || hit === el || el.contains(hit);
});
};
const settle = () => {
if (!el.isConnected) return;
let top = 14;
el.style.top = top + 'px';
const limit = Math.max(160, innerHeight * 0.6);
while (!clear() && top < limit) { top += 8; el.style.top = top + 'px'; }
link.status_top_px = top;
};
settle();
for (const ms of [300, 1200, 3000, 6000]) setTimeout(settle, ms);
if (!placeStatus.listening) {
placeStatus.listening = true;
window.addEventListener('resize', () => {
const live = document.getElementById(STATUS_ID);
if (live) placeStatus(live);
});
}
} catch (error) {
link.failures.push('status placement: ' + 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(',')))