GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Solar and storage design / globalgrid2050 / solar-design-studio/202609270330-site-world-v3/world

Block UI and 4 more files

A JavaScript module in the world folder of GlobalGrid2050 that draws GPU compounds, 33kV, cables and overhead lines (OHL). It creates block (`createBlock`), places gpu (`placeGpu`) and shows gpu (`showGpu`).

496 lines of JavaScript from globalgrid2050, in 5 files. Topic: Solar and storage design. Section 143 of 2044.

Cut 2026-12-06T03:07:51+00:00. A copy for reading; the repository at the stated commit is the source.

In the State lines below, domain stage, users and canonical status are rule-based first approximations from code and path evidence (rules explore-agent-rules-v1), not observed facts: the rules.

In this section

  1. Block GPU ingest · globalgrid2050 / solar-design-studio/202609270330-site-world-v3/world/block-gpu.mjs lines 1–108
  2. Block UI interaction · globalgrid2050 / solar-design-studio/202609270330-site-world-v3/world/block-ui.mjs lines 1–235
  3. Design Tabs interaction · globalgrid2050 / solar-design-studio/202609270330-site-world-v3/world/design-tabs.mjs lines 1–43
  4. First Showing interaction · globalgrid2050 / solar-design-studio/202609270330-site-world-v3/world/first-showing.mjs lines 1–87
  5. Help render · globalgrid2050 / solar-design-studio/202609270330-site-world-v3/world/help.mjs lines 1–23

Block GPU

A JavaScript module in the world folder of GlobalGrid2050 that fetches cables and solar, using SHA-256. It loads prototype (`loadPrototype`), parses prototype (`parsePrototype`) and builds feed (`buildFeed`).

Set aside from the main view: 96% of its lines are the same as solar-design-studio/202609271740-site-world/world/block-gpu.mjs (globalgrid2050), which stays. (near-copy-of, proposed by families.py). 95% of lines shared with Block GPU; read that one first. All set-aside files, with reasons. Nothing was deleted.

Evidence
  • line-jaccard 0.9565 to globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-design-studio/202609271740-site-world/world/block-gpu.mjs:1-111 24b7d69641427ff699c66630e8be324743a43d3e
  • sha256 de6c81cba7b58bd43530ba5248d88f3411eeafd888cd4328bcec8244b7560ce6
  • target sha256 badf7113d6659fece7e75198cb53a0be599a6f77d5a885d521e369b4d7313930
  • group of 2 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines

ingestglobalgrid2050 / solar-design-studio/202609270330-site-world-v3/world/block-gpu.mjs · lines 1–108 of 108 · version 2026-09-27 03:30 · Not reached from any entry point (candidate for review) · pattern parsePrototype (shared by 2 files)

What it does
It fetches cables and solar. Defines 13 functions or classes, including hex, sha256, loadPrototype, parsePrototype, flat. Side effects: 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: cables, solar.
Inputs & outputs
In: JSON file index.json.
Downstream impact
Used directly by 1 file: Block UI (globalgrid2050).
What it achieves
Design > Solar block > GPU-checked placement.
Why it matters
Imported by Block UI.
Application
globalgrid2050 · solar-design-studio/202609270330-site-world-v3/world · JavaScript module
Uses
none found
Used by
imported by Block UI (dynamic import), mentioned in Standalone (comment link)
Produces
GPU_LABEL, GPU_DIR, TABLE_LIFT_M, WORDS, COLORS, loadPrototype, parsePrototype, buildFeed, countAt, feedStage
Defines here
hex, sha256, loadPrototype, parsePrototype, flat, buildFeed, z, add, seg, line, post, countAt, feedStage
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/202609270330-site-world-v3/world/block-gpu.mjs:1-108 · blob aa2007891173126f8fdc65b71d59939c27a5701c · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: network · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: duplicate_candidate
// block-gpu.mjs: Design > Solar block > GPU-checked placement. The prototype's generic station as the GPU study placed
// it on open-land-01 (gpu-night agent A, round 10: least-slope placement off the tower zones and line corridors,
// origin 399560.4, 209785.7, heading -15 degrees), with its pile reveal and table twist flags and its ordered build
// (prototype-sequence.json) as the Sequential feed that the block's Play, Pause and Step drive.
// ILLUSTRATIVE: the placement rule, the tolerances and the rates are the study's assumptions; not a design, not a
// site selection. Files are staged by tools/stage-gpu-prototype.mjs into sites/<site>/gpu-prototype/ (local, git-
// ignored) with an index that names each file's SHA-256; every file is checked against it before use.
// Pure except loadPrototype (which is given its fetch and digest). National-grid metres (e, n, height ODN).

export const GPU_LABEL = 'GPU-checked placement, illustrative: the prototype station placed by an assumed least-slope rule; ' +
  'tolerances and rates assumed. Not a design or a site selection.';
export const GPU_DIR = 'gpu-prototype';
export const TABLE_LIFT_M = 1.0, PILE_POST_M = 1.2, POST_M = 2.5, STEP_M = 2; // drawing only (assumed heights)
export const WORDS = Object.freeze({
  'station-pad-earthworks': 'Station pad levelled', piles: 'Piles driven', table: 'Tables built', 'trench-dug': 'Trenches dug',
  'inverter-set': 'Inverters set', 'dc-cables-pulled': 'DC cables pulled', 'ac-cables-pulled': 'AC cables pulled', 'station-set': 'Transformers set'
});
export const COLORS = Object.freeze({
  'station-pad-earthworks': [0.95, 0.97, 1, 0.9], piles: [0.75, 0.75, 0.78, 0.8], table: [0.62, 0.72, 0.86, 0.85],
  'table-flag': [1, 0.55, 0.25, 1], 'trench-dug': [0.7, 0.6, 0.5, 0.9], 'inverter-set': [0.95, 0.97, 1, 1],
  'dc-cables-pulled': [0.35, 0.8, 1, 0.9], 'ac-cables-pulled': [0.55, 1, 0.62, 0.9], 'station-set': [1, 0.72, 0.35, 1]
});

