oficina / mapa Public

Merge level-up/history: Phase 1 step 6, the History panel, summaries and word diff

relinked and marked on team pages only; summaries from each revision's
event verb, "Earlier history has aged out" and Show older; the panel as a
?panel=1 fragment under the Sec-Fetch-Dest rule, the page beside it
without script; a chosen version's block-then-word diff with Back to
current and Restore. Built by a sub-agent on its own branch; AGENTS.md,
models.go and shell.html merged by hand, and the summaries now carry
their own attribute so the Links panel's counts are not read as them.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev b76e58ba5eb41d0058535d6772e47dd72cd9a222 parent 280ada0parent ebf16b2
25 files changed, +1,998 −92
  • AGENTS.md +5 −1
  • internal/mapa/diff.go +244 −0
  • internal/mapa/diff_test.go +126 −0
  • internal/mapa/diff_words.go +207 −0
  • internal/mapa/frame.go +3 −0
  • internal/mapa/handlers_history.go +48 −13
  • internal/mapa/history.go +34 −53
  • internal/mapa/history_view.go +182 −0
  • internal/mapa/markers.go +2 −1
  • internal/mapa/mentions.go +2 −1
  • internal/mapa/models.go +17 −0
  • internal/mapa/render.go +3 −2
  • internal/mapa/shell.go +3 −0
  • internal/mapa/static/history.css +173 −0
  • internal/mapa/static/history.js +120 −0
  • internal/mapa/templates/history.html +39 −7
  • internal/mapa/templates/revision.html +9 −8
  • internal/mapa/templates/shell.html +4 −1
  • internal/mapa/verbs.go +2 −1
  • internal/mapa/versions.go +353 −0
  • internal/mapatest/browser_history_test.go +67 −0
  • internal/mapatest/browser_test.go +7 −3
  • internal/mapatest/history_panel_test.go +265 −0
  • internal/mapatest/history_test.go +2 −1
  • internal/mapatest/verbs_test.go +81 −0

CI passed — run details

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

