/** * Headless-Chromium smoke for the shipped tablet bundle: serves a page that * loads dist/tablet.js (no compiler, the consumer's path) and drives it over * the DevTools protocol — Input.insertText and Input.dispatchKeyEvent are * trusted input, the same pipeline real keystrokes take, so the element's * beforeinput cancellation and its engine are exercised for real. Assertions * live here in the runner; the page only collects events. * * Run: `bun examples/tablet-smoke.ts`. Exits non-zero on failure. No test * runner, no npm driver: Bun's WebSocket speaks CDP to the playwright-pinned * Chromium directly (pattern: pebble's examples/invokers-smoke.ts). */ import { readdirSync, existsSync } from "node:fs"; import { spawn, spawnSync, type ChildProcess } from "node:child_process"; /** The newest playwright-cached Chromium (the bench/profile.ts pattern). */ function chrome(): string { const cache = `${process.env.HOME}/.cache/ms-playwright`; const newest = readdirSync(cache) .filter(dir => /^chromium-\d+$/.test(dir)) .sort() .pop(); if (newest === undefined) throw new Error(`no playwright chromium under ${cache}`); return `${cache}/${newest}/chrome-linux64/chrome`; } /** dist/tablet.js is the thing under test; build it if absent. */ function bundle(): string { const path = `${import.meta.dir}/../dist/tablet.js`; if (!existsSync(path)) { const built = spawnSync("bun", ["run", "build"], { cwd: `${import.meta.dir}/..` }); if (built.status !== 0) throw new Error(`build failed:\n${built.stderr.toString()}`); } return path; } /** The page under test: a form, a server-rendered textarea, event collectors. */ const PAGE = `
`; /** A minimal CDP client over Bun's WebSocket: one session, awaited ids. */ class Cdp { private ws: WebSocket; private next = 0; private pending = new Map void; reject: (e: unknown) => void }>(); private session = ""; private constructor(ws: WebSocket) { this.ws = ws; ws.onmessage = message => { const data = JSON.parse(String(message.data)); if (data.id !== undefined) { const entry = this.pending.get(data.id); if (entry) { this.pending.delete(data.id); data.error ? entry.reject(new Error(data.error.message)) : entry.resolve(data.result); } } }; } static async connect(process: ChildProcess): Promise { const endpoint = await new Promise((resolve, reject) => { let buffer = ""; process.stderr!.on("data", (chunk: Buffer) => { buffer += chunk.toString(); const match = buffer.match(/DevTools listening on (ws:\/\/\S+)/); if (match) resolve(match[1]); }); setTimeout(() => reject(new Error(`chromium never printed its DevTools endpoint: ${buffer}`)), 15000); }); const ws = new WebSocket(endpoint); await new Promise((resolve, reject) => { ws.onopen = () => resolve(); ws.onerror = event => reject(new Error(`CDP websocket failed: ${event}`)); }); return new Cdp(ws); } /** A command on the browser target (no session). */ send(method: string, params: Record = {}): Promise { const id = (this.next += 1); return new Promise((resolve, reject) => { this.pending.set(id, { resolve: resolve as (v: unknown) => void, reject }); this.ws.send(JSON.stringify({ id, method, params })); }); } /** A command on the page session. */ async call(method: string, params: Record = {}): Promise { const id = (this.next += 1); return new Promise((resolve, reject) => { this.pending.set(id, { resolve: resolve as (v: unknown) => void, reject }); this.ws.send(JSON.stringify({ id, method, params, sessionId: this.session })); }); } async attach(url: string): Promise { const { targetId } = await this.send<{ targetId: string }>("Target.createTarget", { url }); const { sessionId } = await this.send<{ sessionId: string }>("Target.attachToTarget", { targetId, flatten: true }); this.session = sessionId; await this.call("Runtime.enable"); } /** Evaluate an expression in the page; throws on page exceptions. */ async eval(expression: string): Promise { const result = await this.call<{ result: { value: T }; exceptionDetails?: { text: string } }>("Runtime.evaluate", { expression, returnByValue: true, awaitPromise: true, }); if (result.exceptionDetails) throw new Error(`page threw: ${result.exceptionDetails.text}`); return result.result.value; } close(): void { this.ws.close(); } } const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms)); /** CDP modifiers: Alt=1, Ctrl=2, Meta=4, Shift=8. */ const keyDown = (key: string, code: string, modifiers: number) => ({ type: "keyDown", key, code, modifiers, windowsVirtualKeyCode: key.toUpperCase().charCodeAt(0), }); const keyUp = (key: string, code: string, modifiers: number) => ({ type: "keyUp", key, code, modifiers, windowsVirtualKeyCode: key.toUpperCase().charCodeAt(0), }); const checks: Array<[string, boolean, string?]> = []; const check = (name: string, ok: boolean, extra?: string) => checks.push([name, ok, extra]); const server = Bun.serve({ port: 0, fetch(request) { const url = new URL(request.url); if (url.pathname === "/tablet.js") return new Response(Bun.file(bundle()), { headers: { "content-type": "text/javascript" } }); return new Response(PAGE, { headers: { "content-type": "text/html" } }); }, }); const chromium = spawn(chrome(), ["--headless=new", "--disable-gpu", "--no-sandbox", "--remote-debugging-port=0", "about:blank"], { stdio: ["ignore", "ignore", "pipe"], }); try { const cdp = await Cdp.connect(chromium); await cdp.attach(`http://localhost:${server.port}/`); // The attach races the navigation: poll until the document is complete and // the element defined, tolerating the execution context being replaced // underneath us. let ready = false; for (let attempt = 0; attempt < 50 && !ready; attempt += 1) { try { ready = (await cdp.eval(`document.readyState`)) === "complete" && (await cdp.eval(`customElements.whenDefined("pebble-tablet").then(() => true)`)) === true; } catch { await sleep(100); // Execution context was destroyed — the navigation was still going. } } if (!ready) throw new Error("the page never became ready"); await sleep(100); // the upgrade reaction and the element's listeners settle check("enhanced", await cdp.eval(`__tablet.el.getAttribute("data-enhanced") === ""`)); check("surface-is-the-textarea", await cdp.eval(`__tablet.field.hidden === false`)); // Real typing: Input.insertText takes the trusted text-input pipeline, // which fires a cancelable beforeinput on the focused field. await cdp.eval(`__tablet.field.focus(); __tablet.field.setSelectionRange(5, 5); undefined`); await cdp.call("Input.insertText", { text: " world" }); await sleep(50); check("typing", (await cdp.eval(`__tablet.value()`)) === "hello world", JSON.stringify(await cdp.eval(`__tablet.value()`))); check( "beforeinput-was-cancelable-and-canceled", await cdp.eval(`__tablet.prevented.length === 1 && __tablet.prevented[0][0] === "insertText" && __tablet.prevented[0][1] === true`), JSON.stringify(await cdp.eval(`__tablet.prevented`)), ); check("model-has-the-text", (await cdp.eval(`__tablet.doc()`)) === "hello world"); check("formdata-sends-what-was-typed", (await cdp.eval(`__tablet.formValue()`)) === "hello world"); await sleep(450); // past the 300 ms debounce check("change-debounced", await cdp.eval(`__tablet.changes.length === 1 && __tablet.changes[0] === "hello world"`), JSON.stringify(await cdp.eval(`__tablet.changes`))); // Undo is the engine's own: a trusted Mod+Z keydown, one chord, the run. await cdp.call("Input.dispatchKeyEvent", keyDown("z", "KeyZ", 2)); await cdp.call("Input.dispatchKeyEvent", keyUp("z", "KeyZ", 2)); await sleep(50); check("undo", (await cdp.eval(`__tablet.value()`)) === "hello", JSON.stringify(await cdp.eval(`__tablet.value()`))); await cdp.call("Input.dispatchKeyEvent", keyDown("z", "KeyZ", 10)); // Ctrl+Shift await cdp.call("Input.dispatchKeyEvent", keyUp("z", "KeyZ", 10)); await sleep(50); check("redo", (await cdp.eval(`__tablet.value()`)) === "hello world"); // Mod+S saves; the browser's own Save dialog is prevented. await cdp.call("Input.dispatchKeyEvent", keyDown("s", "KeyS", 2)); await cdp.call("Input.dispatchKeyEvent", keyUp("s", "KeyS", 2)); await sleep(50); check("save", await cdp.eval(`__tablet.saves.length === 1 && __tablet.saves[0] === "hello world"`), JSON.stringify(await cdp.eval(`__tablet.saves`))); // A programmatic write reconciles into the model and out as a change… await cdp.eval(`__tablet.field.value = "server morph"; __tablet.field.dispatchEvent(new Event("input", { bubbles: true })); undefined`); await sleep(450); check("programmatic-write", await cdp.eval(`__tablet.changes.at(-1) === "server morph"`), JSON.stringify(await cdp.eval(`__tablet.changes`))); // …and undo reaches past it into what was typed before. Native textarea // undo is dead by here (the value write cleared it); ours is not. await cdp.call("Input.dispatchKeyEvent", keyDown("z", "KeyZ", 2)); await cdp.call("Input.dispatchKeyEvent", keyUp("z", "KeyZ", 2)); await sleep(50); check("undo-past-write", (await cdp.eval(`__tablet.value()`)) === "hello world", JSON.stringify(await cdp.eval(`__tablet.value()`))); // --- Sizing: the field fits its text (field-sizing: content), from its // min-height; --tablet-sizing: fixed opts out. const fieldHeight = () => cdp.eval(`__tablet.field.getBoundingClientRect().height`); const short = await fieldHeight(); check("sizing-starts-at-min-height", Math.abs(short - (await cdp.eval(`parseFloat(getComputedStyle(__tablet.field).minHeight)`))) < 1, String(short)); await cdp.eval(`__tablet.field.value = Array.from({ length: 12 }, (_, i) => "line " + i).join("\\n"); __tablet.field.dispatchEvent(new Event("input", { bubbles: true })); undefined`); await sleep(50); const tall = await fieldHeight(); check("sizing-grows-with-the-text", tall > short * 2 && (await cdp.eval(`__tablet.field.scrollHeight <= __tablet.field.clientHeight + 1`)), `${short} -> ${tall}`); check("sizing-no-resize-handle", (await cdp.eval(`getComputedStyle(__tablet.field).resize`)) === "none"); await cdp.eval(`__tablet.el.style.setProperty("--tablet-sizing", "fixed"); undefined`); await sleep(50); check("sizing-fixed-opts-out", (await fieldHeight()) < tall && (await cdp.eval(`__tablet.field.scrollHeight > __tablet.field.clientHeight`))); await cdp.eval(`__tablet.el.style.removeProperty("--tablet-sizing"); undefined`); // --- A decorating dialect: the backdrop must land on the field's glyphs. check("decorated", await cdp.eval(`__decorated.el.hasAttribute("data-decorated") && __decorated.backdrop() !== null`)); // The caret is the field's own, painted in the text's colour: hiding the // glyphs must not hide it. check( "caret-visible", await cdp.eval(`(() => { const c = getComputedStyle(__decorated.field).caretColor; return c !== "transparent" && !/rgba\\(.*, 0\\)$/.test(c); })()`), JSON.stringify(await cdp.eval(`getComputedStyle(__decorated.field).caretColor`)), ); check( "backdrop-wraps-like-the-field", await cdp.eval(`__decorated.backdrop().scrollHeight === __decorated.field.scrollHeight && __decorated.backdrop().clientWidth === __decorated.field.clientWidth`), JSON.stringify(await cdp.eval(`[__decorated.backdrop().scrollHeight, __decorated.field.scrollHeight, __decorated.backdrop().clientWidth, __decorated.field.clientWidth]`)), ); // Pixels: the decorated view, against the field painting its own glyphs // with the backdrop hidden. Equal images mean every glyph landed in place. const shot = async () => { const rect = await cdp.eval<{ x: number; y: number; width: number; height: number }>( `(() => { const r = __decorated.el.getBoundingClientRect(); return { x: r.x, y: r.y, width: r.width, height: r.height }; })()`, ); const { data } = await cdp.call<{ data: string }>("Page.captureScreenshot", { format: "png", clip: { ...rect, scale: 1 } }); return data; }; // Task boxes are drawn on purpose where the field has "[ ]"; take them out // of this comparison, which is about glyph placement only. await cdp.eval(`document.activeElement.blur(); const plainBoxes = document.createElement("style"); plainBoxes.id = "plain-boxes"; plainBoxes.textContent = "[part~=box] { color: inherit !important; -webkit-text-fill-color: currentColor !important } [part~=box]::before, [part~=box]::after { display: none !important }"; document.head.append(plainBoxes); undefined`); const painted = await shot(); await cdp.eval(`__decorated.el.removeAttribute("data-decorated"); __decorated.backdrop().style.visibility = "hidden"; undefined`); const native = await shot(); await cdp.eval(`__decorated.el.setAttribute("data-decorated", ""); __decorated.backdrop().style.visibility = ""; undefined`); // Byte equality is too strict (a textarea and a div antialias differently); // count the pixels that differ by more than antialiasing does. A glyph off // by one pixel differs by far more (the shifted control below). const differing = (a: string, b: string) => cdp.eval(`(async () => { const load = src => new Promise(done => { const image = new Image(); image.onload = () => done(image); image.src = "data:image/png;base64," + src; }); const [a, b] = await Promise.all([load("${a}"), load("${b}")]); const read = image => { const canvas = new OffscreenCanvas(image.width, image.height); const context = canvas.getContext("2d"); context.drawImage(image, 0, 0); return context.getImageData(0, 0, image.width, image.height).data; }; const [pa, pb] = [read(a), read(b)]; let far = 0; for (let i = 0; i < pa.length; i += 4) { if (Math.max(Math.abs(pa[i] - pb[i]), Math.abs(pa[i + 1] - pb[i + 1]), Math.abs(pa[i + 2] - pb[i + 2])) > 96) far += 1; } return far / (pa.length / 4); })()`); await cdp.eval(`__decorated.backdrop().style.translate = "1px 0"; undefined`); const shifted = await shot(); await cdp.eval(`__decorated.backdrop().style.translate = ""; undefined`); const aligned = await differing(painted, native); const control = await differing(shifted, native); await cdp.eval(`document.getElementById("plain-boxes").remove(); undefined`); check("backdrop-pixels-match-the-field", aligned < 0.002 && control > 10 * aligned, `aligned ${aligned}, shifted 1px ${control}`); // Scrolling the field scrolls the backdrop with it. await cdp.eval(`__decorated.field.scrollTop = 9999; undefined`); await sleep(50); check("sizing-stops-at-max-height", await cdp.eval(`(() => { const f = __decorated.field; return Math.abs(f.getBoundingClientRect().height - parseFloat(getComputedStyle(f).maxHeight)) < 1 && f.scrollHeight > f.clientHeight; })()`)); check( "backdrop-follows-scroll", await cdp.eval(`__decorated.field.scrollTop > 0 && __decorated.backdrop().scrollTop === __decorated.field.scrollTop`), JSON.stringify(await cdp.eval(`[__decorated.field.scrollTop, __decorated.backdrop().scrollTop]`)), ); // A real click on the task box ticks the line, and the field keeps focus. // (focus() scrolls to the caret; put it at the top, then let the backdrop follow.) await cdp.eval(`__decorated.field.focus(); __decorated.field.setSelectionRange(0, 0); __decorated.field.scrollTop = 0; undefined`); await sleep(50); const center = await cdp.eval<{ x: number; y: number }>( `(() => { const r = __decorated.backdrop().querySelector("[part~=box]").getBoundingClientRect(); return { x: r.x + r.width / 2, y: r.y + r.height / 2 }; })()`, ); for (const type of ["mousePressed", "mouseReleased"]) { await cdp.call("Input.dispatchMouseEvent", { type, ...center, button: "left", clickCount: 1 }); } await sleep(50); check("box-click-ticks", await cdp.eval(`__decorated.field.value.split("\\n")[1] === "- [x] milk"`), JSON.stringify(await cdp.eval(`__decorated.field.value.split("\\n")[1]`))); check("box-click-keeps-focus", await cdp.eval(`document.activeElement === __decorated.field`)); // A real Enter in a textarea is insertLineBreak; the dialect's command runs. await cdp.eval(`__decorated.field.focus(); __decorated.field.setSelectionRange(20, 20); undefined`); await cdp.call("Input.dispatchKeyEvent", { type: "keyDown", key: "Enter", code: "Enter", windowsVirtualKeyCode: 13, text: "\r" }); await cdp.call("Input.dispatchKeyEvent", { type: "keyUp", key: "Enter", code: "Enter", windowsVirtualKeyCode: 13 }); await sleep(50); check("real-enter-runs-the-dialect", await cdp.eval(`__decorated.field.value.split("\\n")[2] === "- "`), JSON.stringify(await cdp.eval(`__decorated.field.value.split("\\n").slice(0, 3)`))); cdp.close(); } finally { chromium.kill(); server.stop(true); } let failed = 0; for (const [name, ok, extra] of checks) { console.log(`${ok ? "ok" : "FAIL"} ${name}${ok ? "" : ` ${extra ?? ""}`}`); if (!ok) failed += 1; } console.log(failed === 0 ? "tablet smoke: PASS" : `tablet smoke: FAIL (${failed})`); if (failed > 0) process.exit(1);