const hex = buf => [...new Uint8Array(buf)].map(b => b.toString(16).padStart(2, '0')).join('');
const sha256 = async bytes => hex(await globalThis.crypto.subtle.digest('SHA-256', bytes));

// Reads sites/<site>/gpu-prototype/index.json and each file it names, checked against its SHA-256. -> { layout, sequence }
export async function loadPrototype(site, { get = (u, o) => fetch(u, o), base = './world/sites/', digest = sha256 } = {}) {
  const dir = `${base}${site}/${GPU_DIR}/`, r = await get(dir + 'index.json', { cache: 'no-cache' });
  if (!r.ok) throw Error(`no GPU-checked placement staged for ${site}`);
  const index = await r.json(), out = {};
  for (const f of index.files || []) {
    const res = await get(dir + f.file, { cache: 'no-cache' });
    if (!res.ok) throw Error(`${f.file}: HTTP ${res.status}`);
    const bytes = await res.arrayBuffer(), h = await digest(bytes);
    if (h !== f.sha256) throw Error(`${f.file}: hash ${h.slice(0, 12)} is not the index's ${String(f.sha256).slice(0, 12)}`);
    out[f.role] = JSON.parse(new TextDecoder().decode(bytes));
  }
  if (!out.layout || !out.sequence) throw Error('the GPU placement index names no layout or sequence');
  return out;
}

// Pure: the files -> { origin, heading, slope, tol, flags, tables, steps, hours, bbox }. receipt (optional): the study's
// r10 receipt, for its pile reveal flag count and assumed tolerances.
export function parsePrototype(layout, sequence, receipt = null) {
  if (layout?.schema !== 'gpu-night-a.prototype-layout/1' || sequence?.schema !== 'gpu-night-a.prototype-sequence/1') throw Error('not a GPU prototype layout and sequence');
  const pl = layout.placement, tol = sequence.twist_tol_deg ?? layout.twist_tol_deg ?? 1;
  const tables = (layout.tables || []).map(t => ({ table: t.table, twist: t.twist_deg?.electron, twistPositron: t.twist_deg?.positron,
    reveal: t.reveal_m, embedMin: t.embed_min_m, flagged: Math.abs(t.twist_deg?.electron ?? 0) > tol }));
  const steps = sequence.steps.filter(s => WORDS[s.kind] && s.geometry).map(s => ({ kind: s.kind, id: s.id, t0: s.t_start_h, t1: s.t_end_h, geometry: s.geometry,
    flagged: s.kind === 'table' && Math.abs(s.twist_deg ?? 0) > tol }));
  const all = steps.flatMap(s => flat(s.geometry));
  const e = all.map(p => p[0]), n = all.map(p => p[1]);
  return { origin: pl.origin_bng, heading: pl.heading_deg, slope: pl.mean_slope_pct, photons: pl.photons || [], tol, tables, steps,
    flags: { twisted: tables.filter(t => t.flagged).length, reveal: receipt?.piles?.ILLUSTRATIVE_flags?.reveal_outside_adjustment ?? null,
      piles: receipt?.piles?.count ?? null, revealAdjust: receipt?.assumed?.reveal_adjust_m ?? null }, hours: Math.max(...steps.map(s => s.t1)), receipt: layout.receipt?.body_sha256,
    bbox: { e0: Math.min(...e) - 10, n0: Math.min(...n) - 10, e1: Math.max(...e) + 10, n1: Math.max(...n) + 10 } };
}
function flat(g) {
  if (g.type === 'Point') return [g.coordinates];
  if (g.type === 'MultiPoint' || g.type === 'LineString') return g.coordinates;
  if (g.type === 'Polygon' || g.type === 'MultiLineString') return g.coordinates.flat();
  return [];
}

// Pure: the steps as line groups, one a kind, in national-grid metres relative to each group's base; marks[i] is the
// vertex count once the group's i-th step is drawn and ends[i] its finish hour, so the feed draws a prefix.
// ground(e, n): measured ground or NaN. A 2D point off measured ground is left out (never a guessed height).
export function buildFeed(p, ground) {
  const groups = {};
  let unmeasured = 0;
  const z = (q, lift) => { if (q.length >= 3) return q[2] + lift; const h = ground(q[0], q[1]); if (!Number.isFinite(h)) unmeasured++; return h + lift; };
  const add = (key, t1) => (groups[key] ||= { key, base: null, v: [], marks: [], ends: [] });
  const seg = (G, a, b) => { if (![a[2], b[2]].every(Number.isFinite)) return; G.base ||= a; for (const q of [a, b]) G.v.push(q[0] - G.base[0], q[1] - G.base[1], q[2] - G.base[2]); };
  const line = (G, pts, lift) => {
    for (let i = 1; i < pts.length; i++) {
      const a = pts[i - 1], b = pts[i], k = a.length >= 3 && b.length >= 3 ? 1 : Math.max(1, Math.ceil(Math.hypot(b[0] - a[0], b[1] - a[1]) / STEP_M));
      for (let j = 0; j < k; j++) {
        const pa = [a[0] + (b[0] - a[0]) * j / k, a[1] + (b[1] - a[1]) * j / k], pb = [a[0] + (b[0] - a[0]) * (j + 1) / k, a[1] + (b[1] - a[1]) * (j + 1) / k];
        if (k === 1 && a.length >= 3) seg(G, [a[0], a[1], a[2] + lift], [b[0], b[1], b[2] + lift]); else seg(G, [...pa, z(pa, lift)], [...pb, z(pb, lift)]);
      }
    }
  };
  const post = (G, q, h) => { const b = z(q, 0); seg(G, [q[0], q[1], b], [q[0], q[1], b + h]); };
  for (const s of p.steps) {
    const G = add(s.flagged ? 'table-flag' : s.kind), g = s.geometry;
    if (g.type === 'Polygon') line(G, g.coordinates[0], s.kind === 'table' ? TABLE_LIFT_M : 0);
    else if (g.type === 'LineString') line(G, g.coordinates, 0);
    else if (g.type === 'MultiLineString') for (const c of g.coordinates) line(G, c, 0);
    else if (g.type === 'MultiPoint') for (const q of g.coordinates) post(G, q, PILE_POST_M);
    else if (g.type === 'Point') post(G, g.coordinates, POST_M);
    G.marks.push(G.v.length / 3); G.ends.push(s.t1);
  }
  for (const G of Object.values(groups)) G.v = new Float32Array(G.v);
  return { groups: Object.values(groups).filter(G => G.base), unmeasured };
}

