In this section
- Cmd UI interaction · globalgrid2050 / solar-design-studio/202609271853-site-world/world/cmd-ui.mjs lines 1–151
- Design Sections electrical · globalgrid2050 / solar-design-studio/202609271853-site-world/world/design-sections.mjs lines 1–214
Cmd UI
A JavaScript module in the world folder of GlobalGrid2050 that draws cables, trench sections, overhead lines (OHL) and solar.
interactionglobalgrid2050 / solar-design-studio/202609271853-site-world/world/cmd-ui.mjs · lines 1–151 of 151 · version 2026-09-27 18:53 · pattern replay (shared by 12 files)
- What it does
- It draws cables, trench sections, overhead lines (OHL) and solar. Defines 15 functions or classes, including readKept, writeKept, createCommandLine, data, moduleClass. 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 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: cables, overhead lines (OHL), solar.
- Inputs & outputs
- In: JSON file cables.json; JSON file trench-sections.json; JSON file modules.json; browser storage (getItem); form fields (user input). Out: browser storage (setItem). Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid).
- 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 reads kept (`readKept`), writes kept (`writeKept`) and creates command line (`createCommandLine`). The command line over the world. It responds to click, keydown and input events.
- Why it matters
- Imported by Cmd Mount.
- Application
- globalgrid2050 · solar-design-studio/202609271853-site-world/world · JavaScript module
- Uses
- Cmd Model (import), Cmd Run (import), Cmd Anim (import), Cmd Grammar (import), Bng (import)
- Used by
- imported by Cmd Mount (dynamic import)
- Produces
- createCommandLine
- Defines here
- readKept, writeKept, createCommandLine, data, moduleClass, $, say, drawChips, next, run, lift, mark, open, close, replay
- 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/202609271853-site-world/world/cmd-ui.mjs:1-151 · blob ff266f28d8ff2db7c059a18fb7cc82b507453c24 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, network, storage · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: production_core
// cmd-ui.mjs: the command line over the world. One input: type a command and press Enter; the world changes and the line
// under it says what changed. Up and Down recall earlier commands (the last 50 kept in this browser), Tab takes the first
// suggestion, Escape closes. On a phone the same bar sits along the bottom with suggestion chips above it.
// Loaded the first time the bar is opened (cmd-mount.mjs), never before the first frame.
import { createSession } from './cmd-model.mjs';
import { createEngine } from './cmd-run.mjs';
import { createAnim } from './cmd-anim.mjs';
import { search } from './cmd-grammar.mjs';
import { tmInverse } from './bng.mjs';
const KEEP = 'world.cmd.history', MAX = 50;
const CHIPS = ['plant 50mw south', 'pitch 7', 'tilt 20', 'trench depth 1.1', 'cable 400 al', 'wiring leapfrog', 'piles auto', 'show pylons', 'earthing show', 'undo', 'help'];
const CSS = `
#cmd { position: fixed; left: 50%; transform: translateX(-50%); bottom: calc(var(--foot) + 8px); width: min(620px, calc(100vw - 16px));
box-sizing: border-box; background: var(--panel); border: 1px solid var(--edge); border-radius: 6px; padding: 6px; display: grid; gap: 6px; z-index: 3; }
#cmd[hidden] { display: none; }
#cmd canvas { width: 100%; height: 150px; display: block; border-bottom: 1px solid var(--edge); }
#cmd canvas[hidden] { display: none; }
#cmd-log { max-height: 128px; overflow: auto; margin: 0; font: 12px/1.45 ui-monospace, Consolas, monospace; color: var(--dim); white-space: pre-wrap; }
#cmd-log:empty { display: none; }
#cmd-log .in { color: var(--text); } #cmd-log .out { color: var(--line); } #cmd-log .no { color: #ff8a7a; }
#cmd-chips { display: flex; gap: 4px; overflow-x: auto; scrollbar-width: none; }
#cmd-chips button { flex: none; background: none; color: var(--dim); border: 1px solid var(--edge); border-radius: 12px; padding: 2px 9px; cursor: pointer;
font: 11px system-ui, sans-serif; min-height: 24px; white-space: nowrap; }
#cmd-chips button:hover { color: var(--text); border-color: var(--line); }
#cmd .bar { display: flex; gap: 6px; align-items: center; }
#cmd .bar span { color: var(--line); font: 14px ui-monospace, Consolas, monospace; }
#cmd-input { flex: 1; min-width: 0; min-height: var(--btn); box-sizing: border-box; background: #111; color: var(--text); border: 1px solid var(--edge);
border-radius: 4px; padding: 0 8px; font: 13px ui-monospace, Consolas, monospace; }
#cmd-input:focus { outline: none; border-color: var(--line); }
#cmd .bar button { background: var(--panel); color: var(--dim); border: 1px solid var(--edge); border-radius: 4px; min-height: var(--btn); padding: 0 10px; cursor: pointer; }
@media (pointer: coarse) {
#cmd { left: 8px; right: 8px; width: auto; transform: none; } #cmd canvas { height: 120px; } #cmd-log { max-height: 84px; }
body[data-cmd] #pad, body[data-cmd] #lift, body[data-cmd] #help-toggle { display: none !important; }
#cmd-input { font-size: 16px; } /* 16 px or more: a phone does not zoom the page when the bar takes focus */
}`;
const readKept = () => { try { const v = JSON.parse(localStorage.getItem(KEEP) || '[]'); return Array.isArray(v) ? v.filter(s => typeof s === 'string') : []; } catch { return []; } };
const writeKept = h => { try { localStorage.setItem(KEEP, JSON.stringify(h.slice(-MAX))); } catch { /* private window: history is kept for this visit only */ } };
// deps: { api, world, ohl, doc, onChange() the script changed (the design is saved with it), toggle: the dash button }
export async function createCommandLine({ api, world, ohl, doc = document, onChange = () => {}, toggle = null }) {
const data = f => fetch(new URL(`./world/data/${f}`, location.href), { cache: 'no-cache' }).then(r => (r.ok ? r.json() : null)).catch(() => null);
const [catalogue, sections, modules] = await Promise.all([data('cables.json'), data('trench-sections.json').then(j => j?.sections || []), data('modules.json')]);
// The plant's module is the selected class (Module detail), the one the solar block uses: one string-voltage answer.
const moduleClass = () => { const id = world.module?.debug?.()?.class || 'A', c = modules?.classes?.find(x => x.id === id);
return c ? { wp: c.electrical.nominal_W, voc: Math.max(...c.electrical.bins.map(b => b.voc)), coeffPctPerK: c.temp_coeff.voc } : null; };
const o = world.origin(), latDeg = o.e || o.n ? tmInverse(o.e, o.n).lat * 180 / Math.PI : 51.8;
const session = createSession({ engine: createEngine({ world, api, ohl, doc }), env: { latDeg, catalogue, sections, moduleClass } });
const style = doc.createElement('style'); style.textContent = CSS; doc.head.appendChild(style);
const box = doc.createElement('section');
box.id = 'cmd'; box.hidden = true; box.setAttribute('aria-label', 'Command line');
box.innerHTML = '<canvas id="cmd-anim" hidden aria-hidden="true"></canvas><pre id="cmd-log" aria-live="polite"></pre><div id="cmd-chips" role="list"></div>'
+ '<div class="bar"><span aria-hidden="true">›</span><input id="cmd-input" type="text" enterkeyhint="go" autocapitalize="off" autocomplete="off" '
+ 'spellcheck="false" inputmode="text" aria-label="Command" placeholder="Type a command, e.g. plant 50mw south, then Enter">'
+ '<button type="button" id="cmd-run">Run</button><button type="button" id="cmd-close" aria-label="Close the command line">×</button></div>';
doc.body.appendChild(box);
const $ = id => doc.getElementById(id), input = $('cmd-input'), log = $('cmd-log'), chips = $('cmd-chips'), canvas = $('cmd-anim');
const anim = createAnim(canvas);
const hist = readKept();
let at = hist.length, busy = false, lastDone = null;
function say(line, text, ok) {
const a = doc.createElement('span'), b = doc.createElement('span');
a.className = 'in'; a.textContent = `› ${line}\n`; b.className = ok ? 'out' : 'no'; b.textContent = `${text}\n`;
log.append(a, b);
while (log.childNodes.length > 60) log.firstChild.remove();
log.scrollTop = log.scrollHeight;
}
function drawChips() {
const q = input.value.trim(), list = q ? search(q, 6).map(c => c.usage.split(' · ')[0]) : CHIPS;
chips.replaceChildren(...list.map(s => {
const b = doc.createElement('button'); b.type = 'button'; b.textContent = s; b.setAttribute('role', 'listitem');
b.addEventListener('click', () => { input.value = s; drawChips(); input.focus(); if (!q) run(s); });
return b;
}));
}
// Lines typed while one is still running wait their turn, in order (the bar stays open for typing: a phone keyboard is
// never closed under the thumb by a disabled input), each resolved when it has run.
const waiting = [];
const next = () => { if (!busy && waiting.length) { const w = waiting.shift(); run(w.line, true).then(w.done); } };
async function run(text, queued = false) {
const line = String(text ?? input.value).trim();
if (!line) return null;
if (!queued) { if (hist[hist.length - 1] !== line) { hist.push(line); writeKept(hist); } at = hist.length; if (text == null || input.value.trim() === line) input.value = ''; }
if (busy) { const p = new Promise(done => waiting.push({ line, done })); say(line, `queued (${waiting.length} waiting): runs when the line before it is done`, true); return p; }
busy = true;
let r;
try {
// Extra handlers first (api.hooks.commands: line -> reply | promise | null): build mode's "build ...", the buggy's words.
for (const f of api.hooks?.commands || []) if ((r = await f(line))) break;
r ||= await session.exec(line);
} catch (e) { r = { ok: false, text: e.message, line }; }
finally { busy = false; }
say(line, r.text, r.ok);
if (r.ok && r.anim) { canvas.hidden = false; anim.play(r.anim, r.before, r.d); }
if (r.ok && !r.quiet) onChange();
lastDone = { line, ok: r.ok, text: r.text, anim: r.anim || null };
drawChips();
if (!box.hidden && doc.activeElement !== input) input.focus();
setTimeout(next);
return r;
}
// Keys typed in the bar stay in the bar: the walk keys (W, A, S, D, F, Q, Space) never reach the world.
for (const ev of ['keydown', 'keyup', 'keypress']) box.addEventListener(ev, e => { if (e.key !== 'Escape') e.stopPropagation(); });
input.addEventListener('keydown', e => {
if (e.key === 'Enter') { e.preventDefault(); run(); return; }
if (e.key === 'Escape') { e.preventDefault(); close(); return; }
if (e.key === 'ArrowUp' && at > 0) { e.preventDefault(); input.value = hist[--at]; }
else if (e.key === 'ArrowDown') { e.preventDefault(); at = Math.min(hist.length, at + 1); input.value = hist[at] || ''; }
else if (e.key === 'Tab' && input.value.trim()) { const s = search(input.value.trim(), 1)[0]; if (s) { e.preventDefault(); input.value = s.usage.split(' · ')[0]; } }
else return;
drawChips();
});
input.addEventListener('input', drawChips);
$('cmd-run').addEventListener('click', () => run());
$('cmd-close').addEventListener('click', () => close());
// A phone keyboard covers the bottom of the screen: the bar rides above it.
const vv = globalThis.visualViewport;
const lift = () => { if (!vv || box.hidden) return; const k = Math.max(0, innerHeight - vv.height - vv.offsetTop); box.style.bottom = k ? `${k + 4}px` : ''; };
vv?.addEventListener('resize', lift);
// --cmd-top: how far the bar's top edge sits above the bottom of the screen, so cards along the bottom (Follow) sit above it.
const mark = () => { const t = box.hidden ? 0 : Math.max(0, innerHeight - box.getBoundingClientRect().top); doc.documentElement.style.setProperty('--cmd-top', `${Math.round(t)}px`); };
if (globalThis.ResizeObserver) new ResizeObserver(mark).observe(box);
vv?.addEventListener('resize', mark);
function open() {
const dt = doc.getElementById('design-toggle'); // the bar takes the Design panel's place (its button lives there)
if (dt?.getAttribute('aria-expanded') === 'true') dt.click();
box.hidden = false; doc.body.dataset.cmd = '1'; toggle?.setAttribute('aria-expanded', 'true');
drawChips(); input.focus(); lift(); mark();
}
function close() {
box.hidden = true; delete doc.body.dataset.cmd; toggle?.setAttribute('aria-expanded', 'false');
anim.stop(); canvas.hidden = true; input.blur(); (doc.getElementById('view') || doc.body).focus?.(); mark();
}
// Opening a design with a script replays it: the plant, block and trench choices come back from the typed lines.
async function replay(lines) {
if (!Array.isArray(lines) || !lines.length) return [];
busy = true;
let out = [];
try { out = await session.replay(lines); } finally { busy = false; setTimeout(next); }
const bad = out.filter(r => !r.ok);
say(`replay ${lines.length} lines`, bad.length ? `${bad.length} line(s) refused: ${bad.map(r => r.text).join(' | ')}` : `Rebuilt from the typed script. ${out.at(-1)?.text || ''}`, !bad.length);
return out;
}
return { open, close, toggle: () => (box.hidden ? open() : close()), run, replay, script: session.script, session,
debug: () => ({ open: !box.hidden, busy, waiting: waiting.map(w => w.line), last: lastDone, animating: anim.running(), anim: anim.kind(), script: session.script(), history: session.history() }) };
}Design Sections
A JavaScript module in the world folder of GlobalGrid2050 that loads plant (`loadPlant`) and block (`loadBlock`), loads cables (`loadCables`) and reads inputs for spec source, spec and ground condition.
electricalglobalgrid2050 / solar-design-studio/202609271853-site-world/world/design-sections.mjs · lines 1–214 of 214 · version 2026-09-27 18:53 · Not reached from any entry point (candidate for review) · pattern createSections (shared by 2 files)
- What it does
- It lists and searches cables, solar, 33kV and substations. Defines 14 functions or classes, including cableBox, cableTubes, createSections, $, once. 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: cables, solar, 33kV, substations, 400kV, 275kV.
- Inputs & outputs
- In: user-supplied file (file picker); form fields (user input). Voltage levels named: 400kV, 275kV, 132kV, 33kV.
- Downstream impact
- Used directly by 1 file: Design UI (globalgrid2050).
- What it achieves
- It creates sections (`createSections`), loads options (`loadOptions`) and loads plant (`loadPlant`). The parts of the Design panel that follow a specification, kept out of `design-ui.mjs`. Its code works with 10 MVA, 33 kV and 10 MW. It responds to click and toggle events.
- Why it matters
- Imported by Design UI.
- Application
- globalgrid2050 · solar-design-studio/202609271853-site-world/world · JavaScript module
- Uses
- Spec Rules (import), Trench Section (import), Trench (import), Measure Format (import), Design Tabs (import), Design Options (dynamic import), Plant UI (dynamic import), Block UI (dynamic import), and 1 more
- Used by
- imported by Design UI (import)
- Produces
- cableBox, cableTubes, createSections, nearRuns
- Defines here
- cableBox, cableTubes, createSections, $, once, loadOptions, loadPlant, loadBlock, loadCables, spec, effOf, cross, nearRuns, close
- 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/202609271853-site-world/world/design-sections.mjs:1-214 · blob 1d743fe3069cceae4f5215b89c41e992b68a4b85 · 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
// design-sections.mjs: the parts of the Design panel that follow a specification, kept out of design-ui.mjs.
// Options specification, ground condition (alluvium) and the generic MV network (design-options.mjs)
// Plant layout a plant laid out inside a drawn boundary on the measured ground (plant-ui.mjs)
// Solar block the 10 MVA station block, built in sequence and ringed to the grid (block-ui.mjs)
// Each loads the first time its section opens (or its world.plant / world.block call is made), so none of it is on
// the first frame. Until Options loads, trenches are dug to the network operator spec in normal ground.
// Close to the viewer every trench shows its true cross-section and every cable its outside diameter.
import { OPERATOR_SPEC, applyGround, looseSpoil } from './spec-rules.mjs';
import { crossSection, sectionLines, tubeLines } from './trench-section.mjs';
import { createTrench } from './trench.mjs';
import { formatLength, formatVolume } from './measure-format.mjs';
import { mountDesignTabs } from './design-tabs.mjs';
// The sections' markup, put into the Design panel when this module loads (after the first frame), so world.html
// stays light: the Plant tab gains the specification, ground and MV network, and Plant layout and Solar block folds.
const OPTIONS_HTML = `
<label>Specification <select id="spec-source">
<option value="operator">Network operator spec</option>
<option value="project">Project specification (local file)</option>
<option value="example">Example specification (made-up values)</option>
</select></label>
<input type="file" id="spec-file" accept=".json,application/json" hidden>
<label>Ground condition <select id="ground-condition"><option value="normal">Normal ground</option></select></label>
<details class="fold" id="mv-fold"><summary>MV network (generic)</summary>
<label>Plant size (MW) <input type="number" id="mv-mw" min="1" max="5000" step="1" value="50"></label>
<label>Route file, drawing coordinates (optional) <input type="file" id="mv-routes-file" accept=".json,application/json"></label>
<label>Metres per drawing unit <input type="number" id="mv-scale" min="0.001" step="any" value="1"></label>
<div class="row">
<button type="button" id="mv-place">Place MV network here</button>
<button type="button" id="mv-clear">Clear network</button>
</div>
</details>
<p id="spec-status" role="status"></p>`;
const SECTIONS_HTML = `
<details class="fold" id="plant"><summary>Plant layout</summary>
<div class="row" id="plant-presets" hidden role="group" aria-label="Capacity presets">
<button type="button" data-mw="10">10 MW</button><button type="button" data-mw="100">100 MW</button>
<button type="button" data-mw="500">500 MW</button><button type="button" data-mw="1000">1000 MW</button>
</div>
<label>Capacity, export (MW) <input type="number" id="plant-mw" min="1" max="5000" step="1" value="100"></label>
<label>Layout <select id="plant-layout"></select></label>
<label>Slope limit (%) <input type="number" id="plant-slope" min="1" max="40" step="1" value="15"></label>
<label>Tables inside the fence (m, 5 to 10) <input type="number" id="plant-fence" min="5" max="10" step="0.5" value="8"></label>
<div class="row" role="group" aria-label="Plant boundary">
<button type="button" data-tool="boundary" aria-pressed="false">Draw boundary</button>
<button type="button" id="plant-open">Use the open land around me</button>
</div>
<div class="row">
<button type="button" id="plant-run">Lay out</button>
<button type="button" id="plant-clear">Clear layout</button>
</div>
<div class="row"><button type="button" id="plant-sld">Single-line diagram</button></div>
<p id="plant-status" role="status"></p>
<dl id="plant-readout" aria-live="polite"></dl>
</details>
<details class="fold" id="block"><summary>Solar block (10 MVA station)</summary>
<label>Stations on the 33 kV rings (1 to 10) <input type="number" id="block-stations" min="1" max="10" step="1" value="4"></label>
<label>Grid connection <select id="block-poc"><option value="auto" selected>by plant size</option><option value="400">400 kV</option><option value="275">275 kV</option>
<option value="132">132 kV</option></select></label>
<label>Modules in series (10 to 40) <input type="number" id="block-mps" min="10" max="40" step="1" value="30"></label>
<label>Coldest cell temperature (°C) <input type="number" id="block-tmin" min="-40" max="15" step="1" value="-10"></label>
<div class="row">
<button type="button" id="block-place">Place block here</button>
<button type="button" id="block-clear">Clear block</button>
</div>
<div class="row"><button type="button" id="block-gpu" hidden title="The GPU study's placement on open-land-01, illustrative">GPU-checked placement</button>
<button type="button" id="block-export" hidden aria-pressed="false"
title="The GPU study's 33 kV export route to the nearest substation, illustrative">Export route (GPU-checked, illustrative)</button></div>
<div class="row"><button type="button" id="block-sld">Single-line diagram</button>
<button type="button" id="block-follow" title="From a solar module to the grid landing; or tap any module">Follow a module</button></div>
<div class="row" role="group" aria-label="Build sequence">
<button type="button" id="block-play">Play</button><button type="button" id="block-pause">Pause</button>
<button type="button" id="block-step">Step</button>
</div>
<p id="block-stage" aria-live="polite"></p>
<p id="block-status" role="status"></p>
<dl id="block-readout" aria-live="polite"></dl>
<details class="fold" id="block-cables"><summary>Cable checks (illustrative)</summary><div id="cables-box"></div></details>
</details>`;
const NEAR_M = 25; // full cross-sections within this distance of the viewer; beyond, only the trench outline
// The box [minX, minY, maxX, maxY] round a cable's cores, and its tubes near the eye, appended point by point.
export function cableBox(c) {
let x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity;
for (const core of c.cores || []) for (const p of core.polyline) { x0 = Math.min(x0, p[0]); y0 = Math.min(y0, p[1]); x1 = Math.max(x1, p[0]); y1 = Math.max(y1, p[1]); }
return x0 <= x1 ? [x0, y0, x1, y1] : null;
}
export function cableTubes(c, eye) {
const v = [];
for (const core of c.cores) for (const run of nearRuns(core.polyline, eye, NEAR_M)) { // only the stretches near the eye (v08.1 hotfix)
const t = tubeLines(run, c.spec.od_mm / 1000, { eye, near: NEAR_M });
for (let j = 0; j < t.length; j++) v.push(t[j]);
}
return v;
}
const COLOUR = { section: [0.95, 0.9, 0.7, 1], cable: [0.55, 1, 0.62, 1] };
// deps: { doc, origin(), viewer(), measuredAt(x, y), heightAt(x, y) designed ground, baseHeight(x, y) layers' ground,
// assets() -> grid equipment in reach, nearest(e, n) -> Promise<substation | null> (national index), redraw(),
// animate() (the block's build sequence started or stopped), onChange() (the specification or ground changed) }
export function createSections({ doc, origin, viewer, measuredAt, heightAt, baseHeight, assets = () => [], nearest = null,
redraw, release = () => false, animate = () => {}, onChange = () => {}, ohlZones = () => null }) {
const $ = id => doc.getElementById(id);
if (!$('spec-source')) ($('design-spec') || $('design-options'))?.insertAdjacentHTML('beforeend', OPTIONS_HTML);
if (!$('plant')) ($('design-spec') ? $('design-spec').insertAdjacentHTML('afterend', SECTIONS_HTML)
: ($('phases-fold') || $('design-profile-box'))?.insertAdjacentHTML('beforebegin', SECTIONS_HTML));
let options = null, plant = null, block = null;
const loading = {};
const once = (name, load) => (loading[name] ||= load().catch(e => { loading[name] = null; console.warn(`${name}: ${e.message}`); return null; }));
const loadOptions = () => once('options', async () => {
const { createOptions } = await import('./design-options.mjs');
options = createOptions({ doc, viewer, heightAt, redraw, onChange });
onChange();
return options;
});
const loadPlant = () => once('plant', async () => {
const { createPlant } = await import('./plant-ui.mjs');
return (plant = createPlant({ doc, origin, viewer, measuredAt: measuredAt || baseHeight, heightAt, assets, nearest, redraw, release, ohlZones }));
});
const loadBlock = () => once('block', async () => {
const { createBlock } = await import('./block-ui.mjs');
block = createBlock({ doc, origin, viewer, measuredAt: measuredAt || baseHeight, heightAt: baseHeight, redraw, animate,
towers: () => assets().filter(a => a.kind === 'tower' && Number.isFinite(a.kv)) });
return block;
});
$('design-options-toggle')?.addEventListener('click', () => loadOptions());
// Build, Measure, Plant, Share (design-tabs.mjs): the specification and ground load when Plant first opens.
const tabs = mountDesignTabs(doc, { onFirstOpen: { plant: () => loadOptions() } });
$('plant')?.addEventListener('toggle', e => { if (e.target.open) loadPlant(); });
$('block')?.addEventListener('toggle', e => { if (e.target.open) loadBlock(); });
// A click on Place before the block cartridge has arrived (it loads when the fold opens) is kept, not lost.
$('block-place')?.addEventListener('click', e => { if (block) return; e.stopImmediatePropagation(); loadBlock().then(b => b?.place({ frame: true })); }, true);
// The cable schedule as illustrative checks (cable-checks-ui.mjs): loaded the first time its fold opens.
let cables = null;
const loadCables = () => once('cables', async () => (cables = await (await import('./cable-checks-ui.mjs')).mountCableChecks({ doc, box: $('cables-box') })));
$('block-cables')?.addEventListener('toggle', e => { if (e.target.open) loadCables(); });
const spec = () => options?.spec() || OPERATOR_SPEC, ground = () => options?.ground() || 'normal';
// The trench as it will be dug: the section, under the chosen specification and ground condition.
const effOf = section => applyGround(section, spec(), ground());
const cross = (section, eff, cableOdMm) => crossSection(section, eff, { cableOdMm, tapeAboveM: spec().marker.tape_above_service_m });
return {
effOf, cross,
// Readout rows for the specification and ground, and the loose spoil once the bank volume is known.
rows: eff => [['Specification', eff.specLabel], ['Ground', eff.groundLabel], ['Support', eff.support],
['Working width', formatLength(eff.workingWidth)], ...eff.notes.map((n, i) => [i ? '' : 'Notes', n])],
spoilRows: (spoil, eff) => (eff.bulking > 1 && spoil ? [['Spoil, loose', formatVolume(looseSpoil(spoil, eff), 2)]] : []),
// The solar block's open trenches (they cut the ground like any other) and a key that changes when they do.
key: () => block?.key() || '',
extra(toLocalPts) {
const list = block?.trenchItems() || [];
const eff = list.map(t => effOf(t.section));
return { trenches: list.map((t, i) => createTrench({ path: toLocalPts(t.path), width: eff[i].width, depth: eff[i].depth,
benchSlope: eff[i].benchSlope })), sections: list.map((t, i) => cross(t.section, eff[i], t.cableOdMm)) };
},
// Close up: true cross-sections and cable tubes, rebuilt when the viewer moves a few metres.
// b: design-ui's build ({ key, trenches, sections, cables, near }); batch(key, version, positions, colour).
detail(b, batch) {
const out = [], eye = viewer().pos, k = `${b.key}:${Math.round(eye[0] / 4)}:${Math.round(eye[1] / 4)}:${Math.round(eye[2] / 4)}`;
b.trenches.forEach((t, i) => {
const x = t.bbox;
if (!x || !b.sections[i] || eye[0] < x.minX - NEAR_M || eye[0] > x.maxX + NEAR_M || eye[1] < x.minY - NEAR_M || eye[1] > x.maxY + NEAR_M) return;
if (b.near[i]?.k !== k) b.near[i] = { k, v: sectionLines({ trench: t, groundAt: baseHeight, cs: b.sections[i], eye, near: NEAR_M }) };
out.push(batch('design-section-' + i, k, b.near[i].v, COLOUR.section));
});
// Cables: culled by their box within NEAR_M, and appended by a loop (a spread of a long cable's tube overflowed the
// call stack every frame: RangeError, a frozen view).
b.cables.forEach((c, i) => {
const x = c.bbox ||= cableBox(c);
if (!x || eye[0] < x[0] - NEAR_M || eye[0] > x[2] + NEAR_M || eye[1] < x[1] - NEAR_M || eye[1] > x[3] + NEAR_M) return;
if (b.near['c' + i]?.k !== k) b.near['c' + i] = { k, v: cableTubes(c, eye) };
if (b.near['c' + i].v.length) out.push(batch('design-cable-' + i, k, b.near['c' + i].v, COLOUR.cable));
});
return out;
},
batches: () => [...(options?.batches() || []), ...(plant?.batches() || []), ...(block?.batches() || [])],
// The Boundary tool (in Plant layout) hands its closed outline over on Done.
setBoundary: async path => !!(await loadPlant())?.setBoundary(path),
animating: () => !!block?.animating(),
snapshot: () => ({ options: options?.snapshot() || { spec: spec().label, source: spec().source, ground: ground(), network: null },
plant: plant?.snapshot() || null, block: block?.snapshot() || null }),
plantApi: Object.freeze({ run: async params => (await loadPlant())?.run(params) ?? null, openLand: async params => (await loadPlant())?.useOpenLand(params),
summary: () => plant?.snapshot() || null, result: () => plant?.result() ?? null, extentM: () => plant?.extentM() ?? 0, lod: () => plant?.lod() ?? null,
pack: () => plant?.pack() ?? null, frame: block => plant?.frame(block) ?? null, version: () => plant?.version() ?? 0, boundary: () => plant?.boundary() ?? null,
setBoundary: async path => !!(await loadPlant())?.setBoundary(path), clear: () => plant?.clear() }),
// Piles are automatic from the plant's and the block's tables; auto() reruns them (typed "piles auto").
pilesApi: Object.freeze({ auto: async opts => ({ plant: (await plant?.pilesAuto(opts)) ?? null, block: block?.snapshot()?.piles ?? null }),
summary: () => ({ plant: plant?.snapshot()?.piles ?? null, block: block?.snapshot()?.piles ?? null }) }),
// Billed: the automatic plant and block piles, and the block's trenches sized by rating (trench-plan.mjs).
boqItems: () => [...(plant?.boqItems() || []), ...(block?.boqItems() || []),
...(block?.works() ? [{ id: 'block-trenches', kind: 'trenchPlan', stages: block.trenchStages() }] : [])],
tabs,
blockApi: Object.freeze({ place: async params => (await loadBlock())?.place(params), placeGpu: async () => (await loadBlock())?.placeGpu(),
play: () => block?.play() ?? false, pause: () => block?.pause(),
step: () => block?.step(), clear: () => block?.clear(), counts: () => block?.counts() ?? null, state: () => block?.snapshot() ?? null,
built: () => block?.built?.() ?? null,
strings: async p => (await loadBlock())?.strings(p) ?? null, stringDesign: () => block?.stringDesign() ?? null, // the placed block, its anchor and version (sld-mount.mjs)
cables: async () => { await loadCables(); return cables; },
works: () => block?.works() ?? null, trenchRows: () => block?.trenchRows() ?? null, bounds: () => block?.bounds() ?? null })
};
}
// Pure: the stretches of a polyline within near metres (plan distance) of the eye, each with one point either side,
// so a long cable route only builds tubes where the viewer can see them.
export function nearRuns(pl, eye, near) {
const runs = []; let cur = null; const n2 = near * near;
const close = p => (p[0] - eye[0]) ** 2 + (p[1] - eye[1]) ** 2 <= n2;
for (let i = 0; i < pl.length; i++) {
const inside = close(pl[i]) || (i + 1 < pl.length && close(pl[i + 1])) || (i > 0 && close(pl[i - 1]));
if (inside) { if (!cur) { cur = []; runs.push(cur); } cur.push(pl[i]); } else cur = null;
}
return runs.filter(r => r.length > 1);
}