oficina / mapa Public

Pages inside: Fable round 1 on the build

List ids are the row's path, so a page shown twice keeps two; script
puts every sidebar row in place from the next page, so lists, ids and
the one aria-current agree; a later toggle's reply wins; → and ← on an
arrow. Roots are pages with no parent in the set; a root already pinned
is marked pinned. The cap's cut list links to all; a closed row's arrow
asks only whether anything is inside. Gates: I17 crashes around the pin
write, I23 full sidebar, earlier run, failed parent and Resume by
another member; IN3 404s, IN7 depth and the 200 cap, IN8 a page shown
twice and the arrow keys, IN5 no move on mounting. Luna on the new
report sentences.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev 8585b08283aec78fee1fd291f1efe122200d4d8b parent 0b7cf66
16 files changed, +603 −58
  • copy-review/inside/result.json +16 −1
  • copy-review/inside/strings.json +24 −0
  • docs/superpowers/specs/2026-11-14-mapa-level-up.md +1 −0
  • docs/superpowers/specs/2026-11-22-mapa-columns-icons.md +4 −3
  • internal/mapa/graph.go +3 −0
  • internal/mapa/import_pins.go +12 −5
  • internal/mapa/import_pins_test.go +146 −0
  • internal/mapa/import_report.go +3 −1
  • internal/mapa/import_safety_test.go +20 −1
  • internal/mapa/inside.go +8 −0
  • internal/mapa/side_inside.go +38 −21
  • internal/mapa/static/frame.css +4 −2
  • internal/mapa/static/mapa.js +50 −21
  • internal/mapa/templates/import.html +1 −1
  • internal/mapatest/inside_browser_test.go +171 −2
  • internal/mapatest/inside_test.go +102 −0

CI passed — run details

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

