In this section
- Layers Panel render · galaxies-wafers / iterations/04-400kv-engine/layers-panel.mjs lines 701–1075
Layers Panel
A JavaScript module in the iterations folder of Galaxies Wafers that draws blocks, 400kV, substations and 66kV, and uses data from the ventus-grid-engine repository. Served with the page at https://ventusltd.github.io/galaxies-wafers/iterations/04-400kv-engine/.
rendergalaxies-wafers / iterations/04-400kv-engine/layers-panel.mjs · lines 701–1075 of 1075 (continued from section 41) · Entry point · pattern bandOf (shared by 2 files)
- What it does
- It draws blocks, 400kV, substations and 66kV. Defines 60 functions or classes, including evalExpr, readAtlasTopology, get, isModule, moduleStats. Side effects: changes the web page (DOM); makes network requests.
- Why it exists in the grid workflow
- Domain stage sub33kv_design (path word 'panel'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. Domain terms in the code: 400kV, substations, 66kV.
- Inputs & outputs
- In: data source: ventus-grid-engine data; JSON file blocks.json. Out: canvas drawing. Voltage levels named: 400kV, 66kV.
- Downstream impact
- Used directly by 2 files: Iterations — 04 400kV Engine Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/04-400kv-engine/); Questions (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/04-400kv-engine/). Reached from 88 other entry points, including GlobalGrid2050 Historical Builds (globalgrid2050, https://globalgrid2050.com/historical_builds.html); GlobalGrid2050 Homepage Before Four Nests (globalgrid2050, https://globalgrid2050.com/homepage-before-four-nests-20260925.html); Homepage V037 (globalgrid2050, https://globalgrid2050.com/homepage_versions/homepage_v037.html). It is itself an entry point, published at https://ventusltd.github.io/galaxies-wafers/iterations/04-400kv-engine/.
- What it achieves
- It reads atlas topology (`readAtlasTopology`), computes bands (`computeBands`) and sets text (`setText`). Layers over the inherited wafer, in Grid Atlas's grammar. Its code works with 400 kV and 66 kV. It responds to click, resize and change events.
- Why it matters
- Loaded by the 04 400kV Engine page at https://ventusltd.github.io/galaxies-wafers/iterations/04-400kv-engine/. Also imported by Questions.
- Application
- galaxies-wafers · iterations/04-400kv-engine · JavaScript module
- Uses
- Galaxies Wafers — Lib (import)
- Used by
- loaded by Iterations — 04 400kV Engine Page (script src), imported by Questions (import), mentioned in Standalone (comment link)
- Produces
- MAX_FETCH, FETCH_TIMEOUT_MS, FEATURE_CAP, LOADER
- Defines here
- writeLayersToURL, readLayersFromURL, liveView, visibleLayers, viewKey, sizeFor, strokeRoute, planRaster, startRaster, runRaster, out, commitRaster, carry, carryCovers, tick, pump, drawOverlay, segDist2, pickAt, 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/04-400kv-engine/layers-panel.mjs:701-1075 · blob 5080b715636d31a610d16ec2356c2db7a2a054d6 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, network · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: unknown
schedule(['engine', 'cards', 'draw', 'url']);
}
/* ── 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);
}
/* ── the camera: the wafer's own, read live ──────────────────────────────── */
const liveView = () => window.__wafer?.view ?? null;
function* visibleLayers() {
for (const l of (manifest?.layers || [])) {
const s = state.get(l.id);
if (s?.on && s.status === 'OK' && s.cache) yield [l, s];
}
}
/* ── drawing: the wafer's formula, x * zoom + offset, from placed positions ── */
/* The raster canvas can be the screen plus SPAN_MARGIN of its size on every
side, so a short pan or zoom-out is carried without an empty edge. It is 0,
the screen exactly, for two measured reasons: WebKit's stroke cost grows with
the canvas area (iPhone 13 size, zoom 2.1: margin 0, 0.1, 0.25 -> 291, 336,
1,030 ms), and a canvas offset from the screen's origin is resampled onto a
DPR-3 screen differently, changing pixels at rest. A gesture that uncovers an
edge starts a fresh raster at once, a slice per frame. */
const SPAN_MARGIN = 0;
const SLICE_MS = { moving: 8, idle: 20 }; /* script time per animation frame for a raster in progress */
let gen = 0; /* bumped whenever anything drawn changes other than the camera */
let job = null; /* the raster in progress */
let jobRaf = 0;
const viewKey = v => `${v.x},${v.y},${v.zoom},${v.w},${v.h},${v.dpr}`;
function sizeFor(v) {
const mx = Math.round(v.w * SPAN_MARGIN), my = Math.round(v.h * SPAN_MARGIN);
const cw = v.w + 2 * mx, ch = v.h + 2 * my, dpr = v.dpr || 1;
return { mx, my, cw, ch, dpr, W: Math.round(cw * dpr), H: Math.round(ch * dpr) };
}
/* One feature's route. Skipped when its box is more than `pad` px outside the
raster; otherwise drawn exactly as the first version drew it, one path per feature.
Screen y grows downward, so a box is above the raster when its LOWEST world y
(b[1], the largest screen y) is above the top, and below it when its HIGHEST
(b[3]) is below the bottom. The first version tested these the other way
round, which dropped every route that crossed the top or bottom edge. */
function strokeRoute(g, c, i, W, H, z, ox, oy, pad) {
const b = c.box, bi = i * 4;
if (b[bi + 2] * z + ox < -pad || b[bi] * z + ox > W + pad || oy - b[bi + 1] * z < -pad || oy - b[bi + 3] * z > H + pad) return;
const p = c.pos, s0 = c.start[i], n = c.len[i];
g.beginPath();
for (let k = 0; k < n; k++) {
const x = p[(s0 + k) * 2] * z + ox, y = oy - p[(s0 + k) * 2 + 1] * z;
k ? g.lineTo(x, y) : g.moveTo(x, y);
}
g.stroke();
LOADER.drawn++;
}
/* Everything one raster draws, fixed when it starts: later loads, releases and
band changes wait for the next raster, so a raster is never a mixture. The
order is the first version's: layer colours, then bands 66kV up to 400kV,
then substations, then the inspected feature. */
function planRaster(v) {
const steps = [];
const engineOn = engine.on && engine.bands.length;
for (const [l, s] of visibleLayers()) {
if (engineOn && isModule(l)) continue;
steps.push({ kind: 'layer', l, c: s.cache });
}
if (engineOn) {
const mods = [];
for (const [l, s] of visibleLayers()) if (isModule(l)) { s.eng ??= moduleStats(s.doc); mods.push(s); }
for (const band of [...engine.bands].reverse()) { /* 66kV first, 400kV on top */
for (const s of mods) if (bandOf(s.eng.count) === band) steps.push({ kind: 'band', band, c: s.cache });
}
if (engine.subs) {
const dots = [];
for (const s of mods) {
if (!Number.isFinite(s.eng.first)) continue;
s.eng.xy ??= placeAll([s.eng.first]);
dots.push(s.eng.xy);
}
steps.push({ kind: 'subs', dots, r: evalExpr(engine.subs.radius, Math.log2(v.zoom)) });
}
}
if (picked) steps.push({ kind: 'picked', picked });
return steps;
}
function startRaster(v) {
const sz = sizeFor(v);
const cv = back.canvas;
if (cv.width !== sz.W || cv.height !== sz.H) {
cv.width = sz.W; cv.height = sz.H;
cv.style.width = sz.cw + 'px'; cv.style.height = sz.ch + 'px';
cv.style.left = -sz.mx + 'px'; cv.style.top = -sz.my + 'px';
}
const g = back.ctx;
g.setTransform(sz.dpr, 0, 0, sz.dpr, 0, 0);
g.globalAlpha = 1;
g.clearRect(0, 0, sz.cw, sz.ch);
const z = v.zoom;
job = { v: { x: v.x, y: v.y, zoom: v.zoom, w: v.w, h: v.h, dpr: v.dpr }, key: viewKey(v), gen, sz,
z, ox: sz.cw / 2 - v.x * z, oy: sz.ch / 2 + v.y * z,
steps: planRaster(v), si: 0, fi: 0, cpu: 0, t0: performance.now() };
}
/* Draws the raster in progress until it is done (true) or `budget` ms have passed. */
function runRaster(budget) {
const t0 = performance.now();
const J = job, g = back.ctx, { cw, ch } = J.sz, { z, ox, oy } = J;
const out = () => { J.cpu += performance.now() - t0; return false; };
LOADER.slices++;
while (J.si < J.steps.length) {
const st = J.steps[J.si];
if (st.kind === 'layer') {
const { l, c } = st;
g.strokeStyle = l.colour; g.fillStyle = l.colour;
g.globalAlpha = l.draws === 'lines' ? 0.55 : 0.8;
g.lineWidth = 1;
for (; J.fi < c.F; J.fi++) {
const i = J.fi;
if (c.type[i] === 1) {
const j = c.start[i], x = c.pos[j * 2] * z + ox, y = oy - c.pos[j * 2 + 1] * z;
if (x < -2 || y < -2 || x > cw + 2 || y > ch + 2) continue;
g.fillRect(x - 1, y - 1, 2, 2);
} else if (c.type[i] === 2) {
strokeRoute(g, c, i, cw, ch, z, ox, oy, 2);
if (performance.now() - t0 > budget) { J.fi++; return out(); }
}
}
} else if (st.kind === 'band') {
const { band, c } = st;
g.globalAlpha = 0.9; g.lineCap = 'round'; g.lineJoin = 'round';
g.strokeStyle = band.color; g.lineWidth = band.width;
for (; J.fi < c.F; J.fi++) {
if (c.type[J.fi] !== 2) continue;
strokeRoute(g, c, J.fi, cw, ch, z, ox, oy, band.width + 2);
if (performance.now() - t0 > budget) { J.fi++; return out(); }
}
} else if (st.kind === 'subs') {
const r = st.r;
g.globalAlpha = 0.85; g.fillStyle = engine.subs.color; g.strokeStyle = '#0b0d12'; g.lineWidth = 0.6;
g.lineCap = 'round'; g.lineJoin = 'round';
for (const xy of st.dots) {
const x = xy[0] * z + ox, y = oy - xy[1] * z;
if (x < -r || y < -r || x > cw + r || y > ch + r) continue;
g.beginPath(); g.arc(x, y, r, 0, Math.PI * 2); g.fill(); g.stroke();
}
} else if (st.kind === 'picked') {
const pk = st.picked, geo = pk.feature.geometry;
g.globalAlpha = 1; g.strokeStyle = pk.layer.colour; g.lineWidth = 1.4;
const ks = geo.type === 'Point' ? [geo.key] : geo.keys;
const p = placeAll(ks);
for (let i = 0; i < ks.length; i++) {
g.beginPath(); g.arc(p[i * 2] * z + ox, oy - p[i * 2 + 1] * z, 7, 0, 6.2832); g.stroke();
}
}
g.globalAlpha = 1;
J.si++; J.fi = 0;
}
J.cpu += performance.now() - t0;
return true;
}
/* Shows the finished raster: the two canvases change places. */
function commitRaster() {
const J = job;
job = null;
[front, back] = [back, front];
front.anchor = { ...J.v, key: J.key, gen: J.gen };
front.canvas.id = 'overlay'; back.canvas.removeAttribute('id');
front.canvas.style.transform = '';
front.canvas.style.visibility = '';
back.canvas.style.visibility = 'hidden';
back.canvas.style.transform = '';
LOADER.drawMs = J.cpu; LOADER.rasterWallMs = performance.now() - J.t0; LOADER.rasters++;
}
/* The CSS transform that carries the shown raster to the camera v: translation
and scale about the screen centre, which is the raster's centre. */
function carry(v) {
const a = front.anchor;
const s = v.zoom / a.zoom;
const dx = (a.x - v.x) * v.zoom, dy = -(a.y - v.y) * v.zoom;
return `translate(${dx}px,${dy}px) scale(${s})`;
}
/* True when the carried raster still covers the whole screen at no more than
twice its drawn scale; otherwise a fresh raster is started while moving. */
function carryCovers(v) {
const a = front.anchor;
if (!a || a.w !== v.w || a.h !== v.h || a.dpr !== v.dpr) return false;
const s = v.zoom / a.zoom, { cw, ch } = sizeFor(a);
const dx = (a.x - v.x) * v.zoom, dy = -(a.y - v.y) * v.zoom;
return s <= 2 && Math.abs(dx) + v.w / 2 <= s * cw / 2 && Math.abs(dy) + v.h / 2 <= s * ch / 2;
}
function tick() {
jobRaf = 0;
const v = liveView();
pump(v, !!v?.moving);
}
/* The one entry point for every wafer frame and every change. Idle and up to
date: nothing is drawn. Moving: the shown raster is carried, and a fresh one is
started only when the carried one no longer covers the screen. Settled or
changed: a full raster is started. A raster in progress runs one slice per
frame and is shown when complete. */
function pump(v, moving) {
if (!v || !v.w || !v.h) return; /* the wafer has not framed itself yet */
const key = viewKey(v);
if (!job) {
const a = front.anchor;
if (a && a.key === key && a.gen === gen) { front.canvas.style.transform = ''; return; }
if (!moving || !carryCovers(v)) startRaster(v);
}
if (job && !jobRaf && runRaster(moving ? SLICE_MS.moving : SLICE_MS.idle)) { /* one slice per frame: a pending tick runs the next */
commitRaster();
const a = front.anchor;
if (!moving && (a.key !== key || a.gen !== gen)) startRaster(v); /* the view or the data moved on meanwhile */
}
if (front.anchor) {
const same = front.anchor.key === key;
if (!same) LOADER.carried++;
front.canvas.style.transform = same ? '' : carry(v);
}
if (job && !jobRaf) jobRaf = requestAnimationFrame(tick);
}
function drawOverlay(snap) {
const v = snap && typeof snap.zoom === 'number' ? snap : liveView();
pump(v, !!v?.moving);
}
/* The in-view count follows the camera, and costs nothing while the ring is unchanged. */
let lastRingSig = '';
window.__wafer?.onDraw.add(snap => {
drawOverlay(snap);
if (!engine.index) return;
const r = viewRing(), sig = r ? r.sig : '';
if (sig !== lastRingSig) { lastRingSig = sig; paintLoadState(); }
});
/* ── 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;
const z = v.zoom, ox = v.w / 2 - v.x * z, oy = v.h / 2 + v.y * z;
let best = null, bestD = PICK_REACH * PICK_REACH;
for (const [l, s] of visibleLayers()) {
const c = s.cache;
for (let i = 0; i < c.F; i++) {
if (!c.len[i]) continue;
const j0 = c.start[i];
let px = c.pos[j0 * 2] * z + ox, py = oy - c.pos[j0 * 2 + 1] * z;
let d = (px - cx) ** 2 + (py - cy) ** 2;
if (c.type[i] === 2) {
for (let k = 1; k < c.len[i]; k++) {
const x = c.pos[(j0 + k) * 2] * z + ox, y = oy - c.pos[(j0 + k) * 2 + 1] * z;
d = Math.min(d, segDist2(cx, cy, px, py, x, y));
px = x; py = y;
}
}
if (d < bestD) { bestD = d; best = { layer: l, feature: s.doc.features[i] }; }
}
}
return best;
}
/* Dataset text only ever reaches the page through textContent. */
function inspect(hit) {
picked = hit;
const box = $('layersInspect');
box.replaceChildren();
if (!hit) { box.hidden = true; gen++; 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;
bodyOpened();
gen++; 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);
}
/* Read-only counters for tests. */
window.__layers04 = Object.freeze({ LOADER, FEATURE_CAP, MAX_FETCH, held: () => heldFeatures(), busy: () => !!engine.queue,
rastering: () => !!job, redraw: () => { gen++; drawOverlay(); } });
(async () => {
schedule(['engine']);
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();
try { await readAtlasTopology(); } catch (e) { engine.why = 'Atlas topology unavailable: ' + e.message; engine.on = false; }
for (const l of manifest.layers) state.set(l.id, { status: 'WAIT', on: false, why: '', loaded: false, loading: false, doc: null, cache: null, eng: null, used: 0, keys: null });
buildRows();
schedule(['engine', 'cards']);
readLayersFromURL();
} catch (e) {
$('layersList').replaceChildren(node('div', `Layers unavailable: ${e.message}. The wafer itself is unaffected.`, 'lnote'));
}
})();