oficina / mapa Public

Import page: one vertical rhythm, and the status no longer repeats its heading

Paul, 2026-11-22, on the import page mid-run: "The spacing is all over
the place here." The heading sat as far from its text as the section
sat from the page header, the grey note rested on the Stop button, and
Resume and Start over stacked flush. Every gap was the browser's
default h2 and p margin.

The page and its confirm pages are now a stack: Fiesta's rst-stack,
rst-section and rst-actions (rastrillo/fiesta feat/stack-rhythm),
copied into mapa.css as mapa-stack, mapa-section and mapa-action-row
ahead of Fiesta's release, so adopting Fiesta's is a rename. The stack
zeroes its children's margins and spaces them from one table on the
scale: 0.5rem after a heading, 0.75rem between blocks, 1rem before an
actions row, 1.5rem before a section or after the page header. The
status box keeps role="status" around the heading, progress and note;
the buttons sit after it, side by side.

The progress no longer repeats the heading (Luna, 2026-11-22,
copy-review/import-status): "Reading Notion: 4 pages so far." is
"Pages read so far: 4.", "Writing pages: 2 of 5." is "2 of 5 so far.",
and "Run complete" gains a line saying what the report below holds.

TestImportPageRhythm runs Fiesta's rhythm audit (vendored in
testdata/rhythm until Fiesta releases check/rhythm) over every state
of the page and the three confirm pages: every gap between blocks on
the scale, no text within 0.5rem of a control, and every heading
closer to its content than to what precedes it. On the old markup it
fails in every state.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Squashed from fix/import-spacing into main.
Paul Campbell pushed by claude agent, operated by paul@keymail.dev c66189f5c06f0e6f17e8a25a655ab3de1316cc1b parent 2510b47
11 files changed, +658 −18
  • copy-review/import-status/luna-prompt.md +60 −0
  • copy-review/import-status/luna-review.md +9 −0
  • copy-review/import-status/result.json +54 −0
  • copy-review/import-status/strings.json +34 −0
  • internal/mapa/static/mapa.css +99 −0
  • internal/mapa/templates/import.html +22 −15
  • internal/mapa/templates/import_confirm.html +3 −1
  • internal/mapatest/import_browser_test.go +2 −2
  • internal/mapatest/import_rhythm_browser_test.go +125 −0
  • internal/mapatest/testdata/rhythm/README +5 −0
  • internal/mapatest/testdata/rhythm/rhythm.js +245 −0

CI passed — run details

CI log
=== editor ===
cd editor && npm ci --no-audit --no-fund --loglevel=error

