tobogganSe connecter

library

Prebuilt pebble components: drop-in custom elements, no compiler needed

Clone avec HTTPS, un jeton personnel en mot de passe, ou avec SSH, une clé ajoutée dans vos paramètres.

Dernier runAucun
0Étoiles
0Forks
2Issues
390 lignes · 20388 octetsBrut · Historique
1/**
2 * Headless-Chromium smoke for the shipped tablet bundle: serves a page that
3 * loads dist/tablet.js (no compiler, the consumer's path) and drives it over
4 * the DevTools protocol — Input.insertText and Input.dispatchKeyEvent are
5 * trusted input, the same pipeline real keystrokes take, so the element's
6 * beforeinput cancellation and its engine are exercised for real. Assertions
7 * live here in the runner; the page only collects events.
8 *
9 * Run: `bun examples/tablet-smoke.ts`. Exits non-zero on failure. No test
10 * runner, no npm driver: Bun's WebSocket speaks CDP to the playwright-pinned
11 * Chromium directly (pattern: pebble's examples/invokers-smoke.ts).
12 */
13import { readdirSync, existsSync } from "node:fs";
14import { spawn, spawnSync, type ChildProcess } from "node:child_process";
15
16/** The newest playwright-cached Chromium (the bench/profile.ts pattern). */
17function chrome(): string {
18 const cache = `${process.env.HOME}/.cache/ms-playwright`;
19 const newest = readdirSync(cache)
20 .filter(dir => /^chromium-\d+$/.test(dir))
21 .sort()
22 .pop();
23 if (newest === undefined) throw new Error(`no playwright chromium under ${cache}`);
24 return `${cache}/${newest}/chrome-linux64/chrome`;
25}
26
27/** dist/tablet.js is the thing under test; build it if absent. */
28function bundle(): string {
29 const path = `${import.meta.dir}/../dist/tablet.js`;
30 if (!existsSync(path)) {
31 const built = spawnSync("bun", ["run", "build"], { cwd: `${import.meta.dir}/..` });
32 if (built.status !== 0) throw new Error(`build failed:\n${built.stderr.toString()}`);
33 }
34 return path;
35}
36
37/** The page under test: a form, a server-rendered textarea, event collectors. */
38const PAGE = `<!doctype html>
39<html><body>
40<form><pebble-tablet><textarea name="body">hello</textarea></pebble-tablet></form>
41<pebble-tablet dialect="smoke" style="--tablet-font: monospace; font-size: 16px; width: 320px; --tablet-max-height: 7lh"><textarea name="decorated"></textarea></pebble-tablet>
42<script type="module">
43import { defineDialect } from "/tablet.js";
44// A dialect that decorates without restyling (classes only, no sheet), so the
45// backdrop must paint exactly the field's own glyphs, and draws task boxes.
46defineDialect("smoke", {
47 commands: {
48 insertLineBreak: state => {
49 const at = state.selection.head;
50 const start = state.doc.lastIndexOf("\\n", at - 1) + 1;
51 if (!state.doc.startsWith("- ", start)) return null;
52 return { change: { from: at, to: at, insert: "\\n- " }, selection: { anchor: at + 3, head: at + 3 }, group: "other" };
53 },
54 },
55 decorate: line => line.startsWith("- [ ] ") || line.startsWith("- [x] ")
56 ? { kind: "task", segments: [{ text: "- ", classes: ["mark"] }, { text: line.slice(2, 5), classes: ["mark"], box: { checked: line[3] === "x" } }, { text: line.slice(5), classes: [] }] }
57 : { kind: "plain", segments: [{ text: line, classes: ["word"] }] },
58 tick: (state, line) => {
59 const start = state.doc.split("\\n").slice(0, line).join("\\n").length + (line > 0 ? 1 : 0);
60 const mark = state.doc[start + 3];
61 return { change: { from: start + 3, to: start + 4, insert: mark === "x" ? " " : "x" }, selection: state.selection, group: "other" };
62 },
63});
64const decorated = document.querySelector("pebble-tablet[dialect]");
65decorated.querySelector("textarea").value = [
66 "# a title",
67 "- [ ] milk",
68 "a long line that has to wrap more than once inside three hundred and twenty pixels of monospace text",
69 "tabs\\tand double spaces, unicode café ✓ and an emoji 🙂 at the end",
70 ...Array.from({ length: 12 }, (_, i) => "line " + i),
71].join("\\n");
72decorated.querySelector("textarea").dispatchEvent(new Event("input", { bubbles: true }));
73window.__decorated = {
74 el: decorated,
75 field: decorated.querySelector("textarea"),
76 backdrop: () => decorated.querySelector("[part~=backdrop]"),
77};
78const el = document.querySelector("pebble-tablet");
79const field = el.querySelector("textarea");
80const prevented = [];
81field.addEventListener("beforeinput", event => prevented.push([event.inputType, event.defaultPrevented]));
82window.__tablet = {
83 el,
84 field,
85 changes: [],
86 saves: [],
87 prevented,
88 value: () => field.value,
89 doc: () => el.editor && el.editor.doc,
90 formValue: () => new FormData(el.closest("form")).get("body"),
91};
92el.addEventListener("change", event => window.__tablet.changes.push(event.detail.value));
93el.addEventListener("save", event => window.__tablet.saves.push(event.detail.value));
94</script>
95</body></html>`;
96
97/** A minimal CDP client over Bun's WebSocket: one session, awaited ids. */
98class Cdp {
99 private ws: WebSocket;
100 private next = 0;
101 private pending = new Map<number, { resolve: (v: unknown) => void; reject: (e: unknown) => void }>();
102 private session = "";
103
104 private constructor(ws: WebSocket) {
105 this.ws = ws;
106 ws.onmessage = message => {
107 const data = JSON.parse(String(message.data));
108 if (data.id !== undefined) {
109 const entry = this.pending.get(data.id);
110 if (entry) {
111 this.pending.delete(data.id);
112 data.error ? entry.reject(new Error(data.error.message)) : entry.resolve(data.result);
113 }
114 }
115 };
116 }
117
118 static async connect(process: ChildProcess): Promise<Cdp> {
119 const endpoint = await new Promise<string>((resolve, reject) => {
120 let buffer = "";
121 process.stderr!.on("data", (chunk: Buffer) => {
122 buffer += chunk.toString();
123 const match = buffer.match(/DevTools listening on (ws:\/\/\S+)/);
124 if (match) resolve(match[1]);
125 });
126 setTimeout(() => reject(new Error(`chromium never printed its DevTools endpoint: ${buffer}`)), 15000);
127 });
128 const ws = new WebSocket(endpoint);
129 await new Promise<void>((resolve, reject) => {
130 ws.onopen = () => resolve();
131 ws.onerror = event => reject(new Error(`CDP websocket failed: ${event}`));
132 });
133 return new Cdp(ws);
134 }
135
136 /** A command on the browser target (no session). */
137 send<T = unknown>(method: string, params: Record<string, unknown> = {}): Promise<T> {
138 const id = (this.next += 1);
139 return new Promise<T>((resolve, reject) => {
140 this.pending.set(id, { resolve: resolve as (v: unknown) => void, reject });
141 this.ws.send(JSON.stringify({ id, method, params }));
142 });
143 }
144
145 /** A command on the page session. */
146 async call<T = unknown>(method: string, params: Record<string, unknown> = {}): Promise<T> {
147 const id = (this.next += 1);
148 return new Promise<T>((resolve, reject) => {
149 this.pending.set(id, { resolve: resolve as (v: unknown) => void, reject });
150 this.ws.send(JSON.stringify({ id, method, params, sessionId: this.session }));
151 });
152 }
153
154 async attach(url: string): Promise<void> {
155 const { targetId } = await this.send<{ targetId: string }>("Target.createTarget", { url });
156 const { sessionId } = await this.send<{ sessionId: string }>("Target.attachToTarget", { targetId, flatten: true });
157 this.session = sessionId;
158 await this.call("Runtime.enable");
159 }
160
161 /** Evaluate an expression in the page; throws on page exceptions. */
162 async eval<T = unknown>(expression: string): Promise<T> {
163 const result = await this.call<{ result: { value: T }; exceptionDetails?: { text: string } }>("Runtime.evaluate", {
164 expression,
165 returnByValue: true,
166 awaitPromise: true,
167 });
168 if (result.exceptionDetails) throw new Error(`page threw: ${result.exceptionDetails.text}`);
169 return result.result.value;
170 }
171
172 close(): void {
173 this.ws.close();
174 }
175}
176
177const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));
178
179/** CDP modifiers: Alt=1, Ctrl=2, Meta=4, Shift=8. */
180const keyDown = (key: string, code: string, modifiers: number) => ({
181 type: "keyDown",
182 key,
183 code,
184 modifiers,
185 windowsVirtualKeyCode: key.toUpperCase().charCodeAt(0),
186});
187const keyUp = (key: string, code: string, modifiers: number) => ({
188 type: "keyUp",
189 key,
190 code,
191 modifiers,
192 windowsVirtualKeyCode: key.toUpperCase().charCodeAt(0),
193});
194
195const checks: Array<[string, boolean, string?]> = [];
196const check = (name: string, ok: boolean, extra?: string) => checks.push([name, ok, extra]);
197
198const server = Bun.serve({
199 port: 0,
200 fetch(request) {
201 const url = new URL(request.url);
202 if (url.pathname === "/tablet.js") return new Response(Bun.file(bundle()), { headers: { "content-type": "text/javascript" } });
203 return new Response(PAGE, { headers: { "content-type": "text/html" } });
204 },
205});
206
207const chromium = spawn(chrome(), ["--headless=new", "--disable-gpu", "--no-sandbox", "--remote-debugging-port=0", "about:blank"], {
208 stdio: ["ignore", "ignore", "pipe"],
209});
210
211try {
212 const cdp = await Cdp.connect(chromium);
213 await cdp.attach(`http://localhost:${server.port}/`);
214 // The attach races the navigation: poll until the document is complete and
215 // the element defined, tolerating the execution context being replaced
216 // underneath us.
217 let ready = false;
218 for (let attempt = 0; attempt < 50 && !ready; attempt += 1) {
219 try {
220 ready =
221 (await cdp.eval(`document.readyState`)) === "complete" &&
222 (await cdp.eval(`customElements.whenDefined("pebble-tablet").then(() => true)`)) === true;
223 } catch {
224 await sleep(100); // Execution context was destroyed — the navigation was still going.
225 }
226 }
227 if (!ready) throw new Error("the page never became ready");
228 await sleep(100); // the upgrade reaction and the element's listeners settle
229
230 check("enhanced", await cdp.eval(`__tablet.el.getAttribute("data-enhanced") === ""`));
231 check("surface-is-the-textarea", await cdp.eval(`__tablet.field.hidden === false`));
232
233 // Real typing: Input.insertText takes the trusted text-input pipeline,
234 // which fires a cancelable beforeinput on the focused field.
235 await cdp.eval(`__tablet.field.focus(); __tablet.field.setSelectionRange(5, 5); undefined`);
236 await cdp.call("Input.insertText", { text: " world" });
237 await sleep(50);
238 check("typing", (await cdp.eval(`__tablet.value()`)) === "hello world", JSON.stringify(await cdp.eval(`__tablet.value()`)));
239 check(
240 "beforeinput-was-cancelable-and-canceled",
241 await cdp.eval(`__tablet.prevented.length === 1 && __tablet.prevented[0][0] === "insertText" && __tablet.prevented[0][1] === true`),
242 JSON.stringify(await cdp.eval(`__tablet.prevented`)),
243 );
244 check("model-has-the-text", (await cdp.eval(`__tablet.doc()`)) === "hello world");
245 check("formdata-sends-what-was-typed", (await cdp.eval(`__tablet.formValue()`)) === "hello world");
246
247 await sleep(450); // past the 300 ms debounce
248 check("change-debounced", await cdp.eval(`__tablet.changes.length === 1 && __tablet.changes[0] === "hello world"`), JSON.stringify(await cdp.eval(`__tablet.changes`)));
249
250 // Undo is the engine's own: a trusted Mod+Z keydown, one chord, the run.
251 await cdp.call("Input.dispatchKeyEvent", keyDown("z", "KeyZ", 2));
252 await cdp.call("Input.dispatchKeyEvent", keyUp("z", "KeyZ", 2));
253 await sleep(50);
254 check("undo", (await cdp.eval(`__tablet.value()`)) === "hello", JSON.stringify(await cdp.eval(`__tablet.value()`)));
255 await cdp.call("Input.dispatchKeyEvent", keyDown("z", "KeyZ", 10)); // Ctrl+Shift
256 await cdp.call("Input.dispatchKeyEvent", keyUp("z", "KeyZ", 10));
257 await sleep(50);
258 check("redo", (await cdp.eval(`__tablet.value()`)) === "hello world");
259
260 // Mod+S saves; the browser's own Save dialog is prevented.
261 await cdp.call("Input.dispatchKeyEvent", keyDown("s", "KeyS", 2));
262 await cdp.call("Input.dispatchKeyEvent", keyUp("s", "KeyS", 2));
263 await sleep(50);
264 check("save", await cdp.eval(`__tablet.saves.length === 1 && __tablet.saves[0] === "hello world"`), JSON.stringify(await cdp.eval(`__tablet.saves`)));
265
266 // A programmatic write reconciles into the model and out as a change…
267 await cdp.eval(`__tablet.field.value = "server morph"; __tablet.field.dispatchEvent(new Event("input", { bubbles: true })); undefined`);
268 await sleep(450);
269 check("programmatic-write", await cdp.eval(`__tablet.changes.at(-1) === "server morph"`), JSON.stringify(await cdp.eval(`__tablet.changes`)));
270
271 // …and undo reaches past it into what was typed before. Native textarea
272 // undo is dead by here (the value write cleared it); ours is not.
273 await cdp.call("Input.dispatchKeyEvent", keyDown("z", "KeyZ", 2));
274 await cdp.call("Input.dispatchKeyEvent", keyUp("z", "KeyZ", 2));
275 await sleep(50);
276 check("undo-past-write", (await cdp.eval(`__tablet.value()`)) === "hello world", JSON.stringify(await cdp.eval(`__tablet.value()`)));
277
278 // --- Sizing: the field fits its text (field-sizing: content), from its
279 // min-height; --tablet-sizing: fixed opts out.
280 const fieldHeight = () => cdp.eval<number>(`__tablet.field.getBoundingClientRect().height`);
281 const short = await fieldHeight();
282 check("sizing-starts-at-min-height", Math.abs(short - (await cdp.eval<number>(`parseFloat(getComputedStyle(__tablet.field).minHeight)`))) < 1, String(short));
283 await cdp.eval(`__tablet.field.value = Array.from({ length: 12 }, (_, i) => "line " + i).join("\\n"); __tablet.field.dispatchEvent(new Event("input", { bubbles: true })); undefined`);
284 await sleep(50);
285 const tall = await fieldHeight();
286 check("sizing-grows-with-the-text", tall > short * 2 && (await cdp.eval(`__tablet.field.scrollHeight <= __tablet.field.clientHeight + 1`)), `${short} -> ${tall}`);
287 check("sizing-no-resize-handle", (await cdp.eval(`getComputedStyle(__tablet.field).resize`)) === "none");
288 await cdp.eval(`__tablet.el.style.setProperty("--tablet-sizing", "fixed"); undefined`);
289 await sleep(50);
290 check("sizing-fixed-opts-out", (await fieldHeight()) < tall && (await cdp.eval(`__tablet.field.scrollHeight > __tablet.field.clientHeight`)));
291 await cdp.eval(`__tablet.el.style.removeProperty("--tablet-sizing"); undefined`);
292
293 // --- A decorating dialect: the backdrop must land on the field's glyphs.
294 check("decorated", await cdp.eval(`__decorated.el.hasAttribute("data-decorated") && __decorated.backdrop() !== null`));
295 // The caret is the field's own, painted in the text's colour: hiding the
296 // glyphs must not hide it.
297 check(
298 "caret-visible",
299 await cdp.eval(`(() => { const c = getComputedStyle(__decorated.field).caretColor; return c !== "transparent" && !/rgba\\(.*, 0\\)$/.test(c); })()`),
300 JSON.stringify(await cdp.eval(`getComputedStyle(__decorated.field).caretColor`)),
301 );
302 check(
303 "backdrop-wraps-like-the-field",
304 await cdp.eval(`__decorated.backdrop().scrollHeight === __decorated.field.scrollHeight && __decorated.backdrop().clientWidth === __decorated.field.clientWidth`),
305 JSON.stringify(await cdp.eval(`[__decorated.backdrop().scrollHeight, __decorated.field.scrollHeight, __decorated.backdrop().clientWidth, __decorated.field.clientWidth]`)),
306 );
307
308 // Pixels: the decorated view, against the field painting its own glyphs
309 // with the backdrop hidden. Equal images mean every glyph landed in place.
310 const shot = async () => {
311 const rect = await cdp.eval<{ x: number; y: number; width: number; height: number }>(
312 `(() => { const r = __decorated.el.getBoundingClientRect(); return { x: r.x, y: r.y, width: r.width, height: r.height }; })()`,
313 );
314 const { data } = await cdp.call<{ data: string }>("Page.captureScreenshot", { format: "png", clip: { ...rect, scale: 1 } });
315 return data;
316 };
317 // Task boxes are drawn on purpose where the field has "[ ]"; take them out
318 // of this comparison, which is about glyph placement only.
319 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`);
320 const painted = await shot();
321 await cdp.eval(`__decorated.el.removeAttribute("data-decorated"); __decorated.backdrop().style.visibility = "hidden"; undefined`);
322 const native = await shot();
323 await cdp.eval(`__decorated.el.setAttribute("data-decorated", ""); __decorated.backdrop().style.visibility = ""; undefined`);
324 // Byte equality is too strict (a textarea and a div antialias differently);
325 // count the pixels that differ by more than antialiasing does. A glyph off
326 // by one pixel differs by far more (the shifted control below).
327 const differing = (a: string, b: string) =>
328 cdp.eval<number>(`(async () => {
329 const load = src => new Promise(done => { const image = new Image(); image.onload = () => done(image); image.src = "data:image/png;base64," + src; });
330 const [a, b] = await Promise.all([load("${a}"), load("${b}")]);
331 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; };
332 const [pa, pb] = [read(a), read(b)];
333 let far = 0;
334 for (let i = 0; i < pa.length; i += 4) {
335 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;
336 }
337 return far / (pa.length / 4);
338 })()`);
339 await cdp.eval(`__decorated.backdrop().style.translate = "1px 0"; undefined`);
340 const shifted = await shot();
341 await cdp.eval(`__decorated.backdrop().style.translate = ""; undefined`);
342 const aligned = await differing(painted, native);
343 const control = await differing(shifted, native);
344 await cdp.eval(`document.getElementById("plain-boxes").remove(); undefined`);
345 check("backdrop-pixels-match-the-field", aligned < 0.002 && control > 10 * aligned, `aligned ${aligned}, shifted 1px ${control}`);
346
347 // Scrolling the field scrolls the backdrop with it.
348 await cdp.eval(`__decorated.field.scrollTop = 9999; undefined`);
349 await sleep(50);
350 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; })()`));
351 check(
352 "backdrop-follows-scroll",
353 await cdp.eval(`__decorated.field.scrollTop > 0 && __decorated.backdrop().scrollTop === __decorated.field.scrollTop`),
354 JSON.stringify(await cdp.eval(`[__decorated.field.scrollTop, __decorated.backdrop().scrollTop]`)),
355 );
356
357 // A real click on the task box ticks the line, and the field keeps focus.
358 // (focus() scrolls to the caret; put it at the top, then let the backdrop follow.)
359 await cdp.eval(`__decorated.field.focus(); __decorated.field.setSelectionRange(0, 0); __decorated.field.scrollTop = 0; undefined`);
360 await sleep(50);
361 const center = await cdp.eval<{ x: number; y: number }>(
362 `(() => { const r = __decorated.backdrop().querySelector("[part~=box]").getBoundingClientRect(); return { x: r.x + r.width / 2, y: r.y + r.height / 2 }; })()`,
363 );
364 for (const type of ["mousePressed", "mouseReleased"]) {
365 await cdp.call("Input.dispatchMouseEvent", { type, ...center, button: "left", clickCount: 1 });
366 }
367 await sleep(50);
368 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]`)));
369 check("box-click-keeps-focus", await cdp.eval(`document.activeElement === __decorated.field`));
370
371 // A real Enter in a textarea is insertLineBreak; the dialect's command runs.
372 await cdp.eval(`__decorated.field.focus(); __decorated.field.setSelectionRange(20, 20); undefined`);
373 await cdp.call("Input.dispatchKeyEvent", { type: "keyDown", key: "Enter", code: "Enter", windowsVirtualKeyCode: 13, text: "\r" });
374 await cdp.call("Input.dispatchKeyEvent", { type: "keyUp", key: "Enter", code: "Enter", windowsVirtualKeyCode: 13 });
375 await sleep(50);
376 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)`)));
377
378 cdp.close();
379} finally {
380 chromium.kill();
381 server.stop(true);
382}
383
384let failed = 0;
385for (const [name, ok, extra] of checks) {
386 console.log(`${ok ? "ok" : "FAIL"} ${name}${ok ? "" : ` ${extra ?? ""}`}`);
387 if (!ok) failed += 1;
388}
389console.log(failed === 0 ? "tablet smoke: PASS" : `tablet smoke: FAIL (${failed})`);
390if (failed > 0) process.exit(1);