GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Cables and conductors / testcode / sandbox/202609060432/cable

Layers Panel and 2 more files (part 1)

A JavaScript module in the iterations folder of Galaxies Wafers using data from the ventus-grid-engine repository. Served with the page at https://ventusltd.github.io/galaxies-wafers/iterations/01-route-alpha/.

556 lines of JavaScript and Python from testcode, galaxies-wafers, in 3 files. Topic: Cables and conductors. Section 39 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. Sandbox — Cable electrical · testcode / sandbox/202609060432/cable/app.js lines 1147–1213
  2. Build Cable Candidate electrical · testcode / sandbox/tools/build-cable-candidate.py lines 1–47
  3. Layers Panel render · galaxies-wafers / iterations/01-route-alpha/layers-panel.mjs lines 1–442

Sandbox — Cable

A JavaScript file in Testcode that clamps integer (`clampInteger`), formats mm (`formatMm`), gets min burial depth (`getMinBurialDepth`) and draws on a canvas (units: mm², kV).

electricaltestcode / sandbox/202609060432/cable/app.js · lines 1147–1213 of 1213 · version 2026-09-06 04:32 (continued from section 37) · Not reached from any entry point (candidate for review) · pattern normaliseBurialDepthFieldOnBlur (shared by 4 files)

What it does
It draws cables. Defines 50 functions or classes, including byId, clampInteger, formatMm, effectiveGap, getMinBurialDepth. Side effects: changes the web page (DOM).
Why it exists in the grid workflow
Domain stage experimental (path word 'sandbox'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow. Domain terms in the code: cables, 1500V.
Inputs & outputs
Out: canvas drawing. Voltage levels named: 1500V.
What it achieves
It clamps integer (`clampInteger`), formats mm (`formatMm`) and gets min burial depth (`getMinBurialDepth`). Defines `byId`, `clampInteger`, `formatMm` and 47 more. It responds to focus, click and touchend events.
Why it matters
No other file in the estate was found to import it.
Application
testcode · sandbox/202609060432/cable · script
Uses
none found
Used by
none found
Produces
byId, clampInteger, formatMm, effectiveGap, getMinBurialDepth, getVoltageRuntimeMeta, getSelectedCore, getBurialDepthForComputation, normaliseBurialDepthFieldOnBlur, normaliseIntegerFields, getInputs, populateFormationOptions
Defines here
bindNumericFieldUX, sel, bindEvents, init
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
testcode@a8a215982b13d6e2f6019b40bf0bef5755719773 sandbox/202609060432/cable/app.js:1147-1213 · blob d23e32effebad9a79a8469ca1792c6b0a06fd3be · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom · domain stage: experimental · users: none · canonical: unreached_review
const isOn = document.body.classList.toggle("drawing-view");
byId("drawing_view_btn").textContent = isOn ? "Exit Drawing View" : "Drawing View";
updateViewportMode();
renderAll();
}

function bindNumericFieldUX() {
document.querySelectorAll('input[data-numeric="true"]').forEach(el => {
const sel = () => {
window.setTimeout(() => {
try {
el.select();
if (el.setSelectionRange) el.setSelectionRange(0, el.value.length);
} catch (_) {}
}, 0);
};
el.addEventListener("focus", sel);
el.addEventListener("click", sel);
el.addEventListener("touchend", sel);
});
}

function bindEvents() {
["installation_condition", "service_type", "grouping_basis", "formation_type", "spacing_basis"]
.forEach(id => byId(id).addEventListener("change", handleChange));

byId("lookup_cores").addEventListener("change", () => { populateVoltageOptions(); });
byId("lookup_voltage").addEventListener("change", () => { populateLookupCSA(); applyLookup(); });
byId("lookup_csa").addEventListener("change", applyLookup);

byId("cable_od").addEventListener("input", () => {
const vk = byId("lookup_voltage").value;
const csa = byId("lookup_csa").value;
if (!vk || !csa) {
byId("od_source_note").textContent = "OD entered manually.";
byId("od_source_note").style.color = "var(–muted-soft)";
}
});

["route_name", "section_length", "burial_depth", "circuit_qty", "max_per_row", "cable_od", "spacing_h", "spacing_v", "bend_factor", "formation_type"]
.forEach(id => {
byId(id).addEventListener("input", handleInput);
byId(id).addEventListener("blur", handleBlur);
});

byId("export_btn").addEventListener("click", exportJson);
byId("copy_btn").addEventListener("click", copySnapshot);
byId("drawing_view_btn").addEventListener("click", toggleDrawingView);
window.addEventListener("resize", debounce(() => { updateViewportMode(); renderAll(); }, 80));

}

