In this section
- Single-Line Diagram (SLD) Sandbox Technology Buckets geodesy · gridatlas / atlas/parts/202609041234-sld-sandbox-technology-buckets.js lines 5509–5885
Single-Line Diagram (SLD) Sandbox Technology Buckets
A JavaScript file in the parts folder of GridAtlas that maps grid substations, solar, wind and transformers, using haversine.
geodesygridatlas / atlas/parts/202609041234-sld-sandbox-technology-buckets.js · lines 5509–5885 of 5885 · version 2026-09-04 12:34 (continued from section 436) · pattern coarse (shared by 6 files)
- What it does
- It maps grid substations, solar, wind and transformers. Defines 191 functions or classes, including coverage, isProjectTech, layerIdForBucket, provisionalDeclaredConnection, resolveDeclaredConnection. 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: solar, wind, transformers, 750kV, 415kV, 400kV.
- Inputs & outputs
- In: GeoJSON file grid_substations.geojson; browser storage (getItem); DuckDB queries; form fields (user input). Out: browser storage (setItem); interactive map. Coordinate systems named: WGS84 / EPSG:4326. Voltage levels named: 750kV, 415kV, 400kV, 275kV, 220kV, 132kV, 66kV, 33kV.
- Downstream impact
- Used directly by 2 files: Build Graph (ventus-grid-engine, https://ventusltd.github.io/ventus-grid-engine/genome/); Ventus Grid Engine — Genome Page (ventus-grid-engine, https://ventusltd.github.io/ventus-grid-engine/genome/). Reached from 1 other entry point, including Genome Workflow (ventus-grid-engine).
- What it achieves
- It resolves declared connection (`resolveDeclaredConnection`), opens corridor sheet (`openCorridorSheet`) and runs grid point (`runGridAtPoint`). GridAtlas cartridge — neon substation links and the SLD layout sandbox. Its code works with 400 kV, 33 kV and 132 kV. It responds to click, keydown and touchstart events.
- Why it matters
- Loaded by the Genome page in Ventus Grid Engine at https://ventusltd.github.io/ventus-grid-engine/genome/. Also imported by Build Graph, from Ventus Grid Engine.
- Application
- gridatlas · atlas/parts · script
- VEDIC
- MEASURE (GG2050-VEDIC-000001): GridAtlas / Geodesy · Mathematics / Spherical geometry. coordinate_pair, coordinate_pair → distance_km
- VEDIC
- VOLTAGE (GG2050-VEDIC-000003): GridAtlas / Geodesy · Computer science / Data normalisation. voltage_properties → kilovolt_list
- VEDIC
- REPRESENT (GG2050-VEDIC-000002): GridAtlas / Geodesy · Computer science / Geometry processing. geojson_geometry → coordinate_pair_or_null
- Uses
- none found
- Used by
- named by URL in Build Graph (estate URL), named by URL in Ventus Grid Engine — Genome Page (estate URL)
- Produces
- coverage, isProjectTech, layerIdForBucket, provisionalDeclaredConnection, resolveDeclaredConnection, nearestTransmission, corridorBeside, module, corridorTargets, corridorAction, installCorridorSheet, close
- Defines here
- moneyText, renderSldPanel, finish, closeSld, openSldAt, openSldFromProject, keepLayersInFullscreen, onChange, installSld
- 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/202609041234-sld-sandbox-technology-buckets.js:5509-5885 · blob adc00df9e0bc8a73f1c4f5a040f532ebe0a51398 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, network, storage · domain stage: experimental · users: none · canonical: production_core
if (key === '@') return `<div class="sld-fin-section">${escapeHtml(label)}</div>`;
if (kind === 'checkbox') {
return `<label for="sld_fin_${key}">${escapeHtml(label)}</label>`
+ `<input id="sld_fin_${key}" data-fin-key="${key}" type="checkbox" ${values[key] ? 'checked' : ''}>`;
}
if (kind === 'stage') {
const options = Object.entries(DEVELOPMENT_STAGES).map(([value, text]) =>
`<option value="${value}" ${String(values[key]) === value ? 'selected' : ''}>${escapeHtml(text)}</option>`
).join('');
return `<label for="sld_fin_${key}">${escapeHtml(label)}</label>`
+ `<select id="sld_fin_${key}" data-fin-key="${key}">${options}</select>`;
}
const maximum = key === 'bess_eff' || key === 'dev_success' ? ' max="100"' : '';
return `<label for="sld_fin_${key}">${escapeHtml(label)}</label>`
+ `<input id="sld_fin_${key}" data-fin-key="${key}" type="number" min="0"${maximum} step="any" value="${values[key]}">`;
};
const moneyText = value => `GBP ${Math.round(financeNumber(value)).toLocaleString('en-GB')}`;
function renderSldPanel() {
const el = sldPanel();
const s = sld.stats;
const fields = sld.inputs.mode === 'string' ? FIELDS_STRING : FIELDS_CENTRAL;
const financeInputs = sld.finance[sld.inputs.mode];
const finance = s?.finance;
const detour = sld.straightKm > 0 ? sld.cableKm / sld.straightKm : 1;
const acres = s ? s.gross_site_area_m2 / SLD.M2_PER_ACRE : 0;
el.innerHTML = `
<h4 class="sld-drag">Layout sandbox<span class="sld-beta">Beta</span>
<button class="sld-min" title="Minimise">−</button>
<button class="sld-close" title="Close">×</button></h4>
<div class="sld-site">${escapeHtml(sld.projectName || sld.gridNodeName || 'Grid node')}</div>
${sld.projectName ? `<div class="sld-to">to ${escapeHtml(sld.gridNodeName || 'grid node')}`
+ `${sld.gridNodeVoltage ? ` · ${escapeHtml(sld.gridNodeVoltage)}` : ''}</div>` : ''}
<div class="sld-tabs">
<button data-mode="string" data-on="${sld.inputs.mode === 'string'}">String</button>
<button data-mode="central" data-on="${sld.inputs.mode === 'central'}">Central</button>
</div>
${sld.targetMw ? `
<div class="sld-target">
<div class="sld-target-row"><span>Register states</span><b>${sld.targetMw} MW</b></div>
<div class="sld-basis">
<span>That figure is</span>
<select id="sld_basis">
<option value="unstated" ${sld.targetBasis === 'unstated' ? 'selected' : ''}>not stated</option>
<option value="ac" ${sld.targetBasis === 'ac' ? 'selected' : ''}>AC export MW</option>
<option value="dc" ${sld.targetBasis === 'dc' ? 'selected' : ''}>DC MWp</option>
</select>
</div>
${sld.targetBasis === 'unstated'
? `<div class="sld-danger">REPD does not reliably distinguish AC from DC.
Its figure is nominally MWelec, but schemes report it both ways and the
register does not carry the distinction. Nothing is fitted until you say
which this is: matching AC when the figure was DC oversizes the
connection by the DC/AC ratio, and that is the error that drives export
limitation, curtailment and the size of the offer.</div>`
: `<div class="sld-fitted">Fitted to ${sld.targetBasis === 'ac' ? 'AC export' : 'DC'} by
${sld.inputs.mode === 'string' ? 'ring main circuits' : 'rings'}
${sld.fitResidualPct != null
? `· <b class="${Math.abs(sld.fitResidualPct) > 5 ? 'sld-off' : ''}">${sld.fitResidualPct >= 0 ? '+' : ''}${sld.fitResidualPct.toFixed(1)}%</b> against the stated figure`
: ''}.
Ratings, string length and module choice are untouched.</div>`}
</div>` : ''}
<div class="sld-grid">
${fields.map(([key, label]) =>
`<label for="sld_${key}">${label}</label>`
+ `<input id="sld_${key}" data-key="${key}" type="number" ${electricalInputAttributes(key)} value="${sld.inputs[key]}">`
).join('')}
</div>
<div class="sld-out">
<span>Array DC</span><b>${s ? s.dc_mwp.toFixed(1) : '0.0'} MWp</b>
<span>Inverter AC</span><b>${s?.consistency?.inverter_ac_mw != null
? s.consistency.inverter_ac_mw.toFixed(1) : '0.0'} MW</b>
<span>Export limit</span><b>${s?.consistency?.export_mva != null
? s.consistency.export_mva.toFixed(1) : '0.0'} MVA</b>
<span>Design DC/AC</span><b>${s?.consistency?.design_dc_ac != null
? s.consistency.design_dc_ac.toFixed(2) : '0.00'}</b>
<span>DC / export</span><b>${s?.consistency?.export_dc_ac != null
? s.consistency.export_dc_ac.toFixed(2) : '0.00'}</b>
<span>Inverter / export</span><b>${s?.consistency?.inverter_to_export != null
? s.consistency.inverter_to_export.toFixed(2) : '0.00'}</b>
<span>Modules</span><b>${s ? s.module_count.toLocaleString('en-GB') : '0'}</b>
<span>Blocks</span><b>${s ? s.total_blocks : 0}</b>
<span>Gross site</span><b>${acres.toFixed(0)} acres</b>
<span>Ring main</span><b>${s ? s.ring_main_ac_mva.toFixed(2) : '0.00'} MVA</b>
<span class="lit">Export cable</span><b class="lit">${sld.cableKm.toFixed(3)} km</b>
<span>Straight line</span><b>${sld.straightKm.toFixed(3)} km</b>
<span>Detour factor</span><b>${detour.toFixed(2)}×</b>
<span>Route vertices</span><b>${sld.routePins.length}</b>
<span>Rotation</span><b>${normBearing(sld.rotationDeg).toFixed(0)}°</b>
</div>
${(() => {
const c = s?.consistency;
if (!(c?.stated_dc_ac > 0) || !(c?.design_dc_ac > 0)) return '';
if (Math.abs(c.design_dc_ac - c.stated_dc_ac) / c.stated_dc_ac <= 0.05) return '';
return `<div class="sld-ratio-note">Entered DC/AC ${c.stated_dc_ac.toFixed(2)}; `
+ `the equipment counts and ratings shown give ${c.design_dc_ac.toFixed(2)}. `
+ `Both values remain visible and no input is changed automatically.</div>`;
})()}
${s && s.warning ? `<div class="sld-warn">${escapeHtml(s.warning)}</div>` : ''}
<details class="sld-finance" ${sld.financeOpen ? 'open' : ''}>
<summary>Financial screening inputs and outputs</summary>
<div class="sld-fin-out">
<span>Year 1 revenue</span><b>${moneyText(finance?.annualRevenue)}</b>
<span>25-year revenue</span><b>${moneyText(finance?.revenue25)}</b>
<span>35-year revenue</span><b>${moneyText(finance?.revenue35)}</b>
<span>Total CAPEX</span><b>${moneyText(finance?.totalCapex)}</b>
<span>CAPEX / Wp</span><b>GBP ${financeNumber(finance?.capexPerWp).toFixed(2)}</b>
<span>25-year surplus</span><b>${moneyText(finance?.surplus25)}</b>
<span>35-year surplus</span><b>${moneyText(finance?.surplus35)}</b>
<span>Development capital at risk</span><b>${moneyText(finance?.devCapitalAtRisk)}</b>
<span>Total build cost</span><b>${moneyText(finance?.devTotalBuildCost)}</b>
<span>Target exit value</span><b>${moneyText(finance?.devExitValue)}</b>
<span>Operating NPV</span><b>${moneyText(finance?.devOperatingNpv)}</b>
<span>Gross development margin</span><b>${moneyText(finance?.devGrossMargin)}</b>
<span>Risk-adjusted value</span><b>${moneyText(finance?.devRiskAdjustedValue)}</b>
<span>Equity money multiple</span><b>${financeNumber(finance?.devReturnMultiple).toFixed(2)}x</b>
</div>
<div class="sld-fin-grid">${FINANCE_FIELDS.map(field => financeFieldHtml(field, financeInputs)).join('')}</div>
<div class="sld-fin-note"><b>Screening values only, not financial advice.</b> Revenue, CAPEX,
OPEX, development value and BESS outputs depend entirely on the visible assumptions. They do
not replace project-specific yield, degradation, route-to-market, tax, debt, grid, EPC,
insurance, degradation, augmentation or investment-committee models.</div>
</details>
<div class="sld-hint">Drag the site to move it. Drag the handle to rotate. Click the
cable to add a vertex, drag a vertex to shape the route, double-click one to remove it.</div>
<div class="sld-caveat"><b>Beta analytics, not an actual grid connection.</b> A layout, not
a design. Every length is straight-line between the points shown, with no wayleave,
easement, right of way, crossing, terrain, ground condition or consent content, and no
route has been walked. A real connection depends on factors that must be studied:
network impedance and fault level, thermal headroom, existing committed connections and
queue position, and land control. A mapped substation does not confirm capacity, voltage
suitability or acceptance by any network party.</div>`;
el.dataset.open = 'true';
// Optional throughout: a panel that cannot find its own controls must not
// take the layout down with it. The geometry is the product; the panel is
// how it is driven.
el.querySelector?.('.sld-close')?.addEventListener('click', closeSld);
el.querySelector?.('.sld-min')?.addEventListener('click', () => {
const min = el.dataset.min === 'true';
el.dataset.min = min ? 'false' : 'true';
const button = el.querySelector('.sld-min');
if (button) button.innerHTML = min ? '−' : '+';
});
// The panel is draggable by its heading for the same reason the card is:
// on a map, anything fixed in a corner is eventually in the way.
const heading = el.querySelector?.('h4.sld-drag');
if (heading && !heading.dataset.bound) {
heading.dataset.bound = '1';
let drag = null;
heading.addEventListener('pointerdown', (event) => {
if (event.target.closest('button')) return;
event.preventDefault();
const rect = el.getBoundingClientRect();
drag = {
pointerId: event.pointerId,
dx: event.clientX - rect.left,
dy: event.clientY - rect.top,
};
heading.setPointerCapture?.(event.pointerId);
el.style.right = 'auto';
el.style.bottom = 'auto';
el.style.left = rect.left + 'px';
el.style.top = rect.top + 'px';
const map = capturedMap?.getContainer()?.getBoundingClientRect();
if (map) el.style.maxHeight = Math.max(120, map.bottom - rect.top - 8) + 'px';
});
heading.addEventListener('pointermove', (event) => {
if (!drag || event.pointerId !== drag.pointerId) return;
event.preventDefault();
const map = capturedMap?.getContainer()?.getBoundingClientRect()
|| { left: 0, top: 0, right: window.innerWidth, bottom: window.innerHeight };
const panel = el.getBoundingClientRect();
const minX = map.left + 4;
const maxX = Math.max(minX, map.right - panel.width - 4);
const minY = map.top + 4;
const maxY = Math.max(minY, map.bottom - 44 - 4);
const left = Math.max(minX, Math.min(maxX, event.clientX - drag.dx));
const top = Math.max(minY, Math.min(maxY, event.clientY - drag.dy));
el.style.left = left + 'px';
el.style.top = top + 'px';
el.style.maxHeight = Math.max(120, map.bottom - top - 8) + 'px';
});
const finish = (event) => {
if (!drag || event.pointerId !== drag.pointerId) return;
try { heading.releasePointerCapture?.(event.pointerId); } catch (_) { /* already released */ }
drag = null;
};
heading.addEventListener('pointerup', finish);
heading.addEventListener('pointercancel', finish);
}
(el.querySelectorAll?.('.sld-tabs button') || []).forEach(button => {
button.addEventListener('click', () => {
sld.inputs.mode = button.dataset.mode;
if (capturedMap) redrawSld(capturedMap);
});
});
el.querySelector?.('#sld_basis')?.addEventListener('change', (event) => {
sld.targetBasis = event.target.value;
fitToStatedCapacity();
if (capturedMap) redrawSld(capturedMap, { fit: true });
});
el.querySelector?.('details.sld-finance')?.addEventListener('toggle', (event) => {
sld.financeOpen = Boolean(event.currentTarget.open);
});
(el.querySelectorAll?.('[data-fin-key]') || []).forEach(input => {
input.addEventListener('change', () => {
const values = sld.finance[sld.inputs.mode];
if (input.type === 'checkbox') values[input.dataset.finKey] = Boolean(input.checked);
else if (input.dataset.finKey === 'dev_stage') {
applyDevelopmentStageDefaults(values, input.value);
} else if (input.tagName === 'SELECT') values[input.dataset.finKey] = input.value;
else {
const value = Number(input.value);
if (Number.isFinite(value)) values[input.dataset.finKey] = value;
}
if (capturedMap) redrawSld(capturedMap);
});
});
(el.querySelectorAll?.('input[data-key]') || []).forEach(input => {
input.addEventListener('change', () => {
const key = input.dataset.key;
const value = normalizeElectricalInput(key, input.value);
if (value == null) {
input.value = String(sld.inputs[key]);
return;
}
sld.inputs[key] = value;
if (key === 'gcr' || key === 'gcr_c') {
applyMountingBifacial(sld.inputs.mode, value);
}
// Editing by hand wins. Re-fitting here would silently undo the change
// the user just made; the residual simply moves and says so.
if (sld.targetBasis === 'ac' || sld.targetBasis === 'dc') {
const s = computeSldStats();
const got = sld.targetBasis === 'ac' ? s.ac_mw : s.dc_mwp;
sld.fitResidualPct = sld.targetMw > 0
? ((got - sld.targetMw) / sld.targetMw) * 100 : null;
}
if (capturedMap) redrawSld(capturedMap);
});
});
}
function closeSld() {
sld.active = false;
sld.projectName = null;
sld.routePins = [];
sld.arrayCentre = null;
sld.rotationDeg = 0;
if (sldFlowHandle !== null) { cancelAnimationFrame(sldFlowHandle); sldFlowHandle = null; }
const el = document.getElementById(PANEL_ID);
if (el) el.dataset.open = 'false';
if (capturedMap && capturedMap.getSource(SRC_SLD)) {
setSourceData(capturedMap, SRC_SLD, { type: 'FeatureCollection', features: [] });
}
}
// Opened from the substation card the neon links already produce, so the
// sandbox is one click from the thing it connects to.
function openSldAt(map, gridNode, name, voltage) {
sld.active = true;
sld.projectName = null;
sld.targetMw = null;
sld.targetBasis = 'unstated';
sld.fitResidualPct = null;
sld.gridNode = gridNode;
sld.gridNodeName = name;
sld.gridNodeVoltage = voltage;
sld.arrayCentre = null;
sld.rotationDeg = 0;
sld.routePins = [];
redrawSld(map, { fit: true });
}
sld.openAt = openSldAt;
// Opened from a project card. The scheme sits at the project and the export
// cable runs to the nearest substation the links already found, which is the
// order a scheme is actually built: generation first, then the route to the
// network. Falls back to the project's own point if nothing was in range, so
// the button never does nothing.
function openSldFromProject(map, selection) {
const nearest = selection.links && selection.links[0];
if (!nearest) {
sld.active = false;
link.failures.push('layout: no substation within '
+ `${MAX_LINK_KM} km of ${selection.name}`);
return;
}
sld.active = true;
sld.gridNode = nearest.at;
sld.gridNodeName = nearest.name || 'Grid node';
sld.gridNodeVoltage = nearest.kv && nearest.kv.length ? `${nearest.kv[0]} kV` : '';
sld.projectName = selection.name;
sld.targetMw = selection.statedMw || null;
// Unstated until the user says. The register's figure is not self-describing
// and the layout must not pretend otherwise.
sld.targetBasis = 'unstated';
// The array starts on the project, not offset from the substation, because
// the project is the thing that exists.
sld.arrayCentre = selection.origin;
sld.rotationDeg = initialBearingDeg(
nearest.at[0], nearest.at[1], selection.origin[0], selection.origin[1]);
sld.routePins = [];
enableSubstationLayer();
redrawSld(map, { fit: true });
}
sld.openFromProject = openSldFromProject;
/**
* Keep the layer controls reachable in fullscreen.
*
* The shell fullscreens the map element alone, so on desktop every layer
* checkbox -- the whole dashboard below the map -- vanishes the moment you
* maximise, and there is no way to turn anything on until you come back out.
* Mobile carries its own drop-down curtain inside #map-container. When that
* container is already fullscreen, moving its dashboard ancestor into it
* would create a DOM cycle and throw HierarchyRequestError.
*
* The dashboard node is MOVED into the fullscreen element and moved back on
* exit, rather than cloned. A clone would look right and do nothing, because
* every checkbox listener belongs to the original.
*/
function keepLayersInFullscreen() {
const dashboard = document.getElementById('dashboard')
|| document.querySelector('.dashboard');
if (!dashboard) { link.failures.push('fullscreen: dashboard not found'); return; }
let home = null;
const onChange = () => {
const full = document.fullscreenElement;
/* Relocate only between disjoint trees. If either element contains the
other, the dashboard is already represented in the fullscreen tree;
appending an ancestor to its descendant is invalid DOM. */
if (full && !full.contains(dashboard) && !dashboard.contains(full)) {
home = { parent: dashboard.parentNode, next: dashboard.nextSibling };
dashboard.classList.add('gridatlas-fs-layers');
full.appendChild(dashboard);
} else if (!full && home) {
dashboard.classList.remove('gridatlas-fs-layers');
home.parent.insertBefore(dashboard, home.next);
home = null;
}
boundCardToMap();
};
document.addEventListener('fullscreenchange', onChange);
document.addEventListener('webkitfullscreenchange', onChange);
const style = document.createElement('style');
style.textContent = SLD_STYLES.fullscreenLayers();
document.head.appendChild(style);
}
function installSld(map) {
installSldStyles();
ensureSldLayers(map);
attachSldDragging(map);
try { keepLayersInFullscreen(); }
catch (error) { link.failures.push('fullscreen: ' + String(error?.message || error)); }
try { armCorridorGestures(map); }
catch (error) { link.failures.push('corridor sheet: ' + String(error?.message || error)); }
// A substation click offers the layout; the neon links still draw.
map.on('click', (event) => {
if (fromOwnUi(event)) return;
if (!map.getLayer(SUBS_LAYER_ID)) return;
const hits = map.queryRenderedFeatures(event.point, { layers: [SUBS_LAYER_ID] });
if (!hits.length) return;
const properties = hits[0].properties || {};
const at = representativePoint(hits[0].geometry);
if (!at) return;
openSldAt(map, at, properties.name || 'Grid node',
(voltagesKv(properties)[0] ? `${voltagesKv(properties)[0]} kV` : ''));
});
}
})();