GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Kuiper, cosmos and drawing engines / graphics-engines-open-source / web/versions/202609262227-site-world

Design UI and 3 more files

A JavaScript module in the world folder of Graphics Engines Open Source that converts to local pts (`toLocalPts`), draws profile (`drawProfile`), shows readout (`showReadout`) and calculates planar distances (units: kV).

599 lines of JavaScript and HTML from graphics-engines-open-source, in 4 files. Topic: Kuiper, cosmos and drawing engines. Section 1501 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. Versions — Site World Page render · graphics-engines-open-source / web/versions/202609262227-site-world/index.html lines 1–174
  2. Design UI geodesy · graphics-engines-open-source / web/versions/202609262227-site-world/world/design-ui.mjs lines 1–266
  3. Labels electrical · graphics-engines-open-source / web/versions/202609262227-site-world/world/labels.mjs lines 1–48
  4. Layers ingest · graphics-engines-open-source / web/versions/202609262227-site-world/world/layers.mjs lines 1–111

Versions — Site World Page

A web page in Graphics Engines Open Source that draws SVG graphics and reads inputs for trench section and cable type, covering cables and LiDAR terrain. Published at https://ventusltd.github.io/graphics-engines-open-source/web/versions/202609262227-site-world/.

rendergraphics-engines-open-source / web/versions/202609262227-site-world/index.html · lines 1–174 of 174 · version 2026-09-26 22:27 · Entry point