function init() {
populateFormationOptions(byId("service_type").value, "trefoil_single_row");
syncFormationToLookupCore();
populateVoltageOptions();
syncSpacingInputs();
syncBurialDepthNote(true);
normaliseIntegerFields();
bindNumericFieldUX();
bindEvents();
updateViewportMode();
enforceDCRules();
renderAll();
}

init();

Build Cable Candidate

A Python module in the tools folder of Testcode covering publication and cables, using SHA-256.

electricaltestcode / sandbox/tools/build-cable-candidate.py · lines 1–47 of 47 · Not reached from any entry point (candidate for review)

What it does
Defines blob, sha, write. Uses libraries argparse, hashlib, html, json, pathlib. Side effects: reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage experimental (path word 'sandbox'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow. Domain terms in the code: cables.
Inputs & outputs
In: JSON file source-manifest.json; JSON file publication.json; command-line arguments.
What it achieves
Its name says it builds cable candidate. Defines `blob`, `sha` and `write`. It writes `source-manifest.json`. It accepts `--owner`, `--commit` and `--generation`.
Why it matters
No other file in the estate was found to import it.
Application
testcode · sandbox/tools · Python module
Uses
argparse, hashlib, html, json, pathlib, re, subprocess
Used by
none found
Produces
blob, sha, write
Defines here
blob, sha, write
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
testcode@a8a215982b13d6e2f6019b40bf0bef5755719773 sandbox/tools/build-cable-candidate.py:1-47 · blob 28009da201dbedda48a47e17290bb03f3303807b · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: filesystem, process · domain stage: experimental · users: none · canonical: unreached_review
import argparse
import hashlib
import html
import json
from pathlib import Path
import re
import subprocess

parser = argparse.ArgumentParser()
parser.add_argument('--owner', required=True)
parser.add_argument('--commit', required=True)
parser.add_argument('--generation', required=True)
args = parser.parse_args()
assert re.fullmatch('[a-f0-9]{40}', args.commit)
assert re.fullmatch('[0-9]{12}', args.generation)
root = Path(__file__).resolve().parents[2]
destination = root / 'sandbox' / args.generation
assert not destination.exists(), 'Immutable generation already exists'
def blob(name):
    return subprocess.check_output(['git', 'show', args.commit + ':' + name], cwd=args.owner)
def sha(data):
    return hashlib.sha256(data).hexdigest()
def write(name, data):
    target = destination / name
    target.parent.mkdir(parents=True, exist_ok=True)
    target.write_bytes(data)
prefix = 'releases/' + args.generation + '/'
manifest_bytes = blob(prefix + 'manifest.json')
manifest = json.loads(manifest_bytes)
assert manifest['generation'] == args.generation and manifest['schema'] == 'cable.legacy-syntax-repair.v1'
for item in manifest['files']:
    assert item['path'].startswith('legacy-cable-geometry/') and '..' not in item['path']
    data = blob(prefix + item['path'])
    assert len(data) == item['bytes'] and sha(data) == item['sha256']
    write('cable/' + item['path'].split('/', 1)[1], data)
write('source-manifest.json', manifest_bytes)
title = 'Restored legacy Cable drawing and export'
write('index.html', ('<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">'
      '<title>' + title + '</title><body style="background:#0d1117;color:#7fe3d0;font:18px system-ui;padding:24px">'
      '<h1>' + title + '</h1><p>Original geometry, JSON export and editable inputs, with a reachable Drawing View exit.</p>'
      '<p><a style="color:inherit" href="cable/">Open Cable Geometry</a></p></body></html>').encode('utf-8'))
files = [{'path': file.relative_to(destination).as_posix(), 'bytes': file.stat().st_size, 'sha256': sha(file.read_bytes())}
         for file in sorted(destination.rglob('*')) if file.is_file()]
write('publication.json', (json.dumps({'generation': args.generation, 'lane': 'codex', 'name': title,
      'source_repository': 'Ventusltd/cable-trench-or-drill', 'source_commit': args.commit,
      'status': 'candidate awaiting CI and served-byte checks', 'files': files}, indent=2) + '\n').encode('utf-8'))
print(json.dumps({'generation': args.generation, 'sourceCommit': args.commit, 'files': len(files)}))

Layers Panel

A JavaScript module in the iterations folder of Galaxies Wafers using data from the ventus-grid-engine repository. Served with the page at https://ventusltd.github.io/galaxies-wafers/iterations/01-route-alpha/.

rendergalaxies-wafers / iterations/01-route-alpha/layers-panel.mjs · lines 1–442 of 442 · Entry point · pattern hydrateTiles (shared by 11 files)

What it does
It draws its content. Defines 26 functions or classes, including alphaScale, routeAlpha, $, esc, row. Side effects: changes the web page (DOM); makes network requests.
Why it exists in the grid workflow
Domain stage field_execution (path word 'route'): on-road and off-road field navigation to the farm gate (access gates, terrain slope, ground-bearing limits, electrical hazards), as Ventus Ltd describes its SatNav work.
Inputs & outputs
In: data source: ventus-grid-engine data; form fields (user input). Out: canvas drawing.
Downstream impact
Used directly by 1 file: Iterations — 01 Route Alpha Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/01-route-alpha/). It is itself an entry point, published at https://ventusltd.github.io/galaxies-wafers/iterations/01-route-alpha/.
What it achieves
It routes alpha (`routeAlpha`), renders panel (`renderPanel`) and renders elements (`renderElements`). Layers over the inherited wafer, in Grid Atlas's grammar. It responds to click, change and pointerdown events.
Why it matters
Loaded by the 01 Route Alpha page at https://ventusltd.github.io/galaxies-wafers/iterations/01-route-alpha/.
Application
galaxies-wafers · iterations/01-route-alpha · JavaScript module
Uses
Galaxies Wafers — Lib (import)
Used by
loaded by Iterations — 01 Route Alpha Page (script src), mentioned in Standalone (comment link)
Produces
alphaScale, routeAlpha, $, esc, row, densityLegend, renderPanel, renderElements, el, link, kv, toggle
Defines here
alphaScale, routeAlpha, $, esc, row, densityLegend, renderPanel, renderElements, el, link, kv, toggle, hydrateTiles, writeLayersToURL, readLayersFromURL, liveView, toScreen, visibleLayers, drawOverlay, S, segDist2, pickAt, node, inspect, onStage, end
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
galaxies-wafers@5814793812add74605660fa821e6a39b8de80588 iterations/01-route-alpha/layers-panel.mjs:1-442 · blob 620a0b0109a4305ed244d780fcc2e399b9ee79ad · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, network · domain stage: field_execution · users: EPC_contractor, landowner_planner · canonical: unknown
/* layers-panel.mjs — layers over the inherited wafer, in Grid Atlas's grammar.
 *
 * The wafer page (app.mjs, lib.mjs) is inherited unchanged but for one hook.
 * This file adds a transparent canvas above it and a panel of layers, and
 * touches nothing the wafer draws. Remove this script tag and the wafer is
 * exactly what it was.
 *
 * Layers are files in layers/, listed by layers/manifest.json. Each is a
 * CodeFeatureCollection whose geometry is permanent keys, never coordinates, so
 * every mark is placed by the wafer's own frozen law and cannot disagree with
 * the ground. States follow the Atlas: WAIT until ticked, LOAD while fetching,
 * OK when drawn, EMPTY when loaded with nothing in it, FAIL with its reason.
 *
 * FOLLOWING THE CAMERA. app.mjs exposes exactly one read-only hook,
 * window.__wafer: a getter for its live `view` and a set of `onDraw` listeners
 * it calls at the end of every render(). The overlay registers there, so it
 * repaints in the same frame as the wafer and maps world to screen with the
 * wafer's own formula. An earlier version re-derived only the initial frame and
 * drifted off the points the moment anyone panned; that is what this replaces.
 *
 * TAP TO INSPECT. A tap on the wafer that lands within 14 px of a drawn layer
 * feature shows that feature's properties and its layer's evidence. The wafer
 * still receives the same tap and does whatever it does with it; nothing here
 * captures, prevents or stops the event.
 */
