GLOBALGRID2050 / EXPLORE CODE

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

Project UI and 3 more files

A JavaScript module in the world folder of GlobalGrid2050 that draws sites and cables. It hides choice (`hideChoice`), sets tour (`setTour`) and refreshes phases (`refreshPhases`).

643 lines of JavaScript from globalgrid2050, in 4 files. Topic: Solar and storage design. Section 159 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. Labels electrical · globalgrid2050 / solar-design-studio/202609271552-site-world/world/labels.mjs lines 1–60
  2. Layers UI interaction · globalgrid2050 / solar-design-studio/202609271552-site-world/world/layers-ui.mjs lines 1–105
  3. Print Sheet render · globalgrid2050 / solar-design-studio/202609271552-site-world/world/print-sheet.mjs lines 1–223
  4. Project UI interaction · globalgrid2050 / solar-design-studio/202609271552-site-world/world/project-ui.mjs lines 1–255

Labels

A JavaScript module in the world folder of GlobalGrid2050 that works with 33kV and cables.

electricalglobalgrid2050 / solar-design-studio/202609271552-site-world/world/labels.mjs · lines 1–60 of 60 · version 2026-09-27 15:52 · Not reached from any entry point (candidate for review) · pattern designHint (shared by 2 files)

What it does
It calculates 33kV and cables. Defines 9 functions or classes, including circuits, voltage, basis, sectionLabel, conductorLabel.
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, 132kV, 1.5kV.
Inputs & outputs
Voltage levels named: 132kV, 33kV, 1.5kV.
Downstream impact
Used directly by 2 files: Design UI (globalgrid2050); First Showing (globalgrid2050).
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 First Showing.
Application
globalgrid2050 · solar-design-studio/202609271552-site-world/world · JavaScript module
Uses
none found
Used by
imported by Design UI (import), imported by First Showing (import)
Produces
sectionLabel, conductorLabel, cableLabel, pressWord, distanceLabel, designHint
Defines here
circuits, voltage, basis, sectionLabel, conductorLabel, cableLabel, pressWord, distanceLabel, designHint
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/202609271552-site-world/world/labels.mjs:1-60 · blob 0efa0ac14e48049488286ea78423d206eef36088 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: unreached_review
// 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 (/-agri/.test(id)) return 'farmland';
  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`);

const TOOL_WORD = { trench: 'Trench', cable: 'Cable', road: 'Road', pad: 'Pad', fence: 'Fence', piles: 'Pile row', hdd: 'Drilled crossing' };
// One line for the Design panel that says what to do next. view: 'choose' | 'draw' | 'result'; n: points drawn.
export function designHint(tool, view, n, press) {
  if (!tool) return view === 'result' ? 'Choose a design tool to draw again' : 'Choose a design tool';
  const p = press.toLowerCase();
  if (view === 'result' && !n) return `${TOOL_WORD[tool] || tool} finished. ${press} the ground to draw another.`;
  if (!n) return tool === 'pad' ? `${press} the pad centre or its corners, then Done` : `${press} two or more points on the ground, then Done`;
  return n === 1 && tool !== 'pad' ? `1 point · ${p} the next point` : `${n} point${n === 1 ? '' : 's'} · ${p} more, or Done`;
}

Layers UI

A JavaScript module in the world folder of GlobalGrid2050 that reads overhead lines (OHL). It writes footer (`writeFooter`), fits footer (`fitFooter`) and shows range (`showRange`).

interactionglobalgrid2050 / solar-design-studio/202609271552-site-world/world/layers-ui.mjs · lines 1–105 of 105 · version 2026-09-27 15:52 · Not reached from any entry point (candidate for review) · pattern mountLayersUi (shared by 2 files)

What it does
It loads overhead lines (OHL). Defines 8 functions or classes, including panelLayers, footerFor, applyOn, mountLayersUi, writeFooter. 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: overhead lines (OHL).
What it achieves
Page wiring for the Layers panel. It responds to resize and close events.
Why it matters
No other file in the estate was found to import it.
Application
globalgrid2050 · solar-design-studio/202609271552-site-world/world · JavaScript module
Uses
Layers Panel (import), Layers (import), Attribution (import), Range UI (import), Fade (import)
Used by
none found
Produces
DEFAULT_ON, panelLayers, footerFor, applyOn, mountLayersUi
Defines here
panelLayers, footerFor, applyOn, mountLayersUi, writeFooter, fitFooter, showRange, refresh
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/202609271552-site-world/world/layers-ui.mjs:1-105 · blob 35bda640fd88d5820b00a1eb7525c440b929c5a0 · 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
// Page wiring for the Layers panel. The panel sits inside the Controls panel (no dash button of its own).
// Switching a layer on calls its setEnabled(true) when it has one and lets the substrate draw it; switching it off
// hides it (item.hidden, which the substrate skips). The footer credits exactly the data on screen: every loaded
// base layer plus the optional layers switched on (layers-panel.mjs sourceKeysFor, attribution.mjs footerText).
import { OPTIONAL_LAYERS, START_OFF, createLayersPanel, shownIds, sourceKeysFor } from './layers-panel.mjs';
import { REFUSED } from './layers.mjs';
import { footerText, aboutList } from './attribution.mjs';
import { mountRange } from './range-ui.mjs';
import { MILE_M } from './fade.mjs';

const OPTIONAL = new Set(OPTIONAL_LAYERS.map(l => l.id));
// The grid network with its overhead line zones, and the roads and rail, show from the start (user test: roads were off).
export const DEFAULT_ON = Object.freeze(['grid', 'ohl-safety', 'ways']);

// The loader's items as the panel reads them: a loaded layer's own status line follows the hash check.
export function panelLayers(items) {
  return (items || []).map(it => {
    const own = it.layer && typeof it.layer.status === 'string' && it.layer.status ? it.layer.status : '';
    const loaded = !!it.layer && String(it.status).startsWith('loaded');
    const status = loaded && own ? (REFUSED.test(own) ? `${String(it.status).replace(/,? hash matches/, '')}; ${own}` : `${it.status}; ${own}`) : String(it.status);
    // The public words: the layer's own short summary if it gives one, else a plain word (the details stay in status).
    const short = /^ready/.test(String(it.status)) ? 'Off: loads when switched on.' : !loaded ? 'Not available here.' : own && REFUSED.test(own) ? 'Not available here: its data was refused.'
      : typeof it.layer?.summary === 'string' && it.layer.summary ? it.layer.summary : 'On.';
    return { id: it.id, status, short };
  });
}

// { full, short } footer text for the ids on screen.
export function footerFor(items, on, attribution, year) {
  const keys = sourceKeysFor(shownIds(panelLayers(items), on));
  const byLine = new Map(); // sources that share one required line (OS Open Rivers and Roads) are credited once
  for (const a of aboutList(keys, attribution, { year })) {
    const k = `${a.line} · ${a.licence_name}`;
    byLine.set(k, [...(byLine.get(k) || []), a.name]);
  }
  const full = [...byLine].map(([k, names]) => `${names.join(', ')}: ${k}`).join(' · ');
  return { full, short: footerText(keys, attribution, { year }) };
}

// Marks each optional item hidden unless it is on, and tells layers that load on demand.
export function applyOn(items, on) {
  const set = new Set(on);
  for (const it of items || []) {
    if (!OPTIONAL.has(it.id)) continue;
    const want = set.has(it.id);
    it.hidden = !want;
    if (want && !it.layer && typeof it.load === 'function') { it.load(); continue; } // first switch-on: fetch, check, start
    if (it.layer && typeof it.layer.setEnabled === 'function' && !!it.layer.enabled !== want) {
      try { it.layer.setEnabled(want); } catch (e) { it.layer = null; it.status = 'failed to switch and switched off: ' + e.message; }
    }
  }
}

// items: loadLayers(...).layers (live objects). host: element the panel goes in. footer: the #attribution element.
// Returns { panel, refresh() } or null when there is nothing to host it.
// onChange(ids) is called with the ids switched on, at start and after every change (e.g. to show the sun control).
export function mountLayersUi({ items, host, footer, attribution, invalidate = () => {}, on = DEFAULT_ON, year, onChange = () => {} } = {}) {
  if (!host) return null;
  const start = on.filter(id => !START_OFF.includes(id)).filter(id => panelLayers(items).some(l => l.id === id && l.status.startsWith('loaded')));
  applyOn(items, start);
  const writeFooter = ids => {
    if (!footer || !attribution) return;
    const f = footerFor(items, ids, attribution, year), full = footer.querySelector('.full'), short = footer.querySelector('.short');
    if (full) full.textContent = f.full; if (short) short.textContent = f.short;
    footer.title = f.full;
    fitFooter();
  };
  // On a phone the footer wraps to as many lines as the credit needs (world.html, max-width 600px); --foot-fit tells
  // everything placed above the footer how tall it came out, so no credit line is cut off.
  const fitFooter = () => {
    const h = footer?.scrollHeight, root = footer?.ownerDocument?.documentElement;
    if (Number.isFinite(h) && h > 0 && root?.style?.setProperty) root.style.setProperty('--foot-fit', `${h}px`);
  };
  if (footer && typeof globalThis.addEventListener === 'function') globalThis.addEventListener('resize', fitFooter);
  const panel = createLayersPanel(host, {
    layers: panelLayers(items), attribution, on: start, year,
    onToggle: (_id, _on, ids) => { applyOn(items, ids); writeFooter(ids); showRange(ids); onChange(ids); invalidate(); }
  });
  panel.element.classList.add('in-help');
  // Range (2, 5 or 10 miles) for the wider-area roads and rail, shown under the panel while that layer is on.
  let store = null;
  try { store = globalThis.localStorage || null; } catch { /* no storage */ }
  let range = null;
  try {
    range = mountRange(host, { store, coarse: !!globalThis.matchMedia?.('(pointer: coarse)').matches,
      layer: () => (items || []).find(it => it.id === 'national')?.layer || null, onChange: () => invalidate() });
  } catch { /* no document to draw it in (tests) */ }
  const showRange = ids => range?.show(ids.includes('national'));
  panel.element.addEventListener('close', () => { panel.element.hidden = false; }); // Escape closes Controls, not this part of it
  writeFooter(panel.onIds());
  showRange(panel.onIds());
  onChange(panel.onIds());
  let last = '';
  const refresh = () => { // statuses change as data streams in; redraw the panel only when they do
    if (panel.isOn('national')) range?.apply(); // the layer loads after its first switch-on, at its own start range
    const now = panelLayers(items), key = JSON.stringify(now);
    if (key === last) return;
    last = key;
    panel.update(now);
    applyOn(items, panel.onIds());
    writeFooter(panel.onIds());
  };
  // The wider-area range in metres while that layer is on (the drone's fade reaches it), else 0.
  return { panel, refresh, range, rangeM: () => (range && panel.isOn('national') ? range.miles() * MILE_M : 0) };
}

Print Sheet

A JavaScript module in the world folder of GlobalGrid2050 that clips def (`clipDef`) and draws SVG graphics, covering solar, overhead lines (OHL) and cables, using Helmert.

renderglobalgrid2050 / solar-design-studio/202609271552-site-world/world/print-sheet.mjs · lines 1–223 of 223 · version 2026-09-27 15:52 · Not reached from any entry point (candidate for review) · pattern buildSheet (shared by 2 files)

What it does
It draws solar, overhead lines (OHL) and cables. Defines 14 functions or classes, including legendLabel, dataDate, sheetDate, f, t. 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, overhead lines (OHL), cables.
Inputs & outputs
Out: SVG drawing. Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid).
What it achieves
It builds sheet (`buildSheet`) and is built from the legend label helper (`legendLabel`) and the data date helper (`dataDate`). The whole print sheet as one SVG string: plan, current view, north arrow, scale bar, National Grid references, title block and the credit for exactly the loaded layers.
Why it matters
No other file in the estate was found to import it.
Application
globalgrid2050 · solar-design-studio/202609271552-site-world/world · JavaScript module
Uses
Attribution (import), Print Layout (import), Print SVG (import)
Used by
none found
Produces
NOT_FOR_CONSTRUCTION, CAVEAT, NO_CREDIT, legendLabel, dataDate, sheetDate, buildSheet, legendOf
Defines here
legendLabel, dataDate, sheetDate, f, t, rect, clipDef, stroke, tag, buildSheet, dateYear, viewerMark, legendOf, titleBlock
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/202609271552-site-world/world/print-sheet.mjs:1-223 · blob 22583d327f30ccb8b3acbd26b5e19fcb623e9753 · 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
// The whole print sheet as one SVG string: plan, current view, north arrow, scale bar, National Grid
// references, title block and the credit for exactly the loaded layers. Pure: no DOM, no WebGL.
// Style after the GridAtlas print furniture: monospace, letter-spaced heading, the credit beneath the
// drawing and a stamp; here the stamp grows into a title block with the layers shown and the warning.

import { footerText, unknownLayers } from './attribution.mjs';
import { sheetLayout, fitCredit, wrapText } from './print-layout.mjs';
import {
  FONT, INK, MUTED, RULE, esc, inkFor, planPaths, viewPaths, northArrow, scaleBarSvg, gridSvg,
  planFrame, scaleBar, gridTicks, refAt, trueNorthOffset, bearingText,
} from './print-svg.mjs';

export const NOT_FOR_CONSTRUCTION = 'NOT FOR CONSTRUCTION';
export const CAVEAT = 'Illustrative only. Positions are converted to the British National Grid by a Helmert transformation '
  + '(about 3.5 m); nothing here is surveyed, designed or checked.';
export const NO_CREDIT = 'No third-party data is shown on this sheet.';
// The viewer's own drawing (the design) needs no third-party credit.
// This tool's own illustrative work (and lines derived from a credited layer, such as the overhead line zones from the
// grid): no third-party credit of its own.
const OWN_WORK = /^(design|plant|block|piles|pile|sld|module|cmd|follow|ohl-safety|zones)(-|$)/;
// Legend words for layer ids: numbered items fold into one entry, and no internal id reaches the sheet (user test H8).
const LEGEND_WORDS = [[/^design-trench/, 'Trenches'], [/^design-section/, 'Trench sections'], [/^design-cable/, 'Cables'], [/^design/, 'Design'],
  [/^plant-piles|^piles/, 'Piles'], [/^plant/, 'Solar plant'], [/^block-tables/, 'Solar block tables'], [/^block-strings/, 'Solar block strings'],
  [/^block-(dc|ac|mv|pull)/, 'Solar block cables'], [/^block/, 'Solar block'], [/^ohl-safety|^zones/, 'Overhead line zones'],
  [/^ground-grid/, 'Ground grid'], [/^grid/, 'Grid network'], [/^sld/, 'Single-line diagram'], [/^module/, 'Module detail']];
export function legendLabel(id) {
  const w = LEGEND_WORDS.find(([re]) => re.test(id));
  if (w) return w[1];
  const s = String(id).replace(/-\d+$/, '').replace(/[-_]+/g, ' ').trim();
  return s ? s[0].toUpperCase() + s.slice(1) : 'Lines';
}
// "202609262035" -> "26 September 2026, 20:35"; anything else is left off the sheet (never a raw stamp).
export function dataDate(g) {
  const m = /^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})$/.exec(String(g || ''));
  if (!m) return '';
  return `${sheetDate(`${m[1]}-${m[2]}-${m[3]}T00:00:00Z`)}, ${m[4]}:${m[5]}`;
}

// 26 September 2026 (British order, month in words so it cannot be misread).
export function sheetDate(date) {
  const d = date instanceof Date ? date : new Date(date ?? Date.now());
  if (Number.isNaN(d.getTime())) throw Error('sheetDate needs a valid date');
  const months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
  return `${d.getUTCDate()} ${months[d.getUTCMonth()]} ${d.getUTCFullYear()}`;
}

const f = v => (Math.round(v * 100) / 100).toString();
const t = (x, y, s, size, extra = '') => `<text x="${f(x)}" y="${f(y)}" font-size="${f(size)}"${extra}>${esc(s)}</text>`;
const rect = (r, extra = '') => `<rect x="${f(r.x)}" y="${f(r.y)}" width="${f(r.w)}" height="${f(r.h)}"${extra}/>`;
const clipDef = (id, r) => `<clipPath id="${id}">${rect(r)}</clipPath>`;
const stroke = (p, w) => `<path d="${p.d}" stroke="${p.stroke}" stroke-opacity="${f(p.opacity)}" stroke-width="${w}" fill="none" stroke-linecap="round"/>`;

// A small label with a white backing, so it reads over the drawing.
function tag(x, y, s, size = 2.1, extra = '') {
  const w = s.length * size * 0.6 + 2;
  return `<rect x="${f(x)}" y="${f(y)}" width="${f(w)}" height="${f(size + 1.6)}" fill="#fff" fill-opacity="0.9"/>`
    + t(x + 1, y + size + 0.5, s, size, ` fill="${INK}"${extra}`);
}

// opts:
//   paper        'A3' | 'A4'                 batches   the world's line batches (as given to lines.draw)
//   camera       { pos, yaw, pitch, fov?, label?, eyeHeight? }    origin  { e, n } National Grid metres
//   site         { name }  a neutral name      layerIds  ids of the loaded layers   attribution  data/attribution.json
//   date         Date or ISO string          generation  manifest generation stamp (optional)
//   viewImage    { href, width, height }: the captured frame; omit for a vector redraw of the view
//   extent       { x0, y0, x1, y1 } local metres to frame the plan (default: the batches' bounds, capped)
//   fade         metres at which lines vanish (the world's FADE_M)
// Returns { svg, meta }. meta repeats the facts on the sheet so a caller or a test can check them.
export function buildSheet(opts) {
  const { paper = 'A3', batches = [], camera, origin = { e: 0, n: 0 }, site = {}, layerIds = [], attribution,
    date, generation = '', viewImage = null, extent = null, fade = 450 } = opts || {};
  if (!camera || !Array.isArray(camera.pos)) throw Error('buildSheet needs the camera { pos, yaw, pitch }');
  if (!attribution) throw Error('buildSheet needs the attribution data; a sheet is never printed without its credit');
  const aspect = viewImage && viewImage.width > 0 ? viewImage.height / viewImage.width : camera.aspect;
  const L = sheetLayout(paper, { aspect });
  const frame = planFrame(L, { batches, extent, centre: extent ? null : [camera.pos[0], camera.pos[1]] });
  const ticks = gridTicks(frame, L, origin);
  const bar = scaleBar(frame, L);
  const ce = origin.e + frame.centre[0], cn = origin.n + frame.centre[1];
  const tn = trueNorthOffset(ce, cn);
  const centreRef = refAt(origin, frame.centre[0], frame.centre[1], 10);
  const eyeRef = refAt(origin, camera.pos[0], camera.pos[1], 10);
  // Credit what is loaded and what is drawn; anything drawn without a registered credit is named on the sheet.
  const legend = legendOf(batches);
  const creditIds = [...new Set([...layerIds, ...legend.map(e => e.name)])].filter(id => !OWN_WORK.test(id));
  const credit = footerText(creditIds, attribution, { year: dateYear(date) });
  const missing = unknownLayers(creditIds, attribution);
  const creditText = [credit || (missing.length ? '' : NO_CREDIT),
    missing.length ? `${missing.length === 1 ? 'One drawn layer has' : `${missing.length} drawn layers have`} no source credit registered here: check before issue.` : '']
    .filter(Boolean).join(' · ');
  const name = String(site.name || 'Unnamed site');
  const dateText = sheetDate(date);
  const heightOk = Number.isFinite(camera.eyeHeight);

  const out = [
    `<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="${L.paper.w}mm" height="${L.paper.h}mm" `
      + `viewBox="0 0 ${L.paper.w} ${L.paper.h}" font-family="${esc(FONT)}" data-paper="${L.paper.name}" data-scale="${frame.scale}">`,
    `<title>${esc(`${name}: plan and view, ${L.paper.name} landscape`)}</title>`,
    `<defs>${clipDef('plan-clip', L.planDraw)}${clipDef('view-clip', L.view)}</defs>`,
    `<rect width="${L.paper.w}" height="${L.paper.h}" fill="#fff"/>`,
    rect(L.frame, ` fill="none" stroke="${INK}" stroke-width="0.5"`),
  ];

  // Plan
  out.push(rect(L.plan, ` fill="none" stroke="${INK}" stroke-width="0.3"`), rect(L.planDraw, ` fill="none" stroke="${INK}" stroke-width="0.2"`));
  out.push(gridSvg(ticks, L));
  out.push('<g clip-path="url(#plan-clip)">', ...planPaths(batches, frame, L).map(p => stroke(p, 0.15)));
  const [ex, ey] = [L.planDraw.x + L.planDraw.w / 2 + (camera.pos[0] - frame.centre[0]) / frame.mPerMM,
    L.planDraw.y + L.planDraw.h / 2 - (camera.pos[1] - frame.centre[1]) / frame.mPerMM];
  out.push(viewerMark(ex, ey, camera.yaw), '</g>');
  const d = L.planDraw;
  out.push(tag(d.x + 1.5, d.y + 1.5, 'PLAN · straight down, grid north up', 2.1, ' letter-spacing="0.15"'));
  // The north arrow on its own clear zone: opaque, outlined, a margin round the arrow (nothing drawn shows through).
  out.push(`<rect x="${f(d.x + d.w - 19)}" y="${f(d.y + 1)}" width="18" height="${L.small ? 25 : 28}" fill="#fff" stroke="${RULE}" stroke-width="0.2"/>`);
  out.push(northArrow(d.x + d.w - 9.5, d.y + 12, L.small ? 9 : 11, tn));
  out.push(`<rect x="${f(d.x + 2)}" y="${f(d.y + d.h - 12)}" width="${f(bar.mm + 10)}" height="10" fill="#fff" fill-opacity="0.9"/>`);
  out.push(scaleBarSvg(bar, d.x + 5, d.y + d.h - 8.5, frame.scale));

  // Current view
  const v = L.view;
  out.push(rect(v, ` fill="${viewImage ? '#0a0a0a' : '#fff'}" stroke="none"`), '<g clip-path="url(#view-clip)">');
  if (viewImage) {
    out.push(`<image x="${f(v.x)}" y="${f(v.y)}" width="${f(v.w)}" height="${f(v.h)}" preserveAspectRatio="xMidYMid meet" `
      + `href="${esc(viewImage.href)}" xlink:href="${esc(viewImage.href)}"/>`);
  } else {
    out.push(...viewPaths(batches, camera, v, { fade }).map(p => stroke(p, 0.18)));
  }
  out.push('</g>', rect(v, ` fill="none" stroke="${INK}" stroke-width="0.3"`));
  const how = viewImage ? 'the frame on screen when printed' : 'redrawn from the same lines; ground does not hide lines here';
  out.push(tag(v.x + 1.5, v.y + 1.5, 'CURRENT VIEW', 2.1, ' letter-spacing="0.15"'));
  const look = `${camera.label || 'View'} · looking ${bearingText(camera.yaw)}` + (heightOk ? ` · eye ${camera.eyeHeight.toFixed(1)} m above ground` : '');
  out.push(tag(v.x + 1.5, v.y + v.h - 9.2, look, 1.9), tag(v.x + 1.5, v.y + v.h - 4.8, how, 1.9));

  // Credit (under the plan): exactly the loaded layers' lines, never trimmed
  const c = L.credit, headSize = 2.2;
  out.push(rect(c, ` fill="none" stroke="${INK}" stroke-width="0.3"`));
  out.push(t(c.x + 2, c.y + 4, 'DATA SHOWN ON THIS SHEET', headSize, ` fill="${INK}" letter-spacing="0.4"`));
  const fit = fitCredit(creditText, c.w - 4, c.h - 7.5);
  fit.lines.forEach((line, i) => out.push(t(c.x + 2, c.y + 7 + fit.size * (1 + i * 1.3), line, fit.size, ` fill="${MUTED}"`)));

  // Title block (under the view)
  out.push(titleBlock(L, { name, dateText, frame, centreRef, eyeRef, generation, tn, legend }));
  out.push('</svg>');
  const meta = { paper: L.paper.name, scale: frame.scale, centreRef, eyeRef, credit, creditFits: fit.fits,
    creditComplete: missing.length === 0, creditMissing: missing, squares: ticks.squares,
    creditSize: fit.size, trueNorth: tn, gridSpacing: ticks.spacing, scaleBar: bar.label, date: dateText,
    view: viewImage ? 'image' : 'vector', layers: legend.map(e => e.name) };
  return { svg: out.join(''), meta };
}

function dateYear(date) {
  const d = date instanceof Date ? date : new Date(date ?? Date.now());
  return Number.isNaN(d.getTime()) ? undefined : d.getUTCFullYear();
}

// The viewer's position and heading on the plan: a small circle and a tick along the look direction.
function viewerMark(x, y, yaw) {
  const dx = Math.sin(yaw) * 4, dy = -Math.cos(yaw) * 4;
  return `<g stroke="#b00020" stroke-width="0.35" fill="none"><circle cx="${f(x)}" cy="${f(y)}" r="1.2"/>`
    + `<path d="M${f(x)} ${f(y)}L${f(x + dx)} ${f(y + dy)}"/></g>`;
}

// One legend entry per layer: batch keys are "layer/part", so the part before the slash names the layer.
export function legendOf(batches) {
  const seen = new Map();
  for (const b of batches || []) {
    if (b.occluder || !b.positions || !b.key) continue;
    const name = String(b.key).split('/')[0];
    if (!seen.has(name)) seen.set(name, inkFor(b.color));
  }
  return [...seen].map(([name, ink]) => ({ name, ...ink }));
}

function titleBlock(L, { name, dateText, frame, centreRef, eyeRef, generation, tn, legend: drawn }) {
  let legend = drawn;
  const r = L.title, out = [rect(r, ` fill="none" stroke="${INK}" stroke-width="0.3"`)];
  const x = r.x + 2.5, size = L.small ? 1.9 : 2.5, row = size * 1.5, cs = L.small ? 1.6 : 1.9;
  out.push(t(x, r.y + 4, 'SITE WORLD · PLAN AND VIEW', 1.9, ` fill="${MUTED}" letter-spacing="0.45"`));
  const nameSize = L.small ? 3.6 : 5.2;
  out.push(t(x, r.y + 5.5 + nameSize, wrapText(name, r.w - 5, nameSize)[0] || '', nameSize, ` fill="${INK}" font-weight="700"`));
  const rows = [
    ['Centre', centreRef || 'off the National Grid'],
    ['Viewer', eyeRef || 'off the National Grid'],
    ['Scale', `1:${frame.scale.toLocaleString('en-GB')} at ${L.paper.name} · grid north up`],
    ['North', tn === null ? 'off the National Grid' : Math.abs(tn) < 0.005 ? 'true north on grid north'
      : `true north ${Math.abs(tn).toFixed(2)}° ${tn >= 0 ? 'east' : 'west'} of grid north`],
    ['Date', dateText],
  ];
  if (dataDate(generation)) rows.push(['Data', `as of ${dataDate(generation)}`]);
  let y = r.y + 7 + nameSize + 3.2;
  for (const [k, val] of rows) {
    out.push(t(x, y, k.toUpperCase(), size * 0.9, ` fill="${MUTED}" letter-spacing="0.25"`), t(x + size * 6.5, y, val, size, ` fill="${INK}"`));
    y += row;
  }
  // The warning: a boxed band across the foot of the block, the caveat above it
  const bandH = L.small ? 6 : 7, by = r.y + r.h - bandH - 1.5;
  const cav = wrapText(CAVEAT, r.w - 5, cs), cavTop = by - 1.2 - (cav.length - 1) * cs * 1.3 - cs;
  // Layers between the rows and the caveat, in two columns, as many as there is room for
  out.push(`<path d="M${f(r.x)} ${f(y - size + 0.6)}H${f(r.x + r.w)}" stroke="${RULE}" stroke-width="0.15"/>`);
  y += 1.6;
  out.push(t(x, y, 'LAYERS DRAWN', size * 0.9, ` fill="${MUTED}" letter-spacing="0.25"`));
  y += row;
  const colW = (r.w - 5) / 2, fit = Math.max(0, Math.floor((cavTop - 2 - (y - size)) / row)) * 2;
  const byLabel = new Map();
  for (const e of legend) if (!byLabel.has(legendLabel(e.name))) byLabel.set(legendLabel(e.name), { ...e, name: legendLabel(e.name) });
  legend = [...byLabel.values()];
  const shown = legend.length > fit ? legend.slice(0, Math.max(0, fit - 1)) : legend;
  shown.forEach((e, i) => {
    const cx = x + (i % 2) * colW, cy = y + Math.floor(i / 2) * row;
    out.push(`<path d="M${f(cx)} ${f(cy - size * 0.35)}h5" stroke="${e.stroke}" stroke-opacity="${f(e.opacity)}" stroke-width="0.6"/>`,
      t(cx + 6.5, cy, e.name, size, ` fill="${INK}"`));
  });
  if (shown.length < legend.length) {
    const i = shown.length;
    out.push(t(x + (i % 2) * colW, y + Math.floor(i / 2) * row, `and ${legend.length - shown.length} more`, size, ` fill="${MUTED}"`));
  }
  if (!legend.length) out.push(t(x, y, 'none', size, ` fill="${MUTED}"`));
  cav.forEach((line, i) => out.push(t(x, by - 1.2 - (cav.length - 1 - i) * cs * 1.3, line, cs, ` fill="${MUTED}"`)));
  out.push(`<rect x="${f(r.x + 1.5)}" y="${f(by)}" width="${f(r.w - 3)}" height="${bandH}" fill="none" stroke="#b00020" stroke-width="0.5"/>`);
  out.push(t(r.x + r.w / 2, by + bandH / 2 + (L.small ? 1.3 : 1.5), NOT_FOR_CONSTRUCTION, L.small ? 3.4 : 4,
    ' fill="#b00020" font-weight="700" text-anchor="middle" letter-spacing="0.6"'));
  return out.join('');
}

Project UI

A JavaScript module in the world folder of GlobalGrid2050 that draws sites and cables. It hides choice (`hideChoice`), sets tour (`setTour`) and refreshes phases (`refreshPhases`).

interactionglobalgrid2050 / solar-design-studio/202609271552-site-world/world/project-ui.mjs · lines 1–255 of 255 · version 2026-09-27 15:52 · Not reached from any entry point (candidate for review) · pattern refreshPhases (shared by 2 files)

What it does
It draws sites and cables. Defines 19 functions or classes, including save, plain, mountProject, $, note. 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.
Inputs & outputs
In: JSON file sites.json.
What it achieves
Project tools, placed under the dash's essentials: the design file (Save, Open, Share, Print), Tour and Construction phases in the Design panel; Test sites in the Find panel. It responds to click, change and toggle events.
Why it matters
No other file in the estate was found to import it.
Application
globalgrid2050 · solar-design-studio/202609271552-site-world/world · JavaScript module
Uses
Design Store (import), Tour (import), Print (import), Phases (import), Phases Design (import), Phases Slider (import), Sites UI (import)
Used by
none found
Produces
mountProject
Defines here
save, plain, mountProject, $, note, pts, toDoc, fromDoc, path, of, flyToDesign, hideChoice, shareTab, offerChoice, b, press, setTour, refreshPhases, ready
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/202609271552-site-world/world/project-ui.mjs:1-255 · blob b12cf95389f6f2a7a36af1ecd1e11f478ef3e748 · 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
// Project tools, placed under the dash's essentials: the design file (Save, Open, Share, Print), Tour and
// Construction phases in the Design panel; Test sites in the Find panel.
// It wires existing cartridges to the world through the substrate's extension api; it draws nothing itself.
//   design-store.mjs   the design as a world.design.v1 document in national-grid metres; kept in this browser
//   tour.mjs           record a walk or flight, play it back, save it; Open reads tour files too
//   print.mjs          the plan sheet (A3 or A4) with the current view and the exact credit
//   phases*.mjs        the construction sequence of the drawn trenches and cables, as a step slider with order checks
//   sites-ui.mjs       the staged sites (data/sites.json, local only); choosing one reloads the page with ?site=<name>
import { SCHEMA, exportFile, importText, makeShareLink, readShareLink, autosave, loadAutosave } from './design-store.mjs';
import { createRecorder, exportTour, importTour, createPlayer, fileRefusal } from './tour.mjs';
import { buildSheet, captureView, openSheet } from './print.mjs';
import { createTimeline, validatePlan } from './phases.mjs';
import { itemsFromStore } from './phases-design.mjs';
import { createPhaseSlider } from './phases-slider.mjs';
import { parseSites, createSiteChooser, mountSiteSelect } from './sites-ui.mjs';

const SITES_URL = './world/data/sites.json';
const WORKS = ['road', 'pad', 'fence', 'piles', 'hdd']; // earthworks kinds (design-earthworks.mjs), kept with the design

export { siteFromUrl } from './sites-ui.mjs'; // kept here for callers of the old place

function save(doc, name, text, type = 'application/json') {
  const url = URL.createObjectURL(new Blob([text], { type })), a = doc.createElement('a');
  a.href = url; a.download = name; doc.body.appendChild(a); a.click();
  setTimeout(() => { URL.revokeObjectURL(url); a.remove(); }, 30000);
}
const plain = o => JSON.parse(JSON.stringify(o)); // drops undefined, so params stay plain JSON

export function mountProject(api, doc = document) {
  const $ = id => doc.getElementById(id);
  const note = msg => { $('project-note').textContent = msg; };
  const s0 = api.site(), o0 = api.origin();
  const site = s0 ? { name: s0.name, origin_e: s0.centre_e, origin_n: s0.centre_n } : { name: 'untitled', origin_e: o0.e, origin_n: o0.n };
  let generation = 0;

  // ---- design file ------------------------------------------------------------------------------------
  const pts = path => path.map(p => [p.e, p.n]);
  function toDoc() {
    const d = api.design();
    const items = [
      ...d.trenches.map((t, i) => ({ id: `trench-${i + 1}`, kind: 'trench', params: plain({ section: t.section }), points_bng: pts(t.path) })),
      ...d.cables.map((c, i) => ({ id: `cable-${i + 1}`, kind: 'cable', params: plain({ section: c.section, cable: c.cable }), points_bng: pts(c.path) })),
      ...(d.works || []).map((w, i) => ({ id: `${w.kind}-${i + 1}`, kind: w.kind, params: plain({ option: w.option, ...(w.cable ? { cable: w.cable } : {}) }), points_bng: pts(w.path) })),
      ...[...(api.hooks.items || [])].flatMap(f => f()) // the typed script (cmd-mount.mjs): { kind: 'script', params: { lines } }
    ];
    return { schema: SCHEMA, generation, site: { ...site }, items };
  }
  // quiet: a design that only arrived (a shared link) is shown but not yet kept over the one in this browser.
  let quiet = false, opened = null;
  function fromDoc(d, { keep = true } = {}) {
    const path = it => it.points_bng.map(([e, n]) => ({ e, n }));
    const of = kind => d.items.filter(i => i.kind === kind);
    generation = Math.max(generation, d.generation);
    const works = d.items.filter(i => WORKS.includes(i.kind)).map(i => ({ kind: i.kind, option: i.params?.option, ...(i.params?.cable ? { cable: i.params.cable } : {}), path: path(i) }));
    api.replaceDesign({
      trenches: of('trench').map(i => ({ path: path(i), section: i.params.section })),
      cables: of('cable').map(i => ({ path: path(i), section: i.params.section, cable: i.params.cable })),
      works
    });
    quiet = !keep; opened = d;
    api.hooks.design.forEach(f => f());
    api.hooks.open?.forEach(f => f(d)); // a typed script in the file replays
    return of('trench').length + of('cable').length + works.length;
  }
  // The drone flies to a design that arrived from a link or a file, framing all its points (phone review 4).
  function flyToDesign(d) {
    const pts = d.items.flatMap(i => i.points_bng || []);
    if (!pts.length || typeof api.flyTo !== 'function') return;
    const es = pts.map(p => p[0]), ns = pts.map(p => p[1]);
    const e = (Math.min(...es) + Math.max(...es)) / 2, n = (Math.min(...ns) + Math.max(...ns)) / 2;
    const span = Math.max(Math.max(...es) - Math.min(...es), Math.max(...ns) - Math.min(...ns));
    const o = api.origin(), p = api.state().pos;
    if (Math.hypot(o.e + p[0] - e, o.n + p[1] - n) < 30 && span < 60) return; // already there
    api.flyTo(e - o.e, n - o.n, { height: Math.min(1500, Math.max(80, span * 1.2)) });
  }
  // Every change is kept in this browser, per site; a shared link or a file replaces it only when asked.
  api.hooks.design.add(() => {
    generation++;
    if (quiet) quiet = false; else { autosave(toDoc()); hideChoice(); }
    if (!$('design').hidden && $('phases-fold').open) refreshPhases();
  });
  // A shared link that arrives while a design is kept here: both stay; the viewer chooses which to show.
  const choice = doc.createElement('div');
  choice.className = 'row'; choice.id = 'share-choice'; choice.hidden = true;
  $('project-note').after(choice);
  function hideChoice() { choice.hidden = true; choice.replaceChildren(); }
  // The choice sits in the Design panel's Share tab (design-tabs.mjs): show that tab, whether or not the tabs are wired yet.
  function shareTab() {
    for (const t of doc.querySelectorAll('#design [role="tab"]')) {
      const on = t.dataset.tab === 'share', p = $(t.getAttribute('aria-controls'));
      t.setAttribute('aria-selected', String(on)); t.tabIndex = on ? 0 : -1; if (p) p.hidden = !on;
    }
    $('design-tab-share-btn')?.click(); // once the tabs are wired, they keep their own record in step
  }
  function offerChoice(shared, mine) {
    const b = (id, label, fn) => { const e = doc.createElement('button'); e.type = 'button'; e.id = id; e.textContent = label; e.addEventListener('click', fn); return e; };
    choice.replaceChildren(
      b('share-open', 'Open shared design', () => {
        hideChoice();
        note(`Opened the shared design: ${fromDoc(shared, { keep: false })} items. Your own is kept until you change this one.`);
        flyToDesign(shared);
      }),
      b('share-keep', 'Keep mine', () => { hideChoice(); note(`Kept your design: ${fromDoc(mine, { keep: false })} items.`); }));
    choice.hidden = false;
    shareTab();
  }

  $('project-save').addEventListener('click', async () => {
    try { const f = await exportFile(toDoc()); save(doc, f.filename, f.text); note(`Saved ${f.filename}.`); }
    catch (e) { note('Could not save: ' + e.message); }
  });
  $('project-open').addEventListener('click', () => $('project-file').click());
  $('project-file').addEventListener('change', async () => {
    const file = $('project-file').files?.[0];
    $('project-file').value = '';
    if (!file) return;
    const refused = fileRefusal(file.size); // before reading: an over-size file is never loaded into memory
    if (refused) { note(`File refused: ${refused}.`); return; }
    const text = await file.text();
    if (text.includes('"world.tour.v1"')) {
      try { setTour(await importTour(text)); note(`Opened tour "${tour.name || file.name}". Press Play.`); }
      catch (e) { note('Tour refused: ' + e.message); }
      return;
    }
    const r = await importText(text);
    note(r.ok ? `Opened ${file.name}: ${fromDoc(r.doc)} items.` : 'File refused: ' + r.errors.join('; '));
    if (r.ok) flyToDesign(r.doc);
  });
  $('project-share').addEventListener('click', async () => {
    const r = await makeShareLink(toDoc());
    if (!r.ok) { note(r.errors.join('; ')); return; }
    const url = location.href.split('#')[0] + r.fragment, box = $('project-link');
    try { await navigator.clipboard.writeText(url); box.hidden = true; note(`Share link copied (${url.length} characters).`); }
    catch { box.value = url; box.hidden = false; box.select(); note('Copy the link above to share this design.'); }
  });

  // ---- print --------------------------------------------------------------------------------------------
  $('project-print').addEventListener('click', () => {
    const attribution = api.attribution();
    if (!attribution) { note('Print needs the data credits, which did not load.'); return; }
    const image = captureView(api.canvas, api.redraw); // redraw and read in the same task, or the copy is blank
    const s = api.state(), g = api.heightAt(s.pos[0], s.pos[1]);
    openSheet(paper => buildSheet({
      paper, batches: api.batches(), attribution, viewImage: image, fade: api.FADE_M,
      camera: { pos: s.pos, yaw: s.yaw, pitch: s.pitch, fov: api.FOV, label: api.VIEWS[s.view].label, eyeHeight: s.pos[2] - g,
        aspect: api.canvas.height / api.canvas.width },
      origin: api.origin(), site: { name: site.name }, generation: api.generation(), layerIds: api.live().map(l => l.id)
    }));
  });

  // ---- tour ---------------------------------------------------------------------------------------------
  let recorder = null, t0 = 0, tour = null, player = null;
  const caption = $('tour-caption');
  const press = (id, on, label) => { $(id).setAttribute('aria-pressed', String(on)); $(id).textContent = label; };
  function setTour(t) {
    player?.pause(); player = null; tour = t;
    $('tour-play').disabled = $('tour-save').disabled = false;
    press('tour-play', false, 'Play');
  }
  api.hooks.before.add(now => {
    if (recorder) recorder.sample((now - t0) / 1000, api.origin(), api.state());
    if (player?.playing) {
      // Any movement takes the camera back; the substrate's gate carries on at the walking rate (review A, 3).
      if (api.moving()) { player.pause(); press('tour-play', false, 'Play'); api.resumeGate?.(); }
      else player.frame(now);
    }
  });
  $('tour-record').addEventListener('click', () => {
    if (!recorder) {
      player?.pause();
      recorder = createRecorder({ kind: api.state().view === 'aerial' ? 'drone' : 'walk', name: `${site.name} tour` });
      t0 = performance.now(); recorder.sample(0, api.origin(), api.state());
      press('tour-record', true, 'Stop');
      note('Recording: walk or fly, then press Stop.');
      return;
    }
    recorder.sample((performance.now() - t0) / 1000, api.origin(), api.state());
    try { setTour(recorder.stop()); note(`Tour recorded: ${tour.keyframes.length} keyframes. Play it or save it.`); }
    catch (e) { note('Nothing kept: ' + e.message + '. Move while recording.'); }
    recorder = null;
    press('tour-record', false, 'Record');
  });
  $('tour-play').addEventListener('click', () => {
    if (!tour) return;
    if (player?.playing) { player.pause(); press('tour-play', false, 'Play'); return; }
    if (!player) {
      api.setView(tour.kind === 'drone' ? 'aerial' : 'standing');
      player = createPlayer(tour, {
        gate: api.gate, getOrigin: api.origin, apply: pose => api.setPose(pose),
        onCaption: text => { caption.textContent = text; caption.hidden = !text; },
        onEnd: () => press('tour-play', false, 'Play')
      });
    }
    player.play();
    press('tour-play', true, 'Pause');
  });
  $('tour-save').addEventListener('click', async () => {
    if (!tour) return;
    try { save(doc, `${site.name}-tour.json`, await exportTour(tour)); note('Tour saved.'); } catch (e) { note('Could not save the tour: ' + e.message); }
  });

  // ---- construction phases ------------------------------------------------------------------------------
  function refreshPhases() {
    const box = $('phases-box'), check = $('phases-check');
    box.replaceChildren();
    let items, v;
    try { items = itemsFromStore(toDoc()); if (items.length) { createPhaseSlider(box, createTimeline(items)); v = validatePlan(items); } }
    catch (e) { check.textContent = 'Construction phases not shown: ' + e.message; return; }
    if (!items.length) { check.textContent = 'Draw a trench or cable in Design to sequence its construction.'; return; }
    const skipped = v.warnings.filter(w => w.code === 'BAD_REF').map(w => w.message).join(' ');
    check.textContent = (v.ok ? `Order checks: no problems across ${items.length} items.`
      : `Order checks: ${v.errors.map(e => e.message).join(' ')}`) + (skipped ? ` Skipped: ${skipped}` : '');
  }
  $('phases-fold').addEventListener('toggle', () => { if ($('phases-fold').open) refreshPhases(); });

  // ---- site ---------------------------------------------------------------------------------------------
  (async () => {
    let sites = [];
    try { const r = await fetch(SITES_URL, { cache: 'no-cache' }); if (r.ok) sites = parseSites(await r.json()).sites; } catch { /* none staged */ }
    if (!sites.length) return; // the Site section stays hidden where no sites are staged
    // Test sites are a developer's list: shown on a local server or with ?sites, never on the public page (user test).
    const dev = /^(localhost|127\.0\.0\.1|\[::1\])$/.test(location.hostname) || new URLSearchParams(location.search).has('sites');
    if (!dev) return;
    const chooser = createSiteChooser(sites, {
      current: s0?.name ?? null,
      onChoose: s => { const u = new URL(location.href); u.searchParams.set('site', s.name); u.hash = ''; location.assign(u.href); }
    });
    const select = mountSiteSelect(doc, $('site-box'), chooser);
    $('site-section').hidden = false;
    // Find can fly far from the site: then no site is current and the picker works again (phone review 5).
    let away = false;
    api.hooks.after.add(() => {
      if (away || !chooser.current) return;
      const o = api.origin(), p = api.state().pos, c = chooser.current;
      if (Math.hypot(o.e + p[0] - c.centre_e, o.n + p[1] - c.centre_n) > 3000) { away = true; chooser.leave(); select.value = ''; }
    });
  })();

  // ---- start: a shared link never overwrites the copy kept in this browser without asking -----------------
  const ready = (async () => {
    const kept = await loadAutosave(site), mine = kept.ok && kept.doc.items.length ? kept.doc : null;
    if (/(^#|&)design=/.test(location.hash)) {
      const r = await readShareLink(location.hash);
      if (!r.ok) { note('Shared link refused: ' + r.errors.join('; ')); if (mine) fromDoc(mine, { keep: false }); return; }
      const same = mine && JSON.stringify(mine.items) === JSON.stringify(r.doc.items);
      if (!mine || same) { note(`Opened the shared design: ${fromDoc(r.doc)} items.`); flyToDesign(r.doc); return; }
      note(`This link carries a design (${r.doc.items.length} items); yours (${fromDoc(mine, { keep: false })} items) is shown and kept.`);
      offerChoice(r.doc, mine);
      return;
    }
    if (mine) note(`Restored the design kept in this browser: ${fromDoc(mine, { keep: false })} items.`);
  })();

  return Object.freeze({ ready, toDoc, opened: () => opened, tour: () => tour, playing: () => !!player?.playing, recording: () => !!recorder });
}