oficina / estilo Public

chrome.js: fit a stacked title to its text; switch Appearance in place

The title field with a size attribute is measured at zero width
(scrollWidth, plus its end padding, borders and 2px for the caret) and
set to that width at script time, on input, resize, load and
document.fonts.ready, and after Escape restores it.

A submit of the estilo-appearance form sets data-theme on <html> as
chrome.ThemeAttr writes it (none for System), moves aria-pressed and
POSTs the same form data to the form's action with fetch, no
navigation and no spinner; a failed POST leaves the page switched and
says nothing. Without the script the form posts and redirects.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev 9d5beba58ea8a4addef657ef765f3799685b8bf4 parent d03e258
4 files changed, +232 −7
  • chrome/chrome.go +5 −2
  • chrome/chrome.js +68 −1
  • chrome/chrome.test.mjs +156 −3
  • chrome/chrome_test.go +3 −1

CI passed — run details

diff --git a/chrome/chrome.go b/chrome/chrome.go
index c424cf3..360b6ff 100644
--- a/chrome/chrome.go
+++ b/chrome/chrome.go
@@ -46,8 +46,11 @@ var templateFS embed.FS
func CSS() []byte { return append([]byte(nil), css...) }
// JS returns chrome.js, an optional classic script (defer) that closes an
-// open bar panel on Escape or an outside click, and restores the
-// editable title on Escape. Nothing depends on it.
+// open bar panel on Escape or an outside click, restores the editable
+// title on Escape, fits a stacked bar's title field to its title, and
+// switches Appearance in place (saving it with a background POST).
+// Nothing depends on it: without it the title keeps its server-rendered
+// size and Appearance posts and redirects.
func JS() []byte { return append([]byte(nil), js...) }
// Templates holds estilo-bar, estilo-bar-title, estilo-bar-title-fit,
diff --git a/chrome/chrome.js b/chrome/chrome.js
index 1f583c6..f12257c 100644
--- a/chrome/chrome.js
+++ b/chrome/chrome.js
@@ -12,7 +12,14 @@
// - a row or button that opens a dialog (command="show-modal") closes
// the menu it sat in, returns focus to that menu's title when the
// dialog closes, and opens the dialog itself on an engine without
-// invoker commands.
+// invoker commands;
+// - a stacked bar's title field (the one with a size attribute) is
+// fitted to its title: the size the server rendered is the first
+// paint's guess, and this measures the field and corrects it;
+// - Appearance switches in place: the page takes the scheme at once and
+// the choice is saved by the same POST, sent in the background, with
+// no navigation and no spinner. With scripts off the form posts and
+// redirects as it always has.
//
// The group is one group in every app, so closing it is estilo's job, not
// each app's: Sheets' menubar lost Escape and outside-click entirely when
@@ -47,6 +54,7 @@
const input = e.target.closest && e.target.closest('[estilo-bar-title-input]')
if (input) {
input.value = input.defaultValue
+ if (input.hasAttribute('size')) fit(input)
input.blur()
e.preventDefault()
return
@@ -79,4 +87,63 @@
dialog.showModal()
e.preventDefault()
})
+
+ // The stacked bar's title field is as wide as its title (Paul: "It
+ // should grow according to the title, not start out full-width"). The
+ // field measures itself: at zero width its scroll width is its own text
+ // as it draws it, start padding included; an overflowing field leaves
+ // its end padding out of that, so that and the borders go on top, with
+ // 2px for the caret at the end of the text. field-sizing: content, a
+ // canvas and a mirror span in the same font all came out short in
+ // WebKit; this did not. The width is capped by CSS (max-inline-size), so
+ // a longer title still scrolls inside the field. Nothing after the
+ // title on its row moves when it changes: the stack takes the room.
+ const FIT = '[estilo-bar-title-input][size]'
+ const CARET = 2
+ const fit = (input) => {
+ const cs = getComputedStyle(input)
+ const px = (v) => parseFloat(v) || 0
+ input.style.inlineSize = '0px'
+ const w = input.scrollWidth + px(cs.paddingInlineEnd) + px(cs.borderInlineStartWidth) + px(cs.borderInlineEndWidth)
+ input.style.inlineSize = Math.ceil(w + CARET) + 'px'
+ }
+ const fitAll = () => { Array.prototype.forEach.call(document.querySelectorAll(FIT), fit) }
+ document.addEventListener('input', (e) => {
+ const input = e.target.closest && e.target.closest(FIT)
+ if (input) fit(input)
+ })
+ // Again on resize, once everything has loaded, and once fonts settle:
+ // the first measure, at script time, can come out a few pixels short.
+ window.addEventListener('resize', fitAll)
+ window.addEventListener('load', fitAll)
+ if (document.fonts && document.fonts.ready) document.fonts.ready.then(fitAll)
+ fitAll()
+
+ // Appearance switches at once (Paul: "They're not doing an action ...
+ // they should just switch immediately"). The page takes the scheme as
+ // chrome.ThemeAttr writes it, data-theme="light" or "dark" on <html> and
+ // no attribute for System; the pressed segment moves; and the same
+ // form data is POSTed to the form's action in the background to save
+ // it. The form is data-busy="false", so the busy rule holds nothing. If
+ // the POST fails the page stays switched for this visit and says
+ // nothing; the next load shows the saved choice (spec, P3). Capture
+ // phase, like the rest: an app's own submit handler cannot swallow it.
+ document.addEventListener('submit', (e) => {
+ const form = e.target
+ const button = e.submitter
+ if (e.defaultPrevented || !form.hasAttribute || !form.hasAttribute('estilo-appearance')) return
+ if (!button || button.getAttribute('name') !== 'mode') return
+ const mode = button.value
+ if (mode !== 'light' && mode !== 'dark' && mode !== 'system') return
+ e.preventDefault()
+ const root = document.documentElement
+ if (mode === 'system') root.removeAttribute('data-theme')
+ else root.setAttribute('data-theme', mode)
+ Array.prototype.forEach.call(form.querySelectorAll('button[name="mode"]'), (b) => {
+ b.setAttribute('aria-pressed', b === button ? 'true' : 'false')
+ })
+ const body = new URLSearchParams(new FormData(form))
+ body.set('mode', mode)
+ fetch(form.getAttribute('action'), { method: 'POST', body, credentials: 'same-origin', redirect: 'manual' }).catch(() => {})
+ }, true)
})()
diff --git a/chrome/chrome.test.mjs b/chrome/chrome.test.mjs
index bf8f924..01ca9c0 100644
--- a/chrome/chrome.test.mjs
+++ b/chrome/chrome.test.mjs
@@ -33,6 +33,11 @@ class El {
}
hasAttribute(n) { return this.attrs.has(n); }
getAttribute(n) { return this.attrs.has(n) ? this.attrs.get(n) : null; }
+ setAttribute(n, v) { this.attrs.set(n, String(v)); }
+ removeAttribute(n) { this.attrs.delete(n); }
+ get value() { return this.attrs.get("value") ?? ""; }
+ set value(v) { this.attrs.set("value", v); }
+ blur() { if (doc.activeElement === this) doc.activeElement = null; }
get open() { return this.attrs.has("open"); }
set open(v) { if (v) this.attrs.set("open", ""); else this.attrs.delete("open"); }
get tabIndex() { return Number(this.attrs.get("tabindex") ?? 0); }
@@ -46,21 +51,49 @@ class El {
}
let doc;
-function load(root) {
+// load runs chrome.js against root. The returned dispatch sends an event
+// to document's listeners; dispatch.window sends one to window's.
+// globals adds to (or replaces) what the script sees: fetch,
+// getComputedStyle, document.fonts.
+function load(root, globals = {}) {
const listeners = [];
+ const winListeners = [];
doc = {
activeElement: null,
+ documentElement: new El("html"),
+ fonts: globals.fonts,
querySelector: (s) => root.querySelector(s),
+ querySelectorAll: (s) => root.querySelectorAll(s),
getElementById: () => null,
addEventListener: (type, fn, capture) => listeners.push({ type, fn, capture: !!capture }),
};
- vm.runInNewContext(src, { document: doc, HTMLButtonElement: function () {} });
- return (type, target, init = {}) => {
+ const window = { addEventListener: (type, fn) => winListeners.push({ type, fn }) };
+ vm.runInNewContext(src, {
+ document: doc,
+ window,
+ HTMLButtonElement: function () {},
+ getComputedStyle: globals.getComputedStyle ?? (() => ({})),
+ fetch: globals.fetch ?? (() => Promise.resolve()),
+ FormData: globals.FormData ?? FakeFormData,
+ URLSearchParams,
+ });
+ const dispatch = (type, target, init = {}) => {
const e = { type, target, defaultPrevented: false, preventDefault() { this.defaultPrevented = true; }, ...init };
for (const l of listeners.filter((l) => l.type === type && l.capture)) l.fn(e);
for (const l of listeners.filter((l) => l.type === type && !l.capture)) l.fn(e);
return e;
};
+ dispatch.window = (type) => { for (const l of winListeners.filter((l) => l.type === type)) l.fn({ type }); };
+ return dispatch;
+}
+
+// new FormData(form): the form's named inputs, as a submit sends them
+// (never its buttons; the submitter is the script's to add).
+class FakeFormData {
+ constructor(form) {
+ this.entries = form.querySelectorAll("input").filter((i) => i.hasAttribute("name")).map((i) => [i.getAttribute("name"), i.value]);
+ }
+ [Symbol.iterator]() { return this.entries[Symbol.iterator](); }
}
function menubar(tabindex) {
@@ -101,3 +134,123 @@ test("Escape is heard before a menu that stops propagation", () => {
dispatch("keydown", menus[0].querySelector("button"), { key: "Escape" });
assert.equal(menus[0].open, false);
});
+
+// The stacked bar's title field. Its text draws 140px wide with 6px of
+// padding each side and 1px borders. As a field does, its scroll width
+// at zero width is the text plus its start padding (146), and at any
+// other width at least that width, so a measure that skips the zeroing
+// reads the old width back instead.
+function titleField(attrs = { size: "17" }) {
+ const input = new El("input", { "estilo-bar-title-input": "", value: "Untitled document", ...attrs });
+ input.text = 140;
+ input.style = { inlineSize: "" };
+ Object.defineProperty(input, "scrollWidth", {
+ get() {
+ const w = parseFloat(this.style.inlineSize);
+ return Number.isNaN(w) || w > 0 ? Math.max(400, this.text + 6) : this.text + 6;
+ },
+ });
+ return input;
+}
+const fieldStyle = () => ({ paddingInlineEnd: "6px", borderInlineStartWidth: "1px", borderInlineEndWidth: "1px" });
+
+test("a stacked title field is fitted to its text when the script runs", () => {
+ const fitted = titleField();
+ const plain = titleField({});
+ load(new El("", {}, [fitted, plain]), { getComputedStyle: fieldStyle });
+ // 146 at zero width, + 6 end padding + 2 border + 2 for the caret.
+ assert.equal(fitted.style.inlineSize, "156px");
+ assert.equal(plain.style.inlineSize, "", "a one-row bar's title (no size) is left alone");
+});
+
+test("the title is fitted again as it is typed, on resize, at load and when fonts settle", async () => {
+ const input = titleField();
+ let settle;
+ const fonts = { ready: new Promise((r) => { settle = r; }) };
+ const dispatch = load(new El("", {}, [input]), { getComputedStyle: fieldStyle, fonts });
+ input.text = 200;
+ dispatch("input", input);
+ assert.equal(input.style.inlineSize, "216px", "input");
+ input.text = 100;
+ dispatch.window("resize");
+ assert.equal(input.style.inlineSize, "116px", "resize");
+ input.text = 120;
+ dispatch.window("load");
+ assert.equal(input.style.inlineSize, "136px", "load");
+ input.text = 130;
+ settle();
+ await fonts.ready;
+ await null;
+ assert.equal(input.style.inlineSize, "146px", "document.fonts.ready");
+});
+
+test("Escape restores the title and fits the field to it again", () => {
+ const input = titleField();
+ const dispatch = load(new El("", {}, [input]), { getComputedStyle: fieldStyle });
+ input.defaultValue = "Untitled document";
+ input.value = "Something much longer";
+ input.text = 300;
+ dispatch("input", input);
+ input.text = 140;
+ const e = dispatch("keydown", input, { key: "Escape" });
+ assert.equal(input.value, "Untitled document");
+ assert.equal(input.style.inlineSize, "156px");
+ assert.equal(e.defaultPrevented, true);
+});
+
+function appearance() {
+ 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" }));
+ 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]);
+ return { form, buttons };
+}
+
+test("Appearance switches in place and saves in the background", () => {
+ const { form, buttons } = appearance();
+ const sent = [];
+ const dispatch = load(new El("", {}, [form]), { fetch: (url, init) => { sent.push({ url, init }); return Promise.resolve({}); } });
+ doc.documentElement.setAttribute("data-theme", "dark");
+
+ let e = dispatch("submit", form, { submitter: buttons[0] });
+ assert.equal(e.defaultPrevented, true, "no navigation");
+ assert.equal(doc.documentElement.getAttribute("data-theme"), "light");
+ assert.deepEqual(buttons.map((b) => b.getAttribute("aria-pressed")), ["true", "false", "false"]);
+ assert.equal(sent.length, 1);
+ assert.equal(sent[0].url, "/appearance");
+ assert.equal(sent[0].init.method, "POST");
+ assert.equal(sent[0].init.credentials, "same-origin");
+ assert.equal(String(sent[0].init.body), "return_to=%2Fd%2Fabc&mode=light", "the same form data the form would post");
+
+ // System is no attribute at all, as chrome.ThemeAttr writes it.
+ dispatch("submit", form, { submitter: buttons[2] });
+ assert.equal(doc.documentElement.hasAttribute("data-theme"), false);
+ assert.deepEqual(buttons.map((b) => b.getAttribute("aria-pressed")), ["false", "false", "true"]);
+ assert.equal(String(sent[1].init.body), "return_to=%2Fd%2Fabc&mode=system");
+});
+
+test("a failed save leaves the page switched and says nothing", async () => {
+ const { form, buttons } = appearance();
+ const dispatch = load(new El("", {}, [form]), { fetch: () => Promise.reject(new TypeError("offline")) });
+ let unhandled = null;
+ const onUnhandled = (r) => { unhandled = r; };
+ process.on("unhandledRejection", onUnhandled);
+ dispatch("submit", form, { submitter: buttons[1] });
+ await new Promise((r) => setTimeout(r, 10));
+ process.off("unhandledRejection", onUnhandled);
+ assert.equal(unhandled, null, "the failure surfaced");
+ assert.equal(doc.documentElement.getAttribute("data-theme"), "dark");
+ assert.deepEqual(buttons.map((b) => b.getAttribute("aria-pressed")), ["false", "true", "false"]);
+});
+
+test("any other form, or a submit already handled, posts as it always has", () => {
+ const { form, buttons } = appearance();
+ const other = new El("form", { method: "post", action: "/rename" }, [new El("button", { type: "submit", name: "mode", value: "dark" })]);
+ let fetched = 0;
+ const dispatch = load(new El("", {}, [form, other]), { fetch: () => { fetched++; return Promise.resolve(); } });
+ assert.equal(dispatch("submit", other, { submitter: other.children[0] }).defaultPrevented, false);
+ const handled = dispatch("submit", form, { submitter: buttons[0], defaultPrevented: true });
+ assert.equal(handled.defaultPrevented, true);
+ assert.equal(doc.documentElement.hasAttribute("data-theme"), false);
+ // No submitter (form.submit() or an engine without it): a plain POST.
+ assert.equal(dispatch("submit", form, {}).defaultPrevented, false);
+ assert.equal(fetched, 0);
+});
diff --git a/chrome/chrome_test.go b/chrome/chrome_test.go
index ff719d3..e3c8978 100644
--- a/chrome/chrome_test.go
+++ b/chrome/chrome_test.go
@@ -427,7 +427,9 @@ func TestScriptIsClassicAndSelfContained(t *testing.T) {
// group, the menubar's menus included: Sheets' menubar lost both when
// it left rastrillo's dropdown. And an invoker row closes the menu it
// was in, with a fallback where the platform lacks invoker commands.
- for _, want := range []string{"Escape", "estilo-bar-title-input", "defaultValue", `details[name="estilo-menus"][open]`, "commandfor", "showModal"} {
+ // It fits a stacked title by the field's own scroll width, and switches
+ // Appearance in place on the form's own hook.
+ for _, want := range []string{"Escape", "estilo-bar-title-input", "defaultValue", `details[name="estilo-menus"][open]`, "commandfor", "showModal", "scrollWidth", "document.fonts", "estilo-appearance", "data-theme"} {
if !strings.Contains(src, want) {
t.Errorf("chrome.js lost %q", want)
}