import { place } from '../../lib.mjs';

/* ROUTE ALPHA (iteration 01). Copied from the root layers-panel.mjs; the only
   changes are the ROOT prefix for fetches, the route alpha rule below, and the
   density legend line. Every LineString route is stroked at width ROUTE_WIDTH
   with alpha = scale / sqrt(features in its layer), clamped to 1, so a dense
   module goes translucent and a sparse one stays bright. `scale` is ?alpha=,
   clamped to [ALPHA_MIN, 1]; absent or unreadable, it is 1. */
const ROOT = '../../';
const ROUTE_WIDTH = 0.6;
const ALPHA_MIN = 0.05;
const alphaScale = (() => {
  const raw = new URL(location.href).searchParams.get('alpha');
  const v = raw === null ? NaN : Number(raw);
  return Number.isFinite(v) ? Math.min(1, Math.max(ALPHA_MIN, v)) : 1;
})();
const routeAlpha = n => Math.min(1, alphaScale / Math.sqrt(Math.max(1, n)));

const $ = id => document.getElementById(id);
const esc = s => String(s ?? '').replace(/[&<>"']/g, c =>
  ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));

const state = new Map();   /* id -> {status, doc, why} */
let manifest = null;
let picked = null;         /* {layer, feature} currently inspected */

const TAP_SLOP = 7;        /* px of movement under which a pointer-up is a tap */
const PICK_REACH = 14;     /* px within which a tap picks a layer feature */