// Pure: vertices of group G drawn by hour h (every step finished by then).
export function countAt(G, h) {
  let n = 0;
  for (let i = 0; i < G.ends.length && G.ends[i] <= h + 1e-9; i++) n = G.marks[i];
  return n;
}
// Pure: the step running at hour h, in words.
export function feedStage(p, h) {
  const s = p.steps.find(x => h < x.t1) || p.steps.at(-1), done = p.steps.filter(x => x.t1 <= h + 1e-9).length;
  return `Step ${Math.min(done + 1, p.steps.length)} of ${p.steps.length}: ${WORDS[s.kind]} (${s.id}), hour ${Math.round(Math.min(h, p.hours))} of ${Math.round(p.hours)}`;
}

Block UI

A JavaScript module in the world folder of GlobalGrid2050 that draws GPU compounds, 33kV, cables and overhead lines (OHL). It creates block (`createBlock`), places gpu (`placeGpu`) and shows gpu (`showGpu`).

interactionglobalgrid2050 / solar-design-studio/202609270330-site-world-v3/world/block-ui.mjs · lines 1–235 of 235 · version 2026-09-27 03:30 · Not reached from any entry point (candidate for review) · pattern refreshItems (shared by 2 files)

What it does
It draws GPU compounds, 33kV, cables and overhead lines (OHL). Defines 31 functions or classes, including n0, createBlock, $, say, local. 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: 33kV, cables, overhead lines (OHL).
Inputs & outputs
In: JSON file gpu-compounds.json. Voltage levels named: 33kV.
Downstream impact
Used directly by 1 file: Design Sections (globalgrid2050).
What it achieves
Design > Solar block. Places the owner's 10MVA station block (`block-build.mjs`) on the measured ground in front of the viewer, chains the stations on 33kV rings to the grid, and plays the build sequence (`block-sequence.mjs`). Its code works with 33 kV and 10 MVA. It responds to click events.
Why it matters
Imported by Design Sections.
Application
globalgrid2050 · solar-design-studio/202609270330-site-world-v3/world · JavaScript module
Uses
Origin (import), Block Build (import), Block MV (import), Block Sequence (import), Plant Ground (import), Measure Format (import), Block GPU (dynamic import)
Used by
imported by Design Sections (dynamic import), mentioned in Standalone (comment link)
Produces
BLOCK_LABEL, createBlock
Defines here
n0, createBlock, $, say, local, gpuPads, place, measured, fallback, placeGpu, gpuCounts, gpuHour, gpuBatches, showGpu, cableGroup, o3, prefix, upto, pulling, batches, whole, tick, refreshItems, play, pause, step, clear, counts, showReadout, run
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/202609270330-site-world-v3/world/block-ui.mjs:1-235 · blob 2356047556c34798a85be93f5fd211934ead0274 · 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: unreached_review
// block-ui.mjs: Design > Solar block. Places the owner's 10 MVA station block (block-build.mjs) on the measured ground
// in front of the viewer, chains the stations on 33 kV rings to the grid, and plays the build sequence
// (block-sequence.mjs): Play runs the clock and asks the page for frames at 30 fps; Pause and Step stop the clock,
// so no frame is drawn until something else changes (0 fps). Everything is held in national-grid metres; each line
// group keeps its positions relative to its own base, so a move of the site origin only moves the base.
// Trenches are handed to the design (trenchItems), which cuts them into the ground and draws their cross-sections.

import { toBng } from './origin.mjs';
import { buildBlock, blockCounts, overheadClearance } from './block-build.mjs';
import { mvChain } from './block-mv.mjs';
import { createClock, progress, reveal, partial, stageAt, STAGES, TOTAL } from './block-sequence.mjs';
import { createSiteGround } from './plant-ground.mjs';
import { formatNumber, formatLength } from './measure-format.mjs';
let G = null; // block-gpu.mjs, imported on first use so the section opens as fast as before

export const BLOCK_LABEL = 'Illustrative, not a design for any site.';
const C = { outline: [0.75, 0.75, 0.75, 0.45], tables: [0.62, 0.72, 0.86, 0.8], strings: [0.4, 0.62, 0.95, 0.75], inverters: [0.95, 0.97, 1, 1],
  station: [0.95, 0.97, 1, 1], others: [0.6, 0.67, 0.78, 0.45], rmu: [1, 0.72, 0.35, 1], open: [1, 0.36, 0.3, 1], grid: [0.95, 0.97, 1, 1],
  dc: [0.55, 0.62, 0.7, 1], dcLive: [0.35, 0.8, 1, 1], ac: [0.6, 0.6, 0.62, 1], acLive: [0.55, 1, 0.62, 1], mv: [0.7, 0.6, 0.55, 1],
  mvLive: [1, 0.55, 0.25, 1] };
const FPS = 30, CLEAR_M = 40; // CLEAR_M: tables kept this far from an overhead line (assumed; the line owner sets the easement)
const n0 = x => formatNumber(x, 0), n1 = x => formatNumber(x, 1), n2 = x => formatNumber(x, 2);

