In this section
- Single-Line Diagram (SLD) Sandbox Body geodesy · gridatlas / atlas/parts/202609012045-sld-sandbox-body.js lines 4619–5318
Single-Line Diagram (SLD) Sandbox Body
A JavaScript file in the parts folder of GridAtlas that maps grid substations, solar, transformers and 400kV, using haversine.
Set aside from the main view: 96% of its lines are the same as atlas/parts/202609040229-sld-sandbox-arrival-identity.js (gridatlas), which stays. (near-copy-of, proposed by families.py). 96% of lines shared with Single-Line Diagram (SLD) Sandbox Arrival Identity; read that one first. All set-aside files, with reasons. Nothing was deleted.
Evidence
- line-jaccard 0.9622 to gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 atlas/parts/202609040229-sld-sandbox-arrival-identity.js:1-5948 2c1486ea5aef879022fc222d4363b779d22e165b
- sha256 4494ff9a6fd9db05b7208e2e420f65705b1eaac919f77995f13ff45c3e9e69b9
- target sha256 7c0d4eb1ef95c845bb8bcbf9fa7020eb009c025ed3edbb34afa0cc085c20b5d5
- group of 2 (identity.json near-copy edges >= 0.9)
- canonical rule: reachable, newest stamp, core repo, most lines
geodesygridatlas / atlas/parts/202609012045-sld-sandbox-body.js · lines 4619–5318 of 5782 · version 2026-09-01 20:45 (continued from section 410) · Not reached from any entry point (candidate for review) · pattern provisionalDeclaredConnection (shared by 9 files)
- What it does
- It maps grid substations, solar, transformers and 400kV. Defines 183 functions or classes, including coverage, isProjectTech, provisionalDeclaredConnection, resolveDeclaredConnection, nearestTransmission. 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, transformers, 400kV, 750kV, 415kV, 275kV.
- 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.
- 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
- No other file in the estate was found to import it.
- 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
- none found
- Produces
- coverage, isProjectTech, provisionalDeclaredConnection, resolveDeclaredConnection, nearestTransmission, corridorBeside, module, corridorTargets, corridorAction, installCorridorSheet, close, openCorridorSheet
- Defines here
- freshFinanceInputs, destinationPoint, initialBearingDeg, pathLengthKm, normBearing, localScaleKm, distanceToSegmentKm, rectPolygon, footOnSegment, activePhysicalInputs, applyDevelopmentStageDefaults, applyMountingBifacial, computeScreeningFinance, computeSldStats, fitToStatedCapacity, buildLayout, push, ensureSldLayers, animateSld, step, redrawSld, walk, attachSldDragging, beginDrag, moveDrag, release, installSldStyles, sldPanel
- 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/202609012045-sld-sandbox-body.js:4619-5318 · blob e1451b1f9330cecde3e94fbe6ad608a6425c028d · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, network, storage · domain stage: experimental · users: none · canonical: unreached_review
link.failures.push(String(error?.message || error));
}
/* ══════════════════════════════════════════════════════════════════════
PART 3 — the SLD sandbox, ported from
globalgrid2050/solar-bess-topology-v7/gis-sld-financial-sandbox.
WHAT CHANGED IN THE PORT, AND WHY
---------------------------------
The sandbox is a working engine and the arithmetic below is its
arithmetic, carried across unchanged. Three things are deliberately
different.
1. ONE EARTH RADIUS. The sandbox measures cable length with
atlasHaversineKm on R = 6378.137 but builds every rectangle, offset
and projection with turf.destination, whose default is 6371.0088. It
therefore mixes two radii inside one drawing: a 0.112% disagreement
between where a thing IS and how far away it is said to be. That is
the exact defect Ventusltd/grid-distance-maths was created to end.
The Atlas ships no turf, so every geometric operation here is the
canonical one on R_ATLAS and the mixture cannot recur.
2. GRAB, DO NOT MODE-SWITCH. The sandbox moves the array by arming a
mode and clicking a destination, and edits a route by dropping pins
and committing them. Here the array is dragged by grabbing it, the
rotation has a handle on its boundary, and route vertices are
dragged, inserted on a segment and removed with a double click.
Everything recomputes live while the pointer is down.
3. THE ELECTRON FLOW CARRIES THROUGH. The travelling pulse used for the
substation links runs along the 33 kV collectors and the export cable
too, in the direction power actually flows: block, to customer
substation, to grid node.
WHAT IT STILL IS NOT
--------------------
A layout, not a design. Straight-line geometry with no wayleave,
crossing, terrain, ground condition or consent content, and no
confirmation that any of it can connect. The caveat block travels with
it.
══════════════════════════════════════════════════════════════════════ */
const SLD = {
M2_PER_ACRE: 4046.86,
BESS_M2_PER_MWH: 85,
BESS_ASPECT: 2.5,
BLOCK_SPACING_KM: 0.01,
BOUNDARY_BUFFER_KM: 0.02,
ARRAY_OFFSET_KM: 0.2
};
const SRC_SLD = 'gridatlas-sld';
const SLD_LAYERS = {
boundary: 'l-sld-boundary',
boundaryLine: 'l-sld-boundary-line',
block: 'l-sld-block',
bess: 'l-sld-bess',
radial: 'l-sld-radial',
radialFlow: 'l-sld-radial-flow',
cable: 'l-sld-cable',
cableGlow: 'l-sld-cable-glow',
cableFlow: 'l-sld-cable-flow',
cableFlowB: 'l-sld-cable-flow-b',
node: 'l-sld-node',
pin: 'l-sld-pin',
handle: 'l-sld-handle',
label: 'l-sld-label'
};
// Muted SCADA, same family as the substation links.
const SLD_COLOUR = {
boundary: '#3f7fbf',
block: '#5fbdc2',
bess: '#b06ac0',
radial: '#6fb582',
cable: '#d9963c',
node: '#e0b050',
pin: '#bfe9ee',
handle: '#d8c96a'
};
/* Financial inputs are kept per topology because that is how the original
sandbox works. These are its post-migration defaults: the old HTML stores
several development values as GBP/MW and migrateFinanceUnitsToWp converts
them to GBP/Wp before the first calculation. Keeping the converted values
here makes the units visible and avoids a hidden one-million multiplier. */
const FINANCE_DEFAULTS = Object.freeze({
price: 65, other: 0, yield: 1000, bifacial: 5, losses: 2, deg: 0.4,
opex: 25000, epc_ex: 0.30, flood: false, flood_rate: 0.03,
modules: 0.15, other_capex: 0.20, fixed_capex: 1500000, cont: 7,
loss_dc_string: 0, loss_lv_dc: 0, loss_lv_ac: 0, loss_tx: 0,
loss_other: 0, bess_mw: 0, bess_mwh: 0, bess_capex: 0,
bess_cycles: 0, bess_spread: 0, bess_eff: 88,
dev_stage: '0.100', dev_cost_mw: 0.1, dev_module_mwp: 0.15,
dev_epc_mw: 0.5, dev_owner_mw: 0.1, dev_grid_mw: 0.1,
dev_exit_mwp: 1.35, dev_npv_mwp: 1.2, dev_success: 15, dev_years: 4,
});
const freshFinanceInputs = () => ({ ...FINANCE_DEFAULTS });
const sld = {
active: false,
gridNode: null, // the substation the scheme connects to
gridNodeName: '',
gridNodeVoltage: '',
arrayCentre: null, // null = derived from the grid node and array size
rotationDeg: 0,
routePins: [], // user vertices between customer substation and grid node
stats: null,
projectName: null,
// The capacity the register states for this project, and what that figure
// is taken to mean. REPD does not reliably distinguish, which is why the
// basis is a user choice and not an assumption.
targetMw: null,
targetBasis: 'unstated',
fitResidualPct: null,
financeOpen: false,
cableKm: 0,
straightKm: 0,
dragging: null,
inputs: {
mode: 'string',
mod_wp: 660, mod_l: 2.38, mod_w: 1.30, gcr: 0.45, gross_factor: 1.35,
// 18 strings, which is the ORIGINAL sandbox's own default. It was briefly
// changed to 23 here on the reasoning that 18 gives a block DC/AC of
// 0.945 - an array smaller than its inverters. That reasoning was applied
// without checking the reference, and the reference is explicit: "28
// string inverters rated at 352 kVA create a skid block of approximately
// 9,856 kVA BEFORE TRANSFORMER AND GRID LIMITATIONS". Oversizing the
// inverters against an 8.96 MVA skid is the design, not an error in it.
// A port does not get to improve its reference by guessing.
x_mods: 28, z_strings: 18, y_invs: 28, s_subs: 5, b_cols: 6,
dc_ac_ratio: 1.20, string_inv_kva: 352, string_skid_mva: 8.96,
// The original has a complete second physical-input set for central
// topology. Editing one tab must not rewrite the other tab's module,
// mounting, land or BESS case.
mod_wp_c: 660, mod_l_c: 2.38, mod_w_c: 1.30, gcr_c: 0.45,
gross_factor_c: 1.35,
inv_ac_mw_c: 4.4, inv_dc_mw_c: 5.28, central_skid_mva_c: 4.4,
x_mods_c: 28, str_per_cb_c: 24, inv_per_mv_c: 1, mv_per_ring_c: 4, rings_c: 4
},
finance: {
string: freshFinanceInputs(),
central: freshFinanceInputs(),
}
};
window.__GRIDATLAS_SLD__ = sld;
/* ── geodesy the layout needs, all on R_ATLAS ────────────────────────── */
/* Both moved into the geodesy module, where the radius lives. Delegated
here so every existing caller in the layout is untouched. */
function destinationPoint(lon, lat, km, bearingDeg) {
return GEODESY.destinationPoint(lon, lat, km, bearingDeg);
}
function initialBearingDeg(lon1, lat1, lon2, lat2) {
return GEODESY.initialBearingDeg(lon1, lat1, lon2, lat2);
}
function pathLengthKm(coords) {
let total = 0;
for (let i = 1; i < coords.length; i += 1) {
total += distanceKm(coords[i - 1][0], coords[i - 1][1], coords[i][0], coords[i][1]);
}
return total;
}
function normBearing(deg) { return ((deg % 360) + 360) % 360; }
// Scale factors from the WGS84 radii of curvature at a latitude, so a local
// tangent plane is correct rather than merely convenient.
function localScaleKm(latDeg) {
/* The semi-major axis, taken from the module rather than written again.
It is the same number as the haversine radius for a good reason - the
estate measures on the WGS-84 equatorial axis - and writing it twice
is how the two stop being the same number. */
const a = R_ATLAS;
const e2 = (1 / 298.257223563) * (2 - 1 / 298.257223563);
const s = Math.sin(latDeg * DEG);
const t = 1 - e2 * s * s;
return {
kx: (a / Math.sqrt(t)) * Math.cos(latDeg * DEG) * DEG,
ky: ((a * (1 - e2)) / t ** 1.5) * DEG
};
}
// Perpendicular distance to a SEGMENT, and the foot of that perpendicular.
// Measuring to an endpoint instead can only overstate; this is the function
// whose absence caused the original circuit_km defect, and it is what
// replaces turf.nearestPointOnLine in the ported layout.
function distanceToSegmentKm(lon, lat, aLon, aLat, bLon, bLat) {
const { kx, ky } = localScaleKm(lat);
const ax = (aLon - lon) * kx; const ay = (aLat - lat) * ky;
const bx = (bLon - lon) * kx; const by = (bLat - lat) * ky;
const dx = bx - ax; const dy = by - ay;
const len2 = dx * dx + dy * dy;
let t = 0;
if (len2 > 0) {
t = -(ax * dx + ay * dy) / len2;
t = t < 0 ? 0 : t > 1 ? 1 : t;
}
const foot = [aLon + (bLon - aLon) * t, aLat + (bLat - aLat) * t];
return { km: distanceKm(lon, lat, foot[0], foot[1]), foot, t };
}
// The sandbox's getRectPolygon, on one radius.
function rectPolygon(centre, widthKm, lengthKm, rotationDeg) {
const axis = normBearing(rotationDeg);
const n = destinationPoint(centre[0], centre[1], lengthKm / 2, axis);
const s = destinationPoint(centre[0], centre[1], lengthKm / 2, axis + 180);
const nw = destinationPoint(n[0], n[1], widthKm / 2, axis - 90);
const ne = destinationPoint(n[0], n[1], widthKm / 2, axis + 90);
const se = destinationPoint(s[0], s[1], widthKm / 2, axis + 90);
const sw = destinationPoint(s[0], s[1], widthKm / 2, axis - 90);
return [[nw, ne, se, sw, nw]];
}
// The sandbox uses turf.nearestPointOnLine to drop each block onto the
// collector trunk. distanceToSegmentKm already returns that foot.
function footOnSegment(lon, lat, a, b) {
return distanceToSegmentKm(lon, lat, a[0], a[1], b[0], b[1]).foot;
}
/* ── the sizing arithmetic, in its module ────────────────────────────
Lifted out at 202609012205 into atlas/modules/202609012205-sizing-
arithmetic.js, proven value-for-value against the last inline copy.
These delegations keep every caller's name; the module is handed the
state and the defaults the body used to close over. Absent module:
fail by name, never quietly compute nothing. */
const SIZING = (window.__GRIDATLAS_MODULES__ || {}).sizingArithmetic;
if (!SIZING) throw new Error('sld-sandbox: the sizing-arithmetic module is not composed');
const { DEVELOPMENT_STAGES, financeNumber } = SIZING;
function activePhysicalInputs() { return SIZING.physicalInputs(sld.inputs); }
function applyDevelopmentStageDefaults(financeInputs, stageValue) {
return SIZING.applyDevelopmentStageDefaults(financeInputs, stageValue);
}
function applyMountingBifacial(mode, gcrValue) {
return SIZING.applyMountingBifacial(sld.finance, mode, gcrValue);
}
function computeScreeningFinance(financeInputs, stats) {
return SIZING.screeningFinance(financeInputs, stats,
{ fallbackMode: sld.inputs.mode, defaults: FINANCE_DEFAULTS });
}
const computeSldStats = () => SIZING.computeStats(sld.inputs, sld.finance, FINANCE_DEFAULTS);
sld.computeFinance = computeScreeningFinance;
sld.applyDevelopmentStage = applyDevelopmentStageDefaults;
sld.applyMountingBifacial = applyMountingBifacial;
function fitToStatedCapacity() { return SIZING.fitToStatedCapacity(sld, computeSldStats); }
sld.fitToStatedCapacity = fitToStatedCapacity;
/* ── the layout ──────────────────────────────────────────────────────── */
function buildLayout() {
const stats = computeSldStats();
sld.stats = stats;
if (!sld.gridNode || stats.total_blocks === 0) {
return { type: 'FeatureCollection', features: [] };
}
const axis = normBearing(sld.rotationDeg);
const N = stats.total_blocks;
const cols = Math.ceil(Math.sqrt(N));
const rows = Math.ceil(N / cols);
const blockAreaKm2 = stats.block_ground_area_m2 / 1e6;
const physical = activePhysicalInputs();
const aspect = physical.gcr === 0.45 ? 1 / 1.4 : physical.gcr === 0.75 ? 1.0 : 1.4;
const blockW = Math.sqrt(blockAreaKm2 / aspect);
const blockL = blockW * aspect;
const gap = SLD.BLOCK_SPACING_KM;
const gridW = cols * blockW + (cols - 1) * gap;
const gridL = rows * blockL + (rows - 1) * gap;
const gridNode = sld.gridNode;
const offset = gridL / 2 + SLD.ARRAY_OFFSET_KM;
const centre = sld.arrayCentre
|| destinationPoint(gridNode[0], gridNode[1], offset, axis);
// The customer substation sits on the array edge nearest the grid node.
const customerSub = destinationPoint(centre[0], centre[1], gridL / 2, axis + 180);
const features = [];
const push = (geometry, properties) =>
features.push({ type: 'Feature', geometry, properties });
// Site boundary, and the grab surface for dragging.
push({ type: 'Polygon', coordinates: rectPolygon(centre, gridW + SLD.BOUNDARY_BUFFER_KM, gridL + SLD.BOUNDARY_BUFFER_KM, axis) },
{ kind: 'boundary', colour: SLD_COLOUR.boundary });
// Blocks, laid out from the north-west corner along the axis.
const ptN = destinationPoint(centre[0], centre[1], gridL / 2, axis);
const ptNW = destinationPoint(ptN[0], ptN[1], gridW / 2, axis - 90);
const blocks = [];
let placed = 0;
for (let r = 0; r < rows && placed < N; r += 1) {
for (let c = 0; c < cols && placed < N; c += 1) {
const across = destinationPoint(ptNW[0], ptNW[1],
c * blockW + c * gap + blockW / 2, axis + 90);
const at = destinationPoint(across[0], across[1],
r * blockL + r * gap + blockL / 2, axis + 180);
push({ type: 'Polygon', coordinates: rectPolygon(at, blockW, blockL, axis) },
{ kind: 'block', colour: SLD_COLOUR.block });
blocks.push(at);
placed += 1;
}
}
// 33 kV collectors: each block drops onto a trunk running up the axis
// from the customer substation, and the trunk is clipped to the furthest
// block rather than drawn to the far edge of nothing.
if (blocks.length) {
const trunkEnd = destinationPoint(customerSub[0], customerSub[1], gridL, axis);
let furthest = 0;
const branches = [];
for (const at of blocks) {
const foot = footOnSegment(at[0], at[1], customerSub, trunkEnd);
furthest = Math.max(furthest,
distanceKm(customerSub[0], customerSub[1], foot[0], foot[1]));
branches.push([at, foot]);
}
if (furthest > 0) {
const clipped = destinationPoint(customerSub[0], customerSub[1], furthest, axis);
push({ type: 'LineString', coordinates: [customerSub, clipped] },
{ kind: 'radial', role: 'collector_trunk', colour: SLD_COLOUR.radial });
}
for (const [at, foot] of branches) {
push({ type: 'LineString', coordinates: [at, foot] },
{ kind: 'radial', role: 'block_branch', colour: SLD_COLOUR.radial });
}
}
// BESS compound alongside the customer substation.
// The original drawing reads the same topology-local financial BESS MWh
// that drives CAPEX and revenue. There is no second layout-BESS input.
const bessMwh = financeNumber(sld.finance[sld.inputs.mode]?.bess_mwh);
if (bessMwh > 0) {
const areaKm2 = (bessMwh * SLD.BESS_M2_PER_MWH) / 1e6;
const w = Math.sqrt(areaKm2 * SLD.BESS_ASPECT);
const l = areaKm2 / w;
const at = destinationPoint(customerSub[0], customerSub[1], w / 2 + 0.05, axis - 90);
push({ type: 'Polygon', coordinates: rectPolygon(at, w, l, axis) },
{ kind: 'bess', colour: SLD_COLOUR.bess });
push({ type: 'LineString', coordinates: [at, customerSub] },
{ kind: 'radial', role: 'bess_tie', colour: SLD_COLOUR.radial });
}
// Export cable: customer substation, through the user's vertices, to the
// grid node. Measured along its own path, and against the straight line
// so the detour is visible rather than implied.
const route = [customerSub, ...sld.routePins, gridNode];
sld.cableKm = pathLengthKm(route);
sld.straightKm = distanceKm(customerSub[0], customerSub[1], gridNode[0], gridNode[1]);
push({ type: 'LineString', coordinates: route },
{ kind: 'cable', colour: SLD_COLOUR.cable, km: sld.cableKm });
sld.routePins.forEach((at, index) => {
push({ type: 'Point', coordinates: at },
{ kind: 'pin', index, colour: SLD_COLOUR.pin });
});
push({ type: 'Point', coordinates: customerSub },
{ kind: 'node', role: 'customer_substation', colour: SLD_COLOUR.node,
label: `CUSTOMER SUB · ${stats.production_substation_ac_mva.toFixed(2)} MVA` });
push({ type: 'Point', coordinates: gridNode },
{ kind: 'node', role: 'grid_node', colour: SLD_COLOUR.node,
label: `${sld.gridNodeName || 'GRID NODE'}${sld.gridNodeVoltage ? ` · ${sld.gridNodeVoltage}` : ''}` });
// Rotation handle, off the far edge of the array.
const handle = destinationPoint(centre[0], centre[1], gridL / 2 + 0.12, axis);
push({ type: 'Point', coordinates: handle },
{ kind: 'handle', colour: SLD_COLOUR.handle });
push({ type: 'LineString', coordinates: [centre, handle] },
{ kind: 'radial', role: 'handle_stem', colour: SLD_COLOUR.handle });
sld.geometry = { centre, customerSub, gridW, gridL, axis, handle, blocks: blocks.length };
return { type: 'FeatureCollection', features };
}
function ensureSldLayers(map) {
if (map.getSource(SRC_SLD)) return;
map.addSource(SRC_SLD, { type: 'geojson', data: { type: 'FeatureCollection', features: [] } });
map.addLayer({ id: SLD_LAYERS.boundary, type: 'fill', source: SRC_SLD,
filter: ['==', ['get', 'kind'], 'boundary'],
paint: { 'fill-color': SLD_COLOUR.boundary, 'fill-opacity': 0.07 } });
map.addLayer({ id: SLD_LAYERS.boundaryLine, type: 'line', source: SRC_SLD,
filter: ['==', ['get', 'kind'], 'boundary'],
paint: { 'line-color': SLD_COLOUR.boundary, 'line-width': 1.2, 'line-opacity': 0.65 } });
map.addLayer({ id: SLD_LAYERS.block, type: 'fill', source: SRC_SLD,
filter: ['==', ['get', 'kind'], 'block'],
paint: { 'fill-color': SLD_COLOUR.block, 'fill-opacity': 0.16,
'fill-outline-color': SLD_COLOUR.block } });
map.addLayer({ id: SLD_LAYERS.bess, type: 'fill', source: SRC_SLD,
filter: ['==', ['get', 'kind'], 'bess'],
paint: { 'fill-color': SLD_COLOUR.bess, 'fill-opacity': 0.22,
'fill-outline-color': SLD_COLOUR.bess } });
map.addLayer({ id: SLD_LAYERS.radial, type: 'line', source: SRC_SLD,
filter: ['==', ['get', 'kind'], 'radial'],
layout: { 'line-cap': 'round' },
paint: { 'line-color': ['get', 'colour'], 'line-width': 0.9, 'line-opacity': 0.5 } });
// The electron flow, on the collectors.
map.addLayer({ id: SLD_LAYERS.radialFlow, type: 'line', source: SRC_SLD,
filter: ['all', ['==', ['get', 'kind'], 'radial'], ['!=', ['get', 'role'], 'handle_stem']],
layout: { 'line-cap': 'round' },
paint: { 'line-color': FLOW_COLOUR, 'line-width': 1.3, 'line-opacity': 0.65,
'line-dasharray': [0.2, 3.2] } });
map.addLayer({ id: SLD_LAYERS.cableGlow, type: 'line', source: SRC_SLD,
filter: ['==', ['get', 'kind'], 'cable'],
layout: { 'line-cap': 'round', 'line-join': 'round' },
paint: { 'line-color': SLD_COLOUR.cable, 'line-width': 8, 'line-opacity': 0.12,
'line-blur': 5 } });
map.addLayer({ id: SLD_LAYERS.cable, type: 'line', source: SRC_SLD,
filter: ['==', ['get', 'kind'], 'cable'],
layout: { 'line-cap': 'round', 'line-join': 'round' },
paint: { 'line-color': SLD_COLOUR.cable, 'line-width': 1.8, 'line-opacity': 0.85 } });
map.addLayer({ id: SLD_LAYERS.cableFlow, type: 'line', source: SRC_SLD,
filter: ['==', ['get', 'kind'], 'cable'],
layout: { 'line-cap': 'round' },
paint: { 'line-color': FLOW_COLOUR, 'line-width': 2.4, 'line-opacity': 0.9,
'line-dasharray': [0.2, 3.2] } });
map.addLayer({ id: SLD_LAYERS.cableFlowB, type: 'line', source: SRC_SLD,
filter: ['==', ['get', 'kind'], 'cable'],
layout: { 'line-cap': 'round' },
paint: { 'line-color': FLOW_COLOUR, 'line-width': 1.6, 'line-opacity': 0.55,
'line-dasharray': [0.2, 3.2] } });
map.addLayer({ id: SLD_LAYERS.node, type: 'circle', source: SRC_SLD,
filter: ['==', ['get', 'kind'], 'node'],
paint: { 'circle-radius': 5, 'circle-color': SLD_COLOUR.node,
'circle-stroke-color': '#000c10', 'circle-stroke-width': 1.5 } });
map.addLayer({ id: SLD_LAYERS.pin, type: 'circle', source: SRC_SLD,
filter: ['==', ['get', 'kind'], 'pin'],
paint: { 'circle-radius': 5, 'circle-color': SLD_COLOUR.pin, 'circle-opacity': 0.9,
'circle-stroke-color': '#04343a', 'circle-stroke-width': 1.5 } });
map.addLayer({ id: SLD_LAYERS.handle, type: 'circle', source: SRC_SLD,
filter: ['==', ['get', 'kind'], 'handle'],
paint: { 'circle-radius': 6, 'circle-color': 'rgba(0,0,0,0)',
'circle-stroke-color': SLD_COLOUR.handle, 'circle-stroke-width': 1.8 } });
const sldFont = styleTextFont(map);
if (!sldFont) {
link.failures.push('the basemap serves no glyphs, so layout labels are omitted');
} else {
addLabelLayerWhenDrawable(map, sldFont, { id: SLD_LAYERS.label, type: 'symbol', source: SRC_SLD,
filter: ['==', ['get', 'kind'], 'node'],
layout: { 'text-field': ['get', 'label'], 'text-size': 9.5,
'text-offset': [0, -1.4], 'text-anchor': 'bottom',
'text-font': sldFont },
paint: { 'text-color': '#a9c4c9', 'text-halo-color': '#000c10',
'text-halo-width': 1.5 } }, 'layout');
}
}
let sldFlowHandle = null;
let sldPhase = 0;
function animateSld(map) {
if (sldFlowHandle !== null) cancelAnimationFrame(sldFlowHandle);
if (window.matchMedia?.('(prefers-reduced-motion: reduce)')?.matches) {
try {
map.setPaintProperty(SLD_LAYERS.cableFlow, 'line-opacity', 0);
map.setPaintProperty(SLD_LAYERS.cableFlowB, 'line-opacity', 0);
map.setPaintProperty(SLD_LAYERS.radialFlow, 'line-opacity', 0);
} catch (_) { /* layer gone */ }
return;
}
const step = () => {
sldPhase = (sldPhase + FLOW_SPEED) % FLOW_PERIOD;
const half = (sldPhase + FLOW_PERIOD / 2) % FLOW_PERIOD;
try {
setFlowDash(map, SLD_LAYERS.cableFlow, sldPhase);
setFlowDash(map, SLD_LAYERS.cableFlowB, half);
setFlowDash(map, SLD_LAYERS.radialFlow, sldPhase);
} catch (_) { sldFlowHandle = null; return; }
sldFlowHandle = requestAnimationFrame(step);
};
sldFlowHandle = requestAnimationFrame(step);
}
function redrawSld(map, { fit = false } = {}) {
ensureSldLayers(map);
const data = buildLayout();
setSourceData(map, SRC_SLD, data);
renderSldPanel();
if (data.features.length) animateSld(map);
if (fit && data.features.length && sld.geometry) {
const lons = []; const lats = [];
for (const f of data.features) {
const walk = (c) => {
if (typeof c[0] === 'number') { lons.push(c[0]); lats.push(c[1]); return; }
c.forEach(walk);
};
walk(f.geometry.coordinates);
}
map.fitBounds([[Math.min(...lons), Math.min(...lats)],
[Math.max(...lons), Math.max(...lats)]], { padding: 70, duration: 700 });
}
}
/* ── dragging ────────────────────────────────────────────────────────── */
function attachSldDragging(map) {
const canvas = map.getCanvas();
const grabbable = [SLD_LAYERS.handle, SLD_LAYERS.pin, SLD_LAYERS.boundary];
map.on('mousemove', (event) => {
if (!sld.active || sld.dragging) return;
const hits = map.queryRenderedFeatures(event.point, { layers: grabbable.filter(id => map.getLayer(id)) });
canvas.style.cursor = hits.length ? 'grab' : '';
});
const beginDrag = (event) => {
if (!sld.active || sld.dragging || fromOwnUi(event)) return;
const layers = grabbable.filter(id => map.getLayer(id));
if (!layers.length) return;
const hits = map.queryRenderedFeatures(event.point, { layers });
if (!hits.length) return;
const kind = hits[0].properties?.kind;
let nextDrag = null;
if (kind === 'handle') nextDrag = { what: 'rotate' };
else if (kind === 'pin') nextDrag = { what: 'pin', index: Number(hits[0].properties.index) };
else if (kind === 'boundary') nextDrag = { what: 'array' };
else return;
nextDrag.dragPanWasEnabled = map.dragPan.isEnabled?.() !== false;
nextDrag.touchWasEnabled = map.touchZoomRotate?.isEnabled?.() !== false;
sld.dragging = nextDrag;
event.preventDefault();
map.dragPan.disable();
map.touchZoomRotate?.disable();
canvas.style.cursor = 'grabbing';
};
map.on('mousedown', beginDrag);
map.on('touchstart', beginDrag);
const moveDrag = (event) => {
if (!sld.dragging) return;
event.preventDefault();
const at = [event.lngLat.lng, event.lngLat.lat];
if (sld.dragging.what === 'array') {
sld.arrayCentre = at;
} else if (sld.dragging.what === 'rotate') {
const c = sld.geometry?.centre;
if (c) sld.rotationDeg = initialBearingDeg(c[0], c[1], at[0], at[1]);
} else if (sld.dragging.what === 'pin') {
sld.routePins[sld.dragging.index] = at;
}
redrawSld(map);
};
map.on('mousemove', moveDrag);
map.on('touchmove', moveDrag);
const release = () => {
if (!sld.dragging) return;
const finished = sld.dragging;
sld.dragging = null;
if (finished.dragPanWasEnabled) map.dragPan.enable();
if (finished.touchWasEnabled) map.touchZoomRotate?.enable();
canvas.style.cursor = '';
};
map.on('mouseup', release);
map.on('touchend', release);
map.on('mouseout', release);
canvas.addEventListener?.('pointercancel', release);
// Click the cable to insert a vertex where you clicked; double-click a
// vertex to remove it. No modes, no commit step.
map.on('click', (event) => {
if (fromOwnUi(event)) return;
if (!sld.active || !map.getLayer(SLD_LAYERS.cable)) return;
const onPin = map.queryRenderedFeatures(event.point, { layers: [SLD_LAYERS.pin] });
if (onPin.length) return;
const onCable = map.queryRenderedFeatures(event.point, { layers: [SLD_LAYERS.cable] });
if (!onCable.length) return;
const at = [event.lngLat.lng, event.lngLat.lat];
const route = [sld.geometry.customerSub, ...sld.routePins, sld.gridNode];
let best = 0; let bestKm = Infinity;
for (let i = 0; i < route.length - 1; i += 1) {
const km = distanceToSegmentKm(at[0], at[1], route[i][0], route[i][1],
route[i + 1][0], route[i + 1][1]).km;
if (km < bestKm) { bestKm = km; best = i; }
}
sld.routePins.splice(best, 0, at);
redrawSld(map);
});
map.on('dblclick', (event) => {
if (!sld.active || !map.getLayer(SLD_LAYERS.pin)) return;
const hits = map.queryRenderedFeatures(event.point, { layers: [SLD_LAYERS.pin] });
if (!hits.length) return;
event.preventDefault();
sld.routePins.splice(Number(hits[0].properties.index), 1);
redrawSld(map);
});
}
/* ── the panel ───────────────────────────────────────────────────────── */
const PANEL_ID = 'gridatlas-sld-panel';
function installSldStyles() {
if (document.getElementById('gridatlas-sld-css')) return;
const style = document.createElement('style');
style.id = 'gridatlas-sld-css';
style.textContent = `
/* Top RIGHT, below the search box. The Atlas keeps its own tool buttons down
the left edge -- EXPORT CSV, RADIUS SEARCH, ZONE DRAW, MEASURE -- and a
panel on that side covers them, and the search bar occupies 72-96px inside
the map container on the right, so the panel clears it at 112px. Both offsets
were measured on the live map: no headless test catches a collision with a
component the panel knows nothing about. */
#${PANEL_ID}{position:absolute;right:14px;top:112px;bottom:14px;z-index:11;width:310px;
max-width:calc(100% - 28px);box-sizing:border-box;overflow:auto;font:11px/1.5 'Courier New',monospace;
color:#cfe9ee;background:rgba(2,8,11,.93);border:1px solid #0b5f63;border-radius:5px;
padding:11px 12px;box-shadow:0 0 22px rgba(0,255,255,.14);backdrop-filter:blur(3px);display:none}
#${PANEL_ID}[data-open="true"]{display:block}
#${PANEL_ID} h4{margin:0 0 2px;font-size:10px;letter-spacing:.09em;color:#5fbdc2;text-transform:uppercase;
display:flex;align-items:center;gap:7px}
#${PANEL_ID} .sld-beta{font-size:8px;padding:1px 4px;border-radius:2px;background:#3a2f12;
color:#e0b050;border:1px solid #6a5320}
#${PANEL_ID} .sld-site{color:#fff;font-size:12px;font-weight:bold;margin:2px 0 8px;
overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
#${PANEL_ID} h4.sld-drag{cursor:grab;user-select:none;touch-action:none}
#${PANEL_ID} h4.sld-drag:active{cursor:grabbing}
#${PANEL_ID} .sld-min{margin-left:auto}
#${PANEL_ID} .sld-min,#${PANEL_ID} .sld-close{cursor:pointer;background:#050a0d;
border:1px solid #2f6f75;color:#5fbdc2;font:inherit;font-size:12px;line-height:1;
min-width:44px;height:44px;border-radius:3px;padding:0 5px}
#${PANEL_ID} .sld-min:hover{color:#bfe9ee;border-color:#5fbdc2}
#${PANEL_ID} .sld-close:hover{color:#ff8f8f;border-color:#ff5d5d}
#${PANEL_ID}[data-min="true"] > *:not(h4){display:none}
#${PANEL_ID}[data-min="true"]{width:auto;padding:7px 9px;
box-shadow:0 0 14px rgba(95,189,194,.25)}
#${PANEL_ID}[data-min="true"] h4{margin:0}
#${PANEL_ID}[data-min="true"] .sld-min{border-color:#5fbdc2;color:#bfe9ee}
#${PANEL_ID} .sld-to{color:#8b9aa1;font-size:9.5px;margin:-6px 0 8px}
#${PANEL_ID} .sld-target{margin:0 0 9px;padding:7px 8px;border:1px solid #1d3238;
border-radius:3px;background:#050a0d}
#${PANEL_ID} .sld-target-row{display:flex;justify-content:space-between;align-items:baseline}
#${PANEL_ID} .sld-target-row b{color:#e0b050;font-variant-numeric:tabular-nums}
#${PANEL_ID} .sld-basis{display:flex;align-items:center;gap:6px;margin-top:5px}
#${PANEL_ID} .sld-basis span{color:#8b9aa1;font-size:10px;white-space:nowrap}
#${PANEL_ID} .sld-basis select{flex:1}
#${PANEL_ID} .sld-danger{margin-top:6px;color:#ff5d5d;font-size:9px;line-height:1.5;
border-left:2px solid #ff5d5d;padding-left:6px}
#${PANEL_ID} .sld-fitted{margin-top:6px;color:#8b9aa1;font-size:9px;line-height:1.5}
#${PANEL_ID} .sld-fitted b{color:#6fb582}
#${PANEL_ID} .sld-fitted b.sld-off{color:#ff5d5d}
#${PANEL_ID} .sld-ratio-note{margin-top:6px;color:#d9b45f;font-size:9px;line-height:1.5;
border-left:2px solid #8b6c28;padding-left:6px}
#${PANEL_ID} .sld-tabs{display:flex;gap:5px;margin-bottom:8px}
#${PANEL_ID} .sld-tabs button{flex:1;background:#050a0d;border:1px solid #1d3238;color:#7f939a;
font:inherit;font-size:9px;padding:4px;cursor:pointer;border-radius:3px;text-transform:uppercase}
#${PANEL_ID} .sld-tabs button[data-on="true"]{color:#5fbdc2;border-color:#5fbdc2}
#${PANEL_ID} .sld-grid{display:grid;grid-template-columns:1fr 62px;gap:3px 7px;align-items:center}
#${PANEL_ID} label{color:#8b9aa1;font-size:10px}
#${PANEL_ID} input,#${PANEL_ID} select{width:100%;background:#050a0d;border:1px solid #1d3238;
color:#d8dee6;font:inherit;font-size:10px;padding:2px 4px;border-radius:2px}
#${PANEL_ID} input:focus,#${PANEL_ID} select:focus{outline:1px solid #5fbdc2}
#${PANEL_ID} .sld-out{margin-top:9px;padding-top:8px;border-top:1px solid #10262b;
display:grid;grid-template-columns:1fr auto;gap:2px 8px}
#${PANEL_ID} .sld-out b{color:#e0b050;font-variant-numeric:tabular-nums}
#${PANEL_ID} .sld-out .lit{color:#5fbdc2}
#${PANEL_ID} .sld-warn{margin-top:7px;color:#d9963c;font-size:9px;line-height:1.45}
#${PANEL_ID} .sld-caveat{margin-top:7px;padding-top:7px;border-top:1px solid #10262b;
color:#68797f;font-size:9px;line-height:1.5}
#${PANEL_ID} .sld-caveat b{color:#8b9aa1}
#${PANEL_ID} .sld-hint{margin-top:6px;color:#5f7a80;font-size:9px;line-height:1.45}
#${PANEL_ID} .sld-finance{margin-top:9px;border-top:1px solid #214047;padding-top:7px}
#${PANEL_ID} .sld-finance summary{min-height:32px;display:flex;align-items:center;cursor:pointer;
color:#d9b45f;font-weight:bold;letter-spacing:.05em;user-select:none}
#${PANEL_ID} .sld-fin-grid{display:grid;grid-template-columns:1fr 76px;gap:3px 7px;align-items:center}
#${PANEL_ID} .sld-fin-section{grid-column:1/-1;margin-top:7px;padding-top:5px;
border-top:1px solid #10262b;color:#5fbdc2;font-size:9px;text-transform:uppercase}
#${PANEL_ID} .sld-fin-grid input[type="checkbox"]{width:24px;justify-self:end}
#${PANEL_ID} .sld-fin-out{margin:8px 0;padding:7px;background:#050a0d;border:1px solid #1d3238;
display:grid;grid-template-columns:1fr auto;gap:2px 8px}
#${PANEL_ID} .sld-fin-out b{color:#d9b45f;font-variant-numeric:tabular-nums;text-align:right}
#${PANEL_ID} .sld-fin-note{margin:6px 0;color:#8b9aa1;font-size:9px;line-height:1.5}
@media (max-width:700px){#${PANEL_ID}{width:auto;left:8px;right:8px;top:96px;bottom:8px}}
@media (pointer:coarse){
#${PANEL_ID} .sld-tabs button,#${PANEL_ID} input,#${PANEL_ID} select,
#${PANEL_ID} .sld-finance summary{min-height:44px}
}`;
document.head.appendChild(style);
}
function sldPanel() {
let el = document.getElementById(PANEL_ID);
if (el) return el;
installSldStyles();
el = document.createElement('div');
el.id = PANEL_ID;
(capturedMap?.getContainer() || document.body).appendChild(el);
return el;
}
const ELECTRICAL_RULES = Object.freeze({
mod_wp: { min: 1, step: 1, integer: true },
mod_l: { min: 0.01, step: 0.01 },
mod_w: { min: 0.01, step: 0.01 },