/* ── the panel ───────────────────────────────────────────────────────────── */

const panel = document.createElement('section');
panel.id = 'layers';
panel.innerHTML = `<button id="layersToggle" type="button">LAYERS</button><div id="layersBody" hidden><div id="layersInspect" hidden></div><div id="layersList"></div></div>`;
document.body.appendChild(panel);

const style = document.createElement('style');
style.textContent = `
#layers{position:fixed;z-index:5;right:.5rem;top:calc(env(safe-area-inset-top,0px) + 2.2rem);
  max-width:min(22rem,calc(100% - 1rem));font:12px/1.4 ui-monospace,Menlo,Consolas,monospace}
#layersToggle{float:right;background:#11151f;color:#5ec8f2;border:1px solid #5ec8f2;border-radius:6px;
  padding:.35rem .7rem;font:inherit;letter-spacing:.1em;cursor:pointer}
#layersBody{clear:both;margin-top:.4rem;max-height:60vh;overflow:auto;background:#0e121bf4;
  border:1px solid #1b2030;border-radius:8px;padding:.5rem .6rem}
#layersBody[hidden],#layersInspect[hidden]{display:none!important}
#layersInspect{border-bottom:1px solid #1b2030;padding-bottom:.45rem;margin-bottom:.3rem;position:relative}
#layersInspect h3{margin:.1rem 1.6rem .25rem 0;font-size:12.5px;font-weight:600}
#layersInspect dl{display:grid;grid-template-columns:auto 1fr;gap:.1rem .5rem;margin:.3rem 0}
#layersInspect dt{color:#8b93a7}
#layersInspect dd{margin:0;overflow-wrap:anywhere}
#layersInspect .lnote{margin-left:0}
#layersInspectClose{position:absolute;top:0;right:0;background:none;border:0;color:#8b93a7;font:inherit;cursor:pointer}
.lgroup{color:#8b93a7;font-size:10.5px;letter-spacing:.08em;margin:.55rem 0 .15rem}
.lrow{display:flex;gap:.45rem;align-items:flex-start;margin:.2rem 0}
.lrow input{margin-top:.15rem}
.lname{flex:1}
.ltag{font-size:10.5px}
.ltag.WAIT{color:#8b93a7}.ltag.LOAD{color:#ffd54a}.ltag.OK{color:#7fd6a2}
.ltag.EMPTY{color:#b39ddb}.ltag.FAIL{color:#ff8a80}
.lnote{color:#8b93a7;font-size:10.5px;margin:.1rem 0 .35rem 1.5rem}
.ecard{border:1px solid #1b2030;border-radius:6px;padding:.35rem .45rem;margin:.3rem 0;background:#11151f}
.ehead .esym{font-weight:700}.ename{color:#e7ebf3}
.efns{color:#8b93a7;font-size:10.5px;margin:.1rem 0 .2rem}
.emod{border-top:1px dashed #1b2030;padding-top:.2rem;margin-top:.2rem}
.ekv{font-size:10.5px;word-break:break-word}.ek{color:#8b93a7}.ev{color:#e7ebf3}
.eschema{color:#7fd6a2}.enone{color:#b39ddb}
.elinks{font-size:10.5px;margin-top:.15rem}.elink{color:#5ec8f2}
#overlay{position:fixed;inset:0;width:100%;height:100%;pointer-events:none;z-index:1}
`;
document.head.appendChild(style);