added 16 packages in 486ms
cd editor && node build-bundles.mjs
wrote internal/mapa/static/editor.3c106a8d6eac2ca9.js (354648 bytes, 111.4KB gzipped; L12 budget 120KB)
cd editor && node --test
✔ a badge is named for what it does, starting with its visible word (3.91488ms)
✔ first words stop at five words or forty characters (0.240235ms)
✔ the field keeps one trimmed line, without brackets (0.366109ms)
✔ the field holds at most MaxAlt bytes, cut at a character (0.562193ms)
✔ days and weeks move across months and years (1.065235ms)
✔ a month keeps the day, or takes the month's last (0.2802ms)
✔ the grid is six weeks from Monday, as the month calendar draws it (0.473378ms)
✔ the grid starts the week where the locale does (0.539922ms)
✔ the keys move a day, a week, a month and a year (0.24274ms)
✔ the picked day is the chip [[ makes for a date (14.67095ms)
✔ Insert → Today's date still puts today in at once (2.099394ms)
✔ / offers Date, the picker, and Today's date beside it (0.20523ms)
✔ after a ! the chip goes in after a space, never as an embed (2.622053ms)
✔ where the Markdown would read the chip differently, it is refused (2.365076ms)
✔ over a selection the chip goes after it and the words stay (2.123208ms)
✔ today is the day in the viewer's zone (26.130614ms)
✔ every offered locale has cases (0.992441ms)
✔ dates.mjs writes every date Go writes, byte for byte (6.354256ms)
✔ a chip, the month and the week, in three locales (0.558716ms)
✔ dates.json is what ICU gives, byte for byte (562.291702ms)
✔ L1: mounting then serialising gives cleanBody(body), byte for byte (114.883847ms)
ℹ 871 bodies
✔ L1: mounting a stored body adds nothing, and saving it writes nothing new (112.650506ms)
✔ L2: one edited block changes only that block's bytes; undo gives the body back (135.412821ms)
ℹ 858 single-block edits
✔ L2: inserting or deleting a block changes bytes only at the new seams, by Join (139.227178ms)
ℹ 866 inserts, 817 deletes
✔ L3: seeded edits keep the document and its Markdown saying the same thing (5651.979334ms)
ℹ 20904 edits over 871 bodies
✔ L3: Link to a page makes exactly one chip, and changes nothing else (1479.437704ms)
ℹ 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 (1117.199484ms)
ℹ over 871 bodies: {"inserted":5158,"spaced":23,"refused":45,"unstable":9}
✔ linear: trailing spaces (32.91029ms)
✔ linear: trailing whitespace (27.238971ms)
✔ linear: unclosed web links (38.836079ms)
✔ linear: web links with no address (39.029269ms)
✔ linear: unclosed wiki links (40.139357ms)
✔ linear: unclosed embeds (26.94252ms)
✔ linear: closes only (7.166663ms)
✔ the selected words become the chip's shown text (12.277862ms)
✔ words that are the title make a plain [[Title]] (5.861813ms)
✔ spaces at the selection's edges stay outside the chip (1.226816ms)
✔ a date makes a date link, in a heading, an item and a quote (7.026211ms)
✔ bold words lose their bold: a chip carries no marks in Mapa's Markdown (1.384628ms)
✔ only the linked block's bytes change, and undo gives the body back (2.574745ms)
✔ a selection across blocks, over a chip or a break, or of brackets is refused (1.569701ms)
✔ a target the words cannot be linked to as typed is refused (0.299626ms)
✔ ⌘L: over a selection it opens Page link; with none it types [[; in code it does nothing (2.34533ms)
✔ web-linked words are refused: the address would be lost (review M4) (1.549213ms)
✔ words whose Markdown would read otherwise are refused (review M3) (4.296189ms)
✔ ⌘A then ⌘L says why, instead of doing nothing (review low 1) (0.4633ms)
✔ linkCheck says why it refuses (review low 2) (0.653622ms)
✔ golden file has bodies (0.781099ms)
✔ markup.mjs parses every body into Go's blocks, byte offsets and all (30.417024ms)
✔ markup.mjs strips and spans every block as Go does (64.183201ms)
✔ the schema's toDOM draws every body as Go renders it (82.894837ms)
✔ emphasis draws the four pinned outputs (21.985407ms)
✔ a body ends in the editor's empty paragraph (0.227723ms)
✔ the editor labels date chips as Go does, in every locale L4 holds (14.438329ms)
✔ a POST that never answers is aborted after the timeout (21.808048ms)
✔ a keepalive POST carries no signal, and an answer clears the timer (1.409064ms)
✔ autosave sends only what differs, and the tab owns the draft it wrote (9.036089ms)
✔ an offered draft never commits by itself; Save commits it (1.40138ms)
✔ reload, then close: sessionStorage says the draft is this tab's own (0.682426ms)
✔ closing carries text not yet sent, and the cap leaves it out (50.794799ms)
✔ clean rebase: applied, the caret survives, the base moves by the rebase POST (4.744571ms)
✔ the block under the caret is the teammate's too, and undo brings back yours (4.984264ms)
✔ typing mid-flight: the merge is not applied and the base does not move (1.769181ms)
✔ a merge the editor cannot represent stops after three tries (6.250112ms)
✔ a conflict is shown, locks the editor's own commits, and Resolve settles it (2.151921ms)
✔ leaving: a conflict stays with the choice; a failed flush offers Leave anyway; a stored draft leaves (2.229415ms)
✔ a stale tab shows the newer draft, offered, and never overwrites it (1.377485ms)
✔ the first scratch commit: empty creates nothing, then one page, then drafts on it (2.275841ms)
✔ noBase and gone lead to the existing choices (1.051119ms)
✔ a commit that merged is applied when nothing was typed since (2.027209ms)
✔ back from the cache: nothing unsaved reloads, unsaved text autosaves at once (7.845201ms)
✔ an own draft committed meanwhile goes on as a new draft (3.690855ms)
✔ a reload keeps a stored draft; unsent text still commits (0.599533ms)
✔ a page deleted mid-edit: what is typed is still stored as the draft, and nothing commits (H1) (1.211888ms)
✔ an offered draft committed in another tab: typing goes on as a new draft (H1) (4.993762ms)
✔ a commit reply without a revision is not a commit; an emptied day starts afresh (H2) (1.233087ms)
✔ Resolve stores what was typed first, and takes no typing until its answer is applied (M1) (2.137905ms)
✔ closing with a choice open, or commits held, still writes the text, never commits (M2) (2.454052ms)
✔ closing inside the settling window sends the loaded version with settling=1 (M3) (0.437732ms)
✔ a clean merge not applied because of typing still ends the choice on show (M4) (1.132471ms)
✔ settling finds the draft committed with a teammate's text: a close still writes (M-A) (0.555921ms)
✔ settling finds another tab's newer draft: the tab shows it before any typing (1.128504ms)
✔ a page deleted before the first autosave: the text is offered as a scratch page, and a close makes one (M-B) (0.701341ms)
✔ an autosave that never answered but landed: its 409 keeps the typing since (L3) (0.782972ms)
✔ marks: em outside strong, bold reopened around italics, edges outside (7.125787ms)
✔ marks close before code, links and atoms, and reopen after (0.551803ms)
✔ untouched blocks and atoms re-emit their source; edited atoms are written from attributes (7.368908ms)
✔ empty blocks are written as nothing (2.851759ms)
✔ an unclosed fence that is no longer last gets its closing fence (1.705133ms)
✔ the structure check puts Join's seam where a kept one would merge two blocks (2.586036ms)
✔ prepareSave adopts the parse when no seam or rewrite can save the document (4.334891ms)
✔ reparse: typed emphasis becomes a mark, "- " after a break becomes an item (2.493645ms)
✔ a trailing hard break stays on screen and is written as nothing (1.303999ms)
✔ the reparse waits while an IME is composing (0.758346ms)
✔ copied blocks paste with their bytes and seams; a cut and paste gives the body back (6.015968ms)
✔ a forged x-mapa slice is refused, and text from outside is read as Markdown (0.808239ms)
✔ rebuild changes origins only, outside undo history (2.501268ms)
✔ applyBody takes a teammate's block, keeps the caret, and ends untouched (1.946871ms)
✔ a block whose context changed is written again: a task toggled, a bullet, a quote (3.659178ms)
✔ a duplicate ^id typed above its holder never takes the id from it (1.203312ms)
✔ a copy-dragged block is reparsed, and says what its Markdown says (4.274738ms)
✔ a history command that throws is refused, never thrown (7.113054ms)
✔ an image re-emits its source, and an edited alt changes only its span (2.667467ms)
✔ a paste whose image copy is refused says why and pastes nothing (22.357687ms)
✔ a line of image openers reads in linear time (113.695553ms)
✔ a line of shared link address reads in linear time (12.643339ms)
✔ a line of shared web address reads in linear time (54.900084ms)
✔ one rename at a time, from either field (2.495007ms)
✔ an empty or unchanged title sends nothing (0.208556ms)
✔ a refusal keeps what was typed, and the title (0.436059ms)
✔ the pending state holds for the busy rule (7.204893ms)
✔ a failed POST says so and keeps the title (1.349043ms)
✔ Update links posts the confirm page's POST (0.283265ms)
✔ clean is CleanTitle's whitespace rule (0.438102ms)
✔ the saver's base follows a rename made over it, and only that (0.332847ms)
✔ closing sends the rename as one keepalive POST (2.346862ms)
✔ the port answers every shared case as typeddate.go does (5.927314ms)
✔ numbers follow the locale: 12/11 is November in en-IE, December in en-US (0.261776ms)
✔ M6: several files land in the order they were chosen (43.930308ms)
✔ M5: one Backspace before the box keeps the image where the box is (12.005217ms)
✔ M5: undoing text typed just before the box keeps the upload (12.715644ms)
✔ L12: a failed upload an undo takes away does not stall the next (14.451042ms)
✔ M4: Replace… keeps the old image until the new one is in, and its alt (14.338825ms)
✔ M3 and N1: text wins, except over a picture copied from a page (1.729077ms)
✔ N2: a JPEG over 10 MB is scaled before its size is checked (6.089524ms)
✔ a drag whose anchor the document no longer reaches selects to its end (7.543751ms)
ℹ tests 126
ℹ suites 0
ℹ pass 126
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 8931.62961
=== vet ===
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.899s
ok  	amadan.net/oficina/mapa/internal/mapa/emoji	(cached)
?   	amadan.net/oficina/mapa/internal/mapa/icons	[no test files]
ok  	amadan.net/oficina/mapa/internal/mapa/imagefile	(cached)
ok  	amadan.net/oficina/mapa/internal/mapa/locale	(cached)
ok  	amadan.net/oficina/mapa/internal/mapa/markup	(cached)
ok  	amadan.net/oficina/mapa/internal/mapa/notionmd	(cached)
ok  	amadan.net/oficina/mapa/internal/mapa/seal	(cached)
ok  	amadan.net/oficina/mapa/internal/mapatest	14.176s
?   	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/inside/result.json b/copy-review/inside/result.json
index b17c0fb..d37aaf3 100644
--- a/copy-review/inside/result.json
+++ b/copy-review/inside/result.json
@@ -1,7 +1,7 @@
{
"action": "approve",
"guidance": null,
- "note": "Reviewed 2026-11-22 by Luna (gpt-5.6-luna through Codex). Luna's edits are applied.",
+ "note": "Reviewed 2026-11-22 by Luna (gpt-5.6-luna through Codex). Luna's edits are applied. Three more strings (Fable's phase 3 review: one page, a full sidebar) reviewed the same day; Luna's next steps applied, and its flag that import.pins.one lacked \"team\" was a misreading.",
"not_applied": [],
"strings": [
{
@@ -38,6 +38,21 @@
"id": "import.pins.all",
"text": "Pinned your %d top-level team pages to your sidebar.",
"was": "Pinned your %d top-level pages to your sidebar."
+ },
+ {
+ "id": "import.pins.one",
+ "text": "Pinned your top-level team page to your sidebar.",
+ "was": null
+ },
+ {
+ "id": "import.pins.none.one",
+ "text": "Your sidebar already holds %d pins, so your top-level team page wasn’t pinned. Unpin a page from sidebar first, then choose Pin to sidebar.",
+ "was": "Your sidebar already holds %d pins, so your top-level team page wasn’t pinned."
+ },
+ {
+ "id": "import.pins.none",
+ "text": "Your sidebar already holds %d pins, so your %d top-level team pages weren’t pinned. Unpin pages from sidebar first, then choose Pin to sidebar for each page.",
+ "was": "Your sidebar already holds %d pins, so your %d top-level team pages weren’t pinned."
}
]
}
\ No newline at end of file
diff --git a/copy-review/inside/strings.json b/copy-review/inside/strings.json
index 194693f..fa1547f 100644
--- a/copy-review/inside/strings.json
+++ b/copy-review/inside/strings.json
@@ -54,5 +54,29 @@
"text": "Pinned your %d top-level pages to your sidebar.",
"context": "The same when every top-level page fitted.",
"notes": ""
+ },
+ {
+ "id": "import.pins.one",
+ "section": "Import report",
+ "label": "import.pins.one",
+ "text": "Pinned your top-level team page to your sidebar.",
+ "context": "The import report, when the import found exactly one top-level page and pinned it to the sidebar of the person who ran the import.",
+ "notes": ""
+ },
+ {
+ "id": "import.pins.none.one",
+ "section": "Import report",
+ "label": "import.pins.none.one",
+ "text": "Your sidebar already holds %d pins, so your top-level team page wasn’t pinned.",
+ "context": "The import report, when the import's one top-level page could not be pinned because the sidebar is full. %d is the pin limit (20). The page's title follows as a link, where Page → Pin to sidebar is one click.",
+ "notes": ""
+ },
+ {
+ "id": "import.pins.none",
+ "section": "Import report",
+ "label": "import.pins.none",
+ "text": "Your sidebar already holds %d pins, so your %d top-level team pages weren’t pinned.",
+ "context": "The import report, when none of the import's top-level pages could be pinned because the sidebar is full. First %d is the pin limit (20), second the number of pages. A list of their titles follows, each a link.",
+ "notes": ""
}
]
\ No newline at end of file
diff --git a/docs/superpowers/specs/2026-11-14-mapa-level-up.md b/docs/superpowers/specs/2026-11-14-mapa-level-up.md
index 4f1818d..c11028c 100644
--- a/docs/superpowers/specs/2026-11-14-mapa-level-up.md
+++ b/docs/superpowers/specs/2026-11-14-mapa-level-up.md
@@ -877,6 +877,7 @@ Each quirk gets a WebKit case in `make browser` where possible, and a check by h
- A sealed list of page ids in the member record. No new plaintext column, so §4's list is unchanged.
- `POST /pins` changes it, held for 650ms.
- It logs one event whose object is the **member**, verb `pins`. It never names the page.
+- A `pins` event need not mean the list changed. The Notion import's pin write (columns and icons spec §6.3) logs one when it marks roots that found no free slot, so the marks and the event land in one transaction. It says only that the person's pins were considered.
- A deleted or out-of-scope page drops out of the list when it is read.
**History:**
diff --git a/docs/superpowers/specs/2026-11-22-mapa-columns-icons.md b/docs/superpowers/specs/2026-11-22-mapa-columns-icons.md
index c3b6b00..575c966 100644
--- a/docs/superpowers/specs/2026-11-22-mapa-columns-icons.md
+++ b/docs/superpowers/specs/2026-11-22-mapa-columns-icons.md
@@ -761,9 +761,10 @@ Fable found every round-1 finding answered in substance, and five mediums and si
### Phase 3: pages inside and the import's pins (`feat/pages-inside`)
- **P1, the relation.** `inTarget` reads a team page's first block: exactly `In: ` then one wiki link, no anchor, not a date; its folded target goes in the index's `within` map. `Inside` answers a team page's children in its own order (first links in its body, then by folded title), through the scoped view; private pages are neither children nor parents.
-- **P2, the arrow.** Pinned rows keep a 16px arrow cell. An arrow is a form (`POST /view/open`, the cookie, back to a checked local path), so it works with no script. With script, `mapa.js` sends the form in the background and puts the toggled row and its list in place from the page the server draws next, so the rest of the sidebar keeps its listeners; `GET /side/inside/{id}` (§5.3) was not needed. Opened lists show 50 rows and a link to `GET /p/{id}/inside`; the sidebar draws at most 200 opened rows; indents stop at four levels; a page that is one of its row's ancestors is listed without an arrow. The open list is a plain `ul` labelled "Pages inside <title>": `role="group"` made axe refuse its items.
+- **P2, the arrow.** Pinned rows keep a 16px arrow cell. An arrow is a form (`POST /view/open`, the cookie, back to a checked local path), so it works with no script. With script, `mapa.js` sends the form in the background and puts every sidebar row above the foot in place from the page the server draws next, so open lists, their ids and the one `aria-current` always agree (a page shown twice included); the foot keeps its listeners, and row menus and Search are delegated. A later toggle's reply wins over an earlier one. → opens and ← closes when an arrow has focus. `GET /side/inside/{id}` (§5.3) was not needed. An open list's id is its row's path of public ids (`inside-<ancestors>-<page>`). Opened lists show 50 rows and a link to `GET /p/{id}/inside`; the sidebar draws at most 200 opened rows, and a list the cap cuts gets the link too; a closed row's arrow asks only whether anything is inside, unsorted; indents stop at four levels; a page that is one of its row's ancestors is listed without an arrow. The open list is a plain `ul` labelled "Pages inside <title>": `role="group"` made axe refuse its items.
- **P3, not built: Page → Put inside… and Take out of.** Typing or deleting the `In:` line, with script or in the textarea, does it; a picker for it is left for later.
- **P4, pins.** The limit is 20 (Q4). A list sealed when it held 12 is read and is written as 20 on the next pin.
-- **P5, the import's pins.** After the fix-up pass and before `done`, one lease-checked `Store.write` pins the roots with no `pin` mark (live, surveyed with no imported parent, in survey order, after the runner's own pins, up to the free slots), marks each in its stored coordinate (read again inside the write, since the page's own transaction wrote it last), and logs one `pins` event by the runner. Nothing to offer writes nothing. The report counts the marks with the run's id.
-- **P6, gates.** IN1 and IN2 (`inside_test.go`), IN3, IN4, IN6 and IN7 (`mapatest/inside_test.go`), IN5 and IN8 (`inside_browser_test.go`, axe included), I23 (`import_pins_test.go`, the report too); gate 8 drives `POST /view/open`; two mutations (a private In: line counts; a root offered every run), both caught. Luna's wording applied (`copy-review/inside`).
+- **P5, the import's pins.** After the fix-up pass and before `done`, one lease-checked `Store.write` pins the roots with no `pin` mark (live, surveyed with no imported parent, that is with no parent in the set: a page whose parent failed or was deleted in Mapa is not a root, and is not marked; in survey order, after the runner's own pins, up to the free slots), marks each in its stored coordinate (read again inside the write, since the page's own transaction wrote it last), and logs one `pins` event by the runner. A root already in the runner's pins is marked pinned. Nothing to offer writes nothing. The report counts the marks with the run's id, with a sentence for one page and for a full sidebar. The level-up spec's §8 Pins list now says a `pins` event need not mean a change.
+- **P6, gates.** IN1 and IN2 (`inside_test.go`); IN3 (the private In: line, and `/p/{id}/inside` a 404 for a private or missing page), IN4, IN6 and IN7 (a cycle, 51 children, indents stopping at four levels, the 200-row cap with its link) in `mapatest/inside_test.go`, with IN8's server half (a page shown twice: three distinct list ids, each named by an `aria-controls`, one lit row); IN5 (no move and no shift on mounting, with the cookie set) and IN8 (→ and ←, a page shown twice toggled by script, focus on the arrow pressed, axe) in `inside_browser_test.go`; I23 (`import_pins_test.go`: the report, a full sidebar, an earlier run's roots with one already pinned, a failed parent's child, Resume by another member) and I17's crash list gaining `pin:marked` and `write:pinned`, each resumed run pinning every root once; gate 8 drives `POST /view/open`; two mutations (a private In: line counts; a root offered every run), both caught. Luna's wording applied (`copy-review/inside`).
+- **P7, Fable on the build, round 1 (`0b7cf66`), CHANGES REQUIRED with no High.** Answered: list ids that a script toggle could repeat (M1), the wrong row swapped for a page shown twice (M2), `aria-current` doubled or lost after a toggle (M3), → and ← (M4), the gates above (M5), a failed parent's children taken for roots (M6), a root already pinned reported as having no slot (M7); lows 8, 10 to 17. Not done: low 9, the report's "your" for an importer who is not the run's actor: the marks do not record whose sidebar took the pins, and Resume by another member is rare.
diff --git a/internal/mapa/graph.go b/internal/mapa/graph.go
index 085c28c..9e5c1a0 100644
--- a/internal/mapa/graph.go
+++ b/internal/mapa/graph.go
@@ -102,6 +102,9 @@ func (index *Index) remove(pageID int64) {
}
if page.in != "" {
delete(index.within[page.in], page.id)
+ if len(index.within[page.in]) == 0 {
+ delete(index.within, page.in)
+ }
}
index.termsOf(page).remove(page.id, page.counts)
index.titlesDirty = index.titlesDirty || page.team()
diff --git a/internal/mapa/import_pins.go b/internal/mapa/import_pins.go
index 5f23fd7..f635185 100644
--- a/internal/mapa/import_pins.go
+++ b/internal/mapa/import_pins.go
@@ -42,26 +42,33 @@ func (job *importJob) autoPin(ctx context.Context, set *importSet) error {
return err
}
for _, entry := range roots {
- pinned := len(ids) < maxPins && !hasPin(ids, entry.place.PageID)
- if pinned {
- ids = append(ids, entry.place.PageID)
+ // A root the runner pinned already counts as pinned.
+ pinned := hasPin(ids, entry.place.PageID)
+ if !pinned && len(ids) < maxPins {
+ ids, pinned = append(ids, entry.place.PageID), true
}
entry.place.Pin = &pinMark{Run: job.lease.run, Pinned: pinned}
if err := tx.markPlace(entry); err != nil {
return err
}
}
+ if err := crashPoint("pin:marked"); err != nil {
+ return err
+ }
return tx.savePins(memberID, ids)
})
}
// unofferedRoots is the run's live roots that carry no pin mark, in
-// survey order.
+// survey order. A root is a page surveyed with no imported parent
+// (staged.Parent is ""): a page whose parent failed or was deleted in
+// Mapa this run has no In: line, but it is not top-level in Notion, so
+// it is not offered, and not marked (Fable on the build, M6).
func (job *importJob) unofferedRoots(set *importSet) []*importEntry {
var roots []*importEntry
for _, entry := range set.pages {
if entry.place.Pin != nil || entry.place.PageID == 0 ||
- set.parentTitle(entry) != "" || !entry.live {
+ entry.staged.Parent != "" || !entry.live {
continue
}
roots = append(roots, entry)
diff --git a/internal/mapa/import_pins_test.go b/internal/mapa/import_pins_test.go
index 4c1c13d..d59a825 100644
--- a/internal/mapa/import_pins_test.go
+++ b/internal/mapa/import_pins_test.go
@@ -3,7 +3,9 @@ package mapa
import (
"strings"
"testing"
+ "time"
+ "amadan.net/oficina/mapa/internal/mapa/notionmd"
"amadan.net/oficina/notion.git/notiontest"
)
@@ -87,3 +89,147 @@ func TestI23TheImportPinsItsRootsOnce(t *testing.T) {
}
}
}
+
+// I23, no free slot: a sidebar already holding maxPins pins gains none,
+// every root is still marked, listed by the report, and one pins event
+// is logged; a re-run offers nothing again.
+func TestI23WithNoFreeSlotRootsAreMarkedAndListed(t *testing.T) {
+ doc := notiontest.NewDocumented()
+ world := newImportWorld(t, doc.Workspace)
+ viewer, _ := world.store.Viewer(ctx(), ana, nil)
+ for at := range maxPins {
+ page := mustCreate(t, world.store, "Full "+strings.Repeat("x", at+1),
+ "Text.")
+ if err := world.store.SetPin(ctx(), viewer, page.ID,
+ true); err != nil {
+ t.Fatal(err)
+ }
+ }
+ before := pinTitles(t, world, ana)
+ events := world.count("events", "verb = ?", VerbPinsSet)
+ world.connect(ana)
+ run := world.importAs(ana)
+ report, err := world.store.report(ctx(), run)
+ if err != nil || report.Pinned != 0 || report.Offered == 0 ||
+ len(report.Unpinned) != report.Offered ||
+ report.PinLimit != maxPins {
+ t.Fatalf("the report: %+v %v", report, err)
+ }
+ if got := pinTitles(t, world, ana); strings.Join(got, "|") !=
+ strings.Join(before, "|") {
+ t.Fatalf("a full sidebar changed: %v", got)
+ }
+ if world.count("events", "verb = ?", VerbPinsSet) != events+1 {
+ t.Fatal("the marks were written without their one pins event")
+ }
+ world.server.Reset()
+ world.importAs(ana)
+ if world.count("events", "verb = ?", VerbPinsSet) != events+1 {
+ t.Fatal("a re-run offered the marked roots again")
+ }
+}
+
+// clearPinMarks takes every pin mark away, as the map stood before this
+// feature: the next run offers the roots an earlier run created.
+func (world *importWorld) clearPinMarks() {
+ world.t.Helper()
+ var rows []NotionPage
+ world.store.database.Find(&rows)
+ for _, row := range rows {
+ place, err := world.store.openCoordinate(row)
+ if err != nil || place.Pin == nil {
+ continue
+ }
+ place.Pin = nil
+ sealed, err := world.store.sealCoordinate(place)
+ if err != nil {
+ world.t.Fatal(err)
+ }
+ world.store.database.Model(&NotionPage{}).Where("id = ?", row.ID).
+ Update("sealed_coordinate", sealed)
+ }
+}
+
+// I23, an earlier run's roots: a map with no marks (Paul's existing
+// import) has its roots pinned by the next run, and a root the person
+// pinned already counts as pinned, not as one with no slot (Fable M7).
+func TestI23AnEarlierRunsRootsArePinnedOnce(t *testing.T) {
+ doc := notiontest.NewDocumented()
+ world := newImportWorld(t, doc.Workspace)
+ world.connect(ana)
+ first := world.importAs(ana)
+ report, _ := world.store.report(ctx(), first)
+ roots := report.Offered
+ viewer, _ := world.store.Viewer(ctx(), ana, nil)
+ pins := pinTitles(t, world, ana)
+ for _, title := range pins[1:] {
+ page, _, _ := world.pageTitled(title)
+ if err := world.store.SetPin(ctx(), viewer, page.ID,
+ false); err != nil {
+ t.Fatal(err)
+ }
+ }
+ world.clearPinMarks()
+ world.server.Reset()
+ again := world.importAs(ana)
+ report, err := world.store.report(ctx(), again)
+ if err != nil || report.Offered != roots || report.Pinned != roots ||
+ len(report.Unpinned) != 0 {
+ t.Fatalf("an earlier run's roots: %+v %v", report, err)
+ }
+ if got := pinTitles(t, world, ana); len(got) != roots {
+ t.Fatalf("pinned %v, want the %d roots once each", got, roots)
+ }
+}
+
+// I23, whose sidebar: a run Ana started and Bo resumed pins the roots to
+// Bo's sidebar, the run's actor at the pin write, and Ana's is untouched.
+func TestI23AResumedRunPinsToTheResumer(t *testing.T) {
+ doc := notiontest.NewDocumented()
+ world := newImportWorld(t, doc.Workspace)
+ world.connect(ana)
+ lease, err := world.store.StartRun(ctx(), ana, false)
+ if err != nil {
+ t.Fatal(err)
+ }
+ crashOn(t, "write:fixed", 1)
+ world.finish(lease, ana)
+ importCrash = nil
+ world.store.InterruptRuns(ctx())
+ resumed, err := world.store.ResumeRun(ctx(), bo)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if run := world.finish(resumed, bo); run.State != runDone {
+ t.Fatalf("resumed by Bo: %+v", run)
+ }
+ if got := pinTitles(t, world, ana); len(got) != 0 {
+ t.Fatalf("Ana's pins changed: %v", got)
+ }
+ if got := pinTitles(t, world, bo); len(got) == 0 {
+ t.Fatal("the resumer's sidebar has no roots")
+ }
+}
+
+// I23, roots only: a page whose parent failed this run has no In: line,
+// but it is not top-level in Notion, so it is neither pinned nor marked
+// (Fable on the build, M6).
+func TestI23AFailedParentsChildIsNoRoot(t *testing.T) {
+ doc := notiontest.NewDocumented()
+ world := newImportWorld(t, doc.Workspace)
+ world.connect(ana)
+ saved := renderBudgetFor
+ renderBudgetFor = func(page notionmd.Page) time.Duration {
+ if page.ID == doc.Child {
+ return time.Nanosecond
+ }
+ return time.Minute
+ }
+ t.Cleanup(func() { renderBudgetFor = saved })
+ world.importAs(ana)
+ for _, title := range pinTitles(t, world, ana) {
+ if title == "Grandchild" {
+ t.Fatal("a failed parent's child was pinned as a root")
+ }
+ }
+}
diff --git a/internal/mapa/import_report.go b/internal/mapa/import_report.go
index fa680ad..b53cc56 100644
--- a/internal/mapa/import_report.go
+++ b/internal/mapa/import_report.go
@@ -33,6 +33,8 @@ type reportView struct {
// icons spec §6.3): pinned, and those that found no free slot.
Pinned, Offered int
Unpinned []reportPage
+ // PinLimit is how many pins a sidebar holds.
+ PinLimit int
}
type countView struct {
@@ -57,7 +59,7 @@ func (store *Store) report(ctx context.Context,
}
view := &reportView{SurveyDone: run.Total > 0 ||
run.State == runDone || run.State == runWriting,
- Images: imageCounts{Failed: map[string]int{}}}
+ Images: imageCounts{Failed: map[string]int{}}, PinLimit: maxPins}
tally := &reportTally{view: view, store: store, ctx: ctx, run: run.ID,
losses: map[string]int{}, codes: map[string]int{},
byKey: map[string]reportRow{}}
diff --git a/internal/mapa/import_safety_test.go b/internal/mapa/import_safety_test.go
index 5f85844..586cb0c 100644
--- a/internal/mapa/import_safety_test.go
+++ b/internal/mapa/import_safety_test.go
@@ -40,7 +40,8 @@ func TestI16TheImportOnlyReads(t *testing.T) {
// crashPoints is every named point of the run and the two methods.
var crashPoints = []string{"survey:read", "survey:walked",
"write:rendered", "create:page", "create:title", "write:committed",
- "update:renamed", "update:edited", "write:fixed"}
+ "update:renamed", "update:edited", "write:fixed", "pin:marked",
+ "write:pinned"}
// I17, crash safety (spec §14.1). The process dies between every pair
// of statements in the run, ImportCreate and ImportUpdate, at the first
@@ -83,6 +84,24 @@ func crashThenResume(t *testing.T, point string, nth int, rerun bool) {
world.store.InterruptRuns(ctx())
world.resumeIfNeeded(lease)
world.checkMapAgrees(3)
+ world.checkPinnedOnce(ana)
+}
+
+// checkPinnedOnce is who's pins holding the import's roots, each once
+// (I23: a crash around the pin write pins nothing twice).
+func (world *importWorld) checkPinnedOnce(who string) {
+ world.t.Helper()
+ pins := pinTitles(world.t, world, who)
+ seen := map[string]bool{}
+ for _, title := range pins {
+ if seen[title] {
+ world.t.Errorf("%q pinned twice: %v", title, pins)
+ }
+ seen[title] = true
+ }
+ if len(pins) == 0 {
+ world.t.Error("the import pinned no root")
+ }
}
func (world *importWorld) resumeIfNeeded(lease runLease) {
diff --git a/internal/mapa/inside.go b/internal/mapa/inside.go
index 85893b1..dd6e852 100644
--- a/internal/mapa/inside.go
+++ b/internal/mapa/inside.go
@@ -92,6 +92,14 @@ func (index *Index) Inside(ctx context.Context, scope Scope,
return index.insideLocked(scope, pageID), nil
}
+// holdsAny is whether any page the scope may open is inside page id:
+// the arrow's test for a closed row, which needs no order. The caller
+// holds the read lock.
+func (index *Index) holdsAny(scope Scope, pageID int64) bool {
+ page := index.in(scope).page(pageID)
+ return page != nil && page.team() && len(index.insideOf(page)) > 0
+}
+
func (index *Index) insideLocked(scope Scope, pageID int64) []*entry {
page := index.in(scope).page(pageID)
if page == nil || !page.team() {
diff --git a/internal/mapa/side_inside.go b/internal/mapa/side_inside.go
index a048227..0a3763d 100644
--- a/internal/mapa/side_inside.go
+++ b/internal/mapa/side_inside.go
@@ -2,8 +2,8 @@ package mapa
import (
"context"
+ "log/slog"
"net/http"
- "strconv"
"strings"
)
@@ -46,7 +46,10 @@ func openRows(request *http.Request) []string {
// rows inside it, through the scoped accessor (§5.4).
func (index *Index) insideRows(ctx context.Context, scope Scope,
rows []sideLink, open []string, current string) {
- if index.Sync(ctx) != nil {
+ if err := index.Sync(ctx); err != nil {
+ // The rows draw closed, with no arrows: the sidebar is still
+ // whole, and the next page tries again.
+ slog.Warn("sidebar: index sync", "err", err)
return
}
index.mutex.RLock()
@@ -57,7 +60,7 @@ func (index *Index) insideRows(ctx context.Context, scope Scope,
expand.open[id] = true
}
for at := range rows {
- expand.row(&rows[at], 0, map[int64]bool{})
+ expand.row(&rows[at], 0, nil)
}
}
@@ -68,32 +71,33 @@ type opener struct {
current string
open map[string]bool
drawn int
- lists int
}
-func (expand *opener) row(row *sideLink, depth int, ancestors map[int64]bool) {
+// row draws one row's arrow and, when it is open, the rows inside it.
+// path is the row's ancestors in this sidebar, outermost first: a page
+// on it is listed without an arrow (a cycle), and it names the open
+// list, so a page shown twice has two ids (§5.3: inside-<row>-<page>).
+func (expand *opener) row(row *sideLink, depth int, path []*sideLink) {
row.Gutter, row.Depth = true, min(depth, insideDepth)
- if ancestors[row.id] {
+ for _, above := range path {
+ if above.id == row.id {
+ return
+ }
+ }
+ if !expand.open[row.page.Public] || expand.drawn >= insideTotal {
+ row.Arrow = expand.index.holdsAny(expand.scope, row.id)
return
}
children := expand.index.insideLocked(expand.scope, row.id)
row.Arrow = len(children) > 0
- row.Open = row.Arrow && expand.open[row.page.Public] &&
- expand.drawn < insideTotal
+ row.Open = row.Arrow
if !row.Open {
return
}
- expand.lists++
- row.ListID = "inside-" + strconv.Itoa(expand.lists)
- inner := map[int64]bool{row.id: true}
- for id := range ancestors {
- inner[id] = true
- }
- row.More = max(len(children)-insideShown, 0)
- if row.More > 0 {
- row.All = len(children)
- }
- for _, child := range children[:min(len(children), insideShown)] {
+ row.ListID = listID(path, row)
+ inner := append(append([]*sideLink{}, path...), row)
+ shown := children[:min(len(children), insideShown)]
+ for _, child := range shown {
if expand.drawn >= insideTotal {
break
}
@@ -102,6 +106,18 @@ func (expand *opener) row(row *sideLink, depth int, ancestors map[int64]bool) {
expand.row(&link, depth+1, inner)
row.Inside = append(row.Inside, link)
}
+ if len(row.Inside) < len(children) {
+ row.More, row.All = len(children)-len(row.Inside), len(children)
+ }
+}
+
+// listID is an open list's id: its row's path of public ids.
+func listID(path []*sideLink, row *sideLink) string {
+ parts := []string{"inside"}
+ for _, above := range path {
+ parts = append(parts, above.page.Public)
+ }
+ return strings.Join(append(parts, row.page.Public), "-")
}
// sideLinkOf is a page as a sidebar row.
@@ -115,8 +131,9 @@ func sideLinkOf(found *entry, scope Scope, current string) sideLink {
}
// viewOpen opens or closes one row's pages inside: POST /view/open with
-// id and open (1 or 0). It sets the cookie and goes back; with script,
-// it answers the open row's list as HTML (§5.3).
+// id and open (1 or 0). It sets the cookie and goes back, with script or
+// without: script reads the sidebar from the page it goes back to
+// (build note P2).
func (app *app) viewOpen(writer http.ResponseWriter, request *http.Request) {
id := request.PostFormValue("id")
open := openRows(request)
diff --git a/internal/mapa/static/frame.css b/internal/mapa/static/frame.css
index 5153b5a..291a070 100644
--- a/internal/mapa/static/frame.css
+++ b/internal/mapa/static/frame.css
@@ -237,7 +237,8 @@ kbd[mapa-kbd] {
[mapa-app][data-side="rail"] [mapa-side-item] > svg { inline-size: 18px; block-size: 18px; }
[mapa-app][data-side="rail"] [mapa-side-item] > kbd,
[mapa-app][data-side="rail"] [mapa-side-head],
- [mapa-app][data-side="rail"] [mapa-side-row] { display: none; }
+ [mapa-app][data-side="rail"] [mapa-side-row],
+ [mapa-app][data-side="rail"] ul[mapa-side-inside] { display: none; }
[mapa-app][data-side="rail"] [mapa-side-item][aria-current] { background: none; }
[mapa-app][data-side="rail"] [mapa-side-holds="open"] { display: none; }
[mapa-app][data-side="rail"] [mapa-side-holds="rail"] { display: grid; }
@@ -286,7 +287,8 @@ kbd[mapa-kbd] {
[mapa-app]:not([data-side]) [mapa-side-item] > svg { inline-size: 18px; block-size: 18px; }
[mapa-app]:not([data-side]) [mapa-side-item] > kbd,
[mapa-app]:not([data-side]) [mapa-side-head],
- [mapa-app]:not([data-side]) [mapa-side-row] { display: none; }
+ [mapa-app]:not([data-side]) [mapa-side-row],
+ [mapa-app]:not([data-side]) ul[mapa-side-inside] { display: none; }
[mapa-app]:not([data-side]) [mapa-side-item][aria-current] { background: none; }
[mapa-app]:not([data-side]) [mapa-side-holds="open"] { display: none; }
[mapa-app]:not([data-side]) [mapa-side-holds="rail"] { display: grid; }
diff --git a/internal/mapa/static/mapa.js b/internal/mapa/static/mapa.js
index 2849893..1d958ac 100644
--- a/internal/mapa/static/mapa.js
+++ b/internal/mapa/static/mapa.js
@@ -914,30 +914,58 @@
// and what was typed stay as they are. No busy rule: like the fold, it
// switches at once.
function sideArrows() {
+ var sent = 0;
document.addEventListener("submit", function (event) {
var form = event.target.closest && event.target.closest("form[mapa-side-arrow-form]");
if (!form) return;
event.preventDefault();
+ var nav = form.closest("nav[mapa-side]");
var id = form.querySelector('input[name="id"]').value;
+ // Which of this page's arrows it was: a page shown twice has two.
+ var same = nav ? arrowsFor(nav, id) : [];
+ var nth = Math.max(same.indexOf(form), 0);
+ var mine = ++sent;
fetch(form.action, { method: "POST", body: new URLSearchParams(new FormData(form)),
credentials: "same-origin" }).then(function (response) {
return response.text();
}).then(function (html) {
- // Only this row and its list are put in place: the rest of the
- // sidebar keeps its listeners.
- var row = form.closest("[mapa-side-row]");
- var page = new DOMParser().parseFromString(html, "text/html");
- var input = page.querySelector('nav[mapa-side] form[mapa-side-arrow-form] input[name="id"][value="' + id + '"]');
- var fresh = input && input.closest("[mapa-side-row]");
- if (!row || !fresh) { window.location.reload(); return; }
- var old = row.nextElementSibling;
- if (old && old.matches("ul[mapa-side-inside]")) old.remove();
- var list = fresh.nextElementSibling;
- row.replaceWith(fresh);
- if (list && list.matches("ul[mapa-side-inside]")) fresh.after(list);
- var button = fresh.querySelector("[mapa-side-arrow]");
+ if (mine !== sent) return; // a later toggle's reply is the one shown
+ var fresh = new DOMParser().parseFromString(html, "text/html").querySelector("nav[mapa-side]");
+ if (!nav || !nav.isConnected || !fresh) { window.location.reload(); return; }
+ // Every row above the foot comes from the server's next page, so
+ // the open lists, their ids and the one aria-current all agree
+ // (build note 80); the foot keeps its listeners, and row menus
+ // and search are delegated.
+ var foot = nav.querySelector("[mapa-side-foot]");
+ Array.prototype.slice.call(nav.children).forEach(function (child) {
+ if (child !== foot) child.remove();
+ });
+ Array.prototype.slice.call(fresh.children).forEach(function (child) {
+ if (!child.matches("[mapa-side-foot]")) nav.insertBefore(document.importNode(child, true), foot);
+ });
+ var again = arrowsFor(nav, id);
+ var button = (again[nth] || again[0] || nav).querySelector("[mapa-side-arrow]");
if (button) button.focus({ preventScroll: true });
- }).catch(function () { form.submit(); });
+ }).catch(function () {
+ if (form.isConnected) form.submit(); else window.location.reload();
+ });
+ });
+ // → opens and ← closes, when the arrow has focus (§5.3).
+ document.addEventListener("keydown", function (event) {
+ var button = event.target.closest && event.target.closest("[mapa-side-arrow]");
+ if (!button || event.altKey || event.ctrlKey || event.metaKey) return;
+ var open = button.getAttribute("aria-expanded") === "true";
+ if ((event.key === "ArrowRight" && !open) || (event.key === "ArrowLeft" && open)) {
+ event.preventDefault();
+ button.form.requestSubmit(button);
+ }
+ });
+ }
+
+ // arrowsFor is every arrow form in nav for one page, in document order.
+ function arrowsFor(nav, id) {
+ return Array.prototype.slice.call(nav.querySelectorAll("form[mapa-side-arrow-form]")).filter(function (form) {
+ return form.querySelector('input[name="id"]').value === id;
});
}
@@ -952,13 +980,14 @@
belowTheText();
// Search in the sidebar and in the bar's Menu sheet opens ⌘K;
// without script they are links to the search page.
- document.querySelectorAll('[estilo-bar] a[href="/search"], [mapa-side] a[href="/search"]').forEach(function (link) {
- link.addEventListener("click", function (event) {
- if (event.metaKey || event.ctrlKey || event.shiftKey) return;
- event.preventDefault();
- palette = palette || new Palette();
- palette.open();
- });
+ // Delegated: the sidebar's rows are put in place again when an
+ // arrow opens or closes a row (sideArrows).
+ document.addEventListener("click", function (event) {
+ var link = event.target.closest && event.target.closest('[estilo-bar] a[href="/search"], [mapa-side] a[href="/search"]');
+ if (!link || event.metaKey || event.ctrlKey || event.shiftKey) return;
+ event.preventDefault();
+ palette = palette || new Palette();
+ palette.open();
});
document.addEventListener("keydown", function (event) {
if ((event.metaKey || event.ctrlKey) && event.key === "k") {
diff --git a/internal/mapa/templates/import.html b/internal/mapa/templates/import.html
index cd97f93..2a6e04c 100644
--- a/internal/mapa/templates/import.html
+++ b/internal/mapa/templates/import.html
@@ -56,7 +56,7 @@
<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}}
-{{if or .Pinned .Unpinned}}<p mapa-import-pins>{{if .Unpinned}}Pinned {{number L .Pinned}} of your {{number L .Offered}} top-level team pages to your sidebar. Your sidebar holds {{number L 20}} pins.{{else}}Pinned your {{number L .Pinned}} top-level team pages to your sidebar.{{end}}</p>
+{{if or .Pinned .Unpinned}}<p mapa-import-pins>{{if not .Unpinned}}{{if eq .Pinned 1}}Pinned your top-level team page to your sidebar.{{else}}Pinned your {{number L .Pinned}} top-level team pages to your sidebar.{{end}}{{else if .Pinned}}Pinned {{number L .Pinned}} of your {{number L .Offered}} top-level team pages to your sidebar. Your sidebar holds {{number L .PinLimit}} pins.{{else if eq .Offered 1}}Your sidebar already holds {{number L .PinLimit}} pins, so your top-level team page wasn’t pinned. Unpin a page from sidebar first, then choose Pin to sidebar.{{else}}Your sidebar already holds {{number L .PinLimit}} pins, so your {{number L .Offered}} top-level team pages weren’t pinned. Unpin pages from sidebar first, then choose Pin to sidebar for each page.{{end}}</p>
{{with .Unpinned}}<ul mapa-list>{{range .}}<li>{{if .Href}}<a href="{{.Href}}">{{.Title}}</a>{{else}}{{.Title}}{{end}}</li>{{end}}</ul>{{end}}{{end}}
<dl rst-detail>
<dt>Pages seen</dt><dd>{{number L .Seen}}</dd>
diff --git a/internal/mapatest/inside_browser_test.go b/internal/mapatest/inside_browser_test.go
index 2284004..9d6ea2e 100644
--- a/internal/mapatest/inside_browser_test.go
+++ b/internal/mapatest/inside_browser_test.go
@@ -4,8 +4,13 @@ package mapatest
import (
"context"
+ "encoding/json"
+ "strings"
"testing"
+ "amadan.net/rastrillo/rastrillo/harness"
+ "github.com/chromedp/cdproto/cdp"
+ "github.com/chromedp/cdproto/network"
"github.com/chromedp/chromedp"
"github.com/chromedp/chromedp/kb"
@@ -13,8 +18,10 @@ import (
)
// IN5 and IN8 (columns and icons spec §5.3, §9) in a real Chromium: the
-// arrow opens the pages inside at once, with script, and keeps focus;
-// opened rows are on the first paint after; axe finds nothing serious.
+// arrow opens the pages inside at once, with script, by Enter, → and ←,
+// and keeps focus; a page shown twice keeps two list ids and one lit
+// row; opened rows are on the first paint, and mounting moves none of
+// them; axe finds nothing serious.
func TestIN8TheArrowByKeyboard(t *testing.T) {
rig, store := browserRig(t, 0)
@@ -49,3 +56,165 @@ func TestIN8TheArrowByKeyboard(t *testing.T) {
drive(t, rig, chromedp.Navigate(rig.Origin+mapa.PagePath(projects)),
chromedp.WaitVisible(`ul[mapa-side-inside] [mapa-side-label]`))
}
+
+// sideState is the sidebar's open lists' ids, its aria-controls, its
+// lit rows that show, and the focused element's name.
+const sideState = `JSON.stringify((function () {
+ var nav = document.querySelector("nav[mapa-side]");
+ var all = function (selector) {
+ return [].slice.call(nav.querySelectorAll(selector));
+ };
+ var ids = all("ul[mapa-side-inside]").map(function (list) {
+ return list.id;
+ });
+ var controls = all("[aria-controls]").map(function (button) {
+ return button.getAttribute("aria-controls");
+ });
+ var lit = all('[aria-current="page"]').filter(function (row) {
+ return !row.hidden;
+ }).length;
+ return { ids: ids, controls: controls, lit: lit,
+ focus: document.activeElement.getAttribute("aria-label") || "" };
+})())`
+
+type sideReading struct {
+ IDs []string `json:"ids"`
+ Controls []string `json:"controls"`
+ Lit int `json:"lit"`
+ Focus string `json:"focus"`
+}
+
+func readSide(t *testing.T, rig *harness.Rig) sideReading {
+ t.Helper()
+ var reading sideReading
+ raw := read(t, rig, chromedp.Evaluate[string](sideState))
+ if err := json.Unmarshal([]byte(raw), &reading); err != nil {
+ t.Fatal(err)
+ }
+ return reading
+}
+
+// IN8 with script: Inner is pinned and inside pinned Outer, so it shows
+// twice. Opening each by → keeps every list id distinct and named by its
+// button, one lit row, and focus on the arrow pressed; ← closes it.
+func TestIN8ArrowKeysAndAPageShownTwice(t *testing.T) {
+ rig, store := browserRig(t, 0)
+ ctx := context.Background()
+ viewer, _ := store.Viewer(ctx, Ana, nil)
+ var leaf mapa.Page
+ for _, each := range []struct{ title, body string }{
+ {"Outer", "Text."}, {"Inner", "In: [[Outer]]"},
+ {"Leaf", "In: [[Inner]]\n\nWords."}} {
+ page, err := store.CreateTeamPage(ctx, Bo, each.title, each.body)
+ if err != nil {
+ t.Fatal(err)
+ }
+ leaf = page
+ if each.title != "Leaf" {
+ if err := store.SetPin(ctx, viewer, page.ID, true); err != nil {
+ t.Fatal(err)
+ }
+ }
+ }
+ drive(t, rig, chromedp.EmulateViewport(1440, 900),
+ chromedp.Navigate(rig.Origin+mapa.PagePath(leaf)),
+ chromedp.WaitVisible(mounted))
+ press := func(label string, key string) {
+ drive(t, rig, chromedp.Focus(`[mapa-side-arrow][aria-label="`+
+ label+`"]`), chromedp.KeyEvent(key))
+ }
+ press("Pages inside Outer", kb.ArrowRight)
+ eventually(t, "Outer open", func() bool {
+ return len(readSide(t, rig).IDs) == 1
+ })
+ // Inner's pinned row is the second arrow named for Inner.
+ drive(t, rig, chromedp.Evaluate[chromedp.Void](`document.querySelectorAll(
+ '[mapa-side-arrow][aria-label="Pages inside Inner"]')[1].focus()`),
+ chromedp.KeyEvent(kb.ArrowRight))
+ eventually(t, "Inner open in both places", func() bool {
+ return len(readSide(t, rig).IDs) == 3
+ })
+ reading := readSide(t, rig)
+ seen := map[string]bool{}
+ for _, id := range reading.IDs {
+ if seen[id] || !strings.Contains(strings.Join(reading.Controls,
+ " "), id) {
+ t.Fatalf("list ids %v, controls %v", reading.IDs, reading.Controls)
+ }
+ seen[id] = true
+ }
+ if reading.Lit != 1 || reading.Focus != "Pages inside Inner" {
+ t.Fatalf("after opening: %+v", reading)
+ }
+ focused := evaluate(t, rig, `String([].indexOf.call(
+ document.querySelectorAll(
+ '[mapa-side-arrow][aria-label="Pages inside Inner"]'),
+ document.activeElement))`)
+ if focused != "1" {
+ t.Fatalf("focus went to Inner's arrow %s, not the one pressed", focused)
+ }
+ drive(t, rig, chromedp.KeyEvent(kb.ArrowLeft))
+ eventually(t, "Inner closed", func() bool {
+ return len(readSide(t, rig).IDs) == 1
+ })
+ if reading := readSide(t, rig); reading.Lit != 1 {
+ t.Fatalf("after closing: %+v", reading)
+ }
+}
+
+// sideBoxes is every sidebar row's and open list's box.
+const sideBoxes = `JSON.stringify([].map.call(
+ document.querySelectorAll("nav[mapa-side] [mapa-side-row], " +
+ "nav[mapa-side] ul[mapa-side-inside]"),
+ function (row) {
+ var box = row.getBoundingClientRect();
+ return [box.left, box.top, box.width, box.height].join(" ");
+ }))`
+
+// IN5: with the cookie set, opened rows are on the server's HTML, and
+// mounting moves none of the sidebar's rows.
+func TestIN5OpenRowsAreOnTheFirstPaint(t *testing.T) {
+ rig, store := browserRig(t, 0)
+ ctx := context.Background()
+ projects, err := store.CreateTeamPage(ctx, Bo, "Projects", "See.")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := store.CreateTeamPage(ctx, Bo, "Alpha",
+ "In: [[Projects]]\n\nText."); err != nil {
+ t.Fatal(err)
+ }
+ viewer, _ := store.Viewer(ctx, Ana, nil)
+ if err := store.SetPin(ctx, viewer, projects.ID, true); err != nil {
+ t.Fatal(err)
+ }
+ drive(t, rig, onNewDocument(shiftRecorder),
+ openCookie(rig, strings.TrimPrefix(mapa.PagePath(projects), "/p/")))
+ load := func(live bool) string {
+ drive(t, rig, scripts(live), chromedp.EmulateViewport(1440, 900),
+ chromedp.Navigate(rig.Origin+mapa.PagePath(projects)),
+ chromedp.WaitVisible(`ul[mapa-side-inside]`))
+ if live {
+ drive(t, rig, chromedp.WaitVisible(mounted))
+ }
+ return read(t, rig, chromedp.Evaluate[string](sideBoxes))
+ }
+ if before, after := load(false), load(true); before != after {
+ t.Fatalf("the sidebar moved on mounting:\n%s\n%s", before, after)
+ }
+ shifts := evaluate(t, rig, `JSON.stringify(window.__shifts || [])`)
+ if shifts != "[]" {
+ t.Fatalf("layout shifts %s", shifts)
+ }
+}
+
+// openCookie sets the mapa-open cookie.
+func openCookie(rig *harness.Rig, value string) chromedp.Action[chromedp.Void] {
+ return chromedp.Func(func(ctx context.Context,
+ target *chromedp.Target) error {
+ _, err := cdp.Call(ctx, target, network.SetCookie,
+ network.SetCookieParams{Name: "mapa-open", Value: value,
+ URL: rig.Origin + "/"})
+ return err
+ })
+}
diff --git a/internal/mapatest/inside_test.go b/internal/mapatest/inside_test.go
index c738b72..9d4cb34 100644
--- a/internal/mapatest/inside_test.go
+++ b/internal/mapatest/inside_test.go
@@ -4,6 +4,7 @@ import (
"net/http"
"net/http/httptest"
"net/url"
+ "regexp"
"strings"
"testing"
)
@@ -74,6 +75,20 @@ func TestIN3PrivateInLinesAreNoPageInside(t *testing.T) {
if strings.Contains(before, "Pages inside Projects") {
t.Fatal("an arrow on a page with nothing inside")
}
+ // /p/{id}/inside is the app's 404 for a private page, as for one
+ // that does not exist, to its owner too.
+ scratch := rig.post(t, Ana, "/scratch", url.Values{"body": {"Mine."}}).
+ Header().Get("Location")
+ for _, who := range []string{Ana, Bo} {
+ if code := rig.get(t, who, scratch+"/inside").Code; scratch == "" ||
+ code != http.StatusNotFound {
+ t.Fatalf("a private page's inside list for %s: %d", who, code)
+ }
+ }
+ if code := rig.get(t, Bo, "/p/nothere/inside").Code; code !=
+ http.StatusNotFound {
+ t.Fatalf("a missing page's inside list: %d", code)
+ }
}
func TestIN4OpeningWritesNothing(t *testing.T) {
@@ -117,3 +132,90 @@ func TestIN7CyclesAndCaps(t *testing.T) {
t.Fatal("the list of all pages inside is not all of them")
}
}
+
+// IN7, depth: a chain six deep, every row open, indents no further than
+// four levels.
+func TestIN7IndentsStopAtFourLevels(t *testing.T) {
+ rig := newRig(t)
+ top := pinned(t, rig, "Level 0", "Top.")
+ ids := []string{strings.TrimPrefix(top, "/p/")}
+ for level := 1; level <= 6; level++ {
+ path := rig.createPage(t, Ana, "Level "+string(rune('0'+level)),
+ "In: [[Level "+string(rune('0'+level-1))+"]]")
+ ids = append(ids, strings.TrimPrefix(path, "/p/"))
+ }
+ page := opened(t, rig, top, ids...)
+ if !strings.Contains(page, "mapa-side-label>Level 6<") {
+ t.Fatal("the chain did not open to its end")
+ }
+ for _, depth := range regexp.MustCompile(`data-depth="(\d+)"`).
+ FindAllStringSubmatch(page, -1) {
+ if depth[1] > "4" {
+ t.Fatalf("a row indented %s levels", depth[1])
+ }
+ }
+}
+
+// IN7, the total cap: five open rows of 45 pages each draw 200 rows in
+// all; the row the cap cuts links to all of its pages.
+func TestIN7TheSidebarDrawsAtMost200OpenRows(t *testing.T) {
+ rig := newRig(t)
+ var ids []string
+ for parent := range 5 {
+ title := "Shelf " + string(rune('A'+parent))
+ path := pinned(t, rig, title, "Text.")
+ ids = append(ids, strings.TrimPrefix(path, "/p/"))
+ for at := range 45 {
+ rig.createPage(t, Ana, title+" book "+strings.Repeat("x", at+1),
+ "In: [["+title+"]]")
+ }
+ }
+ page := sideOf(opened(t, rig, "/pages", ids...))
+ books := regexp.MustCompile(`mapa-side-label>Shelf . book x`)
+ if got := len(books.FindAllString(page, -1)); got != 200 {
+ t.Fatalf("%d open rows drawn, want 200", got)
+ }
+ if strings.Count(page, `/inside">See all pages inside (45)`) != 1 {
+ t.Fatal("the row the cap cuts has no link to all its pages")
+ }
+}
+
+// IN7 and IN8 without script: a page shown twice (pinned, and inside
+// another pinned page) gives its two open lists two ids, every
+// aria-controls names a list that is there, and exactly one row is lit.
+func TestIN8APageShownTwiceHasTwoListsAndOneLight(t *testing.T) {
+ rig := newRig(t)
+ outer := pinned(t, rig, "Outer", "Text.")
+ inner := pinned(t, rig, "Inner", "In: [[Outer]]")
+ leaf := rig.createPage(t, Ana, "Leaf", "In: [[Inner]]")
+ page := opened(t, rig, leaf, strings.TrimPrefix(outer, "/p/"),
+ strings.TrimPrefix(inner, "/p/"))
+ side := sideOf(page)
+ if strings.Count(side, "mapa-side-label>Leaf<") != 2 {
+ t.Fatal("Leaf is not shown in both of Inner's lists")
+ }
+ controls := regexp.MustCompile(`aria-controls="([^"]+)"`).
+ FindAllStringSubmatch(side, -1)
+ seen := map[string]bool{}
+ for _, each := range controls {
+ if seen[each[1]] || !strings.Contains(side, `id="`+each[1]+`"`) {
+ t.Fatalf("aria-controls %q repeats or names nothing", each[1])
+ }
+ seen[each[1]] = true
+ }
+ if len(seen) != 3 {
+ t.Fatalf("%d open lists, want 3", len(seen))
+ }
+ // The rail's lit copy of a place is hidden (build note 80).
+ lit := strings.Count(side, `aria-current="page"`) -
+ strings.Count(side, `aria-current="page" hidden`)
+ if lit != 1 {
+ t.Fatalf("%d rows lit, want 1", lit)
+ }
+}
+
+// sideOf is a page's sidebar.
+func sideOf(page string) string {
+ side := page[strings.Index(page, "<nav mapa-side"):]
+ return side[:strings.Index(side, "</nav>")]
+}