oficina / mapa Public

Mapa: pages inside and the import's pins (columns and icons spec, phase 3)

A team page whose first line is In: [[P]] is inside P, derived in the
index and read through the scoped accessor. Pinned rows get a disclosure
arrow (a POST form with no script, the mapa-open cookie, a background
toggle with it), up to 50 rows a list and 200 in all, with
/p/{id}/inside for the rest. The Notion import pins its roots to the
runner's sidebar once, marked in the sealed coordinate, in one
lease-checked write with its pins event. Pins hold 20. Gates IN1 to IN8
and I23.

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

Squashed from feat/pages-inside into main.
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 2be768076172bf9a3a6e6ee5ea3eeee873512d97 parent 416eb3f
30 files changed, +1,661 −39
  • AGENTS.md +7 −0
  • copy-review/inside/result.json +58 −0
  • copy-review/inside/strings.json +82 −0
  • docs/superpowers/specs/2026-11-14-mapa-level-up.md +1 −0
  • docs/superpowers/specs/2026-11-22-mapa-columns-icons.md +11 −0
  • internal/mapa/graph.go +12 −0
  • internal/mapa/import_ledger.go +4 −0
  • internal/mapa/import_pins.go +107 −0
  • internal/mapa/import_pins_test.go +288 −0
  • internal/mapa/import_report.go +17 −1
  • internal/mapa/import_safety_test.go +20 −1
  • internal/mapa/import_write.go +6 −0
  • internal/mapa/index.go +8 −1
  • internal/mapa/inside.go +109 −0
  • internal/mapa/inside_test.go +61 −0
  • internal/mapa/pins.go +10 −6
  • internal/mapa/recent.go +1 −5
  • internal/mapa/render.go +1 −1
  • internal/mapa/side.go +27 −14
  • internal/mapa/side_inside.go +211 −0
  • internal/mapa/static/frame.css +43 −2
  • internal/mapa/static/mapa.js +84 −7
  • internal/mapa/templates/frame.html +10 −1
  • internal/mapa/templates/import.html +2 −0
  • internal/mapa/templates/inside.html +9 −0
  • internal/mapatest/gate8_test.go +4 −0
  • internal/mapatest/inside_browser_test.go +220 −0
  • internal/mapatest/inside_test.go +221 −0
  • scripts/mutate/inside.go +26 −0
  • scripts/mutate/main.go +1 −0

CI passed — run details

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