const overlay = document.createElement('canvas');
overlay.id = 'overlay';
document.body.appendChild(overlay);
const ctx = overlay.getContext('2d');

$('layersToggle').addEventListener('click', () => { $('layersBody').hidden = !$('layersBody').hidden; });

function row(l) {
  const s = state.get(l.id) || { status: 'WAIT' };
  const why = s.why ? ` · ${esc(s.why)}` : '';
  const stat = s.doc?.stats ? ` · ${esc(JSON.stringify(s.doc.stats).slice(0, 80))}` : '';
  return `<div class="lrow"><input type="checkbox" id="L-${esc(l.id)}" ${s.on ? 'checked' : ''}>
    <label class="lname" for="L-${esc(l.id)}" style="color:${esc(l.colour)}">${esc(l.label)}
    <span class="ltag ${s.status}">[${s.status}]</span></label></div>
    <div class="lnote">${esc(l.evidence)}${why}${s.status === 'OK' ? stat : ''}</div>`;
}

function densityLegend() {
  const on = [...visibleLayers()].filter(([, d]) => d.features.some(f => f.geometry.type === 'LineString'));
  const each = on.map(([l, d]) => `${esc(l.id)} ${d.features.length} → ${routeAlpha(d.features.length).toFixed(3)}`).join(' · ');
  return `<div class="lgroup">DENSITY LEGEND</div><div class="lnote" id="densityLegend">route alpha = ${alphaScale} ÷ √(features in layer), max 1 · width ${ROUTE_WIDTH} px · ?alpha= scales it (${ALPHA_MIN}–1)${each ? ' · ' + each : ''}</div>`;
}

function renderPanel() {
  if (!manifest) return;
  const groups = [...new Set(manifest.layers.map(l => l.group))];
  $('layersList').innerHTML = groups.map(g =>
    `<div class="lgroup">${esc(g)}</div>` + manifest.layers.filter(l => l.group === g).map(row).join('')
  ).join('') + densityLegend() + `<div class="lnote">substrate ${esc(manifest.substrate)} · frozen · layers built ${esc(manifest.built_utc)}</div>`;
  for (const l of manifest.layers) {
    $('L-' + l.id).addEventListener('change', e => toggle(l, e.target.checked));
  }
  renderElements(manifest, state);
}

/* ── ELEMENT: what a consumer of a module meets ─────────────────────────────
   Shown when a layer that carries properties.schema or properties.export_subpath
   is OK. One card per block symbol, one entry per module that block's functions
   resolve to: its export subpath (or why there is none), the schema it stamps,
   what its NOT_COMPUTED refuses, and where it lives. Built from DOM nodes with
   textContent only; nothing from a dataset is ever parsed as HTML. */
const ENGINE_LIVE = 'https://ventusltd.github.io/ventus-grid-engine/';

