oficina / estilo Public

side: keep focus across a fold, hoverable rail tooltips, no stray fold

Astra's review of contra-joins-ring, three findings inherited from Mapa.

Folding no longer drops focus: a fold button hands it to the other one,
a menu row returns it to its menu's title (moving the menubar's tab stop
as chrome.js does), and the shortcut moves it off a row the rail hides
to the lit place, or the fold.

Rail tooltips can be hovered: shown, they take the pointer, and a bridge
spans the gap from the row. Escape dismisses the focused or hovered
row's tooltip, keeping focus, until the next hover or focus. The label
stays the link's name and hover still works with scripts off.

With no frame or no Fold, side.js binds nothing and leaves Cmd or Ctrl
and backslash alone.

Tests: Node unit tests for each path, a CSS pin for both rails, and
side_browser_test.go (make test-browser), which fails 13 checks on the
previous code and passes in Chromium and WebKit.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev ff1f43c7c4f6149c9c364df5bc79b8aa3db17507 parent 09e2a13
8 files changed, +523 −41
  • Makefile +3 −2
  • side/fold.browser.mjs +138 −0
  • side/side.css +27 −5
  • side/side.go +7 −2
  • side/side.js +83 −15
  • side/side.test.mjs +93 −17
  • side/side_browser_test.go +145 −0
  • side/side_test.go +27 −0

CI passed — run details

