Merge level-up/p1-history: Fable's Phase 1 review M3, M4, L8 and L9 for History
M3: shared ends trimmed before the block alignment, which is capped at 1<<20 cells (past it, a coarse removed-then-added diff); a restore's lookback opens at most 30 versions. 6,000 items x 7 versions: 902 MB -> 36 MB, held under 50 MB by a test. M4: one empty paragraph, at the end. L8: a kept numbered list after a change keeps its start. L9: removed before added. Built by a sub-agent on its own branch.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
7 files changed,
+433
−70
internal/mapa/diff.go+151 −52internal/mapa/diff_test.go+70 −4internal/mapa/handlers_history.go+5 −2internal/mapa/history_view.go+16 −4internal/mapa/versions.go+37 −8internal/mapa/versions_test.go+134 −0internal/mapatest/history_test.go+20 −0
CI failed — run details
CI log
=== editor ===
cd editor && npm ci --no-audit --no-fund --loglevel=error
added 16 packages in 5s
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 (1.136307ms)
✔ markup.mjs parses every body into Go's blocks, byte offsets and all (31.455125ms)
✔ markup.mjs strips and spans every block as Go does (88.060754ms)
✔ the schema's toDOM draws every body as Go renders it (318.354215ms)
✔ emphasis draws the four pinned outputs (39.866468ms)
✔ a body ends in the editor's empty paragraph (0.425557ms)
ℹ tests 6
ℹ suites 0
ℹ pass 6
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 1178.413717
=== 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 1.213s
? amadan.net/oficina/mapa/internal/mapa/icons [no test files]
ok amadan.net/oficina/mapa/internal/mapa/markup (cached)
ok amadan.net/oficina/mapa/internal/mapa/seal (cached)
--- FAIL: TestGate6SpeedAtSize (45.88s)
speed_test.go:61: seeded 10000 pages in 35.592389133s
speed_test.go:69: cold wake to first search answered, at 10000 pages: 6.399569135s
speed_test.go:75: page views (backlinks and unlinked mentions included): 200, p50 2.453177ms, p95 29.500092ms, max 125.546396ms
speed_test.go:84: /search/suggest: 873 queries, p50 1.710999ms, p95 5.950868ms, max 24.295637ms
speed_test.go:87: /search/suggest p95 is 5.950868ms, over §6.1's 5ms
speed_test.go:84: /links/suggest: 873 queries, p50 334.807µs, p95 1.884394ms, max 9.200676ms
FAIL
FAIL amadan.net/oficina/mapa/internal/mapatest 49.733s
? amadan.net/oficina/mapa/scripts/mutate [no test files]
? amadan.net/oficina/mapa/scripts/preview [no test files]
FAIL
make: *** [Makefile:53: test] Error 1
amadan: step test failed: exit status 2
amadan: job failed at step test — its output is above, not at the tail of this log
diff --git a/internal/mapa/diff.go b/internal/mapa/diff.go| index 03acaa2..f1f5297 100644 |
| --- a/internal/mapa/diff.go |
| +++ b/internal/mapa/diff.go |
| @@ -33,10 +33,12 @@ type blockChange struct { |
| // 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. |
| +// Past the alignment's bound (matchBlocks), nothing pairs: the changed |
| +// middle is all removed, then all added. |
| func diffBlocks(from, to []markup.Block) []blockChange { |
| - matched := matchBlocks(from, to) |
| + matched, coarse := matchBlocks(from, to) |
| alike := func(was, now int) bool { |
| - return similar(tokensOf(from[was]), tokensOf(to[now])) |
| + return !coarse && similar(tokensOf(from[was]), tokensOf(to[now])) |
| } |
| var changes, removed []blockChange |
| next := 0 |
| @@ -57,43 +59,45 @@ func diffBlocks(from, to []markup.Block) []blockChange { |
| // 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. |
| +// by word (a changed block). Between pairs, the rest are drawn removed, |
| +// then added; a removal falls At the block drawn after it. |
| func stretch(removed []blockChange, start, end int, |
| alike func(was, now int) bool) []blockChange { |
| - pairs := pairUp(removed, start, end, alike) |
| + pairs := append(pairUp(removed, start, end, alike), |
| + blockPair{From: math.MaxInt, To: end}) |
| 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) |
| + gone, cursor := 0, start |
| + for _, pair := range pairs { |
| + for ; gone < len(removed) && removed[gone].From < pair.From; gone++ { |
| + change := removed[gone] |
| + change.At = cursor |
| + out = append(out, change) |
| } |
| - } |
| - for index := start; index < end; index++ { |
| - old, paired := pairs[index] |
| - if !paired { |
| + for ; cursor < pair.To; cursor++ { |
| out = append(out, blockChange{Kind: blockAdded, From: -1, |
| - To: index, At: index}) |
| - continue |
| + To: cursor, At: cursor}) |
| + } |
| + if pair.To < end { |
| + out = append(out, blockChange{Kind: blockChanged, |
| + From: pair.From, To: pair.To, At: pair.To}) |
| + gone, cursor = gone+1, cursor+1 |
| } |
| - settle(old, index) |
| - next++ |
| - out = append(out, blockChange{Kind: blockChanged, From: old, |
| - To: index, At: index}) |
| } |
| - settle(math.MaxInt, end) |
| return out |
| } |
| +// blockPair is a removed block, From, that changed into an added one. |
| +type blockPair struct{ From, To int } |
| + |
| // 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. |
| +// pairUp is the removed blocks that changed into added ones in start up |
| +// to end, in order: 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{} |
| + alike func(was, now int) bool) []blockPair { |
| + var pairs []blockPair |
| cursor, tries := start, 0 |
| for _, gone := range removed { |
| for candidate := cursor; candidate < end; candidate++ { |
| @@ -101,7 +105,8 @@ func pairUp(removed []blockChange, start, end int, |
| return pairs |
| } |
| if alike(gone.From, candidate) { |
| - pairs[candidate] = gone.From |
| + pairs = append(pairs, blockPair{From: gone.From, |
| + To: candidate}) |
| cursor = candidate + 1 |
| break |
| } |
| @@ -110,15 +115,57 @@ func pairUp(removed []blockChange, start, end int, |
| return pairs |
| } |
| +// maxBlockCells bounds the block alignment's table, as maxWordCells |
| +// bounds the word diff's: 4 MB of it. The blocks the two versions share |
| +// at either end are matched first and cost nothing; past the bound, the |
| +// middle between them is not aligned at all (coarse). |
| +const maxBlockCells = 1 << 20 |
| + |
| // 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 |
| +// nothing new from markup. coarse reports a middle too large to align, |
| +// whose blocks are all -1. |
| +func matchBlocks(from, to []markup.Block) (matched []int, coarse bool) { |
| + head, tail := sharedEnds(from, to) |
| + rows, columns := len(from)-head-tail, len(to)-head-tail |
| + matched = make([]int, len(from)) |
| + for index := range matched { |
| + switch { |
| + case index < head: |
| + matched[index] = index |
| + case index >= head+rows: |
| + matched[index] = index + len(to) - len(from) |
| + default: |
| + matched[index] = -1 |
| + } |
| + } |
| + if rows*columns > maxBlockCells { |
| + return matched, true |
| + } |
| + middle := lcs(rows, columns, func(row, column int) bool { |
| + return from[head+row].Source == to[head+column].Source |
| + }) |
| + for row, column := range middle { |
| + if column >= 0 { |
| + matched[head+row] = head + column |
| + } |
| + } |
| + return matched, false |
| +} |
| + |
| +// sharedEnds is how many blocks the two versions share at the start, |
| +// and then at the end of what is left. |
| +func sharedEnds(from, to []markup.Block) (head, tail int) { |
| + shorter := min(len(from), len(to)) |
| + for head < shorter && from[head].Source == to[head].Source { |
| + head++ |
| + } |
| + for tail < shorter-head && from[len(from)-1-tail].Source == |
| + to[len(to)-1-tail].Source { |
| + tail++ |
| } |
| - return lcs(len(from), len(to), same) |
| + return head, tail |
| } |
| // lcs maps each of rows items to its match among columns, or -1, by a |
| @@ -156,20 +203,26 @@ func lcs(rows, columns int, same func(row, column int) bool) []int { |
| return matched |
| } |
| +// drawRun draws a run of a version's blocks as the page draws them, in |
| +// the viewer's scope (markup.Render), with no empty paragraph after. |
| +type drawRun func(blocks []markup.Block) (template.HTML, error) |
| + |
| // 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) { |
| +// before it marked. Runs of unchanged blocks go through draw; changed |
| +// blocks are drawn here. The editor's empty paragraph comes once, at the |
| +// end, as the page's renderer decides it (pageEnd). |
| +func diffHTML(from, to []markup.Block, draw drawRun) (template.HTML, |
| + error) { |
| var out strings.Builder |
| var kept []markup.Block |
| + var last *markup.Block |
| flush := func() error { |
| if len(kept) == 0 { |
| return nil |
| } |
| - drawn, err := draw(markup.Join(kept)) |
| - out.WriteString(string(drawn)) |
| - kept = nil |
| + drawn, err := draw(kept) |
| + out.WriteString(continued(string(drawn), last, kept[0])) |
| + last, kept = &kept[len(kept)-1], nil |
| return err |
| } |
| for _, change := range diffBlocks(from, to) { |
| @@ -180,27 +233,68 @@ func diffHTML(from, to []markup.Block, |
| if err := flush(); err != nil { |
| return "", err |
| } |
| - out.WriteString(changedBlock(change, from, to)) |
| + block := blockOf(change, from, to) |
| + out.WriteString(changedBlock(change, block, from)) |
| + last = &block |
| + } |
| + err := flush() |
| + return template.HTML(out.String() + pageEnd(last)), err |
| +} |
| + |
| +// continued is a kept run, drawn, that goes on with a numbered list a |
| +// change interrupted: its list starts at its first item's own number, |
| +// not at 1. |
| +func continued(drawn string, last *markup.Block, first markup.Block) string { |
| + if last == nil || last.Kind != markup.Item || first.Kind != |
| + markup.Item || !first.Ordered { |
| + return drawn |
| } |
| - if err := flush(); err != nil { |
| - return "", err |
| + rest, found := strings.CutPrefix(drawn, "<ol>") |
| + if !found { |
| + return drawn |
| } |
| - return template.HTML(out.String()), nil |
| + return `<ol start="` + itemNumber(first) + `">` + rest |
| +} |
| + |
| +// pageEnd is the editor's empty paragraph after the last block drawn, |
| +// when it is not a paragraph, as markup.RenderPage ends a body. With |
| +// nothing drawn there is none, so the version reads as empty. |
| +func pageEnd(last *markup.Block) string { |
| + if last == nil || last.Kind == markup.Paragraph { |
| + return "" |
| + } |
| + return markup.EmptyParagraph |
| +} |
| + |
| +// drawPage is a whole body drawn as its page, with its end. |
| +func drawPage(body string, draw drawRun) (template.HTML, error) { |
| + blocks := markup.Parse(body) |
| + if len(blocks) == 0 { |
| + return "", nil |
| + } |
| + drawn, err := draw(blocks) |
| + return drawn + template.HTML(pageEnd(&blocks[len(blocks)-1])), err |
| +} |
| + |
| +// blockOf is the block a change draws: the one removed, or this |
| +// version's. |
| +func blockOf(change blockChange, from, to []markup.Block) markup.Block { |
| + if change.Kind == blockRemoved { |
| + return from[change.From] |
| + } |
| + return to[change.To] |
| } |
| // changedBlock is one added, removed or changed block, as its kind. |
| -func changedBlock(change blockChange, from, to []markup.Block) string { |
| - var block markup.Block |
| +func changedBlock(change blockChange, block markup.Block, |
| + from []markup.Block) string { |
| 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))) |
| } |
| @@ -233,12 +327,17 @@ func asItem(block markup.Block, inner string) string { |
| 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)] + `"` |
| + open = `<ol start="` + itemNumber(block) + `"` |
| } |
| return open + ` mapa-diff-level="` + strconv.Itoa(min(block.Level, 3)) + |
| `"><li>` + inner + "</li></" + tag + ">" |
| } |
| + |
| +// itemNumber is a numbered item's own number, as typed. |
| +func itemNumber(block markup.Block) string { |
| + digits := strings.TrimLeft(block.Source, " \t") |
| + end := strings.IndexFunc(digits, func(char rune) bool { |
| + return char < '0' || char > '9' |
| + }) |
| + return digits[:max(end, 0)] |
| +} |
diff --git a/internal/mapa/diff_test.go b/internal/mapa/diff_test.go| index 351025b..e405a64 100644 |
| --- a/internal/mapa/diff_test.go |
| +++ b/internal/mapa/diff_test.go |
| @@ -25,14 +25,27 @@ func TestEditSummaries(t *testing.T) { |
| {strings.Replace(base, "Ana, budget.", "Ana, [[Budget]].", 1), |
| "Edited Contacts"}, |
| } { |
| - if got := editSummary(base, check.body); got != check.want { |
| + if got := editSummary(markup.Parse(base), |
| + markup.Parse(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 plainDraw(blocks []markup.Block) (template.HTML, error) { |
| + return template.HTML("[" + template.HTMLEscapeString( |
| + markup.Join(blocks)) + "]"), nil |
| +} |
| + |
| +// noLinks resolves every link nowhere: enough to draw with Render. |
| +type noLinks struct{} |
| + |
| +func (noLinks) Resolve(string, string) markup.Resolution { |
| + return markup.Resolution{Href: "#"} |
| +} |
| + |
| +func renderDraw(blocks []markup.Block) (template.HTML, error) { |
| + return markup.Render(blocks, noLinks{}), nil |
| } |
| func diffOf(t *testing.T, old, body string) string { |
| @@ -49,7 +62,7 @@ func TestTheWordDiffMarksOnlyWhatChanged(t *testing.T) { |
| "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" |
| + "</li></ul></div>\n" + markup.EmptyParagraph |
| if got != want { |
| t.Fatalf("got %s\nwant %s", got, want) |
| } |
| @@ -124,3 +137,56 @@ func TestChangedBlocksDrawEmphasisAndNumbers(t *testing.T) { |
| t.Fatalf("got %s", got) |
| } |
| } |
| + |
| +// Review L9: between two kept blocks, what was removed is drawn before |
| +// what was added, as diffBlocks says. |
| +func TestRemovedBlocksAreDrawnBeforeAddedOnes(t *testing.T) { |
| + got := diffOf(t, "Kept.\n\nAn old line about budgets.\n\nAlso kept.", |
| + "Kept.\n\n# Something new\n\n- Another\n\nAlso kept.") |
| + removed := strings.Index(got, `mapa-diff="removed"`) |
| + added := strings.Index(got, `mapa-diff="added"`) |
| + if removed < 0 || added < 0 || removed > added { |
| + t.Fatalf("removed is not drawn before added:\n%s", got) |
| + } |
| +} |
| + |
| +// Review M4: the editor's empty paragraph is drawn once, at the end of |
| +// the whole diff and only when its last block is not a paragraph; never |
| +// after a kept list in the middle of the text. |
| +func TestTheEmptyParagraphEndsTheDiffOnce(t *testing.T) { |
| + for _, check := range []struct{ old, body string }{ |
| + {"- a\n- b\n\nOld end.", "- a\n- b\n\nA new end entirely."}, |
| + {"- a\n- b\n\nMiddle.\n\n- c", "- a\n- b\n\nMiddle, now.\n\n- c"}, |
| + {"Start.\n\n- a", "Start, now.\n\n- a"}, |
| + } { |
| + drawn, err := diffHTML(markup.Parse(check.old), |
| + markup.Parse(check.body), renderDraw) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + got := string(drawn) |
| + count := strings.Count(got, markup.EmptyParagraph) |
| + ends := strings.HasSuffix(got, markup.EmptyParagraph) |
| + last := markup.Parse(check.body) |
| + wantEnd := last[len(last)-1].Kind != markup.Paragraph |
| + if count > 1 || (count == 1) != ends || ends != wantEnd { |
| + t.Errorf("%q: %d empty paragraphs in\n%s", check.body, count, |
| + got) |
| + } |
| + } |
| +} |
| + |
| +// Review L8: a numbered list kept after a change goes on from its own |
| +// number rather than starting again at 1. |
| +func TestAContinuedNumberedListKeepsItsNumbers(t *testing.T) { |
| + drawn, err := diffHTML(markup.Parse("1. One\n2. Two\n3. Three\n4. Four"), |
| + markup.Parse("1. One\n2. Two, now\n3. Three\n4. Four"), renderDraw) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + got := string(drawn) |
| + if !strings.HasPrefix(got, "<ol><li><p>One") || |
| + !strings.Contains(got, `</div>`+"\n"+`<ol start="3"><li><p>Three`) { |
| + t.Fatalf("got %s", got) |
| + } |
| +} |
diff --git a/internal/mapa/handlers_history.go b/internal/mapa/handlers_history.go| index 43699da..73fab13 100644 |
| --- a/internal/mapa/handlers_history.go |
| +++ b/internal/mapa/handlers_history.go |
| @@ -6,6 +6,8 @@ import ( |
| "strconv" |
| "github.com/go-chi/chi/v5" |
| + |
| + "amadan.net/oficina/mapa/internal/mapa/markup" |
| ) |
| // History and block links: the page's revisions in the window, one |
| @@ -96,8 +98,9 @@ func (app *app) showVersion(writer http.ResponseWriter, |
| app.historyFragment(writer, request, panel) |
| return |
| } |
| - draw := func(body string) (template.HTML, error) { |
| - return app.index.Preview(request.Context(), ScopeOf(viewer), body) |
| + draw := func(blocks []markup.Block) (template.HTML, error) { |
| + return app.index.drawRun(request.Context(), ScopeOf(viewer), |
| + blocks) |
| } |
| data, err := versionOf(page, chosen, draw) |
| if err != nil { |
diff --git a/internal/mapa/history_view.go b/internal/mapa/history_view.go| index 6641227..a4a90f8 100644 |
| --- a/internal/mapa/history_view.go |
| +++ b/internal/mapa/history_view.go |
| @@ -135,8 +135,8 @@ type versionView struct { |
| // 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) { |
| +func versionOf(page PageView, chosen Chosen, draw drawRun) (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)} |
| @@ -148,11 +148,11 @@ func versionOf(page PageView, chosen Chosen, |
| 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) |
| + view.HTML, err = drawPage(chosen.Record.Body, draw) |
| default: |
| view.Note = "The version before it has aged out, so nothing " + |
| "is marked." |
| - view.HTML, err = draw(chosen.Record.Body) |
| + view.HTML, err = drawPage(chosen.Record.Body, draw) |
| } |
| return view, err |
| } |
| @@ -180,3 +180,15 @@ func versionTitle(page PageView, chosen Chosen) template.HTML { |
| html.EscapeString(chosen.Before.Title) + "</del>", |
| "<ins>" + escaped + "</ins>"}, " ")) |
| } |
| + |
| +// drawRun draws blocks for scope as the page does, with no empty |
| +// paragraph after them: a version's view adds that once, at its end. |
| +func (index *Index) drawRun(ctx context.Context, scope Scope, |
| + blocks []markup.Block) (template.HTML, error) { |
| + if err := index.Sync(ctx); err != nil { |
| + return "", err |
| + } |
| + index.mutex.RLock() |
| + defer index.mutex.RUnlock() |
| + return markup.Render(blocks, resolver{index, scope}), nil |
| +} |
diff --git a/internal/mapa/versions.go b/internal/mapa/versions.go| index f3f29e7..8497a7c 100644 |
| --- a/internal/mapa/versions.go |
| +++ b/internal/mapa/versions.go |
| @@ -64,6 +64,15 @@ type pageHistory struct { |
| records map[int64]Record |
| verbs map[int64]string |
| names map[int64]string |
| + // parsed is the last version's blocks, which the next older edit's |
| + // summary compares against, so each body is parsed once. |
| + parsed parsedVersion |
| +} |
| + |
| +// parsedVersion is one revision's body as blocks. |
| +type parsedVersion struct { |
| + revision int64 |
| + blocks []markup.Block |
| } |
| // History is one screen of a page's versions, from skip on, if the |
| @@ -250,15 +259,21 @@ func (history *pageHistory) renamed(index int) (string, error) { |
| return "Renamed to " + record.Title, nil |
| } |
| +// maxRevertSearch bounds how many older versions one restore's summary |
| +// opens to find its source: a screen's worth. |
| +const maxRevertSearch = HistoryPage |
| + |
| // 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. |
| +// the window with the same text, among the maxRevertSearch before it. |
| +// Restore keeps no pointer to its source, so with none there 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++ { |
| + last := min(len(history.rows), index+1+maxRevertSearch) |
| + for older := index + 1; older < last; older++ { |
| candidate, err := history.record(older) |
| if err != nil { |
| return "", err |
| @@ -287,21 +302,35 @@ func (history *pageHistory) edited(index int) (string, error) { |
| if index+1 >= len(history.rows) { |
| return "Edited", nil |
| } |
| - before, err := history.record(index + 1) |
| + now, err := history.blocks(index) |
| if err != nil { |
| return "", err |
| } |
| - record, err := history.record(index) |
| + before, err := history.blocks(index + 1) |
| if err != nil { |
| return "", err |
| } |
| - return editSummary(before.Body, record.Body), nil |
| + return editSummary(before, now), nil |
| +} |
| + |
| +// blocks is rows[index]'s body parsed, kept until another is asked for. |
| +func (history *pageHistory) blocks(index int) ([]markup.Block, error) { |
| + revision := history.rows[index].Revision |
| + if history.parsed.revision == revision { |
| + return history.parsed.blocks, nil |
| + } |
| + record, err := history.record(index) |
| + if err != nil { |
| + return nil, err |
| + } |
| + history.parsed = parsedVersion{revision: revision, |
| + blocks: markup.Parse(record.Body)} |
| + return history.parsed.blocks, 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) |
| +func editSummary(from, to []markup.Block) string { |
| counts := map[string]int{} |
| var first *blockChange |
| for _, change := range diffBlocks(from, to) { |
diff --git a/internal/mapa/versions_test.go b/internal/mapa/versions_test.go| new file mode 100644 |
| index 0000000..9e44fc3 |
| --- /dev/null |
| +++ b/internal/mapa/versions_test.go |
| @@ -0,0 +1,134 @@ |
| +package mapa |
| + |
| +import ( |
| + "runtime" |
| + "strconv" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/mapa/internal/mapa/markup" |
| +) |
| + |
| +// longList is a page of count list items, the nth reading word. |
| +func longList(count int, word func(item int) string) string { |
| + var out strings.Builder |
| + for item := range count { |
| + out.WriteString("- Item " + strconv.Itoa(item) + " " + word(item) + |
| + "\n") |
| + } |
| + return out.String() |
| +} |
| + |
| +// allocated is the bytes run allocates. |
| +func allocated(run func()) uint64 { |
| + var before, after runtime.MemStats |
| + runtime.GC() |
| + runtime.ReadMemStats(&before) |
| + run() |
| + runtime.ReadMemStats(&after) |
| + return after.TotalAlloc - before.TotalAlloc |
| +} |
| + |
| +// Review M3: history on a long page is bounded. A page of 6,000 list |
| +// items edited here and there, then rewritten throughout, reads its |
| +// history in a modest allocation (902 MB before the bound), and the |
| +// rewrite, too large to align, is summarised as plain "Edited". |
| +func TestALongPagesHistoryIsBounded(t *testing.T) { |
| + store := testStore(t) |
| + clock := time.Now().UTC() |
| + store.SetClock(func() time.Time { return clock }) |
| + edited := map[int]bool{} |
| + word := func(item int) string { |
| + if edited[item] { |
| + return "was edited" |
| + } |
| + return "stays as it was" |
| + } |
| + page := mustCreate(t, store, "Long", longList(6000, word)) |
| + for edit := range 5 { |
| + clock = clock.Add(time.Minute) |
| + edited[edit*1000+500] = true |
| + page = commitBody(t, store, page, longList(6000, word)) |
| + } |
| + clock = clock.Add(time.Minute) |
| + page = commitBody(t, store, page, longList(6000, func(int) string { |
| + return "rewritten throughout" |
| + })) |
| + var summaries []string |
| + used := allocated(func() { |
| + list, err := store.History(ctx(), viewerOf(t, store, ana), page.ID, |
| + 0) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, version := range list.Versions { |
| + summaries = append(summaries, version.Summary) |
| + } |
| + }) |
| + t.Logf("history of a 6,000-block page: %d MB", used>>20) |
| + if used > 50<<20 { |
| + t.Errorf("history allocated %d MB, want under 50", used>>20) |
| + } |
| + want := "Edited | Edited | Edited | Edited | Edited | Edited | " + |
| + "Created this page" |
| + if got := strings.Join(summaries, " | "); got != want { |
| + t.Errorf("summaries %q, want %q", got, want) |
| + } |
| +} |
| + |
| +// Past the bound, a chosen version's diff is coarse: the changed middle |
| +// removed and added whole, between the blocks the versions share, the |
| +// removed first (review L9). |
| +func TestATooLargeChangeIsRemovedThenAddedWhole(t *testing.T) { |
| + old := markup.Parse("Kept first.\n\n" + longList(1100, |
| + func(int) string { return "old" }) + "\nKept last.") |
| + now := markup.Parse("Kept first.\n\n" + longList(1100, |
| + func(int) string { return "new" }) + "\nKept last.") |
| + var kinds []string |
| + for _, change := range diffBlocks(old, now) { |
| + if len(kinds) == 0 || kinds[len(kinds)-1] != change.Kind { |
| + kinds = append(kinds, change.Kind) |
| + } |
| + } |
| + want := []string{blockSame, blockRemoved, blockAdded, blockSame} |
| + if strings.Join(kinds, " ") != strings.Join(want, " ") { |
| + t.Fatalf("runs %q, want %q", kinds, want) |
| + } |
| +} |
| + |
| +// A restore's summary looks back a screen of versions for its source, |
| +// and no further: past that it is "Restored an earlier version". |
| +func TestARestoreLooksBackABoundedWay(t *testing.T) { |
| + store := testStore(t) |
| + clock := time.Now().UTC() |
| + store.SetClock(func() time.Time { return clock }) |
| + page := mustCreate(t, store, "Notes", "First.") |
| + first := page.Revision |
| + for edit := range maxRevertSearch { |
| + clock = clock.Add(time.Minute) |
| + page = commitBody(t, store, page, "Edit "+strconv.Itoa(edit)+".") |
| + } |
| + clock = clock.Add(time.Minute) |
| + if err := store.Revert(ctx(), ana, page.ID, first); err != nil { |
| + t.Fatal(err) |
| + } |
| + list, err := store.History(ctx(), viewerOf(t, store, ana), page.ID, 0) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if got := list.Versions[0].Summary; got != "Restored an earlier "+ |
| + "version" { |
| + t.Fatalf("summary %q", got) |
| + } |
| +} |
| + |
| +// commitBody saves body over page's current revision. |
| +func commitBody(t *testing.T, store *Store, page Page, body string) Page { |
| + t.Helper() |
| + if _, err := store.Commit(ctx(), ana, page.ID, page.Revision, |
| + body); err != nil { |
| + t.Fatal(err) |
| + } |
| + return loadPage(t, store, page.ID) |
| +} |
diff --git a/internal/mapatest/history_test.go b/internal/mapatest/history_test.go| index 4582074..26fe220 100644 |
| --- a/internal/mapatest/history_test.go |
| +++ b/internal/mapatest/history_test.go |
| @@ -71,3 +71,23 @@ func TestLinkToThisBlockMintsAMarkerAsAnEdit(t *testing.T) { |
| t.Fatal("a private page offers block markers") |
| } |
| } |
| + |
| +// Review M4: a chosen version's diff draws the editor's empty paragraph |
| +// at most once, at its end; never after a kept list mid-text. |
| +func TestAVersionDiffEndsInOneEmptyParagraph(t *testing.T) { |
| + rig := newRig(t) |
| + moving := rig.clocked(t) |
| + acme := rig.createPage(t, Ana, "Acme", "- One\n- Two\n\nOld end.\n\n"+ |
| + "- Three") |
| + first := revisionOf(t, rig, acme) |
| + moving.now = moving.now.Add(time.Hour) |
| + rig.post(t, Bo, acme, url.Values{"revision": {first}, |
| + "body": {"- One\n- Two\n\nA new end entirely.\n\n- Three"}}) |
| + version := rig.page(t, Ana, acme+"/history/"+revisionOf(t, rig, acme)) |
| + empty := `<p><br class="ProseMirror-trailingBreak"></p>` |
| + if strings.Count(version, empty) != 1 || !strings.Contains(version, |
| + "<li><p>Three</p></li></ul>"+empty) { |
| + t.Fatalf("the empty paragraph is not drawn once, at the end:\n%s", |
| + version) |
| + } |
| +} |