function renderElements(manifest, state) {
  const body = $('layersBody');
  if (!body || !manifest) return;
  $('layersElements')?.remove();
  const el = (tag, cls, text) => {
    const n = document.createElement(tag);
    if (cls) n.className = cls;
    if (text != null) n.textContent = String(text);
    return n;
  };
  const link = (href, text) => {
    const a = el('a', 'elink', text);
    a.href = href; a.target = '_blank'; a.rel = 'noopener noreferrer';
    return a;
  };
  const cards = new Map();   /* symbol -> {title, colour, modules: Map(path -> props), functions: Set} */
  for (const l of manifest.layers) {
    const s = state.get(l.id);
    if (!s?.on || s.status !== 'OK') continue;
    const feats = s.doc.features.filter(f => f.properties && ('schema' in f.properties || 'export_subpath' in f.properties));
    for (const f of feats) {
      const p = f.properties;
      if (!p.module_path || !p.block) continue;
      if (!cards.has(p.block)) cards.set(p.block, { title: p.title, colour: l.colour, modules: new Map(), functions: new Set() });
      const c = cards.get(p.block);
      c.functions.add(p.function);
      if (!c.modules.has(p.module_path)) c.modules.set(p.module_path, p);
    }
  }
  if (!cards.size) return;
  const sec = el('div'); sec.id = 'layersElements';
  sec.appendChild(el('div', 'lgroup', 'ELEMENT'));
  for (const [sym, c] of [...cards].sort((a, b) => a[0].localeCompare(b[0]))) {
    const card = el('div', 'ecard');
    const head = el('div', 'ehead');
    const symEl = el('span', 'esym', sym); symEl.style.color = c.colour;
    head.append(symEl, el('span', 'ename', ' ' + (c.title || '')));
    card.appendChild(head);
    card.appendChild(el('div', 'efns', [...c.functions].join(', ')));
    for (const [path, p] of c.modules) {
      const m = el('div', 'emod');
      const kv = (k, v, cls) => { const r = el('div', 'ekv'); r.append(el('span', 'ek', k + ' '), el('span', cls || 'ev', v)); m.appendChild(r); };
      kv('module', path);
      kv('export', p.export_subpath ?? ('none — ' + (p.export_reason || 'no subpath')), p.export_subpath ? 'ev' : 'ev enone');
      kv('schema', p.schema ?? ('none — ' + (p.schema_reason || 'no schema')), p.schema ? 'ev eschema' : 'ev enone');
      kv('refuses', (p.refuses && p.refuses.length) ? p.refuses.join(', ')
        : (p.not_computed_form ? `NOT_COMPUTED is a ${p.not_computed_form}, no keys` : 'nothing declared'));
      const links = el('div', 'elinks');
      links.append(link(ENGINE_LIVE, 'live engine'), el('span', null, ' · '),
        link(p.github || `https://github.com/Ventusltd/ventus-grid-engine/blob/main/${path}`, 'GitHub ' + path));
      m.appendChild(links);
      card.appendChild(m);
    }
    sec.appendChild(card);
  }
  body.appendChild(sec);
}

async function toggle(l, on) {
  const s = state.get(l.id) || { status: 'WAIT' };
  s.on = on; state.set(l.id, s);
  writeLayersToURL();
  if (on && !s.doc && !s.loading) {
    s.loading = true; s.why = '';
    s.status = 'LOAD'; renderPanel();
    try {
      if (l.tiles) s.doc = await hydrateTiles(l, s);
      else {
        const r = await fetch(ROOT + l.file, { cache: 'default' });
        if (!r.ok) throw new Error('HTTP ' + r.status);
        s.doc = await r.json();
      }
      s.status = s.doc.features.length ? 'OK' : 'EMPTY';
      if (!s.doc.features.length) s.why = 'loaded; the layer holds no features';
    } catch (e) { s.status = 'FAIL'; s.why = e.message; }
    s.loading = false;
  }
  if (!on && picked?.layer.id === l.id) inspect(null);
  renderPanel(); drawOverlay();
}

/* A tiled layer is split by radius band (build/tile_layer.py): because r = sqrt(key),
   band b is the key range [(b*S)^2, ((b+1)*S)^2). For now every band is fetched up
   front, but as separate requests, so the panel can count them in (LOAD n/N) and a
   later version can fetch only the bands in view. The assembled doc is identical in
   shape to the whole-file layer, so drawing does not know the difference. */
async function hydrateTiles(l, s) {
  const r = await fetch(ROOT + l.tiles, { cache: 'default' });
  if (!r.ok) throw new Error('tile index HTTP ' + r.status);
  const index = await r.json();
  const bands = index.bands || [];
  const N = bands.length;
  let n = 0;
  s.status = `LOAD ${n}/${N}`; renderPanel();
  const parts = await Promise.all(bands.map(async b => {
    const t = await fetch(ROOT + b.file, { cache: 'default' });
    if (!t.ok) throw new Error(`band ${b.band} HTTP ${t.status}`);
    const doc = await t.json();
    if (doc.features.length !== b.features)
      throw new Error(`band ${b.band} holds ${doc.features.length} features, index says ${b.features}`);
    n++; s.status = `LOAD ${n}/${N}`; renderPanel();
    return doc.features;
  }));
  const features = parts.flat();
  if (index.source && features.length !== index.source.features)
    throw new Error(`tiles hold ${features.length} features, source had ${index.source.features}`);
  return {
    type: 'CodeFeatureCollection', substrate: index.substrate, layer: index.layer,
    provenance: index.provenance, stats: { features: features.length, bands: N }, features,
  };
}

