GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Grid network and substations / code-generator / apps/substation-finder/Si

Substation Intelligence (part 1)

A JavaScript file in the substation finder folder of Code Generator that maps elizabeth line and uses data from the ventus-grid-engine repository. Served with the page at https://ventusltd.github.io/code-generator/apps/substation-finder/Si/.

700 lines of JavaScript from code-generator, in 1 file. Topic: Grid network and substations. Section 276 of 2044.

Cut 2026-12-06T03:07:51+00:00. A copy for reading; the repository at the stated commit is the source.

In the State lines below, domain stage, users and canonical status are rule-based first approximations from code and path evidence (rules explore-agent-rules-v1), not observed facts: the rules.

In this section

  1. Substation Intelligence geodesy · code-generator / apps/substation-finder/Si/202609060537-substation-intelligence.js lines 641–1340

Substation Intelligence

A JavaScript file in the substation finder folder of Code Generator that maps elizabeth line and uses data from the ventus-grid-engine repository. Served with the page at https://ventusltd.github.io/code-generator/apps/substation-finder/Si/.

geodesycode-generator / apps/substation-finder/Si/202609060537-substation-intelligence.js · lines 641–1340 of 5427 · version 2026-09-06 05:37 (continued from section 275) · Not reached from any entry point (candidate for review) · pattern restoreLayers (shared by 2 files)

