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
654 lignes · 33547 octetsBrut · Historique
1/**
2 * Headless-Chromium smoke for the shipped timeline bundle: serves a page that
3 * loads dist/timeline.js (no compiler, the consumer's path) and checks what
4 * happy-dom cannot, the geometry: segments sit on their gridlines, shown labels
5 * fit their segments, the tooltip stays inside its lane, the narrow layout puts
6 * each track's label above its lane, and nothing overflows the page, at a
7 * phone's width and a desktop's. Then the table view ([show-table]: the table
8 * in a scroll region under the plot, its numbers right-aligned): in English and
9 * French, with 5, 7 and 9 columns (long capitalised labels, a long note, an
10 * unbreakable DOI), from 280 to 1280px, no word is ever split over two lines,
11 * the page never scrolls sideways, and the region scrolls exactly when the
12 * table is wider than it, with an edge shadow then and only then; the region is
13 * a tab stop with a visible focus ring that the arrow keys scroll; the table
14 * returns to the page's place, exactly, when the element disconnects, and the
15 * element still follows it once reattached. Last, --pebble-timeline-start and
16 * -size are registered (@property) while a page's own --start and --size keep
17 * their meaning, and the motion (a rewritten row's segment glides to its new
18 * width; a shown label is never clipped mid-glide; under reduced motion it
19 * jumps).
20 *
21 * Run: `bun examples/timeline-smoke.ts`. Exits non-zero on failure.
22 * TIMELINE_BUNDLE=path serves another build of the bundle (an older commit's,
23 * to see a new check fail). Bun's WebSocket speaks CDP to the playwright-pinned
24 * Chromium (tablet-smoke.ts's pattern).
25 */
26import { existsSync, readdirSync } from "node:fs";
27import { spawn, spawnSync, type ChildProcess } from "node:child_process";
28
29function chrome(): string {
30 const cache = `${process.env.HOME}/.cache/ms-playwright`;
31 const newest = readdirSync(cache).filter(dir => /^chromium-\d+$/.test(dir)).sort().pop();
32 if (newest === undefined) throw new Error(`no playwright chromium under ${cache}`);
33 return `${cache}/${newest}/chrome-linux64/chrome`;
34}
35
36function bundle(): string {
37 if (process.env.TIMELINE_BUNDLE) return process.env.TIMELINE_BUNDLE;
38 const path = `${import.meta.dir}/../dist/timeline.js`;
39 if (!existsSync(path)) {
40 const built = spawnSync("bun", ["run", "build"], { cwd: `${import.meta.dir}/..` });
41 if (built.status !== 0) throw new Error(`build failed:\n${built.stderr.toString()}`);
42 }
43 return path;
44}
45
46/**
47 * The sample's table in two languages: five columns, long capitalised labels (Blink hyphenates no
48 * capitalised English word, so no fallback could rescue them), a source cell whose "Fig. 2"
49 * must stay whole. Then what a page could well add: a long note, a reference (an unbreakable DOI),
50 * a cultivar and a batch.
51 */
52const SAMPLE = {
53 en: {
54 unit: "wk",
55 axis: "Weeks from taking the cutting",
56 head: ["Method", "Phase", "Starts (day)", "Days", "Source"],
57 tracks: ["Standard Topping", "Early Topping"],
58 phases: ["Rooting", "Vegetative Growth", "Recovery (Supplementary Vegetative Growth)", "Flowering", "Mother-Plant Wait"],
59 extra: [
60 ["Observations", "Measured on the greenhouse bench under the long-day regime, see Supplementary Table S4"],
61 ["Reference", "doi:10.1016/j.scienta.2019.108712"],
62 ["Cultivar", "Cannabis sativa ‘Finola’"],
63 ["Batch", "LOT-2019-1004-A"],
64 ],
65 },
66 fr: {
67 unit: "sem.",
68 axis: "Semaines depuis le prélèvement de la bouture",
69 head: ["Méthode", "Phase", "Début (jour)", "Durée (jours)", "Source"],
70 tracks: ["Écimage Standard", "Écimage Précoce"],
71 phases: ["Enracinement", "Croissance Végétative", "Récupération (Croissance Supplémentaire)", "Floraison", "Attente du Pied-Mère"],
72 extra: [
73 ["Observations", "Mesuré sur la table de culture de la serre en jours longs, voir le Tableau Supplémentaire S4"],
74 ["Référence", "doi:10.1016/j.scienta.2019.108712"],
75 ["Cultivar", "Cannabis sativa ‘Finola’"],
76 ["Lot", "LOT-2019-1004-A"],
77 ],
78 },
79} as const;
80type Lang = keyof typeof SAMPLE;
81const AXIS = { min: -14, max: 105 };
82
83/**
84 * The sample page in \`lang\` with \`cols\` columns (5 to 9). Flowering's length (4th row) is the one
85 * the motion checks rewrite. The page also has its own --start and --size (a box 2rem wide, 3rem
86 * tall), which the element must leave alone, and keeps its timeline's markup as served
87 * (window.served), to compare with what the element leaves when it disconnects.
88 */
89function samplePage(lang: Lang, { showTable = false, cols = 5 } = {}): string {
90 const t = SAMPLE[lang];
91 const extra = t.extra.slice(0, cols - 5);
92 const rows: Array<[number, number, number, number, string]> = [
93 // track, phase, start, length, row attributes
94 [0, 0, 0, 10, ""],
95 [0, 1, 10, 14, ` data-series="2"`],
96 [0, 2, 24, 14, ` data-series="2" data-texture="hatch"`],
97 [0, 3, 38, 56, ` data-series="3"`],
98 [1, 4, -14, 14, ` data-series="muted"`],
99 [1, 0, 0, 10, ""],
100 [1, 1, 10, 14, ` data-series="2"`],
101 [1, 3, 24, 56, ` data-series="3"`],
102 ];
103 const cells = (values: readonly string[], tag: string) => values.map(v => `<${tag}>${v}</${tag}>`).join("");
104 const body = rows
105 .map(([track, phase, start, length, attributes]) =>
106 `<tr${attributes}><th>${t.tracks[track]}</th>${cells([t.phases[phase]!, String(start).replace("-", "−"), String(length), "Fig.&nbsp;2", ...extra.map(e => e[1])], "td")}</tr>`)
107 .join("\n ");
108 return `<!doctype html>
109<html lang="${lang}"><head><meta name="viewport" content="width=device-width, initial-scale=1"></head>
110<body style="margin: 0; padding: 16px; font-family: system-ui">
111<pebble-timeline${showTable ? " show-table" : ""} min="${AXIS.min}" max="${AXIS.max}" step="14" per="7" unit="${t.unit}" axis="${t.axis}">
112 <table>
113 <caption>Two schedules</caption>
114 <thead><tr>${cells([...t.head, ...extra.map(e => e[0])], "th")}</tr></thead>
115 <tbody>
116 ${body}
117 </tbody>
118 </table>
119</pebble-timeline>
120<div id="own" style="--start: 3rem; --size: 2rem; width: var(--size); height: var(--start)"></div>
121<script>window.served = document.querySelector("pebble-timeline").innerHTML;</script>
122<script type="module" src="/timeline.js"></script>
123</body></html>`;
124}
125const PAGE = samplePage("en");
126
127const VIEW_COLUMNS = [5, 7, 9];
128const VIEW_WIDTHS = [280, 320, 360, 390, 1280];
129
130type View = {
131 host: number;
132 inRegion: boolean;
133 region: { left: number; right: number; scroll: number; client: number; shadow: string } | null;
134 table: number;
135 display: string;
136 overflow: number;
137 swatches: number;
138 broken: Array<{ word: string; column: number; lines: number }>;
139 words: number;
140 figures: number;
141};
142/**
143 * The table view against its element and the page: whether the table sits in the region, the
144 * region's scroll and edge shadow, every segment row's swatch, and every word, split over two
145 * lines or not. A word is a run between spaces (a no-break space joins: "Fig.&nbsp;2" is one),
146 * ending after a hyphen ("Mother-" may end a line).
147 */
148const VIEW = `(() => {
149 const el = document.querySelector("pebble-timeline");
150 const table = el.querySelector("table");
151 const region = el.querySelector(".table-view");
152 const cells = [...table.querySelectorAll("th, td")];
153 const broken = [];
154 let words = 0, figures = 0;
155 for (const cell of cells) {
156 const walker = document.createTreeWalker(cell, NodeFilter.SHOW_TEXT);
157 for (let node = walker.nextNode(); node; node = walker.nextNode()) {
158 for (const match of node.data.matchAll(/[^ \\t\\n\\r-]+-?/g)) {
159 const range = document.createRange();
160 range.setStart(node, match.index);
161 range.setEnd(node, match.index + match[0].length);
162 const lines = new Set([...range.getClientRects()].filter(r => r.width > 0).map(r => Math.round(r.top))).size;
163 words++;
164 if (match[0] === "Fig.\\u00a02") figures++;
165 if (lines > 1) broken.push({ word: match[0], column: cell.cellIndex + 1, lines });
166 }
167 }
168 }
169 const box = region?.getBoundingClientRect();
170 return {
171 host: el.getBoundingClientRect().width,
172 inRegion: !!region && table.parentNode === region,
173 region: region ? { left: box.left, right: box.right, scroll: region.scrollWidth, client: region.clientWidth, shadow: getComputedStyle(region).boxShadow } : null,
174 table: table.getBoundingClientRect().width,
175 display: getComputedStyle(table).display,
176 overflow: document.documentElement.scrollWidth - document.documentElement.clientWidth,
177 swatches: [...table.querySelectorAll("tr[data-fill] > :nth-child(2)")].filter(c => getComputedStyle(c, "::before").width === "10px").length,
178 broken,
179 words,
180 figures,
181 };
182})()`;
183
184/** Everything the checks need, measured in the page in one go. */
185const MEASURE = `(() => {
186 const el = document.querySelector("pebble-timeline");
187 const r = n => { const b = n.getBoundingClientRect(); return { left: b.left, right: b.right, top: b.top, bottom: b.bottom, width: b.width }; };
188 const lanes = [...el.querySelectorAll(".lane")].map(r);
189 // Each segment's place from its row (the sample's rows are in track order): the data, not the
190 // element's own inline properties.
191 const rows = [...el.querySelectorAll("tbody > tr")];
192 const cell = (i, c) => Number(rows[i].children[c].textContent.replace("\u2212", "-"));
193 const span = ${AXIS.max} - ${AXIS.min};
194 return {
195 enhanced: el.hasAttribute("data-enhanced"),
196 table: r(el.querySelector("table")),
197 lanes,
198 labels: [...el.querySelectorAll(".track-label")].map(r),
199 plot: r(el.querySelector(".plot")),
200 baseline: r(el.querySelector(".gridline[data-baseline]") ?? el),
201 gridShown: getComputedStyle(el.querySelector(".grid")).display !== "none",
202 segments: [...el.querySelectorAll(".segment")].map((s, i) => ({
203 ...r(s),
204 start: (cell(i, 2) - ${AXIS.min}) / span,
205 size: cell(i, 3) / span,
206 last: s.hasAttribute("data-last"),
207 unlabelled: s.hasAttribute("data-unlabelled"),
208 labelFits: s.querySelector(".segment-label").scrollWidth <= s.querySelector(".segment-label").clientWidth + 0.5,
209 })),
210 overflow: document.documentElement.scrollWidth - document.documentElement.clientWidth,
211 };
212})()`;
213
214class Cdp {
215 private next = 0;
216 private pending = new Map<number, { resolve: (v: unknown) => void; reject: (e: unknown) => void }>();
217 private session = "";
218 private target = "";
219 private constructor(private ws: WebSocket) {
220 ws.onmessage = message => {
221 const data = JSON.parse(String(message.data));
222 const entry = data.id === undefined ? undefined : this.pending.get(data.id);
223 if (entry) {
224 this.pending.delete(data.id);
225 data.error ? entry.reject(new Error(data.error.message)) : entry.resolve(data.result);
226 }
227 };
228 }
229 static async connect(process: ChildProcess): Promise<Cdp> {
230 const endpoint = await new Promise<string>((resolve, reject) => {
231 let buffer = "";
232 process.stderr!.on("data", (chunk: Buffer) => {
233 buffer += chunk.toString();
234 const match = buffer.match(/DevTools listening on (ws:\/\/\S+)/);
235 if (match) resolve(match[1]!);
236 });
237 setTimeout(() => reject(new Error(`chromium never printed its DevTools endpoint: ${buffer}`)), 15000);
238 });
239 const ws = new WebSocket(endpoint);
240 await new Promise<void>((resolve, reject) => {
241 ws.onopen = () => resolve();
242 ws.onerror = event => reject(new Error(`CDP websocket failed: ${event}`));
243 });
244 return new Cdp(ws);
245 }
246 private raw<T>(method: string, params: Record<string, unknown>, sessionId?: string): Promise<T> {
247 const id = (this.next += 1);
248 return new Promise<T>((resolve, reject) => {
249 this.pending.set(id, { resolve: resolve as (v: unknown) => void, reject });
250 this.ws.send(JSON.stringify({ id, method, params, ...(sessionId ? { sessionId } : {}) }));
251 });
252 }
253 call<T = unknown>(method: string, params: Record<string, unknown> = {}): Promise<T> {
254 return this.raw<T>(method, params, this.session);
255 }
256 async attach(url: string): Promise<void> {
257 const { targetId } = await this.raw<{ targetId: string }>("Target.createTarget", { url });
258 const { sessionId } = await this.raw<{ sessionId: string }>("Target.attachToTarget", { targetId, flatten: true });
259 this.session = sessionId;
260 this.target = targetId;
261 await this.call("Runtime.enable");
262 }
263 /** Closes the tab attach opened. */
264 async closeTab(): Promise<void> {
265 if (this.target) await this.raw("Target.closeTarget", { targetId: this.target });
266 this.target = this.session = "";
267 }
268 async eval<T = unknown>(expression: string): Promise<T> {
269 const result = await this.call<{ result: { value: T }; exceptionDetails?: { text: string; exception?: { description?: string } } }>(
270 "Runtime.evaluate",
271 { expression, returnByValue: true, awaitPromise: true },
272 );
273 const thrown = result.exceptionDetails;
274 if (thrown) throw new Error(`page threw: ${thrown.exception?.description ?? thrown.text}`);
275 return result.result.value;
276 }
277 /** A real key press (keyDown, keyUp), so the browser's default actions run: Tab, scrolling. */
278 async press(key: string, keyCode: number): Promise<void> {
279 for (const type of ["rawKeyDown", "keyUp"])
280 await this.call("Input.dispatchKeyEvent", { type, key, code: key, windowsVirtualKeyCode: keyCode, nativeVirtualKeyCode: keyCode });
281 }
282 close(): void {
283 this.ws.close();
284 }
285}
286
287type Registered = {
288 names: string[];
289 typed: string;
290 unit: string;
291 value: number;
292 inline: number;
293 label: string;
294 own: { width: number; height: number };
295};
296/**
297 * The registrations (@property, an unscoped adopted sheet): the names in the document's adopted
298 * sheets, a segment's --pebble-timeline-size as computed (a typed number), its label's (not
299 * inherited: the initial 0), and the page's own box, whose --size: 2rem and --start: 3rem must
300 * still size it once the bundle has loaded.
301 */
302const REGISTERED = `(() => {
303 const segment = document.querySelector("pebble-timeline .segment");
304 const size = segment.computedStyleMap().get("--pebble-timeline-size");
305 const own = document.getElementById("own").getBoundingClientRect();
306 return {
307 names: document.adoptedStyleSheets.flatMap(sheet => [...sheet.cssRules].filter(r => r instanceof CSSPropertyRule).map(r => r.name)),
308 typed: size?.constructor.name ?? "",
309 unit: size?.unit ?? "",
310 value: size?.value ?? NaN,
311 inline: Number(segment.style.getPropertyValue("--pebble-timeline-size")),
312 label: getComputedStyle(segment.querySelector(".segment-label")).getPropertyValue("--pebble-timeline-size").trim(),
313 own: { width: own.width, height: own.height },
314 };
315})()`;
316
317type Focus = { focused: boolean; visible: boolean; outline: string; color: string; scrollLeft: number; scrolls: boolean };
318/** The focused element against the region, its outline, and how far the region is scrolled. */
319const FOCUS = `(() => {
320 const region = document.querySelector(".table-view");
321 if (!region) return { focused: false, visible: false, outline: "no region", color: "", scrollLeft: 0, scrolls: false };
322 const style = getComputedStyle(region);
323 return {
324 focused: document.activeElement === region,
325 visible: region.matches(":focus-visible"),
326 outline: style.outlineStyle + " " + style.outlineWidth,
327 color: style.outlineColor,
328 scrollLeft: region.scrollLeft,
329 scrolls: region.scrollWidth > region.clientWidth,
330 };
331})()`;
332
333type RoundTrip = { parent: boolean; first: boolean; exact: boolean; leftovers: number; back: boolean; followed: boolean };
334/**
335 * Detaches the element and lets it release (define() does so a macrotask after a disconnect): the
336 * table is the host's child again, first, and the host's markup is what the server sent. Then
337 * reattaches it: the table is back in the region, and a rewritten row still moves its segment
338 * (the element observes the same table node).
339 */
340const ROUND_TRIP = `(async () => {
341 const el = document.querySelector("pebble-timeline");
342 const table = el.querySelector("table");
343 const spot = el.nextSibling;
344 el.remove();
345 await new Promise(r => setTimeout(r, 50));
346 const detached = {
347 parent: table.parentNode === el,
348 first: el.firstElementChild === table,
349 exact: el.innerHTML === window.served,
350 leftovers: el.querySelectorAll(".timeline, .table-view").length,
351 };
352 spot.before(el);
353 await new Promise(r => setTimeout(r, 50));
354 const back = table.parentNode === el.querySelector(".table-view");
355 const flowering = () => el.querySelectorAll(".segment")[3].getBoundingClientRect().width;
356 const before = flowering();
357 table.querySelectorAll("tbody > tr")[3].children[3].textContent = "6";
358 await new Promise(r => setTimeout(r, 600));
359 return { ...detached, back, followed: flowering() < before / 4 };
360})()`;
361
362type Rect = { left: number; right: number; top: number; bottom: number; width: number };
363type Measure = {
364 enhanced: boolean;
365 table: Rect;
366 lanes: Rect[];
367 labels: Rect[];
368 plot: Rect;
369 baseline: Rect;
370 gridShown: boolean;
371 segments: Array<Rect & { start: number; size: number; last: boolean; unlabelled: boolean; labelFits: boolean }>;
372 overflow: number;
373};
374
375type TableView = {
376 tableTop: number;
377 plotBottom: number;
378 overflow: number;
379 swatches: number;
380 numbers: Array<{ textRight: number; contentRight: number }>;
381};
382/** Shows the table and measures it; the plot's bottom is the lanes' and the axis'. */
383const TABLE_VIEW = `(async () => {
384 const el = document.querySelector("pebble-timeline");
385 el.setAttribute("show-table", "");
386 await new Promise(r => requestAnimationFrame(() => requestAnimationFrame(r)));
387 const table = el.querySelector("table");
388 const numbers = [...table.querySelectorAll("tbody > tr > :nth-child(3), tbody > tr > :nth-child(4)")].map(cell => {
389 const range = document.createRange();
390 range.selectNodeContents(cell);
391 const style = getComputedStyle(cell);
392 return {
393 textRight: range.getBoundingClientRect().right,
394 contentRight: cell.getBoundingClientRect().right - parseFloat(style.paddingRight) - parseFloat(style.borderRightWidth),
395 };
396 });
397 return {
398 tableTop: table.getBoundingClientRect().top,
399 plotBottom: el.querySelector(".plot").getBoundingClientRect().bottom,
400 overflow: document.documentElement.scrollWidth - document.documentElement.clientWidth,
401 swatches: [...table.querySelectorAll("tbody > tr > :nth-child(2)")].filter(c => getComputedStyle(c, "::before").width === "10px").length,
402 numbers,
403 };
404})()`;
405
406type Sample = { at: number; width: number; hidden: boolean; clipped: string[] };
407type Clip = { samples: Sample[]; settled: { width: number; shown: boolean } };
408/**
409 * Rewrites flowering's length (4th row) to \`days\` and samples every segment at 50, 150 and
410 * 300ms into the glide: a label that shows must show whole, inside its segment's current box.
411 */
412const clipDuring = (days: number) => `(async () => {
413 const el = document.querySelector("pebble-timeline");
414 const segments = [...el.querySelectorAll(".segment")];
415 const flowering = segments[3];
416 const sample = at => ({
417 at,
418 width: flowering.getBoundingClientRect().width,
419 hidden: flowering.hasAttribute("data-unlabelled"),
420 clipped: segments.filter(s => !s.hasAttribute("data-unlabelled")).filter(s => {
421 const label = s.querySelector(".segment-label");
422 return label.scrollWidth > label.clientWidth + 0.5 || label.getBoundingClientRect().right > s.getBoundingClientRect().right + 0.5;
423 }).map(s => s.textContent),
424 });
425 el.querySelectorAll("tbody > tr")[3].children[3].textContent = "${days}";
426 const t0 = performance.now();
427 const samples = [];
428 for (const at of [50, 150, 300]) {
429 await new Promise(r => setTimeout(r, Math.max(0, at - (performance.now() - t0))));
430 samples.push(sample(Math.round(performance.now() - t0)));
431 }
432 await new Promise(r => setTimeout(r, 400));
433 return { samples, settled: { width: flowering.getBoundingClientRect().width, shown: !flowering.hasAttribute("data-unlabelled") } };
434})()`;
435
436type Glide = { before: number; mid: number; after: number; expected: number; kept: boolean };
437/** Rewrites the recovery row (3rd) to \`days\` and samples its segment's width before, mid-way and after. */
438const glideTo = (days: number, flowering: number, midMs: number) => `(async () => {
439 const el = document.querySelector("pebble-timeline");
440 const lane = el.querySelector(".lane").getBoundingClientRect().width;
441 const segment = el.querySelectorAll(".segment")[2];
442 const before = segment.getBoundingClientRect().width;
443 const rows = el.querySelectorAll("tbody > tr");
444 rows[2].children[3].textContent = "${days}";
445 rows[3].children[2].textContent = "${flowering}";
446 await new Promise(r => setTimeout(r, ${midMs}));
447 const mid = segment.getBoundingClientRect().width;
448 await new Promise(r => setTimeout(r, 500));
449 return { before, mid, after: segment.getBoundingClientRect().width, expected: (${days} / 119) * lane - 2, kept: el.querySelectorAll(".segment")[2] === segment };
450})()`;
451const GLIDE = glideTo(7, 31, 150);
452const GLIDE_BACK = glideTo(14, 38, 30);
453
454const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));
455const checks: Array<[string, boolean, string?]> = [];
456const check = (name: string, ok: boolean, extra?: string) => checks.push([name, ok, extra]);
457const near = (a: number, b: number, tolerance = 1) => Math.abs(a - b) <= tolerance;
458
459const server = Bun.serve({
460 port: 0,
461 fetch(request) {
462 const url = new URL(request.url);
463 if (url.pathname === "/timeline.js") return new Response(Bun.file(bundle()), { headers: { "content-type": "text/javascript" } });
464 const lang = url.searchParams.get("lang") as Lang | null;
465 const page = lang ? samplePage(lang, { showTable: url.searchParams.has("show"), cols: Number(url.searchParams.get("cols") ?? 5) }) : PAGE;
466 return new Response(page, { headers: { "content-type": "text/html; charset=utf-8" } });
467 },
468});
469const chromium = spawn(chrome(), ["--headless=new", "--disable-gpu", "--no-sandbox", "--remote-debugging-port=0", "about:blank"], {
470 stdio: ["ignore", "ignore", "pipe"],
471});
472
473/** A fresh tab at \`width\`, on \`path\`, once the timeline has drawn and fitted its labels. */
474async function open(cdp: Cdp, width: number, path: string): Promise<void> {
475 await cdp.attach("about:blank");
476 await cdp.call("Emulation.setDeviceMetricsOverride", { width, height: 800, deviceScaleFactor: 1, mobile: width < 600 });
477 await cdp.call("Emulation.setEmulatedMedia", { features: [{ name: "prefers-reduced-motion", value: "no-preference" }] });
478 await cdp.call("Emulation.setFocusEmulationEnabled", { enabled: true });
479 await cdp.call("Page.navigate", { url: `http://localhost:${server.port}${path}` });
480 let ready = false;
481 for (let attempt = 0; attempt < 50 && !ready; attempt++) {
482 try {
483 ready = (await cdp.eval(`customElements.whenDefined("pebble-timeline").then(() => !!document.querySelector("pebble-timeline .segment"))`)) === true;
484 } catch {
485 await sleep(100); // the navigation replaced the execution context
486 }
487 }
488 if (!ready) throw new Error(`${width}px ${path}: the timeline never drew`);
489 await sleep(100); // the label fit runs on the next animation frame
490}
491
492try {
493 const cdp = await Cdp.connect(chromium);
494 for (const width of [390, 1280]) {
495 await open(cdp, width, "/");
496
497 const m = await cdp.eval<Measure>(MEASURE);
498 const at = `${width}px`;
499 // Visually hidden: the scaled table is a few pixels, clipped to nothing (timeline.css).
500 check(`${at} enhanced, table visually hidden`, m.enhanced && m.table.width < 8, `table ${m.table.width}px`);
501 check(`${at} no horizontal overflow`, m.overflow <= 0, `${m.overflow}px`);
502
503 // Each segment starts where its fraction of the lane says, and the gap is 2px.
504 const lane = m.lanes[0]!;
505 const misplaced = m.segments.filter(s => !near(s.left, lane.left + s.start * lane.width));
506 check(`${at} segments start on their place`, misplaced.length === 0, JSON.stringify(misplaced.map(s => s.left)));
507 const wrongWidth = m.segments.filter(s => !near(s.width, s.size * lane.width - (s.last ? 0 : 2)));
508 check(`${at} segments end 2px short of the next`, wrongWidth.length === 0, JSON.stringify(wrongWidth.map(s => s.width)));
509 // Rooting starts at day 0: on the baseline gridline, where gridlines show.
510 if (m.gridShown) check(`${at} day 0 sits on the baseline gridline`, near(m.segments[0]!.left, m.baseline.left), `${m.segments[0]!.left} vs ${m.baseline.left}`);
511 else {
512 check(`${at} narrow: track labels sit above their lanes`, m.labels.every((label, i) => label.bottom <= m.lanes[i]!.top + 0.5));
513 check(`${at} narrow: lanes take the plot's full width`, m.lanes.every(l => near(l.width, m.plot.width)), `${lane.width} of ${m.plot.width}`);
514 }
515
516 check(`${at} every shown label fits its segment`, m.segments.every(s => s.unlabelled || s.labelFits));
517 check(`${at} some labels show`, m.segments.some(s => !s.unlabelled));
518
519 const registered = await cdp.eval<Registered>(REGISTERED);
520 const names = ["--pebble-timeline-start", "--pebble-timeline-size"];
521 check(
522 `${at} --pebble-timeline-start and -size are registered by an adopted @property sheet, --start and --size are not`,
523 names.every(n => registered.names.includes(n)) && !registered.names.some(n => n === "--start" || n === "--size"),
524 JSON.stringify(registered.names),
525 );
526 check(
527 `${at} a segment's --pebble-timeline-size computes to a typed number`,
528 registered.typed === "CSSUnitValue" && registered.unit === "number" && near(registered.value, registered.inline, 1e-4),
529 JSON.stringify(registered),
530 );
531 check(`${at} a label does not inherit its segment's size`, registered.label === "0", JSON.stringify(registered));
532 check(`${at} the page's own --size: 2rem and --start: 3rem still size its box`, near(registered.own.width, 32, 0.5) && near(registered.own.height, 48, 0.5), JSON.stringify(registered.own));
533
534 // The tooltip of the first and the last segment stays inside the lane.
535 for (const key of ["Home", "End"]) {
536 await cdp.eval(`(() => { const plot = document.querySelector(".plot"); plot.focus();
537 plot.dispatchEvent(new KeyboardEvent("keydown", { key: "${key}", bubbles: true, cancelable: true })); })()`);
538 await sleep(30);
539 const tip = await cdp.eval<Rect & { open: boolean }>(`(() => { const t = document.querySelector(".tooltip");
540 const b = t.getBoundingClientRect(); return { left: b.left, right: b.right, top: b.top, bottom: b.bottom, width: b.width, open: t.hasAttribute("data-open") }; })()`);
541 const laneOfTip = key === "Home" ? m.lanes[0]! : m.lanes[m.lanes.length - 1]!;
542 check(
543 `${at} ${key}: tooltip open, inside its lane, above it`,
544 tip.open && tip.left >= laneOfTip.left - 1 && tip.right <= laneOfTip.right + 1 && tip.bottom <= laneOfTip.top + 1,
545 JSON.stringify({ tip, lane: laneOfTip }),
546 );
547 }
548
549 // The table view: shown under the plot (moved into the region after it), its numbers
550 // right-aligned: each start and length cell's text ends at its content box's right.
551 const view = await cdp.eval<TableView>(TABLE_VIEW);
552 check(`${at} show-table: the table sits under the plot`, view.tableTop >= view.plotBottom, `table top ${view.tableTop}, plot bottom ${view.plotBottom}`);
553 check(`${at} show-table: no horizontal overflow`, view.overflow <= 0, `${view.overflow}px`);
554 check(`${at} show-table: every segment row has a swatch`, view.swatches === m.segments.length, `${view.swatches} of ${m.segments.length}`);
555 const offRight = view.numbers.filter(n => !near(n.textRight, n.contentRight, 1.5));
556 check(`${at} show-table: start and length cells are right-aligned`, view.numbers.length > 0 && offRight.length === 0, JSON.stringify(offRight));
557
558 // Labels mid-glide: flowering shrinks from 56 days to 6 (its label no longer fits), then
559 // grows back. A label that shows is whole and inside its segment at every sample: it hides
560 // as a shrink starts and shows again once a grow is done.
561 for (const [days, way] of [[6, "shrink"], [56, "grow"]] as const) {
562 const clip = await cdp.eval<Clip>(clipDuring(days));
563 const bad = clip.samples.filter(s => s.clipped.length > 0);
564 check(`${at} ${way}: no shown label is clipped at 50, 150, 300ms`, bad.length === 0, JSON.stringify(clip.samples));
565 if (way === "shrink") check(`${at} shrink: flowering's label is hidden from the start`, clip.samples[0]!.hidden, JSON.stringify(clip.samples));
566 check(`${at} ${way}: flowering's label is ${way === "grow" ? "shown" : "hidden"} once it settles`, clip.settled.shown === (way === "grow"), JSON.stringify(clip.settled));
567 }
568
569 // Motion: the recovery shortens from 14 days to 7 (flowering moves up a week). Mid-way
570 // the segment is between its old and new widths; at the end it is the new one, and the
571 // labels are fitted again.
572 const glide = await cdp.eval<Glide>(GLIDE);
573 check(
574 `${at} a rewritten row's segment glides to its new width`,
575 glide.mid < glide.before - 2 && glide.mid > glide.after + 2 && glide.kept,
576 JSON.stringify(glide),
577 );
578 check(`${at} it lands on its new width`, near(glide.after, glide.expected), JSON.stringify(glide));
579 const settled = await cdp.eval<Measure>(MEASURE);
580 check(`${at} after the glide, every shown label fits its segment`, settled.segments.every(s => s.unlabelled || s.labelFits));
581
582 await cdp.call("Emulation.setEmulatedMedia", { features: [{ name: "prefers-reduced-motion", value: "reduce" }] });
583 const jump = await cdp.eval<Glide>(GLIDE_BACK);
584 check(`${at} reduced motion: the segment jumps`, near(jump.mid, jump.expected), JSON.stringify(jump));
585 await cdp.closeTab();
586 }
587
588 // The table view: English and French, 5, 7 and 9 columns, from 280 to 1280px. Words are never
589 // split over two lines (the region scrolls instead), the page never scrolls sideways, and the
590 // region scrolls exactly when the table is wider than it, with an edge shadow then and only then.
591 for (const lang of ["en", "fr"] as const)
592 for (const cols of VIEW_COLUMNS)
593 for (const width of VIEW_WIDTHS) {
594 await open(cdp, width, `/?lang=${lang}&cols=${cols}&show`);
595 const v = await cdp.eval<View>(VIEW);
596 const at = `${width}px ${lang} ${cols} columns`;
597 check(`${at}: the table sits in its region, inside the element`, v.inRegion && v.region!.right <= v.region!.left + v.host + 0.5, JSON.stringify(v.region));
598 check(`${at}: no word split over two lines`, v.broken.length === 0 && v.figures === 8 && v.words > 0, JSON.stringify(v.broken));
599 check(`${at}: the page never scrolls sideways`, v.overflow <= 0, `${v.overflow}px`);
600 const wider = v.table > (v.region?.client ?? v.host) + 0.5;
601 check(
602 `${at}: the region scrolls exactly when the table is wider (${Math.round(v.table)} in ${v.region?.client ?? "no region"})`,
603 v.region !== null && (v.region.scroll > v.region.client) === wider,
604 JSON.stringify(v.region),
605 );
606 check(`${at}: an edge shadow exactly when the region scrolls`, v.region !== null && (v.region.shadow !== "none") === wider, v.region?.shadow);
607 check(`${at}: the table keeps display: table, a swatch per segment row`, v.display === "table" && v.swatches === 8, `${v.display}, ${v.swatches} swatches`);
608 await cdp.closeTab();
609 }
610
611 // The region is the plot's next tab stop, with a visible focus ring, and the arrow keys scroll it.
612 {
613 await open(cdp, 320, "/?lang=en&cols=9&show");
614 await cdp.eval(`document.querySelector(".plot").focus()`);
615 await cdp.press("Tab", 9);
616 const focus = await cdp.eval<Focus>(FOCUS);
617 check(`320px 9 columns: Tab from the plot reaches the region`, focus.focused && focus.scrolls, JSON.stringify(focus));
618 check(
619 `320px 9 columns: the focused region shows a focus ring`,
620 focus.visible && focus.outline === "solid 2px" && !/rgba\(.*, 0\)$/.test(focus.color),
621 JSON.stringify(focus),
622 );
623 for (let i = 0; i < 3; i++) await cdp.press("ArrowRight", 39);
624 await sleep(300); // a smooth scroll
625 const scrolled = await cdp.eval<Focus>(FOCUS);
626 check(`320px 9 columns: the arrow keys scroll the region`, scrolled.focused && scrolled.scrollLeft > 0, JSON.stringify(scrolled));
627 await cdp.closeTab();
628 }
629
630 // The table is the page's: on disconnect it goes back where the page had it, exactly, and the
631 // element follows it again once reattached.
632 {
633 await open(cdp, 390, "/?lang=en&cols=5&show");
634 const trip = await cdp.eval<RoundTrip>(ROUND_TRIP);
635 check(`disconnected: the table is the host's first child again`, trip.parent && trip.first, JSON.stringify(trip));
636 check(`disconnected: the host's markup is what the server sent`, trip.exact && trip.leftovers === 0, JSON.stringify(trip));
637 check(`reattached: the table is in the region again, and a rewritten row moves its segment`, trip.back && trip.followed, JSON.stringify(trip));
638 await cdp.closeTab();
639 }
640 cdp.close();
641} finally {
642 chromium.kill();
643 server.stop(true);
644}
645
646let failed = 0;
647for (const [name, ok, extra] of checks) {
648 console.log(`${ok ? "ok " : "FAIL"} ${name}${!ok && extra ? ` ${extra}` : ""}`);
649 if (!ok) failed++;
650}
651if (failed > 0) {
652 console.log(`\n${failed} check(s) failed`);
653 process.exit(1);
654}