/* ── the URL: ?layers=engine,declared ─────────────────────────────────────── */

/* The wafer's URL grammar: only permanent identifiers travel. A layer id is used
   only if the manifest names it; anything else in the URL is dropped, and the
   next write puts the URL back into canonical, manifest-ordered form. */
function writeLayersToURL() {
  if (!manifest) return;
  const on = manifest.layers.filter(l => state.get(l.id)?.on).map(l => l.id);
  const u = new URL(location.href);
  if (on.length) u.searchParams.set('layers', on.join(','));
  else u.searchParams.delete('layers');
  const next = u.pathname + u.search.replace(/%2C/gi, ',') + u.hash;
  if (next !== location.pathname + location.search + location.hash)
    history.replaceState(history.state, '', next);
}

function readLayersFromURL() {
  if (!manifest) return;
  const raw = new URL(location.href).searchParams.get('layers') || '';
  const known = new Map(manifest.layers.map(l => [l.id, l]));
  const wanted = [...new Set(raw.split(',').map(x => x.trim()))].filter(id => known.has(id));
  for (const id of wanted) state.get(id).on = true;     /* mark all first, so each write keeps the rest */
  if (raw) writeLayersToURL();
  for (const id of wanted) toggle(known.get(id), true);
}

/* ── drawing: follow the wafer's frame ───────────────────────────────────── */

/* ── the camera: the wafer's own, read live ──────────────────────────────── */

const liveView = () => window.__wafer?.view ?? null;

/* The wafer's formula, exactly: see drawMarks() and nearestKeyAt() in app.mjs. */
const toScreen = (v, [x, y]) => [(x - v.x) * v.zoom + v.w / 2, v.h / 2 - (y - v.y) * v.zoom];

function* visibleLayers() {
  for (const l of (manifest?.layers || [])) {
    const s = state.get(l.id);
    if (s?.on && s.status === 'OK') yield [l, s.doc];
  }
}

/* ── drawing ─────────────────────────────────────────────────────────────── */

function drawOverlay() {
  const v = liveView();
  if (!v || !v.w || !v.h) return;          /* the wafer has not framed itself yet */
  const dpr = v.dpr || 1;
  const W = Math.round(v.w * dpr), H = Math.round(v.h * dpr);
  if (overlay.width !== W || overlay.height !== H) { overlay.width = W; overlay.height = H; }
  ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
  ctx.clearRect(0, 0, v.w, v.h);
  const S = p => toScreen(v, p);

  for (const [l, doc] of visibleLayers()) {
    ctx.strokeStyle = l.colour; ctx.fillStyle = l.colour;
    const pointAlpha = l.draws === 'lines' ? 0.55 : 0.8;
    const lineAlpha = routeAlpha(doc.features.length);
    ctx.lineWidth = ROUTE_WIDTH;
    for (const f of doc.features) {
      const g = f.geometry;
      ctx.globalAlpha = g.type === 'LineString' ? lineAlpha : pointAlpha;
      if (g.type === 'Point') {
        const [x, y] = S(place(g.key));
        if (x < -2 || y < -2 || x > v.w + 2 || y > v.h + 2) continue;
        ctx.fillRect(x - 1, y - 1, 2, 2);
      } else if (g.type === 'LineString') {
        ctx.beginPath();
        g.keys.forEach((k, i) => { const [x, y] = S(place(k)); i ? ctx.lineTo(x, y) : ctx.moveTo(x, y); });
        ctx.stroke();
      }
    }
    ctx.globalAlpha = 1;
  }

  if (picked) {
    const g = picked.feature.geometry;
    ctx.strokeStyle = picked.layer.colour; ctx.lineWidth = 1.4;
    for (const k of (g.type === 'Point' ? [g.key] : g.keys)) {
      const [x, y] = S(place(k));
      ctx.beginPath(); ctx.arc(x, y, 7, 0, 6.2832); ctx.stroke();
    }
  }
}

window.__wafer?.onDraw.add(drawOverlay);

/* ── tap to inspect ──────────────────────────────────────────────────────── */

