In this section
- Single-Line Diagram (SLD) Mount electrical · globalgrid2050 / solar-design-studio/202609271740-site-world/world/sld-mount.mjs lines 1–200
- Single-Line Diagram (SLD) Symbols electrical · globalgrid2050 / solar-design-studio/202609271740-site-world/world/sld-symbols.mjs lines 1–105
- Single-Line Diagram (SLD) View electrical · globalgrid2050 / solar-design-studio/202609271740-site-world/world/sld-view.mjs lines 1–169
- String Design transform · globalgrid2050 / solar-design-studio/202609271740-site-world/world/string-design.mjs lines 1–58
- Xray UI render · globalgrid2050 / solar-design-studio/202609271740-site-world/world/xray-ui.mjs lines 1–70
Single-Line Diagram (SLD) Mount
A JavaScript module in the world folder of GlobalGrid2050 that works with so far (`soFar`) and calculates planar distances (units: kV, MW, MVA), covering solar, substations, transformers and cables.
electricalglobalgrid2050 / solar-design-studio/202609271740-site-world/world/sld-mount.mjs · lines 1–200 of 200 · version 2026-09-27 17:40 · Not reached from any entry point (candidate for review) · pattern groundAt (shared by 3 files)
- What it does
- It draws solar, substations, transformers and cables. Defines 21 functions or classes, including mountSld, $, groundAt, connectionFor, network. Side effects: changes the web page (DOM).
- Why it exists in the grid workflow
- Domain stage sub33kv_design (path word 'design'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. Domain terms in the code: solar, substations, transformers, cables, 400kV.
- Inputs & outputs
- Voltage levels named: 400kV.
- Downstream impact
- Used directly by 1 file: Single-Line Diagram (SLD) Hook (globalgrid2050).
- What it achieves
- It is built from the mount SLD helper (`mountSld`), the ground at helper (`groundAt`) and the connection for helper (`connectionFor`). The single-line diagram in the world. Its code works with 40 kA and 400 kV. It responds to click events.
- Why it matters
- Imported by Single-Line Diagram (SLD) Hook.
- Application
- globalgrid2050 · solar-design-studio/202609271740-site-world/world · JavaScript module
- Uses
- Origin (import), Pick (import), Single-Line Diagram (SLD) Source (import), Single-Line Diagram (SLD) Graph (import), Single-Line Diagram (SLD) Calc (import), Single-Line Diagram (SLD) Follow (import), Single-Line Diagram (SLD) Symbols (import), Single-Line Diagram (SLD) View (import), and 3 more
- Used by
- imported by Single-Line Diagram (SLD) Hook (dynamic import)
- Produces
- mountSld
- Defines here
- mountSld, $, groundAt, connectionFor, network, need, rowsFor, o3, batch, batches, show, station, summary, follow, go, play, pause, close, soFar, followState, tap
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-design-studio/202609271740-site-world/world/sld-mount.mjs:1-200 · blob 2bd0d16e213466bddfff02eb442b7f7d84fa1efc · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: unreached_review
// sld-mount.mjs: the single-line diagram in the world. Loaded on first use (world.sld, the Single-line diagram and
// Follow buttons, or a tap on a module of the placed solar block), never on the first frame.
// SLD view the schematic of the whole plant (sld-view.mjs); a station click flies there
// symbols every element's single-line symbol standing over it in the world (sld-symbols.mjs)
// readouts load, current, cable, length, voltage drop and fault level per element (sld-calc.mjs)
// Follow from one module to the landing bay (sld-follow.mjs): the camera flies the path in legs and pauses at
// each element; play, pause, step (next, back). Paused, nothing is drawn (0 fps).
// The network is the placed solar block (Design > Plant > Solar block), else the laid-out plant. The grid source's
// fault level is assumed (40 kA) and can be set with world.sld.source(kA). Illustrative, not a design for any site.
import { toBng, toLocal } from './origin.mjs';
import { rayFromScreen, pickGround } from './pick.mjs';
import { sourceFromBlock, sourceFromLayout } from './sld-source.mjs';
import { buildGraph } from './sld-graph.mjs';
import { solve, readouts, checkGraph, RISE_NOTE } from './sld-calc.mjs';
import { followPath, pickPanel, parsePanel, dropSoFar } from './sld-follow.mjs';
import { symbolGroups, glowGroup, SYMBOL_COLOURS, GLOW } from './sld-symbols.mjs';
import { createSldView } from './sld-view.mjs';
import { SLD_LABEL, ELEC_FOOTER } from './sld-rules.mjs';
import { formatNumber, fmtQ, fmtPct, fmtLen } from './measure-format.mjs';
import { chooseConnection, CONNECT_LABEL } from './sld-connect.mjs';
const VIEW = { walk: { back: 7, pitch: -0.35 }, drone: { back: 45, pitch: -0.6 }, high: { back: 160, pitch: -0.8 } };
const DWELL_MS = 2500;
const FOLLOW_CSS = `#sld-follow { left: 50%; transform: translateX(-50%); bottom: calc(var(--foot, 20px) + 8px); width: min(420px, calc(100vw - 16px));
z-index: 6; } #sld-follow[hidden] { display: none; } #sld-follow h3 { margin: 0 0 4px; font-size: 12px; color: var(--text, #cfe9ff); }
#sld-follow dl { display: grid; grid-template-columns: auto 1fr; gap: 2px 10px; margin: 0 0 6px; font-variant-numeric: tabular-nums; }
#sld-follow dt { color: var(--text, #cfe9ff); } #sld-follow dd { margin: 0; color: var(--dim, #6f8ea6); }
#sld-follow .row { display: flex; gap: 4px; } #sld-follow button { flex: 1; background: var(--panel, #111); color: var(--text, #cfe9ff);
border: 1px solid var(--edge, #1c2c3a); border-radius: 4px; min-height: var(--btn, 30px); cursor: pointer; }
#sld-follow .note { margin: 0 0 4px; color: var(--dim, #6f8ea6); font-size: 11px; }
body:has(#sld-follow:not([hidden])) #sld-panel { bottom: calc(var(--foot, 20px) + 250px); max-height: 30vh; }
body[data-cmd] #sld-follow { bottom: calc(var(--cmd-top, 220px) + 6px); max-height: calc(100vh - var(--cmd-top, 220px) - 60px); overflow: auto; }`;
// Above: with the command line open, the Follow card sits on top of the bar, never over it (cmd-ui.mjs sets --cmd-top).
// deps: { api (substrate), block: design.blockApi, plant: design.plantApi, doc }
export function mountSld({ api, block, plant, doc = document }) {
const $ = id => doc.getElementById(id);
const S = { key: '', net: null, groups: null, v: 0, follow: null, at: -1, playing: false, timer: null, sourceKA: null };
const groundAt = (e, n) => { const [x, y] = toLocal(api.origin(), e, n); return api.heightAt(x, y); };
const view = createSldView({ doc, onStation: id => station(id), onElement: (n, b) => rowsFor(n, b), onClose: () => { api.invalidate({ ground: false }); } });
const box = doc.createElement('section');
box.id = 'sld-follow'; box.className = 'panel'; box.hidden = true; box.setAttribute('aria-label', 'Follow');
box.innerHTML = `<h3 id="sld-follow-title"></h3><p class="note">${SLD_LABEL} Drop is along the path towards the grid. ${ELEC_FOOTER}</p><dl id="sld-follow-rows"></dl>
<div class="row"><button type="button" data-f="back">Back</button><button type="button" data-f="play">Play</button>
<button type="button" data-f="next">Next</button><button type="button" data-f="close">Close</button></div>`;
doc.body.append(box);
if (!$('sld-follow-style')) { const s = doc.createElement('style'); s.id = 'sld-follow-style'; s.textContent = FOLLOW_CSS; doc.head.append(s); }
box.addEventListener('click', e => { const f = e.target.closest('[data-f]')?.dataset.f; if (f === 'play') (S.playing ? pause() : play()); else if (f) api_[f](); });
// ---- the network: the placed block first, else the laid-out plant ----
// What is near: substations and 400 kV towers of the grid layer, plus the national index's nearest substation.
function connectionFor(mw, at, kv = null) {
const model = api.live().find(l => l.id === 'grid')?.layer?.debug?.()?.model, grid = api.live().find(l => l.id === 'grid')?.layer;
const subs = (model?.substations || []).map(s => ({ e: s.e, n: s.n, kv: s.kv }));
const towers = (model?.lines || []).flatMap(l => l.towers.map(t => ({ e: t.e, n: t.n, kv: l.kv })));
const k = `${Math.round(at[0])},${Math.round(at[1])}`;
if (S.natKey !== k && grid?.nearestSubstation) {
S.natKey = k;
Promise.resolve(grid.nearestSubstation(at[0], at[1])).then(x => { if (x && Number.isFinite(x.kv)) { S.nat = x; S.key = ''; api.invalidate({ ground: false }); } }).catch(() => {});
}
if (S.nat) subs.push({ e: S.nat.e, n: S.nat.n, kv: S.nat.kv });
return chooseConnection({ mw, at, subs, towers, kv, rules: S.rules || {} });
}
function network() {
const b = block?.built?.(), pr = !b && plant?.result?.(), r = pr ? { result: pr, version: plant.version?.() ?? 0 } : null;
const key = b ? `b${b.version}` : r ? `p${r.version}` : '';
if (!key) return null;
if (key + ':' + S.sourceKA === S.key && S.net) return S.net;
let src;
if (b) { const at = [b.anchor[0] + b.built.mv.poc.at[0], b.anchor[1] + b.built.mv.poc.at[1]]; src = sourceFromBlock(b.built, b.anchor, connectionFor(b.built.mv.exportMW, at, b.built.mv.poc.kv)); }
else { const first = sourceFromLayout(r.result, null); src = sourceFromLayout(r.result, connectionFor(first.mw, first.hv.plantAt)); }
const g = buildGraph(src, S.sourceKA ? { sourceKA: S.sourceKA } : {}), sol = solve(g), ro = readouts(g, sol);
S.net = { src, g, sol, ro, check: checkGraph(g), block: b };
S.key = key + ':' + S.sourceKA; S.v++; S.groups = null;
return S.net;
}
const need = () => { const n = network(); if (!n) throw Error('Place the solar block, or lay out a plant, first (Design > Plant).'); return n; };
// ---- readouts: one element, as rows ----
// Numbers by the one rule (measure-format.mjs): loads, currents and fault levels 3 figures, percentages 2 dp, whole metres.
function rowsFor(nodeId, branchId) {
if (/\.EARTH$/.test(nodeId || '')) return globalThis.worldEarth?.rowsFor(nodeId) || [['Earthing', 'type earthing show first'], ['Note', ELEC_FOOTER]];
const N = network();
if (!N) return [];
const { g, sol, ro } = N, into = nodeId ? sol.tree.via.get(nodeId) : g.branches.find(b => b.id === branchId);
const n = nodeId && ro.nodes.get(nodeId), b = into && ro.branches.get(into.id), rows = [];
if (n) rows.push(['Element', n.label], ['Voltage level', n.kv < 1 ? `${formatNumber(n.kv * 1000, 0)} V` : `${n.kv} kV`],
['Above the landing', `${fmtPct(n.riseToLandingPct)}${n.high ? ' · ' + RISE_NOTE : ''}`], ['Fault level', `${fmtQ(n.faultKA, 'kA')}, ${fmtQ(n.faultMVA, 'MVA')}`]);
if (b) rows.push(['Feeding it', b.label], ['Load', fmtQ(b.loadMVA, 'MVA')], ['Current', fmtQ(b.currentA, 'A')],
...(b.areaMm2 ? [['Cable', `${b.areaMm2} mm² Al, ${fmtLen(b.lengthM)}${b.ratingA ? `, rated ${fmtQ(b.ratingA, 'A')} (${fmtQ(100 * b.utilisation, '%', 2)})` : ''}`]] : []),
...(b.tap ? [['On-load tap', `${fmtPct((b.tap - 1) * 100)} (±10 % in 1.25 % steps, illustrative)`]] : []), ['Voltage drop', fmtPct(b.dropPct)]);
rows.push(['Basis', `${SLD_LABEL} Grid fault level ${N.g.params.sourceKA} kA assumed; grid transformer taps set by the load flow.`], ['Note', ELEC_FOOTER]);
return rows;
}
// ---- drawing: symbols while the view or Follow is open; the Follow path glows ----
const o3 = base => [base[0] - api.origin().e, base[1] - api.origin().n, base[2]];
const batch = (key, G, color, version) => (G.base && G.v.length >= 6 ? { key: 'sld-' + key, version, positions: G.v instanceof Float32Array ? G.v : (G.v = new Float32Array(G.v)),
color, origin: o3(G.base) } : null);
function batches() {
if (!S.net || (!view.open() && !S.follow)) return [];
S.groups ||= symbolGroups(S.net.g, { groundAt });
const out = Object.entries(S.groups).map(([k, G]) => batch(k, G, SYMBOL_COLOURS[k], `${S.v}`));
if (S.follow) out.push(batch('glow', S.follow.glow, GLOW, `${S.v}:${S.follow.panel}:${S.at}`));
return out.filter(Boolean);
}
// ---- SLD view and stations ----
function show() {
const N = need();
const earth = !!globalThis.worldEarth?.on?.();
view.show(N.src, S.key + (earth ? ':earth' : ''), { earth });
const gts = N.src.grid.length;
view.rows([['Plant', `${N.check.stations} stations · ${N.src.feeders.length} feeders · ${N.src.sections.length} board sections · ${gts} grid transformer${gts === 1 ? '' : 's'}`],
['Network', N.check.ok ? 'every inverter reaches the landing once' : N.check.problems.join('; ')],
['Connection', `${N.src.hv.ruleText} · ${CONNECT_LABEL}`],
['Taps', N.g.branches.filter(x => x.tap).map(x => `${x.id.split('.')[0]} ${fmtPct((x.tap - 1) * 100)}`).join(', ') || 'no grid transformer'],
['Basis', SLD_LABEL], ['Note', ELEC_FOOTER]]);
api.invalidate({ ground: false });
return summary();
}
function station(id) {
const N = need(), n = N.g.nodes.find(x => x.id === `${id}.R`);
if (!n?.at) return null;
const [x, y] = toLocal(api.origin(), n.at[0], n.at[1]);
api.flyTo(x, y, { ...VIEW.drone, yaw: api.state().yaw });
view.highlight([`${id}.R`], []); view.rows(rowsFor(`${id}.R`));
return { id, at: [...n.at], rows: rowsFor(`${id}.R`) };
}
const summary = () => { const N = S.net; return N ? { kind: N.src.kind, stations: N.check.stations, inverters: N.check.inverters, feeders: N.src.feeders.length,
sections: N.src.sections.length, gridTransformers: N.src.grid.length, ok: N.check.ok, landing: { ...N.src.hv.landing }, rule: N.src.hv.rule, ruleText: N.src.hv.ruleText, open: view.open(),
ids: N.g.nodes.filter(x => x.kind === 'rmu').map(x => x.id.slice(0, -2)), label: SLD_LABEL } : null; };
// ---- Follow ----
async function follow(panel = null) {
if (!block?.built?.()) await block?.place?.();
const N = need();
if (!N.block) throw Error('Follow runs on the solar block: place it first (Design > Plant > Solar block).');
const b = N.block.built, P = panel ? parsePanel(panel) : { station: 'S1', string: 0, module: 0 };
if (!P) throw Error('Follow needs a module id such as S1:0:0 (station, string, module).');
const fp = followPath({ built: b, anchor: N.block.anchor, graph: N.g, sol: N.sol, ro: N.ro, panel: P, groundAt });
S.follow = { ...fp, glow: glowGroup(fp.points) };
if (view.open()) view.highlight(fp.nodes, fp.branches);
box.hidden = false; go(0);
return followState();
}
function go(i) {
const F = S.follow;
if (!F) return null;
S.at = Math.max(0, Math.min(F.stops.length - 1, i));
const s = F.stops[S.at], prev = F.stops[S.at - 1]?.at || s.leg[0];
$('sld-follow-title').textContent = `${S.at + 1} / ${F.stops.length} · ${s.title}`;
const nb = box.querySelector('[data-f="next"]'), bb = box.querySelector('[data-f="back"]'); // no Next at the end, no Back at the start
if (nb) nb.disabled = S.at >= F.stops.length - 1; if (bb) bb.disabled = S.at <= 0;
$('sld-follow-rows').replaceChildren(...s.rows.flatMap(([k, v]) => { const dt = doc.createElement('dt'), dd = doc.createElement('dd'); dt.textContent = k; dd.textContent = v; return [dt, dd]; }));
F.glow = glowGroup(F.points, s.at);
const [x, y] = toLocal(api.origin(), s.at[0], s.at[1]), legM = Math.hypot(s.at[0] - prev[0], s.at[1] - prev[1]);
const yaw = legM > 1 ? Math.atan2(s.at[0] - prev[0], s.at[1] - prev[1]) : api.state().yaw, seconds = Math.min(5, 1.5 + legM / 500);
api.flyTo(x, y, { ...VIEW[s.view], yaw, seconds });
clearTimeout(S.timer);
if (S.playing) S.timer = setTimeout(() => { if (S.playing && S.at < F.stops.length - 1) go(S.at + 1); else pause(); }, seconds * 1000 + DWELL_MS);
S.v++; api.invalidate({ ground: false });
return followState();
}
function play() { if (!S.follow) return null; S.playing = true; box.querySelector('[data-f="play"]').textContent = 'Pause'; return go(S.at >= S.follow.stops.length - 1 ? 0 : S.at + 1); }
function pause() { S.playing = false; clearTimeout(S.timer); box.querySelector('[data-f="play"]').textContent = 'Play'; return followState(); }
function close() { pause(); S.follow = null; S.at = -1; box.hidden = true; view.highlight(); S.v++; api.invalidate({ ground: false }); return null; }
// The drop so far at this stop and its DC and AC parts (they add up to it); the whole path's totals beside them.
const soFar = (f, i) => { const d = dropSoFar(f, i); return { cumDropPct: d.cum, dcDropPct: d.dc, acDropPct: d.ac }; };
const followState = () => (S.follow ? { panel: S.follow.panel, stop: S.at, stops: S.follow.stops.length, key: S.follow.stops[S.at]?.key,
title: S.follow.stops[S.at]?.title, playing: S.playing, ...soFar(S.follow, S.at), totalDropPct: S.follow.stops.at(-1).cumDropPct,
dcTotalPct: S.follow.dcDropPct, acTotalPct: S.follow.acDropPct, ends: S.follow.stops.at(-1).key, rows: S.follow.stops[S.at]?.rows } : null);
// A tap on a module of the placed block starts Follow there (not while a design tool is in hand).
function tap(clientX, clientY) {
const b = block?.built?.();
if (!b || api.design().tool) return false;
const c = api.canvas, r = c.getBoundingClientRect(), st = api.state();
const ray = rayFromScreen((clientX - r.left) * c.width / r.width, (clientY - r.top) * c.height / r.height, c.width, c.height, st.pos, st.yaw, st.pitch, api.FOV);
const hit = pickGround(ray, (x, y) => api.heightAt(x, y), { maxDistance: 1500 });
if (!hit) return false;
const p = toBng(api.origin(), hit[0], hit[1]), P = pickPanel(b.built, b.anchor, [p.e, p.n]);
if (!P) return false;
follow(`${P.station}:${P.string}:${P.module}`).catch(e => console.warn('follow: ' + e.message));
return true;
}
const api_ = { next: () => go(S.at + 1), back: () => go(S.at - 1), close };
api.hooks.batches?.add(batches);
return {
show, hide: () => { view.hide(); api.invalidate({ ground: false }); }, station, follow, play, pause, close, tap, summary,
next: api_.next, back: api_.back, state: followState, readout: id => rowsFor(id),
rules(r = {}) { S.rules = { ...(S.rules || {}), ...r }; S.key = ''; if (network() && view.open()) show(); return { ...S.rules }; },
source(kA) { S.sourceKA = Number(kA) > 0 ? Number(kA) : null; S.key = ''; if (network() && view.open()) show(); return S.net?.g.params.sourceKA ?? null; },
graph: () => { const N = network(); return N ? { g: N.g, ro: N.ro } : null; }, // the earthing study reads the network
refresh: () => (view.open() ? show() : null),
network: () => { const N = network(); return N ? { summary: summary(), check: N.check, nodes: N.g.nodes.length, branches: N.g.branches.length } : null; }
};
}Single-Line Diagram (SLD) Symbols
A JavaScript module in the world folder of GlobalGrid2050 that works with transformers, cables and overhead lines (OHL).
electricalglobalgrid2050 / solar-design-studio/202609271740-site-world/world/sld-symbols.mjs · lines 1–105 of 105 · version 2026-09-27 17:40 · pattern earth (shared by 2 files)
- What it does
- It calculates transformers, cables and overhead lines (OHL). Defines 12 functions or classes, including group, put, seg, poly, pen.
- Why it exists in the grid workflow
- Domain stage sub33kv_design (path word 'design'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. Domain terms in the code: transformers, cables, overhead lines (OHL).
- Downstream impact
- Used directly by 2 files: Earth Mount (globalgrid2050); Single-Line Diagram (SLD) Mount (globalgrid2050). Reached from 2 other entry points, including Solar Design Studio — Site World Page (globalgrid2050, https://globalgrid2050.com/solar-design-studio/202609271853-site-world/); Substrate (globalgrid2050).
- What it achieves
- It is built from the group step (`group`), the put step (`put`) and the seg step (`seg`). The single-line diagram drawn in the world, as line groups in national-grid metres.
- Why it matters
- Imported by Earth Mount and Single-Line Diagram (SLD) Mount.
- Application
- globalgrid2050 · solar-design-studio/202609271740-site-world/world · JavaScript module
- Uses
- Elec Style (import)
- Used by
- imported by Earth Mount (import), imported by Single-Line Diagram (SLD) Mount (import)
- Produces
- symbolGroups, glowGroup, SYMBOL_COLOURS, GLOW
- Defines here
- group, put, seg, poly, pen, sw, earth, symbolGroups, at, stem, lift, glowGroup
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-design-studio/202609271740-site-world/world/sld-symbols.mjs:1-105 · blob e5fe7a81a3f6de13cd18fb0f08258a1117d12e53 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: production_core
// sld-symbols.mjs: the single-line diagram drawn in the world, as line groups in national-grid metres.
//
// Each element of the network graph (sld-graph.mjs) gets a small single-line symbol standing on a thin mast above
// where it is: a station's RMU with its three ways (incomer, outgoer, transformer breaker), its transformer (two
// circles) and LV board; the MV board sections with their bus ties (an open blade, drawn red), earthing transformer and
// NER; the grid transformers; the HV bay (disconnector, earth switch, surge arrester) and the landing bay. Feeder chains
// run RMU to RMU along the cable routes just above the ground; a normally-open point is marked red over its RMU; the
// HV connection runs to the landing. Symbols stand in a vertical plane facing the plan's south (x east, z up).
// Illustrative, not a design for any site. Pure: no DOM; groundAt(e, n) gives the ground (m).
import { rgba } from './elec-style.mjs';
const RING = 16;
// Colours by voltage level from the one table (elec-style.mjs).
const COLOUR = Object.freeze({ hv: rgba('hv'), mv: rgba('mv'), lv: rgba('lv'), open: rgba('open'), earth: rgba('earth') });
function group() { return { base: null, v: [] }; }
const put = (G, p) => { if (!G.base) G.base = [p[0], p[1], p[2]]; G.v.push(p[0] - G.base[0], p[1] - G.base[1], p[2] - G.base[2]); };
const seg = (G, a, b) => { put(G, a); put(G, b); };
const poly = (G, pts) => { for (let i = 1; i < pts.length; i++) seg(G, pts[i - 1], pts[i]); };
// Drawing in a symbol's own plane: (x, z) metres from its anchor [e, n, z0].
const pen = (G, [e, n, z0]) => ({
line: (x0, z0a, x1, z1) => seg(G, [e + x0, n, z0 + z0a], [e + x1, n, z0 + z1]),
circle: (x, z, r) => poly(G, Array.from({ length: RING + 1 }, (_, k) => [e + x + r * Math.cos(2 * Math.PI * k / RING), n, z0 + z + r * Math.sin(2 * Math.PI * k / RING)])),
box: (x, z, w, h) => poly(G, [[e + x, n, z0 + z], [e + x + w, n, z0 + z], [e + x + w, n, z0 + z + h], [e + x, n, z0 + z + h], [e + x, n, z0 + z]]),
zig: (x, z0b, z1, k = 6, w = 0.25) => poly(G, Array.from({ length: k + 1 }, (_, i) => [e + x + (i % 2 ? w : -w) * (i && i < k ? 1 : 0), n, z0 + z0b + (z1 - z0b) * i / k]))
});
// A switch in a vertical way from z0 to z1 at x: closed is a straight line; open is a blade swung aside.
function sw(P, x, za, zb, open, breaker = false) {
const m = (za + zb) / 2;
P.line(x, za, x, m - 0.25); P.line(x, m + 0.25, x, zb);
if (open) P.line(x, m - 0.25, x + 0.35, m + 0.2); else P.line(x, m - 0.25, x, m + 0.25);
if (breaker) P.box(x - 0.15, m - 0.15, 0.3, 0.3);
}
const earth = (P, x, z) => { P.line(x - 0.3, z, x + 0.3, z); P.line(x - 0.2, z - 0.12, x + 0.2, z - 0.12); P.line(x - 0.1, z - 0.24, x + 0.1, z - 0.24); };
/**
* symbolGroups(graph, { groundAt, mast = 6 }) -> { mv, hv, lv, open, earth }: each { base: [e, n, z] | null, v: [] }.
* Nodes without a position are left out (a generic plant has none until it is laid out).
*/
export function symbolGroups(g, { groundAt = () => 0, mast = 6 } = {}) {
const G = { mv: group(), hv: group(), lv: group(), open: group(), earth: group() };
const at = (n, h = mast) => { const [e, nn] = n.at; return [e, nn, groundAt(e, nn) + h]; };
const stem = (L, n, h = mast) => { const [e, nn] = n.at, z = groundAt(e, nn); seg(L, [e, nn, z], [e, nn, z + h]); };
const byId = new Map(g.nodes.map(n => [n.id, n]));
const openAt = new Set(g.branches.filter(b => b.kind === 'feeder-cable' && b.open).flatMap(b => [b.from, b.to]));
for (const n of g.nodes) {
if (!n.at) continue;
if (n.kind === 'rmu') { // box, incomer / outgoer switches, transformer breaker
stem(G.mv, n); const P = pen(G.mv, at(n));
P.box(-1.2, 0, 2.4, 1.8); P.line(-1.2, 1.4, 1.2, 1.4);
sw(P, -0.8, 0, 1.4, false); sw(openAt.has(n.id) ? pen(G.open, at(n)) : P, 0, 0, 1.4, openAt.has(n.id)); sw(P, 0.8, 0, 1.4, false, true);
if (openAt.has(n.id)) { const Q = pen(G.open, at(n)); Q.box(-1.4, -0.2, 2.8, 2.2); }
} else if (n.kind === 'st-hv') { // transformer: two circles, then the LV board bar below
const P = pen(G.mv, at(n, mast + 3)), L = pen(G.lv, at(n, mast + 3));
stem(G.mv, n, mast + 2); P.circle(0, 1.3, 0.6); L.circle(0, 0.5, 0.6); L.line(-1, -0.3, 1, -0.3); L.line(0, -0.1, 0, -0.3);
for (const x of [-0.8, -0.3, 0.2, 0.7]) L.line(x, -0.3, x, -0.8);
} else if (n.kind === 'mv-board') { // busbar, ways dropping, earthing on the left
stem(G.mv, n, mast + 2); const P = pen(G.mv, at(n, mast + 2)), E = pen(G.earth, at(n, mast + 2));
P.line(-3, 0, 3, 0);
for (let x = -2; x <= 2; x += 1) sw(P, x, -1.6, 0, false, true);
E.line(-3, 0, -3.6, 0); E.zig(-3.6, -0.2, -1.4); E.box(-3.8, -2.2, 0.4, 0.7); earth(E, -3.6, -2.4);
} else if (n.kind === 'gt-lv') {
stem(G.hv, n, mast + 4); const P = pen(G.hv, at(n, mast + 4)), M = pen(G.mv, at(n, mast + 4));
P.circle(0, 1.2, 1); M.circle(0, 0, 1);
} else if (n.kind === 'hv-bay') { // disconnector, earth switch, surge arrester
const P = pen(G.hv, at(n, mast + 9)), E = pen(G.earth, at(n, mast + 9));
sw(P, 0, 0, 2.4, false); P.line(0, 1.9, 0.9, 1.9); sw(E, 0.9, 0.6, 1.9, true); earth(E, 0.9, 0.6);
P.line(0, 0.5, -0.9, 0.5); E.box(-1.1, -0.5, 0.4, 0.8); earth(E, -0.9, -0.6);
} else if (['gis-bay', 'tower', 'dno-sub', 'none'].includes(n.kind)) {
stem(G.hv, n, mast + 12); const P = pen(G.hv, at(n, mast + 12)); P.box(-1.5, 0, 3, 2.4); sw(P, 0, 0, 2.4, false, true);
} else if (n.kind === 'hv-bus') { stem(G.hv, n, mast + 11); pen(G.hv, at(n, mast + 11)).line(-2, 0, 2, 0); }
}
// Ties between board sections: an open blade between neighbouring bus ends.
for (const b of g.branches.filter(x => x.kind === 'bus-tie')) {
const a = byId.get(b.from), c = byId.get(b.to);
if (!a?.at || !c?.at) continue;
const pa = at(a, mast + 2), pc = at(c, mast + 2), m = [(pa[0] + pc[0]) / 2, (pa[1] + pc[1]) / 2, pa[2] + 0.6];
poly(G.open, [pa, [m[0] - 0.3, m[1], m[2]]]); seg(G.open, [m[0] - 0.3, m[1], m[2]], [m[0] + 0.3, m[1], m[2] + 0.5]); poly(G.open, [[m[0] + 0.3, m[1], m[2]], pc]);
}
// Feeder chains and the HV connection just above the ground along their routes (straight where no route is known).
const lift = (pts, h) => pts.map(q => [q[0], q[1], groundAt(q[0], q[1]) + h]);
for (const b of g.branches) {
const a = byId.get(b.from), c = byId.get(b.to);
if (b.kind === 'feeder-cable') { const pts = b.path ? lift(b.path, 0.4) : a?.at && c?.at ? lift([a.at, c.at], 0.4) : null; if (pts) poly(b.open ? G.open : G.mv, pts); }
if ((b.kind === 'hv-cable' || b.kind === 'ohl-tee') && a?.at && c?.at) poly(G.hv, lift(b.path || [a.at, c.at], b.kind === 'ohl-tee' ? 28 : 0.4));
if (b.kind === 'hv-bay' || b.kind === 'mv-incomer' || b.kind === 'rmu-tx') {
if (a?.at && c?.at && Math.hypot(a.at[0] - c.at[0], a.at[1] - c.at[1]) > 1) poly(b.kind === 'rmu-tx' ? G.mv : G.hv, lift([a.at, c.at], 0.4));
}
}
return G;
}
/** The Follow path as one glowing line, plus a marker over the current stop. */
export function glowGroup(points, marker = null) {
const G = group();
poly(G, points.map(q => [q[0], q[1], q[2] + 0.15]));
if (marker) { const [e, n, z] = marker; seg(G, [e, n, z], [e, n, z + 8]); for (let k = 0; k < RING; k++) {
const a = 2 * Math.PI * k / RING, b = 2 * Math.PI * (k + 1) / RING; seg(G, [e + 1.2 * Math.cos(a), n + 1.2 * Math.sin(a), z + 8], [e + 1.2 * Math.cos(b), n + 1.2 * Math.sin(b), z + 8]); } }
return G;
}
export const SYMBOL_COLOURS = COLOUR;
export const GLOW = rgba('glow');Single-Line Diagram (SLD) View
A JavaScript module in the world folder of GlobalGrid2050 that works with earth mark (`earthMark`) (units: MVA, kV), covering transformers, cables and substations.
electricalglobalgrid2050 / solar-design-studio/202609271740-site-world/world/sld-view.mjs · lines 1–169 of 169 · version 2026-09-27 17:40 · Not reached from any entry point (candidate for review) · pattern circle (shared by 9 files)
- What it does
- It draws transformers, cables and substations. Defines 9 functions or classes, including el, createSldView, rows, draw, hit. Side effects: changes the web page (DOM).
- Why it exists in the grid workflow
- Domain stage sub33kv_design (path word 'design'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. Domain terms in the code: transformers, cables, substations, 33kV.
- Inputs & outputs
- Voltage levels named: 33kV.
- Downstream impact
- Used directly by 1 file: Single-Line Diagram (SLD) Mount (globalgrid2050).
- What it achieves
- It creates SLD view (`createSldView`) and is built from the rows step (`rows`) and the draw step (`draw`). The SLD view, a clean schematic single-line diagram of the whole plant in a flat panel over the world. Its code works with 33 kV. It responds to click events.
- Why it matters
- Imported by Single-Line Diagram (SLD) Mount.
- Application
- globalgrid2050 · solar-design-studio/202609271740-site-world/world · JavaScript module
- Uses
- Single-Line Diagram (SLD) Rules (import), Elec Style (import)
- Used by
- imported by Single-Line Diagram (SLD) Mount (import)
- Produces
- createSldView
- Defines here
- el, createSldView, rows, draw, hit, line, text, circle, earthMark
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-design-studio/202609271740-site-world/world/sld-view.mjs:1-169 · blob a6ec2536744b9fdd854973de5f6ca77848cf11d8 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: unreached_review
// sld-view.mjs: the SLD view, a clean schematic single-line diagram of the whole plant in a flat panel over the world.
//
// Drawn from the same network the world's symbols and the readouts come from (sld-graph.mjs, sld-source.mjs): the
// landing bay and HV cable at the top, the plant-end HV bay and grid transformers, the 33 kV board sections with their
// normally-open bus ties and earthing, then one column per feeder, RMU under RMU, each station beside its RMU. A ring's
// normally-open link is dashed red. Click or tap a station to fly to it; any other symbol shows its readout. Follow
// highlights its path here too. Only redrawn when the network changes (nothing runs while it is open and still).
import { ELEC_FOOTER } from './sld-rules.mjs';
import { elecCss } from './elec-style.mjs';
const NS = 'http://www.w3.org/2000/svg', COL = 96, ROW = 74, TOP = 24;
const CSS = `
#sld-panel { left: 8px; top: 56px; bottom: calc(var(--foot, 20px) + 8px); width: min(640px, calc(100vw - 16px)); display: flex; /* the full height */
flex-direction: column; gap: 6px; z-index: 5; }
#sld-panel[hidden] { display: none; }
#sld-panel header { display: flex; align-items: center; gap: 8px; justify-content: space-between; }
#sld-panel h2 { margin: 0; font-size: 12px; font-weight: 600; color: var(--text, #cfe9ff); }
#sld-panel .note { margin: 0; color: var(--dim, #6f8ea6); font-size: 11px; }
#sld-panel .scroll { overflow: auto; flex: 1; min-height: 120px; border: 1px solid var(--edge, #1c2c3a); border-radius: 4px; }
#sld-panel svg { display: block; }
#sld-panel svg * { vector-effect: non-scaling-stroke; }
#sld-panel .ln { stroke: #9cdbff; stroke-width: 1.4; fill: none; } #sld-panel .mv { stroke: #ffa050; }
#sld-panel .lv { stroke: #8cffa0; } #sld-panel .op { stroke: #ff5a4a; stroke-dasharray: 5 4; } #sld-panel .ea { stroke: #d8d89a; }
#sld-panel .dash { stroke-dasharray: 4 3; } #sld-panel [data-node$='.EARTH'] { cursor: pointer; }
#sld-panel .hl, #sld-panel .hl * { stroke: #c0ffff !important; stroke-width: 3 !important; }
#sld-panel text { fill: #9fb8cc; font: 10px system-ui, sans-serif; } #sld-panel .st { cursor: pointer; }
#sld-panel .st:hover .box { stroke: #fff; }
#sld-panel button { background: var(--panel, #111); color: var(--text, #cfe9ff); border: 1px solid var(--edge, #1c2c3a); border-radius: 4px;
min-height: var(--btn, 30px); padding: 0 9px; cursor: pointer; }
#sld-panel dl { display: grid; grid-template-columns: auto 1fr; gap: 2px 10px; margin: 0; font-variant-numeric: tabular-nums; }
#sld-panel dt { color: var(--text, #cfe9ff); } #sld-panel dd { margin: 0; color: var(--dim, #6f8ea6); }
@media (pointer: coarse) { #sld-panel { right: 8px; width: auto; max-height: 50vh; } }`;
const el = (tag, attrs = {}, parent = null) => {
const e = document.createElementNS(NS, tag);
for (const [k, v] of Object.entries(attrs)) e.setAttribute(k, v);
if (parent) parent.append(e);
return e;
};
// deps: { doc, onStation(id), onElement(nodeId) -> [[label, value]...], onClose() }
export function createSldView({ doc, onStation, onElement, onClose }) {
if (!doc.getElementById('sld-style')) { const s = doc.createElement('style'); s.id = 'sld-style'; s.textContent = CSS; doc.head.append(s); }
// Colour by voltage level and earth dashed, from the one table (elec-style.mjs); later than sld-style, so it wins.
if (!doc.getElementById('sld-elec-style')) { const s = doc.createElement('style'); s.id = 'sld-elec-style'; s.textContent = elecCss('#sld-panel'); doc.head.append(s); }
const panel = doc.createElement('section');
panel.id = 'sld-panel'; panel.className = 'panel'; panel.hidden = true; panel.setAttribute('aria-label', 'Single-line diagram');
panel.innerHTML = `<header><h2>Single-line diagram</h2><button type="button" id="sld-close">Close</button></header>
<p class="note" id="sld-note">Illustrative, not a design for any site. ${ELEC_FOOTER}</p><div class="scroll"></div><dl id="sld-readout" aria-live="polite"></dl>`;
doc.body.append(panel);
const box = panel.querySelector('.scroll'), dl = panel.querySelector('#sld-readout');
panel.querySelector('#sld-close').addEventListener('click', () => { panel.hidden = true; onClose?.(); });
let key = '', svg = null;
function rows(list) {
dl.replaceChildren(...list.flatMap(([k, v]) => { const dt = doc.createElement('dt'), dd = doc.createElement('dd'); dt.textContent = k; dd.textContent = v; return [dt, dd]; }));
}
function draw(src, version, { earth = false } = {}) {
if (key === version && svg) return;
key = version;
const sections = src.sections.map(s => ({ ...s, feeders: src.feeders.filter(f => f.section === s.id) }));
const width = Math.max(4, sections.reduce((t, s) => t + Math.max(1, s.feeders.length) + 1, 0)) * COL;
const depth = Math.max(1, ...src.feeders.map(f => f.hops.filter(h => !h.open).length));
const yLand = TOP, yHv = yLand + 70, yGt = yHv + 60, yBoard = yGt + 90, height = yBoard + 60 + depth * ROW + 30;
svg = el('svg', { width, height, viewBox: `0 0 ${width} ${height}`, role: 'img', 'aria-label': 'Single-line diagram of the plant' });
const hit = (g0, id, station) => { g0.dataset.node = id; if (station) { g0.classList.add('st'); g0.dataset.station = station; } return g0; };
const line = (p, x1, y1, x2, y2, cls = 'ln') => el('line', { x1, y1, x2, y2, class: cls }, p);
const text = (p, x, y, t, anchor = 'middle') => { const e = el('text', { x, y, 'text-anchor': anchor }, p); e.textContent = t; return e; };
const circle = (p, cx, cy, r, cls = 'ln') => el('circle', { cx, cy, r, class: cls }, p);
const earthMark = (p, x, y) => { for (const [w, dy] of [[12, 0], [8, 3], [4, 6]]) line(p, x - w / 2, y + dy, x + w / 2, y + dy, 'ln ea'); }; // earth, drawn our own way
// Sections and their feeder columns.
let x = COL / 2;
const secX = new Map(), colX = new Map();
for (const s of sections) {
const n = Math.max(1, s.feeders.length), x0 = x, x1 = x + (n - 1) * COL;
secX.set(s.id, [x0, x1]); s.feeders.forEach((f, j) => colX.set(f.id, x0 + j * COL));
const G = hit(el('g', {}, svg), s.id);
line(G, x0 - 20, yBoard, x1 + 20, yBoard, 'ln mv'); text(G, x0 - 20, yBoard - 6, s.id.replace('MVB', 'Section '), 'start');
const E = hit(el('g', {}, svg), `${s.id}.NET`); // earthing transformer + NER
const zig = [[-34, 10], [-38, 16], [-30, 22], [-38, 28], [-34, 34]].map(([dx, dy]) => `${x0 + dx},${yBoard + dy}`).join(' ');
line(E, x0 - 20, yBoard, x0 - 34, yBoard + 10, 'ln ea'); el('polyline', { points: zig, class: 'ln ea' }, E);
el('rect', { x: x0 - 38, y: yBoard + 36, width: 8, height: 10, class: 'ln ea' }, E); line(E, x0 - 34, yBoard + 34, x0 - 34, yBoard + 36, 'ln ea');
line(E, x0 - 34, yBoard + 46, x0 - 34, yBoard + 52, 'ln ea'); earthMark(E, x0 - 34, yBoard + 52); text(E, x0 - 34, yBoard + 70, 'NER');
x = x1 + 2 * COL;
}
sections.slice(1).forEach((s, i) => { // bus ties: open blades between sections
const a = secX.get(sections[i].id)[1] + 20, b = secX.get(s.id)[0] - 20, m = (a + b) / 2, G = hit(el('g', {}, svg), s.id);
line(G, a, yBoard, m - 8, yBoard, 'ln op'); line(G, m - 8, yBoard, m + 6, yBoard - 10, 'ln op'); line(G, m + 8, yBoard, b, yBoard, 'ln op');
text(G, m, yBoard + 14, 'N/O');
});
// Grid transformers over their sections, the plant-end HV busbar, the HV cable and the landing bay.
const gx = new Map();
for (const gt of src.grid) {
const mine = sections.filter(s => s.gt === gt.id).flatMap(s => secX.get(s.id)), cx = mine.length ? (Math.min(...mine) + Math.max(...mine)) / 2 : width / 2;
gx.set(gt.id, cx);
const G = hit(el('g', {}, svg), `${gt.id}.hv`);
circle(G, cx, yGt - 8, 12); circle(G, cx, yGt + 8, 12, 'ln mv'); text(G, cx + 18, yGt + 4, `${gt.id} ${gt.mva} MVA`, 'start');
if (earth) { line(G, cx - 12, yGt - 8, cx - 24, yGt - 8, 'ln ea'); line(G, cx - 24, yGt - 8, cx - 24, yGt, 'ln ea'); earthMark(G, cx - 24, yGt); } // star point
line(G, cx, yGt - 20, cx, yHv, 'ln'); line(G, cx - 5, yHv + 18, cx + 5, yHv + 24, 'ln'); // bay: disconnector mark
for (const s of sections.filter(q => q.gt === gt.id)) { const [a, b] = secX.get(s.id); line(G, cx, yGt + 20, (a + b) / 2, yBoard, 'ln mv'); }
}
const xs = [...gx.values()], hvA = Math.min(...xs, width / 2), hvB = Math.max(...xs, width / 2);
const H = hit(el('g', {}, svg), 'HVP'); line(H, hvA - 20, yHv, hvB + 20, yHv); text(H, hvA - 20, yHv - 6, `${src.hv.kv} kV plant-end bay`, 'start');
if (earth) { const Sg = hit(el('g', {}, svg), 'SUB.EARTH'), gx0 = Math.max(4, hvA - 96);
el('rect', { x: gx0, y: yHv + 8, width: 56, height: 22, class: 'ln ea dash' }, Sg); text(Sg, gx0 + 28, yHv + 23, 'earth grid');
text(svg, 8, height - 8, 'Earth: straw, dashed · click an earth mark for its readout', 'start'); }
const Lg = hit(el('g', {}, svg), 'LAND'); line(Lg, width / 2, yHv, width / 2, yLand + 18);
el('rect', { x: width / 2 - 16, y: yLand, width: 32, height: 18, class: 'ln' }, Lg);
const lw = { tower: 'line tower, overhead tee', 'gis-bay': 'substation bay', 'dno-sub': 'network operator substation', none: 'no nearby connection (assumed)' };
text(Lg, width / 2 + 22, yLand + 13, `${src.hv.kv} kV ${lw[src.hv.landing.kind] || lw['gis-bay']}, ${Math.round(src.hv.lengthM)} m`, 'start');
// Feeders: RMU under RMU, each station beside its RMU; a ring's open link dashed red.
const rmuY = new Map();
for (const f of src.feeders) {
const cx = colX.get(f.id);
let y = yBoard, k = 0;
text(svg, cx, yBoard + 22, f.id);
for (const [i, h] of f.hops.entries()) {
if (h.open) continue;
const to = h.to === 'board' ? null : h.to;
if (!to) continue;
const y2 = yBoard + 50 + k * ROW, B = el('g', { 'data-branch': `${f.id}.${i + 1}` }, svg);
line(B, cx, y, cx, y2 - 10, 'ln mv'); y = y2 + 10; k++;
rmuY.set(to, [cx, y2]);
const S = hit(el('g', {}, svg), `${to}.R`, to);
el('rect', { x: cx - 12, y: y2 - 12, width: 74, height: 60, fill: 'transparent', stroke: 'none', 'pointer-events': 'all' }, S); // the whole station taps
el('rect', { x: cx - 10, y: y2 - 10, width: 20, height: 20, class: 'ln mv box' }, S);
line(S, cx + 10, y2, cx + 30, y2, 'ln mv'); circle(S, cx + 38, y2 - 5, 7, 'ln mv'); circle(S, cx + 38, y2 + 5, 7, 'ln lv');
text(S, cx + 50, y2 + 3, to, 'start');
if (earth) { const Ea = hit(el('g', {}, svg), `${to}.EARTH`); line(Ea, cx + 38, y2 + 12, cx + 38, y2 + 22, 'ln ea dash'); earthMark(Ea, cx + 38, y2 + 22); }
// LV to the inverters (one box stands for them all), then their DC strings, in the DC colour.
line(S, cx + 33, y2 + 10, cx + 26, y2 + 20, 'ln lv'); el('rect', { x: cx + 22, y: y2 + 20, width: 8, height: 6, class: 'ln lv' }, S);
line(S, cx + 26, y2 + 26, cx + 26, y2 + 34, 'ln dc'); text(S, cx + 26, y2 + 44, 'DC');
}
}
for (const f of src.feeders) for (const [i, h] of f.hops.entries()) {
if (!h.open) continue;
const p = rmuY.get(h.from), q = rmuY.get(h.to === 'board' ? '' : h.to);
if (p && q) {
const B = el('g', { 'data-branch': `${f.id}.${i + 1}` }, svg);
el('path', { d: `M${p[0]},${p[1] + 10} C${p[0]},${p[1] + 40} ${q[0]},${q[1] + 40} ${q[0]},${q[1] + 10}`, class: 'ln op' }, B);
text(B, (p[0] + q[0]) / 2, Math.max(p[1], q[1]) + 44, 'N/O');
}
}
svg.addEventListener('click', e => {
const t = e.target.closest('[data-node], [data-branch]');
if (!t) return;
if (t.dataset.station) onStation?.(t.dataset.station);
rows(onElement?.(t.dataset.node || null, t.dataset.branch || null) || []);
});
box.replaceChildren(svg);
}
return {
element: panel,
show(src, version, opts = {}) { draw(src, version, opts); panel.hidden = false; },
hide() { panel.hidden = true; },
open: () => !panel.hidden,
rows,
// Follow: its nodes and branches glow here too.
highlight(nodes = [], branches = []) {
if (!svg) return;
const on = new Set([...nodes, ...branches]);
for (const e of svg.querySelectorAll('[data-node], [data-branch]')) e.classList.toggle('hl', on.has(e.dataset.node) || on.has(e.dataset.branch));
},
stations: () => (svg ? [...svg.querySelectorAll('[data-station]')].map(e => e.dataset.station) : [])
};
}String Design
A JavaScript module in the world folder of GlobalGrid2050 that works with solar.
transformglobalgrid2050 / solar-design-studio/202609271740-site-world/world/string-design.mjs · lines 1–58 of 58 · version 2026-09-27 17:40 · pattern stringCounts (shared by 3 files)
- What it does
- It calculates solar. Defines 6 functions or classes, including num, stringDesign, stringLine, stringWords, typedClass.
- Why it exists in the grid workflow
- Domain stage sub33kv_design (path word 'design'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. Domain terms in the code: solar.
- Downstream impact
- Used directly by 4 files: Block UI (globalgrid2050); Build Rules (globalgrid2050); Cmd Model (globalgrid2050); Hud Checks (globalgrid2050). Reached from 2 other entry points, including Solar Design Studio — Site World Page (globalgrid2050, https://globalgrid2050.com/solar-design-studio/202609271853-site-world/); Substrate (globalgrid2050).
- What it achieves
- It is built from the num step (`num`), the string design helper (`stringDesign`) and the string line helper (`stringLine`). The string voltage of the solar block, worked out in the open.
- Why it matters
- Imported by 4 files, including Block UI, Build Rules and Cmd Model.
- Application
- globalgrid2050 · solar-design-studio/202609271740-site-world/world · JavaScript module
- Uses
- Module Catalogue (import)
- Used by
- imported by Block UI (import), imported by Build Rules (import), imported by Cmd Model (import), imported by Hud Checks (import)
- Produces
- STRING_ADVICE, ILLUSTRATIVE, BORDERLINE_PCT, stringDesign, stringLine, stringWords, typedClass, stringCounts
- Defines here
- num, stringDesign, stringLine, stringWords, typedClass, stringCounts
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-design-studio/202609271740-site-world/world/string-design.mjs:1-58 · blob d546c518116dbddd97a8676a80a03c575efc7cec · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: production_core
// string-design.mjs: the string voltage of the solar block, worked out in the open. Owner's instruction (27 Sept): show
// the truth, don't expose people. Modules in series and the site's coldest cell temperature are the owner's to change
// (typed "string 28", "temp min -10", or the block panel); the cold open-circuit voltage is worked out for every power
// bin of the module class (any bin may be delivered, so the string is judged on the highest), with the headroom under
// the system voltage said in volts. Illustrative: early design, no warranty; the advisory below always goes with it.
// Pure: no DOM, no fetch.
import { coldVocOf, highestVoc, VOC_FACTOR } from './module-catalogue.mjs';
export const STRING_ADVICE = 'Study string voltages in detail: get module-maker and inverter-maker sign-off, or a chartered engineer\'s '
+ 'review if borderline, or use fewer modules in series for over-voltage headroom.';
export const ILLUSTRATIVE = 'Illustrative — early design, no warranty; confirm with a qualified engineer.';
export const BORDERLINE_PCT = 3; // headroom under this share of the system voltage is called borderline (an assumption, editable)
const num = v => (v === null || v === undefined || v === '' ? NaN : Number(v));
/**
* stringDesign({ cls, cat, mps, tempMinC, systemV }) -> { mps, tempMinC, systemV, bins, worst, stringV, headroomV, ok, borderline, most }
* cls: a module class (module-catalogue.mjs); cat: the catalogue (coldest_cell_C, system_voltage_V are its defaults).
*/
export function stringDesign({ cls, cat = {}, mps, tempMinC, systemV } = {}) {
if (!cls || !(mps > 0)) return null;
const t = Number.isFinite(num(tempMinC)) ? num(tempMinC) : cat.coldest_cell_C ?? -10, V = num(systemV) > 0 ? num(systemV) : cat.system_voltage_V || 1500;
// Each bin two ways (the coldest cell, and Voc x 1.15); the stricter is the sizing value (module-catalogue.mjs coldVocOf).
const bins = cls.electrical.bins.map(b => { const c = coldVocOf({ voc: b.voc, coeffPctPerK: cls.temp_coeff.voc, tC: t });
return { pmax: b.pmax, voc: b.voc, vocCold: c.v, byTemp: c.byTemp, byFactor: c.byFactor, rule: c.rule, stringV: c.v * mps }; });
const hi = highestVoc(cls), worst = bins.find(b => b.pmax === hi.pmax && b.voc === hi.voc), stringV = worst.stringV, headroomV = V - stringV;
return { mps, tempMinC: t, systemV: V, bins, worst, stringV, headroomV, ok: stringV <= V, borderline: stringV <= V && headroomV < V * BORDERLINE_PCT / 100,
most: Math.floor(V / worst.vocCold + 1e-9), rule: worst.rule };
}
/** The HUD line: red when over, neutral with the headroom when under. */
export function stringLine(d) {
const v = Math.round(d.stringV), tail = `@ ${d.rule === `Voc × ${VOC_FACTOR}` ? `VOC × ${VOC_FACTOR} (STRICTER THAN ${d.tempMinC}°C)` : `${d.tempMinC}°C`}`
+ ` · ${d.worst.pmax} W BIN · ${d.mps} MOD`;
return d.ok ? `STRING VOC ${v} V · ${Math.floor(d.headroomV)} V HEADROOM${d.borderline ? ' (BORDERLINE)' : ''} ${tail}`
: `STRING VOC ${v} V > ${d.systemV} V ${tail}`;
}
/** The block readout's words: every bin's cold Voc, the string, the headroom, the most in series. */
export function stringWords(d) {
const bins = d.bins.map(b => `${b.pmax} W ${b.vocCold.toFixed(1)} V`).join(' · ');
return {
bins: `one module, the stricter of ${d.tempMinC} °C and Voc × ${VOC_FACTOR} (${d.rule} governs): ${bins}`,
string: `${d.mps} in series: ${Math.round(d.stringV)} V (highest bin, ${d.worst.pmax} W) against ${d.systemV} V · `
+ (d.ok ? `${Math.floor(d.headroomV)} V headroom${d.borderline ? ', borderline' : ''}` : `OVER by ${Math.ceil(-d.headroomV)} V`)
+ ` · at most ${d.most} in series on this rule`
};
}
/** A one-bin module class from typed values (a plant with a typed module Voc and power), for stringDesign. */
export const typedClass = ({ wp, voc, coeffPctPerK }) => ({ id: 'typed', electrical: { bins: [{ pmax: wp, voc }], nominal_W: wp }, temp_coeff: { voc: coeffPctPerK } });
/** Strings and inverters for a count of modules: whole strings, modules left over, inverters to connect every string. */
export function stringCounts({ modules, mps, stringsPerInverter = 24, inverters = null }) {
const strings = Math.floor(modules / mps), need = Math.ceil(strings / stringsPerInverter);
return { strings, leftover: modules - strings * mps, invertersNeeded: need, spare: inverters === null ? null : Math.max(0, strings - inverters * stringsPerInverter) };
}Xray UI
A JavaScript module in the world folder of GlobalGrid2050 that draws trench sections, solar and cables.
renderglobalgrid2050 / solar-design-studio/202609271740-site-world/world/xray-ui.mjs · lines 1–70 of 70 · version 2026-09-27 17:40 · pattern showNote (shared by 2 files)
- What it does
- It draws trench sections, solar and cables. Defines 6 functions or classes, including $el, mountXray, works, extra, showNote. Side effects: changes the web page (DOM); makes network requests.
- Why it exists in the grid workflow
- Domain stage sub33kv_design (path word 'design'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. Domain terms in the code: solar, cables.
- Inputs & outputs
- In: JSON file trench-sections.json.
- Downstream impact
- Used directly by 1 file: Cmd Mount (globalgrid2050). Reached from 2 other entry points, including Solar Design Studio — Site World Page (globalgrid2050, https://globalgrid2050.com/solar-design-studio/202609271853-site-world/); Substrate (globalgrid2050).
- What it achieves
- It shows note (`showNote`) and is built from the el step (`$el`) and the mount xray helper (`mountXray`). The As-built X-ray switch, in the Layers panel and typed ("xray on", "xray off"). It responds to click events.
- Why it matters
- Imported by Cmd Mount.
- Application
- globalgrid2050 · solar-design-studio/202609271740-site-world/world · JavaScript module
- Uses
- Xray (dynamic import)
- Used by
- imported by Cmd Mount (dynamic import)
- Produces
- mountXray
- Defines here
- $el, mountXray, works, extra, showNote, set
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-design-studio/202609271740-site-world/world/xray-ui.mjs:1-70 · blob 922b9a71c7f62bca1fe6baf03c7450f0cb7e91cd · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, network · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: production_core
// xray-ui.mjs: the As-built X-ray switch, in the Layers panel and typed ("xray on", "xray off"). It is small and loads just
// after the first frame (cmd-mount.mjs); the drawing (xray.mjs) and the section catalogue load the first time it is
// switched on. While on, every frame goes through xrayFilter (substrate hooks.filter): the ground drawn faint, the
// buried works bright. Nothing asks for frames on its own: a still view stays at 0 fps.
//
// What it draws: the solar block's trenches as sized by rating (world.block.works()) and every trench drawn in Design.
const $el = (doc, tag, props = {}) => Object.assign(doc.createElement(tag), props);
// deps: { api (substrate extension api: hooks.filter, heightAt, origin(), state(), design(), gate), world (window.world) }
export function mountXray({ api, world, doc = document, host = doc.getElementById('layers-slot') }) {
let on = false, mod = null, sections = null, cache = { key: '', batches: [], text: '' };
const box = $el(doc, 'fieldset', { className: 'sun-time xray-box' });
box.append($el(doc, 'legend', { textContent: 'As built' }));
const btn = $el(doc, 'button', { type: 'button', id: 'xray-toggle', textContent: 'X-ray: buried trenches, ducts and cables',
title: 'See through the ground: trenches, ducts, cables, draw pits and joint bays after backfill (type xray on)' });
btn.setAttribute('aria-pressed', 'false');
const note = $el(doc, 'p', { className: 'note' }); note.setAttribute('aria-live', 'polite');
box.append(btn, note);
host?.appendChild(box);
// The runs to draw, in local metres: the block's sized trenches and the Design trenches, with pits and joint bays.
function works() {
const o = api.origin(), L = p => [p.e - o.e, p.n - o.n], runs = [], pits = [], joints = [], drawn = api.design()?.trenches || [];
const b = world.block?.works?.();
if (b) {
for (const t of b.items) runs.push({ path: t.path.map(L), section: t.section, cableOdMm: t.cableOdMm });
for (const p of b.pits) pits.push({ at: L(p.at) });
for (const j of b.joints) joints.push({ at: L(j.at), w: j.widthM });
}
for (const t of drawn) {
const s = sections?.find(x => x.id === t.section);
if (s && Array.isArray(t.path)) runs.push({ path: t.path.map(L), section: s, cableOdMm: null });
}
return { runs, pits, joints, totals: b?.totals ?? null, faults: b?.faults ?? [], key: `${o.id}:${b?.version ?? 'none'}:${drawn.length}` };
}
function extra(pos) {
const w = works(), cell = `${Math.round(pos[0] / 200)},${Math.round(pos[1] / 200)}`, key = `${w.key}:${cell}`;
if (key !== cache.key) {
const base = [Math.round(pos[0] / 100) * 100, Math.round(pos[1] / 100) * 100, Math.round(api.heightAt(pos[0], pos[1]))];
const lines = mod.buriedLines(w.runs, { groundAt: api.heightAt, eye: pos, pits: w.pits, joints: w.joints, base });
cache = { key, batches: mod.xrayBatches(lines, { base, version: key }), text: mod.xraySummary(w.runs, w.pits, w.joints, w.totals), faults: w.faults };
if (on) showNote(); // the note follows every re-size (split, soil, cover), not only xray on
}
return cache.batches;
}
function showNote() {
note.replaceChildren(cache.text, ...(cache.faults || []).map(f => $el(doc, 'span', { className: 'fault', textContent: ` ${f}` })));
}
api.hooks.filter?.add((batches, ctx) => (on && mod ? mod.xrayFilter(batches, extra(ctx.pos)) : batches));
async function set(v) {
v = !!v;
if (v && !mod) {
mod = await import('./xray.mjs');
try { sections = (await (await fetch(new URL('./world/data/trench-sections.json', location.href), { cache: 'no-cache' })).json()).sections; }
catch { sections = []; }
}
on = v; cache.key = '';
btn.setAttribute('aria-pressed', String(on));
api.gate.invalidate();
if (!on) { note.textContent = ''; return 'X-ray off: the ground is drawn as before.'; }
extra(api.state().pos);
showNote();
const faults = (cache.faults || []).map(f => `\n${f}`).join('');
return `${cache.text} Illustrative — early design, no warranty; confirm with a qualified engineer. Not an as-built survey.${faults}`;
}
btn.addEventListener('click', () => { set(!on).catch(e => { note.textContent = 'X-ray: ' + e.message; }); });
return { set, on: () => on, debug: () => ({ on, key: cache.key, batches: cache.batches.map(b => ({ key: b.key, vertices: b.positions.length / 3 })) }) };
}