added 16 packages in 476ms
cd editor && node build-bundles.mjs
wrote internal/mapa/static/editor.9c9edc5536b1d844.js (36245 bytes, 11.3KB gzipped; L12 budget 120KB)
cd editor && node --test
✔ golden file has bodies (0.98293ms)
✔ markup.mjs parses every body into Go's blocks, byte offsets and all (14.980762ms)
✔ markup.mjs strips and spans every block as Go does (27.639831ms)
✔ the schema's toDOM draws every body as Go renders it (43.693148ms)
✔ emphasis draws the four pinned outputs (12.280926ms)
✔ a body ends in the editor's empty paragraph (0.219136ms)
ℹ tests 6
ℹ suites 0
ℹ pass 6
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 175.055747
=== 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	0.545s
?   	amadan.net/oficina/mapa/internal/mapa/icons	[no test files]
ok  	amadan.net/oficina/mapa/internal/mapa/markup	0.047s
ok  	amadan.net/oficina/mapa/internal/mapa/seal	(cached)
ok  	amadan.net/oficina/mapa/internal/mapatest	9.706s
?   	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
diff --git a/AGENTS.md b/AGENTS.md
index 386aa7e..a14e805 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -47,7 +47,11 @@ Makefile, estilo's files served straight from the module).
its map, the week and the month; `pins.go` and `recent.go` are the
sidebar's own lists; `lastedit.go` is the kicker's "Edited by".
`mapa.js` is the editor's and ⌘K's script layer, `links.js` the
- panel's; `frame.css` and `links.css` style them.
+ panel's and `history.js` the History panel's; `frame.css`, `links.css`,
+ `history.css` and `palette.css` style them. `versions.go`, `diff.go`,
+ `diff_words.go` and `history_view.go` are the History panel's list,
+ summaries and word diff (level-up §4.5); `typeddate.go` and
+ `snippet.go` are ⌘K's typed dates and marked snippets.
- `editor/` — the page editor (level-up spec §6): `markup.mjs`, a
line-for-line port of `markup/`'s parser; `schema.mjs`, whose `toDOM`
is the server's HTML; and the bundle build, whose output
diff --git a/internal/mapa/diff.go b/internal/mapa/diff.go
new file mode 100644
index 0000000..03acaa2
--- /dev/null
+++ b/internal/mapa/diff.go
@@ -0,0 +1,244 @@
+package mapa
+
+import (
+ "html/template"
+ "math"
+ "strconv"
+ "strings"
+
+ "amadan.net/oficina/mapa/internal/mapa/markup"
+)
+
+// The history diff (level-up spec §4.5): block by block, aligned as the
+// merge aligns them, then word by word inside a block that changed. A
+// [[link]] is one word. Everything a person typed is escaped; a changed
+// block is drawn as its kind with its text, never through the renderer.
+
+// Kinds of block change.
+const (
+ blockSame = "same"
+ blockAdded = "added"
+ blockRemoved = "removed"
+ blockChanged = "changed"
+)
+
+// blockChange is one step from the version before to this one. From and
+// To are block indices, -1 where the side has none. At is where the step
+// falls in this version: To, or for a removal the block after it.
+type blockChange struct {
+ Kind string
+ From, To, At int
+}
+
+// diffBlocks is the steps from one version's blocks to the next's.
+// Unmatched blocks between two matches pair up in order as changed
+// blocks when their words are alike; the rest are removed, then added.
+func diffBlocks(from, to []markup.Block) []blockChange {
+ matched := matchBlocks(from, to)
+ alike := func(was, now int) bool {
+ return similar(tokensOf(from[was]), tokensOf(to[now]))
+ }
+ var changes, removed []blockChange
+ next := 0
+ for index, target := range matched {
+ if target < 0 {
+ removed = append(removed, blockChange{Kind: blockRemoved,
+ From: index, To: -1})
+ continue
+ }
+ changes = append(changes, stretch(removed, next, target, alike)...)
+ changes = append(changes, blockChange{Kind: blockSame, From: index,
+ To: target, At: target})
+ removed, next = nil, target+1
+ }
+ return append(changes, stretch(removed, next, len(to), alike)...)
+}
+
+// stretch settles the blocks between two matches: removed from the
+// version before, and to's blocks start up to end. Each removed block is
+// paired, in order, with the next added one alike enough to diff word
+// by word (a changed block); the rest are removed or added, in place.
+func stretch(removed []blockChange, start, end int,
+ alike func(was, now int) bool) []blockChange {
+ pairs := pairUp(removed, start, end, alike)
+ var out []blockChange
+ next := 0
+ settle := func(before, at int) {
+ for ; next < len(removed) && removed[next].From < before; next++ {
+ gone := removed[next]
+ gone.At = at
+ out = append(out, gone)
+ }
+ }
+ for index := start; index < end; index++ {
+ old, paired := pairs[index]
+ if !paired {
+ out = append(out, blockChange{Kind: blockAdded, From: -1,
+ To: index, At: index})
+ continue
+ }
+ settle(old, index)
+ next++
+ out = append(out, blockChange{Kind: blockChanged, From: old,
+ To: index, At: index})
+ }
+ settle(math.MaxInt, end)
+ return out
+}
+
+// maxPairings bounds how many block pairs one stretch compares.
+const maxPairings = 2000
+
+// pairUp maps an added block's index to the removed block it changed:
+// greedily, in order on both sides, so a pairing never crosses another.
+func pairUp(removed []blockChange, start, end int,
+ alike func(was, now int) bool) map[int]int {
+ pairs := map[int]int{}
+ cursor, tries := start, 0
+ for _, gone := range removed {
+ for candidate := cursor; candidate < end; candidate++ {
+ if tries++; tries > maxPairings {
+ return pairs
+ }
+ if alike(gone.From, candidate) {
+ pairs[candidate] = gone.From
+ cursor = candidate + 1
+ break
+ }
+ }
+ }
+ return pairs
+}
+
+// matchBlocks maps each block of from to its match in to, by a longest
+// common subsequence of block sources, or -1 where it has none: the
+// merge's alignment (markup's align), kept here so history needs
+// nothing new from markup.
+func matchBlocks(from, to []markup.Block) []int {
+ same := func(row, column int) bool {
+ return from[row].Source == to[column].Source
+ }
+ return lcs(len(from), len(to), same)
+}
+
+// lcs maps each of rows items to its match among columns, or -1, by a
+// longest common subsequence under same.
+func lcs(rows, columns int, same func(row, column int) bool) []int {
+ lengths := make([][]int32, rows+1)
+ for row := range lengths {
+ lengths[row] = make([]int32, columns+1)
+ }
+ for row := rows - 1; row >= 0; row-- {
+ for column := columns - 1; column >= 0; column-- {
+ if same(row, column) {
+ lengths[row][column] = lengths[row+1][column+1] + 1
+ } else {
+ lengths[row][column] = max(lengths[row+1][column],
+ lengths[row][column+1])
+ }
+ }
+ }
+ matched := make([]int, rows)
+ row, column := 0, 0
+ for row < rows {
+ switch {
+ case column < columns && same(row, column):
+ matched[row] = column
+ row, column = row+1, column+1
+ case column < columns &&
+ lengths[row][column+1] >= lengths[row+1][column]:
+ column++
+ default:
+ matched[row] = -1
+ row++
+ }
+ }
+ return matched
+}
+
+// diffHTML draws this version, to, with what changed from the version
+// before it marked. Runs of unchanged blocks go through draw, the page's
+// own renderer with the viewer's scope; changed blocks are drawn here.
+func diffHTML(from, to []markup.Block,
+ draw func(string) (template.HTML, error)) (template.HTML, error) {
+ var out strings.Builder
+ var kept []markup.Block
+ flush := func() error {
+ if len(kept) == 0 {
+ return nil
+ }
+ drawn, err := draw(markup.Join(kept))
+ out.WriteString(string(drawn))
+ kept = nil
+ return err
+ }
+ for _, change := range diffBlocks(from, to) {
+ if change.Kind == blockSame {
+ kept = append(kept, to[change.To])
+ continue
+ }
+ if err := flush(); err != nil {
+ return "", err
+ }
+ out.WriteString(changedBlock(change, from, to))
+ }
+ if err := flush(); err != nil {
+ return "", err
+ }
+ return template.HTML(out.String()), nil
+}
+
+// changedBlock is one added, removed or changed block, as its kind.
+func changedBlock(change blockChange, from, to []markup.Block) string {
+ var block markup.Block
+ var inner string
+ switch change.Kind {
+ case blockAdded:
+ block = to[change.To]
+ inner = drawRuns([]wordRun{{Tag: "ins", Tokens: tokensOf(block)}})
+ case blockRemoved:
+ block = from[change.From]
+ inner = drawRuns([]wordRun{{Tag: "del", Tokens: tokensOf(block)}})
+ default:
+ block = to[change.To]
+ inner = drawRuns(diffWords(tokensOf(from[change.From]),
+ tokensOf(block)))
+ }
+ return `<div mapa-diff="` + change.Kind + `">` + asKind(block, inner) +
+ "</div>\n"
+}
+
+// asKind wraps a block's drawn text in its kind's element.
+func asKind(block markup.Block, inner string) string {
+ switch block.Kind {
+ case markup.Heading:
+ level := strconv.Itoa(min(block.Level+1, 6))
+ return "<h" + level + ">" + inner + "</h" + level + ">"
+ case markup.Item:
+ return asItem(block, inner)
+ case markup.Quote:
+ return "<blockquote><p>" + inner + "</p></blockquote>"
+ case markup.Code:
+ return "<pre><code>" + inner + "</code></pre>"
+ case markup.Rule:
+ return "<hr>"
+ }
+ return "<p>" + inner + "</p>"
+}
+
+// asItem is one list item as a list of its own, at its depth; a numbered
+// item keeps its number.
+func asItem(block markup.Block, inner string) string {
+ open := "<ul"
+ tag := "ul"
+ if block.Ordered {
+ tag = "ol"
+ digits := strings.TrimLeft(block.Source, " \t")
+ end := strings.IndexFunc(digits, func(char rune) bool {
+ return char < '0' || char > '9'
+ })
+ open = `<ol start="` + digits[:max(end, 0)] + `"`
+ }
+ return open + ` mapa-diff-level="` + strconv.Itoa(min(block.Level, 3)) +
+ `"><li>` + inner + "</li></" + tag + ">"
+}
diff --git a/internal/mapa/diff_test.go b/internal/mapa/diff_test.go
new file mode 100644
index 0000000..351025b
--- /dev/null
+++ b/internal/mapa/diff_test.go
@@ -0,0 +1,126 @@
+package mapa
+
+import (
+ "html/template"
+ "strings"
+ "testing"
+
+ "amadan.net/oficina/mapa/internal/mapa/markup"
+)
+
+func TestEditSummaries(t *testing.T) {
+ base := "Intro.\n\n## Where things stand\n\nRenewal in February.\n\n" +
+ "## Contacts\n\nAna, budget."
+ for _, check := range []struct{ body, want string }{
+ {base, "Edited"},
+ {strings.Replace(base, "February", "March", 1),
+ "Edited Where things stand"},
+ {strings.Replace(base, "## Contacts", "## People", 1),
+ "Edited People"},
+ {base + "\n\nTom, signs.", "Added a block"},
+ {base + "\n\nTom, signs.\n\nBo, helps.", "Added 2 blocks"},
+ {strings.Replace(base, "Intro.\n\n", "", 1), "Removed a block"},
+ {"Intro.\n\n## Where things stand", "Removed 3 blocks"},
+ {strings.Replace(base, "Intro.", "Hello.", 1), "Edited"},
+ {strings.Replace(base, "Ana, budget.", "Ana, [[Budget]].", 1),
+ "Edited Contacts"},
+ } {
+ if got := editSummary(base, check.body); got != check.want {
+ t.Errorf("%q: got %q, want %q", check.body, got, check.want)
+ }
+ }
+}
+
+func plainDraw(body string) (template.HTML, error) {
+ return template.HTML("[" + template.HTMLEscapeString(body) + "]"), nil
+}
+
+func diffOf(t *testing.T, old, body string) string {
+ t.Helper()
+ drawn, err := diffHTML(markup.Parse(old), markup.Parse(body), plainDraw)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return string(drawn)
+}
+
+func TestTheWordDiffMarksOnlyWhatChanged(t *testing.T) {
+ got := diffOf(t, "Same.\n\n- The window opens in February.",
+ "Same.\n\n- The window opens in March.")
+ want := `[Same.]<div mapa-diff="changed"><ul mapa-diff-level="0"><li>` +
+ `The window opens in <del>February.</del><ins>March.</ins>` +
+ "</li></ul></div>\n"
+ if got != want {
+ t.Fatalf("got %s\nwant %s", got, want)
+ }
+}
+
+func TestALinkIsOneWord(t *testing.T) {
+ got := diffOf(t, "See [[Acme Holdings|the client]] now.",
+ "See [[Acme Holdings|the clients]] now.")
+ if !strings.Contains(got, `<del><span mapa-diff-link>the client</span>`+
+ `</del><ins><span mapa-diff-link>the clients</span></ins>`) {
+ t.Fatalf("a link was not diffed whole: %s", got)
+ }
+}
+
+func TestAddedAndRemovedBlocksAreWhole(t *testing.T) {
+ got := diffOf(t, "# Old heading\n\nKept.", "Kept.\n\n> New quote")
+ for _, want := range []string{
+ `<div mapa-diff="removed"><h2><del>Old heading</del></h2></div>`,
+ `<div mapa-diff="added"><blockquote><p><ins>New quote</ins>` +
+ `</p></blockquote></div>`,
+ "[Kept.]",
+ } {
+ if !strings.Contains(got, want) {
+ t.Errorf("missing %s in %s", want, got)
+ }
+ }
+}
+
+// Everything typed is escaped: the diff never passes markup through.
+func TestTheDiffEscapes(t *testing.T) {
+ got := diffOf(t, "a <b>", "a <script>alert(1)</script> [[<x>]]")
+ if strings.Contains(got, "<script>") || strings.Contains(got, "<x>") ||
+ strings.Contains(got, "<b>") {
+ t.Fatalf("unescaped: %s", got)
+ }
+}
+
+func TestWordsKeepMultibyteText(t *testing.T) {
+ got := diffOf(t, "café naïve", "café naïf")
+ if !strings.Contains(got, "café <del>naïve</del><ins>naïf</ins>") {
+ t.Fatalf("got %s", got)
+ }
+}
+
+// A changed block pairs with the added block it is like, past blocks
+// inserted before it; an unlike one is removed and added whole.
+func TestBlocksPairByLikeness(t *testing.T) {
+ got := diffOf(t, "- Renewal is tied to the grant cycle\n- Old note",
+ "## Where things stand\n\n- Renewal is tied to the grant cycle "+
+ "in March.\n- Something else entirely")
+ for _, want := range []string{
+ `<div mapa-diff="added"><h3><ins>Where things stand</ins></h3>`,
+ `<div mapa-diff="changed"><ul mapa-diff-level="0"><li>Renewal ` +
+ `is tied to the grant cycle<ins> in March.</ins></li>`,
+ `<div mapa-diff="removed"><ul mapa-diff-level="0"><li><del>Old ` +
+ `note</del>`,
+ `<div mapa-diff="added"><ul mapa-diff-level="0"><li><ins>` +
+ `Something else entirely</ins>`,
+ } {
+ if !strings.Contains(got, want) {
+ t.Errorf("missing %s in\n%s", want, got)
+ }
+ }
+}
+
+func TestChangedBlocksDrawEmphasisAndNumbers(t *testing.T) {
+ got := diffOf(t, "1. Ana, budget.\n2. **Tom**, signs.",
+ "1. Ana, budget.\n2. **Tom**, signs today.")
+ want := `<ol start="2" mapa-diff-level="0"><li><strong>Tom</strong>,` +
+ ` <del>signs.</del><ins>signs today.</ins></li></ol>`
+ if !strings.Contains(got, want) {
+ t.Fatalf("got %s", got)
+ }
+}
diff --git a/internal/mapa/diff_words.go b/internal/mapa/diff_words.go
new file mode 100644
index 0000000..6d74ad5
--- /dev/null
+++ b/internal/mapa/diff_words.go
@@ -0,0 +1,207 @@
+package mapa
+
+import (
+ "html"
+ "regexp"
+ "strings"
+ "unicode"
+ "unicode/utf8"
+
+ "amadan.net/oficina/mapa/internal/mapa/markup"
+)
+
+// The word diff inside a changed block (level-up §4.5): words, the space
+// between them, and whole links, code spans and embeds, compared by
+// what was typed and drawn escaped.
+
+// token is one word of a block: Key is what is compared (a link's
+// source), and HTML is how it is drawn, escaped. Text marks a word of
+// running text, where emphasis is drawn.
+type token struct {
+ Key string
+ HTML string
+ Text bool
+}
+
+// wordRun is a run of tokens kept (Tag ""), removed ("del") or added
+// ("ins").
+type wordRun struct {
+ Tag string
+ Tokens []token
+}
+
+// tokensOf splits a block's text into words, the spaces between them,
+// and whole links, code spans and embeds.
+func tokensOf(block markup.Block) []token {
+ if block.Kind == markup.Code {
+ return wordsIn(markup.Words(block), false)
+ }
+ var out []token
+ for _, span := range markup.Spans(markup.Strip(block)) {
+ switch span.Kind {
+ case markup.Text:
+ out = append(out, wordsIn(span.Text, true)...)
+ case markup.WikiLink:
+ shown := span.Text
+ if shown == "" {
+ shown = span.Target
+ }
+ out = append(out, token{Key: span.Source,
+ HTML: "<span mapa-diff-link>" + html.EscapeString(shown) +
+ "</span>"})
+ case markup.InCode:
+ out = append(out, token{Key: span.Source,
+ HTML: "<code>" + html.EscapeString(span.Text) + "</code>"})
+ default:
+ out = append(out, token{Key: span.Source,
+ HTML: html.EscapeString(span.Text)})
+ }
+ }
+ return out
+}
+
+// wordsIn is text as words and the runs of space between them. In
+// running text a line break is drawn as <br>; code keeps it, in <pre>.
+func wordsIn(text string, running bool) []token {
+ var out []token
+ spaceAt := func(at int) (bool, int) {
+ char, width := utf8.DecodeRuneInString(text[at:])
+ return unicode.IsSpace(char), width
+ }
+ start := 0
+ for start < len(text) {
+ space, _ := spaceAt(start)
+ end := start
+ for end < len(text) {
+ here, width := spaceAt(end)
+ if here != space {
+ break
+ }
+ end += width
+ }
+ run := text[start:end]
+ drawn := html.EscapeString(run)
+ if running {
+ drawn = strings.ReplaceAll(drawn, "\n", "<br>")
+ }
+ out = append(out, token{Key: run, HTML: drawn, Text: running})
+ start = end
+ }
+ return out
+}
+
+// maxWordCells bounds the word diff's table: two blocks longer than
+// this together are shown as removed and added whole.
+const maxWordCells = 250000
+
+// diffWords is to against from as runs: kept, removed and added.
+func diffWords(from, to []token) []wordRun {
+ if len(from)*len(to) > maxWordCells {
+ return []wordRun{{Tag: "del", Tokens: from},
+ {Tag: "ins", Tokens: to}}
+ }
+ matched := lcs(len(from), len(to), func(row, column int) bool {
+ return from[row].Key == to[column].Key
+ })
+ var runs []wordRun
+ add := func(tag string, tokens ...token) {
+ if len(tokens) == 0 {
+ return
+ }
+ if last := len(runs) - 1; last >= 0 && runs[last].Tag == tag {
+ runs[last].Tokens = append(runs[last].Tokens, tokens...)
+ return
+ }
+ runs = append(runs, wordRun{Tag: tag, Tokens: tokens})
+ }
+ next := 0
+ for index, target := range matched {
+ if target < 0 {
+ add("del", from[index])
+ continue
+ }
+ add("ins", to[next:target]...)
+ add("", to[target])
+ next = target + 1
+ }
+ add("ins", to[next:]...)
+ return runs
+}
+
+// similar reports two blocks whose words are alike enough to diff word
+// by word: at least two fifths of their words in common.
+func similar(from, to []token) bool {
+ from, to = wordsOnly(from), wordsOnly(to)
+ if len(from)+len(to) == 0 {
+ return true
+ }
+ if len(from)*len(to) > maxWordCells {
+ return false
+ }
+ common := 0
+ matched := lcs(len(from), len(to), func(row, column int) bool {
+ return from[row].Key == to[column].Key
+ })
+ for _, target := range matched {
+ if target >= 0 {
+ common++
+ }
+ }
+ return common*5 >= len(from)+len(to)
+}
+
+func wordsOnly(tokens []token) []token {
+ var out []token
+ for _, word := range tokens {
+ if strings.TrimSpace(word.Key) != "" {
+ out = append(out, word)
+ }
+ }
+ return out
+}
+
+// drawRuns draws runs of tokens, each removed or added run in its tag.
+func drawRuns(runs []wordRun) string {
+ var out strings.Builder
+ for _, run := range runs {
+ if len(run.Tokens) == 0 {
+ continue
+ }
+ if run.Tag != "" {
+ out.WriteString("<" + run.Tag + ">")
+ }
+ out.WriteString(drawTokens(run.Tokens))
+ if run.Tag != "" {
+ out.WriteString("</" + run.Tag + ">")
+ }
+ }
+ return out.String()
+}
+
+var (
+ strongText = regexp.MustCompile(`\*\*(\S(?:[^*]*?\S)?)\*\*`)
+ emphasisText = regexp.MustCompile(`\*(\S(?:[^*]*?\S)?)\*`)
+)
+
+// drawTokens joins tokens, drawing emphasis inside each stretch of
+// running text, as the page's renderer does. Emphasis that crosses a
+// change, a link or code shows its asterisks.
+func drawTokens(tokens []token) string {
+ var out, text strings.Builder
+ flush := func() {
+ drawn := strongText.ReplaceAllString(text.String(),
+ "<strong>$1</strong>")
+ out.WriteString(emphasisText.ReplaceAllString(drawn, "<em>$1</em>"))
+ text.Reset()
+ }
+ for _, word := range tokens {
+ if word.Text {
+ text.WriteString(word.HTML)
+ continue
+ }
+ flush()
+ out.WriteString(word.HTML)
+ }
+ flush()
+ return out.String()
+}
diff --git a/internal/mapa/frame.go b/internal/mapa/frame.go
index a67f74f..11c9df7 100644
--- a/internal/mapa/frame.go
+++ b/internal/mapa/frame.go
@@ -18,6 +18,9 @@ type frame struct {
// Panel is "open" or "closed": the Links panel's cookie, rendered
// so first paint is already right. Empty on screens without one.
Panel string
+ // History is the History panel, on the history routes; nil
+ // elsewhere (level-up §4.5).
+ History *historyPanel
}
// pageChrome is what a handler says about its screen, beyond its title,
diff --git a/internal/mapa/handlers_history.go b/internal/mapa/handlers_history.go
index 423d006..43699da 100644
--- a/internal/mapa/handlers_history.go
+++ b/internal/mapa/handlers_history.go
@@ -1,6 +1,7 @@
package mapa
import (
+ "html/template"
"net/http"
"strconv"
@@ -18,6 +19,9 @@ func (app *app) historyRoutes(router chi.Router) {
router.Post("/p/{id}/blocks", app.markBlock)
}
+// history is the page with the History panel beside it; a fetch asking
+// ?panel=1 gets the panel alone (level-up §4.5). ?older=N skips the N
+// newest versions. A GET: it reads and writes nothing.
func (app *app) history(writer http.ResponseWriter, request *http.Request) {
page, ok := app.visible(writer, request)
if !ok {
@@ -28,17 +32,36 @@ func (app *app) history(writer http.ResponseWriter, request *http.Request) {
app.fail(writer, request, err)
return
}
- revisions, err := app.store.History(request.Context(), viewer, page.ID)
+ skip, _ := strconv.Atoi(request.URL.Query().Get("older"))
+ list, err := app.store.History(request.Context(), viewer, page.ID, skip)
if err != nil {
app.refuse(writer, request, err)
return
}
- app.show(writer, request, http.StatusOK, "history", view{
- Title: page.Label, Nav: nav(navFor(page.Kind)), Viewer: viewer,
- Data: map[string]any{"Page": page, "Revisions": revisions},
- Chrome: &pageChrome{Page: &page}})
+ panel := panelFor(page, list, 0, app.store.now())
+ writer.Header().Set("Vary", "Sec-Fetch-Dest")
+ if wantsFragment(request) {
+ app.historyFragment(writer, request, panel)
+ return
+ }
+ app.showPage(writer, withHistory(request, &panel))
+}
+
+// historyFragment is the panel alone, for history.js to show in place.
+func (app *app) historyFragment(writer http.ResponseWriter,
+ request *http.Request, panel historyPanel) {
+ drawn, err := fragment(pages["page"], "mapa-history", panel)
+ if err != nil {
+ app.fail(writer, request, err)
+ return
+ }
+ writer.Header().Set("Content-Type", "text/html; charset=utf-8")
+ writer.Header().Set("Cache-Control", "no-store")
+ _, _ = writer.Write([]byte(drawn))
}
+// revision is the page as one version, under its banner, with what
+// changed from the version before marked, and the panel beside it.
func (app *app) revision(writer http.ResponseWriter,
request *http.Request) {
page, ok := app.visible(writer, request)
@@ -55,24 +78,36 @@ func (app *app) revision(writer http.ResponseWriter,
app.fail(writer, request, err)
return
}
- record, err := app.store.AtRevision(request.Context(), viewer, page.ID,
- revision)
+ chosen, err := app.store.ChooseVersion(request.Context(), viewer,
+ page.ID, revision)
if err != nil {
app.refuse(writer, request, err)
return
}
- html, err := app.index.Preview(request.Context(), ScopeOf(viewer),
- record.Body)
+ app.showVersion(writer, request, viewer, page, chosen)
+}
+
+func (app *app) showVersion(writer http.ResponseWriter,
+ request *http.Request, viewer Viewer, page PageView, chosen Chosen) {
+ panel := panelFor(page, chosen.List, chosen.Version.Revision,
+ app.store.now())
+ writer.Header().Set("Vary", "Sec-Fetch-Dest")
+ if wantsFragment(request) {
+ app.historyFragment(writer, request, panel)
+ return
+ }
+ draw := func(body string) (template.HTML, error) {
+ return app.index.Preview(request.Context(), ScopeOf(viewer), body)
+ }
+ data, err := versionOf(page, chosen, draw)
if err != nil {
app.fail(writer, request, err)
return
}
app.show(writer, request, http.StatusOK, "revision", view{
Title: page.Label, Nav: nav(navFor(page.Kind)), Viewer: viewer,
- Chrome: &pageChrome{Page: &page},
- Data: map[string]any{"Page": page, "Record": record, "HTML": html,
- "Current": revision == page.Revision,
- "Action": request.URL.Path}})
+ Chrome: &pageChrome{Page: &page}, Data: data,
+ Frame: frame{History: &panel}})
}
func (app *app) revert(writer http.ResponseWriter, request *http.Request) {
diff --git a/internal/mapa/history.go b/internal/mapa/history.go
index 8aaa8f5..c8031d1 100644
--- a/internal/mapa/history.go
+++ b/internal/mapa/history.go
@@ -3,7 +3,6 @@ package mapa
import (
"context"
"errors"
- "time"
"gorm.io/gorm"
@@ -18,45 +17,6 @@ import (
// VerbReverted is a restore from history.
const VerbReverted = "reverted"
-// RevisionView is one entry in a page's history.
-type RevisionView struct {
- Revision int64
- At time.Time
- Actor string
- Current bool
-}
-
-// History lists a page's revisions in the window, newest first, if the
-// viewer may open the page.
-func (store *Store) History(ctx context.Context, viewer Viewer,
- pageID int64) ([]RevisionView, error) {
- page, err := store.readable(ctx, viewer, pageID)
- if err != nil {
- return nil, err
- }
- var rows []Revision
- err = store.database.WithContext(ctx).Where("page_id = ? AND at > ?",
- pageID, store.now().UTC().Add(-HistoryWindow)).
- Order("at DESC").Limit(500).Find(&rows).Error
- if err != nil {
- return nil, err
- }
- views := make([]RevisionView, 0, len(rows))
- for _, row := range rows {
- actor, err := store.MemberAddress(ctx, row.ActorID)
- if err != nil {
- return nil, err
- }
- at := row.At
- if viewer.TimeZone != nil {
- at = at.In(viewer.TimeZone)
- }
- views = append(views, RevisionView{Revision: row.Revision,
- At: at, Actor: actor, Current: row.Revision == page.Revision})
- }
- return views, nil
-}
-
// readable is a live page the viewer may open, read without writing.
func (store *Store) readable(ctx context.Context, viewer Viewer,
pageID int64) (Page, error) {
@@ -70,23 +30,44 @@ func (store *Store) readable(ctx context.Context, viewer Viewer,
return page, err
}
-// AtRevision is a page's record at one revision in the window.
-func (store *Store) AtRevision(ctx context.Context, viewer Viewer, pageID,
- revision int64) (Record, error) {
- if _, err := store.readable(ctx, viewer, pageID); err != nil {
- return Record{}, err
+// Chosen is one version on screen (§4.5): its text, the text of the
+// version before it in the window if there is one, its verb, and the
+// screen of history that holds it.
+type Chosen struct {
+ Version Version
+ Record Record
+ Before *Record
+ Verb string
+ List VersionList
+}
+
+// ChooseVersion is one revision of a page in the window, if the viewer
+// may open the page; a revision outside the window is not found.
+func (store *Store) ChooseVersion(ctx context.Context, viewer Viewer,
+ pageID, revision int64) (Chosen, error) {
+ history, err := store.loadHistory(ctx, viewer, pageID)
+ if err != nil {
+ return Chosen{}, err
}
- var row Revision
- err := store.database.WithContext(ctx).Where("page_id = ? AND "+
- "revision = ? AND at > ?", pageID, revision,
- store.now().UTC().Add(-HistoryWindow)).First(&row).Error
- if errors.Is(err, gorm.ErrRecordNotFound) {
- return Record{}, ErrNotFound
+ index := history.find(revision)
+ if index < 0 {
+ return Chosen{}, ErrNotFound
}
+ list, err := history.list(index / HistoryPage * HistoryPage)
if err != nil {
- return Record{}, err
+ return Chosen{}, err
+ }
+ chosen := Chosen{List: list, Verb: history.verbs[revision],
+ Version: list.Versions[index%HistoryPage]}
+ if chosen.Record, err = history.record(index); err != nil {
+ return chosen, err
+ }
+ if index+1 < len(history.rows) {
+ before, err := history.record(index + 1)
+ chosen.Before = &before
+ return chosen, err
}
- return store.openRecord(seal.PurposeRecord, row.SealedRecord)
+ return chosen, nil
}
// Revert restores an old revision's body as a new revision. The title
diff --git a/internal/mapa/history_view.go b/internal/mapa/history_view.go
new file mode 100644
index 0000000..6641227
--- /dev/null
+++ b/internal/mapa/history_view.go
@@ -0,0 +1,182 @@
+package mapa
+
+import (
+ "context"
+ "html"
+ "html/template"
+ "net/http"
+ "strconv"
+ "strings"
+ "time"
+ "unicode"
+ "unicode/utf8"
+
+ "amadan.net/oficina/mapa/internal/mapa/markup"
+)
+
+// The History panel and a chosen version, as drawn (level-up §4.5). The
+// panel is templates/history.html's mapa-history, beside the page it is
+// the history of; the version view is templates/revision.html.
+
+// historyPanel is the panel's data.
+type historyPanel struct {
+ // Close is the page itself: the panel's close and Back to current.
+ Close string
+ // State is "list" with no version chosen, "version" with one.
+ State string
+ Days []historyDay
+ Older string
+ AgedOut bool
+ // Restore is the chosen version's restore form, when it is not the
+ // current one.
+ Restore string
+}
+
+// historyDay is the versions of one day in the viewer's zone.
+type historyDay struct {
+ Label string
+ Versions []versionRow
+}
+
+// versionRow is one version as a row of the panel.
+type versionRow struct {
+ Version
+ Href, Time string
+ Chosen bool
+}
+
+// panelFor draws a screen of history for page, chosen marking the
+// version on show (0 for none). now places Today and Yesterday.
+func panelFor(page PageView, list VersionList, chosen int64,
+ now time.Time) historyPanel {
+ base := "/p/" + page.Public + "/history"
+ panel := historyPanel{Close: page.Href, State: "list",
+ AgedOut: list.AgedOut}
+ if list.More {
+ panel.Older = base + "?older=" +
+ strconv.Itoa(list.Skip+len(list.Versions))
+ }
+ if chosen != 0 {
+ panel.State = "version"
+ if chosen != page.Revision {
+ panel.Restore = base + "/" + strconv.FormatInt(chosen, 10)
+ }
+ }
+ for _, version := range list.Versions {
+ label := dayLabel(version.At, now)
+ if len(panel.Days) == 0 || panel.Days[len(panel.Days)-1].Label !=
+ label {
+ panel.Days = append(panel.Days, historyDay{Label: label})
+ }
+ day := &panel.Days[len(panel.Days)-1]
+ day.Versions = append(day.Versions, versionRow{Version: version,
+ Href: base + "/" + strconv.FormatInt(version.Revision, 10),
+ Time: version.At.Format("15:04"),
+ Chosen: version.Revision == chosen})
+ }
+ return panel
+}
+
+// dayLabel is a day heading in the panel: Today, Yesterday, or the date.
+func dayLabel(at, now time.Time) string {
+ now = now.In(at.Location())
+ switch {
+ case sameDay(at, now):
+ return "Today"
+ case sameDay(at, now.AddDate(0, 0, -1)):
+ return "Yesterday"
+ case at.Year() == now.Year():
+ return at.Format("Monday 2 January")
+ }
+ return at.Format("Monday 2 January 2006")
+}
+
+// initial is the letter on a version's avatar.
+func initial(who string) string {
+ first, _ := utf8.DecodeRuneInString(who)
+ if first == utf8.RuneError {
+ return "?"
+ }
+ return string(unicode.ToUpper(first))
+}
+
+// historyKey carries the panel from the history route to show, which
+// draws it beside the page the route rendered.
+type historyKey struct{}
+
+func withHistory(request *http.Request, panel *historyPanel) *http.Request {
+ return request.WithContext(context.WithValue(request.Context(),
+ historyKey{}, panel))
+}
+
+func historyIn(request *http.Request) *historyPanel {
+ panel, _ := request.Context().Value(historyKey{}).(*historyPanel)
+ return panel
+}
+
+// wantsFragment is the panel as a fragment, under Docs' rule: only a
+// fetch (Sec-Fetch-Dest: empty) asking ?panel=1 gets it. A document
+// request, or one with no Sec-Fetch-* at all, gets the full page.
+func wantsFragment(request *http.Request) bool {
+ return request.URL.Query().Get("panel") == "1" &&
+ request.Header.Get("Sec-Fetch-Dest") == "empty"
+}
+
+// versionView is templates/revision.html's data.
+type versionView struct {
+ Page PageView
+ // Banner is "Bo's version, Friday 13 November at 16:15." and Note
+ // what the marks mean, or why there are none.
+ Banner, Note string
+ Title template.HTML
+ HTML template.HTML
+}
+
+// versionOf draws a chosen version: the banner, its title, and its text
+// with what changed from the version before marked. draw is the page's
+// own renderer, in the viewer's scope.
+func versionOf(page PageView, chosen Chosen,
+ draw func(string) (template.HTML, error)) (versionView, error) {
+ view := versionView{Page: page, Banner: possessive(chosen.Version.Who) +
+ " version, " + chosen.Version.At.Format("Monday 2 January at 15:04") +
+ ".", Title: versionTitle(page, chosen)}
+ var err error
+ switch {
+ case chosen.Before != nil:
+ view.Note = "Marked: what changed from the version before."
+ view.HTML, err = diffHTML(markup.Parse(chosen.Before.Body),
+ markup.Parse(chosen.Record.Body), draw)
+ case chosen.Verb == VerbCreated || chosen.Verb == VerbRestored:
+ view.Note = "The first version."
+ view.HTML, err = draw(chosen.Record.Body)
+ default:
+ view.Note = "The version before it has aged out, so nothing " +
+ "is marked."
+ view.HTML, err = draw(chosen.Record.Body)
+ }
+ return view, err
+}
+
+func possessive(who string) string {
+ if who == "You" {
+ return "Your"
+ }
+ return who + "'s"
+}
+
+// versionTitle is the version's title, the old one struck through when
+// this version renamed the page. Escaped here, as it is assembled here.
+func versionTitle(page PageView, chosen Chosen) template.HTML {
+ title := chosen.Record.Title
+ if page.Kind != KindPage || title == "" {
+ return template.HTML(html.EscapeString(page.Label))
+ }
+ escaped := html.EscapeString(title)
+ if chosen.Before == nil || chosen.Before.Title == "" ||
+ chosen.Before.Title == title {
+ return template.HTML(escaped)
+ }
+ return template.HTML(strings.Join([]string{"<del>" +
+ html.EscapeString(chosen.Before.Title) + "</del>",
+ "<ins>" + escaped + "</ins>"}, " "))
+}
diff --git a/internal/mapa/markers.go b/internal/mapa/markers.go
index 90aec89..19edd24 100644
--- a/internal/mapa/markers.go
+++ b/internal/mapa/markers.go
@@ -45,7 +45,8 @@ func (store *Store) MarkBlock(ctx context.Context, who string, pageID int64,
}
record.Body = markup.Replace(record.Body, blocks,
map[int]string{number: block.Source + " ^" + marker})
- return tx.commit(&page, record, actor, VerbEdited)
+ return tx.commit(&page, record, actor,
+ linkVerb(page, VerbMarked))
})
return marker, quiet(err)
}
diff --git a/internal/mapa/mentions.go b/internal/mapa/mentions.go
index c4f0e86..c2d7f7c 100644
--- a/internal/mapa/mentions.go
+++ b/internal/mapa/mentions.go
@@ -164,7 +164,8 @@ func (store *Store) LinkMention(ctx context.Context, who string, sourceID,
return errNoChange
}
record.Body = body
- return tx.commit(&source, record, actor, VerbEdited)
+ return tx.commit(&source, record, actor,
+ linkVerb(source, VerbRelinked))
}))
}
diff --git a/internal/mapa/models.go b/internal/mapa/models.go
index 891fd6c..72ac858 100644
--- a/internal/mapa/models.go
+++ b/internal/mapa/models.go
@@ -165,4 +165,21 @@ const (
// VerbPinsSet is a change to a person's pins. Its object is the
// member, never the page (level-up §8).
VerbPinsSet = "pins"
+
+ // VerbRelinked is "Update links" and "Link it", and VerbMarked is
+ // "Link to this block", on team pages only (level-up §8, N1): a
+ // private page logs VerbEdited for both, so the plaintext log says
+ // nothing about its links. Each replaces the edited row the same
+ // write would have logged; neither adds one.
+ VerbRelinked = "relinked"
+ VerbMarked = "marked"
)
+
+// linkVerb is the verb a link edit to page logs: verb on a team page,
+// VerbEdited on a private one (level-up §8).
+func linkVerb(page Page, verb string) string {
+ if page.Rung == RungTeam {
+ return verb
+ }
+ return VerbEdited
+}
diff --git a/internal/mapa/render.go b/internal/mapa/render.go
index a5d00bd..938151a 100644
--- a/internal/mapa/render.go
+++ b/internal/mapa/render.go
@@ -85,7 +85,7 @@ var shellOf = map[string]string{
"deleted": "shell", "restore": "shell", "day": "shell",
"scratch": "shell", "scratch_new": "shell", "share": "shell",
"settings": "shell", "search": "shell", "conflict": "shell",
- "history": "shell", "revision": "shell", "blocks": "shell",
+ "revision": "shell", "blocks": "shell",
}
func init() {
@@ -101,7 +101,8 @@ func init() {
page = template.Must(page.Parse(savestatus.Template()))
pages[name] = template.Must(page.ParseFS(appFS,
"templates/"+shell+".html", "templates/partials.html",
- "templates/frame.html", "templates/"+name+".html"))
+ "templates/frame.html", "templates/history.html",
+ "templates/"+name+".html"))
}
}
diff --git a/internal/mapa/shell.go b/internal/mapa/shell.go
index f2ebcc8..ccbbe6f 100644
--- a/internal/mapa/shell.go
+++ b/internal/mapa/shell.go
@@ -54,6 +54,9 @@ func (app *app) show(writer http.ResponseWriter, request *http.Request,
page.Account = app.account(request, address)
page.Theme = themeAttr(request)
page.name, page.Return = name, returnTarget(request)
+ if panel := historyIn(request); panel != nil {
+ page.Frame.History = panel
+ }
if err := app.buildFrame(request, &page); err != nil {
app.fail(writer, request, err)
return
diff --git a/internal/mapa/static/history.css b/internal/mapa/static/history.css
new file mode 100644
index 0000000..dd1fc09
--- /dev/null
+++ b/internal/mapa/static/history.css
@@ -0,0 +1,173 @@
+/* history.css: the History panel and a version on show (level-up §4.5).
+ *
+ * The panel is 360px at the inline end, full height under the bar. From
+ * 800px the page column makes room for it, as a third column of
+ * [mapa-app]; below 800px it is the whole screen for the list, and
+ * follows the version it shows. It replaces the Links panel while open.
+ * Tokens only, so Calma and light/dark apply.
+ */
+
+@media (min-width: 800px) {
+ [mapa-app][data-history] {
+ grid-template-columns: var(--mapa-side-w) minmax(0, 1fr) 360px;
+ }
+}
+[mapa-app][data-history] #mapa-links { display: none; }
+
+[mapa-history] {
+ box-sizing: border-box;
+ position: sticky;
+ inset-block-start: var(--mapa-bar-h);
+ block-size: calc(100dvh - var(--mapa-bar-h));
+ display: flex;
+ flex-direction: column;
+ min-inline-size: 0;
+ background: var(--rst-surface);
+ border-inline-start: 1px solid var(--rst-line);
+ box-shadow: -24px 0 48px -32px light-dark(rgb(20 24 33 / 0.35), rgb(0 0 0 / 0.7));
+}
+[mapa-history-head] {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ padding: 16px 12px 6px 20px;
+}
+[mapa-history-head] h2 { margin: 0; font-size: 16px; font-weight: 680; }
+[mapa-history-head] h2:focus { outline: none; }
+[mapa-history-close] {
+ display: inline-grid;
+ place-items: center;
+ inline-size: 32px;
+ block-size: 32px;
+ border-radius: 8px;
+ color: var(--rst-text-muted);
+}
+[mapa-history-close]:hover { background: var(--rst-surface-2); color: var(--rst-text); }
+[mapa-history-close]:focus-visible { outline: 2px solid var(--rst-accent); outline-offset: -2px; }
+[mapa-history-close] svg { inline-size: 18px; block-size: 18px; }
+[mapa-history-lede] {
+ margin: 0 20px 10px;
+ color: var(--rst-text-muted);
+ font-size: 12.5px;
+ line-height: 1.45;
+}
+[mapa-history-list] { flex: 1; overflow: auto; padding: 0 10px 12px; }
+[mapa-history-list] h3 {
+ margin: 12px 10px 4px;
+ color: var(--rst-text-faint, var(--rst-text-muted));
+ font-size: 11.5px;
+ font-weight: 600;
+}
+[mapa-history-list] ul { margin: 0; padding: 0; list-style: none; }
+[mapa-ver] {
+ display: grid;
+ grid-template-columns: 28px minmax(0, 1fr) auto;
+ column-gap: 10px;
+ align-items: center;
+ padding: 8px 10px;
+ border-radius: 10px;
+ color: inherit;
+ font-size: 13px;
+ text-decoration: none;
+}
+[mapa-ver]:hover { background: var(--rst-surface-2); }
+[mapa-ver]:focus-visible { outline: 2px solid var(--rst-accent); outline-offset: -2px; }
+[mapa-ver][aria-current] { background: var(--rst-accent-soft); }
+[mapa-ver-main] { min-inline-size: 0; }
+[mapa-ver] b { font-weight: 650; }
+[mapa-ver-now] { color: var(--rst-text-muted); font-size: 11.5px; font-weight: 600; }
+[mapa-ver] small {
+ display: block;
+ overflow: hidden;
+ color: var(--rst-text-muted);
+ font-size: 12px;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+[mapa-ver] time {
+ align-self: start;
+ padding-block-start: 2px;
+ color: var(--rst-text-muted);
+ font-size: 12px;
+ font-variant-numeric: tabular-nums;
+}
+[mapa-ava] {
+ display: inline-grid;
+ place-items: center;
+ inline-size: 28px;
+ block-size: 28px;
+ border-radius: 50%;
+ background: var(--rst-surface-2);
+ color: var(--rst-text-muted);
+ font: 700 11px/1 var(--rst-font);
+}
+[mapa-history-note] { margin: 14px 10px 4px; color: var(--rst-text-muted); font-size: 12.5px; }
+[mapa-history-more] { margin: 10px 10px 0; }
+[mapa-history-foot] {
+ display: flex;
+ flex-wrap: wrap;
+ justify-content: flex-end;
+ gap: 8px;
+ padding: 12px 16px;
+ border-block-start: 1px solid var(--rst-line);
+}
+[mapa-history-foot] form { display: contents; }
+[mapa-history-foot] svg { inline-size: 16px; block-size: 16px; }
+
+/* Below 800px: the list is the screen; a version shows first, and the
+ panel follows it. */
+@media (max-width: 799.98px) {
+ [mapa-history] {
+ position: static;
+ block-size: auto;
+ border-inline-start: 0;
+ box-shadow: none;
+ }
+ [mapa-app][data-history="list"] [mapa-main] { display: none; }
+ [mapa-app][data-history="list"] [mapa-history] { min-block-size: calc(100dvh - var(--mapa-bar-h)); }
+ [mapa-app][data-history="version"] [mapa-history] { border-block-start: 1px solid var(--rst-line); }
+ [mapa-history-list] { overflow: visible; }
+}
+
+/* ── A version on show: the banner, then the page as it was, with what
+ changed marked. ── */
+[mapa-version-bar] {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: 10px 14px;
+ margin: 0 0 28px;
+ padding: 10px 12px 10px 14px;
+ border: 1px solid var(--rst-line);
+ border-radius: 12px;
+ background: var(--rst-surface-2);
+ font-size: 13px;
+}
+[mapa-version-bar] > span { flex: 1 1 14rem; color: var(--rst-text-muted); }
+[mapa-version-bar] > span b { color: var(--rst-text); }
+[mapa-version] ins,
+h1[mapa-title] ins {
+ border-radius: 3px;
+ background: var(--rst-tone-positive-bg);
+ color: var(--rst-text);
+ text-decoration: underline 2px;
+ text-decoration-color: var(--rst-tone-positive-fg);
+ text-underline-offset: 3px;
+}
+[mapa-version] del,
+h1[mapa-title] del {
+ border-radius: 3px;
+ background: var(--rst-tone-negative-bg);
+ color: var(--rst-text-muted);
+ text-decoration: line-through 1.5px;
+ text-decoration-color: var(--rst-tone-negative-fg);
+}
+[mapa-diff] > ul, [mapa-diff] > ol { margin-block: 0; }
+[mapa-diff-level="1"] { margin-inline-start: 1.5em; }
+[mapa-diff-level="2"] { margin-inline-start: 3em; }
+[mapa-diff-level="3"] { margin-inline-start: 4.5em; }
+[mapa-diff-link] {
+ padding: 0 4px;
+ border: 1px solid var(--rst-line);
+ border-radius: 5px;
+}
diff --git a/internal/mapa/static/history.js b/internal/mapa/static/history.js
new file mode 100644
index 0000000..ba12a13
--- /dev/null
+++ b/internal/mapa/static/history.js
@@ -0,0 +1,120 @@
+// history.js: the History panel in place (level-up spec §4.5). Without
+// it, History is the page /p/{id}/history, the panel drawn beside the
+// page, and every control in it is a link or a form. This only adds:
+// - History in the bar (or the Page menu) fetches the panel with
+// ?panel=1 and shows it beside the page, focus in it;
+// - its close button and Esc take it away and give focus back to what
+// opened it (History, or the menu it was chosen from); "Show older" pages through it in place;
+// - on the history routes, where the server drew the panel, Esc goes
+// back to the page, as the close button does.
+(function () {
+ "use strict";
+
+ var opener = null;
+
+ function frame() { return document.querySelector("[mapa-app]"); }
+ function panel() { return document.querySelector("aside[mapa-history]"); }
+
+ // isHistoryLink is a link to a page's History (/p/{id}/history, nothing
+ // more), from a screen where the server has not drawn the panel
+ // already: the page itself, or a daily note at /d/{date}.
+ function isHistoryLink(link) {
+ if (!link || link.origin !== location.origin || link.search !== "") return false;
+ var drawn = panel();
+ if (drawn && !drawn.hasAttribute("data-mapa-in-place")) return false;
+ return /^\/p\/[^/]+\/history$/.test(link.pathname);
+ }
+
+ function historyAction() {
+ var links = document.querySelectorAll("[estilo-bar-actions] a[href]");
+ for (var index = 0; index < links.length; index++) {
+ if (isHistoryLink(links[index])) return links[index];
+ }
+ return null;
+ }
+
+ function fragmentURL(href) {
+ var url = new URL(href, location.href);
+ url.searchParams.set("panel", "1");
+ return url.toString();
+ }
+
+ // show fetches the panel at href and puts it beside the page. A reply
+ // that is not the panel (a full page, an error) is left to the browser.
+ function show(href) {
+ fetch(fragmentURL(href), {
+ credentials: "same-origin",
+ headers: { "Accept": "text/html" }
+ }).then(function (response) {
+ if (!response.ok) throw new Error("history " + response.status);
+ return response.text();
+ }).then(function (markup) {
+ var holder = document.createElement("template");
+ holder.innerHTML = markup;
+ var aside = holder.content.querySelector("aside[mapa-history]");
+ if (!aside) throw new Error("no panel");
+ aside.setAttribute("data-mapa-in-place", "");
+ var old = panel();
+ if (old) old.replaceWith(aside); else frame().appendChild(aside);
+ frame().setAttribute("data-history", "list");
+ aside.querySelector("#mapa-history-title").focus();
+ }).catch(function () { location.href = href; });
+ }
+
+ function close() {
+ var aside = panel();
+ if (aside) aside.remove();
+ frame().removeAttribute("data-history");
+ var back = opener || historyAction();
+ opener = null;
+ if (back) back.focus();
+ }
+
+ function closeMenus(from) {
+ var menu = from.closest("details[open]");
+ if (menu) menu.removeAttribute("open");
+ }
+
+ function plainClick(event) {
+ return event.button === 0 && !event.metaKey && !event.ctrlKey &&
+ !event.shiftKey && !event.altKey;
+ }
+
+ function clicked(event) {
+ if (!plainClick(event)) return;
+ var link = event.target.closest("a[href]");
+ if (!link) return;
+ var aside = panel();
+ var inPlace = aside && aside.hasAttribute("data-mapa-in-place") &&
+ aside.contains(link);
+ if (inPlace && link.hasAttribute("data-mapa-history-close")) {
+ event.preventDefault();
+ close();
+ } else if (inPlace && link.hasAttribute("data-mapa-history-older")) {
+ event.preventDefault();
+ show(link.href);
+ } else if (isHistoryLink(link)) {
+ event.preventDefault();
+ var menu = link.closest("details");
+ opener = menu ? menu.querySelector("summary") : link;
+ closeMenus(link);
+ show(link.href);
+ }
+ }
+
+ function keyed(event) {
+ var aside = panel();
+ if (event.key !== "Escape" || event.defaultPrevented || !aside) return;
+ if (document.querySelector("details[open], dialog[open]")) return;
+ event.preventDefault();
+ if (aside.hasAttribute("data-mapa-in-place")) {
+ close();
+ return;
+ }
+ var back = aside.querySelector("[data-mapa-history-close]");
+ if (back) location.href = back.href;
+ }
+
+ document.addEventListener("click", clicked);
+ document.addEventListener("keydown", keyed);
+})();
diff --git a/internal/mapa/templates/history.html b/internal/mapa/templates/history.html
index 40476b8..4842a9c 100644
--- a/internal/mapa/templates/history.html
+++ b/internal/mapa/templates/history.html
@@ -1,7 +1,39 @@
-{{define "content"}}{{$page := .Data.Page}}
-{{template "back-nav" dict "Href" $page.Href "Label" $page.Label}}
-{{template "page-header" dict "Title" "History" "Sub" "Every saved version from the last 90 days. Restoring one saves it as the newest; nothing is lost."}}
-<ul mapa-list>
-{{range .Data.Revisions}}<li><a href="/p/{{$page.Public}}/history/{{.Revision}}"><time datetime="{{.At.Format "2006-01-02T15:04:05Z07:00"}}" title="{{.At.Format "2 January 2006 15:04"}}">{{.At.Format "2 Jan 2006, 15:04"}}</time></a> <span mapa-meta>{{.Actor}}{{if .Current}} · current{{end}}</span></li>
-{{end}}</ul>
-{{end}}
+{{/* mapa-history: the History panel (level-up §4.5), parsed into every
+ page. On /p/{id}/history it is drawn beside the page; history.js
+ fetches the same markup with ?panel=1 and shows it in place. Close
+ and Back to current are links to the page, so both work with
+ scripts off; Restore is the existing POST, held by busy.js.
+ Data: historyPanel. */}}
+{{define "mapa-history"}}<aside mapa-history id="mapa-history" aria-labelledby="mapa-history-title" data-state="{{.State}}">
+ <div mapa-history-head>
+ <h2 id="mapa-history-title" tabindex="-1">History</h2>
+ <a mapa-history-close href="{{.Close}}" aria-label="Close history" data-mapa-history-close>{{icon "x"}}</a>
+ </div>
+ <p mapa-history-lede>Every saved version from the last 90 days. Restoring one saves it as the newest; nothing is lost.</p>
+ <div mapa-history-list>
+ {{- range .Days}}
+ <h3>{{.Label}}</h3>
+ <ul>
+ {{- range .Versions}}
+ <li><a mapa-ver href="{{.Href}}"{{if .Chosen}} aria-current="true"{{end}}><span mapa-ava aria-hidden="true">{{.Initial}}</span><span mapa-ver-main><b>{{.Who}}</b>{{if .Current}} <span mapa-ver-now>· current</span>{{end}}<small mapa-ver-summary>{{.Summary}}</small></span><time datetime="{{.At.Format "2006-01-02T15:04:05Z07:00"}}" title="{{.At.Format "2 January 2006 15:04"}}">{{.Time}}</time></a></li>
+ {{- end}}
+ </ul>
+ {{- else}}
+ <p mapa-history-note>No saved versions in the last 90 days.</p>
+ {{- end}}
+ {{- with .Older}}
+ <p mapa-history-more><a rst-btn href="{{.}}" data-mapa-history-older>Show older</a></p>
+ {{- end}}
+ {{- if .AgedOut}}
+ <p mapa-history-note>Earlier history has aged out.</p>
+ {{- end}}
+ </div>
+ {{- if eq .State "version"}}
+ <div mapa-history-foot>
+ <a rst-btn href="{{.Close}}">Back to current</a>
+ {{- with .Restore}}
+ <form method="post" action="{{.}}"><button rst-btn="primary" type="submit">{{icon "rotate-ccw"}}Restore this version</button></form>
+ {{- end}}
+ </div>
+ {{- end}}
+</aside>{{end}}
diff --git a/internal/mapa/templates/revision.html b/internal/mapa/templates/revision.html
index f725886..a6353f0 100644
--- a/internal/mapa/templates/revision.html
+++ b/internal/mapa/templates/revision.html
@@ -1,9 +1,10 @@
-{{define "content"}}{{$page := .Data.Page}}
-{{template "back-nav" dict "Href" (printf "/p/%s/history" $page.Public) "Label" "History"}}
-<h1>{{$page.Label}}</h1>
-<p mapa-meta>{{if .Data.Current}}This is the current version.{{else}}An earlier version.{{end}}</p>
-<article mapa-body>{{.Data.HTML}}</article>
-{{if not .Data.Current}}
-<form method="post" action="{{.Data.Action}}"><div rst-form-foot><a rst-btn href="/p/{{$page.Public}}/history">Back</a><button rst-btn="primary" type="submit">Restore this version</button></div></form>
-{{end}}
+{{define "content"}}{{$d := .Data}}
+<div mapa-version-bar role="note">
+<span><b>{{$d.Banner}}</b> {{$d.Note}}</span>
+<a rst-btn href="{{$d.Page.Href}}">Back to current</a>
+</div>
+<header mapa-page-head><h1 mapa-title>{{$d.Title}}</h1></header>
+<article mapa-body mapa-version>
+{{if $d.HTML}}{{$d.HTML}}{{else}}<p mapa-empty>This version is empty.</p>{{end}}
+</article>
{{end}}
diff --git a/internal/mapa/templates/shell.html b/internal/mapa/templates/shell.html
index c11a6ab..9bfe97e 100644
--- a/internal/mapa/templates/shell.html
+++ b/internal/mapa/templates/shell.html
@@ -19,6 +19,7 @@
<link rel="stylesheet" href="{{asset "static/frame.css"}}">
<link rel="stylesheet" href="{{asset "static/links.css"}}">
<link rel="stylesheet" href="{{asset "static/palette.css"}}">
+<link rel="stylesheet" href="{{asset "static/history.css"}}">
<script defer src="{{asset "static/rastrillo.js"}}"></script>
<script defer src="{{asset "static/busy.js"}}"></script>
<script defer src="{{asset "static/chrome.js"}}"></script>
@@ -27,18 +28,20 @@
it. */}}
<script defer src="{{asset "static/mapa.js"}}"></script>
<script defer src="{{asset "static/links.js"}}"></script>
+<script defer src="{{asset "static/history.js"}}"></script>
{{block "head" .}}{{end}}
</head>
<body data-zone="{{with .Viewer.TimeZone}}{{.String}}{{end}}">
<a rst-skip href="#main">Skip to content</a>
{{template "estilo-bar" .Frame.Bar}}
-<div mapa-app{{with .Frame.Side.State}} data-side="{{.}}"{{end}}{{with .Frame.Panel}} data-links="{{.}}"{{end}}>
+<div mapa-app{{with .Frame.Side.State}} data-side="{{.}}"{{end}}{{with .Frame.Panel}} data-links="{{.}}"{{end}}{{with .Frame.History}} data-history="{{.State}}"{{end}}>
{{template "mapa-side" .Frame.Side}}
<main mapa-main id="main">
<div mapa-doc rst-page>
{{template "content" .}}
</div>
</main>
+{{with .Frame.History}}{{template "mapa-history" .}}{{end}}
</div>
{{template "mapa-keys"}}
</body>
diff --git a/internal/mapa/verbs.go b/internal/mapa/verbs.go
index 29e6614..ce6da48 100644
--- a/internal/mapa/verbs.go
+++ b/internal/mapa/verbs.go
@@ -220,5 +220,6 @@ func (tx *Tx) retarget(actor, pageID int64, matches func(string) bool,
return 0, nil
}
record.Body = body
- return 1, tx.commit(&page, record, actor, VerbEdited)
+ return 1, tx.commit(&page, record, actor,
+ linkVerb(page, VerbRelinked))
}
diff --git a/internal/mapa/versions.go b/internal/mapa/versions.go
new file mode 100644
index 0000000..f3f29e7
--- /dev/null
+++ b/internal/mapa/versions.go
@@ -0,0 +1,353 @@
+package mapa
+
+import (
+ "context"
+ "strconv"
+ "strings"
+ "time"
+
+ "amadan.net/oficina/mapa/internal/mapa/markup"
+ "amadan.net/oficina/mapa/internal/mapa/seal"
+)
+
+// The History panel's list (level-up spec §4.5): a page's versions in
+// the 90-day window, newest first, each with who made it, when, and a
+// one-line summary. The summary's verb is the revision's own event row;
+// only an edit is diffed, and only against the revision before it in the
+// window, never one the window has dropped.
+
+// HistoryPage is how many versions one screen of history summarises.
+// "Show older" pages through the rest.
+const HistoryPage = 30
+
+// Version is one entry in a page's history.
+type Version struct {
+ Revision int64
+ // At is in the viewer's zone.
+ At time.Time
+ // Who is "You" for the viewer, else the address's local part, and
+ // Initial the letter on their avatar.
+ Who, Initial string
+ Summary string
+ // Current marks the page's current revision.
+ Current bool
+}
+
+// VersionList is one screen of a page's history, newest first.
+type VersionList struct {
+ Versions []Version
+ // Skip is how many newer versions come before these.
+ Skip int
+ // More reports older versions in the window after these.
+ More bool
+ // AgedOut reports, on the last screen, that the window has dropped
+ // the page's earlier revisions.
+ AgedOut bool
+}
+
+// revisionRow is a revision's plaintext row, without its record.
+type revisionRow struct {
+ Revision int64
+ At time.Time
+ ActorID int64
+}
+
+// pageHistory is one page's revisions in the window, as one viewer reads
+// them. Records are opened when a summary needs them, once each.
+type pageHistory struct {
+ store *Store
+ ctx context.Context
+ viewer Viewer
+ page Page
+ cutoff time.Time
+ rows []revisionRow
+ records map[int64]Record
+ verbs map[int64]string
+ names map[int64]string
+}
+
+// History is one screen of a page's versions, from skip on, if the
+// viewer may open the page. It reads; it never writes.
+func (store *Store) History(ctx context.Context, viewer Viewer,
+ pageID int64, skip int) (VersionList, error) {
+ history, err := store.loadHistory(ctx, viewer, pageID)
+ if err != nil {
+ return VersionList{}, err
+ }
+ return history.list(skip)
+}
+
+// loadHistory reads the page's revision rows in the window, newest
+// first. Ties in time keep the order they were written in.
+func (store *Store) loadHistory(ctx context.Context, viewer Viewer,
+ pageID int64) (*pageHistory, error) {
+ page, err := store.readable(ctx, viewer, pageID)
+ if err != nil {
+ return nil, err
+ }
+ history := &pageHistory{store: store, ctx: ctx, viewer: viewer,
+ page: page, cutoff: store.now().UTC().Add(-HistoryWindow),
+ records: map[int64]Record{}, verbs: map[int64]string{},
+ names: map[int64]string{}}
+ err = store.database.WithContext(ctx).Model(&Revision{}).
+ Select("revision", "at", "actor_id").
+ Where("page_id = ? AND at > ?", pageID, history.cutoff).
+ Order("at DESC, rowid DESC").Scan(&history.rows).Error
+ return history, err
+}
+
+func (history *pageHistory) list(skip int) (VersionList, error) {
+ skip = max(0, min(skip, len(history.rows)))
+ end := min(skip+HistoryPage, len(history.rows))
+ list := VersionList{Skip: skip, More: end < len(history.rows)}
+ if err := history.loadVerbs(skip, end); err != nil {
+ return list, err
+ }
+ for index := skip; index < end; index++ {
+ version, err := history.version(index)
+ if err != nil {
+ return list, err
+ }
+ list.Versions = append(list.Versions, version)
+ }
+ list.AgedOut = !list.More && history.agedOut()
+ return list, nil
+}
+
+// agedOut reports that the page is older than the window, so its
+// earliest revisions have been (or are about to be) swept.
+func (history *pageHistory) agedOut() bool {
+ return !history.page.CreatedAt.After(history.cutoff)
+}
+
+// find is a revision's place in the rows, or -1.
+func (history *pageHistory) find(revision int64) int {
+ for index, row := range history.rows {
+ if row.Revision == revision {
+ return index
+ }
+ }
+ return -1
+}
+
+// loadVerbs reads the verb of each revision in rows[start:end]: the
+// event that minted it, which is the first event naming it (a delete or
+// a freed alias names the revision it leaves, after the fact).
+func (history *pageHistory) loadVerbs(start, end int) error {
+ if start >= end {
+ return nil
+ }
+ revisions := make([]int64, 0, end-start)
+ for _, row := range history.rows[start:end] {
+ revisions = append(revisions, row.Revision)
+ }
+ var events []Event
+ err := history.store.database.WithContext(history.ctx).
+ Select("revision", "verb").Where("object_kind = ? AND "+
+ "object_id = ? AND revision IN ?", ObjectPage, history.page.ID,
+ revisions).Order("id").Find(&events).Error
+ for _, event := range events {
+ if _, seen := history.verbs[event.Revision]; !seen {
+ history.verbs[event.Revision] = event.Verb
+ }
+ }
+ return err
+}
+
+func (history *pageHistory) version(index int) (Version, error) {
+ row := history.rows[index]
+ summary, err := history.summary(index)
+ if err != nil {
+ return Version{}, err
+ }
+ name, err := history.name(row.ActorID)
+ if err != nil {
+ return Version{}, err
+ }
+ who := name
+ if row.ActorID == history.viewer.MemberID {
+ who = "You"
+ }
+ return Version{Revision: row.Revision, At: history.inZone(row.At),
+ Who: who, Initial: initial(name), Summary: summary,
+ Current: row.Revision == history.page.Revision}, nil
+}
+
+func (history *pageHistory) inZone(at time.Time) time.Time {
+ if history.viewer.TimeZone != nil {
+ return at.In(history.viewer.TimeZone)
+ }
+ return at
+}
+
+// name is the actor's local part.
+func (history *pageHistory) name(actor int64) (string, error) {
+ if actor == history.viewer.MemberID {
+ return personName(history.viewer.Address), nil
+ }
+ if name, ok := history.names[actor]; ok {
+ return name, nil
+ }
+ address, err := history.store.MemberAddress(history.ctx, actor)
+ history.names[actor] = personName(address)
+ return history.names[actor], err
+}
+
+// record is the text of rows[index], opened once.
+func (history *pageHistory) record(index int) (Record, error) {
+ revision := history.rows[index].Revision
+ if record, ok := history.records[revision]; ok {
+ return record, nil
+ }
+ var row Revision
+ err := history.store.database.WithContext(history.ctx).
+ Where("page_id = ? AND revision = ?", history.page.ID, revision).
+ First(&row).Error
+ if err != nil {
+ return Record{}, err
+ }
+ record, err := history.store.openRecord(seal.PurposeRecord,
+ row.SealedRecord)
+ history.records[revision] = record
+ return record, err
+}
+
+// summary is rows[index]'s one line, from its event verb (§4.5).
+func (history *pageHistory) summary(index int) (string, error) {
+ switch history.verbs[history.rows[index].Revision] {
+ case VerbCreated:
+ return "Created this page", nil
+ case VerbRestored:
+ return "Brought back after it was deleted", nil
+ case VerbRelinked:
+ return "Updated links", nil
+ case VerbMarked:
+ return "Made a block linkable", nil
+ case VerbRenamed:
+ return history.renamed(index)
+ case VerbReverted:
+ return history.reverted(index)
+ }
+ return history.edited(index)
+}
+
+// renamed names the old title, or the new one when the revision before
+// has aged out of the window.
+func (history *pageHistory) renamed(index int) (string, error) {
+ record, err := history.record(index)
+ if err != nil {
+ return "", err
+ }
+ if index+1 < len(history.rows) {
+ before, err := history.record(index + 1)
+ if err != nil {
+ return "", err
+ }
+ if before.Title != "" && before.Title != record.Title {
+ return "Renamed from " + before.Title, nil
+ }
+ }
+ return "Renamed to " + record.Title, nil
+}
+
+// reverted names the version it restored: the newest one before it in
+// the window with the same text. Restore keeps no pointer to its source,
+// so with none in the window it cannot be named.
+func (history *pageHistory) reverted(index int) (string, error) {
+ record, err := history.record(index)
+ if err != nil {
+ return "", err
+ }
+ for older := index + 1; older < len(history.rows); older++ {
+ candidate, err := history.record(older)
+ if err != nil {
+ return "", err
+ }
+ if candidate.Body == record.Body {
+ return "Restored the version from " + versionDay(
+ history.inZone(history.rows[older].At),
+ history.store.now()), nil
+ }
+ }
+ return "Restored an earlier version", nil
+}
+
+// versionDay is a version's moment in a summary: "13 November at
+// 16:15", with the year when it is not this one.
+func versionDay(at, now time.Time) string {
+ if at.Year() != now.In(at.Location()).Year() {
+ return at.Format("2 January 2006 at 15:04")
+ }
+ return at.Format("2 January at 15:04")
+}
+
+// edited is the diff's summary against the revision before, or plain
+// "Edited" when the window holds none.
+func (history *pageHistory) edited(index int) (string, error) {
+ if index+1 >= len(history.rows) {
+ return "Edited", nil
+ }
+ before, err := history.record(index + 1)
+ if err != nil {
+ return "", err
+ }
+ record, err := history.record(index)
+ if err != nil {
+ return "", err
+ }
+ return editSummary(before.Body, record.Body), nil
+}
+
+// editSummary is one line for an edit: "Added 2 blocks", "Removed a
+// block", or "Edited" and the nearest heading above the first change.
+func editSummary(old, body string) string {
+ from, to := markup.Parse(old), markup.Parse(body)
+ counts := map[string]int{}
+ var first *blockChange
+ for _, change := range diffBlocks(from, to) {
+ if change.Kind == blockSame {
+ continue
+ }
+ counts[change.Kind]++
+ if first == nil || change.At < first.At || (change.At ==
+ first.At && first.Kind == blockRemoved) {
+ first = &change
+ }
+ }
+ switch {
+ case first == nil:
+ return "Edited"
+ case counts[blockChanged]+counts[blockRemoved] == 0:
+ return blocksCounted("Added", counts[blockAdded])
+ case counts[blockChanged]+counts[blockAdded] == 0:
+ return blocksCounted("Removed", counts[blockRemoved])
+ }
+ if heading := headingAbove(to, *first); heading != "" {
+ return "Edited " + heading
+ }
+ return "Edited"
+}
+
+func blocksCounted(verb string, count int) string {
+ if count == 1 {
+ return verb + " a block"
+ }
+ return verb + " " + strconv.Itoa(count) + " blocks"
+}
+
+// headingAbove is the text of the nearest heading at or above a change:
+// a changed or added heading names itself; a removal looks above where
+// it was. The first change is the earliest in the page, an addition
+// before a removal in the same place.
+func headingAbove(blocks []markup.Block, change blockChange) string {
+ from := change.At
+ if change.Kind == blockRemoved {
+ from--
+ }
+ for index := min(from, len(blocks)-1); index >= 0; index-- {
+ if blocks[index].Kind == markup.Heading {
+ return strings.TrimSpace(markup.Words(blocks[index]))
+ }
+ }
+ return ""
+}
diff --git a/internal/mapatest/browser_history_test.go b/internal/mapatest/browser_history_test.go
new file mode 100644
index 0000000..bde8ecb
--- /dev/null
+++ b/internal/mapatest/browser_history_test.go
@@ -0,0 +1,67 @@
+//go:build browser
+
+package mapatest
+
+import (
+ "strings"
+ "testing"
+
+ "amadan.net/rastrillo/rastrillo/harness"
+ "github.com/chromedp/chromedp"
+ "github.com/chromedp/chromedp/kb"
+)
+
+// The History walk (level-up §4.5, L8): from the page, History, a
+// version under its banner, and Restore, with scripts off as with them.
+
+// The Page menu and its History: the bar's own History action is
+// hidden at the walk's width, below 800px, as on a phone.
+const (
+ pageMenu = `#mapa-menu-page > summary`
+ pageHistory = `#mapa-menu-page a[href$="/history"]`
+)
+
+// historyAndRestore opens History as a page, chooses the oldest
+// version, sees it under its banner, and restores it.
+func historyAndRestore(t *testing.T, rig *harness.Rig) {
+ path := strings.TrimPrefix(read(t, rig, chromedp.Location()),
+ rig.Origin)
+ drive(t, rig, chromedp.Navigate(rig.Origin+path+"/history"))
+ rig.Screen("aside[mapa-history] a[mapa-ver]", "history")
+ oldest := `aside[mapa-history] li:last-child a[mapa-ver]`
+ if !strings.Contains(text(t, rig, oldest), "Created this page") {
+ t.Fatalf("the oldest version reads %q", text(t, rig, oldest))
+ }
+ drive(t, rig, press(oldest))
+ rig.Screen("[mapa-version-bar]", "a version")
+ if !strings.Contains(text(t, rig, "[mapa-version-bar]"), "version,") {
+ t.Fatal("the version has no banner")
+ }
+ drive(t, rig, press(`[mapa-history-foot] button[rst-btn~="primary"]`),
+ chromedp.WaitNotPresent("[mapa-version-bar]"))
+ rig.Screen("header[mapa-page-head]", "restored")
+ if !strings.Contains(text(t, rig, "main"), "Restored that version") {
+ t.Fatal("Restore did not say it restored the version")
+ }
+}
+
+// historyInPlace opens History from the Page menu in place, and Esc
+// closes it with focus back on the menu it came from.
+func historyInPlace(t *testing.T, rig *harness.Rig) {
+ drive(t, rig, press(pageMenu), chromedp.WaitVisible(pageHistory),
+ press(pageHistory))
+ rig.Screen("aside[mapa-history][data-mapa-in-place] a[mapa-ver]",
+ "history in place")
+ focused := read(t, rig, chromedp.Evaluate[string](
+ `document.activeElement.id`))
+ if focused != "mapa-history-title" {
+ t.Fatalf("focus is on %q, not the panel", focused)
+ }
+ drive(t, rig, chromedp.KeyEvent(kb.Escape),
+ chromedp.WaitNotPresent("aside[mapa-history]"))
+ back := read(t, rig, chromedp.Evaluate[bool](
+ `document.activeElement.matches('`+pageMenu+`')`))
+ if !back {
+ t.Fatal("closing History did not give focus back to its menu")
+ }
+}
diff --git a/internal/mapatest/browser_test.go b/internal/mapatest/browser_test.go
index cf5349b..56ce038 100644
--- a/internal/mapatest/browser_test.go
+++ b/internal/mapatest/browser_test.go
@@ -160,6 +160,10 @@ func walk(t *testing.T, rig *harness.Rig, store *mapa.Store, live bool) {
t.Fatal("the new page does not show today's note linking to it")
}
saveAndConflict(t, rig, store, live)
+ if live {
+ historyInPlace(t, rig)
+ }
+ historyAndRestore(t, rig)
}
// searchByPage is ⌘K without scripts: GET /search?q= as a full page,
@@ -235,11 +239,11 @@ func writeAsBo(t *testing.T, store *mapa.Store, path string) {
t.Fatal(err)
}
viewer, _ := store.Viewer(ctx, Bo, nil)
- history, err := store.History(ctx, viewer, pageID)
- if err != nil || len(history) == 0 {
+ history, err := store.History(ctx, viewer, pageID, 0)
+ if err != nil || len(history.Versions) == 0 {
t.Fatalf("history: %v", err)
}
- if _, err := store.Commit(ctx, Bo, pageID, history[0].Revision,
+ if _, err := store.Commit(ctx, Bo, pageID, history.Versions[0].Revision,
"Acme, as Bo has it."); err != nil {
t.Fatal(err)
}
diff --git a/internal/mapatest/history_panel_test.go b/internal/mapatest/history_panel_test.go
new file mode 100644
index 0000000..2f32a64
--- /dev/null
+++ b/internal/mapatest/history_panel_test.go
@@ -0,0 +1,265 @@
+package mapatest
+
+import (
+ "crypto/sha256"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "regexp"
+ "strings"
+ "testing"
+ "time"
+)
+
+// Level-up §4.5, History: the summaries from each revision's event verb,
+// "Earlier history has aged out", the fragment rule, scope (L6, gate 1)
+// and nothing written by a GET (L7).
+
+// summaries is each version's one line in a page's history, newest
+// first, as the viewer reads it.
+func (rig *rig) summaries(t *testing.T, who, path string) []string {
+ t.Helper()
+ panel := rig.page(t, who, path+"/history")
+ var lines []string
+ for _, part := range strings.Split(panel, "<small mapa-ver-summary>")[1:] {
+ line, _, _ := strings.Cut(part, "</small>")
+ lines = append(lines, line)
+ }
+ return lines
+}
+
+func expectSummaries(t *testing.T, got []string, want ...string) {
+ t.Helper()
+ if strings.Join(got, " | ") != strings.Join(want, " | ") {
+ t.Fatalf("summaries:\n got %q\n want %q", got, want)
+ }
+}
+
+func TestHistorySummarisesEachVerb(t *testing.T) {
+ rig := newRig(t)
+ moving := rig.clocked(t)
+ step := func() { moving.now = moving.now.Add(time.Hour) }
+ acme := rig.createPage(t, Ana, "Acme", "Intro.\n\n## Contacts\n\n"+
+ "Ana, budget.")
+ first := revisionOf(t, rig, acme)
+ notes := rig.createPage(t, Ana, "Notes", "See [[Acme]].")
+ edit := func(who, body string) {
+ step()
+ rig.post(t, who, acme, url.Values{"revision": {revisionOf(t, rig,
+ acme)}, "body": {body}})
+ }
+ edit(Bo, "Intro.\n\n## Contacts\n\nAna, budget. Weekly call.")
+ edit(Bo, "Intro.\n\n## Contacts\n\nAna, budget. Weekly call.\n\nTom.")
+ edit(Bo, "## Contacts\n\nAna, budget. Weekly call.\n\nTom.")
+ step()
+ rig.post(t, Bo, acme+"/rename", url.Values{"title": {"Acme Ltd"}})
+ step()
+ rig.post(t, Ana, acme+"/links", nil)
+ step()
+ rig.post(t, Ana, acme+"/blocks", url.Values{"block": {"1"}})
+ step()
+ rig.post(t, Ana, acme+"/history/"+first, nil)
+ expectSummaries(t, rig.summaries(t, Ana, acme),
+ "Restored the version from 12 November at 09:00",
+ "Made a block linkable", "Renamed from Acme", "Removed a block",
+ "Added a block", "Edited Contacts", "Created this page")
+ expectSummaries(t, rig.summaries(t, Ana, notes), "Updated links",
+ "Created this page")
+ panel := rig.page(t, Ana, acme+"/history")
+ if !strings.Contains(panel, "<b>bo</b>") ||
+ !strings.Contains(panel, "<b>You</b>") ||
+ !strings.Contains(panel, "<h3>Today</h3>") {
+ t.Fatal("authors or days are not shown as the viewer reads them")
+ }
+ rig.post(t, Ana, notes+"/delete", nil)
+ back := rig.post(t, Ana, strings.Replace(notes, "/p/", "/deleted/", 1),
+ nil).Header().Get("Location")
+ back, _, _ = strings.Cut(back, "?")
+ expectSummaries(t, rig.summaries(t, Ana, back),
+ "Brought back after it was deleted")
+}
+
+// Past the window, a rename names its new title, a restore cannot name
+// its source, and the list says the rest has aged out. Nothing is ever
+// diffed against a revision the window has dropped.
+func TestHistoryAgesOut(t *testing.T) {
+ rig := newRig(t)
+ moving := rig.clocked(t)
+ acme := rig.createPage(t, Ana, "Acme", "Body A.")
+ first := revisionOf(t, rig, acme)
+ moving.now = moving.now.Add(time.Hour)
+ rig.post(t, Ana, acme, url.Values{"revision": {first},
+ "body": {"Body B."}})
+ if strings.Contains(rig.page(t, Ana, acme+"/history"), "aged out") {
+ t.Fatal("a page inside the window says its history aged out")
+ }
+ moving.now = moving.now.Add(80 * 24 * time.Hour)
+ rig.post(t, Ana, acme+"/rename", url.Values{"title": {"Acme Ltd"}})
+ moving.now = moving.now.Add(5 * 24 * time.Hour)
+ rig.post(t, Ana, acme+"/history/"+first, nil)
+ moving.now = moving.now.Add(6 * 24 * time.Hour)
+ expectSummaries(t, rig.summaries(t, Ana, acme),
+ "Restored an earlier version", "Renamed to Acme Ltd")
+ panel := rig.page(t, Ana, acme+"/history")
+ if !strings.Contains(panel, "Earlier history has aged out.") {
+ t.Fatal("the list does not say earlier history aged out")
+ }
+ oldest := lastBetween(panel, acme+"/history/", `"`)
+ version := rig.page(t, Ana, acme+"/history/"+oldest)
+ if !strings.Contains(version, "The version before it has aged out") ||
+ strings.Contains(version, "<del>") {
+ t.Fatal("a version was diffed against one past the window")
+ }
+}
+
+func TestHistoryShowsOlderInPages(t *testing.T) {
+ rig := newRig(t)
+ moving := rig.clocked(t)
+ acme := rig.createPage(t, Ana, "Acme", "0")
+ for count := 1; count <= 31; count++ {
+ moving.now = moving.now.Add(time.Minute)
+ rig.post(t, Ana, acme, url.Values{"revision": {revisionOf(t, rig,
+ acme)}, "body": {fmt.Sprint(count)}})
+ }
+ if got := len(rig.summaries(t, Ana, acme)); got != 30 {
+ t.Fatalf("the first screen summarises %d versions", got)
+ }
+ panel := rig.page(t, Ana, acme+"/history")
+ older := between(panel, `href="`+acme+`/history?older=`, `"`)
+ if older != "30" {
+ t.Fatalf("Show older pages on to %q", older)
+ }
+ rest := rig.page(t, Ana, acme+"/history?older=30")
+ if strings.Count(rest, "<small mapa-ver-summary>") != 2 ||
+ !strings.Contains(rest, "Created this page") {
+ t.Fatal("Show older does not list the rest")
+ }
+}
+
+// fetchAs is a GET with request headers, as a browser sends them.
+func (rig *rig) fetchAs(who, target string,
+ headers map[string]string) *httptest.ResponseRecorder {
+ request := httptest.NewRequest(http.MethodGet, target, nil)
+ for name, value := range headers {
+ request.Header.Set(name, value)
+ }
+ recorder := httptest.NewRecorder()
+ rig.built.As(who).ServeHTTP(recorder, request)
+ return recorder
+}
+
+// Docs' rule: only a fetch (Sec-Fetch-Dest: empty) gets the fragment; a
+// document request, or one with no Sec-Fetch-* at all, the full page.
+func TestThePanelFragmentFollowsSecFetchDest(t *testing.T) {
+ rig := newRig(t)
+ acme := rig.createPage(t, Ana, "Acme", "Body.")
+ revision := revisionOf(t, rig, acme)
+ for _, path := range []string{acme + "/history?panel=1",
+ acme + "/history/" + revision + "?panel=1"} {
+ for _, check := range []struct {
+ headers map[string]string
+ fragment bool
+ }{
+ {map[string]string{"Sec-Fetch-Dest": "empty",
+ "Sec-Fetch-Mode": "cors"}, true},
+ {map[string]string{"Sec-Fetch-Dest": "document",
+ "Sec-Fetch-Mode": "navigate"}, false},
+ {nil, false},
+ } {
+ got := rig.fetchAs(Ana, path, check.headers)
+ body := got.Body.String()
+ isFragment := strings.HasPrefix(body, "<aside mapa-history")
+ full := strings.HasPrefix(body, "<!doctype html>") &&
+ strings.Contains(body, "<aside mapa-history")
+ if got.Code != http.StatusOK || isFragment != check.fragment ||
+ (!check.fragment && !full) {
+ t.Errorf("%s with %v: %d, fragment %v", path,
+ check.headers, got.Code, isFragment)
+ }
+ }
+ }
+}
+
+// Gate 1 for history: a private page's history and its versions are a
+// 404 to anyone else, and a team page's history reads the same whether
+// or not Ana's private notes link to it (L6, "history summaries").
+func TestHistoryKeepsScope(t *testing.T) {
+ rig := newRig(t)
+ mine := rig.post(t, Ana, "/scratch", url.Values{"body": {"Mine."}}).
+ Header().Get("Location")
+ revision := revisionAs(t, rig, Ana, mine)
+ for _, path := range []string{mine + "/history",
+ mine + "/history?panel=1", mine + "/history/" + revision} {
+ got := rig.fetchAs(Bo, path, map[string]string{
+ "Sec-Fetch-Dest": "empty"})
+ if got.Code != http.StatusNotFound {
+ t.Errorf("Bo's GET %s: %d", path, got.Code)
+ }
+ }
+ quiet, acme := gate1World(t, false)
+ busy, _ := gate1World(t, true)
+ revisions := regexp.MustCompile(`/history/[0-9]+`)
+ for _, path := range []string{acme + "/history",
+ acme + "/history?panel=1"} {
+ without := revisions.ReplaceAllString(quiet.page(t, Bo, path), "")
+ with := revisions.ReplaceAllString(busy.page(t, Bo, path), "")
+ if without != with {
+ t.Errorf("Bo's %s differs:\n%s", path,
+ firstDifference(without, with))
+ }
+ }
+}
+
+// L7: every new GET leaves every table as it was. A dump of the rows is
+// compared, not the file, which the WAL and checkpoints move.
+func TestHistoryGetsWriteNothing(t *testing.T) {
+ rig := newRig(t)
+ acme := rig.createPage(t, Ana, "Acme", "One.\n\nTwo.")
+ first := revisionOf(t, rig, acme)
+ rig.post(t, Ana, acme, url.Values{"revision": {first},
+ "body": {"One.\n\nTwo, again."}})
+ before := dumpAll(t, rig)
+ for _, who := range []string{Bo, Ana} {
+ for _, path := range []string{acme + "/history",
+ acme + "/history?panel=1", acme + "/history?older=30",
+ acme + "/history/" + first, acme + "/history/" + first +
+ "?panel=1"} {
+ for _, dest := range []string{"empty", "document", ""} {
+ got := rig.fetchAs(who, path, map[string]string{
+ "Sec-Fetch-Dest": dest})
+ if got.Code != http.StatusOK {
+ t.Fatalf("%s GET %s: %d", who, path, got.Code)
+ }
+ }
+ }
+ }
+ if dumpAll(t, rig) != before {
+ t.Fatal("a history GET wrote to the database")
+ }
+ rig.post(t, Ana, acme+"/history/"+first, nil)
+ if dumpAll(t, rig) == before {
+ t.Fatal("the dump is vacuous: a restore did not change it")
+ }
+}
+
+// dumpAll hashes every row of every table.
+func dumpAll(t *testing.T, rig *rig) string {
+ t.Helper()
+ var tables []string
+ if err := rig.db.G.Raw("SELECT name FROM sqlite_master WHERE " +
+ "type = 'table' ORDER BY name").Scan(&tables).Error; err != nil {
+ t.Fatal(err)
+ }
+ hash := sha256.New()
+ for _, table := range tables {
+ var rows []map[string]any
+ err := rig.db.G.Raw(`SELECT * FROM "` + table + `" ORDER BY rowid`).
+ Scan(&rows).Error
+ if err != nil {
+ t.Fatal(err)
+ }
+ fmt.Fprintf(hash, "%s %v\n", table, rows)
+ }
+ return fmt.Sprintf("%x", hash.Sum(nil))
+}
diff --git a/internal/mapatest/history_test.go b/internal/mapatest/history_test.go
index ea2402a..4582074 100644
--- a/internal/mapatest/history_test.go
+++ b/internal/mapatest/history_test.go
@@ -19,7 +19,8 @@ func TestHistoryListsRestoresAndForgetsAfter90Days(t *testing.T) {
"body": {"Second version."}})
history := rig.page(t, Ana, acme+"/history")
if strings.Count(history, `href="`+acme+`/history/`) != 2 ||
- !strings.Contains(history, Bo) || !strings.Contains(history, Ana) {
+ !strings.Contains(history, "<b>bo</b>") ||
+ !strings.Contains(history, "<b>You</b>") {
t.Fatalf("history does not list both revisions with their actors")
}
old := rig.page(t, Ana, acme+"/history/"+first)
diff --git a/internal/mapatest/verbs_test.go b/internal/mapatest/verbs_test.go
new file mode 100644
index 0000000..b5824ba
--- /dev/null
+++ b/internal/mapatest/verbs_test.go
@@ -0,0 +1,81 @@
+package mapatest
+
+import (
+ "net/url"
+ "sort"
+ "strings"
+ "testing"
+)
+
+// Level-up §8, "Event verbs" (N1): "Update links" and "Link it" log
+// relinked, and "Link to this block" logs marked, on team pages only. A
+// private page keeps edited, so the plaintext log says nothing about its
+// links. Each replaces the edited row the write logged before: no row
+// is added.
+
+// lastEvent is the newest event's id.
+func (rig *rig) lastEvent(t *testing.T) int64 {
+ t.Helper()
+ var last int64
+ if err := rig.db.G.Raw("SELECT COALESCE(MAX(id), 0) FROM events").
+ Scan(&last).Error; err != nil {
+ t.Fatal(err)
+ }
+ return last
+}
+
+// verbsSince is the verbs of the events after since, sorted.
+func (rig *rig) verbsSince(t *testing.T, since int64) string {
+ t.Helper()
+ var verbs []string
+ if err := rig.db.G.Raw("SELECT verb FROM events WHERE id > ?", since).
+ Scan(&verbs).Error; err != nil {
+ t.Fatal(err)
+ }
+ sort.Strings(verbs)
+ return strings.Join(verbs, ",")
+}
+
+func TestUpdateLinksIsRelinkedOnTeamPagesAndEditedOnPrivate(t *testing.T) {
+ rig := newRig(t)
+ acme := rig.createPage(t, Ana, "Acme", "A customer.")
+ rig.createPage(t, Ana, "Notes", "See [[Acme]].")
+ rig.post(t, Ana, "/d/2026-11-12", url.Values{"body": {"Met [[Acme]]."},
+ "revision": {"0"}})
+ rig.post(t, Ana, acme+"/rename", url.Values{"title": {"Acme Ltd"}})
+ since := rig.lastEvent(t)
+ rig.post(t, Ana, acme+"/links", nil)
+ if got := rig.verbsSince(t, since); got != "edited,relinked" {
+ t.Fatalf("Update links over a team page and a daily note logged %q",
+ got)
+ }
+}
+
+func TestLinkItIsRelinkedOnTeamPagesAndEditedOnPrivate(t *testing.T) {
+ rig := newRig(t)
+ acme := rig.createPage(t, Ana, "Acme", "A customer.")
+ team := rig.createPage(t, Bo, "Plan", "Call Acme soon.")
+ mine := rig.post(t, Ana, "/scratch", url.Values{"body": {"Acme again."}}).
+ Header().Get("Location")
+ for _, check := range []struct{ who, source, want string }{
+ {Bo, team, "relinked"}, {Ana, mine, "edited"}} {
+ since := rig.lastEvent(t)
+ rig.post(t, check.who, acme+"/mentions", url.Values{
+ "source": {strings.TrimPrefix(check.source, "/p/")},
+ "block": {"0"}})
+ if got := rig.verbsSince(t, since); got != check.want {
+ t.Errorf("Link it from %s logged %q, want %q", check.source,
+ got, check.want)
+ }
+ }
+}
+
+func TestLinkToThisBlockIsMarked(t *testing.T) {
+ rig := newRig(t)
+ acme := rig.createPage(t, Ana, "Acme", "First.\n\nSecond.")
+ since := rig.lastEvent(t)
+ rig.post(t, Ana, acme+"/blocks", url.Values{"block": {"1"}})
+ if got := rig.verbsSince(t, since); got != "marked" {
+ t.Fatalf("Link to this block logged %q", got)
+ }
+}