function segDist2(px, py, [ax, ay], [bx, by]) {
  const dx = bx - ax, dy = by - ay, L = dx * dx + dy * dy;
  const t = L ? Math.max(0, Math.min(1, ((px - ax) * dx + (py - ay) * dy) / L)) : 0;
  const qx = ax + t * dx - px, qy = ay + t * dy - py;
  return qx * qx + qy * qy;
}

/* The nearest drawn feature to a screen point, or null when none is within reach. */
function pickAt(cx, cy) {
  const v = liveView();
  if (!v || !v.zoom) return null;
  let best = null, bestD = PICK_REACH * PICK_REACH;
  for (const [l, doc] of visibleLayers()) {
    for (const f of doc.features) {
      const g = f.geometry;
      let d = Infinity;
      if (g.type === 'Point') {
        const [x, y] = toScreen(v, place(g.key));
        d = (x - cx) ** 2 + (y - cy) ** 2;
      } else if (g.type === 'LineString' && g.keys.length) {
        const pts = g.keys.map(k => toScreen(v, place(k)));
        d = segDist2(cx, cy, pts[0], pts[0]);
        for (let i = 1; i < pts.length; i++) d = Math.min(d, segDist2(cx, cy, pts[i - 1], pts[i]));
      }
      if (d < bestD) { bestD = d; best = { layer: l, feature: f }; }
    }
  }
  return best;
}

const node = (tag, text, cls) => {
  const n = document.createElement(tag);
  if (text != null) n.textContent = String(text);
  if (cls) n.className = cls;
  return n;
};

/* Dataset text only ever reaches the page through textContent. */
function inspect(hit) {
  picked = hit;
  const box = $('layersInspect');
  box.replaceChildren();
  if (!hit) { box.hidden = true; drawOverlay(); return; }
  const { layer: l, feature: f } = hit;
  const close = node('button', '✕');
  close.id = 'layersInspectClose'; close.type = 'button'; close.setAttribute('aria-label', 'close');
  close.addEventListener('click', () => inspect(null));
  const h = node('h3', l.label); h.style.color = l.colour;
  const g = f.geometry;
  const where = node('div', g.type === 'Point' ? `line ${g.key}` : `lines ${g.keys.join(' → ')}`, 'lnote');
  const dl = node('dl');
  for (const [k, val] of Object.entries(f.properties || {})) {
    dl.append(node('dt', k), node('dd', val !== null && typeof val === 'object' ? JSON.stringify(val) : val));
  }
  const ev = node('div', 'evidence: ' + (l.evidence ?? 'none recorded'), 'lnote');
  box.append(close, h, where, dl, ev);
  box.hidden = false;
  $('layersBody').hidden = false;
  drawOverlay();
}

/* Non-capturing, and never prevents or stops the event: the wafer's own tap
   (which opens its line panel) still happens exactly as before. */
{
  const pts = new Map();
  let moved = 0;
  const onStage = e => e.target instanceof Element && e.target.id === 'stage';
  document.addEventListener('pointerdown', e => {
    if (!onStage(e)) return;
    pts.set(e.pointerId, [e.clientX, e.clientY]);
    if (pts.size === 1) moved = 0;
  });
  document.addEventListener('pointermove', e => {
    const prev = pts.get(e.pointerId);
    if (!prev) return;
    moved += Math.abs(e.clientX - prev[0]) + Math.abs(e.clientY - prev[1]);
    pts.set(e.pointerId, [e.clientX, e.clientY]);
  });
  const end = e => {
    if (!pts.has(e.pointerId)) return;
    const single = pts.size === 1;
    pts.delete(e.pointerId);
    if (e.type !== 'pointerup' || !single || moved >= TAP_SLOP) return;
    const hit = pickAt(e.clientX, e.clientY);
    if (hit) inspect(hit);
  };
  document.addEventListener('pointerup', end);
  document.addEventListener('pointercancel', end);
}

(async () => {
  try {
    const r = await fetch(ROOT + 'layers/manifest.json', { cache: 'no-cache' });
    if (!r.ok) throw new Error('layers/manifest.json returned HTTP ' + r.status);
    manifest = await r.json();
    for (const l of manifest.layers) state.set(l.id, { status: 'WAIT', on: false });
    renderPanel();
    readLayersFromURL();
  } catch (e) {
    $('layersList').innerHTML = `<div class="lnote">Layers unavailable: ${esc(e.message)}. The wafer itself is unaffected.</div>`;
  }
})();