// deps: { doc, origin(), viewer(), measuredAt(x, y) local, heightAt(x, y) local, towers() -> [{ e, n, kv }], redraw(), animate() }
export function createBlock({ doc, origin, viewer, measuredAt, heightAt, towers = () => [], redraw, animate = () => {} }) {
  const $ = id => doc.getElementById(id);
  const ground = createSiteGround(), clock = createClock();
  const state = { built: null, version: 0, anchor: null, busy: false, stageShown: -1, full: {}, gpuPads: null, playing: false, gpu: null };
  const say = (msg, warn = false) => { const el = $('block-status'); el.textContent = msg; el.className = warn ? 'warn' : ''; };
  const local = (e, n) => [e - origin().e, n - origin().n];

  async function gpuPads() {                                // optional, read-only: station and compound pads from the GPU run
    if (state.gpuPads) return state.gpuPads;
    state.gpuPads = [];
    try {
      const site = (await ground.start()).site?.name, r = await fetch(`./world/sites/${site}/gpu-compounds.json`, { cache: 'no-cache' });
      const j = r.ok ? await r.json() : null;
      if (j?.schema === 'gpu-night-a.compounds/1') state.gpuPads = (j.compounds || []).filter(c => Array.isArray(c.poly) && Number.isFinite(c.level_e))
        .map(c => ({ poly: c.poly, level: c.level_e, cut: c.cut_e, fill: c.fill_e }));
    } catch { /* none staged: the world's own pad earthworks */ }
    return state.gpuPads;
  }

  async function place() {
    if (state.busy) return null;
    state.busy = true; $('block-place').disabled = true;
    try {
      const v = viewer(), c = toBng(origin(), v.pos[0], v.pos[1]), stations = Math.min(10, Math.max(1, Math.round(Number($('block-stations').value) || 4)));
      const pocKv = Number($('block-poc').value) || 400, lines = towers();
      // The viewer stands in the first aisle, facing north; where an overhead line would cross the tables the block
      // steps east (60 m at a time, up to 1.2 km) until every table is at least CLEAR_M from it.
      let anchor = [c.e - 16, c.n + 12], moved = 0;
      for (let k = 0; k <= 20; k++) {
        const o = overheadClearance([anchor[0] + 60 * k, anchor[1]], stations, lines);
        if (!o || o.distanceM >= CLEAR_M) { moved = 60 * k; break; }
      }
      anchor = [anchor[0] + moved, anchor[1]];
      const mv = mvChain({ stations, pocKv }), e1 = anchor[0] + mv.compound.x + mv.compound.w, n1 = anchor[1] + mv.rows * 800;
      say('Reading the measured ground under the block…');
      await ground.loadFor({ e0: anchor[0] - 40, n0: anchor[1] - 80, e1, n1 }).catch(() => null);
      const sample = ground.sampler();
      const measured = (e, n) => { const h = sample(e, n); if (Number.isFinite(h)) return h; const [x, y] = local(e, n); return measuredAt(x, y); };
      const fallback = (e, n) => { const [x, y] = local(e, n); return heightAt(x, y); };
      state.gpu = null;
      const b = buildBlock({ anchor, ground: measured, fallback, stations, pocKv, towers: lines, gpuPads: await gpuPads() });
      for (const k of ['dc', 'ac', 'mv']) state.full[k] = cableGroup(b.cables[k], k === 'mv' ? null : 'inverter');
      state.built = b; state.anchor = anchor; state.version++; state.stageShown = -1;
      clock.finish(); refreshItems(); showReadout(b); redraw();
      say(`${BLOCK_LABEL} Placed${moved ? `, ${moved} m east of you to keep ${CLEAR_M} m from the overhead line` : ''}. Play builds it in sequence.`);
      return counts();
    } catch (e) { say(e.message, true); return null; }
    finally { state.busy = false; $('block-place').disabled = false; }
  }

  // GPU-checked placement (block-gpu.mjs): the study's prototype station where the GPU placed it, its build as the feed.
  async function placeGpu() {
    if (state.busy) return null;
    state.busy = true;
    try {
      const site = (await ground.start()).site?.name;
      say('Reading the GPU-checked placement…');
      G ||= await import('./block-gpu.mjs');
      const f = await G.loadPrototype(site), p = G.parsePrototype(f.layout, f.sequence, f.receipt);
      await ground.loadFor(p.bbox).catch(() => null);
      const sample = ground.sampler(), measured = (e, n) => { const h = sample(e, n); if (Number.isFinite(h)) return h; const [x, y] = local(e, n); return measuredAt(x, y); };
      state.built = null; state.gpu = { p, feed: G.buildFeed(p, measured) }; state.version++; state.stageShown = -1;
      clock.finish(); refreshItems(); showGpu(state.gpu); redraw();
      say(G.GPU_LABEL);
      return gpuCounts();
    } catch (e) { say(e.message, true); return null; }
    finally { state.busy = false; }
  }
  const gpuCounts = () => (state.gpu ? { steps: state.gpu.p.steps.length, groups: state.gpu.feed.groups.length, twisted: state.gpu.p.flags.twisted,
    reveal: state.gpu.p.flags.reveal, unmeasured: state.gpu.feed.unmeasured } : null);
  const gpuHour = () => clock.t() / TOTAL * state.gpu.p.hours;
  function gpuBatches() {
    const h = gpuHour(), out = [];
    for (const g of state.gpu.feed.groups) out.push(prefix('gpu-' + g.key, { v: g.v, base: g.base }, G.countAt(g, h), G.COLORS[g.key]));
    const s = G.feedStage(state.gpu.p, h);
    if (s !== state.stageShown) { state.stageShown = s; $('block-stage').textContent = s; }
    if (state.playing && !clock.playing()) { state.playing = false; clock.pause(); animate(); say(`${G.GPU_LABEL} Built.`); }
    return out.filter(Boolean);
  }
  function showGpu({ p, feed }) {
    const v = viewer(), c = toBng(origin(), v.pos[0], v.pos[1]), n = k => p.steps.filter(s => s.kind === k).length;
    const tw = p.tables.map(t => t.twist).filter(Number.isFinite), f = p.flags;
    const rows = [['Placed at', `${n1(p.origin[0])} E, ${n1(p.origin[1])} N · heading ${n0(p.heading)}° · ${formatLength(Math.hypot(p.origin[0] - c.e, p.origin[1] - c.n))} from you`],
      ['Mean slope', `${n2(p.slope.electron)} % (checked pair ${n2(p.slope.positron)} %)${p.photons.length ? ` · ${p.photons.length} disagreement (${p.photons.join(', ')}), counted` : ''}`],
      ['Tables', `${p.tables.length} · twist ${n2(Math.min(...tw))} to ${n2(Math.max(...tw))}° · ${f.twisted} over the assumed ${n1(p.tol)}° (drawn orange)`],
      ['Piles', f.piles ? `${n0(f.piles)} · ${f.reveal} with a reveal outside the assumed ±${n2(f.revealAdjust)} m adjustment` : 'reveal flags not staged'],
      ['Build feed', `${p.steps.length} steps over ${n0(p.hours)} working hours (assumed rates): ${Object.keys(G.WORDS).map(k => `${n(k)} ${G.WORDS[k].toLowerCase()}`).join(', ')}`],
      ['Ground', feed.unmeasured ? `${n0(feed.unmeasured)} points off the measured tiles were left out` : 'all on measured LiDAR ground'],
      ['Basis', G.GPU_LABEL + (p.receipt ? ` Receipt ${p.receipt.slice(0, 12)}.` : '')]];
    $('block-readout').replaceChildren(...rows.flatMap(([k, t]) => { const dt = doc.createElement('dt'), dd = doc.createElement('dd'); dt.textContent = k; dd.textContent = t; return [dt, dd]; }));
  }

  // All cables of a kind as one line group; marks per inverter (DC, AC) or per circuit (MV).
  function cableGroup(list, by) {
    const v = [], marks = [], base = list[0].points[0];
    list.forEach((c, i) => {
      for (let k = 1; k < c.points.length; k++) for (const p of [c.points[k - 1], c.points[k]]) v.push(p[0] - base[0], p[1] - base[1], p[2] - base[2]);
      if (!by || i === list.length - 1 || list[i + 1][by] !== c[by]) marks.push(v.length / 3);
    });
    return { base, v: new Float32Array(v), marks, items: by ? [...new Set(list.map(c => c[by]))].map(k => list.filter(c => c[by] === k)) : list.map(c => [c]) };
  }

  // ---- drawing: a prefix of each group for the time on the clock ----
  const o3 = base => [base[0] - origin().e, base[1] - origin().n, base[2]];
  const prefix = (key, G, count, color) => (count > 0 && G.v.length ? { key: 'block-' + key, version: `${state.version}:${count}`,
    positions: G.v.subarray(0, count * 3), color, origin: o3(G.base) } : null);
  const upto = (G, whole) => (whole > 0 ? G.marks[Math.min(whole, G.marks.length) - 1] : 0);
  function pulling(key, F, r, color) {                      // the item being pulled in now: its cables so far
    if (!r.part || r.whole >= F.items.length) return null;
    const v = [], base = F.base;
    for (const c of F.items[r.whole]) {
      const pts = partial(c.points, r.part);
      for (let k = 1; k < pts.length; k++) for (const p of [pts[k - 1], pts[k]]) v.push(p[0] - base[0], p[1] - base[1], p[2] - base[2]);
    }
    return v.length ? { key: 'block-pull-' + key, version: `${state.version}:${r.whole}:${r.part.toFixed(4)}`, positions: new Float32Array(v), color, origin: o3(base) } : null;
  }
  function batches() {
    if (state.gpu) return gpuBatches();
    const b = state.built;
    if (!b) return [];
    const P = progress(clock.t()), G = b.groups, out = [];
    const whole = (k, f) => upto(G[k], reveal(G[k].marks.length, f).whole);
    out.push(prefix('outline', G.outline, upto(G.outline, 1), C.outline), prefix('others', G.others, G.others.v.length / 3, C.others));
    out.push(prefix('tables', G.tables, whole('tables', P.tables), C.tables), prefix('strings', G.strings, whole('strings', P.strings), C.strings));
    out.push(prefix('inverters', G.inverters, whole('inverters', P.inverters), C.inverters));
    const live = P.station >= 1, grid = P.grid >= 1;
    for (const [k, f, col] of [['dc', P.dc, live ? C.dcLive : C.dc], ['ac', P.ac, live ? C.acLive : C.ac], ['mv', P.mv, grid ? C.mvLive : C.mv]]) {
      const F = state.full[k], r = reveal(F.items.length, f);
      out.push(prefix(k, F, upto(F, r.whole), col), pulling(k, F, r, col));
    }
    if (P.station > 0) out.push(prefix('station', G.station, upto(G.station, 1), C.station));
    if (P.mv > 0) out.push(prefix('rmu', G.rmu, G.rmu.v.length / 3, C.rmu));
    if (P.mv >= 1) out.push(prefix('open', G.open, G.open.v.length / 3, C.open));
    if (P.grid > 0) out.push(prefix('grid', G.grid, G.grid.v.length / 3, grid ? C.mvLive : C.grid));
    tick(); refreshItems();
    return out.filter(Boolean);
  }
  // While playing: say the stage when it changes; at the end, stop asking for frames.
  function tick() {
    const s = stageAt(clock.t());
    if (s.index !== state.stageShown) { state.stageShown = s.index; $('block-stage').textContent = `Stage ${s.index + 1} of ${STAGES.length}: ${s.label}`; }
    if (state.playing && !clock.playing()) { state.playing = false; clock.pause(); animate(); say(`${BLOCK_LABEL} Built and energised.`); }
  }

  // Trenches open once their stage starts: DC and AC during the first stage, the ring trenches with the 33 kV stage.
  // Called once a frame (batches) and on every control, never from the ground lookups: those only read items.
  let items = { key: '', list: [] }, dcac = [], mvT = [];
  function refreshItems() {
    const b = state.built;
    if (!b) { if (items.key) items = { key: '', list: [] }; return; }
    if (items.version !== state.version) { dcac = b.trenches.filter(t => t.stage !== 'mv'); mvT = b.trenches.filter(t => t.stage === 'mv'); }
    const P = progress(clock.t()), n = Math.min(dcac.length, reveal(dcac.length, P.trenches).whole + (P.trenches > 0 ? 1 : 0));
    const k = `${state.version}:${n}:${P.mv > 0}`;
    if (k !== items.key) items = { key: k, version: state.version, list: [...dcac.slice(0, n), ...(P.mv > 0 ? mvT : [])] };
  }

  // ---- controls ----
  function play() {
    if (!state.built && !state.gpu) { say('Place the block first.', true); return false; }
    clock.play(); state.playing = true; refreshItems(); animate(); redraw(); return true;
  }
  function pause() { clock.pause(); state.playing = false; refreshItems(); animate(); redraw(); }
  function step() { if (!state.built && !state.gpu) return; clock.step(); state.playing = false; refreshItems(); animate(); redraw(); }
  function clear() {
    state.built = null; state.gpu = null; state.version++; clock.finish(); state.playing = false; refreshItems(); animate();
    $('block-readout').replaceChildren(); $('block-stage').textContent = ''; redraw();
  }

  const counts = () => (state.built ? blockCounts(state.built) : null);
  function showReadout(b) {
    const i = b.summary.inventory, s = b.summary, mv = b.mv, km = m => `${n2(m / 1000)} km`;
    const run = p => p.slice(1).reduce((a, q, k) => a + Math.hypot(q.e - p[k].e, q.n - p[k].n), 0);
    const len = st => km(b.trenches.filter(t => t.stage === st).reduce((a, t) => a + run(t.path), 0));
    const pad = s.pads[0], cp = s.compoundPad;
    const rows = [['Tables', `${i.tables} paired tables · ${n1(i.tableKwp)} kWp each · ${n0(s.blockKwp)} kWp DC`],
      ['Strings', `${i.totalStrings} (${i.connectedStrings} connected, ${i.spareStrings} spare) · ${i.modulesPerString} modules, ${n1(i.stringKwp)} kWp`],
      ['Inverters', `${i.inverters} × ${i.inverterKVA} kVA · ${i.stringsPerInverter[0]} strings in parallel each (12 MPPT × 2), 48 DC conductors`],
      ['Station', `${i.transformers} × ${i.transformerMVA} MVA = ${i.aggregateTransformerMVA} MVA · ${i.invertersPerTransformer} inverters each`],
      ['AC phase cables', `${i.acPhaseCables} × ${i.acAreaMm2} mm² Al, 800 V, ${i.formation}`], ['DC home cables', n0(i.dcHomeCables)],
      ['Piles', `${n0(s.piles.count)} · ${n2(s.piles.min)} to ${n2(s.piles.max)} m out of the measured ground`],
      ['Lowest module edge', `${n2(s.lowEdgeMin)} m above the ground at its lowest`],
      ['Station pad', `level ${n2(pad.level)} m · cut ${n0(pad.cut)} m³, fill ${n0(pad.fill)} m³`],
      ['Trenches', `DC ${len('dc')} · AC ${len('ac')} · 33 kV ${km(mv.trenchM)}`],
      ['33 kV rings', `${mv.rings.length} for ${mv.stations.length} stations (${mv.perRing} a ring by the feeder limit)`],
      ...mv.rings.map(r => ['', `${r.id}: ${r.stations.join(' + ')} · ${r.areaMm2} mm² Al · open at ${r.openAt} · drop ${n2(r.dropPct)} % (${n2(r.outageDropPct)} % one end out)`]),
      ['MV board', `${mv.sections} section${mv.sections > 1 ? 's, normally-open bus tie' : ''} · ${2 * mv.rings.length} ring ways`],
      ['Grid transformer', `${mv.grid.units} × ${mv.grid.mva} MVA ${mv.poc.kv}/33 kV${mv.grid.smallest ? ' (smallest standard size)' : ''}`],
      ['Compound pad', `level ${n2(cp.level)} m · cut ${n0(cp.cut)} m³, fill ${n0(cp.fill)} m³${cp.source ? ' · ' + cp.source : ''}`],
      ['Connection', s.connection ? `${mv.poc.kv} kV line tower ${formatLength(s.connection.distanceM)} from the connection structure (straight tee)`
        : `no ${mv.poc.kv} kV tower loaded near here; connection structure shown`],
      ...(s.overhead ? [['Overhead line', `${s.overhead.kv} kV line ${formatLength(s.overhead.distanceM)} from the nearest table corner` +
        (s.overhead.distanceM < CLEAR_M ? ` (under ${CLEAR_M} m: move the block)` : '')]] : []),
      ['Ground', s.unmeasured ? `${n0(s.unmeasured)} points off the measured tiles took the nearest ground` : 'all on measured LiDAR ground'],
      ['Basis', `${BLOCK_LABEL} Geometry and counts from the owner's explorer station; ring sizes from generic rating rules.`]];
    $('block-readout').replaceChildren(...rows.flatMap(([k, v]) => { const dt = doc.createElement('dt'), dd = doc.createElement('dd'); dt.textContent = k; dd.textContent = v; return [dt, dd]; }));
  }

  $('block-place').addEventListener('click', () => place());
  $('block-gpu').addEventListener('click', () => placeGpu());
  $('block-play').addEventListener('click', () => play());
  $('block-pause').addEventListener('click', () => pause());
  $('block-step').addEventListener('click', () => step());
  $('block-clear').addEventListener('click', () => { clear(); say('Block cleared.'); });
  say(BLOCK_LABEL);
  return { place, placeGpu, gpuCounts, play, pause, step, clear, batches, trenchItems: () => items.list, counts, animating: () => state.playing,
    fps: FPS, key: () => items.key,
    snapshot: () => ({ placed: !!state.built, t: clock.t(), stage: stageAt(clock.t()).id, playing: state.playing, counts: counts(),
      anchor: state.anchor ? [...state.anchor] : null,
      compound: state.built ? [state.anchor[0] + state.built.mv.compound.x, state.anchor[1] + state.built.mv.compound.y] : null, trenches: state.built ? state.built.trenches.length : 0,
      gpu: state.gpu ? gpuCounts() : null }) };
}

