← Commit history

0.7.3: the ? button, controls card and one-time Shift+Alt tip

Colby Knox ·1e02855340 · ·parent b3bd2ac
5 files changed +227−5
README.md+14
@@ -132,6 +132,20 @@ near the underside and no beta limit. Presets (`front`, `back`, the view cube) still land upright. `npm run test:orbit` drives real pointer drags across both poles in the Y-up and Z-up frames. +### The ? button: controls card and the Shift+Alt tip++Every viewer draws a small `?` in its bottom-right corner (0.7.3). The card it+opens leads with the move that makes large boards and scaffolds navigable:+Shift+Alt+click a point on the model to set the centre of rotation (a glowing+dot marks it; orbit and zoom then work around that spot). The rest of the+controls follow: drag to orbit, right-drag or Ctrl+drag to pan, scroll to zoom+toward the cursor, the cube faces with Home and Fit, hold Space to spin. The+`?` key and Escape toggle the card. The first time a model is ready in a+browser, a tip bubble says the Shift+Alt line once and is then remembered+(ephemeral storage in sandboxed frames). `init(host, { showHelp: false })`+hides all of it for hosts that draw their own help; `viewer.showHelp()` and+`viewer.hideHelp()` drive the card. `npm run test:help` covers it.+ ### View cube: click on release, drag to orbit  A view-cube face navigates on mouse RELEASE (0.7.2, adom/adom-3d-viewer#4),
VERSION+1−1
@@ -1 +1 @@-0.7.2+0.7.3
package.json+4−3
@@ -1,6 +1,6 @@ {   "name": "adom-3d-viewer-babylon9",-  "version": "0.7.2",+  "version": "0.7.3",   "description": "The Babylon 9.5 engine behind every component page's 3D tab on wiki.adom.inc. Versioned ESM bundle with GLB loading, view cube, layers toolbar, ground shadows, and Z-up CAD framing.",   "type": "app",   "main": "./dist/index.js",@@ -25,8 +25,9 @@     "prepare": "npm run build",     "test:sandbox": "node test/wiki-sandbox.test.mjs",     "test:orbit": "node test/orbit.test.mjs",-    "test": "node test/wiki-sandbox.test.mjs && node test/orbit.test.mjs && node test/viewcube.test.mjs",-    "test:viewcube": "node test/viewcube.test.mjs"+    "test": "node test/wiki-sandbox.test.mjs && node test/orbit.test.mjs && node test/viewcube.test.mjs && node test/help.test.mjs",+    "test:viewcube": "node test/viewcube.test.mjs",+    "test:help": "node test/help.test.mjs"   },   "dependencies": {},   "devDependencies": {
standalone.ts+106−1
@@ -20,6 +20,7 @@ if (typeof (globalThis as any).process === 'undefined') { import ThreeDViewer from './src/ThreeDViewer.svelte'; import type { ViewerReadyReport } from './src/lib/adom-babylon/util/readiness'; export type { ViewerReadyReport, ViewerHint } from './src/lib/adom-babylon/util/readiness';+import { getPref, setPref } from './src/lib/adom-babylon/util/prefs';  // Side-effect: registers the debugLayer getter on Scene. import '@babylonjs/core/Debug/debugLayer';@@ -60,6 +61,9 @@ interface ViewerInstance {   setBottomLight: (on: boolean) => void;   getBottomLightState: () => boolean;   goHome: () => void;+  /** Open or close the controls card (the ? button); showHelp: false at init hides the button. */+  showHelp: () => void;+  hideHelp: () => void;   setProjectionMode: (ortho: boolean) => void;   getProjectionMode: () => 'perspective' | 'orthographic';   /** 3d-viewer-design §8 — toggle world-origin or mesh-local axes. The@@ -104,6 +108,9 @@ function init(container: HTMLElement, options?: {    *  The ground is sized from content bounds and so is recreated on reframe;    *  this is the reliable place to reapply a style. */   onGroundCreated?: (ground: any) => void;+  /** The ? button and its controls card (default true). Set false when the+   *  host draws its own help. The one-time Shift+Alt tip rides with it. */+  showHelp?: boolean; }): ViewerInstance {   const opts = options || {}; @@ -124,7 +131,12 @@ function init(container: HTMLElement, options?: {     },   }); +  const help = opts.showHelp === false ? null : mountHelp(container);+  if (help) component.whenReady().then(() => help.tipOnce()).catch(() => {});+   return {+    showHelp: () => { help && help.show(); },+    hideHelp: () => { help && help.hide(); },     loadModel: (url: string) => component.loadModel(url),     loadModelBytes: (bytes: ArrayBufferView, o?: { extension?: string }) => component.loadModelBytes(bytes, o),     whenReady: () => component.whenReady().then(withVersion),@@ -152,7 +164,100 @@ function init(container: HTMLElement, options?: {     captureScreenshot: (o?: { width?: number; height?: number }) => component.captureScreenshot(o),     getLayers: () => component.getLayers(),     setLayerVisible: (name: string, visible: boolean) => component.setLayerVisible(name, visible),-    destroy: () => component.$destroy(),+    destroy: () => { help && help.destroy(); component.$destroy(); },+  };+}++// ---- The ? button, the controls card, and the one-time Shift+Alt tip -------+//+// Colby, 2026-09-16: on a large board or scaffold, Shift+Alt+click to set the+// centre of rotation is the move that makes this viewer good, and nothing+// told a new reader it existed. Every consumer gets the same small ? in the+// bottom-right corner, a card listing the controls with that one first, and+// a tip bubble the first time a model is ready (remembered per browser,+// ephemeral storage in sandboxed frames so it never throws).++const HELP_TIP_PREF = 'a3d.help.tip.v1';+const HELP_STYLE_ID = 'a3d-help-style';+const HELP_CSS = `+.a3d-help-btn{position:absolute;right:12px;bottom:12px;z-index:12;width:28px;height:28px;border-radius:50%;border:1px solid rgba(240,246,252,.18);background:rgba(22,27,34,.85);color:#c9d1d9;font:600 14px/26px system-ui,sans-serif;text-align:center;cursor:pointer;padding:0;transition:color .15s,border-color .15s}+.a3d-help-btn:hover,.a3d-help-btn[aria-expanded="true"]{color:#e6edf3;border-color:#00b8b0}+.a3d-help-tip{position:absolute;right:48px;bottom:14px;z-index:12;max-width:min(360px,calc(100% - 70px));background:rgba(22,27,34,.96);border:1px solid rgba(0,184,177,.45);border-radius:10px;padding:9px 12px;color:#e6edf3;font:13px/1.4 system-ui,sans-serif;box-shadow:0 12px 40px rgba(0,0,0,.55)}+.a3d-help-tip b{color:#00e6dc;font-weight:600}+.a3d-help-tip button{margin-left:10px;background:none;border:0;color:#8b949e;cursor:pointer;font:inherit;padding:0}+.a3d-help-tip button:hover{color:#e6edf3}+.a3d-help-card{position:absolute;right:12px;bottom:48px;z-index:13;width:min(380px,calc(100% - 24px));max-height:calc(100% - 60px);overflow:auto;background:rgba(22,27,34,.96);backdrop-filter:blur(16px);border:1px solid rgba(0,184,177,.25);border-radius:10px;padding:14px 16px;color:#e6edf3;font:13px/1.45 system-ui,sans-serif;box-shadow:0 12px 40px rgba(0,0,0,.55)}+.a3d-help-card h3{margin:0 0 8px;font-size:14px;font-weight:600;color:#e6edf3}+.a3d-help-card .a3d-help-close{position:absolute;right:10px;top:8px;background:none;border:0;color:#8b949e;font-size:16px;cursor:pointer;line-height:1}+.a3d-help-card .a3d-help-close:hover{color:#e6edf3}+.a3d-help-card dl{margin:0;display:grid;grid-template-columns:auto 1fr;gap:6px 12px;align-items:baseline}+.a3d-help-card dt{margin:0;white-space:nowrap}+.a3d-help-card dd{margin:0;color:#c9d1d9}+.a3d-help-card kbd{display:inline-block;padding:1px 6px;border:1px solid rgba(240,246,252,.18);border-bottom-width:2px;border-radius:5px;background:rgba(240,246,252,.06);font:12px ui-monospace,monospace;color:#e6edf3}+.a3d-help-card .a3d-help-star{grid-column:1/-1;margin:2px 0 6px;padding:8px 10px;border-radius:8px;background:rgba(0,184,177,.10);border:1px solid rgba(0,184,177,.25)}+.a3d-help-card .a3d-help-star b{color:#00e6dc;font-weight:600}+.a3d-help-card p.a3d-help-foot{margin:10px 0 0;color:#8b949e;font-size:12px}+`;++function mountHelp(container: HTMLElement) {+  const doc = container.ownerDocument;+  if (!doc.getElementById(HELP_STYLE_ID)) {+    const st = doc.createElement('style'); st.id = HELP_STYLE_ID; st.textContent = HELP_CSS; doc.head.appendChild(st);+  }+  if (!container.style.position) container.style.position = 'relative';++  const btn = doc.createElement('button');+  btn.type = 'button'; btn.className = 'a3d-help-btn'; btn.textContent = '?';+  btn.setAttribute('aria-label', 'Viewer controls'); btn.setAttribute('aria-expanded', 'false'); btn.title = 'Viewer controls (?)';++  const card = doc.createElement('div');+  card.className = 'a3d-help-card'; card.setAttribute('role', 'dialog'); card.setAttribute('aria-label', 'Viewer controls'); card.hidden = true;+  card.innerHTML = `+    <button type="button" class="a3d-help-close" aria-label="Close">&times;</button>+    <h3>Getting around</h3>+    <dl>+      <div class="a3d-help-star"><b>Set the centre of rotation:</b> <kbd>Shift</kbd>+<kbd>Alt</kbd>+click a point on the model. On a big board or scaffold do this first: the orbit and the zoom then work around that spot instead of the middle of everything. A glowing dot marks it.</div>+      <dt>Orbit</dt><dd>drag</dd>+      <dt>Pan</dt><dd>right-drag, or <kbd>Ctrl</kbd>+drag</dd>+      <dt>Zoom</dt><dd>scroll, toward the cursor</dd>+      <dt>Face-on views</dt><dd>click a face of the cube; Home and Fit sit under it</dd>+      <dt>Spin</dt><dd>hold <kbd>Space</kbd></dd>+      <dt>This card</dt><dd><kbd>?</kbd></dd>+    </dl>+    <p class="a3d-help-foot">Tip: zooming into a corner moves the centre a little on its own; Shift+Alt+click puts it exactly where you want it.</p>`;++  const tip = doc.createElement('div');+  tip.className = 'a3d-help-tip'; tip.setAttribute('role', 'status'); tip.hidden = true;+  tip.innerHTML = `<b>Tip:</b> <kbd>Shift</kbd>+<kbd>Alt</kbd>+click a point to orbit around it.<button type="button" aria-label="Dismiss">Got it</button>`;++  container.appendChild(btn); container.appendChild(card); container.appendChild(tip);++  let tipTimer: ReturnType<typeof setTimeout> | null = null;+  const hideTip = () => { tip.hidden = true; if (tipTimer) { clearTimeout(tipTimer); tipTimer = null; } };+  const show = () => { hideTip(); card.hidden = false; btn.setAttribute('aria-expanded', 'true'); };+  const hide = () => { card.hidden = true; btn.setAttribute('aria-expanded', 'false'); };+  const toggle = () => { card.hidden ? show() : hide(); };+  const tipOnce = () => {+    if (getPref(HELP_TIP_PREF) === '1') return;+    setPref(HELP_TIP_PREF, '1');+    tip.hidden = false;+    tipTimer = setTimeout(hideTip, 12000);+  };++  btn.addEventListener('click', toggle);+  (card.querySelector('.a3d-help-close') as HTMLButtonElement).addEventListener('click', hide);+  (tip.querySelector('button') as HTMLButtonElement).addEventListener('click', hideTip);+  const onKey = (e: KeyboardEvent) => {+    const t = e.target as HTMLElement | null;+    if (t && (t.tagName === 'INPUT' || t.tagName === 'TEXTAREA' || t.isContentEditable)) return;+    if (e.key === '?') { toggle(); e.preventDefault(); }+    else if (e.key === 'Escape' && !card.hidden) { hide(); e.preventDefault(); }+  };+  doc.addEventListener('keydown', onKey);++  return {+    show, hide, tipOnce,+    destroy: () => { doc.removeEventListener('keydown', onKey); hideTip(); btn.remove(); card.remove(); tip.remove(); },   }; } 
test/help.test.mjsadded+102
@@ -0,0 +1,102 @@+// 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 centre 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, "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}#wrap{position:relative;width:640px;height:400px}</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, 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 centre 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("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); }