In this section
- Iterations — 45 Deeplink Round Trip render · galaxies-wafers / iterations/45-deeplink-round-trip/app.mjs lines 1–302
- Iterations — 45 Deeplink Round Trip Page render · galaxies-wafers / iterations/45-deeplink-round-trip/index.html lines 1–62
- Iterations — 45 Deeplink Round Trip Style Sheet render · galaxies-wafers / iterations/45-deeplink-round-trip/style.css lines 1–41
- Iterations — 46 Chemistry Ledger render · galaxies-wafers / iterations/46-chemistry-ledger/app.mjs lines 1–265
Iterations — 45 Deeplink Round Trip
A JavaScript module in Galaxies Wafers that draws receivers and wind. Served with the page at https://ventusltd.github.io/galaxies-wafers/iterations/45-deeplink-round-trip/. It extracts null reason (`extractNullReason`), lists receivers (`listReceivers`) and renders verdict (`renderVerdict`).
rendergalaxies-wafers / iterations/45-deeplink-round-trip/app.mjs · lines 1–302 of 302 · Entry point · pattern chips (shared by 2 files)
- What it does
- It draws receivers and wind. Defines 25 functions or classes, including $, esc, show, enqueue, pump. Side effects: changes the web page (DOM); makes network requests.
- Why it exists in the grid workflow
- Domain terms in the code: wind. README: "The page (`index.html`, `app.mjs`, `lib.mjs`) is inherited unchanged from testcode/202609151339."
- Inputs & outputs
- In: JSON file receivers.json; JSON file current.json.
- Downstream impact
- Used directly by 1 file: Iterations — 45 Deeplink Round Trip Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/45-deeplink-round-trip/). It is itself an entry point, published at https://ventusltd.github.io/galaxies-wafers/iterations/45-deeplink-round-trip/.
- What it achieves
- 45 · The MAP Button, Round Trip. It responds to click, change and input events.
- Why it matters
- Loaded by the page of the same name at https://ventusltd.github.io/galaxies-wafers/iterations/45-deeplink-round-trip/.
- Application
- galaxies-wafers · iterations/45-deeplink-round-trip · JavaScript module
- Uses
- GlobalGrid2050 — Renewable Energy Planning Database (REPD) Grid Atlas v8 Page (estate URL)
- Used by
- loaded by Iterations — 45 Deeplink Round Trip Page (script src)
- Produces
- $, esc, show, enqueue, pump, timedFetch, cachedText, syntheticRecords, extractNullReason, reasonText, roundTrip, fillReasons
- Defines here
- $, esc, show, enqueue, pump, timedFetch, cachedText, syntheticRecords, extractNullReason, reasonText, roundTrip, fillReasons, listReceivers, measure, count, analyse, add, strip, renderVerdict, chips, set, mapButton, update, questions, main
- 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/45-deeplink-round-trip/app.mjs:1-302 · blob 9bd68d058ae14db3724dac00bfce2a9a09c10e83 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, network · domain stage: unknown · users: none · canonical: unknown
/* 45 · The MAP Button, Round Trip.
* Every link, parse, refusal and layer id on this page comes from the estate's
* contract module, imported at a pinned commit. Nothing here re-implements it. */
const COMMIT = 'd9cd18b0e2034325814924e6e4a0e958014f2748';
const ROOT = `https://cdn.jsdelivr.net/gh/Ventusltd/ventus-grid-engine@${COMMIT}/`;
const MOD_URL = ROOT + 'deeplink/contract.js';
const RECEIVERS_URL = ROOT + 'deeplink/receivers.json';
/* The v9.5.1 MAP sender, quoted (not imported): pipelinenews
* releases/javascript/202608261927-projects-v9-5-1.js, atlasUrlV9_5_1(), line 44. */
const SENDER_V951 = { file: 'pipelinenews releases/javascript/202608261927-projects-v9-5-1.js', fn: 'atlasUrlV9_5_1', line: 44,
base: 'https://globalgrid2050.com/repd_grid_atlasv8/' };
const $ = (id) => document.getElementById(id);
const esc = (s) => String(s).replace(/[&<>"]/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c]));
const show = (v) => v === null ? 'null' : v === undefined ? 'undefined' : typeof v === 'string' ? JSON.stringify(v) : String(v);
/* Grid Atlas loading grammar: one queue (4 at once), 15 s timeout, one promise per URL, a failure leaves the cache. */
const queue = { running: 0, waiting: [], max: 4 };
function enqueue(task) {
return new Promise((resolve, reject) => {
queue.waiting.push({ task, resolve, reject });
pump();
});
}
function pump() {
while (queue.running < queue.max && queue.waiting.length) {
const { task, resolve, reject } = queue.waiting.shift();
queue.running++;
task().then(resolve, reject).finally(() => { queue.running--; pump(); });
}
}
function timedFetch(url, init = {}) {
return enqueue(async () => {
const ctl = new AbortController();
const timer = setTimeout(() => ctl.abort(), 15000);
const t0 = performance.now();
try {
const res = await fetch(url, { ...init, signal: ctl.signal });
const text = await res.text();
return { res, text, ms: performance.now() - t0 };
} finally { clearTimeout(timer); }
});
}
const cache = new Map();
function cachedText(url) {
if (!cache.has(url)) {
const p = timedFetch(url).then(({ res, text }) => { if (!res.ok) throw new Error('HTTP ' + res.status); return text; });
p.catch(() => cache.delete(url));
cache.set(url, p);
}
return cache.get(url);
}
let C; // the contract module
let records = []; // synthetic records, one per bucket
let otherReason = null;
function syntheticRecords() {
/* Synthetic: identities are not REPD references; points are a fixed arithmetic walk, not project sites. */
return C.BUCKETS.map((technology, i) => ({
repd_ref: `SYNTH-${String(i + 1).padStart(2, '0')}`,
technology,
latitude: 50.1 + i * 0.37,
longitude: -5.2 + i * 0.61,
zoom: 12
}));
}
function extractNullReason(src) {
const lines = src.split('\n');
const at = lines.findIndex((l) => /`other` maps to null/.test(l));
if (at < 0) return null;
let end = at;
while (end < lines.length && !/\*\//.test(lines[end])) end++;
const text = lines.slice(at, end).map((l) => l.replace(/^\s*\*\s?/, '')).join(' ').replace(/\s+/g, ' ').trim();
return { text, from: at + 1, to: end };
}
function reasonText(bucket) {
return otherReason
? `EMPTY: no Atlas layer. The module, contract.js lines ${otherReason.from}-${otherReason.to}: “${otherReason.text}”`
: `EMPTY: no Atlas layer (LAYER_ID_FOR_BUCKET.${bucket} is null). Reading the module's stated reason from its source...`;
}
function roundTrip() {
let survived = 0, noLayer = 0, renamed = 0;
const frag = document.createDocumentFragment();
for (const rec of records) {
const li = document.createElement('li');
li.dataset.bucket = rec.technology;
let href, parsed;
try { href = C.buildDeepLink(rec); parsed = C.parseDeepLink(href); }
catch (e) {
li.className = 'row empty';
li.innerHTML = `<div class="rhead"><span class="st">REFUSED</span><span>${esc(rec.technology)}</span></div><div class="quote">${esc(e.message)}</div>`;
frag.append(li); continue;
}
const fields = Object.keys(C.PARAMS);
const diffs = fields.filter((k) => parsed[k] !== rec[k]);
if (!diffs.length) survived++;
const layer = parsed.layer_id;
if (!parsed.layer_exists) noLayer++;
if (layer !== null && layer !== rec.technology) renamed++;
li.className = 'row ' + (diffs.length ? 'changed' : 'same');
li.dataset.survived = String(!diffs.length);
li.dataset.layer = String(layer);
const rows = fields.map((k) => `<span>${k}</span><span>${esc(show(rec[k]))} → ${esc(show(parsed[k]))}${parsed[k] === rec[k] ? ' (===)' : ' <b class="refuse">changed</b>'}</span>`).join('');
const layerRows = `<span>layer_id</span><span>${esc(show(layer))}${layer !== null && layer !== rec.technology ? ' (renamed by LAYER_ID_FOR_BUCKET)' : ''}</span><span>layer_exists</span><span>${parsed.layer_exists}</span><span>known_bucket</span><span>${parsed.known_bucket}</span>`;
const reason = layer === null ? `<div class="quote reason" data-bucket="${esc(rec.technology)}">${esc(reasonText(rec.technology))}</div>` : '';
li.innerHTML = `<div class="rhead"><span class="st">${diffs.length ? 'CHANGED ' + esc(diffs.join(', ')) : 'EVERY FIELD SURVIVED'}</span><span>${esc(rec.technology)}</span><span class="dim small">synthetic</span></div>
<code class="link">${esc(href)}</code><div class="f">${rows}${layerRows}</div>${reason}`;
frag.append(li);
}
$('round').replaceChildren(frag);
const n = records.length;
const s = $('summary');
s.innerHTML = `<b>${survived}</b> of <b>${n}</b> buckets read from <code>BUCKETS</code> survived build → parse with every field identical. <b>${noLayer}</b> resolve to no Atlas layer (<code>layer_exists</code> false). <b>${renamed}</b> are renamed by <code>LAYER_ID_FOR_BUCKET</code>.`;
s.dataset.survived = survived; s.dataset.total = n; s.dataset.nolayer = noLayer; s.dataset.renamed = renamed;
}
function fillReasons() {
document.querySelectorAll('.reason').forEach((el) => {
el.textContent = otherReason ? reasonText(el.dataset.bucket)
: `EMPTY: no Atlas layer (LAYER_ID_FOR_BUCKET.${el.dataset.bucket} is null). The module source could not be read for its stated reason.`;
});
}
/* ── Receivers ─────────────────────────────────────────────────────────── */
let receivers = [];
function listReceivers(json) {
receivers = [{ kind: 'canonical', ...json.canonical }, ...json.retired.map((r) => ({ kind: 'retired', ...r }))];
const frag = document.createDocumentFragment();
receivers.forEach((r, i) => {
const li = document.createElement('li');
li.className = 'row empty'; li.id = 'recv-' + i;
const claim = r.kind === 'canonical' ? r.evidence : `${r.reason} Recorded: ${r.measured}.`;
li.innerHTML = `<div class="rhead"><span class="st">${r.kind.toUpperCase()}</span><span>${esc(r.id)}</span><span class="dim">carries_engine: ${r.carries_engine}</span></div>
<code class="link">${esc(r.route)}</code><div class="dim small">file says: ${esc(claim)}</div>
<div class="f"><span>module</span><span>isRetiredReceiver → ${C.isRetiredReceiver(r.route)}</span><span>status now</span><span class="now">WAIT: tap measure</span></div>`;
frag.append(li);
});
$('recv').replaceChildren(frag);
$('measure').disabled = false;
}
let measuring = false;
async function measure() {
if (measuring || !receivers.length) return;
measuring = true; $('measure').disabled = true;
await Promise.all(receivers.map(async (r, i) => {
const li = $('recv-' + i), now = li.querySelector('.now');
now.textContent = 'LOAD: fetching...';
try {
const { res, text, ms } = await timedFetch(r.route, { cache: 'no-store' });
const count = (needle) => text.split(needle).length - 1;
li.className = 'row same';
li.dataset.status = res.status;
now.textContent = `HTTP ${res.status}${res.statusText ? ' ' + res.statusText : ''} · ${Math.round(ms)} ms · ${text.length.toLocaleString('en-GB')} characters${res.redirected ? ' · redirected to ' + res.url : ''} · in the body now: "current.json" ${count('current.json')}×, "cartridge" ${count('cartridge')}×, "nearest" ${count('nearest')}×`;
} catch (e) {
li.className = 'row empty';
li.dataset.status = 'FAIL';
now.textContent = `FAIL: ${e.name === 'AbortError' ? 'no answer within 15 s' : e.name + ': ' + e.message} (the browser exposes no HTTP status for this)`;
}
}));
measuring = false; $('measure').disabled = false; $('measure').textContent = 'measure again';
}
/* ── Break it ──────────────────────────────────────────────────────────── */
function analyse(text) {
const out = [];
const add = (st, field, words) => out.push({ st, field, words });
const input = text.trim();
let parsed;
try { parsed = C.parseDeepLink(input); }
catch (e) {
add('REFUSED', 'the whole link', `parseDeepLink threw. Its first act is new URL(href); the browser's message: “${e.message}”`);
return out;
}
const url = new URL(input);
const base = url.origin + url.pathname;
const strip = (v) => v.replace(/\/+$/, '');
if (C.isRetiredReceiver(base)) add('REFUSED', 'receiver', 'isRetiredReceiver(base) is true: this route is in RETIRED_RECEIVERS. buildDeepLink\'s own words are on the rebuild line.');
else if (strip(base) !== strip(C.CANONICAL_RECEIVER)) add('NOT REGISTERED', 'receiver', `${base} is neither CANONICAL_RECEIVER (${C.CANONICAL_RECEIVER}) nor in RETIRED_RECEIVERS. The module does not refuse it; it does not vouch for it either.`);
else add('OK', 'receiver', 'CANONICAL_RECEIVER');
for (const [k, spec] of Object.entries(C.PARAMS)) {
const all = url.searchParams.getAll(k);
const raw = all.length ? all[0] : null;
const note = spec.note ? `note: “${spec.note}”` : `units: “${spec.units}”`;
if (all.length > 1) add('AMBIGUOUS', k, `sent ${all.length} times (${all.map(show).join(', ')}); parseDeepLink reads searchParams.get, which keeps the first.`);
if (raw === null || raw.trim() === '') {
if (spec.required) add('REFUSED', k, `missing, and PARAMS.${k}.required is true; ${note}. parseDeepLink returns ${show(parsed[k])}.`);
else add('ABSENT', k, `optional (PARAMS.${k}.required is false); parseDeepLink returns null.`);
continue;
}
if (spec.type === 'number') {
if (parsed[k] === null) add('REFUSED', k, `${show(raw)} is not a finite number, so parseDeepLink returns null (type "number", ${note}).`);
else if ((k === 'latitude' && Math.abs(parsed[k]) > 90) || (k === 'longitude' && Math.abs(parsed[k]) > 180))
add('LET THROUGH', k, `${parsed[k]} is outside the earth's range and the contract does not range-check it: parseDeepLink returns it as a number. (The spine emitter drops such values before sending, per docs/deeplink-contract.md section 1a.)`);
else add('OK', k, `${show(raw)} → ${parsed[k]}`);
} else if (k === 'technology') {
if (!parsed.known_bucket) add('REFUSED', k, `${show(raw)} is not in BUCKETS (known_bucket false); ${note}. layerIdForBucket gives ${show(parsed.layer_id)}; layer_exists ${parsed.layer_exists}${parsed.layer_exists ? ': a real layer id, but the sender speaks buckets, not layer ids' : ''}.`);
else if (parsed.layer_id === null) add('NO LAYER', k, `${show(raw)} is a bucket whose layer_id is null. ${otherReason ? 'The module: “' + otherReason.text + '”' : ''}`);
else add('OK', k, `${show(raw)} → layer ${show(parsed.layer_id)}${parsed.layer_id !== raw ? ' (renamed by LAYER_ID_FOR_BUCKET)' : ''}`);
} else {
add('OK', k, show(raw));
}
}
for (const k of new Set(url.searchParams.keys())) {
if (k in C.PARAMS) continue;
const words = k === 'repd_id'
? `not a contract parameter. IDENTITY_PARAM is ${show(C.IDENTITY_PARAM)}; the module's comment: “The project is identified by repd_ref. NOT repd_id.”`
: 'not in PARAMS; the contract does not carry it, and a rebuild drops it.';
add('DROPPED', k, words);
}
try {
const project = Object.fromEntries(Object.keys(C.PARAMS).map((k) => [k, parsed[k]]));
const rebuilt = C.buildDeepLink(base, project);
add(rebuilt === input ? 'OK' : 'CHANGED', 'rebuild', rebuilt === input ? 'buildDeepLink(base, parsed) returns exactly the text above.' : `buildDeepLink(base, parsed) returns: ${rebuilt}`);
} catch (e) {
add('REFUSED', 'rebuild', `buildDeepLink threw: “${e.message}”`);
}
return out;
}
let editTimer = 0;
function renderVerdict() {
const out = analyse($('edit').value);
const refused = out.filter((o) => o.st === 'REFUSED');
const v = $('verdict');
v.dataset.refused = refused.map((o) => o.field).join(',');
v.innerHTML = `<p class="small"><b>${refused.length}</b> refused${refused.length ? ': ' + refused.map((o) => esc(o.field)).join(', ') : ''}</p><ul class="rows">` +
out.map((o) => `<li class="row ${o.st === 'OK' ? 'same' : o.st === 'ABSENT' ? 'empty' : 'changed'}"><div class="rhead"><span class="st">${esc(o.st)}</span><span>${esc(o.field)}</span></div><div class="small">${esc(o.words)}</div></li>`).join('') + '</ul>';
}
function chips() {
const set = (k, v) => (h) => { const u = new URL(h); if (v === null) u.searchParams.delete(k); else u.searchParams.set(k, v); return u.toString(); };
const defs = [
['intact', (h) => h],
['v9.5.1 base', (h) => h.replace(C.CANONICAL_RECEIVER, SENDER_V951.base)],
['repd_id', (h) => h.replace('repd_ref=', 'repd_id=')],
['latitude=abc', set('latitude', 'abc')],
['latitude=91', set('latitude', '91')],
['technology=wind', set('technology', 'wind')],
['technology=other', set('technology', 'other')],
['no technology', set('technology', null)],
['two repd_ref', (h) => h + '&repd_ref=SYNTH-99'],
['+project name', set('project', 'Synthetic name')],
['not a URL', (h) => h.replace('https://', '')]
];
for (const [label, fn] of defs) {
const b = document.createElement('button');
b.type = 'button'; b.className = 'chip'; b.textContent = label; b.dataset.chip = label;
b.addEventListener('click', () => { $('edit').value = fn(C.buildDeepLink(records[0])); renderVerdict(); });
$('chips').append(b);
}
}
/* ── MAP button ────────────────────────────────────────────────────────── */
function mapButton() {
const sel = $('pick');
records.forEach((r, i) => { const o = document.createElement('option'); o.value = i; o.textContent = `${r.repd_ref} · ${r.technology} (synthetic)`; sel.append(o); });
const a = document.createElement('a');
a.className = 'action-link atlaslink'; a.target = '_blank'; a.rel = 'noopener'; a.id = 'map'; a.textContent = 'MAP ↗';
$('mapbtn').replaceChildren(a);
const update = () => {
const r = records[Number(sel.value)];
const href = C.buildDeepLink(r);
a.href = href;
$('maphref').textContent = href;
let refusal;
try { refusal = 'built without refusal: ' + C.buildDeepLink(SENDER_V951.base, r); } catch (e) { refusal = e.message; }
$('sender').innerHTML = `The same record through the base hard-coded in <code>${SENDER_V951.fn}()</code> (${esc(SENDER_V951.file)}, line ${SENDER_V951.line}, quoted from source): <code>${esc(SENDER_V951.base)}</code>. isRetiredReceiver → <b>${C.isRetiredReceiver(SENDER_V951.base)}</b>. buildDeepLink(thatBase, record):<span class="quote" style="display:block">${esc(refusal)}</span>`;
};
sel.addEventListener('change', update);
update();
}
function questions() {
const names = Object.keys(C).sort();
$('q2').innerHTML = `Module <code>deeplink/contract.js</code>, ventus-grid-engine @ <code>${COMMIT.slice(0, 8)}</code>; exports read at run time (${names.length}): ${names.map((n) => '<code>' + n + '</code>').join(', ')}. Sender: Pipeline News, whose MAP button builds the URL (<code>${SENDER_V951.fn}</code> in v9.5.1; <code>buildAtlasV9DeepLink</code> in the later spine emitter, per docs/deeplin … [line shortened here: 720 characters; full line on GitHub]
$('machine').innerHTML = `Machine detail: inputs ${Object.entries(C.PARAMS).map(([k, s]) => `<code>${k}</code> (${s.type}${s.units ? ', ' + esc(s.units) : ''}${s.required ? ', required' : ''})`).join(', ')}. Outputs: <code>buildDeepLink</code> → URL string on CANONICAL_RECEIVER; <code>parseDeepLink</code> → those fields plus <code>layer_id</code> (string or null), <code>layer_exists</code> (bool … [line shortened here: 842 characters; full line on GitHub]
}
async function main() {
try { C = await import(MOD_URL); }
catch (e) {
$('summary').textContent = `FAIL: the contract module could not be imported (${e.message}). Nothing on this page can be computed without it.`;
return;
}
$('src').innerHTML = `module: <a href="${MOD_URL}">ventus-grid-engine @ ${COMMIT.slice(0, 12)} / deeplink/contract.js</a> · imported`;
records = syntheticRecords();
roundTrip();
chips();
$('edit').value = C.buildDeepLink(records[0]);
$('edit').addEventListener('input', () => { clearTimeout(editTimer); editTimer = setTimeout(renderVerdict, 120); });
renderVerdict();
mapButton();
questions();
$('measure').addEventListener('click', measure);
cachedText(MOD_URL).then((src) => { otherReason = extractNullReason(src); fillReasons(); renderVerdict(); })
.catch(() => fillReasons());
cachedText(RECEIVERS_URL).then((t) => listReceivers(JSON.parse(t)))
.catch((e) => { $('recv').innerHTML = `<li class="row empty"><span class="st">FAIL</span> receivers.json could not be read: ${esc(e.message)}</li>`; });
}
main();Iterations — 45 Deeplink Round Trip Page
A web page in Galaxies Wafers that reads inputs for edit and pick, covering substations. Published at https://ventusltd.github.io/galaxies-wafers/iterations/45-deeplink-round-trip/.
rendergalaxies-wafers / iterations/45-deeplink-round-trip/index.html · lines 1–62 of 62 · Entry point
- What it does
- It draws substations. Side effects: changes the web page (DOM).
- Why it exists in the grid workflow
- Domain terms in the code: substations. README: "The page (`index.html`, `app.mjs`, `lib.mjs`) is inherited unchanged from testcode/202609151339."
- Inputs & outputs
- In: form fields (user input). Out: web page.
- Downstream impact
- It is itself an entry point, published at https://ventusltd.github.io/galaxies-wafers/iterations/45-deeplink-round-trip/.
- What it achieves
- The MAP Button, Round Trip.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- galaxies-wafers · iterations/45-deeplink-round-trip · page
- Uses
- Iterations — 45 Deeplink Round Trip Style Sheet (stylesheet), Iterations — 09 Deeplink Receiver Page (link), Iterations — 45 Deeplink Round Trip (script src)
- Used by
- none found
- 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
- galaxies-wafers@5814793812add74605660fa821e6a39b8de80588 iterations/45-deeplink-round-trip/index.html:1-62 · blob a04d7fd3407e087d5e0a02266348d0a5a2b40489 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: unknown · users: none · canonical: unknown
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<meta name="color-scheme" content="dark">
<title>The MAP Button, Round Trip</title>
<link rel="icon" href="data:,">
<link rel="stylesheet" href="style.css">
</head>
<body>
<main>
<h1>THE MAP BUTTON, ROUND TRIP</h1>
<p class="dim">Pipeline News puts a <b>MAP ↗</b> button on a project record. It is a deep link: a URL that carries the project's identity into Grid Atlas. This page runs the estate's own contract module, <code>deeplink/contract.js</code>, in your browser, and shows the link surviving and failing.</p>
<p class="dim small" id="src">module: loading…</p>
<div class="summary" id="summary">running the round trip…</div>
<section class="sec" id="s-round">
<h2>1 · ROUND TRIP</h2>
<p class="dim small">For every bucket in the module's <code>BUCKETS</code>: a <b>synthetic</b> record (not a real project) goes through <code>buildDeepLink</code>, then <code>parseDeepLink</code>. Each field is compared with <code>===</code>.</p>
<ul class="rows" id="round"></ul>
</section>
<section class="sec" id="s-recv">
<h2>2 · RECEIVERS</h2>
<p class="dim small">From <code>deeplink/receivers.json</code> at the same commit. Nothing is fetched until you tap. Queue of 4, 15 s timeout each, GET with no cache. The status is measured now, in your browser.</p>
<div class="pick"><button type="button" id="measure" disabled>measure receivers now</button></div>
<ul class="rows" id="recv"></ul>
</section>
<section class="sec" id="s-break">
<h2>3 · BREAK IT</h2>
<p class="dim small">Edit the link by hand. The page runs <code>parseDeepLink</code> on each change, then asks <code>buildDeepLink</code> to rebuild it, and reports what the module refuses, drops or lets through.</p>
<textarea id="edit" spellcheck="false" autocapitalize="off" autocomplete="off" aria-label="deep link to parse"></textarea>
<div class="pick" id="chips"></div>
<div id="verdict" aria-live="polite"></div>
</section>
<section class="sec" id="s-map">
<h2>4 · MAP BUTTON</h2>
<p class="dim small">Pick a synthetic record. The button opens the canonical receiver with the link <code>buildDeepLink(record)</code> returns. The identity is synthetic, so the receiver's register lookup should not find it: that is the honest arrival for made-up data.</p>
<div class="pick"><select id="pick" aria-label="synthetic record"></select><span id="mapbtn"></span></div>
<code class="link" id="maphref"></code>
<p class="small" id="sender"></p>
</section>
<details id="questions" class="questions">
<summary>Questions</summary>
<dl>
<dt>How does this help draw a system or a single-line diagram?</dt>
<dd id="q1">It draws no busbar, feeder or transformer itself. It carries a project's identity (<code>repd_ref</code>) and its point (<code>latitude</code>, <code>longitude</code>, <code>zoom</code>) to the map, where the receiver draws the project's connection: the measured line to the nearest mapped transmission substation (<code>canonical.computes</code> in receivers.json). The technology … [line shortened here: 487 characters; full line on GitHub]
<dt>What is this code used for?</dt>
<dd id="q2">loading…</dd>
<dt>Where does it lead next?</dt>
<dd id="q3">To the receiver's arrival: register lookup by exact <code>repd_ref</code>, fly to the point, enable the resolved layer, then measure the nearest mapped substation (docs/deeplink-contract.md §3). On this site the receiving side is iteration <a href="../09-deeplink-receiver/">09, the deep-link receiver</a>. Whether a real arrival completes is not established by this page: it sends … [line shortened here: 431 characters; full line on GitHub]
</dl>
<p class="small" id="machine">Machine detail: loading…</p>
</details>
</main>
<script type="module" src="app.mjs"></script>
</body>
</html>Iterations — 45 Deeplink Round Trip Style Sheet
A style sheet in Galaxies Wafers. Served with the page at https://ventusltd.github.io/galaxies-wafers/iterations/45-deeplink-round-trip/.
rendergalaxies-wafers / iterations/45-deeplink-round-trip/style.css · lines 1–41 of 41 · Entry point
- What it does
- Side effects: changes the web page (DOM).
- Downstream impact
- Used directly by 1 file: Iterations — 45 Deeplink Round Trip Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/45-deeplink-round-trip/). It is itself an entry point, published at https://ventusltd.github.io/galaxies-wafers/iterations/45-deeplink-round-trip/.
- 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 45 Deeplink Round Trip page at https://ventusltd.github.io/galaxies-wafers/iterations/45-deeplink-round-trip/.
- Application
- galaxies-wafers · iterations/45-deeplink-round-trip · style sheet
- Uses
- none found
- Used by
- loaded by Iterations — 45 Deeplink Round Trip Page (stylesheet)
- 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
- galaxies-wafers@5814793812add74605660fa821e6a39b8de80588 iterations/45-deeplink-round-trip/style.css:1-41 · blob cf36b6d45f4b3689956b878e7cf69c2cc4337454 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: dom · domain stage: unknown · users: none · canonical: unknown
:root{--ink:#d8dee9;--dim:#8b93a7;--ground:#0b0d12;--edge:#1b2030;--beam:#5ec8f2;--grey:#8b93a7}
*{box-sizing:border-box}
html{-webkit-text-size-adjust:100%}
body{margin:0;background:var(--ground);color:var(--ink);font:13px/1.45 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;
padding:calc(env(safe-area-inset-top,0px) + .8rem) 1rem calc(env(safe-area-inset-bottom,0px) + 2rem)}
main{max-width:52rem;margin:0 auto}
h1{font-size:14px;letter-spacing:.18em;font-weight:600;margin:0 0 .35rem;color:#fff}
h2{font-size:11.5px;letter-spacing:.14em;font-weight:600;margin:0;color:#fff}
p{margin:.35rem 0}
.dim{color:var(--dim)} .small{font-size:11.5px}
a{color:var(--beam);overflow-wrap:anywhere}
code{color:var(--beam);overflow-wrap:anywhere}
.summary{border-left:3px solid #fff;padding:.35rem .6rem;background:#10131b;margin:.6rem 0;overflow-wrap:anywhere}
.sec{border:1px solid var(--edge);border-radius:.45rem;background:#0e1118;margin:.7rem 0;padding:.5rem .65rem}
.rows{list-style:none;margin:.4rem 0 0;padding:0;display:grid;gap:.4rem}
.row{border:1px solid var(--edge);border-left-width:4px;border-radius:.4rem;background:#10131b;padding:.4rem .55rem;overflow-wrap:anywhere;min-width:0}
.row.same{border-left-color:#eceff4;border-left-style:solid}
.row.changed{border-left-color:#eceff4;border-left-style:double;border-left-width:6px}
.row.empty{border-left-color:var(--grey);border-left-style:dotted}
.rhead{display:flex;flex-wrap:wrap;gap:.2rem .6rem;align-items:baseline}
.st{font-weight:600;letter-spacing:.08em;color:#fff;font-size:12px}
.row.empty .st{color:var(--grey)}
.link{display:block;background:#05060a;border:1px solid var(--edge);border-radius:.3rem;padding:.25rem .4rem;margin:.25rem 0;color:#cfd6e4;font-size:11px;white-space:pre-wrap;word-break:break-all}
.f{display:grid;grid-template-columns:6.5rem 1fr;gap:.05rem .5rem;font-size:11.5px}
.f span:nth-child(odd){color:var(--dim)}
.quote{border-left:2px solid var(--dim);padding-left:.5rem;color:#cfd6e4;font-size:11.5px;white-space:pre-wrap;margin:.3rem 0}
.pick{display:flex;flex-wrap:wrap;gap:.4rem;margin:.45rem 0}
.pick select{flex:1 1 12rem;min-width:0;font:inherit;font-size:16px;color:#fff;background:#05060a;border:1px solid var(--edge);border-radius:.35rem;min-height:44px}
button,.chip{font:inherit;color:var(--ink);background:#07080c;border:1px solid var(--edge);border-radius:.35rem;min-height:44px;padding:0 .7rem}
button:disabled{opacity:.4}
.chip{min-height:36px;font-size:11.5px}
textarea{width:100%;font:inherit;font-size:16px;color:#fff;background:#05060a;border:1px solid var(--edge);border-radius:.35rem;padding:.4rem;min-height:7.5em;resize:vertical}
/* The MAP button, in Pipeline News' grammar: an outlined action link reading "MAP ↗". */
.action-link.atlaslink{display:inline-flex;align-items:center;justify-content:center;min-height:44px;min-width:88px;padding:0 .9rem;
border:1px solid var(--beam);border-radius:.3rem;color:var(--beam);text-decoration:none;font-weight:700;letter-spacing:.1em}
.action-disabled{display:inline-flex;align-items:center;min-height:44px;padding:0 .9rem;border:1px dashed var(--grey);border-radius:.3rem;color:var(--grey);letter-spacing:.1em}
.refuse{color:#fff;text-decoration:underline;text-underline-offset:3px}
.questions{border:1px solid var(--edge);border-radius:.45rem;background:#10131b;padding:0 .65rem;margin:1.2rem 0 .5rem}
.questions summary{font-size:11px;letter-spacing:.14em;text-transform:uppercase;cursor:pointer;color:var(--beam);min-height:44px;display:flex;align-items:center}
.questions dt{color:#fff;margin-top:.5rem;font-size:12px}
.questions dd{margin:.2rem 0 .6rem;font-size:11.5px;overflow-wrap:anywhere}Iterations — 46 Chemistry Ledger
A JavaScript module in Galaxies Wafers that draws compounds and uses data from the star-maker repository. Served with the page at https://ventusltd.github.io/galaxies-wafers/iterations/46-chemistry-ledger/.
rendergalaxies-wafers / iterations/46-chemistry-ledger/app.mjs · lines 1–265 of 265 · Entry point · pattern hydrateGraph (shared by 2 files)
- What it does
- It draws compounds. Defines 19 functions or classes, including $, el, fmt, FetchQueue, fetchOnce. Side effects: changes the web page (DOM); makes network requests.
- Why it exists in the grid workflow
- README: "The page (`index.html`, `app.mjs`, `lib.mjs`) is inherited unchanged from testcode/202609151339."
- Inputs & outputs
- In: data source: star-maker data; JSON file compounds.json; JSON file graph.json. Out: canvas drawing.
- Downstream impact
- Used directly by 1 file: Iterations — 46 Chemistry Ledger Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/46-chemistry-ledger/). It is itself an entry point, published at https://ventusltd.github.io/galaxies-wafers/iterations/46-chemistry-ledger/.
- What it achieves
- It fetches queue (`FetchQueue`), fetches once (`fetchOnce`) and sets label (`setLabel`). Grid Atlas loading grammar; arithmetic in `ledger.mjs`. It responds to click, resize and change events.
- Why it matters
- Loaded by the page of the same name at https://ventusltd.github.io/galaxies-wafers/iterations/46-chemistry-ledger/.
- Application
- galaxies-wafers · iterations/46-chemistry-ledger · JavaScript module
- Uses
- Ledger (import)
- Used by
- loaded by Iterations — 46 Chemistry Ledger Page (script src)
- Produces
- $, el, fmt, FetchQueue, fetchOnce, setLabel, hydrateLedger, buildGrid, applyMode, renderRule, renderSummary, renderCard
- Defines here
- $, el, fmt, FetchQueue, fetchOnce, setLabel, hydrateLedger, buildGrid, applyMode, renderRule, renderSummary, renderCard, add, page, renderQuestions, hydrateGraph, geom, drawGraph, P
- 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/46-chemistry-ledger/app.mjs:1-265 · blob 5f6c67ee47812a4342ba633a49e7a5389b073302 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, network · domain stage: unknown · users: none · canonical: unknown
/* Chemistry Ledger — the page. Grid Atlas loading grammar; arithmetic in ledger.mjs. */
import * as L from './ledger.mjs';
const STAR_MAKER_COMMIT = 'c5bf5f6518feba594bb057988e8e99ca81044952';
const RAW = `https://raw.githubusercontent.com/Ventusltd/star-maker/${STAR_MAKER_COMMIT}/`;
const URL_COMPOUNDS = RAW + 'chemistry/compounds.json';
const URL_GRAPH = RAW + 'chemistry/graph.json';
const URL_LEGEND = RAW + 'CHEMISTRY.md';
const PAGE = 40; // compounds shown per "more" tap
const $ = id => document.getElementById(id);
const el = (tag, cls, text) => { const e = document.createElement(tag); if (cls) e.className = cls; if (text != null) e.textContent = text; return e; };
const fmt = n => Number(n).toLocaleString('en-GB');
/* ── one queue of 4, 15 s timeouts, one promise per URL ─────────────────── */
class FetchQueue {
constructor(n) { this.n = n; this.active = 0; this.wait = []; this.peak = 0; }
async add(task) {
if (this.active >= this.n) await new Promise(r => this.wait.push(r));
this.active++; this.peak = Math.max(this.peak, this.active);
try { return await task(); } finally { this.active--; if (this.wait.length) this.wait.shift()(); }
}
}
const queue = new FetchQueue(4);
const cache = new Map();
const fetchLog = [];
function fetchOnce(url, as) {
if (cache.has(url)) return cache.get(url);
const p = queue.add(async () => {
const ctl = new AbortController();
const timer = setTimeout(() => ctl.abort(), 15000);
fetchLog.push(url);
try {
const res = await fetch(url, { signal: ctl.signal });
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return as === 'json' ? await res.json() : await res.text();
} catch (err) {
throw new Error(err && err.name === 'AbortError' ? 'timed out after 15 s' : (err && err.message) || String(err));
} finally { clearTimeout(timer); }
});
cache.set(url, p);
p.catch(() => cache.delete(url));
return p;
}
const RT = { ledger: { loaded: false, loading: false }, graph: { loaded: false, loading: false } };
const S = { compounds: null, elements: null, rules: null, mode: 'all', sel: null, cells: new Map(), graph: null, pos: null, edges: null, gsel: null, matches: 0 };
const LBL_LEDGER = 'Ledger · compounds.json + CHEMISTRY.md';
const LBL_GRAPH = 'Graph · graph.json edges';
function setLabel(id, base, state) { $(id).textContent = `${base} [${state}]`; }
/* ── ledger ─────────────────────────────────────────────────────────────── */
async function hydrateLedger() {
if (RT.ledger.loaded || RT.ledger.loading) return;
RT.ledger.loading = true;
setLabel('lbl-ledger', LBL_LEDGER, 'LOAD');
try {
const [chem, md] = await Promise.all([fetchOnce(URL_COMPOUNDS, 'json'), fetchOnce(URL_LEGEND, 'text')]);
if (!chem || !Array.isArray(chem.compounds)) throw new Error('compounds.json has no compounds[] array');
S.compounds = chem.compounds; S.generated = chem.generated_utc; S.starsDeclared = chem.stars;
S.elements = L.countElements(chem.compounds);
S.rules = L.readRules(md);
RT.ledger.loaded = true;
if (S.elements.size === 0) {
setLabel('lbl-ledger', LBL_LEDGER, 'EMPTY: no elements in any formula');
$('grid').textContent = 'EMPTY — no formula carried an element.';
return;
}
setLabel('lbl-ledger', LBL_LEDGER, `OK · ${fmt(S.compounds.length)} compounds · ${fmt(S.elements.size)} elements`);
buildGrid(); renderSummary(); renderQuestions();
} catch (err) {
setLabel('lbl-ledger', LBL_LEDGER, `FAIL: ${err.message}`);
$('summary').textContent = `FAIL — ${err.message}. Untick and tick again to retry.`;
} finally { RT.ledger.loading = false; }
}
function buildGrid() {
const grid = $('grid'); grid.textContent = '';
const bySym = new Map();
for (const e of S.elements.values()) { if (!bySym.has(e.symbol)) bySym.set(e.symbol, []); bySym.get(e.symbol).push(e); }
const syms = [...bySym.keys()].sort((a, b) => bySym.get(b).length - bySym.get(a).length || (a < b ? -1 : 1));
for (const sym of syms) {
const list = bySym.get(sym).sort((a, b) => (a.stamp === b.stamp ? 0 : a.stamp === null ? -1 : b.stamp === null ? 1 : a.stamp < b.stamp ? -1 : 1));
const row = el('div', 'row');
row.append(el('h3', null, `${sym} · ${list.length} element${list.length === 1 ? '' : 's'}`));
const cells = el('div', 'cells');
for (const e of list) {
const b = el('button', 'cell'); b.type = 'button'; b.dataset.label = e.label;
b.append(el('b', null, e.stamp === null ? e.symbol : e.stamp), el('span', 'n', `${fmt(e.compounds)} · ${fmt(e.greenCompounds)}/${fmt(e.redCompounds)}`));
b.setAttribute('aria-label', `${e.label}: ${e.compounds} compositions, ${e.greenCompounds} all green, ${e.redCompounds} with a red star`);
cells.append(b); S.cells.set(e.label, b);
}
row.append(cells); grid.append(row);
}
applyMode();
}
function applyMode() {
if (!S.elements) return;
$('grid').classList.toggle('filter', S.mode !== 'all');
const rule = S.mode === 'noble' ? S.rules.noble : S.mode === 'radioactive' ? S.rules.radioactive : null;
const test = S.mode === 'noble' ? L.isNoble : L.isRadioactive;
let n = 0;
for (const [label, b] of S.cells) { const m = S.mode !== 'all' && test(S.elements.get(label), rule); b.classList.toggle('match', m); if (m) n++; }
S.matches = n; renderRule();
}
function renderRule() {
const p = $('rule');
if (!S.rules) return;
const r = S.rules;
if (S.mode === 'all') {
p.textContent = `Toggle to outline elements by CHEMISTRY.md's own rules: line ${r.noble ? r.noble.line : 'not found'} (noble) and line ${r.radioactive ? r.radioactive.line : 'not found'} (radioactive). Neither is a field in the JSON files.`;
return;
}
const rule = S.mode === 'noble' ? r.noble : r.radioactive;
if (!rule) { p.textContent = `EMPTY — CHEMISTRY.md has no "${S.mode}" heading this page can read, so no element is outlined.`; return; }
p.textContent = `CHEMISTRY.md line ${rule.line}: "${rule.text}". Applied to counts from compounds.json (red compound = a compound with red > 0): ${fmt(S.matches)} of ${fmt(S.elements.size)} elements match, outlined dashed.`;
}
function renderSummary() {
let stars = 0, red = 0, green = 0, amber = 0;
for (const c of S.compounds) { stars += c.stars; red += c.red; green += c.green; amber += c.amber; }
const vals = [...S.elements.values()];
const noble = vals.filter(e => L.isNoble(e, S.rules.noble)).length;
const rad = vals.filter(e => L.isRadioactive(e, S.rules.radioactive)).length;
const s = $('summary'); s.textContent = '';
s.append('Counted: ', el('b', null, fmt(S.compounds.length)), ' compounds over ', el('b', null, fmt(stars)), ` stars (file header says ${S.starsDeclared}) · `,
el('b', null, fmt(green)), ' green, ', el('b', null, fmt(amber)), ' amber, ', el('b', null, fmt(red)), ' red stars · ',
el('b', null, fmt(S.elements.size)), ' elements · ',
el('b', null, S.rules.noble ? fmt(noble) : 'not yet known'), ' noble, ', el('b', null, S.rules.radioactive ? fmt(rad) : 'not yet known'), ' radioactive by the CHEMISTRY.md rules.');
}
function renderCard(label) {
const e = S.elements.get(label); const card = $('card'); card.textContent = '';
if (S.sel && S.cells.get(S.sel)) S.cells.get(S.sel).classList.remove('on');
S.sel = label; if (S.cells.get(label)) S.cells.get(label).classList.add('on');
card.append(el('h3', null, label));
const dl = el('dl');
const add = (k, v) => { dl.append(el('dt', null, k), el('dd', null, v)); };
add('compositions', `${fmt(e.compounds)} (${Object.entries(e.kinds).map(([k, v]) => `${fmt(v)} ${k}`).join(', ')})`);
add('with a red star', fmt(e.redCompounds));
add('all green', fmt(e.greenCompounds));
add('stars', `${fmt(e.stars)}: ${fmt(e.green)} green, ${fmt(e.amber)} amber, ${fmt(e.red)} red`);
const nr = S.rules.noble, rr = S.rules.radioactive;
add(`noble${nr ? ' (line ' + nr.line + ')' : ''}`, nr ? (L.isNoble(e, nr) ? 'yes' : 'no') : 'not yet known: rule not found');
add(`radioactive${rr ? ' (line ' + rr.line + ')' : ''}`, rr ? (L.isRadioactive(e, rr) ? 'yes' : 'no') : 'not yet known: rule not found');
card.append(dl);
card.append(el('p', 'dim small', 'Failure messages, grouped (compounds[].decays[].text):'));
const groups = [...e.decays.values()].sort((a, b) => b.compounds - a.compounds);
if (!groups.length) card.append(el('p', null, 'EMPTY — no compound carrying this element recorded a decay.'));
else {
const t = el('table'); const hr = el('tr'); hr.append(el('td', 'k', 'comp.'), el('td', 'k', 'stars'), el('td', null, 'message')); t.append(hr);
for (const g of groups) { const tr = el('tr'); tr.append(el('td', 'k', fmt(g.compounds)), el('td', 'k', fmt(g.stars)), el('td', null, g.text)); t.append(tr); }
card.append(t);
}
card.append(el('p', 'dim small', `Compounds (${fmt(e.idx.length)}), in file order, ${PAGE} at a time:`));
const ul = el('ul', 'rows'); card.append(ul);
let shown = 0;
const more = el('button', 'more'); more.type = 'button';
const page = () => {
const end = Math.min(e.idx.length, shown + PAGE);
for (; shown < end; shown++) {
const c = S.compounds[e.idx[shown]];
ul.append(el('li', 'plain', `${c.formula} · ${c.kind} · ${c.stars} star${c.stars === 1 ? '' : 's'}: ${c.green} green, ${c.amber} amber, ${c.red} red`));
}
more.textContent = `show ${Math.min(PAGE, e.idx.length - shown)} more (${fmt(shown)} of ${fmt(e.idx.length)} shown)`;
more.hidden = shown >= e.idx.length;
};
more.addEventListener('click', page); card.append(more); page();
}
function renderQuestions() {
$('q-pin').textContent = STAR_MAKER_COMMIT.slice(0, 12);
if (!S.compounds) return;
const s = L.decayTotals(S.compounds, 'requires the sld-styles module');
const g = L.decayTotals(S.compounds, 'requires the geodesy module');
$('q-styles').textContent = `${fmt(s.compositions)} compositions (${fmt(s.stars)} stars)`;
$('q-geo').textContent = `${fmt(g.compositions)} compositions (${fmt(g.stars)} stars)`;
$('q-verify').textContent = s.compositions === 702 ? 'the files agree, 702' : `the files give ${fmt(s.compositions)}, not 702`;
const r = S.rules;
$('q-rules').textContent = `noble: ${r.noble ? 'line ' + r.noble.line + ' "' + r.noble.text + '"' : 'not found'}; radioactive: ${r.radioactive ? 'line ' + r.radioactive.line + ' "' + r.radioactive.text + '"' : 'not found'}`;
const rad = [...S.elements.values()].filter(e => L.isRadioactive(e, r.radioactive)).map(e => e.label);
$('q-rad').textContent = rad.length ? rad.join(', ') : 'none by the stated rule';
$('machine').textContent = `Machine detail · inputs: compounds.json compounds[] {formula (elements joined by "·"), kind, stars, green, amber, red (star counts, dimensionless), decays[] {text, n = stars}} generated ${S.generated}; CHEMISTRY.md headings (noble: red compounds = 0 and compounds ≥ N; radioactive: red compounds ÷ compounds ≥ P). graph.json nodes[] {label, type}, edges[] {from, to, kin … [line shortened here: 854 characters; full line on GitHub]
}
/* ── graph ──────────────────────────────────────────────────────────────── */
async function hydrateGraph() {
if (RT.graph.loaded) { drawGraph(); return; }
if (RT.graph.loading) return;
RT.graph.loading = true;
setLabel('lbl-graph', LBL_GRAPH, 'LOAD');
try {
const g = await fetchOnce(URL_GRAPH, 'json');
if (!g || !Array.isArray(g.nodes) || !Array.isArray(g.edges)) throw new Error('graph.json lacks nodes[] or edges[]');
S.graph = g; S.pos = L.layout(g.nodes); S.edges = L.drawableEdges(g);
RT.graph.loaded = true;
setLabel('lbl-graph', LBL_GRAPH, S.edges.kept.length ? `OK · ${fmt(g.nodes.length)} nodes · ${fmt(S.edges.kept.length)} edges` : 'EMPTY: no edge has both ends among the nodes');
const kinds = {}; for (const e of S.edges.kept) kinds[e.kind] = (kinds[e.kind] || 0) + 1;
let inGraph = 'not yet known (tick Ledger)';
if (S.elements) { const labels = new Set(g.nodes.map(n => n.label)); inGraph = `${fmt([...S.elements.keys()].filter(k => !labels.has(k)).length)} of the ledger's ${fmt(S.elements.size)} elements are not graph nodes`; }
$('graphcount').textContent = `${fmt(S.edges.kept.length)} of ${fmt(g.edges.length)} edges drawn (${Object.entries(kinds).map(([k, v]) => `${fmt(v)} ${k}`).join(', ')}); ${fmt(S.edges.dropped.length)} skipped for a missing end; ${inGraph}`;
drawGraph();
renderQuestions();
} catch (err) {
setLabel('lbl-graph', LBL_GRAPH, `FAIL: ${err.message}`);
} finally { RT.graph.loading = false; }
}
const canvas = $('plane'); const ctx = canvas.getContext('2d');
function geom() {
const dpr = Math.min(3, window.devicePixelRatio || 1);
const w = canvas.clientWidth, h = canvas.clientHeight;
if (canvas.width !== Math.round(w * dpr) || canvas.height !== Math.round(h * dpr)) { canvas.width = Math.round(w * dpr); canvas.height = Math.round(h * dpr); }
return { dpr, w, h, R: Math.max(10, Math.min(w, h) / 2 - 18), cx: w / 2, cy: h / 2 };
}
function drawGraph() {
const { dpr, w, h, R, cx, cy } = geom();
ctx.setTransform(dpr, 0, 0, dpr, 0, 0); ctx.fillStyle = '#05060a'; ctx.fillRect(0, 0, w, h);
if (!$('open-graph').checked || !S.graph) { $('drawn').textContent = S.graph ? 'hidden — tick Graph' : 'WAIT — tick Graph'; return; }
const P = l => { const p = S.pos.get(l); return [cx + p.x * R, cy + p.y * R]; };
let drawn = 0;
for (const e of S.edges.kept) {
const hot = S.gsel && (e.from === S.gsel || e.to === S.gsel);
if (S.gsel && !hot) continue;
const [x1, y1] = P(e.from), [x2, y2] = P(e.to);
ctx.beginPath(); ctx.moveTo(x1, y1); ctx.lineTo(x2, y2);
if (e.kind === 'DECAYS_TO') { ctx.setLineDash([3, 3]); ctx.strokeStyle = hot ? 'rgba(239,233,220,.9)' : 'rgba(239,233,220,.10)'; }
else { ctx.setLineDash([]); ctx.strokeStyle = hot ? 'rgba(94,200,242,.9)' : 'rgba(94,200,242,.07)'; }
ctx.lineWidth = hot ? 1.2 : 1; ctx.stroke(); drawn++;
}
ctx.setLineDash([]);
for (const [label, p] of S.pos) {
const x = cx + p.x * R, y = cy + p.y * R, on = label === S.gsel, isEl = p.n.type === 'element';
ctx.beginPath(); ctx.arc(x, y, (on ? 4 : isEl ? 2 : 3.2) + 1.5, 0, Math.PI * 2); ctx.fillStyle = '#000'; ctx.fill();
ctx.beginPath(); ctx.arc(x, y, on ? 4 : isEl ? 2 : 3.2, 0, Math.PI * 2); ctx.fillStyle = isEl ? '#ffd54a' : '#ffffff'; ctx.fill();
}
if (S.gsel) { ctx.font = '11px ui-monospace,monospace'; ctx.fillStyle = '#fff'; ctx.fillText(S.gsel.slice(0, 52), 8, 16); }
$('drawn').textContent = `${fmt(drawn)} lines · ${fmt(S.pos.size)} nodes${S.gsel ? ' · tap empty space to clear' : ' · tap a node'}`;
}
canvas.addEventListener('click', ev => {
if (!S.graph || !$('open-graph').checked) return;
const r = canvas.getBoundingClientRect(); const { R, cx, cy } = geom();
const mx = ev.clientX - r.left, my = ev.clientY - r.top;
let best = null, bd = 22 * 22;
for (const [label, p] of S.pos) { const dx = cx + p.x * R - mx, dy = cy + p.y * R - my, d = dx * dx + dy * dy; if (d < bd) { bd = d; best = label; } }
S.gsel = best; drawGraph();
if (best && S.elements && S.elements.has(best)) renderCard(best);
});
window.addEventListener('resize', () => { if (S.graph) drawGraph(); });
/* ── wiring ─────────────────────────────────────────────────────────────── */
$('open-ledger').addEventListener('change', ev => { if (ev.target.checked) hydrateLedger(); });
$('open-graph').addEventListener('change', () => { if ($('open-graph').checked) hydrateGraph(); else drawGraph(); });
$('mode').addEventListener('click', ev => {
const b = ev.target.closest('button'); if (!b) return;
S.mode = b.dataset.m;
for (const x of $('mode').querySelectorAll('button')) x.setAttribute('aria-pressed', String(x === b));
if (!S.elements) { $('rule').textContent = 'WAIT — tick Ledger first; the rules and counts come from the files.'; return; }
applyMode();
});
$('grid').addEventListener('click', ev => { const b = ev.target.closest('.cell'); if (b) renderCard(b.dataset.label); });
renderQuestions();
drawGraph();
window.__ledger = { RT, S, queue, fetchLog };