Design Tabs

A JavaScript module in the world folder of GlobalGrid2050 covering solar. It is built from the mount design tabs helper (`mountDesignTabs`) and the show step (`show`).

interactionglobalgrid2050 / solar-design-studio/202609270330-site-world-v3/world/design-tabs.mjs · lines 1–43 of 43 · version 2026-09-27 03:30 · Not reached from any entry point (candidate for review)

What it does
Defines mountDesignTabs, show. 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.
Downstream impact
Used directly by 2 files: Design Sections (globalgrid2050); Design Sections (globalgrid2050).
What it achieves
The Design panel's four sections as tabs, so a phone shows one short panel at a time. It responds to click and keydown events.
Why it matters
Imported by Design Sections.
Application
globalgrid2050 · solar-design-studio/202609270330-site-world-v3/world · JavaScript module
Uses
none found
Used by
imported by Design Sections (import), imported by Design Sections (import)
Produces
TABS, mountDesignTabs
Defines here
mountDesignTabs, show
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/202609270330-site-world-v3/world/design-tabs.mjs:1-43 · blob 60b5f259433209ebac1c813797494d782fb41c18 · 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-tabs.mjs: the Design panel's four sections as tabs, so a phone shows one short panel at a time.
//   Build    trench, cable, road, pad, piles, fence, drilled crossing (and their options, route to substation, phases)
//   Measure  drum schedule, bill of quantities, level profile
//   Plant    plant layout, solar block, specification and ground condition, the ground under a route
//   Share    save, open, share, print (the File row), tour
// Markup in world.html (#design [role=tab] / [role=tabpanel]). A tab's own modules load the first time it opens
// (onFirstOpen), never before. Arrow keys move between tabs, as the ARIA tabs pattern asks. No other imports.

