In this section
- Ventus Corev8engine Layer Availability geodesy · gridatlas / atlas/parts/202609040212-ventus-corev8engine-layer-availability.js lines 701–1400
Ventus Corev8engine Layer Availability
A JavaScript file in the parts folder of GridAtlas that maps elizabeth line, london underground, UK metros trams and HS2, using haversine.
Set aside from the main view: 94% of its lines are the same as atlas/parts/202609040229-ventus-corev8engine-exact-repd-delegation.js (gridatlas), which stays. (near-copy-of, proposed by families.py). 94% of lines shared with Ventus Corev8engine Exact Renewable Energy Planning Database (REPD) Delegation; read that one first. All set-aside files, with reasons. Nothing was deleted.
Evidence
- line-jaccard 0.9441 to gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 atlas/parts/202609040229-ventus-corev8engine-exact-repd-delegation.js:1-1497 15a213e64af0a6bac53b905bc51ecba4903fbdec
- sha256 81b103b055258ddd177dee5aa7551def23137c08ae73566a002ef043cbadd3cb
- target sha256 d38a958aa3988b25621695576815ddd210ba67c80e09630a2a60320ad67676a0
- group of 3 (identity.json near-copy edges >= 0.9)
- canonical rule: reachable, newest stamp, core repo, most lines
geodesygridatlas / atlas/parts/202609040212-ventus-corev8engine-layer-availability.js · lines 701–1400 of 1541 · version 2026-09-04 02:12 (continued from section 595) · Not reached from any entry point (candidate for review) · pattern countTransitFeaturesLayerCanDraw (shared by 10 files)
- What it does
- It maps elizabeth line, london underground, UK metros trams and hs2. Defines 64 functions or classes, including deepFreeze, escapeHTML, normalizeStatus, fmt, haversine. Side effects: changes the web page (DOM); makes network requests.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (path word 'atlas'): 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.
- Inputs & outputs
- In: GeoJSON file elizabeth_line.geojson; GeoJSON file london_underground.geojson; GeoJSON file uk_metros_trams.geojson; GeoJSON file hs2.geojson; JSON file style.json; JSON file build_manifest.json; GeoJSON file grid_400kv.geojson; form fields (user input). Out: interactive map.
- What it achieves
- It normalizes status (`normalizeStatus`), toggles zone draw mode (`toggleZoneDrawMode`) and opens popup (`openPopup`). 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). It reads `/uk_renewables_pipeline/v9/data/v9.1/build_manifest.json`. It responds to fullscreenchange, webkitfullscreenchange and click events.
- Why it matters
- No other file in the estate was found to import it.
- Application
- gridatlas · atlas/parts · 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.
- Uses
- none found
- Used by
- none found
- Produces
- deepFreeze, escapeHTML, normalizeStatus, fmt, haversine, _zoneDrawGetRadius, _zoneDrawCirclePoints, _zoneDrawCalcArea, _zoneDrawUpdateLayers, _zoneDrawShowPopup, _zoneDrawShowPopupDebounced, _zoneDrawClear
- Defines here
- createGeoJSONCircle, drawRadiusCircle, clearRadiusCircle, _rebuildVisibleCache, buildSearchButtons, buildSearchIndex, flyToProject, focusCanonicalProjectDeepLink, searchProjects, exportCSV, toggleStatusMode, toggleRadiusMode, doRadiusSearch, buildLayerRow, buildDOM, handleLayerToggle, getLayerConfig, getSourceIdForLayer, transitExpressionValue, transitFilterMatches, geometryFitsMapLayer, countTransitFeaturesLayerCanDraw, setLayerControlAvailability, updateTransitSourceStates, hydrateLayer, evalFilter
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 atlas/parts/202609040212-ventus-corev8engine-layer-availability.js:701-1400 · blob 79d907c472e239787032034f9bf3a1508bccca7e · GitHub at these lines
- State
- achieves: code · context: readme_derived · stage: output · effects: dom, network · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: duplicate_candidate
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;
// ── Popup / Search ────────────────────────────────────────────────────────────
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);
}
// V9 canonical project deep links. Identity is resolved only by official REPD Ref;
// URL names and coordinates are never used to manufacture a match.
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'
]);
if (!allowedTechnologies.has(requestedTechnology)) throw new Error('canonical project technology is invalid');
/* This legacy receiver owns only the four partitioned spine
products below. The exact-REPD search cartridge owns every
other canonical technology. Treating those values as invalid
made every wider-fleet MAP link throw before the coordinate
receiver could answer; defer them without fetching all spine
partitions or manufacturing a false match. */
const partitionTechnologies = new Set([
'solar', 'bess', 'wind_onshore', 'wind_offshore'
]);
if (!partitionTechnologies.has(requestedTechnology)) {
window.__GRIDATLAS_V8_DEEP_LINK__ = {
status: 'DEFERRED_TO_EXACT_REPD_RECEIVER',
repd_ref: repdRef,
technology: requestedTechnology
};
return;
}
const manifestResponse = await fetch('/uk_renewables_pipeline/v9/data/v9.1/build_manifest.json', { cache: 'no-store' });
if (!manifestResponse.ok) throw new Error(`canonical manifest HTTP ${manifestResponse.status}`);
const manifest = await manifestResponse.json();
const partitions = Array.isArray(manifest.atlas_partitions)
? manifest.atlas_partitions.filter(item => item.technology === requestedTechnology)
: [];
if (!partitions.length) throw new Error(`no canonical ${requestedTechnology} partitions`);
const payloads = await Promise.all(partitions.map(async item => {
const response = await fetch(`/uk_renewables_pipeline/v9/${item.path}`, { cache: 'no-store' });
if (!response.ok) throw new Error(`canonical project HTTP ${response.status}`);
return response.json();
}));
const feature = payloads.flatMap(payload => Array.isArray(payload.features) ? payload.features : [])
.find(item => String(item?.properties?.repd_ref || '') === repdRef);
if (!feature || feature?.geometry?.type !== 'Point') throw new Error(`REPD Ref ${repdRef} not found`);
const p = feature.properties || {};
const technology = p.technology === 'bess' ? 'bess' : (p.technology.startsWith('wind_') ? 'wind' : 'solar');
const atlasFeature = {
type: 'Feature',
geometry: feature.geometry,
properties: {
name: p.name,
capacity: p.capacity_mw,
raw_tech: p.repd_technology,
tech: technology,
status: p.status,
operator: p.operator,
repd_ref: p.repd_ref
}
};
if (!map.getSource('src-v9-deep-link')) {
map.addSource('src-v9-deep-link', { type: 'geojson', data: atlasFeature });
map.addLayer({
id: 'l-v9-deep-link', type: 'circle', source: 'src-v9-deep-link',
paint: { 'circle-color': '#00ffff', 'circle-radius': 12, 'circle-stroke-width': 4, 'circle-stroke-color': '#000' }
});
} else {
map.getSource('src-v9-deep-link').setData(atlasFeature);
}
const checkbox = document.querySelector(`input[data-layer-id="${technology}"]`);
if (checkbox && !checkbox.checked) { checkbox.checked = true; handleLayerToggle(technology, true); }
flyToProject(atlasFeature);
} 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';
}
// ── Export ────────────────────────────────────────────────────────────────────
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); }
}
// ── Status / Radius ───────────────────────────────────────────────────────────
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>`);
}
// ── DOM Builder ───────────────────────────────────────────────────────────────
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 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);
});
}
}
// ── Layer Hydration ───────────────────────────────────────────────────────────
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}`;
}
/* A successful fetch is not proof that a layer can draw a feature.
------------------------------------------------------------------
The deployed metro/tram partition is made entirely of LineStrings,
while the inherited V8 transit layers are MapLibre circle layers. The
old path called every sibling [OK] as soon as their shared source had
bytes, leaving checked switches which could never paint anything.
Evaluate only the small expression vocabulary used by these transit
filters. An unknown expression deliberately returns true: it must not
be used as evidence for disabling a control. Geometry compatibility is
checked against the layer MapLibre actually created, not the friendly
`point`/`line` name in the configuration.
*/
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;
}
function transitFilterMatches(filter, feature) {
if (!Array.isArray(filter) || filter.length === 0) return true;
const operator = filter[0];
if (operator === 'all') return filter.slice(1).every(item => transitFilterMatches(item, feature));
if (operator === 'any') return filter.slice(1).some(item => transitFilterMatches(item, feature));
if (operator === '!') return !transitFilterMatches(filter[1], feature);
if (operator === '==') return transitExpressionValue(filter[1], feature) === transitExpressionValue(filter[2], feature);
if (operator === '!=') return transitExpressionValue(filter[1], feature) !== transitExpressionValue(filter[2], feature);
if (operator === 'in' || operator === '!in') {
const needle = transitExpressionValue(filter[1], feature);
const haystack = transitExpressionValue(filter[2], feature);
const contains = typeof haystack === 'string'
? haystack.includes(String(needle))
: Array.isArray(haystack) && haystack.includes(needle);
return operator === 'in' ? contains : !contains;
}
return true;
}
function geometryFitsMapLayer(layerType, geometryType) {
if (layerType === 'circle' || layerType === 'heatmap') return geometryType === 'Point' || geometryType === 'MultiPoint';
if (layerType === 'line') return geometryType === 'LineString' || geometryType === 'MultiLineString';
if (layerType === 'fill' || layerType === 'fill-extrusion') return geometryType === 'Polygon' || geometryType === 'MultiPolygon';
return true;
}
function countTransitFeaturesLayerCanDraw(layerId, features) {
const layerConfig = getLayerConfig(layerId);
const mapLayer = map.getLayer(`l-${layerId}`);
if (!layerConfig || !mapLayer) return 0;
return features.reduce((count, feature) => {
const geometryType = feature && feature.geometry && feature.geometry.type;
if (!geometryFitsMapLayer(mapLayer.type, geometryType)) return count;
return transitFilterMatches(layerConfig.filter, feature) ? count + 1 : count;
}, 0);
}
function setLayerControlAvailability(layerId, available) {
document.querySelectorAll(`input[data-layer-id="${layerId}"]`).forEach(input => {
input.disabled = !available;
if (!available) input.checked = false;
});
if (available) return;
[`l-${layerId}`, `l-${layerId}-glow`].forEach(mapLayerId => {
if (map.getLayer(mapLayerId)) map.setLayoutProperty(mapLayerId, 'visibility', 'none');
});
const mapLayerId = `l-${layerId}`;
_visibleInteractiveIds = _visibleInteractiveIds.filter(id => id !== mapLayerId);
_visibleHoverIds = _visibleHoverIds.filter(id => id !== mapLayerId);
}
function updateTransitSourceStates(sourceId, features) {
TRANSIT_IDS.forEach(transitId => {
if (TRANSIT_SOURCE_MAP[transitId] !== sourceId || !RUNTIME_STATE[transitId]) return;
const available = countTransitFeaturesLayerCanDraw(transitId, features) > 0;
RUNTIME_STATE[transitId].loaded = true;
RUNTIME_STATE[transitId].loading = false;
setLayerControlAvailability(transitId, available);
updateUIState(transitId, available ? 'OK' : 'EMPTY');
});
}
async function hydrateLayer(layerId) {
const state = RUNTIME_STATE[layerId];
if (!state || state.loaded || state.loading) return;
state.loading = true; updateUIState(layerId, 'LOAD');
const layerConfig = getLayerConfig(layerId);
if (!layerConfig) { updateUIState(layerId, 'FAIL'); state.loading = false; return; }
await networkQueue.add(async () => {
try {
let features = await fetchAndParseGeoJSON(layerConfig.url);
if (features.length === 0) {
if (TRANSIT_IDS.includes(layerId)) updateTransitSourceStates(TRANSIT_SOURCE_MAP[layerId], features);
else { state.loaded = true; state.loading = false; updateUIState(layerId, 'EMPTY'); }
return;
}
if (layerConfig.isSubs) globalSubsData = features;
if (layerConfig.snap) {
if (!globalSubsData) { const subsLayer = getLayerConfig('subs'); globalSubsData = await fetchAndParseGeoJSON(subsLayer.url); }
console.warn(`[SNAP] Runtime snapping active for "${layerId}" — ${features.length} features. Move to build pipeline when possible.`);
features = snapLines(features, globalSubsData);
}
const sourceId = getSourceIdForLayer(layerId);
const source = map.getSource(sourceId);
if (!source) { console.error(`[SOURCE MISSING] ${sourceId}`); updateUIState(layerId, 'FAIL'); state.loading = false; return; }
source.setData({ type: 'FeatureCollection', features });
state.loaded = true; state.loading = false;
if (REPD_IDS.includes(layerId)) {
allREPDFeatures = features; buildSearchIndex();
function evalFilter(filter, props) {
if (!filter) return true;
const op = filter[0];
if (op === '==') { const v = filter[1][0] === 'get' ? props[filter[1][1]] : null; return String(v).toLowerCase() === String(filter[2]).toLowerCase(); }
if (op === 'all') { return filter.slice(1).every(f => evalFilter(f, props)); }
if (op === '>=') { const v = filter[1][0] === 'coalesce' ? (parseFloat(props[filter[1][1][1]]) || 0) : 0; return v >= filter[2]; }
return true;
}
REPD_IDS.forEach(id => {
if (!RUNTIME_STATE[id]) return;
RUNTIME_STATE[id].loaded = true; RUNTIME_STATE[id].loading = false;
const lCfg = getLayerConfig(id);
const filtered = lCfg && lCfg.filter ? features.filter(f => evalFilter(lCfg.filter, f.properties)) : features.filter(f => f.properties.tech === id);
const idStats = filtered.reduce((acc, f) => {
acc.count++;
acc.mw += parseFloat(f.properties.capacity) || 0;
return acc;
}, { count: 0, mw: 0 });
updateUIState(id, idStats.count > 0 ? 'OK' : 'EMPTY', idStats.count > 0 ? idStats : null);
});
if (statusMode) { toggleStatusMode(); toggleStatusMode(); }
} else if (layerId === 'naei_co2') {
const stats = features.reduce((acc, f) => {
acc.count++;
acc.mw += parseFloat(f.properties.emission_tco2e) || 0;
return acc;
}, { count: 0, mw: 0 });
updateUIState(layerId, stats.count > 0 ? 'OK' : 'EMPTY', stats.count > 0 ? stats : null);
} else if (TRANSIT_IDS.includes(layerId)) {
updateTransitSourceStates(TRANSIT_SOURCE_MAP[layerId], features);
} else {
updateUIState(layerId, 'OK');
}
} catch (err) { console.error(`[LAYER FAILED] ${layerId}:`, err); state.loading = false; updateUIState(layerId, 'FAIL'); }
});
}
// ── Map Load ──────────────────────────────────────────────────────────────────
map.on('load', () => {
buildDOM();
map.addSource('sat-s', { type: 'raster', tiles: ['https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}'], tileSize: 256 });
map.addLayer({ id: 'l-sat', type: 'raster', source: 'sat-s', layout: { visibility: 'none' } });
map.addSource('src-radius-circle', { type: 'geojson', data: { type: 'FeatureCollection', features: [] } });
map.addLayer({ id: 'l-radius-circle-fill', type: 'fill', source: 'src-radius-circle', paint: { 'fill-color': '#00ffff', 'fill-opacity': 0.04 } });
map.addLayer({ id: 'l-radius-circle-stroke', type: 'line', source: 'src-radius-circle', paint: { 'line-color': '#00ffff', 'line-width': 1.5, 'line-opacity': 0.7, 'line-dasharray': [4, 3] } });
map.addSource('src-radius-area', { type: 'geojson', data: { type: 'FeatureCollection', features: [] } });
map.addLayer({ id: 'l-radius-area-fill', type: 'fill', source: 'src-radius-area', paint: { 'fill-color': '#ff00ff', 'fill-opacity': 0.08 } });
map.addLayer({ id: 'l-radius-area-stroke', type: 'line', source: 'src-radius-area', paint: { 'line-color': '#ff00ff', 'line-width': 1.5, 'line-opacity': 0.8, 'line-dasharray': [2, 2] } });
map.addSource('src-measure-line', { type: 'geojson', data: { type: 'FeatureCollection', features: [] } });
map.addSource('src-measure-fill', { type: 'geojson', data: { type: 'FeatureCollection', features: [] } });
map.addSource('src-measure-points', { type: 'geojson', data: { type: 'FeatureCollection', features: [] } });
map.addLayer({ id: 'l-measure-fill', type: 'fill', source: 'src-measure-fill', paint: { 'fill-color': '#ffff00', 'fill-opacity': 0.08 } });
map.addLayer({ id: 'l-measure-line', type: 'line', source: 'src-measure-line', paint: { 'line-color': '#ffff00', 'line-width': 2, 'line-dasharray': [3, 2] } });
map.addLayer({ id: 'l-measure-points', type: 'circle', source: 'src-measure-points', paint: { 'circle-color': '#ffff00', 'circle-radius': 5, 'circle-stroke-width': 1.5, 'circle-stroke-color': '#000' } });
// ── Zone Draw layers (orange accent) ──────────────────────────────────────
map.addSource('src-zonedraw-fill', { type: 'geojson', data: { type: 'FeatureCollection', features: [] } });
map.addSource('src-zonedraw-line', { type: 'geojson', data: { type: 'FeatureCollection', features: [] } });
map.addSource('src-zonedraw-points', { type: 'geojson', data: { type: 'FeatureCollection', features: [] } });
map.addLayer({ id: 'l-zonedraw-fill', type: 'fill', source: 'src-zonedraw-fill', paint: { 'fill-color': '#ff6600', 'fill-opacity': 0.18 } });
map.addLayer({ id: 'l-zonedraw-line', type: 'line', source: 'src-zonedraw-line', paint: { 'line-color': '#ff6600', 'line-width': 3, 'line-dasharray': [4, 2] } });
map.addLayer({ id: 'l-zonedraw-points', type: 'circle', source: 'src-zonedraw-points', paint: {
'circle-color': ['case', ['==', ['get', 'kind'], 'vertex'], '#ff6600', '#ffaa44'],
'circle-radius': ['case', ['==', ['get', 'kind'], 'vertex'], 9, 6],
'circle-stroke-width': 2, 'circle-stroke-color': '#000',
'circle-opacity': ['case', ['==', ['get', 'kind'], 'vertex'], 1, 0.85]
} });
const allLayerIds = [];
GRID_CONFIG.forEach(group => {
group.layers.forEach(layer => {
if (REPD_IDS.includes(layer.id) || TRANSIT_IDS.includes(layer.id) || layer.id === 'ev' || layer.id === 'naei_co2') return;
if (layer.id === '400') {
map.addSource('src-400', {
type: 'geojson',
data: '../cartridges/5f5fbec83f9ce307b47ddc6e7277743f0bba1a2445b0f3ca50a9a1806146e993/grid_400kv.geojson'
});
} else {
map.addSource(`src-${layer.id}`, { type: 'geojson', data: { type: 'FeatureCollection', features: [] } });
}
const layerObject = {
id: `l-${layer.id}`, type: layer.type === 'line' ? 'line' : 'circle', source: `src-${layer.id}`, layout: { visibility: 'none' },
paint: layer.type === 'line' ? { 'line-color': layer.color, 'line-width': layer.width } : { 'circle-color': layer.color, 'circle-radius': layer.radius, 'circle-stroke-width': 1, 'circle-stroke-color': '#000' }
};
if (layer.filter) layerObject.filter = layer.filter; if (layer.minzoom) layerObject.minzoom = layer.minzoom;
map.addLayer(layerObject); allLayerIds.push(`l-${layer.id}`);
});
});
// ── Heavy Industry (Custom VIP styling) ──
map.addSource('src-naei_co2', { type: 'geojson', data: { type: 'FeatureCollection', features: [] } });
map.addLayer({
id: `l-naei_co2-glow`,
type: 'circle',
source: 'src-naei_co2',
filter: ['>=', ['coalesce', ['get', 'emission_tco2e'], 0], 50000],
layout: { visibility: 'none' },
paint: {
'circle-color': ['interpolate',['linear'],['coalesce',['get','emission_tco2e'],0],50000,'#ffaa00',200000,'#ff6600',1000000,'#ff0000'],
'circle-radius': ['interpolate',['linear'],['coalesce',['get','emission_tco2e'],0],50000,20,200000,40,1000000,60,5000000,90],
'circle-opacity': ['interpolate',['linear'],['coalesce',['get','emission_tco2e'],0],50000,0.15,200000,0.25,1000000,0.35],
'circle-blur': 1.0,
'circle-stroke-width': 0
}
});
map.addLayer({
id: 'l-naei_co2',
type: 'circle',
source: 'src-naei_co2',
layout: { visibility: 'none' },
paint: {
'circle-color': ['interpolate',['linear'],['coalesce',['get','emission_tco2e'],0],0,'#ffcc00',50000,'#ffaa00',200000,'#ff6600',1000000,'#ff0000'],
'circle-radius': ['interpolate',['linear'],['coalesce',['get','emission_tco2e'],0],0,6,50000,10,200000,14,1000000,20,5000000,28],
'circle-stroke-width': 1.5,
'circle-stroke-color': '#000',
'circle-opacity': 0.85
}
});
allLayerIds.push('l-naei_co2-glow', 'l-naei_co2');
Object.keys(TRANSIT_URLS).forEach(sourceId => { map.addSource(sourceId, { type: 'geojson', data: { type: 'FeatureCollection', features: [] } }); });
TRANSIT_IDS.forEach(id => {
const layer = getLayerConfig(id);
const layerObject = {
id: `l-${id}`, type: 'circle', source: TRANSIT_SOURCE_MAP[id], layout: { visibility: 'none' },
paint: { 'circle-color': layer.color, 'circle-radius': layer.radius, 'circle-stroke-width': 1, 'circle-stroke-color': '#000', 'circle-opacity': 0.9 }
};
if (layer.filter) layerObject.filter = layer.filter; if (layer.minzoom) layerObject.minzoom = layer.minzoom;
map.addLayer(layerObject); allLayerIds.push(`l-${id}`);