added 16 packages in 333ms
cd editor && node build-bundles.mjs
wrote internal/mapa/static/editor.bad1b29c273b6a86.js (364471 bytes, 114.4KB gzipped; L12 budget 120KB)
cd editor && node --test
✔ a badge is named for what it does, starting with its visible word (1.008349ms)
✔ first words stop at five words or forty characters (0.182627ms)
✔ the field keeps one trimmed line, without brackets (0.355475ms)
✔ the field holds at most MaxAlt bytes, cut at a character (0.904527ms)
✔ a block becomes column 1 of two, and undo gives it back (12.287535ms)
✔ a selection over blocks moves them all into column 1 (2.182693ms)
✔ no layout is made inside a layout (0.522804ms)
✔ Add a column, Remove this column and Undo columns (6.813892ms)
✔ Undo columns puts the blocks in reading order (0.761043ms)
✔ Backspace in an empty column takes the column away (1.042381ms)
✔ ⌥⌘→ and ⌥⌘← move between columns (0.508648ms)
✔ typing a fence line in a column never closes it (D16) (9.691517ms)
✔ a selection holding a layout makes no nested layout (H1) (2.82063ms)
✔ a fence typed after a break in a column stays in the column (H2) (5.688597ms)
✔ code holding a fence line and ::: stays code in its column (H2) (3.625194ms)
✔ Backspace after a layout and Delete before one join nothing (M4) (1.313892ms)
✔ deleting across columns keeps every column (M3) (2.10995ms)
✔ a layout pasted into a column arrives as its blocks (M1) (7.986873ms)
✔ copying inside one column puts no fence on the clipboard (M2) (0.331081ms)
✔ typing goes on in the column after a structural reparse (round 2) (11.562837ms)
✔ a structural reparse in a column leaves code as it was (round 2) (2.643875ms)
✔ days and weeks move across months and years (1.325994ms)
✔ a month keeps the day, or takes the month's last (0.254038ms)
✔ the grid is six weeks from Monday, as the month calendar draws it (2.15406ms)
✔ the grid starts the week where the locale does (0.65631ms)
✔ the keys move a day, a week, a month and a year (0.297318ms)
✔ the picked day is the chip [[ makes for a date (18.075644ms)
✔ Insert → Today's date still puts today in at once (1.978628ms)
✔ / offers Date, the picker, and Today's date beside it (0.327984ms)
✔ after a ! the chip goes in after a space, never as an embed (3.179883ms)
✔ where the Markdown would read the chip differently, it is refused (3.518276ms)
✔ over a selection the chip goes after it and the words stay (2.049529ms)
✔ today is the day in the viewer's zone (19.006169ms)
✔ every offered locale has cases (1.037513ms)
✔ dates.mjs writes every date Go writes, byte for byte (5.668421ms)
✔ a chip, the month and the week, in three locales (0.557728ms)
✔ dates.json is what ICU gives, byte for byte (492.44449ms)
✔ L1: mounting then serialising gives cleanBody(body), byte for byte (83.970156ms)
ℹ 901 bodies
✔ L1: mounting a stored body adds nothing, and saving it writes nothing new (96.419168ms)
✔ L2: one edited block changes only that block's bytes; undo gives the body back (150.347803ms)
ℹ 888 single-block edits
✔ L2: inserting or deleting a block changes bytes only at the new seams, by Join (155.787312ms)
ℹ 896 inserts, 837 deletes
✔ L3: seeded edits keep the document and its Markdown saying the same thing (5641.790179ms)
ℹ 21624 edits over 901 bodies
✔ L3: Link to a page makes exactly one chip, and changes nothing else (1281.394224ms)
ℹ 4710 links over 901 bodies; refused: {"A page link can’t hold another link or a line break. Select plain words.":945,"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 (1299.684567ms)
ℹ over 901 bodies: {"inserted":5338,"spaced":23,"refused":45,"unstable":9}
✔ linear: trailing spaces (30.357837ms)
✔ linear: trailing whitespace (32.918759ms)
✔ linear: unclosed web links (22.164843ms)
✔ linear: web links with no address (28.632507ms)
✔ linear: unclosed wiki links (41.207519ms)
✔ linear: unclosed embeds (19.5594ms)
✔ linear: closes only (7.614068ms)
✔ the selected words become the chip's shown text (13.13127ms)
✔ words that are the title make a plain [[Title]] (5.815001ms)
✔ spaces at the selection's edges stay outside the chip (1.545249ms)
✔ a date makes a date link, in a heading, an item and a quote (9.125383ms)
✔ bold words lose their bold: a chip carries no marks in Mapa's Markdown (1.78967ms)
✔ only the linked block's bytes change, and undo gives the body back (3.476219ms)
✔ a selection across blocks, over a chip or a break, or of brackets is refused (1.929557ms)
✔ a target the words cannot be linked to as typed is refused (0.353011ms)
✔ ⌘L: over a selection it opens Page link; with none it types [[; in code it does nothing (2.919752ms)
✔ web-linked words are refused: the address would be lost (review M4) (1.639923ms)
✔ words whose Markdown would read otherwise are refused (review M3) (2.499639ms)
✔ ⌘A then ⌘L says why, instead of doing nothing (review low 1) (1.796562ms)
✔ linkCheck says why it refuses (review low 2) (1.500246ms)
✔ golden file has bodies (1.043965ms)
✔ markup.mjs parses every body into Go's blocks, byte offsets and all (39.301595ms)
✔ markup.mjs strips and spans every block as Go does (75.864915ms)
✔ the schema's toDOM draws every body as Go renders it (67.252456ms)
✔ emphasis draws the four pinned outputs (19.427016ms)
✔ a body ends in the editor's empty paragraph (0.218833ms)
✔ the editor labels date chips as Go does, in every locale L4 holds (10.850394ms)
✔ a POST that never answers is aborted after the timeout (22.161117ms)
✔ a keepalive POST carries no signal, and an answer clears the timer (1.23141ms)
✔ autosave sends only what differs, and the tab owns the draft it wrote (13.597128ms)
✔ an offered draft never commits by itself; Save commits it (1.460382ms)
✔ reload, then close: sessionStorage says the draft is this tab's own (0.812017ms)
✔ closing carries text not yet sent, and the cap leaves it out (42.773165ms)
✔ clean rebase: applied, the caret survives, the base moves by the rebase POST (4.64822ms)
✔ the block under the caret is the teammate's too, and undo brings back yours (3.935776ms)
✔ typing mid-flight: the merge is not applied and the base does not move (1.961886ms)
✔ a merge the editor cannot represent stops after three tries (3.958157ms)
✔ a conflict is shown, locks the editor's own commits, and Resolve settles it (2.359961ms)
✔ leaving: a conflict stays with the choice; a failed flush offers Leave anyway; a stored draft leaves (2.00648ms)
✔ a stale tab shows the newer draft, offered, and never overwrites it (1.503431ms)
✔ the first scratch commit: empty creates nothing, then one page, then drafts on it (1.063601ms)
✔ noBase and gone lead to the existing choices (0.811076ms)
✔ a commit that merged is applied when nothing was typed since (0.76981ms)
✔ back from the cache: nothing unsaved reloads, unsaved text autosaves at once (7.635786ms)
✔ an own draft committed meanwhile goes on as a new draft (1.317028ms)
✔ a reload keeps a stored draft; unsent text still commits (0.494191ms)
✔ a page deleted mid-edit: what is typed is still stored as the draft, and nothing commits (H1) (1.094508ms)
✔ an offered draft committed in another tab: typing goes on as a new draft (H1) (2.275746ms)
✔ a commit reply without a revision is not a commit; an emptied day starts afresh (H2) (0.974777ms)
✔ Resolve stores what was typed first, and takes no typing until its answer is applied (M1) (3.501996ms)
✔ closing with a choice open, or commits held, still writes the text, never commits (M2) (2.922808ms)
✔ closing inside the settling window sends the loaded version with settling=1 (M3) (0.420445ms)
✔ a clean merge not applied because of typing still ends the choice on show (M4) (1.493023ms)
✔ settling finds the draft committed with a teammate's text: a close still writes (M-A) (0.939773ms)
✔ settling finds another tab's newer draft: the tab shows it before any typing (0.788023ms)
✔ a page deleted before the first autosave: the text is offered as a scratch page, and a close makes one (M-B) (0.799874ms)
✔ an autosave that never answered but landed: its 409 keeps the typing since (L3) (0.713936ms)
✔ marks: em outside strong, bold reopened around italics, edges outside (8.468583ms)
✔ marks close before code, links and atoms, and reopen after (0.532882ms)
✔ untouched blocks and atoms re-emit their source; edited atoms are written from attributes (7.80503ms)
✔ empty blocks are written as nothing (3.628861ms)
✔ an unclosed fence that is no longer last gets its closing fence (3.471369ms)
✔ the structure check puts Join's seam where a kept one would merge two blocks (1.928845ms)
✔ prepareSave adopts the parse when no seam or rewrite can save the document (2.427936ms)
✔ reparse: typed emphasis becomes a mark, "- " after a break becomes an item (2.709185ms)
✔ a trailing hard break stays on screen and is written as nothing (0.659907ms)
✔ the reparse waits while an IME is composing (0.930015ms)
✔ copied blocks paste with their bytes and seams; a cut and paste gives the body back (4.23697ms)
✔ a forged x-mapa slice is refused, and text from outside is read as Markdown (0.823007ms)
✔ rebuild changes origins only, outside undo history (2.449557ms)
✔ applyBody takes a teammate's block, keeps the caret, and ends untouched (2.552135ms)
✔ a block whose context changed is written again: a task toggled, a bullet, a quote (2.428878ms)
✔ a duplicate ^id typed above its holder never takes the id from it (1.571477ms)
✔ a copy-dragged block is reparsed, and says what its Markdown says (1.805549ms)
✔ a history command that throws is refused, never thrown (5.362297ms)
✔ an image re-emits its source, and an edited alt changes only its span (1.407665ms)
✔ a paste whose image copy is refused says why and pastes nothing (23.351469ms)
✔ a line of image openers reads in linear time (82.803777ms)
✔ a line of shared link address reads in linear time (17.327855ms)
✔ a line of shared web address reads in linear time (56.388657ms)
✔ one rename at a time, from either field (2.179699ms)
✔ an empty or unchanged title sends nothing (0.234001ms)
✔ a refusal keeps what was typed, and the title (0.28771ms)
✔ the pending state holds for the busy rule (6.887898ms)
✔ a failed POST says so and keeps the title (0.565372ms)
✔ Update links posts the confirm page's POST (0.812969ms)
✔ clean is CleanTitle's whitespace rule (0.247467ms)
✔ the saver's base follows a rename made over it, and only that (0.373769ms)
✔ closing sends the rename as one keepalive POST (2.789744ms)
✔ the port answers every shared case as typeddate.go does (5.789703ms)
✔ numbers follow the locale: 12/11 is November in en-IE, December in en-US (0.248809ms)
✔ M6: several files land in the order they were chosen (52.172565ms)
✔ M5: one Backspace before the box keeps the image where the box is (10.140815ms)
✔ M5: undoing text typed just before the box keeps the upload (11.924083ms)
✔ L12: a failed upload an undo takes away does not stall the next (13.874439ms)
✔ M4: Replace… keeps the old image until the new one is in, and its alt (14.238851ms)
✔ M3 and N1: text wins, except over a picture copied from a page (1.391305ms)
✔ N2: a JPEG over 10 MB is scaled before its size is checked (11.376104ms)
✔ a drag whose anchor the document no longer reaches selects to its end (6.309512ms)
ℹ tests 143
ℹ suites 0
ℹ pass 143
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 8876.546358
=== 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	4.225s
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	16.151s
?   	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/AGENTS.md b/AGENTS.md
index 129063f..8d248cd 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -166,6 +166,13 @@ Makefile, estilo's files served straight from the module).
origins on the containers: `originAttr`), and `fidelity.mjs`'s
`fenceRule` (D16). `make pandoc-fixture` records Pandoc's reading
(`markup/testdata/pandoc.json`, COL12).
+ - Pages inside (the same spec, §5, §6.3, phase 3): `inside.go` (the
+ "In: [[P]]" relation, derived in the index's `within` map, and the
+ scoped `Inside`), `side_inside.go` (the Pinned rows' arrows, the
+ `mapa-open` cookie, `POST /view/open` and `GET /p/{id}/inside`),
+ `import_pins.go` (the import pins its roots once, marked in the
+ sealed coordinate). Pins hold up to 20 (`pins.go` still reads a
+ list sealed at 12).
- `internal/mapatest/` — the gates of spec §11, from the outside.
`browser_test.go` is behind the `browser` tag.
- `scripts/preview/`, `scripts/mutate/` — `make preview`, `make mutate`.
diff --git a/copy-review/inside/result.json b/copy-review/inside/result.json
new file mode 100644
index 0000000..d37aaf3
--- /dev/null
+++ b/copy-review/inside/result.json
@@ -0,0 +1,58 @@
+{
+ "action": "approve",
+ "guidance": null,
+ "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": [
+ {
+ "id": "inside.arrow",
+ "text": "Pages inside %s",
+ "was": null
+ },
+ {
+ "id": "inside.all",
+ "text": "See all pages inside (%d)",
+ "was": "All %d pages inside"
+ },
+ {
+ "id": "inside.page.title",
+ "text": "Pages inside %s",
+ "was": null
+ },
+ {
+ "id": "inside.page.sub",
+ "text": "Each page starts with a line saying it is inside this page.",
+ "was": "Each one starts with a line that says it is inside this page."
+ },
+ {
+ "id": "pins.full",
+ "text": "You can pin up to 20 pages. Choose Unpin from sidebar first.",
+ "was": "You can pin up to 20 pages. Unpin one first."
+ },
+ {
+ "id": "import.pins.some",
+ "text": "Pinned %d of your %d top-level team pages to your sidebar. Your sidebar holds 20 pins.",
+ "was": "Pinned %d of your %d top-level pages. Your sidebar holds 20 pins."
+ },
+ {
+ "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
new file mode 100644
index 0000000..fa1547f
--- /dev/null
+++ b/copy-review/inside/strings.json
@@ -0,0 +1,82 @@
+[
+ {
+ "id": "inside.arrow",
+ "section": "Sidebar",
+ "label": "inside.arrow",
+ "text": "Pages inside %s",
+ "context": "Accessible name of the disclosure arrow on a pinned sidebar row, and of the list it opens. %s is the page's title. The pages listed are those whose first line is 'In: [[that page]]', which the Notion import writes for each child page.",
+ "notes": ""
+ },
+ {
+ "id": "inside.all",
+ "section": "Sidebar",
+ "label": "inside.all",
+ "text": "All %d pages inside",
+ "context": "A link at the end of an opened list that shows the first 50: it opens a page listing all of them. %d is a number in the reader's locale.",
+ "notes": ""
+ },
+ {
+ "id": "inside.page.title",
+ "section": "All pages inside",
+ "label": "inside.page.title",
+ "text": "Pages inside %s",
+ "context": "Heading of that page.",
+ "notes": ""
+ },
+ {
+ "id": "inside.page.sub",
+ "section": "All pages inside",
+ "label": "inside.page.sub",
+ "text": "Each one starts with a line that says it is inside this page.",
+ "context": "Subheading: explains how a page comes to be listed (its first line is 'In: [[this page]]').",
+ "notes": ""
+ },
+ {
+ "id": "pins.full",
+ "section": "Refusals",
+ "label": "pins.full",
+ "text": "You can pin up to 20 pages. Unpin one first.",
+ "context": "Shown when pinning a page past the limit (raised from 12).",
+ "notes": ""
+ },
+ {
+ "id": "import.pins.some",
+ "section": "Import report",
+ "label": "import.pins.some",
+ "text": "Pinned %d of your %d top-level pages. Your sidebar holds 20 pins.",
+ "context": "In the Notion import's report, after a run that pinned the workspace's top-level pages to the runner's sidebar but ran out of room. A list of the ones not pinned follows.",
+ "notes": ""
+ },
+ {
+ "id": "import.pins.all",
+ "section": "Import report",
+ "label": "import.pins.all",
+ "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 d6d6918..f279c46 100644
--- a/docs/superpowers/specs/2026-11-22-mapa-columns-icons.md
+++ b/docs/superpowers/specs/2026-11-22-mapa-columns-icons.md
@@ -782,3 +782,14 @@ Fable found every round-1 finding answered in substance, and five mediums and si
- **C11, Fable's round 2 on the fixes (`a768523`): CHANGES REQUIRED, two mediums in `adoptColumn`, answered.** The caret now keeps its place after a column's adopt (typing went into the next column), and the neutraliser skips code. A longer fence for code written from its node did nothing (the parser's fence is its first three characters) and is gone. Lows not taken: no test lists every handler that reads an index (the four routes are wrapped by name and COL13 posts to each); a paste over a cross-column selection deletes before the paste is known to succeed; drag and drop across columns is not confined.
- **C12, Fable's round 3 (`eb7dc12`): one medium, answered.** The caret after a column's adopt could land at the start of the block after the edited one, since the whole column was replaced. `adoptColumn` now adopts the column by child, as `adoptInto` does at the top level (`adoptInto` takes a container): blocks the parse still has stay as they are, origins included, only the changed run is replaced, and the caret is measured against that run. The test now places the caret and checks the typed text lands in its block, as the top level does.
+### 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 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, 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.
+- **P8, Fable's round 2 (`8585b08`): APPROVE, no High or Medium.** Its lows answered: arrow toggles go one after another, so two rows opened quickly both stay open (L1); a reply takes focus back only when it was not moved elsewhere (L2); a reply that is not a page back where the person is reloads instead (L3); the report's four sentences are gated (L4); an open row past the 200-row cap is drawn open with only its link to all its pages, so its arrow still closes it (L5); two loose assertions tightened (L6).
+
diff --git a/internal/mapa/graph.go b/internal/mapa/graph.go
index eccab7d..9e5c1a0 100644
--- a/internal/mapa/graph.go
+++ b/internal/mapa/graph.go
@@ -53,6 +53,12 @@ func (index *Index) add(page *entry) {
for _, link := range page.links {
index.linkersOf(Fold(link.Target)).add(page, link.Target)
}
+ if page.in != "" {
+ if index.within[page.in] == nil {
+ index.within[page.in] = map[int64]bool{}
+ }
+ index.within[page.in][page.id] = true
+ }
index.termsOf(page).add(page.id, page.counts, page.length)
index.titlesDirty = index.titlesDirty || page.team()
index.pending.dirty = true
@@ -94,6 +100,12 @@ func (index *Index) remove(pageID int64) {
delete(index.linkers, fold)
}
}
+ 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()
index.pending.dirty = true
diff --git a/internal/mapa/import_ledger.go b/internal/mapa/import_ledger.go
index b75eb3b..ebcdab4 100644
--- a/internal/mapa/import_ledger.go
+++ b/internal/mapa/import_ledger.go
@@ -57,6 +57,10 @@ type coordinate struct {
// row it sits in, and listed (spec §8.1).
UnderRow bool `json:"underRow,omitempty"`
Renamed bool `json:"renamed,omitempty"`
+ // Pin is set once the page, a root of the import, was offered for
+ // the runner's sidebar (columns and icons spec §6.3): Run is the run
+ // that offered it, and Pinned whether a slot was free.
+ Pin *pinMark `json:"pin,omitempty"`
// Render is the last render's counts, ids and losses (§8.5).
Render *notionmd.Result `json:"render,omitempty"`
// Kept says why a page was kept: edited, or only links updated.
diff --git a/internal/mapa/import_pins.go b/internal/mapa/import_pins.go
new file mode 100644
index 0000000..f635185
--- /dev/null
+++ b/internal/mapa/import_pins.go
@@ -0,0 +1,107 @@
+package mapa
+
+import (
+ "context"
+)
+
+// The import's pins (columns and icons spec §6.3): the roots of the
+// import, pages with no imported parent and so no "In:" line, are pinned
+// to the runner's own sidebar, once each, so Pinned resembles the top of
+// their Notion sidebar. Pins are per person and sealed (level-up Q1):
+// nobody else's sidebar changes.
+
+// pinMark is a root's sealed record of its offer.
+type pinMark struct {
+ Run int64 `json:"run"`
+ Pinned bool `json:"pinned"`
+}
+
+// autoPin pins the roots never offered before, in survey order, after
+// the runner's own pins, up to the slots free, in one write that marks
+// each offered root and logs one pins event by the runner. A root with
+// no slot is marked too, and listed. Nothing to offer writes nothing.
+func (job *importJob) autoPin(ctx context.Context, set *importSet) error {
+ roots := job.unofferedRoots(set)
+ if len(roots) == 0 {
+ return nil
+ }
+ return job.store.write(ctx, func(tx *Tx) error {
+ if err := holdLease(tx.db, job.lease); err != nil {
+ return err
+ }
+ memberID, err := tx.member(job.who)
+ if err != nil {
+ return err
+ }
+ var member Member
+ if err := tx.db.First(&member, memberID).Error; err != nil {
+ return err
+ }
+ ids, err := tx.store.openPins(member.SealedPins)
+ if err != nil {
+ return err
+ }
+ for _, entry := range roots {
+ // 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. 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 ||
+ entry.staged.Parent != "" || !entry.live {
+ continue
+ }
+ roots = append(roots, entry)
+ }
+ return roots
+}
+
+func hasPin(ids []int64, pageID int64) bool {
+ for _, id := range ids {
+ if id == pageID {
+ return true
+ }
+ }
+ return false
+}
+
+// markPlace marks an entry's stored coordinate with its pin mark: read
+// again inside the write, since the page's own transaction wrote it
+// last, and the run's copy of it is not that one.
+func (tx *Tx) markPlace(entry *importEntry) error {
+ var row NotionPage
+ if err := tx.db.First(&row, entry.row.ID).Error; err != nil {
+ return err
+ }
+ place, err := tx.store.openCoordinate(row)
+ if err != nil {
+ return err
+ }
+ place.Pin = entry.place.Pin
+ sealed, err := tx.store.sealCoordinate(place)
+ if err != nil {
+ return err
+ }
+ return tx.db.Model(&NotionPage{}).Where("id = ?", row.ID).
+ Update("sealed_coordinate", sealed).Error
+}
diff --git a/internal/mapa/import_pins_test.go b/internal/mapa/import_pins_test.go
new file mode 100644
index 0000000..bd5f7c6
--- /dev/null
+++ b/internal/mapa/import_pins_test.go
@@ -0,0 +1,288 @@
+package mapa
+
+import (
+ "fmt"
+ "strings"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/mapa/internal/mapa/notionmd"
+ "amadan.net/oficina/notion.git/notiontest"
+)
+
+// I23 (columns and icons spec §6.3, §9): the import pins its roots to
+// the runner's sidebar, after their own pins, once; a re-run pins
+// nothing; a root the person unpinned stays unpinned; nobody else's
+// pins change.
+
+func pinTitles(t *testing.T, world *importWorld, who string) []string {
+ t.Helper()
+ viewer, err := world.store.Viewer(ctx(), who, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ ids, err := world.store.Pins(ctx(), viewer)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var titles []string
+ for _, id := range ids {
+ var page Page
+ if err := world.store.database.First(&page, id).Error; err != nil {
+ t.Fatal(err)
+ }
+ record, err := world.store.OpenPage(page)
+ if err != nil {
+ t.Fatal(err)
+ }
+ titles = append(titles, record.Title)
+ }
+ return titles
+}
+
+func TestI23TheImportPinsItsRootsOnce(t *testing.T) {
+ doc := notiontest.NewDocumented()
+ world := newImportWorld(t, doc.Workspace)
+ mine := mustCreate(t, world.store, "Mine", "Text.")
+ viewer, _ := world.store.Viewer(ctx(), ana, nil)
+ if err := world.store.SetPin(ctx(), viewer, mine.ID, true); err != nil {
+ t.Fatal(err)
+ }
+ world.connect(ana)
+ run := world.importAs(ana)
+ if run.State != runDone {
+ t.Fatalf("first run: %+v", run)
+ }
+ pins := pinTitles(t, world, ana)
+ report, err := world.store.report(ctx(), run)
+ if err != nil || report.Pinned != len(pins)-1 ||
+ report.Offered != report.Pinned {
+ t.Fatalf("the report's pins: %+v %v", report, err)
+ }
+ if len(pins) < 2 || pins[0] != "Mine" {
+ t.Fatalf("Ana's pins: %v", pins)
+ }
+ for _, title := range pins[1:] {
+ _, record, ok := world.pageTitled(title)
+ if !ok || strings.HasPrefix(record.Body, "In: ") {
+ t.Errorf("pinned %q, which is not a root", title)
+ }
+ }
+ if got := pinTitles(t, world, bo); len(got) != 0 {
+ t.Fatalf("Bo's pins changed: %v", got)
+ }
+ root, _, _ := world.pageTitled(pins[1])
+ viewer, _ = world.store.Viewer(ctx(), ana, nil)
+ if err := world.store.SetPin(ctx(), viewer, root.ID, false); err != nil {
+ t.Fatal(err)
+ }
+ events := world.count("events", "verb = ?", VerbPinsSet)
+ world.server.Reset()
+ if run := world.importAs(ana); run.State != runDone {
+ t.Fatalf("second run: %+v", run)
+ }
+ if world.count("events", "verb = ?", VerbPinsSet) != events {
+ t.Fatal("a re-run wrote the pins again")
+ }
+ for _, title := range pinTitles(t, world, ana) {
+ if title == pins[1] {
+ t.Fatal("a root Ana unpinned was pinned again")
+ }
+ }
+}
+
+// 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 })
+ run := 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")
+ }
+ }
+ report, _ := world.store.report(ctx(), run)
+ for _, page := range report.Unpinned {
+ if page.Title == "Grandchild" {
+ t.Fatal("a failed parent's child was offered")
+ }
+ }
+ row, _, _ := world.store.mapRowOf(world.store.database, doc.Grandchild)
+ if place, err := world.store.openCoordinate(row); err != nil ||
+ place.Pin != nil {
+ t.Fatalf("a failed parent's child was marked: %v", err)
+ }
+}
+
+// I23, the report's sentence (Fable on the build, L4), in its four
+// forms: one root pinned, every root pinned, some of them, and none for
+// a full sidebar.
+func TestI23TheReportSaysWhatWasPinned(t *testing.T) {
+ sentence := func(t *testing.T, ws *notiontest.Workspace, full int,
+ want string) {
+ t.Helper()
+ world := newImportWorld(t, ws)
+ viewer, _ := world.store.Viewer(ctx(), ana, nil)
+ for at := range full {
+ 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)
+ }
+ }
+ world.connect(ana)
+ run := world.importAs(ana)
+ report, _ := world.store.report(ctx(), run)
+ want = strings.NewReplacer("{n}", fmt.Sprint(report.Offered),
+ "{p}", fmt.Sprint(report.Pinned)).Replace(want)
+ if text := world.importPageText(); !strings.Contains(text, want) {
+ t.Errorf("the report does not say %q", want)
+ }
+ }
+ sentence(t, newSmall().Workspace, 0,
+ "Pinned your top-level team page to your sidebar.")
+ sentence(t, newSmall().Workspace, maxPins, "Your sidebar already "+
+ "holds 20 pins, so your top-level team page wasn’t pinned.")
+ documented := func() *notiontest.Workspace {
+ return notiontest.NewDocumented().Workspace
+ }
+ sentence(t, documented(), 0,
+ "Pinned your {n} top-level team pages to your sidebar.")
+ sentence(t, documented(), maxPins-1, "Pinned 1 of your {n} top-level "+
+ "team pages to your sidebar. Your sidebar holds 20 pins.")
+ sentence(t, documented(), maxPins, "Your sidebar already holds 20 "+
+ "pins, so your {n} top-level team pages weren’t pinned.")
+}
diff --git a/internal/mapa/import_report.go b/internal/mapa/import_report.go
index 24ed578..b53cc56 100644
--- a/internal/mapa/import_report.go
+++ b/internal/mapa/import_report.go
@@ -28,6 +28,13 @@ type reportView struct {
Fallbacks, Neutralised, Unshared, Notion int
Fitted, Kept, FailedPages, NotFoundPages []reportPage
Placeholders, UnderRow []reportPage
+ // Pinned and Unpinned are the roots this run offered to the
+ // runner's sidebar, read from their sealed pin marks (columns and
+ // 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 {
@@ -52,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{}}
@@ -106,6 +113,15 @@ func (tally *reportTally) add(entry reportRow) {
if row.SurveyedRun == tally.run {
tally.outcome(entry)
}
+ if mark := place.Pin; mark != nil && mark.Run == tally.run {
+ tally.view.Offered++
+ if mark.Pinned {
+ tally.view.Pinned++
+ } else {
+ tally.view.Unpinned = append(tally.view.Unpinned,
+ tally.page(place))
+ }
+ }
}
// outcome counts what this run did with a page.
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/import_write.go b/internal/mapa/import_write.go
index 5317157..e9d6aff 100644
--- a/internal/mapa/import_write.go
+++ b/internal/mapa/import_write.go
@@ -38,6 +38,12 @@ func (job *importJob) write(ctx context.Context) error {
if err := crashPoint("write:fixed"); err != nil {
return err
}
+ if err := job.autoPin(ctx, set); err != nil {
+ return err
+ }
+ if err := crashPoint("write:pinned"); err != nil {
+ return err
+ }
return job.done(ctx)
}
diff --git a/internal/mapa/index.go b/internal/mapa/index.go
index 9142964..a0fed23 100644
--- a/internal/mapa/index.go
+++ b/internal/mapa/index.go
@@ -56,6 +56,9 @@ type Index struct {
titleRows []titleRow
titlesDirty bool
pending pendingSet
+ // within maps a folded link text to the team pages whose "In:" line
+ // names it (inside.go, columns and icons spec §5.1).
+ within map[string]map[int64]bool
}
// entry is one live page, opened and parsed.
@@ -68,6 +71,8 @@ type entry struct {
aliases []AliasView
blocks []markup.Block
links []markup.Link
+ // in is the folded target of the page's "In:" line, or "".
+ in string
// unlinked is each block's words outside links and code (§6.4).
unlinked [][]word
// counts and length are what the page is indexed with for search.
@@ -113,6 +118,7 @@ func (index *Index) reset() {
index.ownTerms = map[int64]*partition{}
index.titleRows, index.titlesDirty = nil, true
index.pending = pendingSet{dirty: true}
+ index.within = map[string]map[int64]bool{}
}
// Sync readies the index for a read. A reader never catches the index
@@ -307,7 +313,8 @@ func (index *Index) open(page Page, aliases []AliasView) (*entry, error) {
opened := &entry{id: page.ID, nonce: page.Nonce, owner: page.OwnerID,
revision: page.Revision, kind: page.Kind, rung: page.Rung,
created: page.CreatedAt, updated: page.UpdatedAt, record: record,
- aliases: aliases, blocks: blocks, links: markup.LinksIn(blocks)}
+ aliases: aliases, blocks: blocks, links: markup.LinksIn(blocks),
+ in: inTarget(page.Kind, page.Rung, blocks)}
opened.counts, opened.length = termCounts(searchText(opened))
opened.unlinked = make([][]word, len(blocks))
for number, block := range blocks {
diff --git a/internal/mapa/inside.go b/internal/mapa/inside.go
new file mode 100644
index 0000000..dd6e852
--- /dev/null
+++ b/internal/mapa/inside.go
@@ -0,0 +1,109 @@
+package mapa
+
+import (
+ "context"
+ "sort"
+
+ "amadan.net/oficina/mapa/internal/mapa/markup"
+)
+
+// Pages inside (columns and icons spec §5): a team page is inside team
+// page P when its first block is exactly the line "In: [[P]]" (or
+// "In: [[P|shown]]", with an optional ^id), the line the Notion import
+// writes. The relation is derived from bodies in memory, like every
+// link; nothing is stored. Only team pages are inside anything, and
+// only team pages hold pages, so no private first line reaches the
+// sidebar (level-up build note 80).
+
+// inTarget is the folded link text of a page's "In:" line, or "".
+func inTarget(kind, rung string, blocks []markup.Block) string {
+ if kind != KindPage || rung != RungTeam || len(blocks) == 0 {
+ return ""
+ }
+ first := blocks[0]
+ if first.Kind != markup.Paragraph {
+ return ""
+ }
+ spans := markup.Spans(markup.Strip(first))
+ if len(spans) != 2 || spans[0].Kind != markup.Text ||
+ spans[0].Text != "In: " || spans[1].Kind != markup.WikiLink ||
+ spans[1].Anchor != "" || markup.IsDateShaped(spans[1].Target) {
+ return ""
+ }
+ return Fold(spans[1].Target)
+}
+
+// insideOf is the ids of the team pages inside page, unordered. The
+// caller holds the read lock.
+func (index *Index) insideOf(page *entry) map[int64]bool {
+ out := map[int64]bool{}
+ if page == nil || !page.team() {
+ return out
+ }
+ for _, fold := range page.titleFolds() {
+ for child := range index.within[fold] {
+ if child != page.id && index.team[child] {
+ out[child] = true
+ }
+ }
+ }
+ return out
+}
+
+// insideOrder is page's children in its own order (§5.2): those its
+// body links to, by their first link, then the rest by title.
+func (index *Index) insideOrder(page *entry,
+ children map[int64]bool) []*entry {
+ place := map[int64]int{}
+ for at, link := range page.links {
+ target, ok := index.titles[Fold(link.Target)]
+ if _, seen := place[target]; ok && children[target] && !seen {
+ place[target] = at
+ }
+ }
+ out := make([]*entry, 0, len(children))
+ for child := range children {
+ out = append(out, index.pages[child])
+ }
+ sort.SliceStable(out, func(left, right int) bool {
+ one, okOne := place[out[left].id]
+ other, okOther := place[out[right].id]
+ switch {
+ case okOne && okOther:
+ return one < other
+ case okOne != okOther:
+ return okOne
+ }
+ return Fold(out[left].record.Title) < Fold(out[right].record.Title)
+ })
+ return out
+}
+
+// Inside is the pages inside page id as scope sees them, in order: the
+// scoped accessor's answer (level-up §8). A page the scope may not open,
+// or a private one, has none.
+func (index *Index) Inside(ctx context.Context, scope Scope,
+ pageID int64) ([]*entry, error) {
+ if err := index.Sync(ctx); err != nil {
+ return nil, err
+ }
+ index.mutex.RLock()
+ defer index.mutex.RUnlock()
+ 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() {
+ return nil
+ }
+ return index.insideOrder(page, index.insideOf(page))
+}
diff --git a/internal/mapa/inside_test.go b/internal/mapa/inside_test.go
new file mode 100644
index 0000000..9841273
--- /dev/null
+++ b/internal/mapa/inside_test.go
@@ -0,0 +1,61 @@
+package mapa
+
+import (
+ "strings"
+ "testing"
+)
+
+// IN1 and IN2 (columns and icons spec §5.1, §5.2, §9): which pages are
+// inside which, and in what order.
+
+func insideTitles(t *testing.T, index *Index, scope Scope,
+ pageID int64) string {
+ t.Helper()
+ pages, err := index.Inside(ctx(), scope, pageID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var titles []string
+ for _, page := range pages {
+ titles = append(titles, page.record.Title)
+ }
+ return strings.Join(titles, ", ")
+}
+
+func TestIN1OnlyAnExactFirstInLineIsInside(t *testing.T) {
+ store := testStore(t)
+ index := NewIndex(store)
+ parent := mustCreate(t, store, "Projects", "See [[Beta]] then [[Alpha]].")
+ for title, body := range map[string]string{
+ "Alpha": "In: [[Projects]]\n\nText.",
+ "Beta": "In: [[Projects|the projects]] ^m1",
+ "Gamma": "In: [[Projects]]",
+ "Second": "Intro.\n\nIn: [[Projects]]",
+ "Dated": "In: [[2026-11-12]]",
+ "Self": "In: [[Self]]",
+ "Pending": "In: [[Nowhere]]",
+ "Sentence": "In: [[Projects]] and more.",
+ "Old title": "In: [[Old projects]]",
+ } {
+ mustCreate(t, store, title, body)
+ }
+ _, err := store.Retitle(ctx(), ana, parent.ID, "Old projects")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := store.Retitle(ctx(), ana, parent.ID, "Projects"); err != nil {
+ t.Fatal(err)
+ }
+ scratch, err := store.CreateScratch(ctx(), ana, "In: [[Projects]]")
+ if err != nil {
+ t.Fatal(err)
+ }
+ viewer, _ := store.Viewer(ctx(), ana, nil)
+ got := insideTitles(t, index, ScopeOf(viewer), parent.ID)
+ if got != "Beta, Alpha, Gamma, Old title" {
+ t.Fatalf("inside Projects: %q", got)
+ }
+ if got := insideTitles(t, index, ScopeOf(viewer), scratch.ID); got != "" {
+ t.Fatalf("a private page holds %q", got)
+ }
+}
diff --git a/internal/mapa/pins.go b/internal/mapa/pins.go
index c2d5fde..29bbb4e 100644
--- a/internal/mapa/pins.go
+++ b/internal/mapa/pins.go
@@ -18,12 +18,16 @@ import (
// theirs alone, sealed in their member row, and the event a change logs
// names the member, never the page.
-// maxPins is how many pages a sidebar holds pinned.
-const maxPins = 12
+// maxPins is how many pages a sidebar holds pinned: 20 since the
+// columns and icons spec's Q4, so a Notion workspace's top level fits.
+// A list sealed when it held 12 (oldPinBytes) is still read.
+const maxPins = 20
+
+const oldPinBytes = 12 * 8
// ErrTooManyPins is a pin past maxPins.
-var ErrTooManyPins = errors.New("You can pin up to 12 pages. " +
- "Unpin one first.")
+var ErrTooManyPins = errors.New("You can pin up to 20 pages. " +
+ "Choose Unpin from sidebar first.")
// Pins is the viewer's pinned page ids, newest first. A page since
// deleted or out of scope is dropped where the list is read.
@@ -49,11 +53,11 @@ func (store *Store) openPins(sealed []byte) ([]int64, error) {
if err != nil {
return nil, err
}
- if len(plain) != pinBytes {
+ if len(plain) != pinBytes && len(plain) != oldPinBytes {
return nil, errors.New("mapa: pins of the wrong length")
}
var ids []int64
- for at := 0; at < pinBytes; at += 8 {
+ for at := 0; at < len(plain); at += 8 {
if id := int64(binary.BigEndian.Uint64(plain[at:])); id != 0 {
ids = append(ids, id)
}
diff --git a/internal/mapa/recent.go b/internal/mapa/recent.go
index a821cdd..0774dbe 100644
--- a/internal/mapa/recent.go
+++ b/internal/mapa/recent.go
@@ -140,11 +140,7 @@ func (index *Index) sideLinks(ctx context.Context, scope Scope,
if found == nil || (teamOnly && !found.team()) {
continue
}
- out = append(out, sideLink{Label: found.label(scope.Locale),
- Href: found.href(), Icon: sideIcon(found.kind), Look: found.look(),
- Here: found.href() == current, Private: !found.team(),
- page: PageView{Public: publicID(found.nonce),
- Kind: found.kind, Rung: found.rung}})
+ out = append(out, sideLinkOf(found, scope, current))
if limit > 0 && len(out) == limit {
break
}
diff --git a/internal/mapa/render.go b/internal/mapa/render.go
index 56e4b13..e5a55de 100644
--- a/internal/mapa/render.go
+++ b/internal/mapa/render.go
@@ -103,7 +103,7 @@ var shellOf = map[string]string{
"pages": "shell", "page": "shell",
"page_new": "shell", "page_edit": "shell", "rename": "shell",
"links": "shell", "alias_free": "shell", "delete": "shell",
- "image_remove": "shell", "look": "shell",
+ "image_remove": "shell", "look": "shell", "inside": "shell",
"deleted": "shell", "restore": "shell", "day": "shell",
"scratch": "shell", "scratch_new": "shell", "share": "shell",
"settings": "shell", "search": "shell", "conflict": "shell",
diff --git a/internal/mapa/side.go b/internal/mapa/side.go
index de8a572..c70814a 100644
--- a/internal/mapa/side.go
+++ b/internal/mapa/side.go
@@ -46,6 +46,18 @@ type sideLink struct {
// Menu is the row's ⋯ (build note 88), from what page allows.
Menu []menuEntry
page PageView
+ id int64
+ // Gutter is a Pinned row, which keeps a cell for an arrow; Arrow,
+ // that its page holds pages the viewer may open; Open, that they are
+ // shown, as Inside; Depth, its indent; More and All, how many more
+ // there are than are listed, and all of them (side_inside.go).
+ Gutter, Arrow, Open bool
+ Inside []sideLink
+ Depth, More, All int
+ // Return is where the arrow's form comes back to; Public, the
+ // page's public id; ListID, the open list's own id, unique however
+ // often a page is shown.
+ Return, Public, ListID string
}
func (app *app) side(request *http.Request, page *view) sideView {
@@ -54,6 +66,15 @@ func (app *app) side(request *http.Request, page *view) sideView {
side := sideView{State: sidebarState(request),
Places: slices.Clone(page.Nav), Return: page.Return}
side.Pinned, side.Recent = app.sideLists(request, page)
+ if len(side.Pinned) > 0 {
+ current := ""
+ if page.Chrome != nil && page.Chrome.Page != nil {
+ current = page.Chrome.Page.Href
+ }
+ app.index.insideRows(request.Context(), ScopeOf(page.Viewer),
+ side.Pinned, openRows(request), current)
+ setReturn(side.Pinned, side.Return)
+ }
side.light()
side.menus()
return side
@@ -64,14 +85,10 @@ func (app *app) side(request *http.Request, page *view) sideView {
func (side *sideView) menus() {
back, pinned := withoutNotice(side.Return), map[string]bool{}
for index := range side.Pinned {
- row := &side.Pinned[index]
- pinned[row.Href] = true
- row.Menu = rowMenu(row.page, true, back)
- }
- for index := range side.Recent {
- row := &side.Recent[index]
- row.Menu = rowMenu(row.page, pinned[row.Href], back)
+ pinned[side.Pinned[index].Href] = true
}
+ menuRows(side.Pinned, pinned, back)
+ menuRows(side.Recent, pinned, back)
}
// withoutNotice is a return path less its ?done= notice, which said
@@ -97,13 +114,7 @@ func withoutNotice(path string) string {
func (side *sideView) light() {
var here *sideLink
for _, list := range [][]sideLink{side.Pinned, side.Recent} {
- for index := range list {
- list[index].Here = list[index].Here && here == nil
- list[index].Current = list[index].Here
- if list[index].Here {
- here = &list[index]
- }
- }
+ lightRows(list, &here)
}
if here == nil {
return
@@ -140,6 +151,8 @@ func linksState(request *http.Request) string {
func (app *app) viewRoutes(router chi.Router) {
router.Post("/view/sidebar", app.viewSidebar)
router.Post("/view/links", app.viewLinks)
+ router.Post("/view/open", app.viewOpen)
+ router.Get("/p/{id}/inside", app.insidePage)
router.Get("/help/markdown", app.helpMarkdown)
}
diff --git a/internal/mapa/side_inside.go b/internal/mapa/side_inside.go
new file mode 100644
index 0000000..e0c440e
--- /dev/null
+++ b/internal/mapa/side_inside.go
@@ -0,0 +1,211 @@
+package mapa
+
+import (
+ "context"
+ "log/slog"
+ "net/http"
+ "strings"
+)
+
+// The sidebar's arrows (columns and icons spec §5.3): a Pinned row whose
+// page holds pages the viewer may open has a disclosure arrow, and each
+// row it opens has its own, so the pages inside show one level at a
+// time. Which rows are open is the cookie mapa-open, a view preference
+// like the fold: the server draws open rows at first paint, POST
+// /view/open sets it with no script, and it writes no row.
+
+const (
+ openCookie = "mapa-open"
+ // maxOpen is how many open rows the cookie keeps, newest first.
+ maxOpen = 64
+ // insideShown is how many pages one open row lists before its link
+ // to all of them; insideTotal caps the open rows the sidebar draws.
+ insideShown = 50
+ insideTotal = 200
+ // insideDepth is how many levels are indented; deeper ones keep the
+ // last indent.
+ insideDepth = 4
+)
+
+// openRows is the cookie's set of open page public ids, in its order.
+func openRows(request *http.Request) []string {
+ cookie, err := request.Cookie(openCookie)
+ if err != nil {
+ return nil
+ }
+ var out []string
+ for _, id := range strings.Fields(cookie.Value) {
+ if len(id) <= 20 && len(out) < maxOpen {
+ out = append(out, id)
+ }
+ }
+ return out
+}
+
+// insideRows fills each Pinned row's arrow and, for an open one, the
+// 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 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()
+ defer index.mutex.RUnlock()
+ expand := opener{index: index, scope: scope, current: current,
+ open: map[string]bool{}}
+ for _, id := range open {
+ expand.open[id] = true
+ }
+ for at := range rows {
+ expand.row(&rows[at], 0, nil)
+ }
+}
+
+// opener draws the rows inside rows, counting what it has drawn.
+type opener struct {
+ index *Index
+ scope Scope
+ current string
+ open map[string]bool
+ drawn int
+}
+
+// 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)
+ for _, above := range path {
+ if above.id == row.id {
+ return
+ }
+ }
+ if !expand.open[row.page.Public] {
+ row.Arrow = expand.index.holdsAny(expand.scope, row.id)
+ return
+ }
+ // An open row past the cap is drawn open with its link to all its
+ // pages and no rows, so its arrow still closes it (Fable L5).
+ children := expand.index.insideLocked(expand.scope, row.id)
+ row.Arrow = len(children) > 0
+ row.Open = row.Arrow
+ if !row.Open {
+ return
+ }
+ 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
+ }
+ expand.drawn++
+ link := sideLinkOf(child, expand.scope, expand.current)
+ 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.
+func sideLinkOf(found *entry, scope Scope, current string) sideLink {
+ return sideLink{Label: found.label(scope.Locale), Href: found.href(),
+ Icon: sideIcon(found.kind), Look: found.look(), id: found.id,
+ Public: publicID(found.nonce),
+ Here: found.href() == current, Private: !found.team(),
+ page: PageView{Public: publicID(found.nonce), Kind: found.kind,
+ Rung: found.rung}}
+}
+
+// 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 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)
+ kept := []string{}
+ if request.PostFormValue("open") == "1" && id != "" && len(id) <= 20 {
+ kept = append(kept, id)
+ }
+ for _, each := range open {
+ if each != id && len(kept) < maxOpen {
+ kept = append(kept, each)
+ }
+ }
+ setViewCookie(writer, openCookie, strings.Join(kept, " "))
+ seeOther(writer, request, localReturn(request.PostFormValue("return")))
+}
+
+// setReturn gives every row, open ones' rows included, the return path.
+func setReturn(rows []sideLink, back string) {
+ for at := range rows {
+ rows[at].Return = back
+ setReturn(rows[at].Inside, back)
+ }
+}
+
+// lightRows lights the first row that is Here, in document order: each
+// row, then the rows open inside it (build note 80's one highlight).
+func lightRows(rows []sideLink, here **sideLink) {
+ for at := range rows {
+ rows[at].Here = rows[at].Here && *here == nil
+ rows[at].Current = rows[at].Here
+ if rows[at].Here {
+ *here = &rows[at]
+ }
+ lightRows(rows[at].Inside, here)
+ }
+}
+
+// menuRows gives each row, open ones' rows included, its ⋯.
+func menuRows(rows []sideLink, pinned map[string]bool, back string) {
+ for at := range rows {
+ rows[at].Menu = rowMenu(rows[at].page, pinned[rows[at].Href], back)
+ menuRows(rows[at].Inside, pinned, back)
+ }
+}
+
+// insidePage is GET /p/{id}/inside: every page inside a team page, in
+// its order, for a list the sidebar cuts at insideShown. Scoped as the
+// arrow is; anything else is the app's 404.
+func (app *app) insidePage(writer http.ResponseWriter,
+ request *http.Request) {
+ page, ok := app.teamOnly(writer, request)
+ if !ok {
+ return
+ }
+ viewer, err := app.viewer(request)
+ if err != nil {
+ app.fail(writer, request, err)
+ return
+ }
+ pages, err := app.index.Inside(request.Context(), ScopeOf(viewer),
+ page.ID)
+ if err != nil {
+ app.fail(writer, request, err)
+ return
+ }
+ rows := make([]sideLink, 0, len(pages))
+ for _, found := range pages {
+ rows = append(rows, sideLinkOf(found, ScopeOf(viewer), ""))
+ }
+ app.show(writer, request, http.StatusOK, "inside", view{
+ Title: "Pages inside " + page.Label, Nav: nav("/pages"),
+ Viewer: viewer, Data: map[string]any{"Page": page, "Rows": rows}})
+}
diff --git a/internal/mapa/static/frame.css b/internal/mapa/static/frame.css
index 39165be..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; }
@@ -726,3 +728,42 @@ h1[mapa-title] > [mapa-icon] { margin-inline-end: var(--rst-sp-3); vertical-alig
[mapa-picker] [role="option"][aria-selected="true"] { background: var(--rst-surface-2); outline: 2px solid var(--rst-accent); outline-offset: -2px; }
[mapa-picker-foot] { display: flex; flex-wrap: wrap; gap: var(--rst-sp-2); }
[mapa-picker][aria-busy="true"] { opacity: 0.7; pointer-events: none; }
+
+/* ── Pages inside (columns and icons spec §5.3): Pinned rows keep a 16px
+ cell for the arrow before the icon, so every icon in Pinned lines up;
+ opened rows indent one step per level, up to four. ── */
+[mapa-side-row][mapa-side-gutter] {
+ display: grid;
+ grid-template-columns: 16px minmax(0, 1fr) auto;
+ align-items: center;
+ padding-inline-start: calc(var(--rst-sp-4) * var(--mapa-depth, 0));
+}
+[mapa-side-row][data-depth="1"] { --mapa-depth: 1; }
+[mapa-side-row][data-depth="2"] { --mapa-depth: 2; }
+[mapa-side-row][data-depth="3"] { --mapa-depth: 3; }
+[mapa-side-row][data-depth="4"] { --mapa-depth: 4; }
+[mapa-side-arrow-form] { display: contents; }
+[mapa-side-arrow] {
+ display: grid;
+ place-items: center;
+ inline-size: 16px;
+ block-size: 24px;
+ padding: 0;
+ border: 0;
+ background: none;
+ color: var(--rst-text-muted);
+ cursor: pointer;
+}
+[mapa-side-arrow] svg { inline-size: 12px; block-size: 12px; }
+[mapa-side-arrow][aria-expanded="true"] svg { transform: rotate(90deg); }
+[mapa-side-arrow]:hover { color: var(--rst-text); }
+@media (prefers-reduced-motion: no-preference) {
+ [mapa-side-arrow] svg { transition: transform 120ms ease; }
+}
+ul[mapa-side-inside] { list-style: none; margin: 0; padding: 0; }
+[mapa-side-all] {
+ display: block;
+ padding: var(--rst-sp-1) var(--rst-sp-2) var(--rst-sp-1) var(--rst-sp-6);
+ color: var(--rst-text-muted);
+ font-size: 13px;
+}
diff --git a/internal/mapa/static/mapa.js b/internal/mapa/static/mapa.js
index 123c0f3..e00cf3d 100644
--- a/internal/mapa/static/mapa.js
+++ b/internal/mapa/static/mapa.js
@@ -907,6 +907,81 @@
});
}
+ // ---- Pages inside (columns and icons spec §5.3) -------------------------
+ // An arrow is a form that sets the mapa-open cookie and comes back. With
+ // script it is sent in the background and the sidebar the server draws
+ // for the page is put in place, so the rows open at once and the page
+ // and what was typed stay as they are. No busy rule: like the fold, it
+ // switches at once.
+ function sideArrows() {
+ var sent = 0;
+ // Toggles go one after another: each POST carries the cookie the
+ // last one set, so two rows opened quickly both stay open.
+ var queue = Promise.resolve();
+ 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;
+ var body = new URLSearchParams(new FormData(form));
+ queue = queue.then(function () {
+ return fetch(form.action, { method: "POST", body: body, credentials: "same-origin" });
+ }).then(function (response) {
+ // Only a page back where we are draws this sidebar.
+ if (!response.ok || new URL(response.url).pathname !== window.location.pathname) {
+ throw new Error("elsewhere");
+ }
+ return response.text();
+ }).then(function (html) {
+ 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);
+ });
+ // Focus comes back to the arrow only if it was not taken
+ // elsewhere while the reply was on its way.
+ var active = document.activeElement;
+ if (active && active !== document.body && !nav.contains(active)) return;
+ var again = arrowsFor(nav, id);
+ var button = (again[nth] || again[0] || nav).querySelector("[mapa-side-arrow]");
+ if (button) button.focus({ preventScroll: true });
+ }).catch(function () {
+ if (mine === sent) window.location.reload();
+ }); // caught, so the queue goes on after a failure
+ });
+ // → 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;
+ });
+ }
+
// ---- Start ----------------------------------------------------------------
function start() {
@@ -918,13 +993,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") {
@@ -938,6 +1014,7 @@
});
newTeamPage();
rowMenus();
+ sideArrows();
offerZone();
}
diff --git a/internal/mapa/templates/frame.html b/internal/mapa/templates/frame.html
index 48f378a..5c7e684 100644
--- a/internal/mapa/templates/frame.html
+++ b/internal/mapa/templates/frame.html
@@ -166,7 +166,16 @@
</div>
</nav>{{end}}
{{define "mapa-side-place"}}{{icon .Icon}}<span mapa-side-label>{{.Label}}</span>{{if eq .Href "/search"}}<kbd mapa-kbd aria-hidden="true">⌘K</kbd>{{end}}{{end}}
-{{define "mapa-side-link"}}<div mapa-side-row><a mapa-side-item mapa-side-page href="{{.Href}}"{{if .Current}} aria-current="page"{{end}}>{{pageIcon .Look .Icon}}<span mapa-side-label>{{.Label}}{{if .Private}}<span mapa-sr>, only you see this</span>{{end}}</span>{{if .Private}}<span mapa-side-lock aria-hidden="true">{{icon "lock"}}</span>{{end}}</a>{{template "mapa-row-menu" .}}</div>{{end}}
+{{define "mapa-side-link"}}<div mapa-side-row{{if .Gutter}} mapa-side-gutter data-depth="{{.Depth}}"{{end}}>{{if .Gutter}}{{template "mapa-side-arrow" .}}{{end}}<a mapa-side-item mapa-side-page href="{{.Href}}"{{if .Current}} aria-current="page"{{end}}>{{pageIcon .Look .Icon}}<span mapa-side-label>{{.Label}}{{if .Private}}<span mapa-sr>, only you see this</span>{{end}}</span>{{if .Private}}<span mapa-side-lock aria-hidden="true">{{icon "lock"}}</span>{{end}}</a>{{template "mapa-row-menu" .}}</div>{{if .Open}}<ul mapa-side-inside id="{{.ListID}}" aria-label="Pages inside {{.Label}}">
+ {{- range .Inside}}<li>{{template "mapa-side-link" .}}</li>{{end}}
+ {{- if .More}}<li><a mapa-side-all href="{{.Href}}/inside">See all pages inside ({{number L .All}})</a></li>{{end}}
+</ul>{{end}}{{end}}
+
+{{/* mapa-side-arrow: a Pinned row's disclosure (columns and icons spec
+ §5.3), a form so it works with no script: POST /view/open sets the
+ cookie and comes back. A row with nothing inside keeps the empty
+ cell, so every icon in Pinned lines up. Data: sideLink. */}}
+{{define "mapa-side-arrow"}}{{if .Arrow}}<form method="post" action="/view/open" mapa-side-arrow-form><input type="hidden" name="id" value="{{.Public}}"><input type="hidden" name="open" value="{{if .Open}}0{{else}}1{{end}}"><input type="hidden" name="return" value="{{.Return}}"><button type="submit" mapa-side-arrow aria-expanded="{{if .Open}}true{{else}}false{{end}}"{{if .Open}} aria-controls="{{.ListID}}"{{end}} aria-label="Pages inside {{.Label}}">{{icon "chevron-right"}}</button></form>{{else}}<span mapa-side-arrow-gap aria-hidden="true"></span>{{end}}{{end}}
{{/* mapa-row-menu: a page row's ⋯ (build note 88), the link's sibling,
never inside it. A <details> in estilo's group, as the bar's menus
diff --git a/internal/mapa/templates/import.html b/internal/mapa/templates/import.html
index 1f4f1cd..2a6e04c 100644
--- a/internal/mapa/templates/import.html
+++ b/internal/mapa/templates/import.html
@@ -56,6 +56,8 @@
<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 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>
<dt>Created</dt><dd>{{number L .Created}}</dd>
diff --git a/internal/mapa/templates/inside.html b/internal/mapa/templates/inside.html
new file mode 100644
index 0000000..af8ec16
--- /dev/null
+++ b/internal/mapa/templates/inside.html
@@ -0,0 +1,9 @@
+{{/* inside: every page inside a team page (columns and icons spec
+ §5.3), the sidebar's "All pages inside" link. Data: Page, Rows. */}}
+{{define "content"}}{{$page := .Data.Page}}
+{{template "back-nav" dict "Href" $page.Href "Label" $page.Label}}
+{{template "page-header" dict "Title" (printf "Pages inside %s" $page.Label) "Sub" "Each page starts with a line saying it is inside this page."}}
+<ul mapa-list>
+{{range .Data.Rows}}<li><a href="{{.Href}}" mapa-looked>{{pageIcon .Look "file-text"}}<span>{{.Label}}</span></a></li>
+{{end}}</ul>
+{{end}}
diff --git a/internal/mapatest/gate8_test.go b/internal/mapatest/gate8_test.go
index ebcb9a8..76ca341 100644
--- a/internal/mapatest/gate8_test.go
+++ b/internal/mapatest/gate8_test.go
@@ -137,6 +137,10 @@ func gate8Steps(t *testing.T, world *rig) []step {
url.Values{"state": {"rail"}, "return": {"/"}}),
posting("/view/links", Ana, "/view/links",
url.Values{"state": {"closed"}, "return": {"/"}}),
+ // The sidebar's arrows: a cookie, no row (columns and icons
+ // spec §5.3).
+ posting("/view/open", Ana, "/view/open",
+ url.Values{"id": {"x"}, "open": {"1"}, "return": {"/"}}),
posting("/p/{id}/pin", Bo, acme+"/pin", url.Values{"pin": {"1"}}),
// A team page's look: a styled revision (columns and icons
// spec §4.1).
diff --git a/internal/mapatest/inside_browser_test.go b/internal/mapatest/inside_browser_test.go
new file mode 100644
index 0000000..1c239d8
--- /dev/null
+++ b/internal/mapatest/inside_browser_test.go
@@ -0,0 +1,220 @@
+//go:build browser
+
+package mapatest
+
+import (
+ "context"
+ "encoding/json"
+ "slices"
+ "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"
+
+ "amadan.net/oficina/mapa/internal/mapa"
+)
+
+// IN5 and IN8 (columns and icons spec §5.3, §9) in a real Chromium: the
+// 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)
+ ctx := context.Background()
+ projects, err := store.CreateTeamPage(ctx, Bo, "Projects", "See.")
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, title := range []string{"Alpha", "Beta"} {
+ if _, err := store.CreateTeamPage(ctx, Bo, title,
+ "In: [[Projects]]\n\nText."); err != nil {
+ t.Fatal(err)
+ }
+ }
+ titledPage(t, rig, store, "Desk", "Work.")
+ viewer, _ := store.Viewer(ctx, Ana, nil)
+ if err := store.SetPin(ctx, viewer, projects.ID, true); err != nil {
+ t.Fatal(err)
+ }
+ drive(t, rig, chromedp.Reload(), chromedp.WaitVisible(mounted),
+ chromedp.Focus(`[mapa-side-arrow][aria-label="Pages inside Projects"]`),
+ chromedp.KeyEvent(kb.Enter),
+ chromedp.WaitVisible(`ul[mapa-side-inside]`))
+ focused := evaluate(t, rig,
+ `document.activeElement.getAttribute("aria-expanded")`)
+ if focused != "true" {
+ t.Fatalf("focus after opening: aria-expanded %q", focused)
+ }
+ if found := axeSerious(t, rig); found != "" {
+ t.Fatalf("axe, a row open:\n%s", found)
+ }
+ 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] || !slices.Contains(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
new file mode 100644
index 0000000..9d4cb34
--- /dev/null
+++ b/internal/mapatest/inside_test.go
@@ -0,0 +1,221 @@
+package mapatest
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "regexp"
+ "strings"
+ "testing"
+)
+
+// IN3, IN4, IN6 and IN7 (columns and icons spec §5, §9), from the
+// outside: the arrow on a pinned row, its rows, what scope shows, what
+// is written (nothing), the scriptless form, cycles and the caps.
+
+// pinned is a team page made by Ana and pinned by Bo.
+func pinned(t *testing.T, rig *rig, title, body string) string {
+ t.Helper()
+ path := rig.createPage(t, Ana, title, body)
+ rig.post(t, Bo, path+"/pin", url.Values{"pin": {"1"}})
+ return path
+}
+
+// opened is a page as Bo sees it with the rows of ids open.
+func opened(t *testing.T, rig *rig, path string, ids ...string) string {
+ t.Helper()
+ request, _ := http.NewRequest(http.MethodGet, path, nil)
+ request.AddCookie(&http.Cookie{Name: "mapa-open",
+ Value: strings.Join(ids, " ")})
+ recorder := httptest.NewRecorder()
+ rig.built.As(Bo).ServeHTTP(recorder, request)
+ return recorder.Body.String()
+}
+
+func TestIN6AnArrowOpensThePagesInside(t *testing.T) {
+ rig := newRig(t)
+ projects := pinned(t, rig, "Projects", "See [[Beta]].")
+ rig.createPage(t, Ana, "Alpha", "In: [[Projects]]\n\nA.")
+ rig.createPage(t, Ana, "Beta", "In: [[Projects]]\n\nB.")
+ closed := rig.page(t, Bo, projects)
+ if !strings.Contains(closed, `aria-label="Pages inside Projects"`) ||
+ !strings.Contains(closed, `aria-expanded="false"`) {
+ t.Fatal("the pinned row has no closed arrow")
+ }
+ answer := rig.post(t, Bo, "/view/open", url.Values{
+ "id": {strings.TrimPrefix(projects, "/p/")}, "open": {"1"},
+ "return": {projects}})
+ if answer.Code != http.StatusSeeOther ||
+ !strings.Contains(answer.Header().Get("Set-Cookie"), "mapa-open=") {
+ t.Fatalf("the arrow's form: %d", answer.Code)
+ }
+ open := opened(t, rig, projects, strings.TrimPrefix(projects, "/p/"))
+ beta := strings.Index(open, "mapa-side-label>Beta<")
+ alpha := strings.Index(open, "mapa-side-label>Alpha<")
+ if !strings.Contains(open, `aria-expanded="true"`) || beta < 0 ||
+ alpha < beta {
+ t.Fatal("the open row does not list Beta then Alpha")
+ }
+ answer = rig.post(t, Bo, "/view/open", url.Values{"id": {"x"},
+ "open": {"1"}, "return": {"https://example.com/"}})
+ if answer.Header().Get("Location") != "/" {
+ t.Fatal("a foreign return was followed")
+ }
+}
+
+func TestIN3PrivateInLinesAreNoPageInside(t *testing.T) {
+ rig := newRig(t)
+ projects := pinned(t, rig, "Projects", "Text.")
+ id := strings.TrimPrefix(projects, "/p/")
+ before := opened(t, rig, projects, id)
+ rig.post(t, Ana, "/scratch", url.Values{"body": {"In: [[Projects]]"}})
+ if after := opened(t, rig, projects, id); after != before {
+ t.Fatal("Ana's private note changed Bo's sidebar")
+ }
+ 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) {
+ rig := newRig(t)
+ projects := pinned(t, rig, "Projects", "Text.")
+ rig.createPage(t, Ana, "Alpha", "In: [[Projects]]")
+ before := snapshot(t, rig)
+ rig.post(t, Bo, "/view/open", url.Values{"id": {"x"}, "open": {"1"}})
+ if code := rig.get(t, Bo, projects+"/inside").Code; code != http.StatusOK {
+ t.Fatalf("all pages inside: %d", code)
+ }
+ if snapshot(t, rig) != before {
+ t.Fatal("opening a row or the list wrote a row")
+ }
+}
+
+func TestIN7CyclesAndCaps(t *testing.T) {
+ rig := newRig(t)
+ one := pinned(t, rig, "One", "In: [[Two]]")
+ two := rig.createPage(t, Ana, "Two", "In: [[One]]")
+ page := opened(t, rig, one, strings.TrimPrefix(one, "/p/"),
+ strings.TrimPrefix(two, "/p/"))
+ // One's row opens Two, whose row lists One again without an arrow.
+ if strings.Count(page, "mapa-side-label>Two<") != 1 ||
+ strings.Count(page, "mapa-side-label>One<") != 2 ||
+ strings.Count(page, `<button type="submit" mapa-side-arrow`) != 2 {
+ t.Fatal("a cycle opened more than once")
+ }
+ big := pinned(t, rig, "Big", "Text.")
+ for at := range 51 {
+ rig.createPage(t, Ana, "Child "+strings.Repeat("x", at+1),
+ "In: [[Big]]")
+ }
+ page = opened(t, rig, big, strings.TrimPrefix(big, "/p/"))
+ if strings.Count(page, `mapa-side-label>Child x`) != 50 ||
+ !strings.Contains(page, big+`/inside">See all pages inside (51)`) {
+ t.Fatal("51 pages inside are not 50 rows and a link")
+ }
+ if all := rig.page(t, Bo, big+"/inside"); strings.Count(all,
+ ">Child x") != 51 {
+ 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>")]
+}
diff --git a/scripts/mutate/inside.go b/scripts/mutate/inside.go
new file mode 100644
index 0000000..f27dae3
--- /dev/null
+++ b/scripts/mutate/inside.go
@@ -0,0 +1,26 @@
+package main
+
+// The columns and icons spec's mutations for pages inside and the
+// import's pins (§9): a private page inside a team page, and a root
+// pinned again on every run.
+
+const (
+ insideGo = "internal/mapa/inside.go"
+ importPinsGo = "internal/mapa/import_pins.go"
+)
+
+var insideMutations = []mutation{
+ {gate: "IN3", test: "TestIN3PrivateInLinesAreNoPageInside",
+ name: "a private page's In: line counts",
+ edits: []edit{{file: insideGo,
+ from: "\tif kind != KindPage || rung != RungTeam || " +
+ "len(blocks) == 0 {",
+ to: "\tif len(blocks) == 0 {"}, {file: insideGo,
+ from: "\t\t\tif child != page.id && index.team[child] {",
+ to: "\t\t\tif child != page.id {"}}},
+ {gate: "I23", test: "TestI23TheImportPinsItsRootsOnce", pkg: inside,
+ name: "a root is offered on every run",
+ edits: []edit{{file: importPinsGo,
+ from: "\t\tif entry.place.Pin != nil || entry.place.PageID == 0 ||",
+ to: "\t\tif entry.place.PageID == 0 ||"}}},
+}
diff --git a/scripts/mutate/main.go b/scripts/mutate/main.go
index da84093..bedbf99 100644
--- a/scripts/mutate/main.go
+++ b/scripts/mutate/main.go
@@ -43,6 +43,7 @@ func every() []mutation {
all := append([]mutation{}, mutations...)
all = append(all, imageMutations...)
all = append(all, lookMutations...)
+ all = append(all, insideMutations...)
all = append(all, columnMutations...)
all = append(all, mapperMutations...)
all = append(all, importMutations...)