export const TABS = Object.freeze(['build', 'measure', 'plant', 'share']);

// doc: the page. onFirstOpen: { [tab]: () => void } run once, the first time that tab is shown.
export function mountDesignTabs(doc, { onFirstOpen = {}, onChange = () => {} } = {}) {
  const tabs = [...doc.querySelectorAll('#design [role="tab"][data-tab]')];
  if (!tabs.length) return { show: () => false, current: () => null };
  const opened = new Set();
  let current = tabs.find(t => t.getAttribute('aria-selected') === 'true')?.dataset.tab || TABS[0];
  function show(name, { focus = false } = {}) {
    const tab = tabs.find(t => t.dataset.tab === name);
    if (!tab) return false;
    for (const t of tabs) {
      const on = t === tab, panel = doc.getElementById(t.getAttribute('aria-controls'));
      t.setAttribute('aria-selected', String(on));
      t.tabIndex = on ? 0 : -1;
      if (panel) panel.hidden = !on;
    }
    if (focus) tab.focus();
    const changed = current !== name;
    current = name;
    if (!opened.has(name)) { opened.add(name); try { onFirstOpen[name]?.(); } catch (e) { console.warn(`Design ${name}: ${e.message}`); } }
    if (changed) onChange(name);
    return true;
  }
  for (const t of tabs) {
    t.addEventListener('click', () => show(t.dataset.tab));
    t.addEventListener('keydown', e => {
      const i = tabs.indexOf(t), step = e.key === 'ArrowRight' ? 1 : e.key === 'ArrowLeft' ? -1 : 0;
      if (e.key === 'Home' || e.key === 'End') { e.preventDefault(); show(tabs[e.key === 'Home' ? 0 : tabs.length - 1].dataset.tab, { focus: true }); }
      else if (step) { e.preventDefault(); show(tabs[(i + step + tabs.length) % tabs.length].dataset.tab, { focus: true }); }
    });
  }
  show(current);
  return { show, current: () => current };
}

