In this section
- Map Receiver Restoration Browser render · gridatlas / tools/proofs/map-receiver-restoration.browser.mjs lines 1–51
- Menu Bar Attrib Clearance Browser render · gridatlas / tools/proofs/menu-bar-attrib-clearance.browser.mjs lines 1–277
- Menu Bar Dom Proof interaction · gridatlas / tools/proofs/menu-bar-dom.proof.mjs lines 1–372
Map Receiver Restoration Browser
A JavaScript module in the proofs folder of GridAtlas that draws National Energy System Operator (NESO) connection sites lean, map receiver timeout and the Renewable Energy Planning Database (REPD) register.
rendergridatlas / tools/proofs/map-receiver-restoration.browser.mjs · lines 1–51 of 51 · Entry point
- What it does
- It draws NESO connection sites lean, map receiver timeout and the REPD register. Uses libraries node:fs/promises, node:path, node:assert/strict. Side effects: changes the web page (DOM); reads or writes files.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (repository name word 'gridatlas'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: the REPD register.
- Inputs & outputs
- In: JSON file neso-connection-sites.lean.json; JSON file current.json. Out: JSON file map-receiver-timeout.json.
- Downstream impact
- Used directly by 1 file: GridAtlas PR File Size Guard Workflow (gridatlas).
- What it achieves
- It writes `work/map-receiver-timeout.json`.
- Why it matters
- Run by GridAtlas PR File Size Guard Workflow.
- Application
- gridatlas · tools/proofs · JavaScript module
- Uses
- GridAtlas — Index Page (estate URL), node:fs/promises, node:path, node:assert/strict
- Used by
- run by GridAtlas PR File Size Guard Workflow (workflow run)
- 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
- gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 tools/proofs/map-receiver-restoration.browser.mjs:1-51 · blob 31fe47cda8f7dab7e7608da24e37daba05dc0bdb · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
import { chromium } from 'playwright';
import fs from 'node:fs/promises';
import path from 'node:path';
import assert from 'node:assert/strict';
const ROOT=process.cwd(), GEN=process.env.MAP_RECEIVER_GENERATION||'202611161645';
assert.match(GEN,/^\d{12}$/);
const widths=process.env.WIDTHS?.split(',').map(Number)||[390,393,1440];
const refs=process.env.REFS?.split(',')||['12588','14535','2470'];
const channel=process.env.BROWSER_CHANNEL||null;
const receipts=[];const browser=await chromium.launch({headless:true,...(channel?{channel}:{})});
const browserIdentity={channel:channel||'playwright-chromium',version:browser.version()};
await fs.mkdir('work',{recursive:true});
try{
for(const width of widths)for(const ref of refs){
const context=await browser.newContext({viewport:{width,height:900},hasTouch:width<700,isMobile:width<700});
if (!process.env.MAP_RECEIVER_PUBLIC) await context.route('https://ventusltd.github.io/gridatlas/**',async route=>{
const pathname=new URL(route.request().url()).pathname.replace(/^\/gridatlas\//,'');
if(process.env.NESO_TIMEOUT==='1' && pathname.endsWith('neso-connection-sites.lean.json')){await new Promise(resolve=>setTimeout(resolve,6500));await route.abort().catch(()=>{});return;}
const rel=pathname==='atlas/current.json'?`atlas/manifests/${GEN}-composition.json`:pathname.endsWith('/')?pathname+'index.html':pathname;
try{const body=await fs.readFile(path.join(ROOT,rel));const ext=path.extname(rel);await route.fulfill({body,contentType:({'.html':'text/html','.json':'application/json','.js':'text/javascript','.mjs':'text/javascript','.css':'text/css'})[ext]||'application/octet-stream',headers:{'access-control-allow-origin':'*'}});}catch{await route.continue();}
});
const page=await context.newPage();const errors=[];
await page.goto('https://globalgrid2050.com/uk_renewables_pipeline/202611161244/',{waitUntil:'domcontentloaded'});
await page.locator('#search').fill(ref);const map=page.locator(`#repd-${ref} a.atlaslink`);await map.waitFor({timeout:60000});
const [receiver]=await Promise.all([context.waitForEvent('page'),map.click()]);receiver.on('pageerror',e=>errors.push(e.message));
await receiver.waitForLoadState('domcontentloaded');
await receiver.waitForFunction(()=>window.__GRIDATLAS_NEON_LINKS__?.arrival_engine?.terminal && window.__GRIDATLAS_NEON_LINKS__?.links_drawn>0,null,{timeout:120000});
const card=receiver.locator('.maplibregl-popup').first();
if((await card.getAttribute('class')).includes('gridatlas-min'))await receiver.locator('.gridatlas-card-bar .min').first().click();
await receiver.waitForTimeout(12000);
await receiver.locator('.neon-km').first().scrollIntoViewIfNeeded();
assert.ok(await receiver.locator('.neon-km').first().isVisible());
const r=await receiver.evaluate(()=>{const l=window.__GRIDATLAS_NEON_LINKS__,p=document.querySelector('.maplibregl-popup'),block=p?.querySelector('.gridatlas-neon-block')||p;return {generation:document.documentElement.dataset.gridatlasGeneration,url:location.href,compute:l.compute_receipt,neso:l.neso_lookup,identity:l.identity_verification,arrival:l.arrival_engine,selection:l.last_selection,link … [line shortened here: 560 characters; full line on GitHub]
r.width=width;r.ref=ref;r.errors=errors;r.browser=browserIdentity;r.receiver_mode=process.env.MAP_RECEIVER_PUBLIC?'public':'local-candidate-interception';
assert.equal(r.generation,GEN);assert.equal(new URL(r.url).searchParams.get('repd_ref'),ref);
assert.equal(r.identity.repd_ref,ref);assert.equal(r.arrival.answered,true);assert.ok(Number.isFinite(r.selection.nearest_km));assert.ok(r.selection.nearest_name);
assert.ok(!r.cardClass.includes('gridatlas-min'),'reader restore must persist');assert.match(r.cardText,/km/);assert.ok(r.rect.height>100);assert.deepEqual(errors,[]);
assert.equal(r.compute.status,'completed');assert.equal(r.compute.entity.id,ref);assert.equal(r.compute.entity.kind,'repd');assert.ok(r.compute.measurements.length>0);assert.match(r.cardText,/Ventus Grid Engine/);
if(process.env.NESO_TIMEOUT==='1'){assert.equal(r.neso.status,'failed');assert.equal(r.neso.reason,'TIMEOUT');assert.match(r.cardText,/Declared connection lookup unavailable/);}
assert.equal(r.technology.enabled,true);assert.deepEqual(r.failures,[]);
await receiver.screenshot({path:`work/map-${channel||'chromium'}-${width}-${ref}${process.env.NESO_TIMEOUT==='1'?'-timeout':''}.png`});
await receiver.locator('.gridatlas-compute-state').scrollIntoViewIfNeeded();
assert.ok(await receiver.locator('.gridatlas-compute-state').isVisible());
await receiver.evaluate(()=>new Promise(resolve=>requestAnimationFrame(()=>requestAnimationFrame(resolve))));
const stateBounds=await receiver.locator('.gridatlas-compute-state').boundingBox();
assert.ok(stateBounds.x>=0 && stateBounds.x+stateBounds.width<=width,'owner state must fit the viewport horizontally');
await receiver.screenshot({path:`work/engine-${channel||'chromium'}-${width}-${ref}${process.env.NESO_TIMEOUT==='1'?'-timeout':''}.png`});
receipts.push(r);console.log('PASS',width,ref,r.identity.status,r.selection.nearest_name,r.selection.nearest_km);
await context.close();
}
}finally{await fs.mkdir('work',{recursive:true});await fs.writeFile(process.env.NESO_TIMEOUT==='1'?'work/map-receiver-timeout.json':`work/map-receiver-${channel||'chromium'}-candidate.json`,JSON.stringify(receipts,null,2));await browser.close();}Menu Bar Attrib Clearance Browser
A JavaScript module in the proofs folder of GridAtlas that works with attrib hit (`attribHit`) and installed hit (`installedHit`).
rendergridatlas / tools/proofs/menu-bar-attrib-clearance.browser.mjs · lines 1–277 of 277 · Entry point · pattern fixtureHtml (shared by 2 files)
- What it does
- Defines fixtureHtml, attribHit, installedHit, check. Uses libraries node:assert/strict, node:path, node:url, playwright. Side effects: changes the web page (DOM).
- Why it exists in the grid workflow
- Domain stage upstream_foresight (repository name word 'gridatlas'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight.
- Inputs & outputs
- In: form fields (user input).
- Downstream impact
- It is itself an entry point (JavaScript module); no other file was found loading it.
- What it achieves
- It is built from the fixture HTML helper (`fixtureHtml`), the attrib hit helper (`attribHit`) and the installed hit helper (`installedHit`). Proof: the OpenStreetMap / CARTO / Open Charge Map credit (`.custom-map-attrib`, in the immutable shell) is never occluded by the v9.107 menu bar (`atlas/modules/202609031958-menu-bar.js`), at any width.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- gridatlas · tools/proofs · JavaScript module
- Uses
- node:assert/strict, node:path, node:url, playwright
- Used by
- none found
- Produces
- fixtureHtml, attribHit, installedHit, check
- Defines here
- fixtureHtml, attribHit, installedHit, check
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 tools/proofs/menu-bar-attrib-clearance.browser.mjs:1-277 · blob 614c6a7e656b75e7c8c641227c6e2e7b5a6168f4 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env node
/**
* Proof: the OpenStreetMap / CARTO / Open Charge Map credit
* (`.custom-map-attrib`, in the immutable shell) is never occluded by the
* v9.107 menu bar (`atlas/modules/202609031958-menu-bar.js`), at any width.
*
* Measured live by the architect on the composed Atlas:
*
* - at rest, desktop widths (1425, 2327 CSS px): `.custom-map-attrib`
* rect y=15, `document.elementFromPoint()` at its centre returned
* `NAV#gridatlas-menu-bar` / `#gridatlas-menu-bar-title-4` -- the ABOUT
* title, not the credit. `document.body.className === ""`.
* - a phone-class viewport (456x906): the same page read as clear, rect
* y~47, because a touch arrival calls `window.enterFullscreen()`
* (`atlas/parts/*-exact-repd-delegation.js` etc.), which sets
* `fs-active`, which the shell's own
* `body.fs-active .custom-map-attrib{top:44px}` rule answers. Desktop
* never calls `enterFullscreen()`, so that rule never fires there.
*
* So the credit's safety depended on a class a desktop visit never sets.
* The architect's rule is absolute: "the attributions MUST NEVER BE
* COVERED" -- at every width, not only the one a touch arrival happens to
* reach. The fix in the menu-bar module clears the credit whenever the bar
* is hosted (`.gridatlas-menu-hosted`, unconditional -- no width media
* query, no dependency on `fs-active`), by an offset MEASURED from the
* bar's own `getBoundingClientRect().height` (36px at rest, 34px under the
* module's own `@media(max-width:700px)` rule) and kept current by a
* ResizeObserver; the ONE fallback constant (44px, the value the shell
* already used for fs-active) is written once, for the instant before the
* bar has measured itself, not duplicated per breakpoint.
*
* This is an occlusion proof, not an existence proof: asserting that
* `.custom-map-attrib` exists, or is visible/opaque/z-indexed, would have
* passed on the broken page at every width tested here -- that is exactly
* how the defect shipped. The only assertion that would have caught it is
* the one every check below makes: `document.elementFromPoint()` at the
* credit's own centre must resolve INSIDE `.custom-map-attrib`.
*
* WIDTHS is deliberately the five the architect named: 393 and 456 (the two
* phone widths measured live), 768 (tablet / the module's own 700px
* breakpoint boundary), 1280 and 2327 (the two desktop widths measured
* live, where the defect actually reproduced). Each is checked with the
* body AT REST (className === "", no fs-active) -- the strict case, since
* that is what a desktop visit always is and what a touch arrival is for
* however long it takes enterFullscreen() to run.
*/
import assert from 'node:assert/strict';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { chromium } from 'playwright';
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..');
const menuPath = path.join(ROOT, 'atlas', 'modules', '202609031958-menu-bar.js');
// The immutable shell's own rules for the credit, copied verbatim from
// atlas/releases/202608300453-atlas-v9/ventusv8.css lines 27-30 -- not
// restated from memory, so a change to the shell CSS this proof does not
// know about shows up as a diff against this file, not a silent miss.
const SHELL_ATTRIB_CSS = `
.custom-map-attrib { position: absolute; top: 10px; left: 10px; background: rgba(5, 5, 5, 0.7); color: #888; font-family: 'Courier New', monospace; font-size: 9px; border-radius: 4px; padding: 4px 8px; z-index: 10; border: 1px solid #333; pointer-events: auto; max-width: calc(100% - 60px); line-height: 1.6; }
.custom-map-attrib a { color: #00ffff; text-decoration: none; }
.custom-map-attrib a:hover { text-decoration: underline; }
body.fs-active .custom-map-attrib { top: 44px; }
`;
const engineIds = Array.from({ length: 60 }, (_, index) =>
index === 37 ? 'dlr' : `engine-${index}`);
const engineControls = engineIds.map((id) => `
<label class="key-item"><input type="checkbox" data-layer-id="${id}">
<span data-base-label="${id}">${id}</span></label>`).join('');
const pipelineControls = ['same-tech', 'wider-fleet', 'all-pipeline'].map((id) => `
<label class="key-item"><input type="checkbox" data-pn-layer="${id}">
<span data-pn-label="${id}">${id}</span></label>`).join('');
function fixtureHtml(bodyClass) {
return `<!doctype html>
<html><head><meta name="viewport" content="width=device-width,initial-scale=1"><style>
html,body{margin:0;width:100%;height:100%;font:12px sans-serif;background:#071217}
.map-container{position:relative;width:100%;height:100%}
.map-controls{position:absolute;top:50px;left:4px}
.scada-wrapper{position:fixed;left:12px;top:580px;z-index:2;color:white}
.key-item{display:block;min-height:22px}
${SHELL_ATTRIB_CSS}
</style></head><body${bodyClass ? ` class="${bodyClass}"` : ''}>
<div id="dashboard" class="dashboard">
<div class="hud-header">GridAtlas</div>
<div id="map-container" class="map-container">
<div class="search-bar-wrapper"><input id="search-input"><div id="search-results"></div></div>
<div class="map-controls">
<button id="btn-export">Export</button><button id="btn-status">Status</button>
<button id="btn-radius">Radius</button><button id="btn-radius-area">Area</button>
<button id="btn-zonedraw">Zone</button><button id="btn-measure">Measure</button>
</div>
<button id="btn-fullscreen">Fullscreen</button>
<!-- the real shell element: immutable, restyled only from a cartridge -->
<div class="custom-map-attrib">Data © OpenStreetMap contributors | © CARTO | EV data © Open Charge Map</div>
</div>
<div class="scada-wrapper"><div class="scada-brand">Ventus</div>
<div id="scada-ui-container">
<div class="key-group"><div class="key-title">Engine layers</div>${engineControls}</div>
<div class="key-group"><div class="key-title">Pipeline News</div>${pipelineControls}</div>
</div>
</div>
<button id="gridatlas-dash-toggle">Layers</button>
<button id="btn-fullscreen-exit">Exit</button>
<div id="fs-curtain-tab">Layers</div>
</div>
</body></html>`;
}
async function attribHit(page) {
return page.locator('.custom-map-attrib').evaluate((node) => {
const rect = node.getBoundingClientRect();
const x = rect.left + rect.width / 2;
const y = rect.top + rect.height / 2;
const top = document.elementFromPoint(x, y);
return {
rect: { x: rect.x, y: rect.y, w: rect.width, h: rect.height },
insideAttrib: !!top && (top === node || node.contains(top)),
hitTag: top?.tagName || null,
hitId: top?.id || null,
hitClass: top?.className || '',
computedTop: getComputedStyle(node).top,
barHeight: document.getElementById('gridatlas-menu-bar')?.getBoundingClientRect().height ?? null,
clearanceVar: getComputedStyle(document.documentElement)
.getPropertyValue('--gridatlas-menu-bar-clear').trim(),
};
});
}
async function installedHit(page, { width, height, touch }) {
const context = await page.context().browser().newContext({
viewport: { width, height },
...(touch ? { isMobile: true, hasTouch: true } : {}),
});
const p = await context.newPage();
const pageErrors = [];
p.on('pageerror', (error) => pageErrors.push(String(error?.message || error)));
await p.setContent(fixtureHtml(''));
const before = await attribHit(p);
await p.addScriptTag({ path: menuPath });
await p.waitForFunction(() => window.__GRIDATLAS_MODULES__?.menuBar?.installed === true);
// The clearance is applied by a ResizeObserver callback, which the spec
// schedules for a later animation frame than script execution -- wait for
// that frame rather than for a fix-specific side effect (the CSS variable
// may legitimately never appear on unfixed code, and that must read as a
// clean FAIL below, not a hung wait).
await p.evaluate(() => new Promise((resolve) => requestAnimationFrame(() =>
requestAnimationFrame(resolve))));
const bodyClass = await p.evaluate(() => document.body.className);
const hit = await attribHit(p);
await context.close();
return { before, bodyClass, hit, pageErrors };
}
const failures = [];
function check(label, condition, detail) {
if (condition) {
console.log(` [PASS] ${label}`);
} else {
console.log(` [FAIL] ${label}${detail ? ' -- ' + detail : ''}`);
failures.push(label);
}
}
// The five widths the architect named: two phone widths measured live
// (393, 456), the module's own 700px breakpoint boundary (768), and the
// two desktop widths where the defect actually reproduced (1280, 2327).
const WIDTHS = [
{ width: 393, height: 852, touch: true },
{ width: 456, height: 906, touch: true },
{ width: 768, height: 1024, touch: false },
{ width: 1280, height: 800, touch: false },
{ width: 2327, height: 1200, touch: false },
];
const browser = await chromium.launch({ headless: true });
try {
const anchor = await browser.newContext();
const anchorPage = await anchor.newPage();
for (const spec of WIDTHS) {
const { before, bodyClass, hit, pageErrors } = await installedHit(anchorPage, spec);
check(`${spec.width}px: fixture reproduces the measured case before the bar installs `
+ '(no bar yet, so the credit is naturally clear)',
before.insideAttrib === true);
check(`${spec.width}px: reproduces the exact measured condition -- body.className `
+ 'is empty at rest (no fs-active)',
bodyClass === '', `got "${bodyClass}"`);
console.log(` ${spec.width}px: rect=${JSON.stringify(hit.rect)} `
+ `bar=${hit.barHeight}px clear-var=${hit.clearanceVar} top=${hit.computedTop}`);
check(`${spec.width}px, body AT REST (not fs-active): elementFromPoint at the `
+ 'credit\'s centre resolves INSIDE .custom-map-attrib, not the menu bar',
hit.insideAttrib === true,
`hit ${hit.hitTag}#${hit.hitId}.${hit.hitClass}`);
check(`${spec.width}px: the clearance was MEASURED from the bar's real rendered `
+ 'height, not a value duplicated per breakpoint',
hit.barHeight !== null
&& hit.clearanceVar === (Math.ceil(hit.barHeight) + 8) + 'px');
assert.deepEqual(pageErrors, [],
`${spec.width}px raised page errors: ${pageErrors.join(' | ')}`);
}
// -- body.fs-active set (a completed touch arrival). The rule carries
// !important specifically so it keeps winning over the shell's own
// body.fs-active .custom-map-attrib{top:44px} rather than the two
// fighting back to an accidental match. --
{
const context = await browser.newContext({ viewport: { width: 456, height: 906 },
isMobile: true, hasTouch: true });
const page = await context.newPage();
await page.setContent(fixtureHtml('fs-active'));
await page.addScriptTag({ path: menuPath });
await page.waitForFunction(() => window.__GRIDATLAS_MODULES__?.menuBar?.installed === true);
await page.evaluate(() => new Promise((resolve) => requestAnimationFrame(() =>
requestAnimationFrame(resolve))));
const hit = await attribHit(page);
console.log(` 456px fs-active: rect=${JSON.stringify(hit.rect)} `
+ `bar=${hit.barHeight}px clear-var=${hit.clearanceVar} top=${hit.computedTop}`);
check('456px, body.fs-active (a completed touch arrival): elementFromPoint at the '
+ 'credit\'s centre still resolves INSIDE .custom-map-attrib',
hit.insideAttrib === true,
`hit ${hit.hitTag}#${hit.hitId}.${hit.hitClass}`);
await context.close();
}
// -- Resize after install: the bar's own height is watched, not read
// once at boot. A tab opened at desktop width and then resized (or
// rotated) must not be left with a stale clearance computed for a bar
// height it no longer has. --
{
const context = await browser.newContext({ viewport: { width: 1280, height: 800 } });
const page = await context.newPage();
await page.setContent(fixtureHtml(''));
await page.addScriptTag({ path: menuPath });
await page.waitForFunction(() => window.__GRIDATLAS_MODULES__?.menuBar?.installed === true);
await page.evaluate(() => new Promise((resolve) => requestAnimationFrame(() =>
requestAnimationFrame(resolve))));
const wide = await attribHit(page);
await page.setViewportSize({ width: 393, height: 852 });
try {
await page.waitForFunction((expected) =>
getComputedStyle(document.documentElement)
.getPropertyValue('--gridatlas-menu-bar-clear').trim() !== expected,
wide.clearanceVar, { timeout: 5000 });
} catch { /* unfixed code never updates the variable; fall through to a clean FAIL below */ }
const narrow = await attribHit(page);
console.log(` resized 1280->393: clear-var ${wide.clearanceVar} -> ${narrow.clearanceVar}`);
check('a live resize (desktop to phone width) re-measures the bar and updates '
+ 'the clearance, rather than keeping the width it booted at',
narrow.clearanceVar !== wide.clearanceVar && Math.abs(narrow.barHeight - 34) < 1);
check('and the credit is still uncovered after the resize',
narrow.insideAttrib === true);
await context.close();
}
await anchor.close();
console.log(`\n${failures.length === 0 ? 'ALL' : (WIDTHS.length * 4 + 4 - failures.length)} checks passed`
+ ` (${failures.length} failure(s))`);
if (failures.length) {
console.error('\nFAILURES');
for (const failure of failures) console.error(' ' + failure);
process.exitCode = 1;
} else {
console.log('the credit clears the menu bar at 393, 456, 768, 1280 and 2327 CSS px, '
+ 'at rest, in fs-active, and after a live resize.');
}
} finally {
await browser.close();
}Menu Bar Dom Proof
A JavaScript module in the proofs folder of GridAtlas that works with selector parts (`selectorParts`) and fake element (`FakeElement`).
interactiongridatlas / tools/proofs/menu-bar-dom.proof.mjs · lines 1–372 of 514 · Not reached from any entry point (candidate for review) · pattern classes (shared by 3 files)
- What it does
- It draws its content. Defines 13 functions or classes, including classes, selectorParts, matches, FakeElement, visit. Uses libraries node:fs/promises, node:vm. Side effects: changes the web page (DOM); reads or writes files.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (repository name word 'gridatlas'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight.
- What it achieves
- It proves menu bar (`proveMenuBar`) and is built from the selector parts helper (`selectorParts`) and the fake element class (`FakeElement`). Defines `classes`, `selectorParts`, `matches` and 10 more. It responds to click and change events.
- Why it matters
- No other file in the estate was found to import it.
- Application
- gridatlas · tools/proofs · JavaScript module
- Uses
- node:fs/promises, node:vm
- Used by
- none found
- Produces
- proveMenuBar
- Defines here
- classes, selectorParts, matches, FakeElement, visit, FakeDocument, add, fixture, run, proveMenuBar, check, title, panel
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 tools/proofs/menu-bar-dom.proof.mjs:1-372 · blob ddf54aebb14c3a7b434cc174f09d9fa18dafe50b · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
import { readFile } from 'node:fs/promises';
import vm from 'node:vm';
function classes(node) {
return new Set(String(node.className || '').split(/\s+/).filter(Boolean));
}
function selectorParts(selector) {
return selector.split(',').map((part) => part.trim()).filter(Boolean);
}
function matches(node, selector) {
if (!node || !node.tagName) return false;
let part = selector.trim();
if (!part || /\s/.test(part.replace(/\[[^\]]*\]/g, ''))) return false;
const tag = part.match(/^[a-z][\w-]*/i);
if (tag && node.tagName !== tag[0].toUpperCase()) return false;
const id = part.match(/#([\w-]+)/);
if (id && node.id !== id[1]) return false;
for (const hit of part.matchAll(/\.([\w-]+)/g)) {
if (!classes(node).has(hit[1])) return false;
}
for (const hit of part.matchAll(/\[([\w-]+)(?:="([^"]*)")?\]/g)) {
const name = hit[1];
const actual = node.getAttribute(name);
if (actual === null) return false;
if (hit[2] !== undefined && actual !== hit[2]) return false;
}
return true;
}
class FakeElement {
constructor(tag, doc) {
this.tagName = String(tag).toUpperCase();
this.ownerDocument = doc;
this.id = '';
this.className = '';
this.children = [];
this.parentNode = null;
this.attrs = Object.create(null);
this.dataset = Object.create(null);
this.style = { cssText: '' };
this.textContent = '';
this.type = '';
this.name = '';
this.value = '';
this.checked = false;
this.disabled = false;
this.hidden = false;
this.listeners = Object.create(null);
this.classList = {
add: (...names) => {
const next = classes(this);
names.forEach((name) => next.add(name));
this.className = [...next].join(' ');
},
remove: (...names) => {
const next = classes(this);
names.forEach((name) => next.delete(name));
this.className = [...next].join(' ');
},
contains: (name) => classes(this).has(name),
toggle: (name) => {
const next = classes(this);
const added = !next.has(name);
if (added) next.add(name); else next.delete(name);
this.className = [...next].join(' ');
return added;
}
};
}
get firstChild() { return this.children[0] || null; }
appendChild(child) {
if (child.parentNode) {
const at = child.parentNode.children.indexOf(child);
if (at >= 0) child.parentNode.children.splice(at, 1);
}
this.children.push(child);
child.parentNode = this;
return child;
}
insertBefore(child, before) {
if (child.parentNode) {
const at = child.parentNode.children.indexOf(child);
if (at >= 0) child.parentNode.children.splice(at, 1);
}
const index = before ? this.children.indexOf(before) : -1;
this.children.splice(index < 0 ? this.children.length : index, 0, child);
child.parentNode = this;
return child;
}
setAttribute(name, value) {
const text = String(value);
this.attrs[name] = text;
if (name === 'id') this.id = text;
if (name === 'class') this.className = text;
if (name === 'type') this.type = text;
if (name === 'name') this.name = text;
if (name === 'value') this.value = text;
if (name.startsWith('data-')) {
const key = name.slice(5).replace(/-([a-z])/g, (_, letter) => letter.toUpperCase());
this.dataset[key] = text;
}
}
getAttribute(name) {
if (name === 'id') return this.id || null;
if (name === 'class') return this.className || null;
if (name === 'type') return this.type || this.attrs[name] || null;
if (name === 'name') return this.name || this.attrs[name] || null;
if (name === 'value') return this.value || this.attrs[name] || null;
return Object.hasOwn(this.attrs, name) ? this.attrs[name] : null;
}
hasAttribute(name) { return this.getAttribute(name) !== null; }
removeAttribute(name) {
delete this.attrs[name];
if (name === 'hidden') this.hidden = false;
}
addEventListener(type, fn) {
(this.listeners[type] ||= []).push(fn);
}
dispatch(type, supplied = {}) {
const event = {
type,
target: supplied.target || this,
currentTarget: this,
key: supplied.key,
stopped: false,
defaultPrevented: false,
stopPropagation() { this.stopped = true; },
preventDefault() { this.defaultPrevented = true; }
};
let node = this;
while (node) {
event.currentTarget = node;
for (const fn of node.listeners?.[type] || []) fn.call(node, event);
if (event.stopped) break;
node = node.parentNode;
}
if (!event.stopped) this.ownerDocument.dispatch(type, event);
return event;
}
click() {
if (this.disabled) return;
if (this.type === 'checkbox') this.checked = !this.checked;
if (this.type === 'radio') this.checked = true;
this.dispatch('click');
if (this.type === 'checkbox' || this.type === 'radio') this.dispatch('change');
}
focus() { this.ownerDocument.activeElement = this; }
contains(other) {
for (let node = other; node; node = node.parentNode) if (node === this) return true;
return false;
}
closest(selector) {
for (let node = this; node; node = node.parentNode) {
if (selectorParts(selector).some((part) => matches(node, part))) return node;
}
return null;
}
querySelectorAll(selector) {
const wanted = selectorParts(selector);
const found = [];
const visit = (node) => {
for (const child of node.children) {
if (wanted.some((part) => matches(child, part))) found.push(child);
visit(child);
}
};
visit(this);
return found;
}
querySelector(selector) { return this.querySelectorAll(selector)[0] || null; }
}
class FakeDocument {
constructor() {
this.listeners = Object.create(null);
this.readyState = 'complete';
this.activeElement = null;
this.documentElement = new FakeElement('html', this);
this.head = new FakeElement('head', this);
this.body = new FakeElement('body', this);
this.documentElement.appendChild(this.head);
this.documentElement.appendChild(this.body);
}
createElement(tag) { return new FakeElement(tag, this); }
addEventListener(type, fn) { (this.listeners[type] ||= []).push(fn); }
dispatch(type, event) {
for (const fn of this.listeners[type] || []) fn.call(this, event);
}
querySelectorAll(selector) { return this.documentElement.querySelectorAll(selector); }
querySelector(selector) { return this.querySelectorAll(selector)[0] || null; }
getElementById(id) { return this.querySelector('#' + id); }
}
function add(doc, parent, tag, attrs = {}, text = '') {
const node = doc.createElement(tag);
Object.entries(attrs).forEach(([name, value]) => {
if (name === 'className') node.className = value;
else if (name in node && !name.startsWith('data-')) node[name] = value;
else node.setAttribute(name, value);
});
node.textContent = text;
parent.appendChild(node);
return node;
}
function fixture({ engineCount = 60, pipelineCount = 3, duplicate = false } = {}) {
const doc = new FakeDocument();
const dashboard = add(doc, doc.body, 'div', { className: 'dashboard' });
const header = add(doc, dashboard, 'div', { className: 'hud-header' }, 'System time Ventus Live');
const map = add(doc, dashboard, 'div', { className: 'map-container' });
const result = add(doc, map, 'div', { id: 'radius-popup', className: 'radius-popup' });
const search = add(doc, map, 'div', { className: 'search-bar-wrapper' });
const searchInner = add(doc, search, 'div');
add(doc, searchInner, 'input', { id: 'search-input', type: 'text' });
add(doc, searchInner, 'div', { id: 'search-results', className: 'search-results' });
add(doc, search, 'button', { id: 'search-btn', type: 'button' }, 'GO');
const stack = add(doc, map, 'div', { className: 'map-controls' });
const actions = {};
for (const [id, label] of [
['btn-export', 'Export CSV'], ['btn-radius', 'Radius Search'],
['btn-radius-area', 'Radius Area'], ['btn-zonedraw', 'Poly Zone'],
['btn-status', 'Status Colours'], ['btn-measure', 'Measure']
]) {
actions[id] = add(doc, stack, 'button', { id, type: 'button', className: 'map-ctrl-btn' }, label);
actions[id].hits = 0;
actions[id].addEventListener('click', () => { actions[id].hits += 1; });
}
actions['btn-fullscreen'] = add(doc, map, 'button', { id: 'btn-fullscreen', type: 'button' }, 'Full screen');
actions['btn-fullscreen-exit'] = add(doc, doc.body, 'button', { id: 'btn-fullscreen-exit', type: 'button' }, 'Exit');
const curtain = add(doc, doc.body, 'div', { id: 'fs-curtain-tab' }, 'Layers');
curtain.hits = 0;
curtain.addEventListener('click', () => { curtain.hits += 1; });
const tray = add(doc, stack, 'div', { id: 'gridatlas-mobile-tray' });
for (const text of ['Tools', 'Grid', 'Subs', 'Scope', 'Clear']) {
const button = add(doc, tray, 'button', { type: 'button' }, text);
button.hits = 0;
button.addEventListener('click', () => { button.hits += 1; });
actions['tray-' + text.toLowerCase()] = button;
}
const scada = add(doc, dashboard, 'div', { className: 'scada-wrapper' });
const brand = add(doc, scada, 'div', { className: 'scada-brand' }, 'Ventus');
add(doc, scada, 'div', { className: 'status-legend' }, 'Operational');
const controls = add(doc, scada, 'div', { id: 'scada-ui-container' });
const originals = [];
const group = add(doc, controls, 'div', { className: 'key-group' });
add(doc, group, 'div', { className: 'key-title' }, 'Engine layers');
for (let index = 0; index < engineCount; index += 1) {
const label = add(doc, group, 'label', { className: 'key-item' });
const id = duplicate && index === engineCount - 1 ? 'engine-0' : 'engine-' + index;
const input = add(doc, label, 'input', { type: 'checkbox', 'data-layer-id': id });
input.hits = 0;
input.addEventListener('change', () => { input.hits += 1; });
add(doc, label, 'span', { 'data-base-label': 'Engine ' + index }, 'Engine ' + index + ' [WAIT]');
originals.push(input);
}
const pnGroup = add(doc, controls, 'div', { className: 'key-group' });
add(doc, pnGroup, 'div', { className: 'key-title' }, 'Pipeline News (REPD)');
for (let index = 0; index < pipelineCount; index += 1) {
const label = add(doc, pnGroup, 'label', { className: 'key-item' });
const input = add(doc, label, 'input', { type: 'checkbox', 'data-pn-layer': 'pn-' + index });
input.hits = 0;
input.addEventListener('change', () => { input.hits += 1; });
add(doc, label, 'span', { 'data-pn-label': 'pn-' + index }, 'Pipeline ' + index + ' [WAIT]');
originals.push(input);
}
const bmGroup = add(doc, controls, 'div', { className: 'key-group' });
add(doc, bmGroup, 'div', { className: 'key-title' }, 'Basemap');
for (const value of ['dark', 'sat']) {
const label = add(doc, bmGroup, 'label', { className: 'key-item' });
const input = add(doc, label, 'input', { type: 'radio', name: 'bm', value });
input.checked = value === 'dark';
add(doc, label, 'span', {}, value === 'dark' ? 'Dark' : 'Satellite');
}
add(doc, scada, 'div', { className: 'disclaimer-box' }, 'Public data only');
add(doc, map, 'div', { className: 'podcast-shoutout' }, 'The Future of Solar Photovoltaics');
const dash = add(doc, doc.body, 'button', { id: 'gridatlas-dash-toggle', type: 'button' }, 'Hide layers');
dash.addEventListener('click', () => {
if (scada.hasAttribute('data-gridatlas-collapsed')) scada.removeAttribute('data-gridatlas-collapsed');
else scada.setAttribute('data-gridatlas-collapsed', '1');
});
const gb = add(doc, stack, 'div', { id: 'gridatlas-gb-conditions' });
add(doc, gb, 'button', { type: 'button' }, 'GB prices');
const ledger = add(doc, stack, 'div', { id: 'gridatlas-version-ledger' });
add(doc, ledger, 'button', { type: 'button' }, 'Versions');
return { doc, map, result, stack, scada, brand, header, controls, originals, actions };
}
function run(source, options) {
const page = fixture(options);
const intervals = [];
const box = {
console,
document: page.doc,
Set,
Object,
Array,
String,
RegExp,
window: {
console,
setInterval: (fn) => { intervals.push(fn); return intervals.length; },
clearInterval: () => {},
setTimeout: (fn) => { fn(); return 1; }
}
};
box.window.window = box.window;
box.globalThis = box;
vm.createContext(box);
vm.runInContext(source, box, { filename: 'menu-bar.js' });
return { ...page, api: box.window.__GRIDATLAS_MODULES__?.menuBar, intervals };
}
export async function proveMenuBar(menuPath, servedSource = '') {
const source = await readFile(menuPath, 'utf8');
const failures = [];
let passed = 0;
const check = (name, condition) => {
if (condition) passed += 1;
else failures.push(name);
};
const complete = run(source);
const api = complete.api;
const bar = complete.doc.getElementById('gridatlas-menu-bar');
const styleText = complete.doc.getElementById('gridatlas-menu-bar-css')?.textContent || '';
const titleNodes = bar ? bar.querySelectorAll('.gm-title') : [];
const title = (name) => titleNodes.find((node) => node.textContent === name);
const panel = (name) => title(name)?.parentNode.querySelector('.gm-panel');
check('menu v2 registers and installs only on the complete UI',
api?.schema === 'gridatlas.menu-bar.v2' && api.installed === true);
check('served cartridge contains the same menu implementation',
!servedSource || servedSource.includes('gridatlas.menu-bar.v2'));
let partialIntervals = 0;
const partialBox = {
console,
document: {
readyState: 'complete',
addEventListener() {},
getElementById() { return null; },
querySelector() { return null; },
querySelectorAll() { return []; },
createElement() { return { style: {} }; },
body: {}
},
Set,
Object,
Array,
String,
RegExp,
window: {