| 1 | // chrome.js behaviour, run under Node against a minimal DOM: just enough |
| 2 | // elements, attribute selectors and event dispatch for the script's own |
| 3 | // selectors. Most of the browser proof is in the adopting apps (Sheets' |
| 4 | // tools/drive/menu-actions.mjs, Docs' menu tests); the stacked title's |
| 5 | // fit is also measured in Chromium and WebKit by make test-browser |
| 6 | // (title_browser_test.go). |
| 7 | import assert from "node:assert/strict"; |
| 8 | import fs from "node:fs"; |
| 9 | import test from "node:test"; |
| 10 | import vm from "node:vm"; |
| 11 | |
| 12 | const src = fs.readFileSync(new URL("./chrome.js", import.meta.url), "utf8"); |
| 13 | |
| 14 | // A compound selector: tag, [attr], [attr="value"] and [attr~="token"], |
| 15 | // comma-separated. |
| 16 | function matches(el, selector) { |
| 17 | return selector.split(",").some((part) => { |
| 18 | const m = part.trim().match(/^([a-z]*)((?:\[[^\]]+\])*)$/); |
| 19 | if (!m) throw new Error("unsupported selector " + part); |
| 20 | if (m[1] && el.tag !== m[1]) return false; |
| 21 | for (const [, name, op, value] of m[2].matchAll(/\[([^~=\]]+)(?:(~?=)"([^"]*)")?\]/g)) { |
| 22 | if (!el.attrs.has(name)) return false; |
| 23 | if (op === "=" && el.attrs.get(name) !== value) return false; |
| 24 | if (op === "~=" && !el.attrs.get(name).split(/\s+/).includes(value)) return false; |
| 25 | } |
| 26 | return true; |
| 27 | }); |
| 28 | } |
| 29 | |
| 30 | class El { |
| 31 | constructor(tag, attrs = {}, children = []) { |
| 32 | this.tag = tag; |
| 33 | this.attrs = new Map(Object.entries(attrs)); |
| 34 | this.children = children; |
| 35 | this.parent = null; |
| 36 | for (const c of children) c.parent = this; |
| 37 | } |
| 38 | hasAttribute(n) { return this.attrs.has(n); } |
| 39 | getAttribute(n) { return this.attrs.has(n) ? this.attrs.get(n) : null; } |
| 40 | setAttribute(n, v) { this.attrs.set(n, String(v)); } |
| 41 | removeAttribute(n) { this.attrs.delete(n); } |
| 42 | get value() { return this.attrs.get("value") ?? ""; } |
| 43 | set value(v) { this.attrs.set("value", v); } |
| 44 | blur() { if (doc.activeElement === this) doc.activeElement = null; } |
| 45 | get open() { return this.attrs.has("open"); } |
| 46 | set open(v) { if (v) this.attrs.set("open", ""); else this.attrs.delete("open"); } |
| 47 | get tabIndex() { return Number(this.attrs.get("tabindex") ?? 0); } |
| 48 | set tabIndex(v) { this.attrs.set("tabindex", String(v)); } |
| 49 | *walk() { for (const c of this.children) { yield c; yield* c.walk(); } } |
| 50 | querySelectorAll(s) { return [...this.walk()].filter((e) => matches(e, s)); } |
| 51 | querySelector(s) { return this.querySelectorAll(s)[0] ?? null; } |
| 52 | closest(s) { for (let e = this; e; e = e.parent) if (e.tag && matches(e, s)) return e; return null; } |
| 53 | contains(o) { for (let e = o; e; e = e.parent) if (e === this) return true; return false; } |
| 54 | focus() { doc.activeElement = this; } |
| 55 | } |
| 56 | |
| 57 | let doc; |
| 58 | // load runs chrome.js against root. The returned dispatch sends an event |
| 59 | // to document's listeners; dispatch.window sends one to window's. |
| 60 | // globals adds to (or replaces) what the script sees: fetch, |
| 61 | // getComputedStyle, document.fonts. |
| 62 | function load(root, globals = {}) { |
| 63 | const listeners = []; |
| 64 | const winListeners = []; |
| 65 | doc = { |
| 66 | activeElement: null, |
| 67 | documentElement: Object.assign(new El("html"), { style: fakeStyle() }), |
| 68 | fonts: globals.fonts, |
| 69 | getAnimations: globals.getAnimations, |
| 70 | querySelector: (s) => root.querySelector(s), |
| 71 | querySelectorAll: (s) => root.querySelectorAll(s), |
| 72 | getElementById: () => null, |
| 73 | addEventListener: (type, fn, capture) => listeners.push({ type, fn, capture: !!capture }), |
| 74 | }; |
| 75 | const window = { addEventListener: (type, fn) => winListeners.push({ type, fn }), matchMedia: globals.matchMedia }; |
| 76 | vm.runInNewContext(src, { |
| 77 | document: doc, |
| 78 | window, |
| 79 | HTMLButtonElement: function () {}, |
| 80 | getComputedStyle: globals.getComputedStyle ?? (() => ({})), |
| 81 | fetch: globals.fetch ?? (() => Promise.resolve()), |
| 82 | FormData: globals.FormData ?? FakeFormData, |
| 83 | URLSearchParams, |
| 84 | ResizeObserver: globals.ResizeObserver, |
| 85 | AbortController, |
| 86 | }); |
| 87 | const dispatch = (type, target, init = {}) => { |
| 88 | const e = { type, target, defaultPrevented: false, preventDefault() { this.defaultPrevented = true; }, ...init }; |
| 89 | for (const l of listeners.filter((l) => l.type === type && l.capture)) l.fn(e); |
| 90 | for (const l of listeners.filter((l) => l.type === type && !l.capture)) l.fn(e); |
| 91 | return e; |
| 92 | }; |
| 93 | dispatch.window = (type) => { for (const l of winListeners.filter((l) => l.type === type)) l.fn({ type }); }; |
| 94 | return dispatch; |
| 95 | } |
| 96 | |
| 97 | function fakeStyle() { |
| 98 | const props = new Map(); |
| 99 | return { props, setProperty: (k, v) => props.set(k, v), removeProperty: (k) => props.delete(k), getPropertyValue: (k) => props.get(k) ?? "" }; |
| 100 | } |
| 101 | |
| 102 | // new FormData(form): the form's named inputs, as a submit sends them |
| 103 | // (never its buttons; the submitter is the script's to add). |
| 104 | class FakeFormData { |
| 105 | constructor(form) { |
| 106 | this.entries = form.querySelectorAll("input").filter((i) => i.hasAttribute("name")).map((i) => [i.getAttribute("name"), i.value]); |
| 107 | } |
| 108 | [Symbol.iterator]() { return this.entries[Symbol.iterator](); } |
| 109 | } |
| 110 | |
| 111 | function menubar(tabindex) { |
| 112 | const titles = ["File", "Edit", "Tools"].map((name, i) => new El("summary", { "estilo-menubar-title": "", ...(tabindex ? { tabindex: i === 0 ? "0" : "-1" } : {}) })); |
| 113 | const menus = titles.map((t) => new El("details", { "estilo-menubar-menu": "", name: "estilo-menus" }, [t, new El("div", { "estilo-menu": "" }, [new El("button", { "estilo-menu-item": "" })])])); |
| 114 | return { root: new El("", {}, [new El("nav", { "estilo-menubar": "" }, menus)]), titles, menus }; |
| 115 | } |
| 116 | |
| 117 | // Astra, estilo #11: Escape closed the menu and focused its title, but |
| 118 | // the menubar's roving tab stop stayed on File, so Tab then Shift+Tab |
| 119 | // landed on File instead of the menu you had been in. |
| 120 | test("Escape moves a menubar's roving tab stop to the title it focuses", () => { |
| 121 | const { root, titles, menus } = menubar(true); |
| 122 | const dispatch = load(root); |
| 123 | menus[2].open = true; |
| 124 | const item = menus[2].querySelector("button"); |
| 125 | const e = dispatch("keydown", item, { key: "Escape" }); |
| 126 | assert.equal(menus[2].open, false); |
| 127 | assert.equal(doc.activeElement, titles[2]); |
| 128 | assert.deepEqual(titles.map((t) => t.getAttribute("tabindex")), ["-1", "-1", "0"]); |
| 129 | assert.equal(e.defaultPrevented, true); |
| 130 | }); |
| 131 | |
| 132 | test("a menubar without a roving tab stop is left without one", () => { |
| 133 | const { root, titles, menus } = menubar(false); |
| 134 | const dispatch = load(root); |
| 135 | menus[1].open = true; |
| 136 | dispatch("keydown", menus[1].querySelector("button"), { key: "Escape" }); |
| 137 | assert.equal(doc.activeElement, titles[1]); |
| 138 | assert.deepEqual(titles.map((t) => t.getAttribute("tabindex")), [null, null, null]); |
| 139 | }); |
| 140 | |
| 141 | test("Escape is heard before a menu that stops propagation", () => { |
| 142 | const { root, menus } = menubar(true); |
| 143 | const dispatch = load(root); |
| 144 | menus[0].open = true; |
| 145 | // The capture listener runs first, whatever the target's own handlers do. |
| 146 | dispatch("keydown", menus[0].querySelector("button"), { key: "Escape" }); |
| 147 | assert.equal(menus[0].open, false); |
| 148 | }); |
| 149 | |
| 150 | // The stacked bar's title field. Its text draws 140px wide with 6px of |
| 151 | // padding each side and 1px borders; with no inline size set it is 400px |
| 152 | // (its size attribute's guess). The engines measure a field's scroll and |
| 153 | // client widths in different boxes (measured, Chromium 158 and WebKit |
| 154 | // 27.2): WebKit's are its padding box, so at zero width its scroll width |
| 155 | // is the text and both paddings (152) and its client width the paddings |
| 156 | // (12); Chromium's are its content box, so at zero width its scroll width |
| 157 | // is the text alone (140) and its client width 0. At any width the scroll |
| 158 | // width is at least the client width, so a measure that skips the zeroing |
| 159 | // reads the old width back. The fitted field must give the text its 140px |
| 160 | // and the caret 2px in both: 156px. Measuring only WebKit's box, as this |
| 161 | // fake once did, let a fit that added only the borders through, and in |
| 162 | // Chromium that cut the title's last letter off. |
| 163 | const PAD = 6, BORDER = 1; |
| 164 | function titleField(attrs = { size: "17" }, engine = "webkit") { |
| 165 | const input = new El("input", { "estilo-bar-title-input": "", value: "Untitled document", ...attrs }); |
| 166 | input.text = 140; |
| 167 | input.style = { inlineSize: "" }; |
| 168 | const box = () => { |
| 169 | const w = parseFloat(input.style.inlineSize); |
| 170 | return Math.max(Number.isNaN(w) ? 400 : w, 2 * (PAD + BORDER)); // border-box: never under its own frame |
| 171 | }; |
| 172 | const inner = engine === "chromium" ? 2 * (PAD + BORDER) : 2 * BORDER; // what lies outside the measured box |
| 173 | const drawn = engine === "chromium" ? 0 : 2 * PAD; // the paddings, when the measured box holds them |
| 174 | Object.defineProperties(input, { |
| 175 | offsetWidth: { get: () => box() }, |
| 176 | clientWidth: { get: () => box() - inner }, |
| 177 | scrollWidth: { get: () => Math.max(box() - inner, input.text + drawn) }, |
| 178 | }); |
| 179 | return input; |
| 180 | } |
| 181 | const fieldStyle = () => ({ paddingInlineStart: PAD + "px", paddingInlineEnd: PAD + "px", borderInlineStartWidth: BORDER + "px", borderInlineEndWidth: BORDER + "px" }); |
| 182 | // The room the field gives its text: its content box. |
| 183 | const room = (input) => parseFloat(input.style.inlineSize) - 2 * (PAD + BORDER); |
| 184 | |
| 185 | for (const engine of ["webkit", "chromium"]) { |
| 186 | test(`a stacked title field is fitted to its text when the script runs (${engine})`, () => { |
| 187 | const fitted = titleField(undefined, engine); |
| 188 | const plain = titleField({}, engine); |
| 189 | load(new El("", {}, [fitted, plain]), { getComputedStyle: fieldStyle }); |
| 190 | // The text's 140, the frame's 14, and 2 for the caret. |
| 191 | assert.equal(fitted.style.inlineSize, "156px"); |
| 192 | assert.ok(room(fitted) >= fitted.text, "the whole title has room"); |
| 193 | assert.equal(plain.style.inlineSize, "", "a one-row bar's title (no size) is left alone"); |
| 194 | }); |
| 195 | } |
| 196 | |
| 197 | test("the title is fitted again as it is typed, on resize, at load and when fonts settle", async () => { |
| 198 | for (const engine of ["webkit", "chromium"]) { |
| 199 | const input = titleField(undefined, engine); |
| 200 | let settle; |
| 201 | const fonts = { ready: new Promise((r) => { settle = r; }) }; |
| 202 | const dispatch = load(new El("", {}, [input]), { getComputedStyle: fieldStyle, fonts }); |
| 203 | input.text = 200; |
| 204 | dispatch("input", input); |
| 205 | assert.equal(input.style.inlineSize, "216px", engine + " input"); |
| 206 | input.text = 100; |
| 207 | dispatch.window("resize"); |
| 208 | assert.equal(input.style.inlineSize, "116px", engine + " resize"); |
| 209 | input.text = 120; |
| 210 | dispatch.window("load"); |
| 211 | assert.equal(input.style.inlineSize, "136px", engine + " load"); |
| 212 | input.text = 130; |
| 213 | settle(); |
| 214 | await fonts.ready; |
| 215 | await null; |
| 216 | assert.equal(input.style.inlineSize, "146px", engine + " document.fonts.ready"); |
| 217 | } |
| 218 | }); |
| 219 | |
| 220 | test("Escape restores the title and fits the field to it again", () => { |
| 221 | const input = titleField(undefined, "chromium"); |
| 222 | const dispatch = load(new El("", {}, [input]), { getComputedStyle: fieldStyle }); |
| 223 | input.defaultValue = "Untitled document"; |
| 224 | input.value = "Something much longer"; |
| 225 | input.text = 300; |
| 226 | dispatch("input", input); |
| 227 | input.text = 140; |
| 228 | const e = dispatch("keydown", input, { key: "Escape" }); |
| 229 | assert.equal(input.value, "Untitled document"); |
| 230 | assert.equal(input.style.inlineSize, "156px"); |
| 231 | assert.equal(e.defaultPrevented, true); |
| 232 | }); |
| 233 | |
| 234 | function appearance() { |
| 235 | const buttons = ["light", "dark", "system"].map((m) => new El("button", { "estilo-menu-item": "", type: "submit", name: "mode", value: m, "aria-pressed": m === "dark" ? "true" : "false" })); |
| 236 | const form = new El("form", { "estilo-appearance": "", method: "post", action: "/appearance", "data-busy": "false" }, [new El("input", { type: "hidden", name: "return_to", value: "/d/abc" }), ...buttons]); |
| 237 | return { form, buttons }; |
| 238 | } |
| 239 | |
| 240 | test("Appearance switches in place and saves in the background", () => { |
| 241 | const { form, buttons } = appearance(); |
| 242 | const sent = []; |
| 243 | const dispatch = load(new El("", {}, [form]), { fetch: (url, init) => { sent.push({ url, init }); return Promise.resolve({}); } }); |
| 244 | doc.documentElement.setAttribute("data-theme", "dark"); |
| 245 | |
| 246 | let e = dispatch("submit", form, { submitter: buttons[0] }); |
| 247 | assert.equal(e.defaultPrevented, true, "no navigation"); |
| 248 | assert.equal(doc.documentElement.getAttribute("data-theme"), "light"); |
| 249 | assert.deepEqual(buttons.map((b) => b.getAttribute("aria-pressed")), ["true", "false", "false"]); |
| 250 | assert.equal(sent.length, 1); |
| 251 | assert.equal(sent[0].url, "/appearance"); |
| 252 | assert.equal(sent[0].init.method, "POST"); |
| 253 | assert.equal(sent[0].init.credentials, "same-origin"); |
| 254 | // Not followed: the server's answer is a 303 back to the page, and a |
| 255 | // followed redirect would fetch the whole page again for nothing. |
| 256 | assert.equal(sent[0].init.redirect, "manual"); |
| 257 | assert.equal(String(sent[0].init.body), "return_to=%2Fd%2Fabc&mode=light", "the same form data the form would post"); |
| 258 | |
| 259 | // System is no attribute at all, as chrome.ThemeAttr writes it. |
| 260 | dispatch("submit", form, { submitter: buttons[2] }); |
| 261 | assert.equal(doc.documentElement.hasAttribute("data-theme"), false); |
| 262 | assert.deepEqual(buttons.map((b) => b.getAttribute("aria-pressed")), ["false", "false", "true"]); |
| 263 | assert.equal(String(sent[1].init.body), "return_to=%2Fd%2Fabc&mode=system"); |
| 264 | }); |
| 265 | |
| 266 | // Two quick clicks are two POSTs with no order between them, so the |
| 267 | // server could save the first choice last. Each switch aborts the save |
| 268 | // before it; the aborted one fails quietly, like any failed save. |
| 269 | test("a second switch aborts the first save, quietly", async () => { |
| 270 | const { form, buttons } = appearance(); |
| 271 | const sent = []; |
| 272 | const fetch = (url, init) => { |
| 273 | sent.push(init); |
| 274 | return new Promise((resolve, reject) => { |
| 275 | if (init.signal) init.signal.addEventListener("abort", () => reject(new DOMException("aborted", "AbortError"))); |
| 276 | }); |
| 277 | }; |
| 278 | const dispatch = load(new El("", {}, [form]), { fetch }); |
| 279 | let unhandled = null; |
| 280 | const onUnhandled = (r) => { unhandled = r; }; |
| 281 | process.on("unhandledRejection", onUnhandled); |
| 282 | dispatch("submit", form, { submitter: buttons[0] }); |
| 283 | dispatch("submit", form, { submitter: buttons[1] }); |
| 284 | await new Promise((r) => setTimeout(r, 10)); |
| 285 | process.off("unhandledRejection", onUnhandled); |
| 286 | assert.equal(sent.length, 2); |
| 287 | assert.ok(sent[0].signal, "the save can be aborted"); |
| 288 | assert.equal(sent[0].signal.aborted, true, "the first save is aborted by the second"); |
| 289 | assert.equal(sent[1].signal.aborted, false, "the last save stands"); |
| 290 | assert.equal(String(sent[1].body), "return_to=%2Fd%2Fabc&mode=dark"); |
| 291 | assert.equal(unhandled, null, "the aborted save surfaced"); |
| 292 | assert.equal(doc.documentElement.getAttribute("data-theme"), "dark"); |
| 293 | }); |
| 294 | |
| 295 | // A switch lands everything mid-transition in the new scheme at once, as |
| 296 | // rastrillo's shim does for its own scheme menu (land()): transitions are |
| 297 | // cancelled, which puts each on its end value, after the attribute has |
| 298 | // changed (getAnimations() flushes style, starting the new ones); an |
| 299 | // animation, a spinner, is left running. |
| 300 | test("a switch lands running transitions and leaves animations alone", () => { |
| 301 | const { form, buttons } = appearance(); |
| 302 | const cancelled = []; |
| 303 | let themeAtCall; |
| 304 | const transition = { transitionProperty: "background-color", cancel() { cancelled.push("transition"); } }; |
| 305 | const spinner = { animationName: "spin", cancel() { cancelled.push("spinner"); } }; |
| 306 | const dispatch = load(new El("", {}, [form]), { |
| 307 | getAnimations: () => { themeAtCall = doc.documentElement.getAttribute("data-theme"); return [transition, spinner]; }, |
| 308 | }); |
| 309 | dispatch("submit", form, { submitter: buttons[1] }); |
| 310 | assert.equal(themeAtCall, "dark", "the transitions were read before the scheme changed"); |
| 311 | assert.deepEqual(cancelled, ["transition"]); |
| 312 | }); |
| 313 | |
| 314 | test("a failed save leaves the page switched and says nothing", async () => { |
| 315 | const { form, buttons } = appearance(); |
| 316 | const dispatch = load(new El("", {}, [form]), { fetch: () => Promise.reject(new TypeError("offline")) }); |
| 317 | let unhandled = null; |
| 318 | const onUnhandled = (r) => { unhandled = r; }; |
| 319 | process.on("unhandledRejection", onUnhandled); |
| 320 | dispatch("submit", form, { submitter: buttons[1] }); |
| 321 | await new Promise((r) => setTimeout(r, 10)); |
| 322 | process.off("unhandledRejection", onUnhandled); |
| 323 | assert.equal(unhandled, null, "the failure surfaced"); |
| 324 | assert.equal(doc.documentElement.getAttribute("data-theme"), "dark"); |
| 325 | assert.deepEqual(buttons.map((b) => b.getAttribute("aria-pressed")), ["false", "true", "false"]); |
| 326 | }); |
| 327 | |
| 328 | test("any other form, or a submit already handled, posts as it always has", () => { |
| 329 | const { form, buttons } = appearance(); |
| 330 | const other = new El("form", { method: "post", action: "/rename" }, [new El("button", { type: "submit", name: "mode", value: "dark" })]); |
| 331 | let fetched = 0; |
| 332 | const dispatch = load(new El("", {}, [form, other]), { fetch: () => { fetched++; return Promise.resolve(); } }); |
| 333 | assert.equal(dispatch("submit", other, { submitter: other.children[0] }).defaultPrevented, false); |
| 334 | const handled = dispatch("submit", form, { submitter: buttons[0], defaultPrevented: true }); |
| 335 | assert.equal(handled.defaultPrevented, true); |
| 336 | assert.equal(doc.documentElement.hasAttribute("data-theme"), false); |
| 337 | // No submitter (form.submit() or an engine without it): a plain POST. |
| 338 | assert.equal(dispatch("submit", form, {}).defaultPrevented, false); |
| 339 | assert.equal(fetched, 0); |
| 340 | }); |
| 341 | |
| 342 | // A stacked bar below 800px whose menu row wraps is taller than the 85px |
| 343 | // CSS publishes; the script publishes its real height there, and stands |
| 344 | // down from 800px, where the header's height is the variable itself. |
| 345 | test("below 800px a stacked bar publishes its real height", () => { |
| 346 | const header = new El("header", { "estilo-bar": "stacked" }); |
| 347 | let height = 117; |
| 348 | header.getBoundingClientRect = () => ({ height }); |
| 349 | const media = { matches: true, listeners: [], addEventListener(t, fn) { this.listeners.push(fn); } }; |
| 350 | let observed = null; |
| 351 | class RO { constructor(fn) { this.fn = fn; } observe(el) { observed = { el, fn: this.fn }; } } |
| 352 | load(new El("", {}, [header]), { matchMedia: () => media, ResizeObserver: RO }); |
| 353 | assert.equal(observed.el, header); |
| 354 | observed.fn(); |
| 355 | const style = doc.documentElement.style; |
| 356 | assert.equal(style.getPropertyValue("--estilo-bar-block-size"), "117px"); |
| 357 | height = 85; |
| 358 | observed.fn(); |
| 359 | assert.equal(style.getPropertyValue("--estilo-bar-block-size"), "85px"); |
| 360 | // Wide: the CSS value stands, with nothing written over it. |
| 361 | media.matches = false; |
| 362 | for (const fn of media.listeners) fn(); |
| 363 | assert.equal(style.props.has("--estilo-bar-block-size"), false); |
| 364 | }); |
| 365 | |
| 366 | test("a bar that is not stacked publishes nothing", () => { |
| 367 | let observed = false; |
| 368 | class RO { observe() { observed = true; } } |
| 369 | load(new El("", {}, [new El("header", { "estilo-bar": "sticky" })]), { matchMedia: () => ({ matches: true }), ResizeObserver: RO }); |
| 370 | assert.equal(observed, false); |
| 371 | }); |
| 372 | |