First Showing

A JavaScript module in the world folder of GlobalGrid2050 that reads substations and the Renewable Energy Planning Database (REPD) register. It places label (`placeLabel`) and shows place (`showPlace`).

interactionglobalgrid2050 / solar-design-studio/202609270330-site-world-v3/world/first-showing.mjs · lines 1–87 of 87 · version 2026-09-27 03:30 · Not reached from any entry point (candidate for review) · pattern mountFirstShowing (shared by 2 files)

What it does
It loads substations and the REPD register. Defines 10 functions or classes, including placeLabel, substationLine, pinBatch, mountFirstShowing, $. Side effects: changes the web page (DOM); 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: substations, the REPD register.
Inputs & outputs
In: browser storage (getItem). Out: browser storage (setItem). Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid).
What it achieves
The first step, offered once (a small card that opens Find; dismissed for good with × or by using Find), and the place just found. It responds to click events.
Why it matters
No other file in the estate was found to import it.
Application
globalgrid2050 · solar-design-studio/202609270330-site-world-v3/world · JavaScript module
Uses
Bng (import), Origin (import), Labels (import)
Used by
mentioned in Standalone (comment link)
Produces
PHONE, SUBSTATION_REACH_M, placeLabel, substationLine, pinBatch, mountFirstShowing
Defines here
placeLabel, substationLine, pinBatch, mountFirstShowing, $, remembered, dismissStart, phone, gridLine, showPlace
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/202609270330-site-world-v3/world/first-showing.mjs:1-87 · blob 1c90a9221f658a2468df4436a3d98f9e54d1eeb2 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, storage · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: unreached_review
// First showing: the first step, offered once (a small card that opens Find; dismissed for good with × or by using
// Find), and the place just found: a card with its grid reference and the nearest substation, and a pin on the ground.
// A REPD project is named on the card by its reference only; project names stay in the Find results the user asked for.
import { gridRef } from './bng.mjs';
import { toLocal } from './origin.mjs';
import { distanceLabel } from './labels.mjs';

const START_KEY = 'world.start.dismissed';
export const PHONE = '(max-width: 700px), (pointer: coarse)';
export const SUBSTATION_REACH_M = 5000; // further than this, the grid data here is not the grid near the place

// The words for the place card: "REPD 1234" for a project, else the label the search gave (postcode, coordinates).
export const placeLabel = choice => (choice?.ref != null && choice.ref !== '' ? `REPD ${choice.ref}` : String(choice?.label ?? ''));

// The nearest substation line from { label, d, national? } (or null) and the nearest pylon, in plain words. A substation
// from the national index is the true nearest, so its distance is always given.
export function substationLine(sub, tower) {
  if (sub && (sub.national || sub.d <= SUBSTATION_REACH_M)) return `Nearest ${sub.label}: ${distanceLabel(sub.d)}`;
  const none = `No substation within ${SUBSTATION_REACH_M / 1000} km in the grid data loaded`;
  return tower ? `${none} · nearest ${tower.label} ${distanceLabel(tower.d)}` : none;
}