What it does
It draws cables and LiDAR terrain. Side effects: changes the web page (DOM).
Why it exists in the grid workflow
Domain terms in the code: cables, LiDAR terrain.
Inputs & outputs
In: form fields (user input). Out: web page; SVG drawing.
Downstream impact
Used directly by 1 file: Graphics Engines Open Source — Versions Page (graphics-engines-open-source, https://ventusltd.github.io/graphics-engines-open-source/web/versions/). It is itself an entry point, published at https://ventusltd.github.io/graphics-engines-open-source/web/versions/202609262227-site-world/.
What it achieves
No statement of purpose was found in the file, a README line naming it, or its name.
Why it matters
Loaded by the Versions page at https://ventusltd.github.io/graphics-engines-open-source/web/versions/.
Application
graphics-engines-open-source · web/versions/202609262227-site-world · page
Uses
Substrate (script src)
Used by
linked from Graphics Engines Open Source — Versions Page (link)
Produces
none declared
Defines here
none
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
graphics-engines-open-source@79e0bd8ee33844835e553fc84d552b6aa1521152 web/versions/202609262227-site-world/index.html:1-174 · blob 9d128285cade077d28a3f9a391f452c2ce9a5b01 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom · domain stage: unknown · users: none · canonical: unknown
<!doctype html>
<html lang="en-GB">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<title>Site world</title>
<link rel="icon" href="data:,">
<style>
  :root { --bg: #0a0a0a; --line: #9cdbff; --text: #cfe9ff; --dim: #6f8ea6; --panel: rgba(10, 10, 10, 0.86); --edge: #1c2c3a;
    --foot: 20px; --btn: 30px; }
  html, body { margin: 0; height: 100%; background: var(--bg); color: var(--text); font: 12px/1.45 system-ui, sans-serif; overflow: hidden; }
  button, select { font: inherit; }
  #view { position: fixed; inset: 0; width: 100%; height: 100%; display: block; touch-action: none; outline: none; }
  #where { position: fixed; left: 10px; bottom: calc(var(--foot) + 8px); color: var(--dim); pointer-events: none; }
  #help-toggle { position: fixed; right: 10px; bottom: calc(var(--foot) + 6px); min-height: 28px; border-radius: 4px; padding: 0 10px;
    background: var(--panel); color: var(--dim); border: 1px solid var(--edge); cursor: pointer; }
  #help-toggle[aria-expanded="true"] { color: var(--text); border-color: var(--line); }
  .panel { position: fixed; box-sizing: border-box; background: var(--panel); border: 1px solid var(--edge); border-radius: 6px;
    padding: 10px 12px; overflow: auto; }
  .panel[hidden] { display: none; }
  #help { right: 10px; bottom: calc(var(--foot) + 42px); width: min(320px, calc(100vw - 20px)); max-height: calc(100vh - var(--foot) - 110px); }
  #help dl, #design dl { display: grid; grid-template-columns: auto 1fr; gap: 3px 10px; margin: 0 0 8px; }
  #help dt, #design dt { color: var(--text); white-space: nowrap; }
  #help dd, #design dd { margin: 0; color: var(--dim); }
  #help .credit { margin: 8px 0 0; padding: 0; list-style: none; color: var(--dim); font-size: 10px; }
  #help .credit a { color: var(--dim); }
  #dash { position: fixed; top: 8px; right: 8px; display: flex; gap: 4px; }
  #dash button, #design button { background: var(--panel); color: var(--dim); border: 1px solid var(--edge); border-radius: 4px;
    padding: 5px 9px; cursor: pointer; min-height: var(--btn); }
  #dash button[aria-pressed="true"], #dash button[aria-expanded="true"], #design button[aria-pressed="true"] { color: #fff; border-color: var(--line); }
  #design { top: calc(var(--btn) + 20px); right: 8px; width: min(300px, calc(100vw - 16px)); max-height: calc(100vh - 120px); }
  #design .row { display: flex; gap: 4px; flex-wrap: wrap; margin: 0 0 8px; }
  #design label { display: grid; gap: 2px; margin: 0 0 8px; color: var(--dim); }
  #design select { background: #111; color: var(--text); border: 1px solid var(--edge); border-radius: 4px; min-height: var(--btn); max-width: 100%; }
  #design-readout dd { color: var(--text); font-variant-numeric: tabular-nums; }
  #design-readout .warn { color: #ff8a7a; }
  #design figure { margin: 0 0 8px; } #design figure[hidden] { display: none; }
  #design svg { display: block; width: 100%; height: 90px; }
  #design svg polyline { fill: none; stroke-width: 1.5; vector-effect: non-scaling-stroke; }
  #design svg .ground { stroke: var(--line); } #design svg .floor { stroke: #ffc773; stroke-dasharray: 4 3; }
  #design svg text { fill: var(--dim); font-size: 12px; }
  #design figcaption { color: var(--dim); font-size: 10px; }
  #find.find-panel { top: calc(var(--btn) + 20px); right: 8px; }
  #lift { position: fixed; right: 10px; bottom: 50%; display: flex; flex-direction: column; gap: 6px; transform: translateY(50%); }
  #lift[hidden] { display: none; }
  #lift button { width: 56px; height: 44px; background: var(--panel); color: var(--text); border: 1px solid var(--edge);
    border-radius: 6px; touch-action: none; user-select: none; -webkit-user-select: none; cursor: pointer; }
  #lift button:active { border-color: var(--line); }
  #where-detail { margin: 0 0 6px; color: var(--dim); font-variant-numeric: tabular-nums; }
  #design .hint { margin: 0 0 8px; color: var(--text); }
  #design[data-state="choose"] #design-draw, #design[data-state="choose"] #design-readout,
  #design[data-state="result"] #design-draw { display: none; }
  #design-options[hidden] { display: none; }
  /* Small cards over the world: the first step, and the place just found. Hidden while any panel is open. */
  .card { position: fixed; top: 8px; left: 8px; width: min(340px, calc(100vw - 16px)); box-sizing: border-box; display: flex;
    align-items: stretch; gap: 4px; background: var(--panel); border: 1px solid var(--edge); border-radius: 6px; padding: 4px; }
  .card[hidden], body[data-panel] .card { display: none; }
  .card button { background: none; border: 0; color: var(--text); cursor: pointer; min-height: var(--btn); border-radius: 4px; }
  .card button:hover { background: rgba(156, 219, 255, 0.08); }
  #start-go { flex: 1; text-align: left; padding: 4px 8px; }
  .card .close { min-width: var(--btn); font-size: 16px; color: var(--dim); }
  #place > div { flex: 1; padding: 4px 8px; display: grid; gap: 2px; }
  #place-name { color: #fff; } #place-grid, #place-terrain { color: var(--dim); } #place-terrain:empty { display: none; }
  /* While Design is open, the joypad, Up and Down step aside so taps land on the ground or the panel. */
  body[data-panel="design"] #pad, body[data-panel="design"] #lift { display: none !important; }
  @media (max-width: 900px) and (pointer: fine) { .card { top: calc(var(--btn) + 20px); } }
  @media (pointer: fine) { body[data-panel="help"] #lift { display: none; } } /* keys still fly the drone */
  #status { color: var(--dim); font-size: 11px; overflow-wrap: anywhere; }
  #attribution { position: fixed; left: 0; right: 0; bottom: 0; height: var(--foot); box-sizing: border-box; padding: 3px 10px 4px;
    font-size: 10px; line-height: 13px; color: var(--dim); background: rgba(10, 10, 10, 0.72); pointer-events: none;
    white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
  #attribution .short { display: none; }
  #pad { position: fixed; left: 24px; bottom: calc(var(--foot) + 36px); width: 120px; height: 120px; border-radius: 50%; touch-action: none;
    border: 1px solid var(--edge); background: rgba(156, 219, 255, 0.04); display: none; }
  #pad span { position: absolute; left: 36px; top: 36px; width: 48px; height: 48px; border-radius: 50%;
    border: 1px solid var(--line); background: rgba(156, 219, 255, 0.12); pointer-events: none; }
  @media (max-width: 900px) { #attribution .full { display: none; } #attribution .short { display: inline; } }
  /* Narrow screens: the credit may take two lines; everything above the footer moves up with --foot. */
  @media (max-width: 600px) { :root { --foot: 33px; } #attribution { white-space: normal; } }
  @media (pointer: fine) { #help dl.touch { display: none; } }
  /* Touch screens: 44 px targets; panels open as a sheet under the dash so the joypad, Up and Down stay clear. */
  @media (pointer: coarse) {
    :root { --btn: 44px; }
    #pad { display: block; }
    #help dl.keys, #design dl.keys { display: none; }
    #where { bottom: auto; top: calc(var(--btn) + 16px); }
    #dash button { min-width: 48px; }
    #help-toggle { min-height: 44px; min-width: 44px; bottom: calc(var(--foot) + 8px); }
    #lift { bottom: calc(var(--foot) + 64px); transform: none; }
    #help, #design, #find.find-panel { top: calc(var(--btn) + 40px); left: 8px; right: 8px; bottom: auto; width: auto;
      max-height: calc(100vh - var(--btn) - 40px - var(--foot) - 180px); overflow: auto; }
    #find.find-panel input { height: 44px; }
    .card { top: calc(var(--btn) + 40px); width: auto; right: 8px; max-width: 420px; }
    /* Design is a short sheet along the bottom: tools, one line of guidance, Undo / Done / Clear; results after Done. */
    #design { top: auto; bottom: calc(var(--foot) + 4px); max-height: calc(100vh - var(--btn) - 60px - var(--foot)); }
    #design[data-state="draw"] #design-readout, #design[data-state="draw"] #design-profile-box,
    #design[data-state="draw"] #design-keys, #design[data-state="choose"] #design-keys { display: none; }
    #design[data-state="result"] #design-keys { display: none; }
    #design .row { flex-wrap: nowrap; } #design .row button { flex: 1; }
    body[data-panel="design"] #help-toggle { display: none; }
    #help .credit a { display: flex; align-items: center; min-height: 40px; }
  }
</style>
</head>
<body>
<canvas id="view" tabindex="0" aria-label="Site world. Move with W and S or the joypad, turn with A and D; look by dragging."></canvas>
<div id="where" role="status"></div>
<nav id="dash" aria-label="View">
  <button type="button" id="find-toggle" aria-expanded="false" aria-controls="find">Find</button>
  <button type="button" data-view="standing" aria-pressed="true">Walk</button>
  <button type="button" data-view="aerial" aria-pressed="false">Drone</button>
  <button type="button" id="design-toggle" aria-expanded="false" aria-controls="design">Design</button>
  <button type="button" id="to-gridatlas" title="Open GridAtlas at this spot">GridAtlas</button>
</nav>
<section id="design" class="panel" hidden aria-label="Design" data-state="choose">
  <p id="design-hint" class="hint" role="status">Choose Trench or Cable</p>
  <div class="row" role="group" aria-label="Design tool">
    <button type="button" data-tool="trench" aria-pressed="false">Trench</button>
    <button type="button" data-tool="cable" aria-pressed="false">Cable</button>
    <button type="button" id="design-options-toggle" aria-expanded="false" aria-controls="design-options">Options</button>
  </div>
  <div id="design-options" hidden>
    <label>Trench section <select id="trench-section"></select></label>
    <label>Cable (voltage and size) <select id="cable-type"></select></label>
  </div>
  <div class="row" id="design-draw">
    <button type="button" id="design-undo">Undo</button>
    <button type="button" id="design-finish">Done</button>
    <button type="button" id="design-clear">Clear</button>
  </div>
  <dl id="design-readout" aria-live="polite"></dl>
  <figure id="design-profile-box" hidden>
    <svg id="design-profile" role="img" aria-label="Level profile along the route"></svg>
    <figcaption>Ground level (solid) and trench floor (dashed) along the route</figcaption>
  </figure>
  <dl id="design-keys"></dl>
</section>
<div id="start" class="card" hidden>
  <button type="button" id="start-go">Enter a postcode or planning reference — e.g. GL7 5</button>
  <button type="button" id="start-close" class="close" aria-label="Dismiss">×</button>
</div>
<div id="place" class="card" hidden role="status">
  <div><strong id="place-name"></strong><span id="place-grid"></span><span id="place-terrain"></span></div>
  <button type="button" id="place-close" class="close" aria-label="Close">×</button>
</div>
<div id="lift" hidden>
  <button type="button" data-lift="1" aria-label="Fly up">Up</button>
  <button type="button" data-lift="-1" aria-label="Fly down">Down</button>
</div>
<div id="pad" aria-label="Joypad: up to move forward, sideways to turn"><span></span></div>
<button id="help-toggle" type="button" aria-expanded="false" aria-controls="help">Controls</button>
<section id="help" class="panel" hidden aria-label="Controls">
  <dl class="keys">
    <dt>W / S</dt><dd>forward and back (or up / down arrows)</dd>
    <dt>A / D</dt><dd>turn left and right (or left / right arrows)</dd>
    <dt>Drag</dt><dd>look around</dd>
    <dt>Shift</dt><dd>hold to move slowly and precisely</dd>
    <dt>F</dt><dd>drone on and off · Space up, Q down · flies low enough to pass under tables</dd>
  </dl>
  <dl class="touch">
    <dt>Joypad</dt><dd>up to go forward, sideways to turn</dd>
    <dt>Drag</dt><dd>anywhere else to look around</dd>
  </dl>
  <p id="where-detail"></p>
  <div id="status"></div>
  <ul id="credits" class="credit"><li>Terrain: Environment Agency LIDAR Composite DTM 1 m · © Environment Agency copyright and/or
    database right 2022. All rights reserved. · Open Government Licence v3.0</li></ul>
</section>
<footer id="attribution"><span class="full" id="credit-full">Terrain: Environment Agency LIDAR Composite DTM 1 m ·
  © Environment Agency copyright and/or database right 2022. All rights reserved. · Open Government Licence v3.0</span><span
  class="short" id="credit-short">Terrain © Environment Agency 2022 · OGL v3.0</span></footer>
<script type="module" src="world/substrate.mjs"></script>
</body>
</html>

Design UI

A JavaScript module in the world folder of Graphics Engines Open Source that converts to local pts (`toLocalPts`), draws profile (`drawProfile`), shows readout (`showReadout`) and calculates planar distances (units: kV).

geodesygraphics-engines-open-source / web/versions/202609262227-site-world/world/design-ui.mjs · lines 1–266 of 266 · version 2026-09-26 22:27 · pattern drawProfile (shared by 2 files)

What it does
It draws cables, trench sections, substations and 33kV. Defines 32 functions or classes, including createDesign, $, groundVersion, section, cableSpec. 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: cables, substations, 33kV.
Inputs & outputs
In: JSON file cables.json; JSON file trench-sections.json. Voltage levels named: 33kV.
Downstream impact
Used directly by 1 file: Substrate (graphics-engines-open-source). Reached from 2 other entry points, including Graphics Engines Open Source — Versions Page (graphics-engines-open-source, https://ventusltd.github.io/graphics-engines-open-source/web/versions/); Versions — Site World Page (graphics-engines-open-source, https://ventusltd.github.io/graphics-engines-open-source/web/versions/202609262227-site-world/).
What it achieves
It creates design (`createDesign`), draws profile (`drawProfile`) and shows readout (`showReadout`). Design tools in the world: Trench and Cable, drawn by clicking the ground. It responds to click, change and keydown events.
Why it matters
Imported by Substrate.
Application
graphics-engines-open-source · web/versions/202609262227-site-world/world · JavaScript module
VEDIC
HEIGHT (GG2050-VEDIC-000011): Solar Design Studio / LiDAR · Mathematics / Raster sampling. bng_easting_m, bng_northing_m → height_receipt_or_null
Uses
Origin (import), Pick (import), Route Tool (import), Trench (import), Cable Route (import), Measure (import), Measure Format (import), Labels (import)
Used by
imported by Substrate (import), mentioned in Standalone (comment link)
Produces
createDesign
Defines here
createDesign, $, groundVersion, section, cableSpec, toLocalPts, trenchOf, cableOf, build, heightAt, batch, marker, tightIndices, batches, nearestAsset, near, onMeasuredGround, measure, drawProfile, X, line, text, hint, showReadout, finish, choose, pickAt, shift, options, loadCatalogue
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
graphics-engines-open-source@79e0bd8ee33844835e553fc84d552b6aa1521152 web/versions/202609262227-site-world/world/design-ui.mjs:1-266 · blob a8c5120801075a2ebceb94b439a6fa85a1d23004 · 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: unknown
// Design tools in the world: Trench and Cable, drawn by clicking the ground. The substrate hands in the ground,
// the origin and the viewer; this module owns the design panel (world.html #design), the design held in memory
// and the lines it draws. Routes are kept in national-grid metres, so they survive every move of the origin.
// A trench cuts the ground (composeGround): walkers and the drone follow its floor. A cable is laid in trefoil
// on the floor of its own trench, with the governing installation bend radius for its size; bends tighter than
// that are flagged. Numbers come from measure.mjs, so the readout says what the panels and exports will say.

import { toBng, toLocal } from './origin.mjs';
import { rayFromScreen, pickGround } from './pick.mjs';
import { createRouteTool, describeControls } from './route-tool.mjs';
import { createTrench, composeGround } from './trench.mjs';
import { routeCable } from './cable-route.mjs';
import { profile, cableSummary, bendRule } from './measure.mjs';
import { formatNumber, formatLength, formatVolume, formatGradient } from './measure-format.mjs';
import { sectionLabel, cableLabel, pressWord, distanceLabel } from './labels.mjs';

const COLOUR = { draft: [1, 1, 1, 0.95], trench: [1, 0.78, 0.45, 1], cable: [0.55, 1, 0.62, 1], tight: [1, 0.36, 0.3, 1] };
const WHEN = 'installation'; // the cable is being pulled in: the larger of the two radii governs the route
const SVG = 'http://www.w3.org/2000/svg';

// deps: { doc, canvas, fov, baseHeight(x, y), origin(), viewer() -> state, invalidate({ ground }), redraw(), assets() }
// assets() -> [{ label, e, n }] grid equipment to measure the route's end against (may be empty).
export function createDesign({ doc, canvas, fov, baseHeight, measured = () => NaN, origin, viewer, invalidate, redraw, assets = () => [] }) {
  const $ = id => doc.getElementById(id);
  const catalogue = { sections: [], cables: [], rules: [], json: null };
  // view: what the panel is showing. 'choose' a tool, 'draw' a route, or the 'result' of the one just finished.
  const design = { tool: null, trenches: [], cables: [], finished: 0, drafts: 0, last: null, view: 'choose' };
  const coarse = matchMedia('(pointer: coarse)').matches, press = pressWord(coarse);
  let built = { o: -1, g: -1, f: -1, key: '', ground: baseHeight, trenches: [], cables: [] };
  let groundVersion = () => 0;
  const route = createRouteTool({ onChange: () => { design.drafts++; if (route.state.points.length) design.view = 'draw'; showReadout(); redraw(); } });

  const section = id => catalogue.sections.find(s => s.id === id) || catalogue.sections[0];
  const cableSpec = id => catalogue.cables.find(c => c.id === id) || catalogue.cables[0];
  const toLocalPts = path => path.map(p => toLocal(origin(), p.e, p.n));
  const trenchOf = (sectionId, pts) => {
    const s = section(sectionId);
    return createTrench({ path: pts, width: s.trench_width_m, depth: s.trench_depth_m });
  };
  // Trefoil on the floor: the centreline is lifted so the lower two cores rest on it.
  const cableOf = (cableId, ground, pts) => {
    const spec = cableSpec(cableId), od = spec.od_mm / 1000;
    const bend = bendRule(catalogue.json, { voltageKv: spec.voltage_kv, when: WHEN, odMm: spec.od_mm });
    // The bend rule applies at the cable's inner edge, so the centreline bends at rule + OD/2.
    const r = routeCable({ points: pts, minBendRadius: (bend.radius || 0) + od / 2,
      depthBelowGround: -(od / 2 + od / (2 * Math.sqrt(3))), groundAt: ground, formation: 'trefoil', spacing: od, step: 0.5 });
    return Object.assign(r, { spec, bend, summary: cableSummary(r, { cables: catalogue.json, cableId: spec.id, when: WHEN }) });
  };

  // Local geometry, rebuilt only when the origin, the ground or the finished design changes (plain number checks:
  // heightAt runs this for every height anyone asks for).
  function build() {
    const o = origin(), g = groundVersion();
    if (built.o === o.id && built.g === g && built.f === design.finished) return built;
    const all = [...design.trenches, ...design.cables];
    const trenches = all.map(t => trenchOf(t.section, toLocalPts(t.path)));
    const ground = trenches.length ? composeGround(baseHeight, trenches) : baseHeight;
    built = { o: o.id, g, f: design.finished, key: `${o.id}:${g}:${design.finished}`, ground, trenches, cables: [] };
    built.cables = design.cables.map(c => cableOf(c.cable, ground, toLocalPts(c.path)));
    return built;
  }
  const heightAt = (x, y) => build().ground(x, y);

  // Positions relative to their first point, worked out in doubles, so far-out lines stay sharp on the GPU.
  function batch(key, version, pos, color) {
    if (!pos || pos.length < 6) return null;
    const o = [pos[0], pos[1], pos[2]], out = new Float32Array(pos.length);
    for (let i = 0; i < pos.length; i++) out[i] = pos[i] - o[i % 3];
    return { key, version, positions: out, color, origin: o };
  }
  const marker = (v, [x, y, z], h, arm) => v.push(x, y, z, x, y, z + h, x - arm, y, z + h, x + arm, y, z + h, x, y - arm, z + h, x, y + arm, z + h);
  const tightIndices = c => [...new Set([...c.violations.map(v => v.index), ...c.summary.below.map(b => b.index)])].sort((a, b) => a - b);

  function batches() {
    const b = build(), out = [];
    b.trenches.forEach((t, i) => out.push(batch('design-trench-' + i, b.key, t.wallLines(baseHeight), COLOUR.trench)));
    b.cables.forEach((c, i) => {
      out.push(batch('design-cable-' + i, b.key, c.drawLines({ includeCentreline: false }), COLOUR.cable));
      const tight = [], pts = toLocalPts(design.cables[i].path);
      for (const k of tightIndices(c)) { const [x, y] = pts[k]; marker(tight, [x, y, heightAt(x, y)], 3, 1.2); }
      out.push(batch('design-tight-' + i, b.key, tight, COLOUR.tight));
    });
    const d = route.state.points, v = [];
    for (let i = 0; i < d.length; i++) {
      const [x, y] = d[i], z = heightAt(x, y) + 0.05;
      if (i) { const [px, py] = d[i - 1]; v.push(px, py, heightAt(px, py) + 0.05, x, y, z); }
      marker(v, [x, y, z], 1.5, 0.4);
    }
    out.push(batch('design-draft', `${b.key}:${design.drafts}`, v, COLOUR.draft));
    return out.filter(Boolean);
  }

  // ---- readout ----------------------------------------------------------------------------------------
  // Where the route ends against the grid: the nearest substation if one is in reach, else says so plainly and
  // gives the nearest pylon. A route may end at a pylon or any drawn point.
  const REACH_M = 5000;
  function nearestAsset(pt) {
    const o = origin(), end = toBng(o, pt[0], pt[1]), list = assets();
    const near = kind => list.filter(a => a.kind === kind).map(a => ({ ...a, d: Math.hypot(a.e - end.e, a.n - end.n) }))
      .sort((x, y) => x.d - y.d)[0] || null;
    if (!list.length) return 'no grid equipment loaded here';
    const sub = near('substation'), tower = near('tower');
    if (sub && sub.d <= REACH_M) return `${sub.label}, ${distanceLabel(sub.d)} from the end`;
    const none = `no substation within ${formatNumber(REACH_M / 1000, 0)} km`;
    return tower ? `${none} · nearest ${tower.label} ${distanceLabel(tower.d)} from the end` : none;
  }
  // Level change is only stated where every point and every midpoint of the route is on measured ground.
  const onMeasuredGround = pts => pts.every((p, i) => Number.isFinite(measured(p[0], p[1])) &&
    (i === 0 || Number.isFinite(measured((p[0] + pts[i - 1][0]) / 2, (p[1] + pts[i - 1][1]) / 2))));
  // Rows for the readout and the level profile. spoil: undefined = not yet worked out.
  function measure(kind, sectionId, cableId, pts, spoil) {
    const s = section(sectionId), t = trenchOf(s.id, pts);
    const rows = [['Trench', `${sectionLabel(s)} · ${s.trench_width_m} m wide × ${s.trench_depth_m} m deep`]];
    let plan = pts;
    if (kind === 'cable') {
      const c = cableOf(cableId, heightAt, pts), cs = c.summary, tight = tightIndices(c);
      plan = c.centreline.map(p => [p[0], p[1]]);
      rows.unshift(['Cable', cableLabel(c.spec)]);
      rows.push(['Minimum bend radius', cs.required.radius == null ? `no ${WHEN} rule for this cable`
        : `${formatNumber(cs.required.radius, 2)} m (${formatNumber(cs.required.multiple, 0)} × OD, ${WHEN})`],
      ['Cable length (plan)', formatLength(cs.length2d)], ['Cable length (3D)', formatLength(cs.length3d)],
      ['Tight bends', tight.length ? `${tight.length} (at point${tight.length > 1 ? 's' : ''} ${tight.map(k => k + 1).join(', ')})` : 'none']);
    }
    const p = profile(baseHeight, plan, 1);
    rows.push(['Trench length (plan)', formatLength(t.length2d)], ['Trench length (3D)', formatLength(t.length3dOn(baseHeight))],
      ['Spoil volume', spoil === undefined ? 'on finish' : spoil === null ? 'working out…' : formatVolume(spoil, 2)],
      ...(onMeasuredGround(plan) ? [['Level change', `${formatNumber(p.max - p.min, 2)} m (ground ${formatNumber(p.min, 2)} to ${formatNumber(p.max, 2)} m above sea level)`],
        ['Steepest gradient', formatGradient(p.gradient.max)]]
        : [['Level change', 'not known: no measured ground (terrain tiles) under this route']]),
      ['Nearest grid', nearestAsset(pts[pts.length - 1])]);
    return { rows, profile: onMeasuredGround(plan) ? p : null, depth: s.trench_depth_m };
  }
  function drawProfile(m) {
    const box = $('design-profile-box'), svg = $('design-profile');
    box.hidden = !m;
    if (!m) return;
    const W = 300, H = 90, L = 4, R = 296, T = 14, B = 76, pr = m.profile;
    const lo = pr.min - m.depth, hi = Math.max(pr.max, lo + 0.5), len = Math.max(pr.length2d, 1e-6);
    const X = s => L + (s / len) * (R - L), Y = z => B - ((z - lo) / (hi - lo)) * (B - T);
    const line = (dz, cls) => {
      const el = doc.createElementNS(SVG, 'polyline');
      el.setAttribute('points', pr.pairs.map(([s, z]) => `${X(s).toFixed(1)},${Y(z - dz).toFixed(1)}`).join(' '));
      el.setAttribute('class', cls); return el;
    };
    const text = (x, y, s, anchor = 'start') => {
      const el = doc.createElementNS(SVG, 'text');
      Object.entries({ x, y, 'text-anchor': anchor }).forEach(([k, v]) => el.setAttribute(k, v));
      el.textContent = s; return el;
    };
    svg.setAttribute('viewBox', `0 0 ${W} ${H}`);
    svg.replaceChildren(line(0, 'ground'), line(m.depth, 'floor'), text(L, 10, `${formatNumber(hi, 1)} m`),
      text(L, H - 2, `${formatNumber(lo, 1)} m`), text(R, H - 2, formatLength(pr.length2d), 'end'));
  }
  // One line that says what to do next, and which parts of the panel are showing (world.html styles #design[data-state]).
  function hint(pts) {
    if (!design.tool) return 'Choose Trench or Cable';
    if (design.view === 'result' && !pts.length) return `${design.tool === 'cable' ? 'Cable' : 'Trench'} finished. ${press} the ground to draw another.`;
    if (!pts.length) return `${press} two or more points on the ground, then Done`;
    if (pts.length === 1) return `1 point · ${press.toLowerCase()} the next point`;
    return `${pts.length} points · ${press.toLowerCase()} more, or Done`;
  }
  function showReadout() {
    const pts = route.state.points.map(p => [p[0], p[1]]);
    if (!design.tool && design.view === 'draw') design.view = 'choose';
    let m = design.last || { rows: [['Status', design.tool ? `${press.toLowerCase()} the ground to start a ${design.tool}` : 'choose Trench or Cable']] };
    if (design.tool && pts.length >= 2) {
      try { m = measure(design.tool, $('trench-section').value, $('cable-type').value, pts); } catch (e) { m = { rows: [['Status', e.message]] }; }
    } else if (design.tool && pts.length === 1) m = { rows: [['Status', '1 point · add another']] };
    $('design').dataset.state = design.view;
    $('design-hint').textContent = hint(pts);
    $('design-readout').replaceChildren(...m.rows.flatMap(([k, v]) => {
      const dt = doc.createElement('dt'), dd = doc.createElement('dd');
      dt.textContent = k; dd.textContent = v;
      if (k === 'Tight bends' && v !== 'none') dd.className = 'warn';
      return [dt, dd];
    }));
    drawProfile(m.profile ? m : null);
  }

  // ---- actions ----------------------------------------------------------------------------------------
  function finish() {
    const pts = route.state.points, kind = design.tool;
    if (!kind || !route.finish()) return false;
    const o = origin(), path = pts.map(([x, y]) => toBng(o, x, y)), plan = pts.map(p => [p[0], p[1]]);
    const item = { path, section: $('trench-section').value, ...(kind === 'cable' ? { cable: $('cable-type').value } : {}) };
    (kind === 'trench' ? design.trenches : design.cables).push(item);
    design.finished++;
    const last = measure(kind, item.section, item.cable, plan, null); // measured on the ground it has just cut
    design.last = last;
    design.view = 'result';
    route.clear();
    invalidate({ ground: true }); // new ground: walkers and the drone follow the trench floor
    // Spoil is a fine grid over the whole trench; work it out after the frame, then say it.
    setTimeout(() => {
      const spoil = trenchOf(item.section, plan).spoilVolumeOn(baseHeight);
      item.spoil_m3 = spoil;
      if (design.last === last) { design.last = measure(kind, item.section, item.cable, plan, spoil); showReadout(); }
    }, 0);
    return true;
  }
  function choose(tool) {
    design.tool = design.tool === tool ? null : tool;
    design.view = design.tool ? 'draw' : 'choose';
    route.clear();
    for (const b of doc.querySelectorAll('[data-tool]')) b.setAttribute('aria-pressed', String(b.dataset.tool === design.tool));
    showReadout();
  }
  function pickAt(x, y) {
    if (!design.tool) return false;
    const s = viewer();
    const ray = rayFromScreen(x, y, canvas.clientWidth, canvas.clientHeight, s.pos, s.yaw, s.pitch, fov);
    const p = pickGround(ray, heightAt, { maxDistance: 3000 });
    return p ? route.addPoint(p) : false;
  }
  // The origin moved by (dx, dy): the route being drawn moves the other way, so it stays put in the world.
  const shift = (dx, dy) => route.state.points.forEach((p, i) => route.movePoint(i, [p[0] - dx, p[1] - dy, p[2]]));

  // ---- page wiring ------------------------------------------------------------------------------------
  for (const b of doc.querySelectorAll('[data-tool]')) b.addEventListener('click', () => { choose(b.dataset.tool); canvas.focus(); });
  $('design-undo').addEventListener('click', () => route.removeLast());
  $('design-finish').addEventListener('click', () => finish());
  $('design-clear').addEventListener('click', () => route.clear());
  // Section and cable choices sit behind Options; on a phone, choosing one folds them away again so the ground stays clear.
  const options = open => { $('design-options').hidden = !open; $('design-options-toggle').setAttribute('aria-expanded', String(open)); };
  $('design-options-toggle').addEventListener('click', () => options($('design-options').hidden));
  for (const id of ['trench-section', 'cable-type']) $(id).addEventListener('change', () => { if (coarse) options(false); showReadout(); canvas.focus(); });
  addEventListener('keydown', e => {
    if (!design.tool || e.ctrlKey || e.metaKey || e.altKey) return;
    if (['SELECT', 'INPUT', 'TEXTAREA', 'BUTTON'].includes(e.target?.tagName)) return;
    if (e.code === 'Backspace') { route.removeLast(); e.preventDefault(); }
    else if (e.code === 'Enter' || e.code === 'NumpadEnter') { finish(); e.preventDefault(); }
    else if (e.code === 'Escape') route.clear();
  });
  $('design-keys').className = coarse ? 'touch' : 'keys';
  $('design-keys').replaceChildren(...describeControls({ touch: coarse }).flatMap(([k, v]) => {
    const dt = doc.createElement('dt'), dd = doc.createElement('dd');
    dt.textContent = k; dd.textContent = v; return [dt, dd];
  }));

  async function loadCatalogue() {
    try {
      const get = async p => { const r = await fetch(p, { cache: 'no-cache' }); if (!r.ok) throw Error(`${p}: HTTP ${r.status}`); return r.json(); };
      const [cables, trenches] = await Promise.all([get('./world/data/cables.json'), get('./world/data/trench-sections.json')]);
      Object.assign(catalogue, { sections: trenches.sections || [], cables: cables.cables || [], rules: cables.rules || [], json: cables });
      const fill = (id, items, label, chosen) => $(id).replaceChildren(...items.map(it => {
        const o = new Option(label(it), it.id); o.selected = it.id === chosen; return o;
      }));
      fill('trench-section', catalogue.sections, s => `${sectionLabel(s)} · ${s.trench_width_m} × ${s.trench_depth_m} m`, '33kv-1-dno');
      fill('cable-type', catalogue.cables, cableLabel, '33kv-1c-al-xlpe-300');
    } catch (e) {
      for (const b of doc.querySelectorAll('[data-tool]')) b.disabled = true;
      design.last = { rows: [['Status', 'design data could not be loaded: ' + e.message]] };
    }
    showReadout();
  }

  return {
    heightAt, batches, pickAt, shift, finish, loadCatalogue,
    setGroundVersion: fn => { groundVersion = fn; },
    putDown: () => { if (design.tool) choose(design.tool); },
    drawing: () => !!design.tool,
    // The design in memory, in national-grid metres (export and import come later).
    snapshot: () => JSON.parse(JSON.stringify({ tool: design.tool, trenches: design.trenches, cables: design.cables,
      draft: route.state.points.map(([x, y]) => toBng(origin(), x, y)), readout: design.last?.rows || null }))
  };
}

Labels

A JavaScript module in the world folder of Graphics Engines Open Source that works with 33kV.

electricalgraphics-engines-open-source / web/versions/202609262227-site-world/world/labels.mjs · lines 1–48 of 48 · version 2026-09-26 22:27 · pattern conductorLabel (shared by 3 files)

What it does
It calculates 33kV. Defines 8 functions or classes, including circuits, voltage, basis, sectionLabel, conductorLabel.
Why it exists in the grid workflow
Domain terms in the code: 33kV, 132kV, 1.5kV.
Inputs & outputs
Voltage levels named: 132kV, 33kV, 1.5kV.
Downstream impact
Used directly by 2 files: Design UI (graphics-engines-open-source); Substrate (graphics-engines-open-source). Reached from 2 other entry points, including Graphics Engines Open Source — Versions Page (graphics-engines-open-source, https://ventusltd.github.io/graphics-engines-open-source/web/versions/); Versions — Site World Page (graphics-engines-open-source, https://ventusltd.github.io/graphics-engines-open-source/web/versions/202609262227-site-world/).
What it achieves
It is built from the circuits step (`circuits`), the voltage step (`voltage`) and the basis step (`basis`). Human words for what the page shows. Its code works with 33 kV, 1.5 kV and 132 kV.
Why it matters
Imported by Design UI and Substrate.
Application
graphics-engines-open-source · web/versions/202609262227-site-world/world · JavaScript module
Uses
none found
Used by
imported by Design UI (import), imported by Substrate (import), mentioned in Standalone (comment link)
Produces
sectionLabel, conductorLabel, cableLabel, pressWord, distanceLabel
Defines here
circuits, voltage, basis, sectionLabel, conductorLabel, cableLabel, pressWord, distanceLabel
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
graphics-engines-open-source@79e0bd8ee33844835e553fc84d552b6aa1521152 web/versions/202609262227-site-world/world/labels.mjs:1-48 · blob 3c51c2d04d2c2bc1a30dd92aaa038a14ddeac908 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: unknown · users: none · canonical: unknown
// Human words for what the page shows. Pure: no DOM, no imports.
// Trench sections and cables carry code ids in the data files (e.g. "33kv-1-dno"); people read these labels instead.

const COUNT = ['no', 'one', 'two', 'three', 'four'];
const circuits = n => `${COUNT[n] ?? n} circuit${n === 1 ? '' : 's'}`;

// The voltage in plain words, from the section's voltage_class.
function voltage(s) {
  const v = String(s.voltage_class || '');
  if (/DC string/i.test(v)) return '1.5 kV DC string';
  if (/^LV/i.test(v)) return 'LV';
  return v.replace(/\s*AC$/i, '').replace(/\s*\(.*\)$/, '').trim() || 'Trench';
}

// Where the section's dimensions come from, or how it is laid, in a few words.
function basis(s) {
  const id = String(s.id || '');
  if (/-dno/.test(id)) return /agricultural/.test(id) ? 'farmland (network operator spec)' : '(network operator spec)';
  if (/-owner/.test(id)) return `(owner rule, ${s.cover_to_top_m} m cover)`;
  if (/duct/i.test(s.formation || '')) return s.cover_to_top_m >= 1.2 ? `in ducts, ${s.cover_to_top_m} m cover` : 'in ducts';
  return '';
}

// "33 kV, one circuit (network operator spec)"
export function sectionLabel(s) {
  if (!s) return '';
  const b = basis(s);
  return `${voltage(s)}, ${circuits(Number(s.circuits) || 1)}${b ? (b.startsWith('(') ? ' ' : ', ') + b : ''}`;
}

const METAL = { al: 'aluminium', cu: 'copper' };
// "aluminium", "copper", or "conductor not stated"
export const conductorLabel = c => METAL[String(c || '').toLowerCase()] || 'conductor not stated';

// "33 kV aluminium 300 mm² · OD 51.5 mm", "132 kV 300 mm², conductor not stated · OD 72 mm"
export function cableLabel(c) {
  if (!c) return '';
  const metal = METAL[String(c.conductor || '').toLowerCase()];
  const armour = /armoured/.test(String(c.id || '')) ? ', armoured' : '';
  const core = metal ? `${c.voltage_kv} kV ${metal} ${c.csa_mm2} mm²` : `${c.voltage_kv} kV ${c.csa_mm2} mm², conductor not stated`;
  return `${core}${armour} · OD ${c.od_mm} mm`;
}

// "Tap" on a touch screen, "Click" with a mouse.
export const pressWord = coarse => (coarse ? 'Tap' : 'Click');

// Distance in words: "850 m", "1.2 km".
export const distanceLabel = m => (m < 1000 ? `${Math.round(m)} m` : `${(m / 1000).toFixed(m < 10000 ? 1 : 0)} km`);

Layers

A JavaScript module in the world folder of Graphics Engines Open Source that makes API (`makeApi`) and fetches verified (`fetchVerified`), using SHA-256.

ingestgraphics-engines-open-source / web/versions/202609262227-site-world/world/layers.mjs · lines 1–111 of 111 · version 2026-09-26 22:27 · pattern sha256Bytes (shared by 3 files)

What it does
It fetches data. Defines 9 functions or classes, including loadLayers, startLayer, off, makeApi, fetchVerified. Side effects: makes network requests.
Downstream impact
Used directly by 1 file: Substrate (graphics-engines-open-source). Reached from 2 other entry points, including Graphics Engines Open Source — Versions Page (graphics-engines-open-source, https://ventusltd.github.io/graphics-engines-open-source/web/versions/); Versions — Site World Page (graphics-engines-open-source, https://ventusltd.github.io/graphics-engines-open-source/web/versions/202609262227-site-world/).
What it achieves
It starts layer (`startLayer`), makes API (`makeApi`) and fetches verified (`fetchVerified`). The manifest lists layers in order; each layer file is fetched, its SHA-256 compared with the manifest, and only then imported.
Why it matters
Imported by Substrate.
Application
graphics-engines-open-source · web/versions/202609262227-site-world/world · JavaScript module
Uses
Overhead (import), Trench (import), Cable Route (import)
Used by
imported by Substrate (import), mentioned in Standalone (comment link)
Produces
loadLayers, startLayer, makeApi, normalise, sha256, sha256Bytes
Defines here
loadLayers, startLayer, off, makeApi, fetchVerified, fetchJSON, normalise, sha256, sha256Bytes
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
graphics-engines-open-source@79e0bd8ee33844835e553fc84d552b6aa1521152 web/versions/202609262227-site-world/world/layers.mjs:1-111 · blob 0f7b17d168a2fbcdb8a02b389453a4a3cfc52048 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: network · domain stage: unknown · users: none · canonical: unknown
// Layer loader. The manifest lists layers in order; each layer file is fetched, its SHA-256 compared
// with the manifest, and only then imported. A layer whose hash differs is refused and named, never run.
// A layer is a module whose default export may offer:
//   init(api)        -> called once after the layer is verified and imported (may return a promise)
//   lines(ctx)       -> [{ key, version, positions: Float32Array, color: [r,g,b,a], origin?: [x,y,z] }]
//   heightAt(x, y)   -> ground height in metres (the first layer offering a finite height is the ground)
//   solids(ctx)      -> [{ min: [x,y,z], max: [x,y,z] }] boxes nobody can walk or fly through
// Layers are self-contained: no imports (they run from a blob URL). Positions are in local metres
// from the site origin, never national-grid coordinates: the GPU pair (tools/gpu/world_pair.py) measured
// 32-bit drawing error passing 0.1 px about 200 m from the origin and 0.5 px about 1 km out.
// A batch may carry an origin (local metres) with its positions relative to it, so it stays sharp far out.
//
// The api handed to init(api):
//   base                         absolute URL of the manifest's folder
//   fetchVerified(path, sha256)  -> Promise<ArrayBuffer>; the raw bytes are hashed as sent, nothing normalised
//   fetchJSON(path, sha256)      -> Promise<any>; the same check, then the text is decoded and parsed
//   invalidate({ ground })       asks for a redraw; ground (default true) says new ground has arrived
//   origin()                     -> { e, n, id }: the site origin in national-grid metres and its change count
//   lib                          pure helpers a self-contained layer may call: lib.overhead (buildOverhead, catenarySpan...),
//                                lib.trench (createTrench, composeGround), lib.cableRoute (routeCable)

import * as overhead from './overhead.mjs';
import { createTrench, composeGround } from './trench.mjs';
import { routeCable } from './cable-route.mjs';

const LIB = Object.freeze({ overhead, trench: Object.freeze({ createTrench, composeGround }), cableRoute: Object.freeze({ routeCable }) });

export async function loadLayers(manifestUrl, hooks = {}) {
  const base = new URL(manifestUrl, location.href);
  const res = await fetch(base, { cache: 'no-cache' });
  if (!res.ok) throw Error(`manifest HTTP ${res.status}`);
  const manifest = await res.json();
  const api = makeApi(new URL('./', base).href, hooks);
  const out = [];
  for (const entry of manifest.layers || []) {
    const url = new URL(entry.path, base);
    try {
      if (!entry.sha256) { out.push({ id: entry.id, status: 'refused: the manifest gives no hash' }); continue; }
      const res = await fetch(url, { cache: 'no-cache' });
      if (!res.ok) throw Error(`HTTP ${res.status}`);
      const text = normalise(await res.text());
      const hash = await sha256(text);
      if (!hash) { out.push({ id: entry.id, status: 'refused: this browser cannot check hashes here (needs https)' }); continue; }
      if (hash !== entry.sha256) {
        out.push({ id: entry.id, status: `refused: file hash ${hash.slice(0, 12)} is not the manifest's ${entry.sha256.slice(0, 12)}` });
        continue;
      }
      const blob = URL.createObjectURL(new Blob([text], { type: 'text/javascript' }));
      const mod = await import(blob);
      URL.revokeObjectURL(blob);
      const item = { id: entry.id, status: 'loaded, hash matches', layer: mod.default };
      out.push(item);
      startLayer(item, Object.freeze({ ...api, config: entry.config || null })); // per-layer settings from the manifest
    } catch (e) {
      out.push({ id: entry.id, status: 'failed: ' + e.message });
    }
  }
  return { generation: manifest.generation, site: manifest.site || null, layers: out };
}

// Runs a layer's init. A layer whose init throws, or whose promise rejects, is switched off and named.
export function startLayer(item, api) {
  const off = e => {
    item.layer = null; item.status = 'failed to start and switched off: ' + (e?.message || e);
    api.invalidate({ ground: false });
  };
  try {
    const r = item.layer?.init?.(api);
    if (r && typeof r.then === 'function') r.then(null, off);
  } catch (e) { off(e); }
}

// base: absolute URL of a folder. hooks: { invalidate(opts), origin() }; fetchImpl is for tests.
export function makeApi(base, { invalidate = () => {}, origin = () => ({ e: 0, n: 0, id: 0 }), fetchImpl } = {}) {
  const get = fetchImpl || ((u, o) => fetch(u, o));
  async function fetchVerified(path, sha) {
    if (typeof sha !== 'string' || !/^[0-9a-f]{64}$/i.test(sha)) throw Error(`${path}: no valid SHA-256 given`);
    const res = await get(new URL(path, base).href, { cache: 'no-cache' });
    if (!res.ok) throw Error(`${path}: HTTP ${res.status}`);
    const bytes = await res.arrayBuffer();
    const hash = await sha256Bytes(bytes);
    if (!hash) throw Error(`${path}: this browser cannot check hashes here (needs https)`);
    if (hash !== sha.toLowerCase()) throw Error(`${path}: hash ${hash.slice(0, 12)} is not the expected ${sha.slice(0, 12)}`);
    return bytes;
  }
  async function fetchJSON(path, sha) {
    return JSON.parse(new TextDecoder().decode(await fetchVerified(path, sha)));
  }
  return Object.freeze({
    base,
    fetchVerified,
    fetchJSON,
    invalidate: (opts = {}) => invalidate({ ground: opts.ground !== false }),
    origin: () => { const o = origin(); return { e: o.e, n: o.n, id: o.id }; },
    lib: LIB
  });
}

// Line endings and a byte-order mark are normalised so a Windows checkout and the published file hash the same.
// This applies to layer code only; data files are hashed exactly as sent (see fetchVerified).
export const normalise = text => text.replace(/^/, '').replace(/\r\n/g, '\n');

export async function sha256(text) {
  return sha256Bytes(new TextEncoder().encode(text));
}

export async function sha256Bytes(bytes) {
  if (!globalThis.crypto?.subtle) return null;
  const digest = await crypto.subtle.digest('SHA-256', bytes);
  return [...new Uint8Array(digest)].map(b => b.toString(16).padStart(2, '0')).join('');
}