added 16 packages in 317ms
cd editor && node build-bundles.mjs
wrote internal/mapa/static/editor.115ddee5d3f54787.js (354112 bytes, 111.2KB gzipped; L12 budget 120KB)
cd editor && node --test
✔ a badge is named for what it does, starting with its visible word (0.90925ms)
✔ first words stop at five words or forty characters (0.153015ms)
✔ the field keeps one trimmed line, without brackets (0.283507ms)
✔ the field holds at most MaxAlt bytes, cut at a character (1.012864ms)
✔ days and weeks move across months and years (1.021399ms)
✔ a month keeps the day, or takes the month's last (0.680416ms)
✔ the grid is six weeks from Monday, as the month calendar draws it (0.446421ms)
✔ the grid starts the week where the locale does (0.574999ms)
✔ the keys move a day, a week, a month and a year (0.247921ms)
✔ the picked day is the chip [[ makes for a date (12.295477ms)
✔ Insert → Today's date still puts today in at once (1.385667ms)
✔ / offers Date, the picker, and Today's date beside it (0.242231ms)
✔ after a ! the chip goes in after a space, never as an embed (2.287804ms)
✔ where the Markdown would read the chip differently, it is refused (2.610756ms)
✔ over a selection the chip goes after it and the words stay (2.69882ms)
✔ today is the day in the viewer's zone (16.797428ms)
✔ every offered locale has cases (0.783376ms)
✔ dates.mjs writes every date Go writes, byte for byte (2.893079ms)
✔ a chip, the month and the week, in three locales (0.364548ms)
✔ dates.json is what ICU gives, byte for byte (522.602957ms)
✔ L1: mounting then serialising gives cleanBody(body), byte for byte (96.731149ms)
ℹ 871 bodies
✔ L1: mounting a stored body adds nothing, and saving it writes nothing new (96.471386ms)
✔ L2: one edited block changes only that block's bytes; undo gives the body back (153.808254ms)
ℹ 858 single-block edits
✔ L2: inserting or deleting a block changes bytes only at the new seams, by Join (151.483963ms)
ℹ 866 inserts, 817 deletes
✔ L3: seeded edits keep the document and its Markdown saying the same thing (4561.067232ms)
ℹ 20904 edits over 871 bodies
✔ L3: Link to a page makes exactly one chip, and changes nothing else (1165.429809ms)
ℹ 4532 links over 871 bodies; refused: {"A page link can’t hold another link or a line break. Select plain words.":918,"A page link can’t show [ or ]]. Select words without them.":404,"Select some words to link them to a page.":174,"Linked here, the Markdown around these words would read differently: a ! before them makes an embed, and a stray ` or * pairs up. Select other words.":18}
✔ L3: a picked date is one more date chip, or refused where a letter would be too (1163.979613ms)
ℹ over 871 bodies: {"inserted":5158,"spaced":23,"refused":45,"unstable":9}
✔ linear: trailing spaces (37.716281ms)
✔ linear: trailing whitespace (27.16594ms)
✔ linear: unclosed web links (20.320779ms)
✔ linear: web links with no address (32.858065ms)
✔ linear: unclosed wiki links (30.194052ms)
✔ linear: unclosed embeds (32.175356ms)
✔ linear: closes only (8.424267ms)
✔ the selected words become the chip's shown text (12.124829ms)
✔ words that are the title make a plain [[Title]] (3.771854ms)
✔ spaces at the selection's edges stay outside the chip (1.033712ms)
✔ a date makes a date link, in a heading, an item and a quote (5.202796ms)
✔ bold words lose their bold: a chip carries no marks in Mapa's Markdown (1.454064ms)
✔ only the linked block's bytes change, and undo gives the body back (2.487015ms)
✔ a selection across blocks, over a chip or a break, or of brackets is refused (1.451048ms)
✔ a target the words cannot be linked to as typed is refused (0.339411ms)
✔ ⌘L: over a selection it opens Page link; with none it types [[; in code it does nothing (2.734727ms)
✔ web-linked words are refused: the address would be lost (review M4) (1.598282ms)
✔ words whose Markdown would read otherwise are refused (review M3) (1.962709ms)
✔ ⌘A then ⌘L says why, instead of doing nothing (review low 1) (0.389575ms)
✔ linkCheck says why it refuses (review low 2) (1.383403ms)
✔ golden file has bodies (1.696345ms)
✔ markup.mjs parses every body into Go's blocks, byte offsets and all (37.463679ms)
✔ markup.mjs strips and spans every block as Go does (56.668607ms)
✔ the schema's toDOM draws every body as Go renders it (80.139223ms)
✔ emphasis draws the four pinned outputs (24.643108ms)
✔ a body ends in the editor's empty paragraph (0.328732ms)
✔ the editor labels date chips as Go does, in every locale L4 holds (11.905661ms)
✔ a POST that never answers is aborted after the timeout (21.708641ms)
✔ a keepalive POST carries no signal, and an answer clears the timer (2.883431ms)
✔ autosave sends only what differs, and the tab owns the draft it wrote (12.861508ms)
✔ an offered draft never commits by itself; Save commits it (1.871991ms)
✔ reload, then close: sessionStorage says the draft is this tab's own (0.689783ms)
✔ closing carries text not yet sent, and the cap leaves it out (31.013375ms)
✔ clean rebase: applied, the caret survives, the base moves by the rebase POST (4.277656ms)
✔ the block under the caret is the teammate's too, and undo brings back yours (3.098873ms)
✔ typing mid-flight: the merge is not applied and the base does not move (1.265644ms)
✔ a merge the editor cannot represent stops after three tries (4.052487ms)
✔ a conflict is shown, locks the editor's own commits, and Resolve settles it (1.496393ms)
✔ leaving: a conflict stays with the choice; a failed flush offers Leave anyway; a stored draft leaves (1.880017ms)
✔ a stale tab shows the newer draft, offered, and never overwrites it (1.123228ms)
✔ the first scratch commit: empty creates nothing, then one page, then drafts on it (1.007724ms)
✔ noBase and gone lead to the existing choices (1.185855ms)
✔ a commit that merged is applied when nothing was typed since (1.127016ms)
✔ back from the cache: nothing unsaved reloads, unsaved text autosaves at once (9.632394ms)
✔ an own draft committed meanwhile goes on as a new draft (2.038531ms)
✔ a reload keeps a stored draft; unsent text still commits (0.73101ms)
✔ a page deleted mid-edit: what is typed is still stored as the draft, and nothing commits (H1) (1.63457ms)
✔ an offered draft committed in another tab: typing goes on as a new draft (H1) (4.474982ms)
✔ a commit reply without a revision is not a commit; an emptied day starts afresh (H2) (1.517251ms)
✔ Resolve stores what was typed first, and takes no typing until its answer is applied (M1) (3.897058ms)
✔ closing with a choice open, or commits held, still writes the text, never commits (M2) (2.277015ms)
✔ closing inside the settling window sends the loaded version with settling=1 (M3) (0.744604ms)
✔ a clean merge not applied because of typing still ends the choice on show (M4) (1.752639ms)
✔ settling finds the draft committed with a teammate's text: a close still writes (M-A) (0.833059ms)
✔ settling finds another tab's newer draft: the tab shows it before any typing (1.245927ms)
✔ a page deleted before the first autosave: the text is offered as a scratch page, and a close makes one (M-B) (1.051876ms)
✔ an autosave that never answered but landed: its 409 keeps the typing since (L3) (1.103111ms)
✔ marks: em outside strong, bold reopened around italics, edges outside (7.639847ms)
✔ marks close before code, links and atoms, and reopen after (0.556545ms)
✔ untouched blocks and atoms re-emit their source; edited atoms are written from attributes (7.729064ms)
✔ empty blocks are written as nothing (2.892579ms)
✔ an unclosed fence that is no longer last gets its closing fence (2.23094ms)
✔ the structure check puts Join's seam where a kept one would merge two blocks (3.154857ms)
✔ prepareSave adopts the parse when no seam or rewrite can save the document (5.155077ms)
✔ reparse: typed emphasis becomes a mark, "- " after a break becomes an item (2.76433ms)
✔ a trailing hard break stays on screen and is written as nothing (0.608351ms)
✔ the reparse waits while an IME is composing (0.780591ms)
✔ copied blocks paste with their bytes and seams; a cut and paste gives the body back (4.052045ms)
✔ a forged x-mapa slice is refused, and text from outside is read as Markdown (0.775041ms)
✔ rebuild changes origins only, outside undo history (1.502204ms)
✔ applyBody takes a teammate's block, keeps the caret, and ends untouched (1.631204ms)
✔ a block whose context changed is written again: a task toggled, a bullet, a quote (2.980202ms)
✔ a duplicate ^id typed above its holder never takes the id from it (0.743191ms)
✔ a copy-dragged block is reparsed, and says what its Markdown says (1.069679ms)
✔ a history command that throws is refused, never thrown (4.763869ms)
✔ an image re-emits its source, and an edited alt changes only its span (0.968782ms)
✔ a paste whose image copy is refused says why and pastes nothing (13.121252ms)
✔ a line of image openers reads in linear time (103.779116ms)
✔ a line of shared link address reads in linear time (14.686863ms)
✔ a line of shared web address reads in linear time (61.590638ms)
✔ one rename at a time, from either field (5.743952ms)
✔ an empty or unchanged title sends nothing (0.179493ms)
✔ a refusal keeps what was typed, and the title (0.196205ms)
✔ the pending state holds for the busy rule (9.560439ms)
✔ a failed POST says so and keeps the title (3.68856ms)
✔ Update links posts the confirm page's POST (0.30638ms)
✔ clean is CleanTitle's whitespace rule (0.50537ms)
✔ the saver's base follows a rename made over it, and only that (0.345542ms)
✔ closing sends the rename as one keepalive POST (5.008283ms)
✔ the port answers every shared case as typeddate.go does (6.013443ms)
✔ numbers follow the locale: 12/11 is November in en-IE, December in en-US (0.176889ms)
✔ M6: several files land in the order they were chosen (42.02379ms)
✔ M5: one Backspace before the box keeps the image where the box is (12.049659ms)
✔ M5: undoing text typed just before the box keeps the upload (12.405491ms)
✔ L12: a failed upload an undo takes away does not stall the next (15.461442ms)
✔ M4: Replace… keeps the old image until the new one is in, and its alt (15.068264ms)
✔ M3 and N1: text wins, except over a picture copied from a page (2.059309ms)
✔ N2: a JPEG over 10 MB is scaled before its size is checked (6.253719ms)
✔ a drag whose anchor the document no longer reaches selects to its end (5.128206ms)
ℹ tests 126
ℹ suites 0
ℹ pass 126
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 7571.003209
=== vet ===
go: downloading go1.26.11 (linux/amd64)
go vet ./...
go vet -tags browser ./internal/mapatest/
=== fmt ===
=== code ===
go tool rastrillo budget code
The base has no .rastrillo/code.txt: skipping the check that records only go down.
budget code: within the limits.
=== test ===
CGO_ENABLED=0 go test ./...
?   	amadan.net/oficina/mapa/cmd/mapa	[no test files]
ok  	amadan.net/oficina/mapa/internal/mapa	3.665s
?   	amadan.net/oficina/mapa/internal/mapa/icons	[no test files]
ok  	amadan.net/oficina/mapa/internal/mapa/imagefile	0.204s
ok  	amadan.net/oficina/mapa/internal/mapa/locale	0.007s
ok  	amadan.net/oficina/mapa/internal/mapa/markup	0.132s
ok  	amadan.net/oficina/mapa/internal/mapa/notionmd	0.320s
ok  	amadan.net/oficina/mapa/internal/mapa/seal	0.003s
ok  	amadan.net/oficina/mapa/internal/mapatest	13.834s
?   	amadan.net/oficina/mapa/scripts/mutate	[no test files]
?   	amadan.net/oficina/mapa/scripts/preview	[no test files]
=== migration-check ===
go tool rastrillo migration check
rastrillo migration check: models and migrations agree
=== credits-check ===
python3 scripts/credits.py --check
credits: checked
diff --git a/copy-review/import-status/luna-prompt.md b/copy-review/import-status/luna-prompt.md
new file mode 100644
index 0000000..af79f6b
--- /dev/null
+++ b/copy-review/import-status/luna-prompt.md
@@ -0,0 +1,60 @@
+# Copy pass: Mapa's Import from Notion page, the run's status box
+
+You are the copy-review gate itself for this set. Paul delegated copy review
+of Oficina's UI copy to you on 2026-10-25, so your verdicts are the review.
+Do NOT run any copy-review skill, do NOT start any server, change nothing on
+disk. Answer in your reply only.
+
+Mapa is the Oficina suite's team knowledge base. Its Import from Notion page
+(/import/notion) copies pages from a Notion workspace into the team's Mapa.
+While an import runs, the page shows a status box: an h2 heading naming the
+state, then one sentence of progress, then a small grey line, then buttons.
+The page refreshes itself every five seconds and works with JavaScript off.
+Readers are team owners importing their Notion workspace; not technical.
+
+Paul looked at the page while an import ran and said the spacing was all
+over the place; the layout is being fixed separately. He also saw that the
+heading's words repeat in the body, which is what this pass fixes:
+
+ Reading Notion (h2)
+ Reading Notion: 4 pages so far. The total isn't known until every
+ shared page has been read.
+ This page refreshes itself every five seconds. Closing it doesn't
+ stop the import. (small grey line)
+ [Stop]
+
+## The states and their strings (headings stay as they are)
+
+| key | heading | body today | body proposed |
+|---|---|---|---|
+| status.surveying.text | Reading Notion | Reading Notion: {n} pages so far. The total isn't known until every shared page has been read. | {n} pages so far. The total isn't known until every shared page has been read. |
+| status.writing.text | Writing pages | Writing pages: {written} of {total}. | {written} of {total} so far. |
+| status.done.text (new) | Run complete | (no body: the heading sits alone, then a grey note about images and a "Run the import again" button, then a "Report" section with the counts) | The report below says what came in and what didn't. |
+| status.stopped.text | Stopped | You stopped the import. It had read {n} pages. Resume carries on from there. (or: It had written {written} of {total} pages.) | unchanged unless you think "Stopped" / "You stopped" repeats |
+| status.interrupted.text | Interrupted | Mapa restarted during the import. It had … Resume carries on from there. | unchanged |
+
+Facts: {n}, {written} and {total} are numbers formatted in the reader's
+locale; there is no plural handling, so {n} can be 1 ("1 pages so far" is
+possible today). "Surveying" reads every page shared with the integration;
+the total is only known once that is done. "Writing" writes the pages into
+Mapa; then the total is known. A completed run always shows the Report
+section below the status box, listing created, updated, kept, failed and
+not-imported counts. Some pages may have failed even in a completed run.
+
+## House rules (Paul's)
+
+- Plain, direct voice. Say what happened, then what to do. No marketing
+ tone, no exclamation marks, no "simply", no throat-clearing.
+- No em or en dashes used as dashes. Use a full stop and a new sentence.
+- Keep every placeholder ({n}, {written}, {total}) in the same order. If
+ you must reorder one, say so in "why".
+- Undefined jargon is not fine.
+- The body must not repeat the heading's words.
+
+## What to return
+
+1. A table `key | new | why` with only the rows you change from the
+ "body proposed" column (or from today's text for the unchanged rows).
+ Rows you leave alone are approved as proposed.
+2. A `## Flags` section with only what needs a person (a fact you can't
+ make work, a product decision). Write "none" if there are none.
diff --git a/copy-review/import-status/luna-review.md b/copy-review/import-status/luna-review.md
new file mode 100644
index 0000000..3ebf168
--- /dev/null
+++ b/copy-review/import-status/luna-review.md
@@ -0,0 +1,9 @@
+| key | new | why |
+|---|---|---|
+| status.surveying.text | Pages read so far: {n}. The total isn't known until every shared page has been read. | Avoids repeating the heading and avoids the possible “1 pages” error. |
+| status.done.text | The report below shows how many pages were created, updated, kept, failed, and not imported. | States clearly what the report contains. |
+| status.stopped.text | The import ended before it finished. It had read {n} pages. Select Resume to continue from there. (or: The import ended before it finished. It had written {written} of {total} pages. Select Resume to continue from there.) | Avoids repeating “Stopped” / “stopped” and gives a direct next step. |
+
+## Flags
+
+none
diff --git a/copy-review/import-status/result.json b/copy-review/import-status/result.json
new file mode 100644
index 0000000..559ed42
--- /dev/null
+++ b/copy-review/import-status/result.json
@@ -0,0 +1,54 @@
+{
+ "action": "approve",
+ "guidance": null,
+ "note": "Reviewed 2026-11-22 by Luna (gpt-5.6-luna through Codex, codex exec --ephemeral), the copy-review gate for Oficina platform copy since Paul's delegation of 2026-10-25. Prompt in luna-prompt.md, answer in luna-review.md. Paul asked on 2026-11-22 that the status box stop repeating its heading in its body. Luna's edits are applied byte for byte, except where listed under \"not_applied\". Supersedes notion-import's status.surveying.text and status.writing.text.",
+ "strings": [
+ {
+ "id": "status.surveying.text",
+ "text": "Pages read so far: {n}. The total isn't known until every shared page has been read.",
+ "original": "{n} pages so far. The total isn't known until every shared page has been read.",
+ "edited": true,
+ "rerolled": false,
+ "rerolls": [],
+ "done": true
+ },
+ {
+ "id": "status.writing.text",
+ "text": "{written} of {total} so far.",
+ "original": "{written} of {total} so far.",
+ "edited": false,
+ "rerolled": false,
+ "rerolls": [],
+ "done": true
+ },
+ {
+ "id": "status.done.text",
+ "text": "The report below shows how many pages were created, updated, kept, failed, and not imported.",
+ "original": "The report below says what came in and what didn't.",
+ "edited": true,
+ "rerolled": false,
+ "rerolls": [],
+ "done": true
+ },
+ {
+ "id": "status.stopped.text",
+ "text": "You stopped the import.",
+ "original": "You stopped the import.",
+ "edited": false,
+ "rerolled": false,
+ "rerolls": [],
+ "done": true
+ }
+ ],
+ "not_applied": [
+ {
+ "id": "status.stopped.text",
+ "luna": "The import ended before it finished. It had read {n} pages. Select Resume to continue from there.",
+ "why": "\"Ended\" is what Finish import does on this page (its notice says \"Import ended: Mapa no longer holds the secret\"), so a stopped run must not say it ended; and the progress half is shared with Interrupted, which Luna left as it is. Kept as today."
+ }
+ ],
+ "flags": [],
+ "follow_up": [
+ "status.paused.progress.read still says \"It had read {n} pages\", which reads \"1 pages\" at one; Luna fixed the same in surveying by putting the count last. Not changed in this pass."
+ ]
+}
\ No newline at end of file
diff --git a/copy-review/import-status/strings.json b/copy-review/import-status/strings.json
new file mode 100644
index 0000000..d1a06e1
--- /dev/null
+++ b/copy-review/import-status/strings.json
@@ -0,0 +1,34 @@
+[
+ {
+ "id": "status.surveying.text",
+ "section": "Import page: the run's status",
+ "label": "Progress while reading Notion",
+ "text": "{n} pages so far. The total isn't known until every shared page has been read.",
+ "context": "Under the heading 'Reading Notion'. {n} is how many pages have been read so far. Replaces 'Reading Notion: {n} pages so far. …', which repeated the heading (Paul, 2026-11-22).",
+ "notes": ""
+ },
+ {
+ "id": "status.writing.text",
+ "section": "Import page: the run's status",
+ "label": "Progress while writing pages",
+ "text": "{written} of {total} so far.",
+ "context": "Under the heading 'Writing pages'. Replaces 'Writing pages: {written} of {total}.', which repeated the heading.",
+ "notes": ""
+ },
+ {
+ "id": "status.done.text",
+ "section": "Import page: the run's status",
+ "label": "Line under 'Run complete'",
+ "text": "The report below says what came in and what didn't.",
+ "context": "New. Under the heading 'Run complete', which sat alone; the Report section with the counts follows.",
+ "notes": ""
+ },
+ {
+ "id": "status.stopped.text",
+ "section": "Import page: the run's status",
+ "label": "Opening sentence under 'Stopped'",
+ "text": "You stopped the import.",
+ "context": "Asked whether it repeats the heading 'Stopped'. Followed by the shared progress sentence, 'It had read {n} pages. Resume carries on from there.'",
+ "notes": ""
+ }
+]
\ No newline at end of file
diff --git a/internal/mapa/static/mapa.css b/internal/mapa/static/mapa.css
index 374211b..3f5b40f 100644
--- a/internal/mapa/static/mapa.css
+++ b/internal/mapa/static/mapa.css
@@ -24,6 +24,105 @@
margin: 0;
}
+/* ---- The page's vertical rhythm: Fiesta's rst-stack, rst-section and
+ rst-actions (rastrillo/fiesta feat/stack-rhythm), copied ahead of
+ their release. When Fiesta ships them, the swap is a rename:
+ mapa-stack to rst-stack, mapa-section to rst-section, mapa-action-row
+ to rst-actions, and this block goes.
+
+ A stack is a flex column, so no margin collapses; every child's own
+ block margins are zeroed, and the space before each child comes from
+ one table, by what it is and what it follows. Higher wins:
+
+ before an actions row or a button --rst-sp-4
+ (rst-form-actions, the confirm form,
+ is one too: Mapa's addition)
+ after a heading --rst-sp-2
+ a label or hint, then its input --rst-sp-2
+ before h1, h2 or a section, or after
+ the page header --rst-sp-5
+ before h3 to h6 --rst-sp-4
+ anything else --rst-sp-3
+
+ Each relation sets its own custom property and the one margin rule
+ reads them in that order, so the precedence is written here rather
+ than left to specificity; every child resets all five first, so a
+ nested stack's child never inherits its parent's answer. A section
+ is a stack, and a new section where it sits. An actions row holds
+ buttons and one-button forms side by side, wrapping on a phone. */
+[mapa-stack],
+[mapa-section] { display: flex; flex-direction: column; }
+[mapa-stack] > :not([hidden]),
+[mapa-section] > :not([hidden]) {
+ --mapa-stack-actions: initial;
+ --mapa-stack-heading: initial;
+ --mapa-stack-control: initial;
+ --mapa-stack-section: initial;
+ --mapa-stack-sub: initial;
+ margin-block: 0;
+}
+[mapa-stack] > :not([hidden]) + :not([hidden]),
+[mapa-section] > :not([hidden]) + :not([hidden]) {
+ margin-block-start: var(--mapa-stack-actions, var(--mapa-stack-heading, var(--mapa-stack-control, var(--mapa-stack-section, var(--mapa-stack-sub, var(--rst-sp-3))))));
+}
+[mapa-stack] > button,
+[mapa-section] > button,
+[mapa-stack] > [rst-btn],
+[mapa-section] > [rst-btn],
+[mapa-stack] > img,
+[mapa-section] > img { align-self: flex-start; }
+[mapa-stack] > :not([hidden]) + h3,
+[mapa-section] > :not([hidden]) + h3,
+[mapa-stack] > :not([hidden]) + h4,
+[mapa-section] > :not([hidden]) + h4,
+[mapa-stack] > :not([hidden]) + h5,
+[mapa-section] > :not([hidden]) + h5,
+[mapa-stack] > :not([hidden]) + h6,
+[mapa-section] > :not([hidden]) + h6 { --mapa-stack-sub: var(--rst-sp-4); }
+[mapa-stack] > :not([hidden]) + h1,
+[mapa-section] > :not([hidden]) + h1,
+[mapa-stack] > :not([hidden]) + h2,
+[mapa-section] > :not([hidden]) + h2,
+[mapa-stack] > :not([hidden]) + [mapa-section],
+[mapa-section] > :not([hidden]) + [mapa-section],
+[mapa-stack] > [rst-page-header] + :not([hidden]),
+[mapa-section] > [rst-page-header] + :not([hidden]) { --mapa-stack-section: var(--rst-sp-5); }
+[mapa-stack] > label + input:not([hidden]),
+[mapa-section] > label + input:not([hidden]),
+[mapa-stack] > label + select:not([hidden]),
+[mapa-section] > label + select:not([hidden]),
+[mapa-stack] > label + textarea:not([hidden]),
+[mapa-section] > label + textarea:not([hidden]),
+[mapa-stack] > [rst-field-help] + input:not([hidden]),
+[mapa-section] > [rst-field-help] + input:not([hidden]),
+[mapa-stack] > [rst-field-help] + select:not([hidden]),
+[mapa-section] > [rst-field-help] + select:not([hidden]),
+[mapa-stack] > [rst-field-help] + textarea:not([hidden]),
+[mapa-section] > [rst-field-help] + textarea:not([hidden]) { --mapa-stack-control: var(--rst-sp-2); }
+[mapa-stack] > h1 + :not([hidden]),
+[mapa-section] > h1 + :not([hidden]),
+[mapa-stack] > h2 + :not([hidden]),
+[mapa-section] > h2 + :not([hidden]),
+[mapa-stack] > h3 + :not([hidden]),
+[mapa-section] > h3 + :not([hidden]),
+[mapa-stack] > h4 + :not([hidden]),
+[mapa-section] > h4 + :not([hidden]),
+[mapa-stack] > h5 + :not([hidden]),
+[mapa-section] > h5 + :not([hidden]),
+[mapa-stack] > h6 + :not([hidden]),
+[mapa-section] > h6 + :not([hidden]) { --mapa-stack-heading: var(--rst-sp-2); }
+[mapa-stack] > :not([hidden]) + [mapa-action-row],
+[mapa-section] > :not([hidden]) + [mapa-action-row],
+[mapa-stack] > :not([hidden]) + [rst-form-foot],
+[mapa-section] > :not([hidden]) + [rst-form-foot],
+[mapa-stack] > :not([hidden]) + [rst-form-actions],
+[mapa-section] > :not([hidden]) + [rst-form-actions],
+[mapa-stack] > :not([hidden]) + button,
+[mapa-section] > :not([hidden]) + button,
+[mapa-stack] > :not([hidden]) + [rst-btn],
+[mapa-section] > :not([hidden]) + [rst-btn] { --mapa-stack-actions: var(--rst-sp-4); }
+[mapa-action-row] { align-items: center; display: flex; flex-wrap: wrap; gap: var(--rst-sp-2); }
+
/* ---- A page: its title and actions on one row, the body on a card. */
[mapa-page-head] {
display: flex;
diff --git a/internal/mapa/templates/import.html b/internal/mapa/templates/import.html
index 0dc37bc..1f4f1cd 100644
--- a/internal/mapa/templates/import.html
+++ b/internal/mapa/templates/import.html
@@ -1,32 +1,39 @@
{{define "head"}}{{with .Data.Run}}{{if .Refresh}}<meta http-equiv="refresh" content="5">{{end}}{{end}}{{end}}
{{define "content"}}{{$d := .Data}}
+<div mapa-stack>
{{template "page-header" dict "Title" "Import from Notion" "Sub" "Copy pages from a Notion workspace into this team's Mapa."}}
{{template "notice" $d.Notice}}
{{template "form-error" $d.Error}}
-{{with $d.Run}}<section mapa-import-run aria-labelledby="import-run" role="status">
+{{with $d.Run}}<section mapa-section mapa-import-run aria-labelledby="import-run">
+<div mapa-stack role="status">
<h2 id="import-run">{{if eq .State "surveying"}}Reading Notion{{else if eq .State "writing"}}Writing pages{{else if eq .State "done"}}Run complete{{else if eq .State "interrupted"}}Interrupted{{else if eq .State "stopped"}}Stopped{{else}}The import failed{{end}}</h2>
-{{if eq .State "surveying"}}<p>Reading Notion: {{number L .Surveyed}} pages so far. The total isn't known until every shared page has been read.</p>
-{{else if eq .State "writing"}}<p>Writing pages: {{number L .Written}} of {{number L .Total}}.</p>
+{{if eq .State "surveying"}}<p>Pages read so far: {{number L .Surveyed}}. The total isn't known until every shared page has been read.</p>
+{{else if eq .State "writing"}}<p>{{number L .Written}} of {{number L .Total}} so far.</p>
{{else if or (eq .State "interrupted") (eq .State "stopped")}}<p>{{if eq .State "interrupted"}}Mapa restarted during the import.{{else}}You stopped the import.{{end}} It had {{if .Total}}written {{number L .Written}} of {{number L .Total}} pages{{else}}read {{number L .Surveyed}} pages{{end}}. Resume carries on from there.</p>
+{{else if eq .State "done"}}<p>The report below shows how many pages were created, updated, kept, failed, and not imported.</p>
{{else if eq .State "failed"}}<p>{{importFailure .Code}}</p>{{end}}
{{if .Active}}<p mapa-meta>This page refreshes itself every five seconds. Closing it doesn't stop the import.</p>{{else if or (eq .State "surveying") (eq .State "writing")}}<p mapa-meta>Nothing has happened for a while. Stop it, then resume.</p>{{end}}
-</section>{{end}}
-{{if and $d.NoImages $d.CanStart}}<p mapa-meta>Images aren't set up in Mapa yet, so each image from Notion comes in as a line saying it wasn't imported. Run the import again once images are set up, and the pages nobody has edited get their pictures.</p>{{end}}
-{{with $d.Images}}{{if $d.CanStart}}<p mapa-meta>Imported images count against the team's image allowance, now {{.Team}} used, and, until each page is written, against yours, now {{.Own}}. If either fills, the run stops fetching images and says so; raise it, or free some, and run again.</p>{{end}}{{end}}
-{{if or $d.CanStop $d.CanResume $d.CanStart $d.CanStartOver}}<div mapa-import-actions>
-{{if $d.CanStop}}<form method="post" action="/import/notion/stop"><button rst-btn type="submit">Stop</button></form>{{end}}
-{{if $d.CanResume}}<form method="post" action="/import/notion/resume"><button rst-btn="primary" type="submit">Resume</button></form>{{end}}
-{{if $d.CanStartOver}}<form method="post" action="/import/notion/startover"><button rst-btn type="submit">Start over</button></form>{{end}}
-{{if $d.CanStart}}<form method="post" action="/import/notion/start"><button rst-btn="primary" type="submit">{{if $d.Run}}Run the import again{{else}}Start the import{{end}}</button></form>{{end}}
-</div>{{end}}
+</div>
+{{template "import-start" $d}}
+</section>{{else}}{{template "import-start" $d}}{{end}}
{{with $d.Report}}{{template "import-report" .}}{{end}}
{{if not $d.CanStop}}{{template "import-connection" $d}}{{end}}
+</div>
{{end}}
-{{define "import-connection"}}<section mapa-import-connection aria-labelledby="import-connection">
+{{define "import-start"}}{{if and .NoImages .CanStart}}<p mapa-meta>Images aren't set up in Mapa yet, so each image from Notion comes in as a line saying it wasn't imported. Run the import again once images are set up, and the pages nobody has edited get their pictures.</p>{{end}}
+{{with .Images}}{{if $.CanStart}}<p mapa-meta>Imported images count against the team's image allowance, now {{.Team}} used, and, until each page is written, against yours, now {{.Own}}. If either fills, the run stops fetching images and says so; raise it, or free some, and run again.</p>{{end}}{{end}}
+{{if or .CanStop .CanResume .CanStart .CanStartOver}}<div mapa-action-row mapa-import-actions>
+{{if .CanStop}}<form method="post" action="/import/notion/stop"><button rst-btn type="submit">Stop</button></form>{{end}}
+{{if .CanResume}}<form method="post" action="/import/notion/resume"><button rst-btn="primary" type="submit">Resume</button></form>{{end}}
+{{if .CanStartOver}}<form method="post" action="/import/notion/startover"><button rst-btn type="submit">Start over</button></form>{{end}}
+{{if .CanStart}}<form method="post" action="/import/notion/start"><button rst-btn="primary" type="submit">{{if .Run}}Run the import again{{else}}Start the import{{end}}</button></form>{{end}}
+</div>{{end}}{{end}}
+
+{{define "import-connection"}}<section mapa-section mapa-import-connection aria-labelledby="import-connection">
<h2 id="import-connection">Connection</h2>
{{if .Connected}}<p>Connected to {{if .Workspace}}the Notion workspace “{{.Workspace}}”{{else}}a Notion workspace{{end}}. Mapa holds its secret, sealed, and never shows it.</p>
-<p><a rst-btn href="/import/notion/finish">Finish import…</a> <a rst-btn href="/import/notion/disconnect">Disconnect…</a></p>
+<div mapa-action-row><a rst-btn href="/import/notion/finish">Finish import…</a><a rst-btn href="/import/notion/disconnect">Disconnect…</a></div>
<details><summary>Replace the secret</summary>{{template "import-token-form" .}}</details>
{{else}}{{if .Finished}}<p><strong>The previous import was ended.</strong> Connecting again starts a new import. It has no record of what the last one wrote, so it would create a second copy of every page it finds.</p>{{end}}
<p><strong>Everything you share with this integration becomes a team page that every member of this team can read.</strong> Share only what the whole team should have.</p>
@@ -45,7 +52,7 @@
{{template "form-foot" dict "Submit" "Connect"}}
</form>{{end}}
-{{define "import-report"}}<section mapa-import-report aria-labelledby="import-report">
+{{define "import-report"}}<section mapa-section mapa-import-report aria-labelledby="import-report">
<h2 id="import-report">Report</h2>
{{range .ImageFailures}}{{if eq .Label "images aren't set up in Mapa yet"}}<p mapa-notice role="status"><strong>No images were imported: images aren't set up in Mapa yet.</strong> Each one is a line in its page. Run the import again once images are set up.</p>{{end}}{{if hasSuffix .Label "allowance is full"}}<p mapa-notice role="status"><strong>Images stopped: {{.Label}}.</strong> Raise that allowance, or free some, and run the import again: the pages waiting for images are filled in.</p>{{end}}{{end}}
{{with .Roots}}<p>Started from: {{range $i, $r := .}}{{if $i}}, {{end}}“{{$r}}”{{end}}.</p>{{end}}
diff --git a/internal/mapa/templates/import_confirm.html b/internal/mapa/templates/import_confirm.html
index 74177e1..1c12f26 100644
--- a/internal/mapa/templates/import_confirm.html
+++ b/internal/mapa/templates/import_confirm.html
@@ -1,4 +1,5 @@
{{define "content"}}{{$d := .Data}}
+<div mapa-stack>
{{template "back-nav" dict "Href" "/import/notion" "Label" "Import from Notion"}}
{{if eq $d.Act "disconnect"}}{{template "page-header" dict "Title" "Disconnect from Notion?"}}
<p>Mapa deletes the integration's secret. The pages already imported stay, and so does Mapa's record of which Notion page each came from, so connecting again later carries on from there. An interrupted run can't be resumed.</p>
@@ -10,6 +11,7 @@
{{end}}
<p>Then remove the integration from Notion's connection settings.</p>
{{if $d.Active}}{{template "form-error" "An import is running. Stop the run first."}}
-<p><a rst-btn href="/import/notion">Back</a></p>
+<div mapa-action-row><a rst-btn href="/import/notion">Back</a></div>
{{else}}{{template "confirm-form" dict "Action" $d.Action "Label" (index (dict "disconnect" "Disconnect" "finish" "Finish import" "forget" "Forget the import") $d.Act) "Danger" true "CancelHref" "/import/notion" "CancelLabel" "Cancel"}}{{end}}
+</div>
{{end}}
diff --git a/internal/mapatest/import_browser_test.go b/internal/mapatest/import_browser_test.go
index 64e1ddc..39ffd56 100644
--- a/internal/mapatest/import_browser_test.go
+++ b/internal/mapatest/import_browser_test.go
@@ -83,7 +83,7 @@ func importWalk(t *testing.T, live bool) {
server.Lock()
drive(t, rig, press(`form[action="/import/notion/start"] button`),
chromedp.WaitVisible(`form[action="/import/notion/stop"]`))
- expectIn(t, rig, "Reading Notion: 0 pages so far")
+ expectIn(t, rig, "Pages read so far: 0.")
if !strings.Contains(read(t, rig, chromedp.OuterHTML("head")),
`http-equiv="refresh"`) {
t.Error("a running import's page does not refresh itself")
@@ -111,7 +111,7 @@ func midWrite(t *testing.T, rig *harness.Rig, database func() *gorm.DB,
database().Exec("UPDATE notion_runs SET state = 'writing', total = 5,"+
" written = 2, heartbeat_at = ?, progress_at = ?", now, now)
drive(t, rig, chromedp.Navigate(rig.Origin+"/import/notion"))
- expectIn(t, rig, "Writing pages: 2 of 5.")
+ expectIn(t, rig, "2 of 5 so far.")
shot(t, rig, live, "4-mid-write")
database().Exec("UPDATE notion_runs SET state = 'stopped', total = 0," +
" written = 0")
diff --git a/internal/mapatest/import_rhythm_browser_test.go b/internal/mapatest/import_rhythm_browser_test.go
new file mode 100644
index 0000000..21c6ac9
--- /dev/null
+++ b/internal/mapatest/import_rhythm_browser_test.go
@@ -0,0 +1,125 @@
+//go:build browser
+
+package mapatest
+
+import (
+ "context"
+ _ "embed"
+ "encoding/json"
+ "fmt"
+ "strings"
+ "testing"
+ "time"
+
+ "amadan.net/rastrillo/rastrillo/harness"
+ "github.com/chromedp/chromedp"
+)
+
+// The import page's vertical rhythm (Paul, 2026-11-22: "The spacing is
+// all over the place here"), held by Fiesta's rhythm audit in every
+// state the page has: connect, connected, reading, stopped, writing,
+// interrupted, failed and done, and the three confirm pages. In each,
+// every gap between two blocks is a step of the spacing scale, no text
+// sits closer than --rst-sp-2 to a control, and every heading is closer
+// to its own content than to the block before it.
+
+// rhythmScript is Fiesta's check/rhythm audit, vendored ahead of its
+// release (testdata/rhythm/README).
+//
+//go:embed testdata/rhythm/rhythm.js
+var rhythmScript string
+
+// rhythmFinding is one thing the audit saw, as check/rhythm's Finding.
+type rhythmFinding struct {
+ Kind string `json:"kind"`
+ Gap float64 `json:"gap"`
+ Before string `json:"before"`
+ After string `json:"after"`
+ Message string `json:"message"`
+}
+
+// rhythmSkip is what the audit leaves alone on the import page:
+// rst-form is Fiesta's form, whose rhythm (and the extra air above its
+// closing row) is Fiesta's to set and its own gates' to check.
+var rhythmSkip = []string{"[rst-form]"}
+
+func TestImportPageRhythm(t *testing.T) {
+ rig, server, database := importRig(t)
+ rig.Run(scripts(false))
+ page := rig.Origin + "/import/notion"
+ audit := func(stage string) { auditRhythm(t, rig, stage) }
+ drive(t, rig, chromedp.Navigate(page))
+ audit("connect")
+ drive(t, rig, chromedp.SendKeys(`input[name="token"]`, "secret_test"),
+ press(`form[action="/import/notion/connect"] button`),
+ chromedp.WaitVisible(`form[action="/import/notion/start"]`))
+ audit("connected")
+ server.Lock()
+ drive(t, rig, press(`form[action="/import/notion/start"] button`),
+ chromedp.WaitVisible(`form[action="/import/notion/stop"]`))
+ audit("reading")
+ drive(t, rig, press(`form[action="/import/notion/stop"] button`),
+ chromedp.WaitVisible(`form[action="/import/notion/resume"]`))
+ server.Unlock()
+ audit("stopped")
+ now := time.Now().UTC()
+ for _, state := range []string{"writing", "interrupted", "failed"} {
+ database().Exec("UPDATE notion_runs SET state = ?, total = 5,"+
+ " written = 2, error_code = 'unauthorized', heartbeat_at = ?,"+
+ " progress_at = ?", state, now, now)
+ drive(t, rig, chromedp.Navigate(page))
+ audit(state)
+ }
+ database().Exec("UPDATE notion_runs SET state = 'stopped', total = 0," +
+ " written = 0, error_code = ''")
+ drive(t, rig, chromedp.Navigate(page),
+ press(`form[action="/import/notion/resume"] button`))
+ waitFor(t, rig, "Run complete")
+ audit("done")
+ for _, act := range []string{"finish", "disconnect", "forget"} {
+ drive(t, rig, chromedp.Navigate(page+"/"+act))
+ audit("confirm " + act)
+ }
+}
+
+// auditRhythm runs the audit over the page's content and fails the
+// test on each finding, naming the stage. A read that lands while the
+// page's own refresh replaces it is tried again.
+func auditRhythm(t *testing.T, rig *harness.Rig, stage string) {
+ t.Helper()
+ options, err := json.Marshal(map[string]any{"skip": rhythmSkip})
+ if err != nil {
+ t.Fatal(err)
+ }
+ expression := "JSON.stringify((" + rhythmScript + ")(\"[mapa-doc]\", " +
+ string(options) + "))"
+ var answer string
+ for try := 0; ; try++ {
+ ctx, cancel := context.WithTimeout(rig.Context(), 10*time.Second)
+ answer, err = chromedp.Run(ctx, chromedp.Evaluate[string](expression))
+ cancel()
+ if err == nil || try == 2 {
+ break
+ }
+ }
+ if err != nil {
+ t.Fatalf("%s: the rhythm audit did not run: %v", stage, err)
+ }
+ var found []rhythmFinding
+ if err := json.Unmarshal([]byte(answer), &found); err != nil {
+ t.Fatalf("%s: the rhythm audit answered %q: %v", stage, answer, err)
+ }
+ if len(found) > 0 {
+ t.Errorf("%s: the import page's rhythm:\n%s", stage,
+ rhythmReport(found))
+ }
+}
+
+func rhythmReport(found []rhythmFinding) string {
+ lines := make([]string, len(found))
+ for at, finding := range found {
+ lines[at] = fmt.Sprintf("%s: %s\n\tabove: %s\n\tbelow: %s",
+ finding.Kind, finding.Message, finding.Before, finding.After)
+ }
+ return strings.Join(lines, "\n")
+}
diff --git a/internal/mapatest/testdata/rhythm/README b/internal/mapatest/testdata/rhythm/README
new file mode 100644
index 0000000..bef7613
--- /dev/null
+++ b/internal/mapatest/testdata/rhythm/README
@@ -0,0 +1,5 @@
+rhythm.js is Fiesta's rhythm audit (rastrillo/fiesta, check/rhythm), copied
+ahead of its release from the branch feat/stack-rhythm. Its licence is
+Fiesta's, MPL-2.0. Test-only: it is not in the release build. When Fiesta
+releases check/rhythm, import amadan.net/rastrillo/fiesta/check/rhythm
+and delete this copy.
diff --git a/internal/mapatest/testdata/rhythm/rhythm.js b/internal/mapatest/testdata/rhythm/rhythm.js
new file mode 100644
index 0000000..2c0f228
--- /dev/null
+++ b/internal/mapatest/testdata/rhythm/rhythm.js
@@ -0,0 +1,245 @@
+// Fiesta's rhythm audit: the runtime half of the spacing rule
+// (DESIGN.md, "Spacing"). It walks a page's content as the browser laid
+// it out and reports three things a reader sees and a stylesheet check
+// cannot:
+//
+// off-scale two blocks, one under the other, whose gap is not a
+// step of the spacing scale (0, or --rst-sp-1 to 6);
+// touching text directly above or below a control (a button, a
+// field, a disclosure) with less than --rst-sp-2 between;
+// heading a heading further from its own content than it is from
+// what comes before it, so it reads as belonging to the
+// block above.
+//
+// It is one function expression, evaluated in the page: the Go package
+// beside it wraps it as rhythm.Expression for a chromedp drive, and
+// any other driver can evaluate the file and call it. It reads the
+// layout and changes nothing.
+//
+// It walks the content flow: the root, and every element in it that
+// holds blocks, except Fiesta's components (an element carrying an
+// rst- name other than the layout ones), whose insides are Fiesta's to
+// space and its own gates to check, text blocks (p, headings, lists,
+// tables, pre), controls, and whatever options.skip names.
+(function fiestaRhythm(root, options) {
+ options = options || {};
+ var tolerance = typeof options.tolerance === "number" ? options.tolerance : 1;
+ var skip = options.skip || [];
+ var start = typeof root === "string" ? document.querySelector(root) : root;
+ if (!start) {
+ return [{ kind: "missing", gap: 0, before: "", after: "", message: "no element matches " + root }];
+ }
+
+ var htmlStyle = getComputedStyle(document.documentElement);
+ var rem = parseFloat(htmlStyle.fontSize) || 16;
+ var defaults = [0.25, 0.5, 0.75, 1, 1.5, 2.5];
+ var scale = [0];
+ for (var step = 1; step <= 6; step++) {
+ scale.push(length(htmlStyle.getPropertyValue("--rst-sp-" + step), defaults[step - 1] * rem));
+ }
+
+ // length reads a token's value: a rem, px or bare zero length.
+ function length(value, fallback) {
+ var m = /^\s*(-?[0-9.]+)(rem|px)?\s*$/.exec(value || "");
+ if (!m) return fallback;
+ var n = parseFloat(m[1]);
+ return m[2] === "rem" ? n * rem : n;
+ }
+
+ var layoutNames = { "rst-page": 1, "rst-stack": 1, "rst-section": 1, "rst-form": 1, "rst-form-flow": 1 };
+ var textTags = { P: 1, H1: 1, H2: 1, H3: 1, H4: 1, H5: 1, H6: 1, UL: 1, OL: 1, DL: 1, TABLE: 1, PRE: 1, BLOCKQUOTE: 1, FIGURE: 1, SVG: 1, IMG: 1, VIDEO: 1, CANVAS: 1, IFRAME: 1, svg: 1 };
+ var headingTags = { H1: 1, H2: 1, H3: 1, H4: 1, H5: 1, H6: 1 };
+
+ function skipped(el) {
+ for (var i = 0; i < skip.length; i++) {
+ if (el.matches(skip[i])) return true;
+ }
+ return false;
+ }
+
+ // rstNames is every rst- name an element carries, attribute or class.
+ function rstNames(el) {
+ var names = [];
+ for (var i = 0; i < el.attributes.length; i++) {
+ var name = el.attributes[i].name;
+ if (name.indexOf("rst-") === 0) names.push(name);
+ }
+ el.classList.forEach(function (c) {
+ if (c.indexOf("rst-") === 0) names.push(c.split("__")[0].split("--")[0]);
+ });
+ return names;
+ }
+
+ function isComponent(el) {
+ var names = rstNames(el);
+ for (var i = 0; i < names.length; i++) {
+ if (!layoutNames[names[i]]) return true;
+ }
+ return false;
+ }
+
+ function isControl(el) {
+ var tag = el.tagName;
+ if (tag === "BUTTON" || tag === "SELECT" || tag === "TEXTAREA" || tag === "SUMMARY") return true;
+ if (tag === "INPUT") return el.type !== "hidden";
+ if (el.hasAttribute("rst-btn") || el.classList.contains("rst-btn")) return true;
+ var role = el.getAttribute("role");
+ return role === "button" || role === "switch" || role === "checkbox" || role === "radio" || role === "textbox" || role === "combobox";
+ }
+
+ function isHeading(el) {
+ return !!headingTags[el.tagName] || el.getAttribute("role") === "heading";
+ }
+
+ function shown(el) {
+ var style = getComputedStyle(el);
+ if (style.display === "none" || style.visibility === "hidden") return false;
+ if (style.position === "absolute" || style.position === "fixed" || style.float !== "none") return false;
+ var box = el.getBoundingClientRect();
+ return box.height > 0 && box.width > 0;
+ }
+
+ // flow is a container's block-level children in order, looking
+ // through display: contents.
+ function flow(container) {
+ var out = [];
+ for (var el = container.firstElementChild; el; el = el.nextElementSibling) {
+ var style = getComputedStyle(el);
+ if (style.display === "contents") {
+ out.push.apply(out, flow(el));
+ continue;
+ }
+ if (style.display.indexOf("inline") === 0 || el.tagName === "SCRIPT" || el.tagName === "TEMPLATE") continue;
+ if (shown(el)) out.push(el);
+ }
+ return out;
+ }
+
+ // edge says whether an element begins (first) or ends (!first) with
+ // text or with a control, looking through wrappers: "text",
+ // "control" or "".
+ function edge(el, first) {
+ if (isControl(el)) return "control";
+ var nodes = el.childNodes;
+ for (var k = 0; k < nodes.length; k++) {
+ var node = nodes[first ? k : nodes.length - 1 - k];
+ if (node.nodeType === 3) {
+ if (node.textContent.trim() !== "") return "text";
+ continue;
+ }
+ if (node.nodeType !== 1) continue;
+ var style = getComputedStyle(node);
+ if (style.display === "none" || style.visibility === "hidden") continue;
+ var found = edge(node, first);
+ if (found) return found;
+ }
+ return "";
+ }
+
+ function describe(el) {
+ var out = el.tagName.toLowerCase();
+ if (el.id) out += "#" + el.id;
+ for (var i = 0; i < el.attributes.length; i++) {
+ var a = el.attributes[i].name;
+ if (a !== "id" && a !== "class" && a !== "style" && a.indexOf("aria-") !== 0 && a.indexOf("-") > 0) {
+ out += "[" + a + "]";
+ break;
+ }
+ }
+ var text = (el.textContent || "").replace(/\s+/g, " ").trim();
+ if (text) out += " “" + (text.length > 40 ? text.slice(0, 39) + "…" : text) + "”";
+ return out;
+ }
+
+ function onScale(gap) {
+ for (var i = 0; i < scale.length; i++) {
+ if (Math.abs(gap - scale[i]) <= tolerance) return true;
+ }
+ return false;
+ }
+
+ function round(n) {
+ return Math.round(n * 10) / 10;
+ }
+
+ var findings = [];
+ var gapBefore = new Map();
+ var firstChildOf = new Map();
+ var headings = [];
+
+ function walk(container) {
+ var kids = flow(container);
+ if (kids.length) firstChildOf.set(kids[0], container);
+ for (var i = 0; i < kids.length; i++) {
+ var b = kids[i];
+ if (isHeading(b)) headings.push(b);
+ if (i > 0) measure(kids[i - 1], b);
+ if (!skipped(b) && !isComponent(b) && !isControl(b) && !textTags[b.tagName]) walk(b);
+ }
+ }
+
+ function measure(a, b) {
+ var ra = a.getBoundingClientRect();
+ var rb = b.getBoundingClientRect();
+ var stacked = rb.top >= ra.bottom - tolerance && rb.left < ra.right && ra.left < rb.right;
+ if (!stacked || skipped(a) || skipped(b)) return;
+ var gap = rb.top - ra.bottom;
+ gapBefore.set(b, { gap: gap, from: a });
+ if (!onScale(gap)) {
+ findings.push({
+ kind: "off-scale", gap: round(gap), before: describe(a), after: describe(b),
+ message: round(gap) + "px between blocks is not a step of the spacing scale"
+ });
+ }
+ var touching = (edge(a, false) === "text" && edge(b, true) === "control") ||
+ (edge(a, false) === "control" && edge(b, true) === "text");
+ if (touching && gap < scale[2] - tolerance) {
+ findings.push({
+ kind: "touching", gap: round(gap), before: describe(a), after: describe(b),
+ message: "text and a control are " + round(gap) + "px apart; they need --rst-sp-2 (" + round(scale[2]) + "px) or more"
+ });
+ }
+ }
+
+ // before is the gap that opens a heading: from its previous block,
+ // or, for the first block of a container, the gap that opens the
+ // container, and so on up to the root.
+ function before(el) {
+ for (var at = el; at && at !== start; at = firstChildOf.get(at)) {
+ if (gapBefore.has(at)) return gapBefore.get(at).gap;
+ if (!firstChildOf.has(at)) return undefined;
+ }
+ return undefined;
+ }
+
+ walk(start);
+
+ // The space that opens a section is the gap before each heading of a
+ // level; a heading with nothing before it on the page is held to the
+ // smallest of those for its level.
+ var opening = {};
+ headings.forEach(function (h) {
+ var gap = before(h);
+ if (gap !== undefined) {
+ opening[h.tagName] = Math.min(opening[h.tagName] === undefined ? Infinity : opening[h.tagName], gap);
+ }
+ });
+ headings.forEach(function (h) {
+ var next = null;
+ gapBefore.forEach(function (v, k) {
+ if (v.from === h) next = { el: k, gap: v.gap };
+ });
+ if (!next) return;
+ var open = before(h);
+ if (open === undefined) open = opening[h.tagName];
+ if (open === undefined) return;
+ if (next.gap >= open - tolerance) {
+ findings.push({
+ kind: "heading", gap: round(next.gap), before: describe(h), after: describe(next.el),
+ message: "a heading is " + round(next.gap) + "px from its content and " + round(open) +
+ "px from what comes before it; it should sit closer to its content"
+ });
+ }
+ });
+ return findings;
+})