What it does
It maps elizabeth line, london underground, UK metros trams and hs2. Defines 232 functions or classes, including close, open, dockLayers, restoreLayers, show. 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 upstream_foresight (path word 'substation'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. 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 restores layers (`restoreLayers`), saves outline (`saveOutline`) and reads outline (`readOutline`). 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
code-generator · apps/substation-finder/Si · 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
none found
Produces
close, open, dockLayers, restoreLayers, show, clearValues, validOutline, saveOutline, readOutline, clearOutline, analyzeOutline, fail
Defines here
validateRadiusInput, updateMeasureDisplay, updateMeasureLayers, clearMeasure, undoLastMeasurePoint, toggleMeasureMode, toggleRadiusAreaMode, doRadiusAreaMeasure, updateUIState, FetchQueue, fetchWithTimeout, fetchAndParseGeoJSON, snapLines, snapCoordinate, createGeoJSONCircle, drawRadiusCircle, clearRadiusCircle, _rebuildVisibleCache, buildSearchButtons, buildSearchIndex, flyToProject, focusCanonicalProjectDeepLink, searchProjects, exportCSV, toggleStatusMode, toggleRadiusMode, doRadiusSearch, buildLayerRow, buildDOM, handleLayerToggle
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
code-generator@3897d83efcd0259d21dce87704b0c33118fe2c2e apps/substation-finder/Si/202609060537-substation-intelligence.js:641-1340 · blob fd8aeb8a8884da62dc50991d5f4bf8cc48b33c43 · GitHub at these lines
State
achieves: code · context: readme_derived · stage: output · effects: dom, filesystem, network, storage · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
const raw = parseFloat(document.getElementById('radius-input').value);
if (isNaN(raw) || raw < RADIUS_MIN) return RADIUS_MIN;
if (raw > RADIUS_MAX) return RADIUS_MAX;
return raw;
}
function validateRadiusInput() {
const input = document.getElementById('radius-input');
const raw = parseFloat(input.value);
const invalid = isNaN(raw) || raw < RADIUS_MIN || raw > RADIUS_MAX;
input.classList.toggle('invalid', invalid);
return !invalid;
}
let measureMode = false;
let measurePoints = [];
let measureClosed = false;
let _lastMouseMoveRaf = null;
function updateMeasureDisplay() {
const lineEl = document.getElementById('m-line');
const perimEl = document.getElementById('m-perim');
const areaEl = document.getElementById('m-area');
const hint = document.getElementById('m-hint');
const undoBtn = document.getElementById('btn-measure-undo');
undoBtn.style.display = (measurePoints.length > 0 && !measureClosed) ? 'inline-block' : 'none';
if (measurePoints.length < 2) {
lineEl.style.display = 'none'; perimEl.style.display = 'none'; areaEl.style.display = 'none';
hint.innerText = 'Click to add points · Double-click to close polygon';
return;
}
let totalKm = 0;
for (let i = 1; i < measurePoints.length; i++) {
totalKm += haversine(measurePoints[i-1][0], measurePoints[i-1][1], measurePoints[i][0], measurePoints[i][1]);
}
if (!measureClosed) {
lineEl.style.display = 'block'; perimEl.style.display = 'none'; areaEl.style.display = 'none';
document.getElementById('m-km').innerText = fmt(totalKm, 2);
document.getElementById('m-m').innerText = fmt(totalKm * 1000, 0);
document.getElementById('m-mi').innerText = fmt(totalKm * 0.621371, 2);
hint.innerText = 'Double-click last point to close polygon';
} else {
const closingKm = haversine(measurePoints[measurePoints.length-1][0], measurePoints[measurePoints.length-1][1], measurePoints[0][0], measurePoints[0][1]);
const perimKm = totalKm + closingKm;
let area = 0;
const R = EARTH_RADIUS_KM;
for (let i = 0; i < measurePoints.length; i++) {
const j = (i + 1) % measurePoints.length;
const xi = measurePoints[i][0] * Math.PI / 180; const yi = measurePoints[i][1] * Math.PI / 180;
const xj = measurePoints[j][0] * Math.PI / 180; const yj = measurePoints[j][1] * Math.PI / 180;
area += (xj - xi) * (2 + Math.sin(yi) + Math.sin(yj));
}
const areaKm2 = Math.abs(area) * R * R / 2;
const areaHa = areaKm2 * 100; const areaAc = areaKm2 * 247.105;
lineEl.style.display = 'none'; perimEl.style.display = 'block'; areaEl.style.display = 'block';
document.getElementById('m-pkm').innerText = fmt(perimKm, 2); document.getElementById('m-pm').innerText = fmt(perimKm * 1000, 0);
document.getElementById('m-km2').innerText = fmt(areaKm2, 3); document.getElementById('m-ha').innerText = fmt(areaHa, 1);
document.getElementById('m-ac').innerText = fmt(areaAc, 1);
hint.innerText = 'Click 📏 Measure again to reset';
}
}
function updateMeasureLayers() {
if (!map.getSource('src-measure-line')) return;
const lineCoords = [...measurePoints];
if (measureClosed && measurePoints.length > 2) lineCoords.push(measurePoints[0]);
map.getSource('src-measure-line').setData({ type: 'FeatureCollection', features: lineCoords.length > 1 ? [{ type: 'Feature', geometry: { type: 'LineString', coordinates: lineCoords } }] : [] });
map.getSource('src-measure-fill').setData({ type: 'FeatureCollection', features: measureClosed && measurePoints.length > 2 ? [{ type: 'Feature', geometry: { type: 'Polygon', coordinates: [[...measurePoints, measurePoints[0]]] } }] : [] });
map.getSource('src-measure-points').setData({ type: 'FeatureCollection', features: measurePoints.map(c => ({ type: 'Feature', geometry: { type: 'Point', coordinates: c } })) });
}
function clearMeasure() {
measurePoints = []; measureClosed = false; updateMeasureLayers(); updateMeasureDisplay();
document.getElementById('measure-display').style.display = 'none';
}
function undoLastMeasurePoint() {
if (measurePoints.length === 0 || measureClosed) return;
measurePoints.pop(); updateMeasureLayers(); updateMeasureDisplay();
}
function toggleMeasureMode() {
measureMode = !measureMode;
const btn = document.getElementById('btn-measure');
btn.classList.toggle('active', measureMode); btn.setAttribute('aria-pressed', measureMode);
map.getCanvas().style.cursor = measureMode ? 'crosshair' : '';
if (!measureMode) { clearMeasure(); } else {
if (radiusMode) toggleRadiusMode();
if (radiusAreaMode) toggleRadiusAreaMode();
if (zoneDrawMode) toggleZoneDrawMode();
document.getElementById('measure-display').style.display = 'block'; updateMeasureDisplay();
}
}
function toggleRadiusAreaMode() {
radiusAreaMode = !radiusAreaMode;
const btn = document.getElementById('btn-radius-area');
if(btn) {
btn.classList.toggle('active', radiusAreaMode);
btn.setAttribute('aria-pressed', radiusAreaMode);
}
const popupEl = document.getElementById('radius-area-popup');
if(popupEl) popupEl.style.display = radiusAreaMode ? 'block' : 'none';
map.getCanvas().style.cursor = radiusAreaMode ? 'crosshair' : '';
if (radiusAreaMode && radiusMode) toggleRadiusMode();
if (radiusAreaMode && measureMode) toggleMeasureMode();
if (radiusAreaMode && zoneDrawMode) toggleZoneDrawMode();
if (radiusAreaMode) measurementDock.open(map, 'radius-area-popup');
if (!radiusAreaMode) {
measurementDock.close();
if(map.getSource('src-radius-area')) {
map.getSource('src-radius-area').setData({ type: 'FeatureCollection', features: [] });
}
radiusAreaCenter = null;
if (radiusAreaMarker) { radiusAreaMarker.remove(); radiusAreaMarker = null; }
closeActivePopup();
}
}
function doRadiusAreaMeasure(lon, lat) {
const input = document.getElementById('radius-area-input');
if(!input) return;
const km = parseFloat(input.value);
if (isNaN(km) || km <= 0 || km > MAX_RADIUS_KM) {
input.classList.add('invalid');
return;
}
input.classList.remove('invalid');
radiusAreaCenter = { lon, lat };
if(map.getSource('src-radius-area')) {
map.getSource('src-radius-area').setData(createGeoJSONCircle(lon, lat, km));
}
if (radiusAreaMarker) radiusAreaMarker.remove(); radiusAreaMarker = null;
const R = EARTH_RADIUS_KM;
const areaKm2 = 2 * Math.PI * R * R * (1 - Math.cos(km / R));
const areaM2 = areaKm2 * 1000000;
const areaHa = areaM2 / 10000;
const areaAc = areaM2 / 4046.85642;
const areaMi2 = areaKm2 * 0.386102;
const pitches = areaM2 / 7140;
measurementDock.show( `
            <div style="font-family:monospace;background:#000;padding:10px 12px;border:1px solid #ff00ff;border-radius:4px;min-width:220px;position:relative;">
                <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:8px;">
                    <b style="color:#ff00ff;font-size:13px;">◵ ${km}km radius</b>
                    <span onclick="window._closePopupKeepShape()" style="color:#555;font-size:14px;cursor:pointer;line-height:1;padding:0 2px;user-select:none;" title="Close popup, keep circle">✕</span>
                </div>
                <div style="color:#ffae00;font-size:13px;margin-bottom:10px;">⚽ ${fmt(pitches, 1)} football pitches</div>
                <div style="display:grid;grid-template-columns:auto 1fr;gap:4px 14px;font-size:12px;">
                    <span style="color:#888;">Square Metres</span><span style="color:#fff;">${fmt(areaM2, 0)}</span>
                    <span style="color:#888;">Hectares</span><span style="color:#fff;">${fmt(areaHa, 2)}</span>
                    <span style="color:#888;">Acres</span><span style="color:#fff;">${fmt(areaAc, 2)}</span>
                    <span style="color:#888;">Square Kilometres</span><span style="color:#fff;">${fmt(areaKm2, 3)}</span>
                    <span style="color:#888;">Square Miles</span><span style="color:#fff;">${fmt(areaMi2, 3)}</span>
                </div>
            </div>`);
}
setInterval(() => {
const now = new Date();
const target = new Date(Date.UTC(2050, 0, 1, 0, 0, 0));
document.getElementById('clock').innerText = now.toLocaleTimeString('en-GB');
document.getElementById('date').innerText = now.toLocaleDateString('en-GB');
document.getElementById('days').innerText = Math.floor((target - now) / 86400000) + ' DAYS';
}, 1000);
const map = new maplibregl.Map({
container: 'map',
style: 'https://basemaps.cartocdn.com/gl/dark-matter-gl-style/style.json',
center: center,
zoom: zoom,
attributionControl: false
});
new ResizeObserver(() => map.resize()).observe(document.getElementById('map'));
function updateUIState(id, state, stats) {
RUNTIME_STATE[id].status = state;
['lbl-', 'fs-lbl-'].forEach(prefix => {
const span = document.getElementById(`${prefix}${id}`);
if (span) {
const baseText = span.getAttribute('data-base-label');
if (stats && stats.count > 0) {
let unitStr = '';
if (id === 'naei_co2') {
unitStr = `${fmt(stats.mw, 0)} tCO₂e`;
} else {
unitStr = stats.mw >= 1000 ? `${(stats.mw / 1000).toFixed(1)}GW` : `${Math.round(stats.mw)}MW`;
}
span.innerText = `${baseText} [${stats.count} | ${unitStr}]`;
} else {
span.innerText = `${baseText} [${state}]`;
}
span.style.opacity = state === 'FAIL' ? '0.5' : '1';
}
});
}
class FetchQueue {
constructor(concurrency) { this.concurrency = concurrency; this.active = 0; this.queue = []; }
async add(task) {
if (this.active >= this.concurrency) await new Promise(resolve => this.queue.push(resolve));
this.active++;
try { return await task(); }
finally { this.active--; if (this.queue.length > 0) this.queue.shift()(); }
}
}
const networkQueue = new FetchQueue(4);
async function fetchWithTimeout(url, ms = 15000) {
const controller = new AbortController();
const id = setTimeout(() => controller.abort(), ms);
try {
const response = await fetch(url, { signal: controller.signal, cache: 'no-cache' });
clearTimeout(id);
if (!response.ok) throw new Error(`HTTP ${response.status} for ${url}`);
return response;
} catch (err) { clearTimeout(id); throw err; }
}
async function fetchAndParseGeoJSON(url) {
if (urlCache[url]) return await urlCache[url];
const promise = fetchWithTimeout(url)
.then(res => res.json())
.then(data => {
if (!data || !Array.isArray(data.features)) { console.error(`[INVALID GEOJSON] ${url}`, data); return []; }
console.log(`[DATA LOADED] ${url}: ${data.features.length} features`); return data.features;
})
.catch(err => { delete urlCache[url]; console.error(`[FETCH ERROR] ${url}`, err); throw err; });
urlCache[url] = promise;
return promise;
}
function snapLines(features, subs) {
if (!subs || !subs.length) return features;
const TOLERANCE_DEG_SQ = 0.001 * 0.001;
const RAD = Math.PI / 180;
const snapCoordinate = (coord) => {
let best = coord, min = Infinity;
const latCos = Math.cos(coord[1] * RAD);
subs.forEach(s => {
const sc = s.geometry && s.geometry.coordinates;
if (!sc) return;
const dx = (coord[0] - sc[0]) * latCos;
const dy = (coord[1] - sc[1]);
const d = dx * dx + dy * dy;
if (d < min && d <= TOLERANCE_DEG_SQ) { min = d; best = sc; }
});
return best;
};
return features.map(f => {
const geom = f.geometry;
if (!geom || !geom.coordinates) return f;
if (geom.type === 'LineString') {
const c = [...geom.coordinates];
if (c.length > 0) {
c[0] = snapCoordinate(c[0]);
c[c.length - 1] = snapCoordinate(c[c.length - 1]);
}
return { ...f, geometry: { ...geom, coordinates: c } };
}
if (geom.type === 'MultiLineString') {
const coords = geom.coordinates.map(line => {
const l = [...line];
if (l.length > 0) {
l[0] = snapCoordinate(l[0]);
l[l.length - 1] = snapCoordinate(l[l.length - 1]);
}
return l;
});
return { ...f, geometry: { ...geom, coordinates: coords } };
}
return f;
});
}
function createGeoJSONCircle(lon, lat, radiusKm) {
const points = radiusKm > 5000 ? 128 : radiusKm > 500 ? 96 : 64;
const R = EARTH_RADIUS_KM, DEG = Math.PI / 180;
const ad = radiusKm / R;
const lat1 = lat * DEG;
const coords = Array.from({ length: points }, (_, i) => {
const b = (i / points) * 2 * Math.PI;
const lat2 = Math.asin(Math.sin(lat1) * Math.cos(ad) + Math.cos(lat1) * Math.sin(ad) * Math.cos(b));
const lon2 = lon * DEG + Math.atan2(Math.sin(b) * Math.sin(ad) * Math.cos(lat1), Math.cos(ad) - Math.sin(lat1) * Math.sin(lat2));
return [lon2 / DEG, lat2 / DEG];
});
coords.push(coords[0]);
return { type: 'FeatureCollection', features: [{ type: 'Feature', geometry: { type: 'Polygon', coordinates: [coords] } }] };
}
function drawRadiusCircle(lon, lat, radiusKm) { map.getSource('src-radius-circle').setData(createGeoJSONCircle(lon, lat, radiusKm)); }
function clearRadiusCircle() { map.getSource('src-radius-circle').setData({ type: 'FeatureCollection', features: [] }); }
let _visibleInteractiveIds = [];
let _visibleHoverIds = [];
function _rebuildVisibleCache(allLayerIds) {
_visibleInteractiveIds = allLayerIds.filter(id => {
try { return map.getLayoutProperty(id, 'visibility') === 'visible'; }
catch(e) { return false; }
});
_visibleHoverIds = [..._visibleInteractiveIds];
}
let _lastHoverMs = 0;
function buildSearchButtons(name, capacity, tech) {
const threshold = SEARCH_THRESHOLD[tech] !== undefined ? SEARCH_THRESHOLD[tech] : 50;
if (capacity < threshold) return '';
const term = TECH_TERMS.get(tech) || 'energy project';
const q = encodeURIComponent(`${name} ${term} UK`);
const newsUrl = `https://news.google.com/search?q=${q}`;
const imageUrl = `https://www.google.com/search?q=${q}&tbm=isch`;
return `<div class="popup-search-btns">
            <a class="popup-btn popup-btn-news" href="${newsUrl}" target="_blank" rel="noopener noreferrer">📰 NEWS</a>
            <a class="popup-btn popup-btn-images" href="${imageUrl}" target="_blank" rel="noopener noreferrer">🖼 IMAGES</a>
        </div>`;
}
function buildSearchIndex() {
searchIndex = allREPDFeatures
.filter(f => f && f.properties && f.properties.name)
.map(f => ({ feature: f, nameLower: String(f.properties.name).toLowerCase(), capacity: Number(f.properties.capacity) || 0 }));
}
function flyToProject(feature) {
const [lon, lat] = feature.geometry.coordinates;
const p = feature.properties;
const cap = p.capacity ? `${p.capacity} MW` : '';
const mounting = (p.mounting && p.mounting !== 'nan') ? ` | ${escapeHTML(p.mounting)}` : '';
map.flyTo({ center: [lon, lat], zoom: 12, duration: 1800, essential: true });
setTimeout(() => {
openPopup([lon, lat], `<div style="font-family:monospace;background:#000;padding:6px">
                    <b style="color:#00ffff;font-size:13px">${escapeHTML(p.name)}</b><br>
                    <span style="color:#888">${escapeHTML(p.raw_tech || p.tech)}${mounting}</span><br>
                    <span style="color:#ffae00">${escapeHTML(cap)}</span>
                    <span style="color:#666"> | ${escapeHTML(p.status)}</span><br>
                    <span style="color:#555;font-size:10px">${escapeHTML(p.operator)}</span>
                    ${REPD_IDS.includes(p.tech) ? buildSearchButtons(p.name, parseFloat(p.capacity) || 0, p.tech) : ''}
                </div>`);
}, 1900);
}
async function focusCanonicalProjectDeepLink() {
const params = new URLSearchParams(window.location.search);
const repdRef = String(params.get('repd_ref') || '').trim();
if (!/^[A-Za-z0-9-]{1,40}$/.test(repdRef)) return;
try {
const requestedTechnology = String(params.get('technology') || '').trim();
const allowedTechnologies = new Set([
'solar', 'solar_operational', 'solar_roof',
'bess', 'bess_operational',
'wind', 'wind_onshore', 'wind_onshore_operational',
'wind_offshore', 'wind_offshore_operational',
'biomass', 'tidal', 'hydrogen', 'hydro', 'flywheel',
'act', 'geothermal', 'caes', 'other'
]);
window.__GRIDATLAS_V8_DEEP_LINK__ = {
status: 'DEFERRED_TO_EXACT_REPD_RECEIVER',
repd_ref: repdRef,
technology: requestedTechnology || null,
technology_recognised: requestedTechnology
? allowedTechnologies.has(requestedTechnology) : null,
legacy_fetches: 0
};
return;
} catch (error) {
console.error('[V9 DEEP LINK FAILED]', error);
const lon = Number(params.get('longitude'));
const lat = Number(params.get('latitude'));
if (Number.isFinite(lon) && Number.isFinite(lat) && Math.abs(lon) <= 180 && Math.abs(lat) <= 90) {
map.flyTo({ center: [lon, lat], zoom: 12, duration: 1800, essential: true });
}
}
}
function searchProjects(query) {
const resultsEl = document.getElementById('search-results');
if (!query || query.length < 2) { resultsEl.style.display = 'none'; return; }
if (!allREPDFeatures.length) {
resultsEl.innerHTML = '<div class="search-no-results">Load a REPD layer first to enable search</div>';
resultsEl.style.display = 'block'; return;
}
const q = query.toLowerCase();
const matches = searchIndex.filter(item => item.nameLower.includes(q)).sort((a, b) => b.capacity - a.capacity).slice(0, 12).map(item => item.feature);
if (!matches.length) { resultsEl.innerHTML = '<div class="search-no-results">No projects found</div>'; resultsEl.style.display = 'block'; return; }
resultsEl.innerHTML = matches.map((f, i) => {
const p = f.properties;
const cap = p.capacity ? ` — ${p.capacity} MW` : '';
const col = TECH_COLOURS.get(p.tech) || '#888';
return `<div class="search-result-item" data-idx="${i}"><b>${escapeHTML(p.name)}</b><span style="color:#555">${escapeHTML(cap)}</span><br>
                <span style="color:${col};font-size:9px">${escapeHTML(p.raw_tech || p.tech)}</span>
                <span style="color:#444;font-size:9px"> | ${escapeHTML(p.status || '')}</span></div>`;
}).join('');
resultsEl.querySelectorAll('.search-result-item').forEach((el, i) => {
el.addEventListener('click', () => { flyToProject(matches[i]); resultsEl.style.display = 'none'; document.getElementById('search-input').value = matches[i].properties.name; });
});
resultsEl.style.display = 'block';
}
function exportCSV() {
if (!allREPDFeatures.length) { alert('Load a REPD layer first'); return; }
const visibleTechs = REPD_IDS.filter(id => { const cb = document.querySelector(`input[data-layer-id="${id}"]`); return cb && cb.checked; });
const rows = allREPDFeatures.filter(f => visibleTechs.includes(f.properties.tech));
if (!rows.length) { alert('No visible REPD layers to export — tick some layers first'); return; }
const headers = ['name','tech','raw_tech','capacity_mw','status','operator','mounting','longitude','latitude'];
const csv = [headers.join(','), ...rows.map(f => {
const p = f.properties; const [lon, lat] = f.geometry.coordinates;
return [`"${(p.name||'').replace(/"/g, '""')}"`,`"${(p.tech||'').replace(/"/g, '""')}"`,`"${(p.raw_tech||'').replace(/"/g, '""')}"`,p.capacity,`"${(p.status||'').replace(/"/g, '""')}"`,`"${(p.operator||'').replace(/"/g, '""')}"`,`"${(p.mounting||'').replace(/"/g, '""')}"`,lon, lat].join(',');
})].join('\n');
const blob = new Blob([csv], { type: 'text/csv' });
const objectUrl = URL.createObjectURL(blob);
const a = document.createElement('a'); a.href = objectUrl; a.download = `globalgrid2050_export_${new Date().toISOString().slice(0, 10)}.csv`;
document.body.appendChild(a);
try { a.click(); } finally { a.remove(); setTimeout(() => URL.revokeObjectURL(objectUrl), 1000); }
}
function toggleStatusMode() {
statusMode = !statusMode;
const btn = document.getElementById('btn-status');
btn.classList.toggle('active', statusMode); btn.setAttribute('aria-pressed', statusMode);
if (map.getLayer('l-naei_co2-glow')) {
const isBaseVisible = document.querySelector('input[data-layer-id="naei_co2"]')?.checked;
map.setLayoutProperty('l-naei_co2-glow', 'visibility', statusMode ? 'none' : (isBaseVisible ? 'visible' : 'none'));
}
REPD_IDS.forEach(id => {
if (!map.getLayer(`l-${id}`)) return;
if (id === 'solar' || id === 'solar_roof') {
if (map.getLayer(`l-${id}-glow`)) {
const isBaseVisible = document.querySelector(`input[data-layer-id="${id}"]`).checked;
map.setLayoutProperty(`l-${id}-glow`, 'visibility', statusMode ? 'none' : (isBaseVisible ? 'visible' : 'none'));
}
}
if (statusMode) {
map.setPaintProperty(`l-${id}`, 'circle-color', ['match', ['downcase', ['coalesce', ['get', 'status'], '']],
'operational','#00ff88','under construction','#ffcc00','awaiting construction','#ffaa00',
'consented','#ff8800','planning permission granted','#ff8800','planning approved','#ff8800',
'application submitted','#8888ff','pre-construction','#aaaaff','#444']);
} else {
const layer = layerConfigById.get(id);
if (id === 'solar_roof') {
map.setPaintProperty(`l-${id}`, 'circle-color', ['interpolate',['linear'],['coalesce',['get','capacity'],0],0,'#ffcc00',0.99,'#ffcc00',1.0,'#ff8c00',5.0,'#ff6600',10.0,'#ff4400']);
} else if (id === 'solar') {
map.setPaintProperty(`l-${id}`, 'circle-color', ['interpolate',['linear'],['coalesce',['get','capacity'],0],0,'#ffff00',20.0,'#ffcc00',50.0,'#ffaa00',200.0,'#ff6600',500.0,'#ff2200']);
} else {
map.setPaintProperty(`l-${id}`, 'circle-color', layer.color);
}
}
});
}
function toggleRadiusMode() {
radiusMode = !radiusMode;
const btn = document.getElementById('btn-radius');
btn.classList.toggle('active', radiusMode); btn.setAttribute('aria-pressed', radiusMode);
document.getElementById('radius-popup').style.display = radiusMode ? 'block' : 'none';
map.getCanvas().style.cursor = radiusMode ? 'crosshair' : '';
if (radiusMode && measureMode) toggleMeasureMode();
if (radiusMode && radiusAreaMode) toggleRadiusAreaMode();
if (radiusMode && zoneDrawMode) toggleZoneDrawMode();
if (!radiusMode) { clearRadiusCircle(); radiusCenter = null; if (radiusMarker) { radiusMarker.remove(); radiusMarker = null; } }
}
function doRadiusSearch(lon, lat) {
if (!validateRadiusInput()) return;
const km = getRadiusValue(); radiusCenter = { lon, lat }; drawRadiusCircle(lon, lat, km);
if (radiusMarker) radiusMarker.remove(); radiusMarker = null;
const nearby = allREPDFeatures.filter(f => { const [flon, flat] = f.geometry.coordinates; return haversine(lon, lat, flon, flat) <= km; }).sort((a, b) => (b.properties.capacity || 0) - (a.properties.capacity || 0));
if (!nearby.length) {
openPopup([lon, lat], `
                <div style="font-family:monospace;background:#000;padding:8px">
                    <b style="color:#00ffff">◎ ${km}km radius active</b><br><br>
                    <span style="color:#888;font-size:10px">No REPD assets found in this area.</span><br>
                    <span style="color:#555;font-size:9px;line-height:1.6">Tick layers in the panel below<br>to explore assets within this circle.</span>
                </div>`);
return;
}
const totalMW = nearby.reduce((s, f) => s + (parseFloat(f.properties.capacity) || 0), 0);
const byTech = {};
nearby.forEach(f => { const t = f.properties.tech; byTech[t] = (byTech[t] || 0) + 1; });
const techSummary = Object.entries(byTech).sort((a, b) => b[1] - a[1]).map(([t, n]) => `<span style="color:#888">${escapeHTML(t)}: ${n}</span>`).join('<br>');
const topAssets = nearby.slice(0, 5).map(f => {
const p = f.properties;
return `<div style="border-top:1px solid #222;padding-top:4px;margin-top:4px">
                <b style="color:#ffcc00;font-size:11px">${escapeHTML(p.name)}</b><br>
                <span style="color:#888;font-size:10px">${escapeHTML(p.raw_tech)}</span>
                <span style="color:#ffae00;font-size:10px"> ${p.capacity || '?'} MW</span></div>`;
}).join('');
openPopup([lon, lat], `
            <div style="font-family:monospace;background:#000;padding:6px">
                <b style="color:#00ffff">◎ ${km}km — ${nearby.length} assets | ${totalMW.toFixed(1)} MW</b><br>
                <span style="color:#555;font-size:9px;line-height:1.8">Tick layers in the panel to explore this area</span><br><br>
                ${techSummary}${topAssets}
            </div>`);
}
function buildLayerRow(layer, idPrefix) {
const label = document.createElement('label'); label.className = 'key-item';
const input = document.createElement('input'); input.type = 'checkbox'; input.dataset.layerId = layer.id; input.setAttribute('data-layer-id', layer.id);
const span = document.createElement('span'); span.id = `${idPrefix}${layer.id}`; span.setAttribute('data-base-label', layer.label); span.style.color = layer.color; span.style.fontSize = '11px';
const existing = document.getElementById(`lbl-${layer.id}`); span.innerText = existing ? existing.innerText : `${layer.label} [WAIT]`;
const mainCb = document.querySelector(`input[data-layer-id="${layer.id}"]`); if (mainCb) input.checked = mainCb.checked;
label.appendChild(input); label.appendChild(document.createTextNode(' ')); label.appendChild(span);
return label;
}
function buildDOM() {
const container = document.getElementById('scada-ui-container');
const fsContainer = document.getElementById('fs-curtain-keys');
container.innerHTML = ''; fsContainer.innerHTML = '';
const fragment = document.createDocumentFragment();
const fsFragment = document.createDocumentFragment();
GRID_CONFIG.forEach(group => {
const groupDiv = document.createElement('div'); groupDiv.className = 'key-group';
const fsGroupDiv = document.createElement('div'); fsGroupDiv.className = 'key-group';
groupDiv.innerHTML = fsGroupDiv.innerHTML = `<div class="key-title">${group.group}</div>`;
group.layers.forEach(layer => {
const label = document.createElement('label'); label.className = 'key-item';
const input = document.createElement('input'); input.type = 'checkbox'; input.dataset.layerId = layer.id; input.setAttribute('data-layer-id', layer.id);
const span = document.createElement('span'); span.id = `lbl-${layer.id}`; span.setAttribute('data-base-label', layer.label); span.style.color = layer.color; span.innerText = `${layer.label} [WAIT]`;
label.appendChild(input); label.appendChild(document.createTextNode(' ')); label.appendChild(span);
groupDiv.appendChild(label); fsGroupDiv.appendChild(buildLayerRow(layer, 'fs-lbl-'));
});
fragment.appendChild(groupDiv); fsFragment.appendChild(fsGroupDiv);
});
const bmHTML = `<div class="key-title">Basemap</div><label class="key-item"><input type="radio" name="bm" value="dark" checked> Dark</label><label class="key-item"><input type="radio" name="bm" value="sat"> Satellite</label>`;
const bmGroup = document.createElement('div'); bmGroup.className = 'key-group'; bmGroup.innerHTML = bmHTML; fragment.appendChild(bmGroup);
const fsBmGroup = document.createElement('div'); fsBmGroup.className = 'key-group'; fsBmGroup.innerHTML = bmHTML.replace(/name="bm"/g, 'name="bm-fs"'); fsFragment.appendChild(fsBmGroup);
container.appendChild(fragment); fsContainer.appendChild(fsFragment);
container.addEventListener('change', e => {
if (e.target.type === 'checkbox' && e.target.dataset.layerId) {
const layerId = e.target.dataset.layerId; const isVisible = e.target.checked;
const fsCb = document.querySelector(`#fs-curtain-keys input[data-layer-id="${layerId}"]`); if (fsCb) fsCb.checked = isVisible;
handleLayerToggle(layerId, isVisible);
} else if (e.target.name === 'bm') {
map.setLayoutProperty('l-sat', 'visibility', e.target.value === 'sat' ? 'visible' : 'none');
const fsBm = document.querySelector(`input[name="bm-fs"][value="${e.target.value}"]`); if (fsBm) fsBm.checked = true;
}
});
fsContainer.addEventListener('change', e => {
if (e.target.type === 'checkbox' && e.target.dataset.layerId) {
const layerId = e.target.dataset.layerId; const isVisible = e.target.checked;
const mainCb = document.querySelector(`#scada-ui-container input[data-layer-id="${layerId}"]`); if (mainCb) mainCb.checked = isVisible;
handleLayerToggle(layerId, isVisible);
} else if (e.target.name === 'bm-fs') {
map.setLayoutProperty('l-sat', 'visibility', e.target.value === 'sat' ? 'visible' : 'none');
const mainBm = document.querySelector(`input[name="bm"][value="${e.target.value}"]`); if (mainBm) mainBm.checked = true;
}
});
document.getElementById('fs-curtain-tab').addEventListener('click', toggleCurtain);
const input = document.getElementById('search-input'); const btn = document.getElementById('search-btn'); const resultsEl = document.getElementById('search-results');
input.addEventListener('input', () => searchProjects(input.value));
input.addEventListener('keydown', e => { if (e.key === 'Enter') searchProjects(input.value); if (e.key === 'Escape') resultsEl.style.display = 'none'; });
btn.addEventListener('click', () => searchProjects(input.value));
document.getElementById('map').addEventListener('click', () => { resultsEl.style.display = 'none'; });
document.getElementById('btn-export').addEventListener('click', exportCSV); document.getElementById('btn-status').addEventListener('click', toggleStatusMode);
document.getElementById('btn-radius').addEventListener('click', toggleRadiusMode); document.getElementById('btn-measure').addEventListener('click', toggleMeasureMode);
document.getElementById('btn-measure-undo').addEventListener('click', undoLastMeasurePoint);
const zoneReset = document.createElement('button');
zoneReset.id = 'btn-zonedraw-reset';
zoneReset.type = 'button';
zoneReset.textContent = 'Reset polygon';
zoneReset.title = 'Clear this polygon and place a new circle';
zoneReset.style.cssText = 'display:block;margin-top:8px;padding:8px;border:1px solid #ff6600;background:#111;color:#ffb14d;cursor:pointer;min-height:44px';
zoneReset.addEventListener('click', () => {
_zoneDrawClear();
const control = document.getElementById('zonedraw-display');
if (control && zoneDrawMode) control.style.display = 'block';
});
document.getElementById('zonedraw-display').append(zoneReset);
const zoneExport = document.createElement('button');
zoneExport.id = 'btn-zonedraw-export'; zoneExport.type = 'button';
zoneExport.textContent = 'Save GeoJSON'; zoneExport.disabled = zoneDrawPoints.length < 3;
zoneExport.style.cssText = 'display:block;margin-top:8px;padding:8px;border:1px solid #42bcca;background:#111;color:#b9f8ff;cursor:pointer;min-height:44px';
zoneExport.addEventListener('click', () => {
try {
const area = _zoneDrawCalcArea(zoneDrawPoints);
const data = window.__GRIDATLAS_MODULES__.polygonFiles.exportOutline(zoneDrawPoints,{area_m2:area.areaM2,area_ha:area.areaHa,perimeter_km:area.perimKm});
const url = URL.createObjectURL(new Blob([JSON.stringify(data,null,2)+'\n'],{type:'application/geo+json'}));
const anchor = document.createElement('a'); anchor.href=url;
anchor.download='gridatlas-polygon-'+new Date().toISOString().replace(/[:.]/g,'-')+'.geojson';
document.body.append(anchor); anchor.click(); anchor.remove();
setTimeout(() => URL.revokeObjectURL(url),1000);
_zoneDrawStorageStatus({message:'GeoJSON download created'});
} catch(error) {_zoneDrawStorageStatus({message:error.message});}
});
document.getElementById('zonedraw-display').append(zoneExport);
const zoneImport = document.createElement('button');
zoneImport.id='btn-zonedraw-import'; zoneImport.type='button'; zoneImport.textContent='Open GeoJSON';
zoneImport.style.cssText=zoneExport.style.cssText;
const zoneFile=document.createElement('input'); zoneFile.type='file'; zoneFile.id='zonedraw-file';
zoneFile.accept='.geojson,.json,application/geo+json,application/json'; zoneFile.hidden=true;
zoneImport.addEventListener('click',()=>zoneFile.click());
zoneFile.addEventListener('change',async()=>{
const file=zoneFile.files[0]; if(!file)return;
try {
if(file.size>250000)throw Error('Choose a GeoJSON file under 250 KB.');
const points=window.__GRIDATLAS_MODULES__.polygonFiles.importOutline(await file.text());
zoneDrawPoints=points; zoneDrawDragging=false; zoneDrawDragIdx=-1;
_zoneDrawUpdateLayers(false); _zoneDrawShowPopup(); _zoneDrawFit();
_zoneDrawStorageStatus({message:'Opened '+points.length+' polygon vertices from '+file.name});
} catch(error) {_zoneDrawStorageStatus({message:error.message});}
finally {zoneFile.value='';}
});
document.getElementById('zonedraw-display').append(zoneImport,zoneFile);
const zoneRedo=document.createElement('button');zoneRedo.id='btn-zonedraw-redo';zoneRedo.type='button';
zoneRedo.textContent='Redo edit';zoneRedo.disabled=true;zoneRedo.style.cssText=zoneExport.style.cssText;
zoneRedo.addEventListener('click',()=>zoneDrawHistoryMove('redo'));
document.getElementById('zonedraw-display').append(zoneRedo);
const zoneLock=document.createElement('button');zoneLock.id='btn-zonedraw-lock';zoneLock.type='button';
zoneLock.textContent='Lock polygon';zoneLock.setAttribute('aria-pressed','false');zoneLock.style.cssText=zoneExport.style.cssText;
zoneLock.addEventListener('click',()=>{
zoneDrawLocked=!zoneDrawLocked;zoneDrawDragging=false;zoneDrawDragIdx=-1;map.dragPan.enable();
zoneLock.textContent=zoneDrawLocked?'Unlock polygon':'Lock polygon';zoneLock.setAttribute('aria-pressed',String(zoneDrawLocked));
map.getCanvas().style.cursor=zoneDrawLocked?'grab':'crosshair';_zoneDrawUpdateLayers(false);
_zoneDrawStorageStatus({message:zoneDrawLocked?'Polygon locked: pan and zoom without editing vertices':'Polygon unlocked: drag corners to edit'});
});
document.getElementById('zonedraw-display').append(zoneLock);
const zoneFit=document.createElement('button');zoneFit.id='btn-zonedraw-fit';zoneFit.type='button';
zoneFit.textContent='Fit polygon';zoneFit.disabled=zoneDrawPoints.length<3;zoneFit.style.cssText=zoneExport.style.cssText;
zoneFit.addEventListener('click',()=>{if(zoneDrawPoints.length>=3)_zoneDrawFit();});
document.getElementById('zonedraw-display').append(zoneFit);
const zoneCSV=document.createElement('button');zoneCSV.id='btn-zonedraw-csv';zoneCSV.type='button';
zoneCSV.textContent='Save vertex CSV';zoneCSV.disabled=zoneDrawPoints.length<3;zoneCSV.style.cssText=zoneExport.style.cssText;
zoneCSV.addEventListener('click',()=>{
if(zoneDrawPoints.length<3)return;
let chainage=0;const lines=['vertex,longitude_deg,latitude_deg,chainage_m,next_segment_m'];
zoneDrawPoints.forEach((p,i)=>{const q=zoneDrawPoints[(i+1)%zoneDrawPoints.length],length=haversine(p[0],p[1],q[0],q[1])*1000;
lines.push([i+1,p[0],p[1],chainage,length].join(','));chainage+=length;});
const url=URL.createObjectURL(new Blob([lines.join('\r\n')+'\r\n'],{type:'text/csv;charset=utf-8'}));
const anchor=document.createElement('a');anchor.href=url;anchor.download='gridatlas-polygon-vertices.csv';
document.body.append(anchor);anchor.click();anchor.remove();setTimeout(()=>URL.revokeObjectURL(url),1000);
_zoneDrawStorageStatus({message:'Vertex CSV created. Chainage follows the drawn order; the last segment closes the outline. Distances are geodesic estimates.'});
});
document.getElementById('zonedraw-display').append(zoneCSV);
const zoneEditor=document.createElement('details');zoneEditor.id='zonedraw-coordinate-editor';zoneEditor.style.cssText='margin-top:8px;font-size:12px';
const summary=document.createElement('summary');summary.textContent='Edit or remove vertices';summary.style.cssText='min-height:44px;cursor:pointer';zoneEditor.append(summary);
for(const spec of [['Vertex','zonedraw-vertex','select'],['Longitude (degrees)','zonedraw-longitude','input'],['Latitude (degrees)','zonedraw-latitude','input']]){
const label=document.createElement('label');label.textContent=spec[0];label.htmlFor=spec[1];label.style.display='block';
const control=document.createElement(spec[2]);control.id=spec[1];control.disabled=true;control.style.cssText='display:block;box-sizing:border-box;width:100%;min-height:44px;background:#111;color:#fff;border:1px solid #64748b';
if(spec[2]==='input'){control.type='number';control.step='any';control.min=spec[1].endsWith('longitude')?'-180':'-85.051129';control.max=spec[1].endsWith('longitude')?'180':'85.051129';}
zoneEditor.append(label,control);
}
const zoneApply=document.createElement('button');zoneApply.id='btn-zonedraw-coordinate';zoneApply.type='button';zoneApply.textContent='Apply coordinate';zoneApply.disabled=true;zoneApply.style.cssText=zoneExport.style.cssText;zoneEditor.append(zoneApply);
const zoneRemove=document.createElement('button');zoneRemove.id='btn-zonedraw-remove';zoneRemove.type='button';zoneRemove.textContent='Remove selected vertex';zoneRemove.disabled=true;zoneRemove.style.cssText=zoneExport.style.cssText;zoneEditor.append(zoneRemove);
zoneRemove.title='Keep at least three vertices. Undo restores a removed vertex.';
zoneRemove.addEventListener('click',()=>{
if(zoneDrawLocked||zoneDrawPoints.length<=3)return;
const i=Number(document.getElementById('zonedraw-vertex').value);
if(!Number.isInteger(i)||!zoneDrawPoints[i])return;
zoneDrawPoints.splice(i,1);_zoneDrawUpdateLayers(false);_zoneDrawShowPopup();
_zoneDrawStorageStatus({message:'Removed vertex '+(i+1)+'. Undo restores the exact outline.'});
});
document.getElementById('zonedraw-display').append(zoneEditor);
document.getElementById('zonedraw-vertex').addEventListener('change',_zoneDrawRefreshEditor);
zoneApply.addEventListener('click',()=>{
if(zoneDrawLocked||zoneDrawPoints.length<3)return;
const i=Number(document.getElementById('zonedraw-vertex').value),a=document.getElementById('zonedraw-longitude').value,b=document.getElementById('zonedraw-latitude').value;
const lon=Number(a),lat=Number(b);
if(!a.trim()||!b.trim()||!Number.isInteger(i)||!zoneDrawPoints[i]||!Number.isFinite(lon)||!Number.isFinite(lat)||Math.abs(lon)>180||Math.abs(lat)>85.051129){_zoneDrawStorageStatus({message:'Enter longitude from -180 to 180 and latitude from -85.051129 to 85.051129 degrees. The outline has not changed.'});return;}
zoneDrawPoints[i]=[lon,lat];_zoneDrawUpdateLayers(false);_zoneDrawShowPopup();
_zoneDrawStorageStatus({message:'Updated vertex '+(i+1)+'. Undo restores its previous coordinate.'});
});
const existingUndo=document.getElementById('btn-zonedraw-undo');
if(existingUndo){existingUndo.textContent='Undo edit';existingUndo.title='Undo the last polygon edit, import or reset';existingUndo.disabled=true;}
const radiusInput = document.getElementById('radius-input');
if(radiusInput) {
radiusInput.addEventListener('input', () => validateRadiusInput());
radiusInput.addEventListener('keydown', e => { if (e.key === 'Enter') { e.preventDefault(); if (validateRadiusInput() && radiusCenter) doRadiusSearch(radiusCenter.lon, radiusCenter.lat); } e.stopPropagation(); });
radiusInput.addEventListener('blur', () => {
const raw = parseFloat(radiusInput.value);
if (isNaN(raw) || raw < RADIUS_MIN) radiusInput.value = RADIUS_MIN; else if (raw > RADIUS_MAX) radiusInput.value = RADIUS_MAX;
radiusInput.classList.remove('invalid'); if (radiusCenter) doRadiusSearch(radiusCenter.lon, radiusCenter.lat);
});
}
const btnRadiusArea = document.getElementById('btn-radius-area');
if (btnRadiusArea) btnRadiusArea.addEventListener('click', toggleRadiusAreaMode);
const btnZoneDraw = document.getElementById('btn-zonedraw');
if (btnZoneDraw) btnZoneDraw.addEventListener('click', toggleZoneDrawMode);
const btnZoneDrawUndo = document.getElementById('btn-zonedraw-undo');
if (btnZoneDrawUndo) btnZoneDrawUndo.addEventListener('click', zoneDrawUndo);
const zdRadiusInput = document.getElementById('zonedraw-radius-input');
if (zdRadiusInput) {
zdRadiusInput.addEventListener('keydown', e => { e.stopPropagation(); });
zdRadiusInput.addEventListener('blur', () => {
const raw = parseFloat(zdRadiusInput.value);
if (isNaN(raw) || raw <= 0) zdRadiusInput.value = String(ZONE_DRAW_DEFAULT_KM);
else if (raw > ZONE_DRAW_MAX_KM) zdRadiusInput.value = String(ZONE_DRAW_MAX_KM);
});
}
const rAreaInput = document.getElementById('radius-area-input');
if (rAreaInput) {
rAreaInput.addEventListener('keydown', e => {
if (e.key === 'Enter') {
e.preventDefault();
if (radiusAreaCenter) doRadiusAreaMeasure(radiusAreaCenter.lon, radiusAreaCenter.lat);
}
e.stopPropagation();
});
rAreaInput.addEventListener('blur', () => {
const raw = parseFloat(rAreaInput.value);
if (isNaN(raw) || raw <= 0) rAreaInput.value = 1; else if (raw > MAX_RADIUS_KM) rAreaInput.value = MAX_RADIUS_KM;
rAreaInput.classList.remove('invalid');
if (radiusAreaCenter) doRadiusAreaMeasure(radiusAreaCenter.lon, radiusAreaCenter.lat);
});
}
}
function handleLayerToggle(layerId, isVisible) {
if (map.getLayer(`l-${layerId}`)) map.setLayoutProperty(`l-${layerId}`, 'visibility', isVisible ? 'visible' : 'none');
if (map.getLayer(`l-${layerId}-glow`)) map.setLayoutProperty(`l-${layerId}-glow`, 'visibility', (isVisible && !statusMode) ? 'visible' : 'none');
const mapId = `l-${layerId}`;
if (isVisible) {
if (!_visibleInteractiveIds.includes(mapId)) _visibleInteractiveIds.push(mapId);
if (!_visibleHoverIds.includes(mapId)) _visibleHoverIds.push(mapId);
} else {
_visibleInteractiveIds = _visibleInteractiveIds.filter(id => id !== mapId);
_visibleHoverIds = _visibleHoverIds.filter(id => id !== mapId);
}
if (isVisible && layerId !== '400') hydrateLayer(layerId);
}
function getLayerConfig(layerId) { return layerConfigById.get(layerId); }
function getSourceIdForLayer(layerId) {
if (REPD_IDS.includes(layerId)) return 'src-repd';
if (TRANSIT_IDS.includes(layerId)) return TRANSIT_SOURCE_MAP[layerId];
if (layerId === 'naei_co2') return 'src-naei_co2';
return `src-${layerId}`;
}
function transitExpressionValue(expression, feature) {
if (!Array.isArray(expression)) return expression;
if (expression[0] === 'get') return feature && feature.properties
? feature.properties[expression[1]] : undefined;
if (expression[0] === 'literal') return expression[1];
return undefined;