/** * Headless-Chromium smoke for the shipped timeline bundle: serves a page that * loads dist/timeline.js (no compiler, the consumer's path) and checks what * happy-dom cannot, the geometry: segments sit on their gridlines, shown labels * fit their segments, the tooltip stays inside its lane, the narrow layout puts * each track's label above its lane, and nothing overflows the page, at a * phone's width and a desktop's. Then the table view ([show-table]: the table * in a scroll region under the plot, its numbers right-aligned): in English and * French, with 5, 7 and 9 columns (long capitalised labels, a long note, an * unbreakable DOI), from 280 to 1280px, no word is ever split over two lines, * the page never scrolls sideways, and the region scrolls exactly when the * table is wider than it, with an edge shadow then and only then; the region is * a tab stop with a visible focus ring that the arrow keys scroll; the table * returns to the page's place, exactly, when the element disconnects, and the * element still follows it once reattached. Last, --pebble-timeline-start and * -size are registered (@property) while a page's own --start and --size keep * their meaning, and the motion (a rewritten row's segment glides to its new * width; a shown label is never clipped mid-glide; under reduced motion it * jumps). * * Run: `bun examples/timeline-smoke.ts`. Exits non-zero on failure. * TIMELINE_BUNDLE=path serves another build of the bundle (an older commit's, * to see a new check fail). Bun's WebSocket speaks CDP to the playwright-pinned * Chromium (tablet-smoke.ts's pattern). */ import { existsSync, readdirSync } from "node:fs"; import { spawn, spawnSync, type ChildProcess } from "node:child_process"; 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`; } function bundle(): string { if (process.env.TIMELINE_BUNDLE) return process.env.TIMELINE_BUNDLE; const path = `${import.meta.dir}/../dist/timeline.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 sample's table in two languages: five columns, long capitalised labels (Blink hyphenates no * capitalised English word, so no fallback could rescue them), a source cell whose "Fig. 2" * must stay whole. Then what a page could well add: a long note, a reference (an unbreakable DOI), * a cultivar and a batch. */ const SAMPLE = { en: { unit: "wk", axis: "Weeks from taking the cutting", head: ["Method", "Phase", "Starts (day)", "Days", "Source"], tracks: ["Standard Topping", "Early Topping"], phases: ["Rooting", "Vegetative Growth", "Recovery (Supplementary Vegetative Growth)", "Flowering", "Mother-Plant Wait"], extra: [ ["Observations", "Measured on the greenhouse bench under the long-day regime, see Supplementary Table S4"], ["Reference", "doi:10.1016/j.scienta.2019.108712"], ["Cultivar", "Cannabis sativa ‘Finola’"], ["Batch", "LOT-2019-1004-A"], ], }, fr: { unit: "sem.", axis: "Semaines depuis le prélèvement de la bouture", head: ["Méthode", "Phase", "Début (jour)", "Durée (jours)", "Source"], tracks: ["Écimage Standard", "Écimage Précoce"], phases: ["Enracinement", "Croissance Végétative", "Récupération (Croissance Supplémentaire)", "Floraison", "Attente du Pied-Mère"], extra: [ ["Observations", "Mesuré sur la table de culture de la serre en jours longs, voir le Tableau Supplémentaire S4"], ["Référence", "doi:10.1016/j.scienta.2019.108712"], ["Cultivar", "Cannabis sativa ‘Finola’"], ["Lot", "LOT-2019-1004-A"], ], }, } as const; type Lang = keyof typeof SAMPLE; const AXIS = { min: -14, max: 105 }; /** * The sample page in \`lang\` with \`cols\` columns (5 to 9). Flowering's length (4th row) is the one * the motion checks rewrite. The page also has its own --start and --size (a box 2rem wide, 3rem * tall), which the element must leave alone, and keeps its timeline's markup as served * (window.served), to compare with what the element leaves when it disconnects. */ function samplePage(lang: Lang, { showTable = false, cols = 5 } = {}): string { const t = SAMPLE[lang]; const extra = t.extra.slice(0, cols - 5); const rows: Array<[number, number, number, number, string]> = [ // track, phase, start, length, row attributes [0, 0, 0, 10, ""], [0, 1, 10, 14, ` data-series="2"`], [0, 2, 24, 14, ` data-series="2" data-texture="hatch"`], [0, 3, 38, 56, ` data-series="3"`], [1, 4, -14, 14, ` data-series="muted"`], [1, 0, 0, 10, ""], [1, 1, 10, 14, ` data-series="2"`], [1, 3, 24, 56, ` data-series="3"`], ]; const cells = (values: readonly string[], tag: string) => values.map(v => `<${tag}>${v}`).join(""); const body = rows .map(([track, phase, start, length, attributes]) => `${t.tracks[track]}${cells([t.phases[phase]!, String(start).replace("-", "−"), String(length), "Fig. 2", ...extra.map(e => e[1])], "td")}`) .join("\n "); return ` ${cells([...t.head, ...extra.map(e => e[0])], "th")} ${body}
Two schedules
`; } const PAGE = samplePage("en"); const VIEW_COLUMNS = [5, 7, 9]; const VIEW_WIDTHS = [280, 320, 360, 390, 1280]; type View = { host: number; inRegion: boolean; region: { left: number; right: number; scroll: number; client: number; shadow: string } | null; table: number; display: string; overflow: number; swatches: number; broken: Array<{ word: string; column: number; lines: number }>; words: number; figures: number; }; /** * The table view against its element and the page: whether the table sits in the region, the * region's scroll and edge shadow, every segment row's swatch, and every word, split over two * lines or not. A word is a run between spaces (a no-break space joins: "Fig. 2" is one), * ending after a hyphen ("Mother-" may end a line). */ const VIEW = `(() => { const el = document.querySelector("pebble-timeline"); const table = el.querySelector("table"); const region = el.querySelector(".table-view"); const cells = [...table.querySelectorAll("th, td")]; const broken = []; let words = 0, figures = 0; for (const cell of cells) { const walker = document.createTreeWalker(cell, NodeFilter.SHOW_TEXT); for (let node = walker.nextNode(); node; node = walker.nextNode()) { for (const match of node.data.matchAll(/[^ \\t\\n\\r-]+-?/g)) { const range = document.createRange(); range.setStart(node, match.index); range.setEnd(node, match.index + match[0].length); const lines = new Set([...range.getClientRects()].filter(r => r.width > 0).map(r => Math.round(r.top))).size; words++; if (match[0] === "Fig.\\u00a02") figures++; if (lines > 1) broken.push({ word: match[0], column: cell.cellIndex + 1, lines }); } } } const box = region?.getBoundingClientRect(); return { host: el.getBoundingClientRect().width, inRegion: !!region && table.parentNode === region, region: region ? { left: box.left, right: box.right, scroll: region.scrollWidth, client: region.clientWidth, shadow: getComputedStyle(region).boxShadow } : null, table: table.getBoundingClientRect().width, display: getComputedStyle(table).display, overflow: document.documentElement.scrollWidth - document.documentElement.clientWidth, swatches: [...table.querySelectorAll("tr[data-fill] > :nth-child(2)")].filter(c => getComputedStyle(c, "::before").width === "10px").length, broken, words, figures, }; })()`; /** Everything the checks need, measured in the page in one go. */ const MEASURE = `(() => { const el = document.querySelector("pebble-timeline"); const r = n => { const b = n.getBoundingClientRect(); return { left: b.left, right: b.right, top: b.top, bottom: b.bottom, width: b.width }; }; const lanes = [...el.querySelectorAll(".lane")].map(r); // Each segment's place from its row (the sample's rows are in track order): the data, not the // element's own inline properties. const rows = [...el.querySelectorAll("tbody > tr")]; const cell = (i, c) => Number(rows[i].children[c].textContent.replace("\u2212", "-")); const span = ${AXIS.max} - ${AXIS.min}; return { enhanced: el.hasAttribute("data-enhanced"), table: r(el.querySelector("table")), lanes, labels: [...el.querySelectorAll(".track-label")].map(r), plot: r(el.querySelector(".plot")), baseline: r(el.querySelector(".gridline[data-baseline]") ?? el), gridShown: getComputedStyle(el.querySelector(".grid")).display !== "none", segments: [...el.querySelectorAll(".segment")].map((s, i) => ({ ...r(s), start: (cell(i, 2) - ${AXIS.min}) / span, size: cell(i, 3) / span, last: s.hasAttribute("data-last"), unlabelled: s.hasAttribute("data-unlabelled"), labelFits: s.querySelector(".segment-label").scrollWidth <= s.querySelector(".segment-label").clientWidth + 0.5, })), overflow: document.documentElement.scrollWidth - document.documentElement.clientWidth, }; })()`; class Cdp { private next = 0; private pending = new Map void; reject: (e: unknown) => void }>(); private session = ""; private target = ""; private constructor(private ws: WebSocket) { ws.onmessage = message => { const data = JSON.parse(String(message.data)); const entry = data.id === undefined ? undefined : 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); } private raw(method: string, params: Record, sessionId?: string): 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 ? { sessionId } : {}) })); }); } call(method: string, params: Record = {}): Promise { return this.raw(method, params, this.session); } async attach(url: string): Promise { const { targetId } = await this.raw<{ targetId: string }>("Target.createTarget", { url }); const { sessionId } = await this.raw<{ sessionId: string }>("Target.attachToTarget", { targetId, flatten: true }); this.session = sessionId; this.target = targetId; await this.call("Runtime.enable"); } /** Closes the tab attach opened. */ async closeTab(): Promise { if (this.target) await this.raw("Target.closeTarget", { targetId: this.target }); this.target = this.session = ""; } async eval(expression: string): Promise { const result = await this.call<{ result: { value: T }; exceptionDetails?: { text: string; exception?: { description?: string } } }>( "Runtime.evaluate", { expression, returnByValue: true, awaitPromise: true }, ); const thrown = result.exceptionDetails; if (thrown) throw new Error(`page threw: ${thrown.exception?.description ?? thrown.text}`); return result.result.value; } /** A real key press (keyDown, keyUp), so the browser's default actions run: Tab, scrolling. */ async press(key: string, keyCode: number): Promise { for (const type of ["rawKeyDown", "keyUp"]) await this.call("Input.dispatchKeyEvent", { type, key, code: key, windowsVirtualKeyCode: keyCode, nativeVirtualKeyCode: keyCode }); } close(): void { this.ws.close(); } } type Registered = { names: string[]; typed: string; unit: string; value: number; inline: number; label: string; own: { width: number; height: number }; }; /** * The registrations (@property, an unscoped adopted sheet): the names in the document's adopted * sheets, a segment's --pebble-timeline-size as computed (a typed number), its label's (not * inherited: the initial 0), and the page's own box, whose --size: 2rem and --start: 3rem must * still size it once the bundle has loaded. */ const REGISTERED = `(() => { const segment = document.querySelector("pebble-timeline .segment"); const size = segment.computedStyleMap().get("--pebble-timeline-size"); const own = document.getElementById("own").getBoundingClientRect(); return { names: document.adoptedStyleSheets.flatMap(sheet => [...sheet.cssRules].filter(r => r instanceof CSSPropertyRule).map(r => r.name)), typed: size?.constructor.name ?? "", unit: size?.unit ?? "", value: size?.value ?? NaN, inline: Number(segment.style.getPropertyValue("--pebble-timeline-size")), label: getComputedStyle(segment.querySelector(".segment-label")).getPropertyValue("--pebble-timeline-size").trim(), own: { width: own.width, height: own.height }, }; })()`; type Focus = { focused: boolean; visible: boolean; outline: string; color: string; scrollLeft: number; scrolls: boolean }; /** The focused element against the region, its outline, and how far the region is scrolled. */ const FOCUS = `(() => { const region = document.querySelector(".table-view"); if (!region) return { focused: false, visible: false, outline: "no region", color: "", scrollLeft: 0, scrolls: false }; const style = getComputedStyle(region); return { focused: document.activeElement === region, visible: region.matches(":focus-visible"), outline: style.outlineStyle + " " + style.outlineWidth, color: style.outlineColor, scrollLeft: region.scrollLeft, scrolls: region.scrollWidth > region.clientWidth, }; })()`; type RoundTrip = { parent: boolean; first: boolean; exact: boolean; leftovers: number; back: boolean; followed: boolean }; /** * Detaches the element and lets it release (define() does so a macrotask after a disconnect): the * table is the host's child again, first, and the host's markup is what the server sent. Then * reattaches it: the table is back in the region, and a rewritten row still moves its segment * (the element observes the same table node). */ const ROUND_TRIP = `(async () => { const el = document.querySelector("pebble-timeline"); const table = el.querySelector("table"); const spot = el.nextSibling; el.remove(); await new Promise(r => setTimeout(r, 50)); const detached = { parent: table.parentNode === el, first: el.firstElementChild === table, exact: el.innerHTML === window.served, leftovers: el.querySelectorAll(".timeline, .table-view").length, }; spot.before(el); await new Promise(r => setTimeout(r, 50)); const back = table.parentNode === el.querySelector(".table-view"); const flowering = () => el.querySelectorAll(".segment")[3].getBoundingClientRect().width; const before = flowering(); table.querySelectorAll("tbody > tr")[3].children[3].textContent = "6"; await new Promise(r => setTimeout(r, 600)); return { ...detached, back, followed: flowering() < before / 4 }; })()`; type Rect = { left: number; right: number; top: number; bottom: number; width: number }; type Measure = { enhanced: boolean; table: Rect; lanes: Rect[]; labels: Rect[]; plot: Rect; baseline: Rect; gridShown: boolean; segments: Array; overflow: number; }; type TableView = { tableTop: number; plotBottom: number; overflow: number; swatches: number; numbers: Array<{ textRight: number; contentRight: number }>; }; /** Shows the table and measures it; the plot's bottom is the lanes' and the axis'. */ const TABLE_VIEW = `(async () => { const el = document.querySelector("pebble-timeline"); el.setAttribute("show-table", ""); await new Promise(r => requestAnimationFrame(() => requestAnimationFrame(r))); const table = el.querySelector("table"); const numbers = [...table.querySelectorAll("tbody > tr > :nth-child(3), tbody > tr > :nth-child(4)")].map(cell => { const range = document.createRange(); range.selectNodeContents(cell); const style = getComputedStyle(cell); return { textRight: range.getBoundingClientRect().right, contentRight: cell.getBoundingClientRect().right - parseFloat(style.paddingRight) - parseFloat(style.borderRightWidth), }; }); return { tableTop: table.getBoundingClientRect().top, plotBottom: el.querySelector(".plot").getBoundingClientRect().bottom, overflow: document.documentElement.scrollWidth - document.documentElement.clientWidth, swatches: [...table.querySelectorAll("tbody > tr > :nth-child(2)")].filter(c => getComputedStyle(c, "::before").width === "10px").length, numbers, }; })()`; type Sample = { at: number; width: number; hidden: boolean; clipped: string[] }; type Clip = { samples: Sample[]; settled: { width: number; shown: boolean } }; /** * Rewrites flowering's length (4th row) to \`days\` and samples every segment at 50, 150 and * 300ms into the glide: a label that shows must show whole, inside its segment's current box. */ const clipDuring = (days: number) => `(async () => { const el = document.querySelector("pebble-timeline"); const segments = [...el.querySelectorAll(".segment")]; const flowering = segments[3]; const sample = at => ({ at, width: flowering.getBoundingClientRect().width, hidden: flowering.hasAttribute("data-unlabelled"), clipped: segments.filter(s => !s.hasAttribute("data-unlabelled")).filter(s => { const label = s.querySelector(".segment-label"); return label.scrollWidth > label.clientWidth + 0.5 || label.getBoundingClientRect().right > s.getBoundingClientRect().right + 0.5; }).map(s => s.textContent), }); el.querySelectorAll("tbody > tr")[3].children[3].textContent = "${days}"; const t0 = performance.now(); const samples = []; for (const at of [50, 150, 300]) { await new Promise(r => setTimeout(r, Math.max(0, at - (performance.now() - t0)))); samples.push(sample(Math.round(performance.now() - t0))); } await new Promise(r => setTimeout(r, 400)); return { samples, settled: { width: flowering.getBoundingClientRect().width, shown: !flowering.hasAttribute("data-unlabelled") } }; })()`; type Glide = { before: number; mid: number; after: number; expected: number; kept: boolean }; /** Rewrites the recovery row (3rd) to \`days\` and samples its segment's width before, mid-way and after. */ const glideTo = (days: number, flowering: number, midMs: number) => `(async () => { const el = document.querySelector("pebble-timeline"); const lane = el.querySelector(".lane").getBoundingClientRect().width; const segment = el.querySelectorAll(".segment")[2]; const before = segment.getBoundingClientRect().width; const rows = el.querySelectorAll("tbody > tr"); rows[2].children[3].textContent = "${days}"; rows[3].children[2].textContent = "${flowering}"; await new Promise(r => setTimeout(r, ${midMs})); const mid = segment.getBoundingClientRect().width; await new Promise(r => setTimeout(r, 500)); return { before, mid, after: segment.getBoundingClientRect().width, expected: (${days} / 119) * lane - 2, kept: el.querySelectorAll(".segment")[2] === segment }; })()`; const GLIDE = glideTo(7, 31, 150); const GLIDE_BACK = glideTo(14, 38, 30); const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms)); const checks: Array<[string, boolean, string?]> = []; const check = (name: string, ok: boolean, extra?: string) => checks.push([name, ok, extra]); const near = (a: number, b: number, tolerance = 1) => Math.abs(a - b) <= tolerance; const server = Bun.serve({ port: 0, fetch(request) { const url = new URL(request.url); if (url.pathname === "/timeline.js") return new Response(Bun.file(bundle()), { headers: { "content-type": "text/javascript" } }); const lang = url.searchParams.get("lang") as Lang | null; const page = lang ? samplePage(lang, { showTable: url.searchParams.has("show"), cols: Number(url.searchParams.get("cols") ?? 5) }) : PAGE; return new Response(page, { headers: { "content-type": "text/html; charset=utf-8" } }); }, }); const chromium = spawn(chrome(), ["--headless=new", "--disable-gpu", "--no-sandbox", "--remote-debugging-port=0", "about:blank"], { stdio: ["ignore", "ignore", "pipe"], }); /** A fresh tab at \`width\`, on \`path\`, once the timeline has drawn and fitted its labels. */ async function open(cdp: Cdp, width: number, path: string): Promise { await cdp.attach("about:blank"); await cdp.call("Emulation.setDeviceMetricsOverride", { width, height: 800, deviceScaleFactor: 1, mobile: width < 600 }); await cdp.call("Emulation.setEmulatedMedia", { features: [{ name: "prefers-reduced-motion", value: "no-preference" }] }); await cdp.call("Emulation.setFocusEmulationEnabled", { enabled: true }); await cdp.call("Page.navigate", { url: `http://localhost:${server.port}${path}` }); let ready = false; for (let attempt = 0; attempt < 50 && !ready; attempt++) { try { ready = (await cdp.eval(`customElements.whenDefined("pebble-timeline").then(() => !!document.querySelector("pebble-timeline .segment"))`)) === true; } catch { await sleep(100); // the navigation replaced the execution context } } if (!ready) throw new Error(`${width}px ${path}: the timeline never drew`); await sleep(100); // the label fit runs on the next animation frame } try { const cdp = await Cdp.connect(chromium); for (const width of [390, 1280]) { await open(cdp, width, "/"); const m = await cdp.eval(MEASURE); const at = `${width}px`; // Visually hidden: the scaled table is a few pixels, clipped to nothing (timeline.css). check(`${at} enhanced, table visually hidden`, m.enhanced && m.table.width < 8, `table ${m.table.width}px`); check(`${at} no horizontal overflow`, m.overflow <= 0, `${m.overflow}px`); // Each segment starts where its fraction of the lane says, and the gap is 2px. const lane = m.lanes[0]!; const misplaced = m.segments.filter(s => !near(s.left, lane.left + s.start * lane.width)); check(`${at} segments start on their place`, misplaced.length === 0, JSON.stringify(misplaced.map(s => s.left))); const wrongWidth = m.segments.filter(s => !near(s.width, s.size * lane.width - (s.last ? 0 : 2))); check(`${at} segments end 2px short of the next`, wrongWidth.length === 0, JSON.stringify(wrongWidth.map(s => s.width))); // Rooting starts at day 0: on the baseline gridline, where gridlines show. 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}`); else { check(`${at} narrow: track labels sit above their lanes`, m.labels.every((label, i) => label.bottom <= m.lanes[i]!.top + 0.5)); 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}`); } check(`${at} every shown label fits its segment`, m.segments.every(s => s.unlabelled || s.labelFits)); check(`${at} some labels show`, m.segments.some(s => !s.unlabelled)); const registered = await cdp.eval(REGISTERED); const names = ["--pebble-timeline-start", "--pebble-timeline-size"]; check( `${at} --pebble-timeline-start and -size are registered by an adopted @property sheet, --start and --size are not`, names.every(n => registered.names.includes(n)) && !registered.names.some(n => n === "--start" || n === "--size"), JSON.stringify(registered.names), ); check( `${at} a segment's --pebble-timeline-size computes to a typed number`, registered.typed === "CSSUnitValue" && registered.unit === "number" && near(registered.value, registered.inline, 1e-4), JSON.stringify(registered), ); check(`${at} a label does not inherit its segment's size`, registered.label === "0", JSON.stringify(registered)); 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)); // The tooltip of the first and the last segment stays inside the lane. for (const key of ["Home", "End"]) { await cdp.eval(`(() => { const plot = document.querySelector(".plot"); plot.focus(); plot.dispatchEvent(new KeyboardEvent("keydown", { key: "${key}", bubbles: true, cancelable: true })); })()`); await sleep(30); const tip = await cdp.eval(`(() => { const t = document.querySelector(".tooltip"); 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") }; })()`); const laneOfTip = key === "Home" ? m.lanes[0]! : m.lanes[m.lanes.length - 1]!; check( `${at} ${key}: tooltip open, inside its lane, above it`, tip.open && tip.left >= laneOfTip.left - 1 && tip.right <= laneOfTip.right + 1 && tip.bottom <= laneOfTip.top + 1, JSON.stringify({ tip, lane: laneOfTip }), ); } // The table view: shown under the plot (moved into the region after it), its numbers // right-aligned: each start and length cell's text ends at its content box's right. const view = await cdp.eval(TABLE_VIEW); check(`${at} show-table: the table sits under the plot`, view.tableTop >= view.plotBottom, `table top ${view.tableTop}, plot bottom ${view.plotBottom}`); check(`${at} show-table: no horizontal overflow`, view.overflow <= 0, `${view.overflow}px`); check(`${at} show-table: every segment row has a swatch`, view.swatches === m.segments.length, `${view.swatches} of ${m.segments.length}`); const offRight = view.numbers.filter(n => !near(n.textRight, n.contentRight, 1.5)); check(`${at} show-table: start and length cells are right-aligned`, view.numbers.length > 0 && offRight.length === 0, JSON.stringify(offRight)); // Labels mid-glide: flowering shrinks from 56 days to 6 (its label no longer fits), then // grows back. A label that shows is whole and inside its segment at every sample: it hides // as a shrink starts and shows again once a grow is done. for (const [days, way] of [[6, "shrink"], [56, "grow"]] as const) { const clip = await cdp.eval(clipDuring(days)); const bad = clip.samples.filter(s => s.clipped.length > 0); check(`${at} ${way}: no shown label is clipped at 50, 150, 300ms`, bad.length === 0, JSON.stringify(clip.samples)); if (way === "shrink") check(`${at} shrink: flowering's label is hidden from the start`, clip.samples[0]!.hidden, JSON.stringify(clip.samples)); check(`${at} ${way}: flowering's label is ${way === "grow" ? "shown" : "hidden"} once it settles`, clip.settled.shown === (way === "grow"), JSON.stringify(clip.settled)); } // Motion: the recovery shortens from 14 days to 7 (flowering moves up a week). Mid-way // the segment is between its old and new widths; at the end it is the new one, and the // labels are fitted again. const glide = await cdp.eval(GLIDE); check( `${at} a rewritten row's segment glides to its new width`, glide.mid < glide.before - 2 && glide.mid > glide.after + 2 && glide.kept, JSON.stringify(glide), ); check(`${at} it lands on its new width`, near(glide.after, glide.expected), JSON.stringify(glide)); const settled = await cdp.eval(MEASURE); check(`${at} after the glide, every shown label fits its segment`, settled.segments.every(s => s.unlabelled || s.labelFits)); await cdp.call("Emulation.setEmulatedMedia", { features: [{ name: "prefers-reduced-motion", value: "reduce" }] }); const jump = await cdp.eval(GLIDE_BACK); check(`${at} reduced motion: the segment jumps`, near(jump.mid, jump.expected), JSON.stringify(jump)); await cdp.closeTab(); } // The table view: English and French, 5, 7 and 9 columns, from 280 to 1280px. Words are never // split over two lines (the region scrolls instead), the page never scrolls sideways, and the // region scrolls exactly when the table is wider than it, with an edge shadow then and only then. for (const lang of ["en", "fr"] as const) for (const cols of VIEW_COLUMNS) for (const width of VIEW_WIDTHS) { await open(cdp, width, `/?lang=${lang}&cols=${cols}&show`); const v = await cdp.eval(VIEW); const at = `${width}px ${lang} ${cols} columns`; 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)); check(`${at}: no word split over two lines`, v.broken.length === 0 && v.figures === 8 && v.words > 0, JSON.stringify(v.broken)); check(`${at}: the page never scrolls sideways`, v.overflow <= 0, `${v.overflow}px`); const wider = v.table > (v.region?.client ?? v.host) + 0.5; check( `${at}: the region scrolls exactly when the table is wider (${Math.round(v.table)} in ${v.region?.client ?? "no region"})`, v.region !== null && (v.region.scroll > v.region.client) === wider, JSON.stringify(v.region), ); check(`${at}: an edge shadow exactly when the region scrolls`, v.region !== null && (v.region.shadow !== "none") === wider, v.region?.shadow); check(`${at}: the table keeps display: table, a swatch per segment row`, v.display === "table" && v.swatches === 8, `${v.display}, ${v.swatches} swatches`); await cdp.closeTab(); } // The region is the plot's next tab stop, with a visible focus ring, and the arrow keys scroll it. { await open(cdp, 320, "/?lang=en&cols=9&show"); await cdp.eval(`document.querySelector(".plot").focus()`); await cdp.press("Tab", 9); const focus = await cdp.eval(FOCUS); check(`320px 9 columns: Tab from the plot reaches the region`, focus.focused && focus.scrolls, JSON.stringify(focus)); check( `320px 9 columns: the focused region shows a focus ring`, focus.visible && focus.outline === "solid 2px" && !/rgba\(.*, 0\)$/.test(focus.color), JSON.stringify(focus), ); for (let i = 0; i < 3; i++) await cdp.press("ArrowRight", 39); await sleep(300); // a smooth scroll const scrolled = await cdp.eval(FOCUS); check(`320px 9 columns: the arrow keys scroll the region`, scrolled.focused && scrolled.scrollLeft > 0, JSON.stringify(scrolled)); await cdp.closeTab(); } // The table is the page's: on disconnect it goes back where the page had it, exactly, and the // element follows it again once reattached. { await open(cdp, 390, "/?lang=en&cols=5&show"); const trip = await cdp.eval(ROUND_TRIP); check(`disconnected: the table is the host's first child again`, trip.parent && trip.first, JSON.stringify(trip)); check(`disconnected: the host's markup is what the server sent`, trip.exact && trip.leftovers === 0, JSON.stringify(trip)); check(`reattached: the table is in the region again, and a rewritten row moves its segment`, trip.back && trip.followed, JSON.stringify(trip)); await cdp.closeTab(); } 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 ? ` ${extra}` : ""}`); if (!ok) failed++; } if (failed > 0) { console.log(`\n${failed} check(s) failed`); process.exit(1); }