In this section
- Substation Intelligence geodesy · testcode / sandbox/202609060459/atlas/cartridges/202609060459-substation-intelligence.js lines 3930–4629
Substation Intelligence
A JavaScript file in the cartridges folder of Testcode that maps elizabeth line and london underground, using haversine and SHA-256, and uses data from the ventus-grid-engine, data-federation-map-for-GlobalGrid2050-all-repos and spiders repositories.
Set aside from the main view: 99% of its lines are the same as apps/substation-finder/Si/202609060537-substation-intelligence.js (code-generator), which stays. (near-copy-of, proposed by families.py). 99% of lines shared with Substation Intelligence; read that one first. All set-aside files, with reasons. Nothing was deleted.
Evidence
- line-jaccard 0.9913 to code-generator@3897d83efcd0259d21dce87704b0c33118fe2c2e apps/substation-finder/Si/202609060537-substation-intelligence.js:1-5427 fd8aeb8a8884da62dc50991d5f4bf8cc48b33c43
- sha256 916bad1b531c94d9acd3bc54f6ed205b467b96e6c1d86beea47a7d66e2f51669
- target sha256 afc18391911f8ab467480aa8f22fd30467de554c76c58101956f9fec49ad9449
- group of 3 (identity.json near-copy edges >= 0.9)
- canonical rule: reachable, newest stamp, core repo, most lines
geodesytestcode / sandbox/202609060459/atlas/cartridges/202609060459-substation-intelligence.js · lines 3930–4629 of 5400 · version 2026-09-06 04:59 (continued from section 453) · Not reached from any entry point (candidate for review) · pattern _zoneDrawRefreshEditor (shared by 3 files)
- What it does
- It maps elizabeth line, london underground, UK metros trams and hs2. Defines 230 functions or classes, including close, open, show, clearValues, validOutline. 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: 400kV, 275kV, 132kV, 66kV, 33kV, 11kV.
- Inputs & outputs
- In: data source: ventus-grid-engine data; data source: data-federation-map-for-globalgrid2050-all-repos data; data source: spiders data; GeoJSON file elizabeth_line.geojson; GeoJSON file london_underground.geojson; GeoJSON file uk_metros_trams.geojson; GeoJSON file hs2.geojson; JSON file style.json. Out: CSV file gridatlas-polygon-vertices.csv; downloaded file gridatlas-polygon-; downloaded file gridatlas-polygon-vertices.csv; downloaded file gridatlas-; downloaded file globalgrid2050-map-; browser storage (setItem); interactive map; canvas drawing. Coordinate systems named: WGS84 / EPSG:4326. Voltage levels named: 400kV, 275kV, 132kV, 66kV, 33kV, 11kV.
- What it achieves
- It saves outline (`saveOutline`), reads outline (`readOutline`) and exports outline (`exportOutline`). Its `snapLines` function gives line features whose first and last vertices are moved onto the nearest substation point within tolerance; other geometry unchanged from line features and substation point features (VEDIC: snap line ends to substations). Its code works with 400 kV and 100 MVA. It responds to fullscreenchange, webkitfullscreenchange and click events.
- Why it matters
- No other file in the estate was found to import it.
- Application
- testcode · sandbox/202609060459/atlas/cartridges · script
- VEDIC
- SNAP LINE ENDS TO SUBSTATIONS (GG2050-VEDIC-000106): GridAtlas / Substations · Geospatial data processing. line_features, substation_point_features → Line features whose first and last vertices are moved onto the nearest substation point within tolerance; other geometry unchanged.
- 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
- Uses
- Spider Full Po Test (estate URL), Data — Grid Studies Public Page (estate URL)
- Used by
- mentioned in Standalone (comment link)
- Produces
- close, open, show, clearValues, validOutline, saveOutline, readOutline, clearOutline, analyzeOutline, fail, orient, on
- Defines here
- capture, clean, looksBlank, saveImage, say, grab, appendExport, appendEstateLinks, layerCheckbox, buildLayerControls, move, trayRoute, chipStaysOnMap, adoptLate, install, loudFailure, start, tidy, retire, watch, note, readRegisterSource, primeRegister, loadRegister, readSelection, near, collection, setSourceData, ensureLayers, escapeHtml
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- testcode@a8a215982b13d6e2f6019b40bf0bef5755719773 sandbox/202609060459/atlas/cartridges/202609060459-substation-intelligence.js:3930-4629 · blob fd03f2ae502f2d404cb773df8858c2746ada6401 · GitHub at these lines
- State
- achieves: code · context: readme_derived · stage: output · effects: dom, filesystem, network, storage · domain stage: experimental · users: ICP_grid_engineer · canonical: unreached_review
if (!canvas) return;
var capture = function () {
var url;
try { url = canvas.toDataURL('image/png'); } catch (_) { return; }
if (looksBlank(canvas)) return;
var old = doc.getElementById('gridatlas-print-furniture');
if (old) old.remove();
var furniture = buildPrintFurniture(doc);
var image = doc.createElement('img');
image.className = 'gpf-map'; image.alt = 'Current Grid Atlas map'; image.src = url;
furniture.appendChild(image);
var style = doc.getElementById('gridatlas-print-css');
if (!style) { style = doc.createElement('style'); style.id = 'gridatlas-print-css'; doc.head.appendChild(style); }
style.textContent = '#gridatlas-print-furniture{display:none}' +
'@media print{@page{size:auto;margin:8mm}html,body{margin:0!important;padding:0!important;height:auto!important;overflow:visible!important;background:white!important}' +
'body>*:not(#gridatlas-print-furniture){display:none!important}' +
'#gridatlas-print-furniture{display:block!important;position:fixed;inset:0;box-sizing:border-box;padding:4mm;background:white;color:#101c22;font:11px/1.4 system-ui}' +
'.gpf-head{font-size:12px;letter-spacing:2px}.gpf-brand{font-weight:bold;margin-right:10px}.gpf-title{font-size:18px;margin-top:3mm}' +
'.gpf-map{position:absolute;left:4mm;top:22mm;width:calc(100% - 8mm);height:calc(100% - 42mm);object-fit:contain}' +
'.gpf-foot{position:absolute;left:4mm;right:4mm;bottom:3mm;display:flex;gap:12px;justify-content:space-between;font-size:9px}.gpf-stamp{white-space:nowrap}}';
var clean = function () { furniture.remove(); window.removeEventListener('afterprint', clean); };
window.addEventListener('afterprint', clean);
image.decode().then(function () { window.print(); }).catch(clean);
window.setTimeout(clean, 300000);
};
map.once('render', capture); map.triggerRepaint();
}
function looksBlank(canvas) {
try {
var probe = document.createElement('canvas');
probe.width = 40; probe.height = 40;
var context = probe.getContext('2d');
context.drawImage(canvas, 0, 0, 40, 40);
var data = context.getImageData(0, 0, 40, 40).data;
for (var i = 3; i < data.length; i += 4) if (data[i] !== 0) return false;
return true;
} catch (_) {
return false;
}
}
function saveImage(doc, button) {
var map = window.__GRIDATLAS_V9_MAP__;
if (!map || !map.getCanvas) {
map = (window.map && window.map.getCanvas) ? window.map : null;
}
var canvas = doc.querySelector('.maplibregl-canvas')
|| (map && map.getCanvas ? map.getCanvas() : null);
var say = function (text) { button.textContent = text; };
if (!canvas) { say('⊘ No map canvas to save — use Print'); return; }
var grab = function () {
var url;
try { url = canvas.toDataURL('image/png'); } catch (_) { url = null; }
if (!url || looksBlank(canvas)) {
say('⊘ The map could not be captured — use Print instead');
return;
}
var link = doc.createElement('a');
link.href = url;
link.download = 'gridatlas-' + exportStamp().replace(/[^0-9]/g, '').slice(0, 12) + '.png';
doc.body.appendChild(link);
link.click();
doc.body.removeChild(link);
say('✓ Image saved');
window.setTimeout(function () { say('⤓ Save an image of this view'); }, 4000);
};
if (map && map.once && map.triggerRepaint) {
map.once('render', grab);
map.triggerRepaint();
} else {
grab();
}
}
function appendExport(panel, doc) {
if (!panel || panel.querySelector('[data-gm-export]')) return 0;
appendGroup(panel, 'Export this view');
var print = doc.createElement('button');
print.setAttribute('data-gm-export', '1');
print.setAttribute('type', 'button');
print.textContent = '⎙ Print · or save as PDF';
print.addEventListener('click', function () { printView(doc); });
panel.appendChild(print);
var image = doc.createElement('button');
image.setAttribute('data-gm-export', '1');
image.setAttribute('type', 'button');
image.textContent = '⤓ Save an image of this view';
image.addEventListener('click', function () { saveImage(doc, image); });
panel.appendChild(image);
return 2;
}
function appendEstateLinks(panel) {
if (!panel || panel.querySelector('[data-gm-estate]')) return 0;
appendGroup(panel, 'Estate');
var added = 0;
ESTATE_LINKS.forEach(function (item) {
var a = document.createElement('a');
a.setAttribute('data-gm-estate', '1');
a.setAttribute('role', 'button');
a.href = item.href;
a.target = '_blank';
a.rel = 'noopener';
a.textContent = item.text;
panel.appendChild(a);
added += 1;
});
return added;
}
function layerCheckbox(kind) {
var proxy = document.createElement('input');
proxy.type = kind;
var box = document.createElement('span');
box.className = 'gm-layer-box';
box.setAttribute('aria-hidden', 'true');
return { proxy: proxy, box: box };
}
function buildLayerControls(found) {
var lastGroup = '';
found.controls.forEach(function (original) {
var key = layerKey(original);
var group = layerGroup(original);
if (group !== lastGroup) {
appendGroup(gridBody, group);
lastGroup = group;
}
var label = document.createElement('label');
label.className = 'gm-layer';
label.setAttribute('data-gridatlas-layer-key', key);
var built = layerCheckbox('checkbox');
var proxy = built.proxy;
proxy.setAttribute('data-gridatlas-layer-proxy', key);
var name = document.createElement('span');
name.className = 'gm-layer-name';
label.appendChild(proxy);
label.appendChild(built.box);
label.appendChild(name);
gridBody.appendChild(label);
layerTargets[key] = original;
layerProxies[key] = proxy;
proxy.addEventListener('change', function () {
if (!!original.checked !== !!proxy.checked && typeof original.click === 'function') {
forwardingLayerChoice = true;
try { original.click(); }
finally { forwardingLayerChoice = false; }
}
syncLayer(key);
});
syncLayer(key);
});
var basemaps = array(found.host.querySelectorAll('input[type="radio"][name="bm"]'));
if (basemaps.length) appendGroup(gridBody, 'Basemap');
basemaps.forEach(function (original) {
var label = document.createElement('label');
label.className = 'gm-layer';
var built = layerCheckbox('radio');
var proxy = built.proxy;
proxy.name = 'gridatlas-menu-basemap';
proxy.value = original.value;
proxy.checked = !!original.checked;
var name = document.createElement('span');
name.className = 'gm-layer-name';
name.textContent = cleanText(original.closest('label').textContent) || original.value;
proxy.addEventListener('change', function () {
if (proxy.checked && !original.checked && typeof original.click === 'function') original.click();
closeAll();
});
label.appendChild(proxy);
label.appendChild(built.box);
label.appendChild(name);
gridBody.appendChild(label);
});
}
function move(panel, node, label) {
if (!node || !panel || (bar && bar.contains(node))) return false;
if (label && node.setAttribute) node.setAttribute('aria-label', label);
panel.appendChild(node);
if (node.removeAttribute) node.removeAttribute('hidden');
state.controls_moved += 1;
return true;
}
function trayRoute(node) {
var text = cleanText(node && node.textContent).toLowerCase();
if (/\bclear\b|\bscope\b/.test(text)) return 'Scope';
if (/\bgrid\b|\bsubs\b/.test(text)) return 'Grid';
return '';
}
function chipStaysOnMap(node) {
var text = cleanText(node && node.textContent).toLowerCase();
if (!/\bgrid\b|\bsubs\b/.test(text)) return false;
var coarse = false;
try {
coarse = !!(window.matchMedia && window.matchMedia('(pointer: coarse)').matches);
} catch (error) {
coarse = false;
}
var width = Number(window.innerWidth);
var narrow = isFinite(width) && width > 0 && width <= 700;
return coarse || narrow;
}
function adoptLate(doc) {
if (!bar) return;
move(panels.View, doc.getElementById('gridatlas-gb-conditions'));
move(panels.About, doc.getElementById('gridatlas-version-ledger'));
move(panels.View, doc.getElementById('btn-fullscreen-exit'), 'Exit full screen');
var curtain = doc.getElementById('fs-curtain-tab');
if (curtain && !bar.contains(curtain)) {
curtain.setAttribute('role', 'button');
curtain.setAttribute('tabindex', '0');
curtain.setAttribute('aria-label', 'Open the fullscreen layer curtain');
move(panels.Grid, curtain);
}
var tray = doc.getElementById('gridatlas-mobile-tray');
if (tray) {
array(tray.querySelectorAll('button')).forEach(function (button) {
if (chipStaysOnMap(button)) return;
var route = trayRoute(button);
if (route) move(panels[route], button);
else button.hidden = true;
});
}
move(panels.Scope, doc.getElementById('btn-gridpoint'));
var disclaimer = doc.querySelector('.disclaimer-box');
var shoutout = doc.querySelector('.podcast-shoutout');
move(panels.About, disclaimer);
move(panels.About, shoutout);
state.estate_links = appendEstateLinks(panels.About);
appendEngineModules(panels.File);
state.export_controls = appendExport(panels.File, doc);
state.studies = appendStudies(panels.View);
var attrib = doc.querySelector('.custom-map-attrib');
if (attrib) {
if (!bar || !bar.contains(attrib)) move(panels.About, attrib);
else if (panels.About.lastElementChild !== attrib) panels.About.appendChild(attrib);
}
var dashToggle = doc.getElementById('gridatlas-dash-toggle');
if (dashToggle) dashToggle.hidden = false;
var stack = doc.querySelector('.map-controls');
if (stack) {
var leftovers = array(stack.querySelectorAll('button,input,select,textarea,a'))
.filter(function (node) { return !node.hidden; });
if (leftovers.length === 0) stack.setAttribute('data-gridatlas-menu-emptied', '1');
}
MENUS.forEach(function (name) {
state.panel_counts[name] = panels[name] ? panels[name].children.length : 0;
});
}
function install(doc) {
if (state.installed || doc.getElementById(BAR_ID)) return true;
var ready = required(doc);
state.engine_layer_controls = ready.found.engine.length;
state.pipeline_layer_controls = ready.found.pipeline.length;
state.layer_controls = ready.found.controls.length;
if (ready.missing.length) {
state.waiting_for = ready.missing.slice();
return false;
}
installStyle(doc);
bar = buildBar(doc);
buildLayerControls(ready.found);
if (ready.nodes.search) ready.nodes.search.setAttribute("data-testcode-search", "persistent");
move(panels.File, ready.nodes.exportButton);
move(panels.Edit, ready.nodes.statusButton);
move(panels.View, ready.nodes.fullscreenButton);
move(panels.Scope, ready.nodes.radiusButton);
move(panels.Scope, ready.nodes.radiusAreaButton);
move(panels.Scope, ready.nodes.zoneButton);
move(panels.Scope, ready.nodes.measureButton);
move(brandSlot, ready.nodes.header);
move(gridHead, doc.querySelector('.scada-brand'));
move(gridHead, doc.querySelector('.status-legend'));
ready.nodes.host.insertBefore(bar, ready.nodes.host.firstChild);
doc.documentElement.classList.add('gridatlas-menu-hosted');
syncAttribClearance(doc);
if (typeof ResizeObserver === 'function') {
var barResize = new ResizeObserver(function () {
syncAttribClearance(doc);
if (openPanelRefs) clampPanel(doc, openPanelRefs.menu, openPanelRefs.panel);
});
barResize.observe(bar);
state.attrib_clearance_source = 'ResizeObserver';
} else if (doc.defaultView && typeof doc.defaultView.addEventListener === 'function') {
doc.defaultView.addEventListener('resize', function () {
syncAttribClearance(doc);
if (openPanelRefs) clampPanel(doc, openPanelRefs.menu, openPanelRefs.panel);
});
state.attrib_clearance_source = 'resize-listener';
}
doc.addEventListener('click', function (event) {
if (!bar.contains(event.target)) {
if (!forwardingLayerChoice) closeAll();
}
else if (event.target && /^(BUTTON|INPUT)$/.test(event.target.tagName || '')) {
if (event.target.type !== 'text'
&& !event.target.classList.contains('gm-title')
&& !event.target.hasAttribute('data-gridatlas-layer-proxy')) {
window.setTimeout ? window.setTimeout(closeAll, 0) : closeAll();
}
}
});
doc.addEventListener('change', function (event) {
var key = layerKey(event.target);
if (key && layerProxies[key]) syncLayer(key);
});
state.listeners = 2;
adoptLate(doc);
closeAll();
state.installed = true;
state.waiting_for = [];
state.failure = null;
state.one_identity_surface = true;
state.mobile_sheet_hit_target_guard = true;
state.layer_status_mirrored = true;
state.layer_menu_stays_open = true;
if (typeof MutationObserver === 'function') {
observer = new MutationObserver(function () {
adoptLate(doc);
syncAll();
});
observer.observe(doc.body, { childList: true, subtree: true, characterData: true });
}
return true;
}
state.install = function () { return install(document); };
state.closeAll = closeAll;
function loudFailure(doc) {
if (state.installed || doc.getElementById(FAILURE_ID)) return;
var found = inventory(doc);
state.failure = 'menu not installed: expected 60 engine + 3 Pipeline News layer controls; found '
+ found.engine.length + ' + ' + found.pipeline.length;
if (window.console && typeof window.console.error === 'function') {
window.console.error('[GRIDATLAS MENU] ' + state.failure);
}
var alert = doc.createElement('div');
alert.id = FAILURE_ID;
alert.setAttribute('role', 'alert');
alert.textContent = state.failure + '. Original controls remain available.';
alert.style.cssText = 'position:fixed;left:8px;right:8px;top:8px;z-index:10030;'
+ 'padding:8px;background:#280b0b;color:#ffd0d0;border:1px solid #b44;'
+ 'font:11px/1.4 monospace';
(doc.body || doc.documentElement).appendChild(alert);
}
function start() {
if (!document.documentElement || typeof document.createElement !== 'function') {
state.failure = 'menu not installed: full document unavailable';
return;
}
var probe = document.createElement('div');
if (!probe || typeof probe.setAttribute !== 'function' || !probe.classList) {
state.failure = 'menu not installed: full DOM element API unavailable';
return;
}
if (install(document)) return;
if (typeof window.setInterval !== 'function'
|| typeof window.clearInterval !== 'function') return;
timer = window.setInterval(function () {
state.tries += 1;
if (install(document)) {
window.clearInterval(timer);
timer = null;
} else if (state.tries >= MAX_TRIES) {
window.clearInterval(timer);
timer = null;
loudFailure(document);
}
}, 250);
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', start, { once: true });
} else {
start();
}
}());
;(() => {
const style=document.createElement('style');style.textContent=`
.search-bar-wrapper{display:flex!important;position:absolute!important;top:64px!important;left:12px!important;right:12px!important;width:auto!important;max-width:520px!important;z-index:1100!important;margin:0!important;transform:none!important}
.search-bar-wrapper input{min-height:48px!important;font-size:16px!important;width:100%!important;box-sizing:border-box}
.testcode-identity{position:fixed;right:12px;bottom:64px;z-index:2000;background:#08161fee;color:#aaf6ff;padding:8px;border:1px solid #36616a;font:12px monospace;text-decoration:none}
@media print{.testcode-identity,.search-bar-wrapper{display:none!important}}
`;document.head.append(style);
const link=document.createElement('a');link.className='testcode-identity';link.href='/testcode/202609051906/';link.textContent='Test Code · 202609051906';document.body.append(link);
})();
(function arrivalTidy() {
if (typeof document === 'undefined' || typeof window === 'undefined') return;
if (typeof MutationObserver !== 'function') return;
var ref = '';
try {
ref = String(new URLSearchParams(window.location.search).get('repd_ref') || '').trim();
} catch (_) { return; }
if (!ref) return;
var typed = false;
var done = false;
function tidy() {
if (done) return true;
var state = document.body && document.body.dataset
? document.body.dataset.gridatlasRepdDeepLink : '';
if (state !== 'resolved') return state === 'failed';
var results = document.getElementById('search-results');
var input = document.getElementById('search-input');
if (!results || !input) return false;
if (!typed) {
results.style.display = 'none';
if (input.value === ref) input.value = '';
}
done = true;
return true;
}
function retire() { typed = true; }
function watch() {
var input = document.getElementById('search-input');
if (input) {
input.addEventListener('focus', retire, { once: true });
input.addEventListener('input', retire, { once: true });
}
if (tidy()) return;
var observer = new MutationObserver(function () {
if (tidy()) observer.disconnect();
});
observer.observe(document.body, {
attributes: true, attributeFilter: ['data-gridatlas-repd-deep-link']
});
window.__GRIDATLAS_ARRIVAL_TIDY__ = {
installed: true,
repd_ref: ref,
get dismissed() { return done; },
get retired_by_reader() { return typed; }
};
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', watch, { once: true });
} else {
watch();
}
}());
(() => {
'use strict';
const NS = (window.__GRIDATLAS_MODULES__ = window.__GRIDATLAS_MODULES__ || {});
if (NS.pipelineNewsLayers) return;
const geodesy = NS.geodesy;
if (!geodesy) {
throw new Error('pipeline-news-layers requires the geodesy module');
}
const GENERATION = '202609030048';
const RADIUS_KM = 25;
const GROUP_TITLE = 'PIPELINE NEWS (REPD)';
const REGISTER_SOURCE = 'src-repd';
const REGISTER_PRIMER = 'biomass';
const SPINE_TECHS = new Set(['solar', 'solar_roof', 'bess', 'wind']);
const TECH_COLOUR = {
solar: '#ffff00', solar_roof: '#ffcc00', bess: '#ffae00', wind: '#00ffff',
biomass: '#39ff14', hydro: '#00aaff', hydrogen: '#ffffff', tidal: '#00bfff',
act: '#ff6600', geothermal: '#ff3300', flywheel: '#ff69b4', caes: '#88aaff',
other: '#888888'
};
const CONTROLS = [
{
id: 'same',
label: 'Same technology',
colour: '#5fbdc2',
keep: (row, selection) => row.tech === selection.tech
},
{
id: 'wider',
label: 'Wider fleet',
colour: '#39ff14',
keep: (row) => !SPINE_TECHS.has(row.tech)
},
{
id: 'all',
label: 'All pipeline',
colour: '#d8b64a',
keep: () => true
}
];
const state = {
schema: 'gridatlas.pipeline-news-layers.v1',
generation: GENERATION,
installed: false,
register_rows: 0,
register_url: null,
radius_km: RADIUS_KM,
selection: null,
counts: {},
active: [],
failures: []
};
window.__GRIDATLAS_PIPELINE_LAYERS__ = state;
function note(message) {
const text = String(message && message.message ? message.message : message);
if (!state.failures.includes(text)) state.failures.push(text);
}
let register = null;
function readRegisterSource(map) {
try {
const source = map.getSource(REGISTER_SOURCE);
const features = source && source._data && source._data.features;
if (!Array.isArray(features) || !features.length) return null;
return features.map((feature) => {
const properties = feature.properties || {};
const coordinates = (feature.geometry || {}).coordinates || [];
return {
name: properties.name || '',
operator: properties.operator || '',
tech: properties.tech || 'other',
raw: properties.raw_tech || '',
status: properties.status || '',
mw: Number(properties.capacity) || 0,
lon: Number(coordinates[0]),
lat: Number(coordinates[1])
};
}).filter((row) => Number.isFinite(row.lon) && Number.isFinite(row.lat));
} catch (error) {
note('register: ' + String(error && error.message || error));
return null;
}
}
function primeRegister() {
const box = document.querySelector(
'#scada-ui-container input[type=checkbox][data-layer-id="' + REGISTER_PRIMER + '"]');
if (!box) { note('register: no ' + REGISTER_PRIMER + ' control to prime with'); return false; }
if (!box.checked) box.click();
state.primed_with = REGISTER_PRIMER;
return true;
}
async function loadRegister(map) {
if (register) return register;
register = readRegisterSource(map);
if (register) { state.register_rows = register.length; return register; }
if (!primeRegister()) throw new Error('register unavailable');
for (let attempt = 0; attempt < 40; attempt += 1) {
await new Promise((resolve) => setTimeout(resolve, 250));
register = readRegisterSource(map);
if (register) { state.register_rows = register.length; return register; }
}
note('register: ' + REGISTER_SOURCE + ' did not hydrate within 10 s');
throw new Error('register unavailable');
}
function readSelection(map) {
try {
const source = map.getSource('gridatlas-project-pin');
const features = source && source._data && source._data.features;
if (!features || !features.length) return null;
const [lon, lat] = features[0].geometry.coordinates || [];
if (!Number.isFinite(lon) || !Number.isFinite(lat)) return null;
const links = window.__GRIDATLAS_NEON_LINKS__ || {};
const name = (features[0].properties || {}).name
|| (links.project_pin || {}).name || '';
return { lon, lat, name, tech: (links.last_selection || {}).tech || '' };
} catch (error) {
note('selection: ' + String(error && error.message || error));
return null;
}
}
function near(rows, selection) {
const found = [];
for (const row of rows) {
const km = geodesy.distanceKm(selection.lon, selection.lat, row.lon, row.lat);
if (km > RADIUS_KM) continue;
if (km < 0.0005 && row.name === selection.name) continue;
found.push({ ...row, km });
}
found.sort((a, b) => a.km - b.km);
return found;
}
function collection(rows) {
return {
type: 'FeatureCollection',
features: rows.map((row) => ({
type: 'Feature',
geometry: { type: 'Point', coordinates: [row.lon, row.lat] },
properties: {
name: row.name, operator: row.operator, tech: row.tech,
raw_tech: row.raw, status: row.status, mw: row.mw,
km: Number(row.km.toFixed(3)),
colour: TECH_COLOUR[row.tech] || TECH_COLOUR.other
}
}))
};
}
function setSourceData(map, id, data) {
try {
const source = map.getSource(id);
if (!source || typeof source.setData !== 'function') {
note('source missing, nothing drawn: ' + id);
return false;
}
source.setData(data);
return true;
} catch (error) {
note('source ' + id + ': ' + String(error && error.message || error));
return false;
}
}
function ensureLayers(map, control) {
const sourceId = 'pn-src-' + control.id;
const ringId = 'l-pn-' + control.id + '-ring';
const dotId = 'l-pn-' + control.id;
if (map.getSource(sourceId)) return { sourceId, ringId, dotId };
try {
map.addSource(sourceId, { type: 'geojson', data: collection([]) });
} catch (error) {
note('addSource ' + sourceId + ': ' + String(error && error.message || error));
return { sourceId, ringId, dotId };
}
map.addLayer({
id: ringId, type: 'circle', source: sourceId,
paint: {
'circle-radius': ['interpolate', ['linear'], ['zoom'], 6, 4, 12, 8, 16, 13],
'circle-color': 'rgba(0,0,0,0)',
'circle-stroke-color': control.colour,
'circle-stroke-width': 1.4,
'circle-stroke-opacity': 0.9
}
});
map.addLayer({
id: dotId, type: 'circle', source: sourceId,
paint: {
'circle-radius': ['interpolate', ['linear'], ['zoom'], 6, 1.8, 12, 3.4, 16, 5.5],
'circle-color': ['coalesce', ['get', 'colour'], '#888888'],
'circle-opacity': 0.95
}
});
map.on('click', dotId, (event) => {
const properties = (event.features && event.features[0] || {}).properties || {};
try {
new window.maplibregl.Popup({ closeButton: true })
.setLngLat(event.lngLat)
.setHTML(
'<div style="font-family:monospace;background:#000;padding:6px;max-width:260px">'
+ '<b style="color:#5fbdc2;font-size:12px">' + escapeHtml(properties.name || 'Project') + '</b><br>'
+ '<span style="color:#888">' + escapeHtml(properties.raw_tech || properties.tech || '') + '</span><br>'
+ '<span style="color:#ffae00">' + escapeHtml(String(properties.mw || 0)) + ' MW</span> · '
+ '<span style="color:#aaa">' + escapeHtml(properties.status || '') + '</span><br>'
+ '<span style="color:#555;font-size:10px">' + escapeHtml(String(properties.km)) + ' km from the selected project. '
+ 'Proximity only — not a connection, a circuit or a queue position.</span></div>')
.addTo(map);
} catch (error) {
note('popup: ' + String(error && error.message || error));
}
});
map.on('mouseenter', dotId, () => { map.getCanvas().style.cursor = 'pointer'; });
map.on('mouseleave', dotId, () => { map.getCanvas().style.cursor = ''; });
return { sourceId, ringId, dotId };
}
function escapeHtml(value) {
return String(value == null ? '' : value)
.replace(/[&<>"]/g, (character) => ({
'&': '&', '<': '<', '>': '>', '"': '"'
}[character]));
}
function setVisibility(map, control, visible) {
for (const id of ['l-pn-' + control.id + '-ring', 'l-pn-' + control.id]) {
if (map.getLayer(id)) map.setLayoutProperty(id, 'visibility', visible ? 'visible' : 'none');
}
}
function labelFor(control, count, selection) {
if (!selection) return control.label + ' [SELECT A PROJECT]';
if (count === null || count === undefined) return control.label + ' [WAIT]';
return control.label + ' [' + count.toLocaleString('en-GB') + ' within ' + RADIUS_KM + ' km]';
}
function paintLabels(selection) {
for (const control of CONTROLS) {
const text = labelFor(control, state.counts[control.id], selection);
for (const span of document.querySelectorAll('[data-pn-label="' + control.id + '"]')) {
span.textContent = text;
}
}
}
async function refresh(map, control) {
const selection = state.selection;
if (!selection) return;
const rows = await loadRegister(map);
const found = near(rows.filter((row) => control.keep(row, selection)), selection);
state.counts[control.id] = found.length;
const { sourceId } = ensureLayers(map, control);
setSourceData(map, sourceId, collection(found));
paintLabels(selection);
}
function buildGroup(container, isFullscreen) {
if (container.querySelector('[data-pn-group]')) return;
const group = document.createElement('div');
group.className = 'key-group';
group.setAttribute('data-pn-group', '1');
const title = document.createElement('div');
title.className = 'key-title';
title.textContent = GROUP_TITLE;
group.appendChild(title);
for (const control of CONTROLS) {
const label = document.createElement('label');
label.className = 'key-item';
const input = document.createElement('input');
input.type = 'checkbox';
input.setAttribute('data-pn-layer', control.id);
input.dataset.pnLayer = control.id;
const span = document.createElement('span');
span.setAttribute('data-pn-label', control.id);
span.style.color = control.colour;
span.textContent = labelFor(control, state.counts[control.id], state.selection);
label.appendChild(input);
label.appendChild(document.createTextNode(' '));
label.appendChild(span);
group.appendChild(label);
}