master
AdityaAngajala v0.12.8 160fd3c
// The ? button, the controls card and the one-time Shift+Alt tip (Colby,
// 2026-09-16): every consumer gets a small ? in the corner; its card leads
// with Shift+Alt+click to set the center of rotation; the tip bubble shows
// once per browser when the first model is ready; showHelp:false hides it all.
import http from "node:http";
import { existsSync, readFileSync, readdirSync } 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");
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 + "]"); }
const sleep = (ms) => new Promise(r => setTimeout(r, ms));

function makeBoxGlb() {
  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.01, v[1]*0.01, v[2]*0.01)); const b = fi*4; idx.push(b, b+1, b+2, b, b+2, b+3); });
  const posBuf = Buffer.from(new Float32Array(pos).buffer), idxBuf = Buffer.from(new Uint16Array(idx).buffer);
  const bin = Buffer.concat([posBuf, idxBuf, Buffer.alloc((4 - (idxBuf.length % 4)) % 4)]);
  const json = { asset: { version: "2.0" }, scene: 0, scenes: [{ nodes: [0] }], nodes: [{ mesh: 0, name: "chip_body" }], meshes: [{ primitives: [{ attributes: { POSITION: 0 }, indices: 1, material: 0 }] }], materials: [{ pbrMetallicRoughness: { baseColorFactor: [0.9,0.55,0.1,1], metallicFactor: 0.2, roughnessFactor: 0.5 } }], buffers: [{ byteLength: bin.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.01,-0.01,-0.01], max: [0.01,0.01,0.01] }, { bufferView: 1, componentType: 5123, count: idx.length, type: "SCALAR" }] };
  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 GLB = makeBoxGlb();
const HARNESS = (showHelp) => `<!doctype html><html><head><meta charset="utf-8"><style>html,body{margin:0;height:100%;background:#000}#host{position:relative;width:640px;height:400px}#wrap{position:absolute;inset:0}</style></head><body><div id="host"><div id="wrap"></div></div>
<script type="module">
  await import('/adom-3d-viewer-babylon9.esm.js');
  const v = window.Adom3DViewerBabylon9.init(document.getElementById('wrap'), { zUp: true, showViewCube: false, showGround: false, modelUrl: '/chip.glb'${showHelp ? "" : ", showHelp: false"} });
  await v.whenReady(); 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); }
const server = http.createServer((req, res) => {
  const url = new URL(req.url, "http://x");
  if (url.pathname === "/help.html" || url.pathname === "/nohelp.html") { res.writeHead(200, { "Content-Type": "text/html" }); return res.end(HARNESS(url.pathname === "/help.html")); }
  if (url.pathname === "/chip.glb") { res.writeHead(200, { "Content-Type": "model/gltf-binary" }); return res.end(GLB); }
  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");
}
const browser = await puppeteer.launch({ executablePath: findChrome(), headless: true, args: ["--no-sandbox", "--use-gl=angle", "--use-angle=swiftshader", "--enable-unsafe-swiftshader", "--disable-gpu-sandbox"] });
try {
  const page = await browser.newPage();
  const errors = []; page.on("pageerror", e => errors.push(String(e && e.message || e)));
  await page.setViewport({ width: 640, height: 400 });
  await page.goto(`http://127.0.0.1:${port}/help.html`, { waitUntil: "load", timeout: 90000 });
  await page.waitForFunction(() => window.__ready === true, { timeout: 90000 });
  await sleep(300);

  section("first load: the ? button and the one-time tip");
  assert(await page.$(".a3d-help-btn") !== null, "the ? button is in the container");
  assert(await page.$eval(".a3d-help-tip", t => !t.hidden), "the tip bubble shows on the first ready model");
  assert(/Shift\s*\+\s*Alt\s*\+click a point to orbit around it/.test(await page.$eval(".a3d-help-tip", t => t.textContent.replace(/\s+/g, " "))), "the tip says what Shift+Alt+click does");
  await page.click(".a3d-help-tip button");
  assert(await page.$eval(".a3d-help-tip", t => t.hidden), "Got it dismisses the tip");

  section("the card: Shift+Alt first, the rest of the controls, ? and Escape");
  assert(await page.$eval(".a3d-help-card", c => c.hidden), "card starts closed");
  await page.click(".a3d-help-btn");
  assert(await page.$eval(".a3d-help-card", c => !c.hidden), "clicking ? opens the card");
  const text = await page.$eval(".a3d-help-card", c => c.textContent.replace(/\s+/g, " "));
  assert(/Set the center of rotation:\s*Shift\+Alt\+click/.test(text), "the card leads with Shift+Alt+click");
  assert(/Orbit\s*drag/.test(text) && /Pan\s*right-drag/.test(text) && /Zoom\s*scroll/.test(text) && /hold Space/.test(text), "orbit, pan, zoom and spin are listed");
  assert(await page.$eval(".a3d-help-btn", b => b.getAttribute("aria-expanded")) === "true", "button reports expanded");
  await page.keyboard.press("Escape");
  assert(await page.$eval(".a3d-help-card", c => c.hidden), "Escape closes it");
  await page.keyboard.type("?");
  assert(await page.$eval(".a3d-help-card", c => !c.hidden), "the ? key opens it");
  await page.evaluate(() => window.__viewer.hideHelp());
  assert(await page.$eval(".a3d-help-card", c => c.hidden), "hideHelp() closes it");
  await page.evaluate(() => window.__viewer.showHelp());
  assert(await page.$eval(".a3d-help-card", c => !c.hidden), "showHelp() opens it");

  section("the host's own positioning survives, and the canvas refills after a hide/show");
  assert(await page.$eval("#wrap", w => getComputedStyle(w).position) === "absolute", "an absolute host container stays absolute (was forced to relative)");
  assert(await page.$eval("#wrap", w => w.style.position) === "", "no inline position written onto a positioned host");
  await page.evaluate(() => { document.getElementById("host").style.display = "none"; window.dispatchEvent(new Event("resize")); });
  await sleep(300);
  await page.evaluate(() => { document.getElementById("host").style.display = ""; window.dispatchEvent(new Event("resize")); });
  await sleep(600);
  const h = await page.$eval("canvas", c => Math.round(c.getBoundingClientRect().height));
  assert(h >= 390, `the canvas is back to the host's height after hide/show (${h}px, not the 150px default)`);

  section("second load in the same browser: no tip again");
  await page.goto(`http://127.0.0.1:${port}/help.html`, { waitUntil: "load", timeout: 90000 });
  await page.waitForFunction(() => window.__ready === true, { timeout: 90000 });
  await sleep(300);
  assert(await page.$eval(".a3d-help-tip", t => t.hidden), "the tip is remembered as seen");

  section("showHelp: false");
  await page.goto(`http://127.0.0.1:${port}/nohelp.html`, { waitUntil: "load", timeout: 90000 });
  await page.waitForFunction(() => window.__ready === true, { timeout: 90000 });
  assert(await page.$(".a3d-help-btn") === null && await page.$(".a3d-help-tip") === null, "no button and no tip when the host opts out");
  assert(errors.length === 0, `no page errors (${errors.join("; ").slice(0, 200)})`);
  await page.close();
} finally { await browser.close(); server.close(); }
console.log(`\nhelp: ${passed} passed, ${failed} failed`);
if (failed) { for (const f of failures) console.log("  - " + f); process.exit(1); }