master
AdityaAngajala
v0.12.8
160fd3c
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
// Layers panel (adom/adom-3d-viewer#12), headless Chrome on the built bundle.
// A 13-part board whose parts name their pieces Adom.Chip.Substrate,
// Adom.Chip.Lens, ... as siblings, in a 250 px viewer and a full-height one:
// - the panel fits the viewer, its body scrolls, its header and close stay
// in view; Esc, the close button and the Layers tab each close it;
// - the Chip pieces are one expandable "Chip" row (its box switches them all,
// mixed when some are on), a family of one stays a plain row.
// Screenshots go to $SHOTS when set (the ralph pass looks at them).
import http from "node:http";
import { existsSync, readFileSync, readdirSync, mkdirSync } from "node:fs";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
const __dirname = dirname(fileURLToPath(import.meta.url));
const ROOT = resolve(__dirname, "..");
const DIST = join(ROOT, process.env.VIEWER_DIST || "dist-standalone");
const SHOTS = process.env.SHOTS || "";
let passed = 0, failed = 0; const failures = [];
function assert(cond, msg) { if (cond) { passed++; console.log(" ok " + msg); } else { failed++; failures.push(msg); console.log(" FAIL " + msg); } }
function section(t) { console.log("\n [" + t + "]"); }
/** One cube mesh, many named nodes. `tree` is [{ name, mesh?, children? }]. */
function makeGlb(tree) {
const pos = [], idx = [];
const faces = [[[-1,-1,1],[1,-1,1],[1,1,1],[-1,1,1]],[[1,-1,-1],[-1,-1,-1],[-1,1,-1],[1,1,-1]],[[-1,1,1],[1,1,1],[1,1,-1],[-1,1,-1]],[[-1,-1,-1],[1,-1,-1],[1,-1,1],[-1,-1,1]],[[1,-1,1],[1,-1,-1],[1,1,-1],[1,1,1]],[[-1,-1,-1],[-1,-1,1],[-1,1,1],[-1,1,-1]]];
faces.forEach((f, fi) => { f.forEach(v => pos.push(v[0] * 0.001, v[1] * 0.001, v[2] * 0.001)); const b = fi * 4; idx.push(b, b + 1, b + 2, b, b + 2, b + 3); });
const pad = (b) => Buffer.concat([b, Buffer.alloc((4 - (b.length % 4)) % 4)]);
const posBuf = pad(Buffer.from(new Float32Array(pos).buffer)), idxBuf = pad(Buffer.from(new Uint16Array(idx).buffer));
const nodes = [];
const add = (n, at) => {
const i = nodes.length; nodes.push({ name: n.name, translation: at || [0, 0, 0] });
if (n.mesh) nodes[i].mesh = 0;
if (n.children) nodes[i].children = n.children.map((c, k) => add(c, [k * 0.003, 0, 0]));
return i;
};
const roots = tree.map((n, k) => add(n, [0, k * 0.004, 0]));
const json = {
asset: { version: "2.0" }, scene: 0, scenes: [{ nodes: roots }], nodes,
meshes: [{ name: "cube", primitives: [{ attributes: { POSITION: 0 }, indices: 1, material: 0 }] }],
materials: [{ name: "m", pbrMetallicRoughness: { baseColorFactor: [0.7, 0.7, 0.7, 1] } }],
buffers: [{ byteLength: posBuf.length + idxBuf.length }],
bufferViews: [{ buffer: 0, byteOffset: 0, byteLength: posBuf.length }, { buffer: 0, byteOffset: posBuf.length, byteLength: idxBuf.length }],
accessors: [
{ bufferView: 0, componentType: 5126, count: pos.length / 3, type: "VEC3", min: [-0.001, -0.001, -0.001], max: [0.001, 0.001, 0.001] },
{ bufferView: 1, componentType: 5123, count: idx.length, type: "SCALAR" },
],
};
const bin = Buffer.concat([posBuf, idxBuf]);
let jsonBuf = Buffer.from(JSON.stringify(json)); jsonBuf = Buffer.concat([jsonBuf, Buffer.alloc((4 - (jsonBuf.length % 4)) % 4, 0x20)]);
const header = Buffer.alloc(12); header.write("glTF", 0); header.writeUInt32LE(2, 4); header.writeUInt32LE(12 + 8 + jsonBuf.length + 8 + bin.length, 8);
const ch = (len, type) => { const b = Buffer.alloc(8); b.writeUInt32LE(len, 0); b.write(type, 4); return b; };
return Buffer.concat([header, ch(jsonBuf.length, "JSON"), jsonBuf, ch(bin.length, "BIN\0"), bin]);
}
const PIECES = ["Substrate", "TerminalK", "TerminalA", "Lens", "Die"];
const parts = Array.from({ length: 13 }, (_, i) => ({ name: `D${i + 1}`, children: [
...PIECES.map(p => ({ name: `Adom.Chip.${p}`, mesh: true })),
{ name: "Adom.LaserEtch", mesh: true },
] }));
const BOARD = makeGlb([
{ name: "board", children: [{ name: "fr4_board", mesh: true }, { name: "pad_top", mesh: true }, { name: "silk_top", mesh: true }, ...parts] },
]);
const HARNESS = (h) => `<!doctype html><html><head><meta charset="utf-8"><style>html,body{margin:0;height:100%;background:#000}#wrap{position:absolute;left:0;top:0;width:640px;height:${h}px}</style></head><body><div id="wrap"></div>
<script type="module">
await import('/adom-3d-viewer-babylon9.esm.js');
const v = window.Adom3DViewerBabylon9.init(document.getElementById('wrap'), { zUp: true, showViewCube: false, showHelp: false });
await v.whenReady(); await v.loadModel('/board.glb'); window.__viewer = v; window.__ready = true;
</script></body></html>`;
if (!existsSync(join(DIST, "adom-3d-viewer-babylon9.esm.js"))) { console.error("dist-standalone missing; run npm run build:standalone first"); process.exit(2); }
let height = 250;
const server = http.createServer((req, res) => {
const url = new URL(req.url, "http://x");
if (url.pathname === "/board.glb") { res.writeHead(200, { "Content-Type": "model/gltf-binary" }); return res.end(BOARD); }
if (url.pathname === "/view.html") { res.writeHead(200, { "Content-Type": "text/html" }); return res.end(HARNESS(height)); }
const file = join(DIST, url.pathname.replace(/^\/+/, ""));
if (file.startsWith(DIST) && existsSync(file)) { res.writeHead(200, { "Content-Type": file.endsWith(".js") ? "text/javascript" : "application/octet-stream" }); return res.end(readFileSync(file)); }
res.writeHead(404); res.end();
});
await new Promise(r => server.listen(0, "127.0.0.1", r));
const port = server.address().port;
let puppeteer; try { puppeteer = (await import("puppeteer-core")).default; } catch { puppeteer = (await import(resolve(ROOT, "..", "node_modules", "puppeteer-core", "lib", "puppeteer", "puppeteer-core.js"))).default; }
function findChrome() {
const env = process.env.PUPPETEER_EXECUTABLE_PATH; if (env && existsSync(env)) return env;
const base = join(process.env.HOME || "", ".cache", "puppeteer", "chrome");
if (existsSync(base)) for (const d of readdirSync(base)) { const p = join(base, d, "chrome-linux64", "chrome"); if (existsSync(p)) return p; }
throw new Error("no Chrome found; set PUPPETEER_EXECUTABLE_PATH");
}
if (SHOTS) mkdirSync(SHOTS, { recursive: true });
const browser = await puppeteer.launch({ executablePath: findChrome(), headless: true, args: ["--no-sandbox", "--use-gl=angle", "--use-angle=swiftshader", "--enable-unsafe-swiftshader", "--disable-gpu-sandbox"] });
const rect = (page, sel) => page.evaluate((s) => { const e = document.querySelector(s); if (!e) return null; const r = e.getBoundingClientRect(); return { top: r.top, bottom: r.bottom, left: r.left, right: r.right, h: r.height }; }, sel);
try {
for (const h of [250, 560]) {
height = h;
const page = await browser.newPage();
await page.setViewport({ width: 640, height: h });
await page.goto(`http://127.0.0.1:${port}/view.html`, { waitUntil: "load", timeout: 90000 });
await page.waitForFunction("window.__ready === true", { timeout: 90000 });
section(`a ${h} px viewer: the open panel fits, its header and close stay in reach`);
await page.click(".layers-toggle");
await page.waitForSelector(".layers-panel");
const panel = await rect(page, ".layers-panel"), close = await rect(page, ".layers-close"), head = await rect(page, ".layers-head");
assert(panel && panel.top >= 0 && panel.bottom <= h, `panel inside the viewer (${panel && Math.round(panel.top)}..${panel && Math.round(panel.bottom)} of ${h})`);
assert(close && close.top >= 0 && close.bottom <= h, "the close button is on screen");
const scroll = await page.evaluate(() => { const b = document.querySelector(".layers-body"); const before = b.getBoundingClientRect().top; b.scrollTop = b.scrollHeight; return { sh: b.scrollHeight, ch: b.clientHeight, top: b.scrollTop }; });
const headAfter = await rect(page, ".layers-head");
assert(scroll.sh <= scroll.ch || scroll.top > 0, `the body scrolls when it is taller than the panel (${scroll.sh} > ${scroll.ch})`);
assert(head && headAfter && Math.abs(head.top - headAfter.top) < 1, "the header stays put while the body scrolls");
if (SHOTS) await page.screenshot({ path: join(SHOTS, `layers-${h}-open.png`) });
section("the Chip pieces are one expandable row; a family of one stays plain");
const rows = await page.evaluate(() => [...document.querySelectorAll(".layers-body .layers-row")].map(r => ({ text: r.textContent.trim().replace(/\s+/g, " "), family: r.classList.contains("layers-family"), member: r.classList.contains("layers-member") })));
const fam = rows.filter(r => r.family);
assert(fam.length === 1 && /^Chip \(5\)/.test(fam[0].text), `one family row "Chip (5)" (${JSON.stringify(fam.map(r => r.text))})`);
assert(rows.some(r => !r.family && /^Laser etch \(13\)/i.test(r.text)), "Laser etch, a family of one, is a plain row with its count");
assert(rows.filter(r => r.member).length === 0, "collapsed: no member rows yet");
const partsRows = rows.filter(r => /Chip|Laser/.test(r.text)).length;
assert(partsRows === 2, `13 parts x 6 pieces read as 2 rows (${partsRows})`);
await page.click(".layers-family .layers-expand");
const members = await page.evaluate(() => [...document.querySelectorAll(".layers-member")].map(r => r.textContent.trim().replace(/\s+/g, " ")));
assert(members.length === 5 && members.includes("Substrate (13)") && members.includes("Terminal K (13)"), `expanded: the five pieces, short labels (${members.join(", ")})`);
if (SHOTS) await page.screenshot({ path: join(SHOTS, `layers-${h}-expanded.png`) });
section("the family box switches every piece; one piece off makes it mixed");
await page.click(".layers-family input");
let st = await page.evaluate(() => ({ groups: window.__viewer.getStateGroups().filter(g => /Chip/.test(g.key)).map(g => g.enabled), box: document.querySelector(".layers-family input").checked }));
assert(st.groups.length === 5 && st.groups.every(e => e === false) && st.box === false, "unchecking the family turns all five off");
await page.click(".layers-member input");
st = await page.evaluate(() => { const b = document.querySelector(".layers-family input"); return { on: window.__viewer.getStateGroups().filter(g => /Chip/.test(g.key) && g.enabled).length, ind: b.indeterminate, box: b.checked }; });
assert(st.on === 1 && st.ind === true && st.box === false, `one piece back on: the family box is mixed (${JSON.stringify(st)})`);
await page.click(".layers-family input");
st = await page.evaluate(() => ({ on: window.__viewer.getStateGroups().filter(g => /Chip/.test(g.key) && g.enabled).length, ind: document.querySelector(".layers-family input").indeterminate }));
assert(st.on === 5 && st.ind === false, "clicking a mixed box turns them all on");
section("Esc, the close button and the Layers tab each close it");
await page.keyboard.press("Escape");
assert(!(await page.$(".layers-panel")), "Esc closes the panel");
await page.click(".layers-toggle"); await page.waitForSelector(".layers-panel");
await page.click(".layers-close");
assert(!(await page.$(".layers-panel")), "the close button closes it");
await page.click(".layers-toggle"); await page.waitForSelector(".layers-panel");
await page.click(".layers-toggle");
assert(!(await page.$(".layers-panel")), "the Layers tab closes it again");
await page.close();
}
} finally {
await browser.close();
server.close();
}
console.log(`\n=== layers ===\n${passed} passed, ${failed} failed`);
if (failures.length) for (const f of failures) console.log(" - " + f);
process.exit(failed ? 1 : 0);