// The pin at (x, y, z) local: a 40 m mast with a diamond on the ground, so it can be seen from the drone.
export function pinBatch(x, y, z, version) {
  const r = 6, h = 40;
  const v = [0, 0, 0, 0, 0, h, -r, 0, 0, 0, r, 0, 0, r, 0, r, 0, 0, r, 0, 0, 0, -r, 0, 0, -r, 0, -r, 0, 0,
    0, 0, h, -3, 0, h - 6, 0, 0, h, 3, 0, h - 6];
  return { key: 'place-pin', version, positions: new Float32Array(v), color: [1, 0.45, 0.85, 1], origin: [x, y, z] };
}

// deps: { doc, canvas, redraw(), origin(), heightAt(x, y), groundVersion(), assets() -> [{ kind, label, e, n }],
//   nearest?(e, n) -> Promise<substation | null> (the national index), openFind() }.
export function mountFirstShowing({ doc = document, canvas, redraw, origin, heightAt, groundVersion, assets = () => [], nearest = null, openFind }) {
  const $ = id => doc.getElementById(id);
  let place = null; // { label, e, n } national-grid metres
  const remembered = () => { try { return localStorage.getItem(START_KEY) === '1'; } catch { return false; } };
  function dismissStart() {
    if ($('start')) $('start').hidden = true;
    try { localStorage.setItem(START_KEY, '1'); } catch { /* private window: it just shows again next time */ }
  }
  // On a phone the card would sit over the view: there Find starts closed and opens only from the Find button.
  const phone = () => { try { return !!globalThis.matchMedia?.(PHONE).matches; } catch { return false; } };
  if ($('start')) $('start').hidden = remembered() || phone();
  $('start-close')?.addEventListener('click', () => { dismissStart(); canvas?.focus(); });
  $('start-go')?.addEventListener('click', () => openFind?.());
  $('place-close')?.addEventListener('click', () => { $('place').hidden = true; place = null; redraw(); canvas?.focus(); });

  // Nearest substation and pylon in the grid data loaded here; the national index answers for the substation when it can.
  async function gridLine(e, n) {
    const all = assets(), near = kind => all.filter(a => a.kind === kind)
      .map(a => ({ ...a, d: Math.hypot(a.e - e, a.n - n) })).sort((a, b) => a.d - b.d)[0] || null;
    let sub = near('substation');
    if (nearest) {
      try {
        const a = await nearest(e, n);
        if (a) sub = { ...a, national: true, d: Math.hypot(a.e - e, a.n - n),
          label: a.label || (a.kv ? `${a.kv} kV substation` : a.tier ? `${a.tier} substation` : 'substation') };
      } catch { /* local data only */ }
    }
    if (!sub && !all.length) return 'Grid data not loaded for this area';
    return substationLine(sub, near('tower'));
  }

  // Names the place just found, pins it, and says what is known there. note: the arrival note (terrain), or ''.
  function showPlace(choice, e, n, note = '') {
    place = { label: placeLabel(choice), e, n };
    $('place-name').textContent = place.label;
    let ref = '';
    try { ref = gridRef(e, n, 8); } catch { /* off the national grid */ }
    $('place-grid').textContent = ref;
    const mine = place;
    gridLine(e, n).then(t => { if (place === mine) $('place-grid').textContent = ref ? `${ref} · ${t}` : t; });
    $('place-terrain').textContent = note;
    $('place').hidden = false;
    redraw();
  }

  return {
    dismissStart, showPlace,
    place: () => (place ? { ...place } : null),
    batches() {
      if (!place) return [];
      const o = origin(), [x, y] = toLocal(o, place.e, place.n);
      return [pinBatch(x, y, heightAt(x, y), `${o.id}:${groundVersion()}:${place.e}:${place.n}`)];
    }
  };
}

Help

A JavaScript module in the world folder of GlobalGrid2050 that works with fill basis (`fillBasis`).

renderglobalgrid2050 / solar-design-studio/202609270330-site-world-v3/world/help.mjs · lines 1–23 of 23 · version 2026-09-27 03:30 · Not reached from any entry point (candidate for review)

What it does
Defines fillBasis, set, mountHelp. 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.
What it achieves
It is built from the fill basis helper (`fillBasis`), the set step (`set`) and the mount help helper (`mountHelp`). The "How to use" part of the Controls panel (`world.html` #help).
Why it matters
No other file in the estate was found to import it.
Application
globalgrid2050 · solar-design-studio/202609270330-site-world-v3/world · JavaScript module
Uses
Boq Assumptions (import)
Used by
none found
Produces
ROOMY, fillBasis, mountHelp
Defines here
fillBasis, set, mountHelp
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/202609270330-site-world-v3/world/help.mjs:1-23 · blob e38f6f5618ebe8d02de6802502645057bc43df31 · 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
// Help: the "How to use" part of the Controls panel (world.html #help). The words are in the page; this module
// makes the basis lines quote the same wording the readouts and the bill of quantities use (BASIS), so the help
// can never promise a different ground, accuracy or datum from the numbers it describes, and opens the
// How to use fold where the screen has room for it beside the controls (closed on phones: one tap opens it).
// Mouse and touch wording is chosen in CSS (pointer: fine / coarse), so nothing here depends on the device.

import { BASIS } from './boq-assumptions.mjs';

export const ROOMY = '(min-width: 700px)';

export function fillBasis(doc = document) {
  const set = (id, text) => { const el = doc.getElementById(id); if (el && text) el.textContent = text; };
  set('help-ground', BASIS.ground);
  set('help-datum', BASIS.datum);
}

export function mountHelp(doc = document, win = globalThis) {
  fillBasis(doc);
  const how = doc.getElementById('help-how');
  if (how && typeof win.matchMedia === 'function' && win.matchMedia(ROOMY).matches) how.open = true;
}

if (typeof document !== 'undefined') mountHelp(document, window);