CI log
=== modcache ===
all modules verified
=== vet ===
CGO_ENABLED=0 go vet ./...
CGO_ENABLED=0 go vet -tags browser ./...
=== fmt ===
=== build ===
CGO_ENABLED=0 go build -buildvcs=false ./...
=== go-test ===
CGO_ENABLED=0 go test -count=1 ./...
ok  	amadan.net/oficina/estilo.git/base	0.006s
ok  	amadan.net/oficina/estilo.git/brand	0.004s
ok  	amadan.net/oficina/estilo.git/busy	0.009s
ok  	amadan.net/oficina/estilo.git/callui	0.004s
ok  	amadan.net/oficina/estilo.git/chrome	2.845s
?   	amadan.net/oficina/estilo.git/cmd/oficina-notices	[no test files]
ok  	amadan.net/oficina/estilo.git/colophon	0.023s
ok  	amadan.net/oficina/estilo.git/credits	0.005s
ok  	amadan.net/oficina/estilo.git/credits/catalog	0.004s
ok  	amadan.net/oficina/estilo.git/desk	0.004s
ok  	amadan.net/oficina/estilo.git/googleimport	1.482s
ok  	amadan.net/oficina/estilo.git/homeconnect	0.005s
ok  	amadan.net/oficina/estilo.git/internal/lint	0.007s
?   	amadan.net/oficina/estilo.git/internal/tokencheck	[no test files]
ok  	amadan.net/oficina/estilo.git/menu	0.012s
ok  	amadan.net/oficina/estilo.git/savestatus	0.108s
ok  	amadan.net/oficina/estilo.git/side	0.139s
ok  	amadan.net/oficina/estilo.git/sky	0.032s
ok  	amadan.net/oficina/estilo.git/theme	0.012s
diff --git a/Makefile b/Makefile
index 9a2d2ba..327653a 100644
--- a/Makefile
+++ b/Makefile
@@ -75,8 +75,9 @@ test-go:
# ESTILO_BROWSERS, default chromium,webkit). Today that is theme's
# no-flash check for the chrome text, by pixels
# (theme/fonts_browser_test.go), the stacked bar's title field fitted to
-# its whole title (chrome/title_browser_test.go) and the Google import
-# chooser (googleimport/browser_test.go). It runs the whole suite with
+# its whole title (chrome/title_browser_test.go), the Google import
+# chooser (googleimport/browser_test.go) and the side's fold focus and
+# rail tooltips (side/side_browser_test.go). It runs the whole suite with
# the tag.
# An engine that will not launch fails it; it never skips to a pass.
test-browser:
diff --git a/side/fold.browser.mjs b/side/fold.browser.mjs
new file mode 100644
index 0000000..05c484d
--- /dev/null
+++ b/side/fold.browser.mjs
@@ -0,0 +1,138 @@
+// fold.browser.mjs: drive the side's fold and rail tooltips in each
+// engine and report what happened. Driven by side_browser_test.go (go
+// test -tags browser ./side), which serves the pages and makes every
+// assertion; this file only drives the browsers and reports, as
+// {name, got, want} pairs.
+//
+// ESTILO_PLAYWRIGHT=<path to the playwright package> \
+// node fold.browser.mjs <job JSON>
+import { createRequire } from 'node:module'
+
+const require = createRequire(import.meta.url)
+const pw = require(process.env.ESTILO_PLAYWRIGHT || 'playwright')
+const job = JSON.parse(process.argv[2])
+
+// focused names the focused element by what a test can tell apart.
+const focused = () => {
+ const a = document.activeElement
+ if (!a || a === document.body) return 'body'
+ for (const n of ['estilo-side-fold-to', 'estilo-side-holds']) if (a.hasAttribute(n)) return n + '=' + a.getAttribute(n)
+ if (a.hasAttribute('estilo-side-page')) return 'page ' + a.getAttribute('href')
+ return a.tagName.toLowerCase() + (a.id ? '#' + a.id : '')
+}
+const state = () => document.querySelector('[estilo-side-frame]')?.getAttribute('estilo-side-frame') ?? 'no frame'
+const tip = (href) => getComputedStyle(document.querySelector(`[estilo-side-item][href="${href}"]:not([hidden]) [estilo-side-label]`)).opacity
+
+// The shortcut's event, as the page saw it after every listener ran.
+const watchKeys = () => {
+ window.__keys = []
+ window.addEventListener('keydown', (e) => { if (e.key === '\\') window.__keys.push(e.defaultPrevented ? 'prevented' : 'left alone') })
+}
+
+async function run(browser, origin, checks) {
+ const check = (name, got, want) => checks.push({ name, got: String(got), want: String(want) })
+ const open = async (query, width = 1440) => {
+ const page = await browser.newPage({ viewport: { width, height: 700 } })
+ await page.goto(origin + '/' + query)
+ await page.waitForFunction(() => document.readyState === 'complete')
+ return page
+ }
+
+ // 1. The fold's own buttons, by keyboard: focus moves to the other one.
+ let page = await open('?state=open')
+ await page.focus('[estilo-side-fold-to="rail"]')
+ await page.keyboard.press('Enter')
+ check('Hide: state', await page.evaluate(state), 'rail')
+ check('Hide: focus', await page.evaluate(focused), 'estilo-side-fold-to=open')
+ await page.keyboard.press('Enter')
+ check('Show again by Enter: state', await page.evaluate(state), 'open')
+ check('Show again by Enter: focus', await page.evaluate(focused), 'estilo-side-fold-to=rail')
+ await page.close()
+
+ // 2. A menu row folds, closes its menu and returns focus to its title.
+ page = await open('?state=open')
+ await page.click('#view > summary')
+ await page.focus('#view-fold')
+ await page.keyboard.press('Enter')
+ check('menu row: state', await page.evaluate(state), 'rail')
+ check('menu row: menu closed', await page.evaluate(() => document.querySelector('#view').open), false)
+ check('menu row: focus', await page.evaluate(focused), 'summary')
+ await page.close()
+
+ // 3. The shortcut from a page row the rail hides: focus goes to the lit
+ // place; and back again from the rail.
+ page = await open('?state=open')
+ await page.evaluate(watchKeys)
+ await page.focus('[estilo-side-page][href="/p/a"]')
+ await page.keyboard.press('Control+Backslash')
+ check('shortcut from a page row: state', await page.evaluate(state), 'rail')
+ check('shortcut from a page row: focus', await page.evaluate(focused), 'estilo-side-holds=rail')
+ await page.keyboard.press('Control+Backslash')
+ check('shortcut from the rail place: state', await page.evaluate(state), 'open')
+ check('shortcut from the rail place: focus', await page.evaluate(focused), 'estilo-side-holds=open')
+ check('shortcut: event', await page.evaluate(() => window.__keys.join()), 'prevented,prevented')
+ await page.close()
+
+ // 4. Tooltips, on the explicit rail and the width's rail.
+ for (const [label, query, width] of [['rail', '?state=rail', 1440], ['width rail', '?state=', 1000]]) {
+ page = await open(query, width)
+ // Keyboard focus shows it; Escape hides it and leaves focus.
+ await page.focus('[estilo-side-item][href="/search"]')
+ await page.keyboard.press('Shift')
+ check(`${label}: focus shows the tooltip`, await page.evaluate(tip, '/search'), '1')
+ await page.keyboard.press('Escape')
+ check(`${label}: Escape hides it`, await page.evaluate(tip, '/search'), '0')
+ check(`${label}: Escape keeps focus`, await page.evaluate(() => document.activeElement.getAttribute('href')), '/search')
+ // Pointer: hover the row, cross the gap to the tooltip, stay on it.
+ const row = await page.locator('[estilo-side-item][href="/search"]').boundingBox()
+ const y = row.y + row.height / 2
+ await page.mouse.move(row.x + row.width / 2, y)
+ check(`${label}: hover shows it again`, await page.evaluate(tip, '/search'), '1')
+ const box = await page.evaluate(() => {
+ const r = document.querySelector('[estilo-side-item][href="/search"] [estilo-side-label]').getBoundingClientRect()
+ return { x: r.x, y: r.y, w: r.width, h: r.height }
+ })
+ let lost = 0
+ for (let x = row.x + row.width - 2; x <= box.x + box.w / 2; x += 2) {
+ await page.mouse.move(x, box.y + box.h / 2)
+ if (await page.evaluate(tip, '/search') !== '1') lost++
+ }
+ check(`${label}: crossing to the tooltip keeps it`, lost, 0)
+ check(`${label}: the pointer is on the tooltip`, await page.evaluate(({ x, y }) =>
+ !!document.elementFromPoint(x, y)?.closest('[estilo-side-label]'), { x: box.x + box.w / 2, y: box.y + box.h / 2 }), true)
+ await page.keyboard.press('Escape')
+ check(`${label}: Escape hides it under the pointer`, await page.evaluate(tip, '/search'), '0')
+ await page.mouse.move(row.x + row.width / 2, y + 200)
+ await page.mouse.move(row.x + row.width / 2, y)
+ check(`${label}: a new hover shows it`, await page.evaluate(tip, '/search'), '1')
+ check(`${label}: the label names the link`, await page.getByRole('link', { name: 'Search', exact: true }).count(), 1)
+ await page.close()
+ }
+
+ // 5. No fold, and no frame: the shortcut does nothing and leaves the
+ // key event alone.
+ for (const [label, query] of [['no fold', '?state=open&fold=no'], ['no frame', '?frame=no']]) {
+ page = await open(query)
+ await page.evaluate(watchKeys)
+ await page.keyboard.press('Control+Backslash')
+ check(`${label}: state`, await page.evaluate(state), label === 'no fold' ? 'open' : 'no frame')
+ check(`${label}: event`, await page.evaluate(() => window.__keys.join()), 'left alone')
+ await page.close()
+ }
+}
+
+const results = []
+for (const engine of job.engines) {
+ const result = { engine, error: '', checks: [] }
+ results.push(result)
+ let browser
+ try {
+ browser = await pw[engine].launch()
+ await run(browser, job.origin, result.checks)
+ } catch (err) {
+ result.error = String(err && err.stack || err)
+ } finally {
+ if (browser) await browser.close()
+ }
+}
+process.stdout.write(JSON.stringify(results))
diff --git a/side/side.css b/side/side.css
index 37e788c..bb03b9d 100644
--- a/side/side.css
+++ b/side/side.css
@@ -122,7 +122,11 @@ kbd[estilo-side-key] {
in the accessibility tree and is the tooltip. The tooltip is fixed
where its row puts it (its static position, insets left auto), then
moved out beside the 40px row: a fixed box escapes the side's
- scrolling, which clipped an absolute one. ── */
+ scrolling, which clipped an absolute one. The tooltip is part of its
+ row, so the row stays hovered while the pointer is on it, and a
+ bridge (its ::before) spans the 10px gap so the pointer can cross to
+ it. side.js dismisses it on Escape (data-estilo-side-tip="off") until
+ the next hover or focus. ── */
@media (min-width: 800px) {
[estilo-side-frame~="rail"] [estilo-side] { padding-inline: 8px; align-items: center; }
[estilo-side-frame~="rail"] [estilo-side-item] {
@@ -162,14 +166,23 @@ kbd[estilo-side-key] {
color: var(--rst-surface);
font-size: 12px;
font-weight: 500;
+ overflow: visible;
pointer-events: none;
opacity: 0;
clip-path: inset(50%);
}
- [estilo-side-frame~="rail"] [estilo-side-item]:hover [estilo-side-label],
- [estilo-side-frame~="rail"] [estilo-side-item]:focus-visible [estilo-side-label] {
+ [estilo-side-frame~="rail"] [estilo-side-label]::before {
+ content: "";
+ position: absolute;
+ inset-block: 0;
+ inset-inline-end: 100%;
+ inline-size: 12px;
+ }
+ [estilo-side-frame~="rail"] [estilo-side-item]:not([data-estilo-side-tip="off"]):hover [estilo-side-label],
+ [estilo-side-frame~="rail"] [estilo-side-item]:not([data-estilo-side-tip="off"]):focus-visible [estilo-side-label] {
opacity: 1;
clip-path: none;
+ pointer-events: auto;
}
}
@media (min-width: 800px) and (max-width: 79.99rem) {
@@ -211,14 +224,23 @@ kbd[estilo-side-key] {
color: var(--rst-surface);
font-size: 12px;
font-weight: 500;
+ overflow: visible;
pointer-events: none;
opacity: 0;
clip-path: inset(50%);
}
- [estilo-side-frame]:not([estilo-side-frame~="open"], [estilo-side-frame~="rail"]) [estilo-side-item]:hover [estilo-side-label],
- [estilo-side-frame]:not([estilo-side-frame~="open"], [estilo-side-frame~="rail"]) [estilo-side-item]:focus-visible [estilo-side-label] {
+ [estilo-side-frame]:not([estilo-side-frame~="open"], [estilo-side-frame~="rail"]) [estilo-side-label]::before {
+ content: "";
+ position: absolute;
+ inset-block: 0;
+ inset-inline-end: 100%;
+ inline-size: 12px;
+ }
+ [estilo-side-frame]:not([estilo-side-frame~="open"], [estilo-side-frame~="rail"]) [estilo-side-item]:not([data-estilo-side-tip="off"]):hover [estilo-side-label],
+ [estilo-side-frame]:not([estilo-side-frame~="open"], [estilo-side-frame~="rail"]) [estilo-side-item]:not([data-estilo-side-tip="off"]):focus-visible [estilo-side-label] {
opacity: 1;
clip-path: none;
+ pointer-events: auto;
}
}
diff --git a/side/side.go b/side/side.go
index de552e5..837377d 100644
--- a/side/side.go
+++ b/side/side.go
@@ -48,8 +48,13 @@ func CSS() []byte { return append([]byte(nil), css...) }
// JS returns side.js, an optional classic script (defer) that folds the
// side in place: any control with data-estilo-side-fold (the fold's own
// buttons, or an app's menu row) and ⌘\ or Ctrl+\ switch the frame
-// between open and rail and set the fold's cookie. Without it the fold
-// posts and the next page is drawn folded.
+// between open and rail and set the fold's cookie. Focus stays on
+// screen: a fold button hands it to the other one, a menu row to its
+// menu's title, and a row the rail hides to the lit place (or the
+// fold). Escape dismisses a rail tooltip until the next hover or focus.
+// A page with no frame or no Fold has nothing to fold, and the script
+// leaves the shortcut alone. Without it the fold posts and the next page
+// is drawn folded.
func JS() []byte { return append([]byte(nil), js...) }
// Templates holds estilo-side, estilo-side-item, estilo-side-fold and the
diff --git a/side/side.js b/side/side.js
index 18b1c7d..af79536 100644
--- a/side/side.js
+++ b/side/side.js
@@ -2,10 +2,16 @@
// side). Optional: without it the fold's form posts the new state and the
// next page is drawn folded. It sets the same cookie the form does
// (data-estilo-side-cookie on the fold's form), so the next page is drawn
-// the same. Mapa's, copied.
+// the same. Mapa's, copied, with focus kept and the rail's tooltips
+// dismissable (Astra's review of contra-joins-ring).
+//
+// A page with no frame, or a side drawn with no fold (Side.Fold nil),
+// has nothing to fold: the script binds nothing and leaves ⌘\ alone.
(function () {
"use strict";
+ var ITEM = "[estilo-side-item]";
+
// shown is what the side shows now: the frame's state, or what CSS
// chose by width when there is none (open from 80rem).
function shown(frame) {
@@ -15,36 +21,98 @@
return window.matchMedia("(min-width: 80rem)").matches ? "open" : "rail";
}
- function fold() {
- var frame = document.querySelector("[estilo-side-frame]");
- if (!frame) return;
- var next = shown(frame) === "open" ? "rail" : "open";
- frame.setAttribute("estilo-side-frame", next);
- var form = document.querySelector("form[estilo-side-fold][data-estilo-side-cookie]");
- if (!form) return;
- document.cookie = form.getAttribute("data-estilo-side-cookie") + "=" + next +
- "; path=/; max-age=31536000; samesite=lax" +
- (location.protocol === "https:" ? "; secure" : "");
+ // returnTo focuses a menu's title; in a menubar with a roving tab stop
+ // the stop moves with it, as chrome.js does on Escape.
+ function returnTo(title) {
+ title.focus();
+ var bar = title.closest("[estilo-menubar]");
+ if (!bar) return;
+ var titles = Array.prototype.slice.call(bar.querySelectorAll("[estilo-menubar-title]"));
+ if (!titles.some(function (t) { return t.hasAttribute("tabindex"); })) return;
+ titles.forEach(function (t) { t.tabIndex = t === title ? 0 : -1; });
+ }
+
+ // replacement is the control that takes focus from active when the side
+ // turns to next, or null when active stays on screen. The fold's two
+ // buttons swap; a place drawn twice (estilo-side-holds) swaps for its
+ // other copy; a page row, which the rail hides, gives way to the lit
+ // place that holds the page, or else to the fold.
+ function replacement(side, form, active, next) {
+ if (!active || !side.contains(active)) return null;
+ var other = next === "rail" ? "open" : "rail";
+ if (active.hasAttribute("estilo-side-fold-to")) {
+ return form.querySelector('[estilo-side-fold-to="' + other + '"]');
+ }
+ var holds = active.getAttribute("estilo-side-holds");
+ if (holds && holds !== next) {
+ var href = active.getAttribute("href");
+ return Array.prototype.filter.call(side.querySelectorAll('[estilo-side-holds="' + next + '"]'),
+ function (copy) { return copy.getAttribute("href") === href; })[0] || null;
+ }
+ if (next === "rail" && active.hasAttribute("estilo-side-page")) {
+ return side.querySelector('[estilo-side-holds="rail"]') ||
+ form.querySelector('[estilo-side-fold-to="open"]');
+ }
+ return null;
}
function start() {
+ var frame = document.querySelector("[estilo-side-frame]");
+ var side = frame && frame.querySelector("[estilo-side]");
+ var form = side && side.querySelector("form[estilo-side-fold]");
+ if (!form) return;
+
+ // fold turns the side; from is the control that asked, if any.
+ function fold(from) {
+ var active = document.activeElement;
+ var next = shown(frame) === "open" ? "rail" : "open";
+ var target = replacement(side, form, active, next);
+ frame.setAttribute("estilo-side-frame", next);
+ var cookie = form.getAttribute("data-estilo-side-cookie");
+ if (cookie) {
+ document.cookie = cookie + "=" + next + "; path=/; max-age=31536000; samesite=lax" +
+ (location.protocol === "https:" ? "; secure" : "");
+ }
+ var menu = from && from.closest("details");
+ if (menu) {
+ // A menu row: the menu closes and focus goes back to its title.
+ menu.open = false;
+ var title = menu.querySelector("summary");
+ if (title) returnTo(title);
+ } else if (target) {
+ target.focus();
+ }
+ }
+
// The fold's own buttons, and any control an app marks (a View menu
// row): each folds in place instead of posting.
document.querySelectorAll("[data-estilo-side-fold]").forEach(function (control) {
control.disabled = false;
control.addEventListener("click", function (event) {
event.preventDefault();
- var menu = control.closest("details");
- if (menu) menu.open = false;
- fold();
+ fold(control);
});
});
+
document.addEventListener("keydown", function (event) {
if ((event.metaKey || event.ctrlKey) && event.key === "\\") {
event.preventDefault();
- fold();
+ fold(null);
+ } else if (event.key === "Escape" && !event.defaultPrevented) {
+ // Escape dismisses the rail's tooltip, on the focused row and the
+ // hovered one, and leaves focus where it is. It stays dismissed
+ // until a new hover or focus.
+ var active = document.activeElement;
+ side.querySelectorAll(ITEM).forEach(function (item) {
+ if (item === active || item.matches(":hover")) item.setAttribute("data-estilo-side-tip", "off");
+ });
}
});
+ side.querySelectorAll(ITEM).forEach(function (item) {
+ var again = function () { item.removeAttribute("data-estilo-side-tip"); };
+ item.addEventListener("pointerenter", again);
+ item.addEventListener("focus", again);
+ });
}
if (document.readyState === "loading") {
diff --git a/side/side.test.mjs b/side/side.test.mjs
index 2140cb4..2cc34bc 100644
--- a/side/side.test.mjs
+++ b/side/side.test.mjs
@@ -1,6 +1,7 @@
// side.js behaviour, run under Node against a minimal DOM: just enough
-// elements, attribute selectors and event dispatch for the script's own
-// selectors.
+// elements, attribute selectors, focus and event dispatch for the
+// script's own selectors. It has no CSS, so what is visible is the
+// browser test's (side_browser_test.go, make test-browser).
import assert from "node:assert/strict";
import fs from "node:fs";
import test from "node:test";
@@ -8,12 +9,14 @@ import vm from "node:vm";
const src = fs.readFileSync(new URL("./side.js", import.meta.url), "utf8");
-// A compound selector: tag, [attr] and [attr="value"], comma-separated.
+// A compound selector: tag, [attr] and [attr="value"], comma-separated,
+// and :hover, which the fake answers from el.hovered.
function matches(el, selector) {
return selector.split(",").some((part) => {
- const m = part.trim().match(/^([a-z]*)((?:\[[^\]]+\])*)$/);
+ const m = part.trim().match(/^([a-z]*)((?:\[[^\]]+\])*)(:hover)?$/);
if (!m) throw new Error("unsupported selector " + part);
if (m[1] && el.tag !== m[1]) return false;
+ if (m[3] && !el.hovered) return false;
for (const [, name, value] of m[2].matchAll(/\[([^=\]]+)(?:="([^"]*)")?\]/g)) {
if (!el.attrs.has(name)) return false;
if (value !== undefined && el.attrs.get(name) !== value) return false;
@@ -22,6 +25,7 @@ function matches(el, selector) {
});
}
+let doc;
class El {
constructor(tag, attrs = {}, children = []) {
this.tag = tag;
@@ -29,59 +33,85 @@ class El {
this.children = children;
this.parent = null;
this.listeners = [];
+ this.hovered = false;
this.disabled = "disabled" in attrs;
for (const c of children) c.parent = this;
}
+ 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 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); }
+ set tabIndex(v) { this.attrs.set("tabindex", String(v)); }
addEventListener(type, fn) { this.listeners.push({ type, fn }); }
+ fire(type) { for (const l of this.listeners.filter((l) => l.type === type)) l.fn({ type }); }
+ focus() { doc.activeElement = this; this.fire("focus"); }
click() {
const e = { type: "click", defaultPrevented: false, preventDefault() { this.defaultPrevented = true; } };
for (const l of this.listeners.filter((l) => l.type === "click")) l.fn(e);
return e;
}
+ matches(s) { return matches(this, s); }
+ contains(o) { for (let e = o; e; e = e.parent) if (e === this) return true; return false; }
*walk() { for (const c of this.children) { yield c; yield* c.walk(); } }
querySelectorAll(s) { return [...this.walk()].filter((e) => matches(e, s)); }
querySelector(s) { return this.querySelectorAll(s)[0] ?? null; }
closest(s) { for (let e = this; e; e = e.parent) if (e.tag && matches(e, s)) return e; return null; }
}
-function page(state, { wide = true, protocol = "https:" } = {}) {
- const hide = new El("button", { "estilo-side-fold-to": "rail", "data-estilo-side-fold": "" });
- const show = new El("button", { "estilo-side-fold-to": "open", "data-estilo-side-fold": "" });
+// page draws a side as the template does after Light(): Home holds the
+// page, which is lit on its own row under Pinned. fold: false draws it
+// with no fold (Side.Fold nil); frame: false draws no frame at all.
+function page(state, { wide = true, protocol = "https:", fold = true, frame = true } = {}) {
+ const item = (attrs) => new El("a", { "estilo-side-item": "", ...attrs }, [new El("span", { "estilo-side-label": "" })]);
+ const homeOpen = item({ "estilo-side-holds": "open", href: "/" });
+ const homeRail = item({ "estilo-side-holds": "rail", href: "/", "aria-current": "page", hidden: "" });
+ const search = item({ href: "/search" });
+ const pinned = item({ "estilo-side-page": "", href: "/p/a", "aria-current": "page" });
+ const hide = new El("button", { "estilo-side-item": "", "estilo-side-fold-to": "rail", "data-estilo-side-fold": "" });
+ const show = new El("button", { "estilo-side-item": "", "estilo-side-fold-to": "open", "data-estilo-side-fold": "" });
const form = new El("form", { "estilo-side-fold": "", "data-estilo-side-cookie": "app-side" }, [hide, show]);
+ const foot = new El("div", { "estilo-side-foot": "" }, fold ? [form] : []);
+ const side = new El("nav", { "estilo-side": "" }, [homeOpen, homeRail, search, pinned, foot]);
+ const title = new El("summary", { "estilo-menubar-title": "", tabindex: "-1" });
+ const file = new El("summary", { "estilo-menubar-title": "", tabindex: "0" });
const row = new El("button", { "estilo-menu-item": "", "data-estilo-side-fold": "", disabled: "" });
- const menu = new El("details", { open: "" }, [row]);
- const frame = new El("div", { "estilo-side-frame": state }, [new El("nav", { "estilo-side": "" }, [form])]);
- const root = new El("", {}, [menu, frame]);
+ const menu = new El("details", { open: "" }, [title, new El("div", { "estilo-menu": "" }, [row])]);
+ const bar = new El("nav", { "estilo-menubar": "" }, [new El("details", {}, [file]), menu]);
+ const framed = new El("div", { "estilo-side-frame": state }, [side]);
+ const root = new El("", {}, frame ? [bar, framed] : [bar]);
const listeners = [];
- const document = {
+ doc = {
readyState: "complete",
cookie: "",
+ activeElement: null,
querySelector: (s) => root.querySelector(s),
querySelectorAll: (s) => root.querySelectorAll(s),
addEventListener: (type, fn) => listeners.push({ type, fn }),
};
const window = { matchMedia: () => ({ matches: wide }) };
- vm.runInNewContext(src, { document, window, location: { protocol } });
+ vm.runInNewContext(src, { document: doc, window, location: { protocol } });
const key = (init) => {
const e = { type: "keydown", defaultPrevented: false, preventDefault() { this.defaultPrevented = true; }, ...init };
for (const l of listeners.filter((l) => l.type === "keydown")) l.fn(e);
return e;
};
- return { document, frame, hide, show, row, menu, key };
+ return { doc, frame: framed, hide, show, row, menu, title, file, key, homeOpen, homeRail, search, pinned };
}
-test("the fold folds in place and sets the form's cookie", () => {
+test("the fold folds in place, sets the form's cookie and moves focus to the other button", () => {
const p = page("open");
+ p.hide.focus();
const e = p.hide.click();
assert.equal(e.defaultPrevented, true);
assert.equal(p.frame.getAttribute("estilo-side-frame"), "rail");
- assert.equal(p.document.cookie, "app-side=rail; path=/; max-age=31536000; samesite=lax; secure");
+ assert.equal(p.doc.cookie, "app-side=rail; path=/; max-age=31536000; samesite=lax; secure");
+ assert.equal(p.doc.activeElement, p.show);
p.show.click();
assert.equal(p.frame.getAttribute("estilo-side-frame"), "open");
+ assert.equal(p.doc.activeElement, p.hide);
});
test("with no state the width decides what is shown", () => {
@@ -91,15 +121,19 @@ test("with no state the width decides what is shown", () => {
const narrow = page("", { wide: false, protocol: "http:" });
narrow.show.click();
assert.equal(narrow.frame.getAttribute("estilo-side-frame"), "open");
- assert.equal(narrow.document.cookie, "app-side=open; path=/; max-age=31536000; samesite=lax");
+ assert.equal(narrow.doc.cookie, "app-side=open; path=/; max-age=31536000; samesite=lax");
});
-test("an app's menu row folds, is enabled and closes its menu", () => {
+test("a menu row folds, is enabled, closes its menu and returns focus to its title", () => {
const p = page("open");
assert.equal(p.row.disabled, false);
+ p.row.focus();
p.row.click();
assert.equal(p.menu.open, false);
assert.equal(p.frame.getAttribute("estilo-side-frame"), "rail");
+ assert.equal(p.doc.activeElement, p.title);
+ assert.equal(p.title.getAttribute("tabindex"), "0");
+ assert.equal(p.file.getAttribute("tabindex"), "-1");
});
test("Cmd or Ctrl and backslash fold; other keys do not", () => {
@@ -111,3 +145,45 @@ test("Cmd or Ctrl and backslash fold; other keys do not", () => {
assert.equal(p.key({ key: "\\" }).defaultPrevented, false);
assert.equal(p.frame.getAttribute("estilo-side-frame"), "rail");
});
+
+test("the shortcut moves focus off a row the rail hides, and back", () => {
+ const p = page("open");
+ p.pinned.focus();
+ p.key({ key: "\\", ctrlKey: true });
+ assert.equal(p.doc.activeElement, p.homeRail);
+ p.key({ key: "\\", ctrlKey: true });
+ assert.equal(p.doc.activeElement, p.homeOpen);
+ p.search.focus();
+ p.key({ key: "\\", ctrlKey: true });
+ assert.equal(p.doc.activeElement, p.search, "a row still shown keeps focus");
+});
+
+test("with no fold the shortcut does nothing and leaves the key alone", () => {
+ const p = page("open", { fold: false });
+ const e = p.key({ key: "\\", ctrlKey: true });
+ assert.equal(e.defaultPrevented, false);
+ assert.equal(p.frame.getAttribute("estilo-side-frame"), "open");
+ assert.equal(p.row.disabled, true, "a menu row stays as drawn");
+});
+
+test("with no frame the shortcut does nothing and leaves the key alone", () => {
+ const p = page("open", { frame: false });
+ assert.equal(p.key({ key: "\\", metaKey: true }).defaultPrevented, false);
+ assert.equal(p.row.disabled, true);
+});
+
+test("Escape dismisses the tooltip of the focused and the hovered row until a new hover or focus", () => {
+ const p = page("rail");
+ p.search.focus();
+ p.homeRail.hovered = true;
+ const e = p.key({ key: "Escape" });
+ assert.equal(e.defaultPrevented, false);
+ assert.equal(p.doc.activeElement, p.search);
+ assert.equal(p.search.getAttribute("data-estilo-side-tip"), "off");
+ assert.equal(p.homeRail.getAttribute("data-estilo-side-tip"), "off");
+ assert.equal(p.pinned.getAttribute("data-estilo-side-tip"), null);
+ p.homeRail.fire("pointerenter");
+ assert.equal(p.homeRail.getAttribute("data-estilo-side-tip"), null);
+ p.search.focus();
+ assert.equal(p.search.getAttribute("data-estilo-side-tip"), null);
+});
diff --git a/side/side_browser_test.go b/side/side_browser_test.go
new file mode 100644
index 0000000..dadeb8f
--- /dev/null
+++ b/side/side_browser_test.go
@@ -0,0 +1,145 @@
+//go:build browser
+
+// The side's fold and rail tooltips in real engines: focus kept across a
+// fold, tooltips that can be hovered and dismissed, and no fold where
+// there is none. Not part of `make test`: it needs Node 22+ and
+// Playwright with its browsers (ESTILO_PLAYWRIGHT names the playwright
+// package directory when it is not resolvable from here; ESTILO_BROWSERS
+// picks engines, default "chromium,webkit"). Run it with `make
+// test-browser`. An engine that will not launch fails the test.
+//
+// 2026-11-21, Astra's review of contra-joins-ring: folding left focus on
+// BODY, the rail's tooltip vanished as the pointer crossed to it and
+// Escape did not dismiss it, and ⌘\ folded a side drawn with no fold.
+// The Node test's DOM has neither focus nor CSS; this has both.
+package side
+
+import (
+ "bytes"
+ "encoding/json"
+ "fmt"
+ "html/template"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "os/exec"
+ "strings"
+ "testing"
+
+ "amadan.net/oficina/estilo.git/base"
+ "amadan.net/oficina/estilo.git/chrome"
+ "amadan.net/oficina/estilo.git/menu"
+ "amadan.net/oficina/estilo.git/theme"
+ "github.com/carlosframework/rastrillo/ui"
+)
+
+const sidePage = `<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8">
+<meta name="viewport" content="width=device-width, initial-scale=1">
+<link rel="stylesheet" href="/tokens.css">
+<link rel="stylesheet" href="/theme.css">
+<link rel="stylesheet" href="/base.css">
+<link rel="stylesheet" href="/menu.css">
+<link rel="stylesheet" href="/chrome.css">
+<link rel="stylesheet" href="/side.css">
+<script defer src="/side.js"></script>
+</head>
+<body>
+<nav estilo-menubar aria-label="Menus"><details estilo-menubar-menu name="estilo-menus" id="view"><summary estilo-menubar-title>View</summary><div estilo-menu><button estilo-menu-item type="button" data-estilo-side-fold id="view-fold"><span estilo-menu-label>Hide or show sidebar</span></button></div></details></nav>
+%s
+</body>
+</html>
+`
+
+type sideCheck struct {
+ Engine string `json:"engine"`
+ Error string `json:"error"`
+ Checks []struct {
+ Name string `json:"name"`
+ Got string `json:"got"`
+ Want string `json:"want"`
+ } `json:"checks"`
+}
+
+func TestFoldAndTooltipsInBrowsers(t *testing.T) {
+ if _, err := exec.LookPath("node"); err != nil {
+ t.Fatal("node is required (Node 22+)")
+ }
+ tmpl := template.Must(template.ParseFS(Templates(), "templates/*.html"))
+ icon := template.HTML(`<svg viewBox="0 0 24 24" aria-hidden="true"><rect x="3" y="3" width="18" height="18"/></svg>`)
+ mux := http.NewServeMux()
+ mux.HandleFunc("GET /{$}", func(w http.ResponseWriter, r *http.Request) {
+ q := r.URL.Query()
+ s := Side{Label: "App", State: q.Get("state"),
+ Places: []Item{{Href: "/", Label: "Home", Icon: icon, Current: true},
+ {Href: "/search", Label: "Search", Icon: icon, Key: "⌘K"}},
+ Sections: []Section{{Heading: "Pinned", Items: []Item{
+ {Href: "/p/a", Label: "Alpha", Icon: icon, Current: true}}}},
+ }
+ if q.Get("fold") != "no" {
+ s.Fold = &Fold{Action: "/fold", Return: "/", Hide: "Hide sidebar", Show: "Show sidebar", Cookie: "app-side"}
+ }
+ s.Light()
+ var body bytes.Buffer
+ if q.Get("frame") == "no" {
+ body.WriteString(`<main id="main"><a href="/x" id="plain">x</a></main>`)
+ } else {
+ fmt.Fprintf(&body, `<div estilo-side-frame="%s">`, template.HTMLEscapeString(s.State))
+ if err := tmpl.ExecuteTemplate(&body, "estilo-side", s); err != nil {
+ t.Error(err)
+ }
+ body.WriteString(`<main id="main"><p>Body.</p></main></div>`)
+ }
+ w.Header().Set("Content-Type", "text/html; charset=utf-8")
+ fmt.Fprintf(w, sidePage, body.String())
+ })
+ assets := map[string][]byte{"/tokens.css": ui.TokensCSS(), "/theme.css": theme.CSS(), "/base.css": base.CSS(),
+ "/menu.css": menu.CSS(), "/chrome.css": chrome.CSS(), "/side.css": CSS(), "/side.js": JS()}
+ for path, body := range assets {
+ mux.HandleFunc("GET "+path, func(w http.ResponseWriter, r *http.Request) {
+ ct := "text/css; charset=utf-8"
+ if strings.HasSuffix(path, ".js") {
+ ct = "text/javascript; charset=utf-8"
+ }
+ w.Header().Set("Content-Type", ct)
+ _, _ = w.Write(body)
+ })
+ }
+ srv := httptest.NewServer(mux)
+ t.Cleanup(srv.Close)
+
+ engines := strings.Split(os.Getenv("ESTILO_BROWSERS"), ",")
+ if engines[0] == "" {
+ engines = []string{"chromium", "webkit"}
+ }
+ job, _ := json.Marshal(map[string]any{"origin": srv.URL, "engines": engines})
+ cmd := exec.Command("node", "fold.browser.mjs", string(job))
+ cmd.Stderr = os.Stderr
+ raw, err := cmd.Output()
+ if err != nil {
+ t.Fatalf("node fold.browser.mjs: %v", err)
+ }
+ var results []sideCheck
+ if err := json.Unmarshal(raw, &results); err != nil {
+ t.Fatalf("driver output: %v\n%s", err, raw)
+ }
+ if len(results) != len(engines) {
+ t.Fatalf("%d engines asked for, %d reported", len(engines), len(results))
+ }
+ for _, r := range results {
+ if r.Error != "" {
+ t.Errorf("%s: %s", r.Engine, r.Error)
+ continue
+ }
+ if len(r.Checks) == 0 {
+ t.Errorf("%s reported no checks", r.Engine)
+ }
+ for _, c := range r.Checks {
+ if c.Got != c.Want {
+ t.Errorf("%s: %s: got %q, want %q", r.Engine, c.Name, c.Got, c.Want)
+ }
+ }
+ }
+}
diff --git a/side/side_test.go b/side/side_test.go
index 1a78183..cbd8394 100644
--- a/side/side_test.go
+++ b/side/side_test.go
@@ -211,3 +211,30 @@ func TestScriptBehaviour(t *testing.T) {
t.Fatalf("node --test side.test.mjs: %v\n%s", err, out)
}
}
+
+// Both rails (the folded one and the width's) let the pointer onto the
+// tooltip across the gap from its row, and let Escape dismiss it
+// (Astra, contra-joins-ring). The browser test proves the behaviour.
+func TestRailTooltipsCanBeHoveredAndDismissed(t *testing.T) {
+ src := string(CSS())
+ for _, rail := range []string{
+ `[estilo-side-frame~="rail"]`,
+ `[estilo-side-frame]:not([estilo-side-frame~="open"], [estilo-side-frame~="rail"])`,
+ } {
+ for _, want := range []string{
+ rail + ` [estilo-side-label]::before {`,
+ rail + ` [estilo-side-item]:not([data-estilo-side-tip="off"]):hover [estilo-side-label],`,
+ rail + ` [estilo-side-item]:not([data-estilo-side-tip="off"]):focus-visible [estilo-side-label] {
+ opacity: 1;
+ clip-path: none;
+ pointer-events: auto;`,
+ } {
+ if !strings.Contains(src, want) {
+ t.Errorf("side.css lost %q", want)
+ }
+ }
+ }
+ if strings.Count(src, "overflow: visible;") != 2 {
+ t.Error("each rail's tooltip must let its bridge out (overflow: visible)")
+ }
+}