Merge level-up/p2-server: Phase 2's server half
Byte-preserving Settle with a Join fallback (D13); no-op commits write nothing; the autosave reply carries revision and a merge over the exact text sent; rebase=R (this page, in the window, version-checked); commit=1; Resolve answers JSON; Make team page checks its revision; POST /links/resolve; the editor's data island and the draft bar; the first scratch commit single-flight by a tab token (D12). Gates L7 and L9, gate 8 and gate 1 extended. Built by a sub-agent on its own branch.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
36 files changed,
+1,845
−147
AGENTS.md+5 −0docs/superpowers/specs/2026-11-12-mapa-design.md+10 −3docs/superpowers/specs/2026-11-14-mapa-level-up.md+15 −0internal/mapa/app.go+2 −0internal/mapa/around.go+36 −0internal/mapa/autosave.go+128 −0internal/mapa/commit.go+29 −5internal/mapa/daily.go+19 −2internal/mapa/daily_test.go+10 −5internal/mapa/drafts.go+50 −16internal/mapa/firstscratch.go+125 −0internal/mapa/handlers_autosave.go+146 −0internal/mapa/handlers_drafts.go+7 −26internal/mapa/handlers_edit.go+37 −2internal/mapa/handlers_pages.go+6 −5internal/mapa/handlers_search.go+1 −0internal/mapa/island.go+190 −0internal/mapa/markup/merge.go+76 −58internal/mapa/markup/settle.go+172 −0internal/mapa/markup/settle_test.go+126 −0internal/mapa/private.go+18 −3internal/mapa/share.go+13 −2internal/mapa/templates/day.html+2 −2internal/mapa/templates/page.html+2 −2internal/mapa/templates/partials.html+12 −3internal/mapa/templates/scratch_new.html+1 −0internal/mapa/templates/share.html+1 −0internal/mapa/today.go+9 −0internal/mapatest/daily_test.go+11 −2internal/mapatest/drafts_test.go+5 −5internal/mapatest/gate1_test.go+19 −2internal/mapatest/gate8_test.go+18 −1internal/mapatest/history_panel_test.go+4 −2internal/mapatest/island_test.go+142 −0internal/mapatest/plaintext_scan_test.go+2 −1internal/mapatest/saving_test.go+396 −0
CI passed — run details
CI log
=== editor === cd editor && npm ci --no-audit --no-fund --loglevel=error added 16 packages in 314ms 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.566705ms) ✔ markup.mjs parses every body into Go's blocks, byte offsets and all (10.448699ms) ✔ markup.mjs strips and spans every block as Go does (14.930793ms) ✔ the schema's toDOM draws every body as Go renders it (33.170235ms) ✔ emphasis draws the four pinned outputs (10.483895ms) ✔ a body ends in the editor's empty paragraph (0.152717ms) ℹ tests 6 ℹ suites 0 ℹ pass 6 ℹ fail 0 ℹ cancelled 0 ℹ skipped 0 ℹ todo 0 ℹ duration_ms 133.632659 === 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.335s ? amadan.net/oficina/mapa/internal/mapa/icons [no test files] ok amadan.net/oficina/mapa/internal/mapa/markup 0.025s ok amadan.net/oficina/mapa/internal/mapa/seal (cached) ok amadan.net/oficina/mapa/internal/mapatest 7.932s ? 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 a14e805..5e4c004 100644 |
| --- a/AGENTS.md |
| +++ b/AGENTS.md |
| @@ -52,6 +52,11 @@ Makefile, estilo's files served straight from the module). |
| `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. |
| + Phase 2's server half: `autosave.go` and `handlers_autosave.go` are |
| + the editor's autosave, its merge reply, `rebase` and `commit=1`; |
| + `firstscratch.go` a new scratch page's single-flight first commit |
| + (D12); `island.go` the editor's JSON island and `/links/resolve`; |
| + `markup/settle.go` the byte-preserving `Settle`. |
| - `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/docs/superpowers/specs/2026-11-12-mapa-design.md b/docs/superpowers/specs/2026-11-12-mapa-design.md| index ee978a9..4af1dbc 100644 |
| --- a/docs/superpowers/specs/2026-11-12-mapa-design.md |
| +++ b/docs/superpowers/specs/2026-11-12-mapa-design.md |
| @@ -892,9 +892,16 @@ this list together. |
| 23. **The block merge refines diff3.** Where both sides kept the same |
| number of blocks in a changed stretch (edits in place), each block is |
| resolved on its own, so Ana's edit to one block and Bo's to the next |
| - do not conflict for being neighbours. A merged body is re-joined with |
| - one blank line between blocks (a tight list stays tight), so a merged |
| - save can tidy blank lines. A save that needs no merge keeps every byte. |
| + do not conflict for being neighbours. A save that needs no merge |
| + keeps every byte. *Revised by the level-up (§6.4, D13):* a merged |
| + body keeps the current revision's bytes too. Its blocks, and the |
| + bytes between two of its blocks that are still neighbours, are |
| + emitted as they are; blocks taken from the saver's text bring their |
| + own source and seams; only a seam where the two sides meet is |
| + re-joined with one blank line (a tight list stays tight). If the |
| + result would not parse back to the settled blocks, the whole body is |
| + re-joined that way instead. Resolve's chosen text settles the same |
| + way. |
| 24. **A conflict offers Yours, Theirs, or Both (yours first)** for each |
| block both people changed. With no merge base, it is Yours or Theirs |
| whole. Choosing only what is saved now discards the draft and commits |
diff --git a/docs/superpowers/specs/2026-11-14-mapa-level-up.md b/docs/superpowers/specs/2026-11-14-mapa-level-up.md| index 7760796..be4ad28 100644 |
| --- a/docs/superpowers/specs/2026-11-14-mapa-level-up.md |
| +++ b/docs/superpowers/specs/2026-11-14-mapa-level-up.md |
| @@ -1068,6 +1068,21 @@ Phase 1's choices where this spec was silent, or where the build chose different |
| 20. **The gate-7 walk had a race,** which the level-up's slower pages exposed: ⌘K could show the answer to "Acm" before "Acme". The walk now waits for the whole word's Create row, and so does the new palette test. |
| 21. **Help has no Colophon yet.** Paul's rule asks every app for one; it waits for Phase 2, when the bundle is loaded and its packages are what the page runs. |
| +**Phase 2, the server's half** (steps 2 to 5 and 7's server changes, §8): |
| + |
| +22. **`Settle`'s seams** (§6.4, D13). Two blocks that were neighbours in mine keep mine's bytes between them, as theirs' do; only a seam where the sides meet follows `Join`. Theirs' leading bytes are kept when its first block comes first. A block both sides changed the same way is taken from theirs. The structure check compares each block's kind, level, list kind and source. |
| +23. **The autosave reply** is `{version, revision, merge?}`, every revision and version as text (they are int63s). `merge` is `{against, body}`, `{against, conflict: true, hunks: [{at, count, base, mine, theirs}]}`, `{noBase: true}` or `{gone: true}`; `at` and `count` are block positions in the text the request carried, and `base`, `mine` and `theirs` each side's exact bytes from the hunk's first block to its last. `revision` is left out for an unwritten day and a deleted page. |
| +24. **`rebase=R`** writes the request's `body` as the draft too. With no draft, to a revision of another page, past the window, or on a deleted page it answers 422 `{refused: "rebase"}`; a stale version is the existing 409. Nothing moves. Every draft write is now compare-and-swap on the version it read, so two tabs racing cannot both win. |
| +25. **`commit=1`** answers as Save does. Version 0 with a body is a tab that never autosaved: its text becomes the draft and is committed. Version 0 with no body is refused (409). |
| +26. **A save that changes nothing** reports the outcome it computed: a `Merged` result equal to the current body still answers `merged` with the body, so the tab takes the teammate's text. From a stale tab it is `Kept`. The draft is dropped only if it is still the version the tab held. Restore still mints a revision: it is its own verb. |
| +27. **Resolve's JSON** `outcome` is `saved`, `merged`, `conflicted`, `noBase` or `kept`. A choice that no longer fits (another revision landed, the draft changed, a choice missing) answers `conflicted` with the current `revision` and `body`; no draft at all is the 404 it was. |
| +28. **Make team page's `revision`** is required: none is stale. The refusal asks the person to choose again. |
| +29. **The first scratch commit (D12) is keyed by a token**, `first=<16–64 of [A-Za-z0-9_-]>` on `POST /scratch`, which the tab draws once for the new page and sends until it learns the page's address. The server keeps (person, token) → page in memory only, for 10 minutes and at most 4,096 at once, and runs the whole create-or-look-up under one lock. So the first request creates the page and answers `{href, page, revision}`; any later one with the token is an autosave of a draft on that page, answered like any autosave plus `{href, page}`; an empty body is 422 `{empty: true}` and creates nothing. Nothing new is stored, so §4 is unchanged. The version check could not key it, because no draft row exists before the page. A token forgotten (past 10 minutes, or across a restart or a CARLOS swap) makes a second page; only a tab still sending its first token that late meets it. |
| +30. **The island** is on `/p/{id}` (and `/p/{id}/history`, the current page with the panel), `/` and `/d/{date}` written or not, and `/scratch/new`. Its `base` is the page's current revision, `"0"` for a day or page not written yet; `draft.base` is the draft's own. Link keys are the target as typed, with `#^id` for a block. A date's `title` is the day in words; a pending link's is empty. `?saved=1` and a day re-shown after a refused Save carry none: neither is the text the draft continues. |
| +31. **`POST /links/resolve`** takes form fields `target`, each a link key (anything after `|` is ignored). Over 32 is 422 `{refused: "too many"}`. The answer is keyed by each key as sent; a key with no target is left out. |
| +32. **The draft bar** says "You're seeing the saved version" under `?saved=1`, with "Show your unsaved version". "Show the saved version" is left off where nothing is saved yet (an unwritten day) and in the Markdown editor. |
| +33. **Gate 1 compares the island's revisions as one value.** Revisions are random in both worlds (doctrine §6.6), so they cannot say anything about Ana's notes; the history scope test already did the same for history links. |
| + |
| ## 14. Findings and what changed |
| ### Round 1: Fable on revision 1 (`4027e10`), answered in revision 2 |
diff --git a/internal/mapa/app.go b/internal/mapa/app.go| index cec72e3..7ec154a 100644 |
| --- a/internal/mapa/app.go |
| +++ b/internal/mapa/app.go |
| @@ -28,6 +28,8 @@ type app struct { |
| auth *auth.Auth |
| logger *slog.Logger |
| routes chi.Router |
| + // firsts is the new scratch pages' first-commit tokens (D12). |
| + firsts firsts |
| // testIdentity and allowUnauthenticated let a test act as a person |
| // without a magic-link round trip. Only AppForTest sets them. |
| testIdentity string |
diff --git a/internal/mapa/around.go b/internal/mapa/around.go| index c35d781..e15cae9 100644 |
| --- a/internal/mapa/around.go |
| +++ b/internal/mapa/around.go |
| @@ -186,3 +186,39 @@ func (view scoped) around(page *entry, backlinks, |
| ring := view.mapNeighbours(page, backlinks, mentions) |
| return &Around{Out: view.linksOut(page), Map: view.mapOf(page, ring)} |
| } |
| + |
| +// LinkState is one chip's state for the editor (level-up §6.8): its |
| +// kind (team, pending, date, block, "block gone" or broken), where it |
| +// leads, and the current title of the team page it names, or the day |
| +// in words. |
| +type LinkState struct { |
| + Kind string `json:"kind"` |
| + Href string `json:"href"` |
| + Title string `json:"title"` |
| +} |
| + |
| +// linkState is where a [[link]] leads for this scope, as a chip draws |
| +// it. Like target, it reads team titles and the scope's own days only. |
| +func (view scoped) linkState(target, anchor string) LinkState { |
| + if markup.IsDateShaped(target) { |
| + if !markup.IsDate(target) { |
| + return LinkState{Kind: "broken"} |
| + } |
| + return LinkState{Kind: "date", Href: "/d/" + target, |
| + Title: markup.DayLabel(target, thisYear())} |
| + } |
| + page := view.target(target) |
| + if page == nil { |
| + return LinkState{Kind: "pending", Href: pendingHref(target)} |
| + } |
| + state := LinkState{Kind: "team", Href: page.href(), |
| + Title: page.record.Title} |
| + switch { |
| + case anchor == "": |
| + case page.hasMarker(anchor): |
| + state.Kind, state.Href = "block", state.Href+"#b-"+anchor |
| + default: |
| + state.Kind = "block gone" |
| + } |
| + return state |
| +} |
diff --git a/internal/mapa/autosave.go b/internal/mapa/autosave.go| new file mode 100644 |
| index 0000000..2806be9 |
| --- /dev/null |
| +++ b/internal/mapa/autosave.go |
| @@ -0,0 +1,128 @@ |
| +package mapa |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + |
| + "gorm.io/gorm" |
| + |
| + "amadan.net/oficina/mapa/internal/mapa/markup" |
| +) |
| + |
| +// The editor's autosave (level-up §6.5). An autosave writes the |
| +// person's draft and nothing else, and its reply tells the editor |
| +// whether a teammate's revision landed since the draft's base: the |
| +// merge of exactly the text the request carried. A rebase moves an |
| +// existing draft's base once the editor has taken that merge in. Every |
| +// write here is a draft write, exempt from gate 8 by name (§5). |
| + |
| +// DraftWrite is one autosave: the base a new draft starts from, the |
| +// draft version the tab holds (0 for none), and its text. Rebase, when |
| +// set, moves an existing draft's base to that revision of its page. |
| +type DraftWrite struct { |
| + Base, Version int64 |
| + Body string |
| + Rebase int64 |
| +} |
| + |
| +// ErrRebase is a rebase the store refuses: no draft to move, or a |
| +// revision that is not this page's inside the history window. Nothing |
| +// is written. |
| +var ErrRebase = errors.New("mapa: that is not a revision of this page") |
| + |
| +// Autosaved is an autosave's answer: the draft's new version, the |
| +// page's current revision (0 for an unwritten day or a deleted page), |
| +// and Behind when the draft's base is not that revision. |
| +type Autosaved struct { |
| + Version, Revision int64 |
| + Behind *Behind |
| +} |
| + |
| +// Behind is the merge an autosave's reply carries (level-up §6.5): a |
| +// clean merge's body, a conflict's hunks, no merge base, or a page that |
| +// was deleted. |
| +type Behind struct { |
| + Against int64 |
| + Body string |
| + Conflict bool |
| + Hunks []markup.Hunk |
| + NoBase bool |
| + Gone bool |
| +} |
| + |
| +// Autosave writes the draft and says how it stands against the page. |
| +func (store *Store) Autosave(ctx context.Context, viewer Viewer, |
| + key DraftKey, write DraftWrite) (Autosaved, error) { |
| + row, err := store.saveDraft(ctx, viewer.Address, key, write) |
| + if err != nil { |
| + return Autosaved{}, err |
| + } |
| + saved := Autosaved{Version: row.Version} |
| + if key.PageID == 0 { |
| + return saved, nil |
| + } |
| + viewer.MemberID = row.PersonID |
| + page, err := store.readable(ctx, viewer, key.PageID) |
| + if errors.Is(err, ErrNotFound) { |
| + saved.Behind = &Behind{Gone: true} |
| + return saved, nil |
| + } |
| + if err != nil || row.BaseRevision == page.Revision { |
| + saved.Revision = page.Revision |
| + return saved, err |
| + } |
| + saved.Revision = page.Revision |
| + saved.Behind, err = store.behind(ctx, page, row.BaseRevision, |
| + cleanBody(write.Body)) |
| + return saved, err |
| +} |
| + |
| +// behind merges sent, the text an autosave carried, from base over the |
| +// page's current revision. |
| +func (store *Store) behind(ctx context.Context, page Page, base int64, |
| + sent string) (*Behind, error) { |
| + original, found, err := store.baseBody(ctx, page.ID, base) |
| + if err != nil { |
| + return nil, err |
| + } |
| + if !found { |
| + return &Behind{NoBase: true}, nil |
| + } |
| + current, err := store.OpenPage(page) |
| + if err != nil { |
| + return nil, err |
| + } |
| + hunks, clean := markup.Merge3(original, sent, current.Body) |
| + out := &Behind{Against: page.Revision} |
| + if !clean { |
| + out.Conflict, out.Hunks = true, hunks |
| + return out, nil |
| + } |
| + merged, _ := markup.Settle(hunks, nil) |
| + out.Body = cleanBody(merged) |
| + return out, nil |
| +} |
| + |
| +// rebaseTo moves an existing draft's base to revision, which must be a |
| +// revision of the draft's own live page inside the history window. |
| +func (store *Store) rebaseTo(database *gorm.DB, row *Draft, found bool, |
| + key DraftKey, revision int64) error { |
| + if !found || key.PageID == 0 { |
| + return ErrRebase |
| + } |
| + var held int64 |
| + err := database.Model(&Revision{}). |
| + Joins("JOIN pages ON pages.id = revisions.page_id"). |
| + Where("revisions.page_id = ? AND revisions.revision = ? AND "+ |
| + "revisions.at > ? AND pages.gone = ?", key.PageID, revision, |
| + store.now().UTC().Add(-HistoryWindow), false). |
| + Count(&held).Error |
| + if err != nil { |
| + return err |
| + } |
| + if held == 0 { |
| + return ErrRebase |
| + } |
| + row.BaseRevision = revision |
| + return nil |
| +} |
diff --git a/internal/mapa/commit.go b/internal/mapa/commit.go| index 4941cdb..7ac9808 100644 |
| --- a/internal/mapa/commit.go |
| +++ b/internal/mapa/commit.go |
| @@ -69,6 +69,9 @@ func (store *Store) CommitFrom(ctx context.Context, who string, pageID, |
| record.Body); err != nil { |
| return err |
| } |
| + if body == record.Body { |
| + return errNoChange |
| + } |
| record.Body = body |
| if stale { |
| outcome = Kept |
| @@ -77,10 +80,25 @@ func (store *Store) CommitFrom(ctx context.Context, who string, pageID, |
| } |
| return tx.commit(&page, record, actor, VerbEdited) |
| }) |
| - if errors.Is(err, errUnmerged) && stale { |
| + return store.afterCommitFrom(ctx, who, pageID, base, held, body, |
| + outcome, stale, err) |
| +} |
| + |
| +// afterCommitFrom finishes a commit outside its transaction: a save |
| +// that could not merge keeps its text as the draft, and one that changed |
| +// nothing drops the draft the tab held, writing no revision and no |
| +// event (level-up §6.4, step 7). |
| +func (store *Store) afterCommitFrom(ctx context.Context, who string, |
| + pageID, base, held int64, body string, outcome Outcome, stale bool, |
| + err error) (Outcome, error) { |
| + switch { |
| + case errors.Is(err, errNoChange) && stale: |
| + return Kept, nil |
| + case errors.Is(err, errNoChange): |
| + return outcome, store.dropHeldDraft(ctx, who, pageID, held) |
| + case errors.Is(err, errUnmerged) && stale: |
| return outcome, ErrStaleTab |
| - } |
| - if errors.Is(err, errUnmerged) { |
| + case errors.Is(err, errUnmerged): |
| return outcome, store.keepDraft(ctx, who, pageID, base, body) |
| } |
| return outcome, err |
| @@ -136,7 +154,7 @@ func (tx *Tx) merged(page Page, base int64, mine, |
| return Conflicted, mine, errUnmerged |
| } |
| settled, _ := markup.Settle(hunks, nil) |
| - return Merged, settled, nil |
| + return Merged, cleanBody(settled), nil |
| } |
| // Resolve settles a conflict the person has chosen through: it commits |
| @@ -160,14 +178,20 @@ func (store *Store) Resolve(ctx context.Context, who string, pageID, |
| outcome = Conflicted |
| return errUnmerged |
| } |
| + if cleanBody(body) == record.Body { |
| + return errNoChange |
| + } |
| record.Body = cleanBody(body) |
| if err := tx.dropDraft(actor, page.ID); err != nil { |
| return err |
| } |
| return tx.commit(&page, record, actor, VerbEdited) |
| }) |
| - if errors.Is(err, errUnmerged) { |
| + switch { |
| + case errors.Is(err, errUnmerged): |
| return outcome, nil |
| + case errors.Is(err, errNoChange): |
| + return outcome, store.dropHeldDraft(ctx, who, pageID, held) |
| } |
| return outcome, err |
| } |
diff --git a/internal/mapa/daily.go b/internal/mapa/daily.go| index 0f970a4..abb71f6 100644 |
| --- a/internal/mapa/daily.go |
| +++ b/internal/mapa/daily.go |
| @@ -104,12 +104,29 @@ func (store *Store) SaveDailyFrom(ctx context.Context, who, date string, |
| if page.Revision != baseRevision { |
| return ErrStale |
| } |
| - return tx.commit(&page, Record{Date: date, Body: body}, actor, |
| - VerbEdited) |
| + return tx.commitDay(&page, actor, date, body) |
| }) |
| + if errors.Is(err, errNoChange) { |
| + return page, nil |
| + } |
| return page, err |
| } |
| +// commitDay commits a written day's note, unless the body is already |
| +// what it says: a save that changes nothing writes nothing (level-up |
| +// §6.4, step 7). |
| +func (tx *Tx) commitDay(page *Page, actor int64, date, body string) error { |
| + current, err := tx.store.OpenPage(*page) |
| + if err != nil { |
| + return err |
| + } |
| + if current.Body == body { |
| + return errNoChange |
| + } |
| + return tx.commit(page, Record{Date: date, Body: body}, actor, |
| + VerbEdited) |
| +} |
| + |
| func (tx *Tx) newDaily(actor int64, date string, baseRevision, held int64, |
| body string) (Page, error) { |
| if baseRevision != 0 { |
diff --git a/internal/mapa/daily_test.go b/internal/mapa/daily_test.go| index 1e9df37..79b6530 100644 |
| --- a/internal/mapa/daily_test.go |
| +++ b/internal/mapa/daily_test.go |
| @@ -79,7 +79,8 @@ func TestMakeTeamPageMovesTheChosenBlocksOnly(t *testing.T) { |
| note, _ := store.SaveDaily(ctx(), ana, "2026-11-12", 0, |
| "Private thought.\n\n- Acme renews in March\n- Ask Tom\n\nMore.") |
| before := loadPage(t, store, note.ID) |
| - shared, err := store.MakeTeamPage(ctx(), ana, note.ID, []int{1, 2}, |
| + shared, err := store.MakeTeamPage(ctx(), ana, note.ID, |
| + note.Revision, []int{1, 2}, |
| "Acme renewal") |
| if err != nil { |
| t.Fatal(err) |
| @@ -112,12 +113,14 @@ func TestGate2MakeTeamPageRefusesTakenAndDateTitles(t *testing.T) { |
| before := counts(t, store) |
| for title, want := range map[string]error{"ACME": ErrTitleTaken, |
| "2026-11-13": ErrTitleDate, "2026-11-13": ErrTitleDate} { |
| - if _, err := store.MakeTeamPage(ctx(), ana, note.ID, []int{0}, |
| + if _, err := store.MakeTeamPage(ctx(), ana, note.ID, |
| + note.Revision, []int{0}, |
| title); !errors.Is(err, want) { |
| t.Errorf("%q: %v", title, err) |
| } |
| } |
| - if _, err := store.MakeTeamPage(ctx(), ana, note.ID, nil, |
| + if _, err := store.MakeTeamPage(ctx(), ana, note.ID, |
| + note.Revision, nil, |
| "Fresh"); !errors.Is(err, ErrNothingChosen) { |
| t.Errorf("nothing chosen: %v", err) |
| } |
| @@ -130,12 +133,14 @@ func TestGate2MakeTeamPageRefusesTakenAndDateTitles(t *testing.T) { |
| func TestOnlyTheOwnerSharesAndOnlyPrivateNotes(t *testing.T) { |
| store := testStore(t) |
| note, _ := store.SaveDaily(ctx(), ana, "2026-11-12", 0, "a") |
| - if _, err := store.MakeTeamPage(ctx(), bo, note.ID, []int{0}, |
| + if _, err := store.MakeTeamPage(ctx(), bo, note.ID, |
| + note.Revision, []int{0}, |
| "Stolen"); !errors.Is(err, ErrNotFound) { |
| t.Fatalf("Bo shared Ana's note: %v", err) |
| } |
| team := mustCreate(t, store, "Team", "x") |
| - if _, err := store.MakeTeamPage(ctx(), ana, team.ID, []int{0}, |
| + if _, err := store.MakeTeamPage(ctx(), ana, team.ID, |
| + team.Revision, []int{0}, |
| "Again"); !errors.Is(err, ErrNotFound) { |
| t.Fatalf("a team page was shared again: %v", err) |
| } |
diff --git a/internal/mapa/drafts.go b/internal/mapa/drafts.go| index 6d4dc74..ff17313 100644 |
| --- a/internal/mapa/drafts.go |
| +++ b/internal/mapa/drafts.go |
| @@ -84,32 +84,53 @@ func (store *Store) OwnDraft(ctx context.Context, viewer Viewer, |
| // for none; a mismatch is ErrStaleTab. It returns the new version. |
| func (store *Store) SaveDraft(ctx context.Context, who string, |
| key DraftKey, base, version int64, body string) (int64, error) { |
| + row, err := store.saveDraft(ctx, who, key, DraftWrite{Base: base, |
| + Version: version, Body: body}) |
| + return row.Version, err |
| +} |
| + |
| +// saveDraft writes one autosave and returns the draft as stored. A |
| +// rebase moves an existing draft's base first (rebase.go). |
| +func (store *Store) saveDraft(ctx context.Context, who string, |
| + key DraftKey, write DraftWrite) (Draft, error) { |
| person, err := store.ensureMember(ctx, who) |
| if err != nil { |
| - return 0, err |
| + return Draft{}, err |
| } |
| database := store.database.WithContext(ctx) |
| row, found, err := store.draftRow(database, person, key) |
| if err != nil { |
| - return 0, err |
| + return row, err |
| } |
| - if (found && row.Version != version) || (!found && version != 0) { |
| - return 0, ErrStaleTab |
| + if (found && row.Version != write.Version) || |
| + (!found && write.Version != 0) { |
| + return row, ErrStaleTab |
| } |
| if !found { |
| - row = Draft{PersonID: person, BaseRevision: base} |
| + row = Draft{PersonID: person, BaseRevision: write.Base} |
| } |
| - return store.writeDraft(database, row, key, cleanBody(body)) |
| + if write.Rebase != 0 { |
| + if err := store.rebaseTo(database, &row, found, key, |
| + write.Rebase); err != nil { |
| + return row, err |
| + } |
| + } |
| + row.Version, err = store.writeDraft(database, row, key, |
| + cleanBody(write.Body)) |
| + return row, err |
| } |
| -// writeDraft stores a draft's text under a fresh version. No event: this |
| -// is the exemption. |
| +// writeDraft stores a draft's text and base under a fresh version. An |
| +// existing row is written only if it still holds the version it was |
| +// read with: a write another tab made in between is never lost, and |
| +// this one is ErrStaleTab. No event: this is the exemption. |
| func (store *Store) writeDraft(database *gorm.DB, row Draft, key DraftKey, |
| body string) (int64, error) { |
| sealed, err := store.sealRecord(seal.PurposeDraft, Record{Body: body}) |
| if err != nil { |
| return 0, err |
| } |
| + held := row.Version |
| if row.Version, err = randomPositive(); err != nil { |
| return 0, err |
| } |
| @@ -120,8 +141,13 @@ func (store *Store) writeDraft(database *gorm.DB, row Draft, key DraftKey, |
| } |
| return row.Version, database.Create(&row).Error |
| } |
| - return row.Version, database.Model(&row).Select("Version", |
| - "SealedRecord", "UpdatedAt").Updates(&row).Error |
| + written := database.Model(&row).Where("version = ?", held). |
| + Select("Version", "SealedRecord", "UpdatedAt", "BaseRevision"). |
| + Updates(&row) |
| + if written.Error == nil && written.RowsAffected == 0 { |
| + return 0, ErrStaleTab |
| + } |
| + return row.Version, written.Error |
| } |
| func (store *Store) keyDraft(row *Draft, key DraftKey) error { |
| @@ -152,12 +178,6 @@ func (store *Store) keepDraft(ctx context.Context, who string, pageID, |
| row = Draft{PersonID: person} |
| } |
| row.BaseRevision = base |
| - if found { |
| - err = database.Model(&row).Update("base_revision", base).Error |
| - } |
| - if err != nil { |
| - return err |
| - } |
| _, err = store.writeDraft(database, row, key, body) |
| return err |
| } |
| @@ -179,6 +199,20 @@ func (store *Store) DiscardDraft(ctx context.Context, viewer Viewer, |
| return database.Delete(&row).Error |
| } |
| +// dropHeldDraft removes the person's draft on a page if it is still the |
| +// version the tab held: a commit that changed nothing ends the draft as |
| +// a commit would, and never a newer one another tab wrote. No event. |
| +func (store *Store) dropHeldDraft(ctx context.Context, who string, |
| + pageID, held int64) error { |
| + viewer, err := store.Viewer(ctx, who, nil) |
| + if err != nil || viewer.MemberID == 0 || held == 0 { |
| + return err |
| + } |
| + return store.database.WithContext(ctx).Where("person_id = ? AND "+ |
| + "page_id = ? AND version = ?", viewer.MemberID, pageID, held). |
| + Delete(&Draft{}).Error |
| +} |
| + |
| // dropDraft removes the person's draft for a page inside a commit. |
| func (tx *Tx) dropDraft(person, pageID int64) error { |
| return tx.db.Where("person_id = ? AND page_id = ?", person, pageID). |
diff --git a/internal/mapa/firstscratch.go b/internal/mapa/firstscratch.go| new file mode 100644 |
| index 0000000..27339a9 |
| --- /dev/null |
| +++ b/internal/mapa/firstscratch.go |
| @@ -0,0 +1,125 @@ |
| +package mapa |
| + |
| +import ( |
| + "errors" |
| + "net/http" |
| + "regexp" |
| + "sync" |
| + "time" |
| +) |
| + |
| +// A new scratch page's first commit (level-up §6.5, D12). The editor on |
| +// New scratch page has no Save button, so its first autosave is the |
| +// save: a commit that creates the page, refused when empty (ErrEmpty), |
| +// and single-flight, so two quick autosaves create one page. |
| +// |
| +// The key is a token the tab draws once for the new page and sends as |
| +// "first" with every autosave until it learns the page's address. It is |
| +// held only here, in memory, for firstHold: never in the database, so |
| +// §4's plaintext list is unchanged. The first request with a token |
| +// creates the page; any later one with the same token, from the same |
| +// person, waits for it and is an autosave of a draft on that page |
| +// instead. A token forgotten (past firstHold, or by a restart) is a new |
| +// page, which only a tab that kept sending it for that long could meet. |
| + |
| +// firstHold is how long a token is remembered. |
| +const firstHold = 10 * time.Minute |
| + |
| +// firstCap bounds how many tokens are remembered at once. |
| +const firstCap = 4096 |
| + |
| +var firstToken = regexp.MustCompile(`^[A-Za-z0-9_-]{16,64}$`) |
| + |
| +// firsts remembers which scratch page each first-commit token made. |
| +type firsts struct { |
| + mutex sync.Mutex |
| + made map[string]firstMade |
| +} |
| + |
| +type firstMade struct { |
| + pageID, revision int64 |
| + public string |
| + at time.Time |
| +} |
| + |
| +// recall is the page a token made, forgetting tokens past firstHold. |
| +// The caller holds the mutex. |
| +func (held *firsts) recall(key string, now time.Time) (firstMade, bool) { |
| + if held.made == nil { |
| + held.made = map[string]firstMade{} |
| + } |
| + for other, made := range held.made { |
| + if now.Sub(made.at) > firstHold { |
| + delete(held.made, other) |
| + } |
| + } |
| + made, ok := held.made[key] |
| + return made, ok |
| +} |
| + |
| +func (held *firsts) remember(key string, made firstMade) { |
| + if len(held.made) < firstCap { |
| + held.made[key] = made |
| + } |
| +} |
| + |
| +// firstScratch is POST /scratch with a "first" token: the new page's |
| +// first autosave. It answers JSON: {href, page, revision} when it made |
| +// the page; when the page was already made, this is an autosave of a |
| +// draft on it, answered {href, page, version, revision, merge?}; and |
| +// 422 {empty: true} when there is nothing to save. |
| +func (app *app) firstScratch(writer http.ResponseWriter, |
| + request *http.Request, token string) { |
| + viewer, err := app.viewer(request) |
| + if err != nil || !firstToken.MatchString(token) { |
| + notFound(writer, request) |
| + return |
| + } |
| + key := viewer.Address + "\x00" + token |
| + app.firsts.mutex.Lock() |
| + defer app.firsts.mutex.Unlock() |
| + made, ok := app.firsts.recall(key, app.store.now()) |
| + if ok { |
| + app.firstDraft(writer, request, viewer, made) |
| + return |
| + } |
| + page, err := app.store.CreateScratch(request.Context(), viewer.Address, |
| + request.PostFormValue("body")) |
| + if errors.Is(err, ErrEmpty) { |
| + writer.Header().Set("Content-Type", "application/json; charset=utf-8") |
| + writer.WriteHeader(http.StatusUnprocessableEntity) |
| + answer(writer, map[string]any{"empty": true}) |
| + return |
| + } |
| + if err != nil { |
| + app.fail(writer, request, err) |
| + return |
| + } |
| + made = firstMade{pageID: page.ID, revision: page.Revision, |
| + public: publicID(page.Nonce), at: app.store.now()} |
| + app.firsts.remember(key, made) |
| + answer(writer, map[string]any{"href": PagePath(page), |
| + "page": made.public, "revision": idText(page.Revision)}) |
| +} |
| + |
| +// firstDraft is a later autosave carrying a token whose page exists: a |
| +// draft on that page, based on its first revision, answered as any |
| +// autosave is, with the page's address. |
| +func (app *app) firstDraft(writer http.ResponseWriter, |
| + request *http.Request, viewer Viewer, made firstMade) { |
| + key := DraftKey{PageID: made.pageID} |
| + saved, err := app.store.Autosave(request.Context(), viewer, key, |
| + DraftWrite{Base: made.revision, Version: formInt(request, "version"), |
| + Body: request.PostFormValue("body")}) |
| + if errors.Is(err, ErrStaleTab) { |
| + app.staleTab(writer, request, key) |
| + return |
| + } |
| + if err != nil { |
| + app.fail(writer, request, err) |
| + return |
| + } |
| + reply := autosaveReply(saved) |
| + reply["href"], reply["page"] = "/p/"+made.public, made.public |
| + answer(writer, reply) |
| +} |
diff --git a/internal/mapa/handlers_autosave.go b/internal/mapa/handlers_autosave.go| new file mode 100644 |
| index 0000000..b33706a |
| --- /dev/null |
| +++ b/internal/mapa/handlers_autosave.go |
| @@ -0,0 +1,146 @@ |
| +package mapa |
| + |
| +import ( |
| + "errors" |
| + "net/http" |
| + "strconv" |
| + |
| + "amadan.net/oficina/mapa/internal/mapa/markup" |
| +) |
| + |
| +// POST …/draft, the editor's autosave (level-up §6.5, §8). With base, |
| +// version and body it writes the person's draft and answers |
| +// |
| +// {version, revision, merge?} |
| +// |
| +// where merge, present when the draft's base is not the page's current |
| +// revision, is computed over exactly the text this request carried: |
| +// |
| +// {against, body} the merge is clean |
| +// {against, conflict: true, hunks} each {at, count, base, mine, theirs} |
| +// {noBase: true} the base is past the window |
| +// {gone: true} the page was deleted |
| +// |
| +// rebase=R also moves an existing draft's base to R, if version is |
| +// current and R is a revision of this page inside the window; anything |
| +// else is refused (409 stale, 422 {refused: "rebase"}) and moves |
| +// nothing. commit=1 writes the draft (when body is sent) and commits it |
| +// in one request, only from the current version. It never touches the |
| +// page or its revision except through that commit (gate 11). |
| + |
| +func (app *app) autosave(writer http.ResponseWriter, request *http.Request) { |
| + viewer, err := app.viewer(request) |
| + key, ok := app.draftKey(request, viewer) |
| + if err != nil || !ok || !app.mayDraft(request, viewer, key) { |
| + notFound(writer, request) |
| + return |
| + } |
| + if request.PostFormValue("commit") == "1" { |
| + app.commitNow(writer, request, viewer, key) |
| + return |
| + } |
| + saved, err := app.store.Autosave(request.Context(), viewer, key, |
| + DraftWrite{Base: formInt(request, "base"), |
| + Version: formInt(request, "version"), |
| + Body: request.PostFormValue("body"), |
| + Rebase: formInt(request, "rebase")}) |
| + switch { |
| + case errors.Is(err, ErrStaleTab): |
| + app.staleTab(writer, request, key) |
| + case errors.Is(err, ErrRebase): |
| + refuseJSON(writer, http.StatusUnprocessableEntity, "rebase") |
| + case err != nil: |
| + app.fail(writer, request, err) |
| + default: |
| + answer(writer, autosaveReply(saved)) |
| + } |
| +} |
| + |
| +// refuseJSON answers the script that nothing was done, and why. |
| +func refuseJSON(writer http.ResponseWriter, status int, why string) { |
| + writer.Header().Set("Content-Type", "application/json; charset=utf-8") |
| + writer.Header().Set("Cache-Control", "no-store") |
| + writer.WriteHeader(status) |
| + answer(writer, map[string]any{"refused": why}) |
| +} |
| + |
| +// autosaveReply is an autosave's JSON. Revisions and versions are |
| +// int63s, past what a JavaScript number holds, so they travel as text. |
| +func autosaveReply(saved Autosaved) map[string]any { |
| + reply := map[string]any{"version": idText(saved.Version)} |
| + if saved.Revision != 0 { |
| + reply["revision"] = idText(saved.Revision) |
| + } |
| + if saved.Behind != nil { |
| + reply["merge"] = mergeReply(*saved.Behind) |
| + } |
| + return reply |
| +} |
| + |
| +func mergeReply(behind Behind) map[string]any { |
| + switch { |
| + case behind.Gone: |
| + return map[string]any{"gone": true} |
| + case behind.NoBase: |
| + return map[string]any{"noBase": true} |
| + case !behind.Conflict: |
| + return map[string]any{"against": idText(behind.Against), |
| + "body": behind.Body} |
| + } |
| + return map[string]any{"against": idText(behind.Against), |
| + "conflict": true, "hunks": hunkReplies(behind.Hunks)} |
| +} |
| + |
| +// hunkReply is one conflicting hunk: at and count are its blocks in the |
| +// text the request carried, and base, mine and theirs the Markdown of |
| +// its three sides. |
| +type hunkReply struct { |
| + At int `json:"at"` |
| + Count int `json:"count"` |
| + Base string `json:"base"` |
| + Mine string `json:"mine"` |
| + Theirs string `json:"theirs"` |
| +} |
| + |
| +func hunkReplies(hunks []markup.Hunk) []hunkReply { |
| + out := []hunkReply{} |
| + for _, hunk := range hunks { |
| + if !hunk.Conflict { |
| + continue |
| + } |
| + base, mine, theirs := hunk.Sources() |
| + out = append(out, hunkReply{At: hunk.MineAt, Count: len(hunk.Mine), |
| + Base: base, Mine: mine, Theirs: theirs}) |
| + } |
| + return out |
| +} |
| + |
| +func idText(value int64) string { return strconv.FormatInt(value, 10) } |
| + |
| +// commitNow is commit=1: the closing tab's one keepalive POST (D3). It |
| +// writes the text it carries as the draft and commits it, only if |
| +// version is the current draft's; otherwise it writes and commits |
| +// nothing. Past the keepalive cap the tab sends no body, and the draft |
| +// as last autosaved is committed. |
| +func (app *app) commitNow(writer http.ResponseWriter, request *http.Request, |
| + viewer Viewer, key DraftKey) { |
| + version := formInt(request, "version") |
| + if _, sent := request.PostForm["body"]; sent { |
| + saved, err := app.store.SaveDraft(request.Context(), viewer.Address, |
| + key, formInt(request, "base"), version, |
| + request.PostFormValue("body")) |
| + if errors.Is(err, ErrStaleTab) { |
| + app.staleTab(writer, request, key) |
| + return |
| + } |
| + if err != nil { |
| + app.fail(writer, request, err) |
| + return |
| + } |
| + version = saved |
| + } else if version == 0 { |
| + app.staleTab(writer, request, key) |
| + return |
| + } |
| + app.commitDraft(writer, request, viewer, key, version) |
| +} |
diff --git a/internal/mapa/handlers_drafts.go b/internal/mapa/handlers_drafts.go| index 73ab7f2..a6d0b63 100644 |
| --- a/internal/mapa/handlers_drafts.go |
| +++ b/internal/mapa/handlers_drafts.go |
| @@ -44,31 +44,6 @@ func (app *app) draftKey(request *http.Request, |
| return DraftKey{Date: date}, err == nil |
| } |
| -// autosave writes the person's draft. It never touches the page, its |
| -// body or its revision (gate 11). A stale tab is told, with the newer |
| -// draft to load. |
| -func (app *app) autosave(writer http.ResponseWriter, request *http.Request) { |
| - viewer, err := app.viewer(request) |
| - key, ok := app.draftKey(request, viewer) |
| - if err != nil || !ok || !app.mayDraft(request, viewer, key) { |
| - notFound(writer, request) |
| - return |
| - } |
| - base := formInt(request, "base") |
| - version, err := app.store.SaveDraft(request.Context(), viewer.Address, |
| - key, base, formInt(request, "version"), |
| - request.PostFormValue("body")) |
| - if errors.Is(err, ErrStaleTab) { |
| - app.staleTab(writer, request, key) |
| - return |
| - } |
| - if err != nil { |
| - app.fail(writer, request, err) |
| - return |
| - } |
| - answer(writer, map[string]any{"version": strconv.FormatInt(version, 10)}) |
| -} |
| - |
| // mayDraft reports whether the viewer may touch a draft for the page: |
| // one they may open, or a deleted page they have a draft on. Anything |
| // else is answered as a page that is not there, so a page someone else |
| @@ -119,8 +94,14 @@ func (app *app) saveDraft(writer http.ResponseWriter, |
| notFound(writer, request) |
| return |
| } |
| + app.commitDraft(writer, request, viewer, key, formInt(request, "version")) |
| +} |
| + |
| +// commitDraft commits the viewer's draft at version and answers. |
| +func (app *app) commitDraft(writer http.ResponseWriter, |
| + request *http.Request, viewer Viewer, key DraftKey, version int64) { |
| outcome, pageID, err := app.store.CommitDraft(request.Context(), viewer, |
| - key, formInt(request, "version")) |
| + key, version) |
| switch { |
| case errors.Is(err, ErrStaleTab): |
| app.staleTab(writer, request, key) |
diff --git a/internal/mapa/handlers_edit.go b/internal/mapa/handlers_edit.go| index 4c8660f..01001a6 100644 |
| --- a/internal/mapa/handlers_edit.go |
| +++ b/internal/mapa/handlers_edit.go |
| @@ -172,7 +172,7 @@ func (app *app) resolve(writer http.ResponseWriter, request *http.Request) { |
| } |
| body, keep, err := app.chosen(request, viewer, page.ID) |
| if errors.Is(err, errUnchosen) { |
| - seeOther(writer, request, pageHref(page.Public, "")+"/conflict") |
| + app.afterResolve(writer, request, page, Conflicted, nil) |
| return |
| } |
| if err != nil { |
| @@ -214,11 +214,46 @@ func (app *app) linkMention(writer http.ResponseWriter, |
| seeOther(writer, request, pageHref(target.Public, "linked")) |
| } |
| +// afterResolve answers a choice: the form is sent on to the page, or to |
| +// the conflict again; the editor, asking for JSON, gets |
| +// {outcome, revision, body}, the page as it now stands (level-up §6.5). |
| func (app *app) afterResolve(writer http.ResponseWriter, |
| request *http.Request, page PageView, outcome Outcome, err error) { |
| if err != nil { |
| app.refuse(writer, request, err) |
| return |
| } |
| - seeOther(writer, request, afterSave(page.Href, page.Public, outcome)) |
| + if !wantsJSON(request) { |
| + seeOther(writer, request, afterSave(page.Href, page.Public, outcome)) |
| + return |
| + } |
| + viewer, err := app.viewer(request) |
| + current := page |
| + if err == nil { |
| + current, err = app.index.View(request.Context(), ScopeOf(viewer), |
| + page.ID) |
| + } |
| + if err != nil { |
| + app.refuse(writer, request, err) |
| + return |
| + } |
| + answer(writer, map[string]any{"outcome": outcomeName(outcome), |
| + "revision": idText(current.Revision), "body": current.Body}) |
| +} |
| + |
| +// outcomeName is an outcome as the script reads it. |
| +func outcomeName(outcome Outcome) string { |
| + switch outcome { |
| + case Saved: |
| + return "saved" |
| + case Merged: |
| + return "merged" |
| + case Conflicted: |
| + return "conflicted" |
| + case NoBase: |
| + return "noBase" |
| + case Kept: |
| + return "kept" |
| + } |
| + return "" |
| } |
diff --git a/internal/mapa/handlers_pages.go b/internal/mapa/handlers_pages.go| index 18facc2..9586b36 100644 |
| --- a/internal/mapa/handlers_pages.go |
| +++ b/internal/mapa/handlers_pages.go |
| @@ -2,6 +2,7 @@ package mapa |
| import ( |
| "errors" |
| + "html/template" |
| "net/http" |
| "strconv" |
| @@ -82,12 +83,10 @@ func (app *app) showPage(writer http.ResponseWriter, |
| app.fail(writer, request, err) |
| return |
| } |
| - data := map[string]any{"Page": page, "Notice": notice(request)} |
| - draft, found, err := app.store.OwnDraft(request.Context(), viewer, |
| + state, err := app.editorFor(request, viewer, &page, |
| DraftKey{PageID: page.ID}) |
| - if found { |
| - data["Draft"] = draft |
| - } |
| + data := map[string]any{"Page": page, "Notice": notice(request), |
| + "Draft": state.Draft, "Saved": state.Saved, "Island": state.Island} |
| editing, editErr := app.store.Editing(request.Context(), viewer, page.ID) |
| if err = errors.Join(err, editErr); err != nil { |
| app.fail(writer, request, err) |
| @@ -126,6 +125,8 @@ type pageForm struct { |
| // this editor holds; empty for a page that does not exist yet. |
| Drafts string |
| Version int64 |
| + // Island is the editor's data (level-up §6.8), on New scratch page. |
| + Island template.JS |
| } |
| func (app *app) newPage(writer http.ResponseWriter, request *http.Request) { |
diff --git a/internal/mapa/handlers_search.go b/internal/mapa/handlers_search.go| index fdebf16..90f7160 100644 |
| --- a/internal/mapa/handlers_search.go |
| +++ b/internal/mapa/handlers_search.go |
| @@ -23,6 +23,7 @@ func (app *app) searchRoutes(router chi.Router) { |
| router.Get("/search", app.searchPage) |
| router.Get("/search/suggest", app.searchSuggest) |
| router.Get("/links/suggest", app.linkSuggest) |
| + router.Post("/links/resolve", app.resolveLinks) |
| } |
| func (app *app) searchPage(writer http.ResponseWriter, |
diff --git a/internal/mapa/island.go b/internal/mapa/island.go| new file mode 100644 |
| index 0000000..391285f |
| --- /dev/null |
| +++ b/internal/mapa/island.go |
| @@ -0,0 +1,190 @@ |
| +package mapa |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "html/template" |
| + "net/http" |
| + "strings" |
| + |
| + "amadan.net/oficina/mapa/internal/mapa/markup" |
| +) |
| + |
| +// What the editor is given (level-up §6.8). Every editable page carries |
| +// a JSON island, <script type="application/json" id="mapa-editor">, |
| +// holding the source the editor mounts over, the page's current |
| +// revision, the person's draft if they have one, and each link's chip |
| +// state under the viewer's scope. Chips typed after mount ask |
| +// POST /links/resolve. Both read through the scoped accessor |
| +// (around.go) and write nothing. |
| + |
| +// maxResolve is how many link targets one /links/resolve may ask for. |
| +const maxResolve = 32 |
| + |
| +// island is the editor's data, as JSON. Revisions and versions are |
| +// int63s, past what a JavaScript number holds, so they are text. |
| +type island struct { |
| + Source string `json:"source"` |
| + Base string `json:"base"` |
| + Draft *islandDraft `json:"draft"` |
| + Links map[string]LinkState `json:"links"` |
| +} |
| + |
| +type islandDraft struct { |
| + Version string `json:"version"` |
| + Base string `json:"base"` |
| +} |
| + |
| +// linkKey is how a link is named in the island and in /links/resolve: |
| +// its target as typed, with "#^id" when it names a block. |
| +func linkKey(target, anchor string) string { |
| + if anchor == "" { |
| + return target |
| + } |
| + return target + "#^" + anchor |
| +} |
| + |
| +// splitKey reads a link key back, by the parser's own rule for what |
| +// sits between [[ and ]] (markup's wikiSpan): "|" ends the target, "#^" |
| +// starts the anchor, and the target is trimmed. |
| +func splitKey(key string) (string, string, bool) { |
| + target, _, _ := strings.Cut(key, "|") |
| + target, anchor, _ := strings.Cut(target, "#") |
| + target = strings.TrimSpace(target) |
| + if !strings.HasPrefix(anchor, "^") { |
| + anchor = "" |
| + } else { |
| + anchor = strings.TrimSpace(anchor[1:]) |
| + } |
| + return target, anchor, target != "" |
| +} |
| + |
| +// LinkStates is each key's chip state for scope. |
| +func (index *Index) LinkStates(ctx context.Context, scope Scope, |
| + keys []string) (map[string]LinkState, error) { |
| + if err := index.Sync(ctx); err != nil { |
| + return nil, err |
| + } |
| + index.mutex.RLock() |
| + defer index.mutex.RUnlock() |
| + view := index.in(scope) |
| + out := make(map[string]LinkState, len(keys)) |
| + for _, key := range keys { |
| + if target, anchor, ok := splitKey(key); ok { |
| + out[key] = view.linkState(target, anchor) |
| + } |
| + } |
| + return out, nil |
| +} |
| + |
| +// islandFor is the island for a page the viewer may edit: source is the |
| +// text the page shows (the draft's, when there is one), revision the |
| +// page's current one (0 for a page or day not written yet). |
| +func (app *app) islandFor(ctx context.Context, viewer Viewer, |
| + source string, revision int64, draft *DraftView) (template.JS, error) { |
| + var keys []string |
| + for _, link := range markup.Links(source) { |
| + keys = append(keys, linkKey(link.Target, link.Anchor)) |
| + } |
| + links, err := app.index.LinkStates(ctx, ScopeOf(viewer), keys) |
| + if err != nil { |
| + return "", err |
| + } |
| + data := island{Source: source, Base: idText(revision), Links: links} |
| + if draft != nil { |
| + data.Draft = &islandDraft{Version: idText(draft.Version), |
| + Base: idText(draft.BaseRevision)} |
| + } |
| + // encoding/json escapes <, >, & and U+2028/9, so no body can end |
| + // the script element early or open a comment in it. |
| + encoded, err := json.Marshal(data) |
| + return template.JS(encoded), err |
| +} |
| + |
| +// resolveLinks is POST /links/resolve: up to maxResolve link keys in |
| +// the body, as "target" fields, answered as {key: {kind, href, title}}. |
| +// A POST so the targets travel in the body, not a URL that logs keep; |
| +// it writes nothing, like /preview. |
| +func (app *app) resolveLinks(writer http.ResponseWriter, |
| + request *http.Request) { |
| + viewer, err := app.viewer(request) |
| + if err == nil { |
| + err = request.ParseForm() |
| + } |
| + if err != nil { |
| + app.fail(writer, request, err) |
| + return |
| + } |
| + keys := request.PostForm["target"] |
| + if len(keys) > maxResolve { |
| + refuseJSON(writer, http.StatusUnprocessableEntity, "too many") |
| + return |
| + } |
| + states, err := app.index.LinkStates(request.Context(), ScopeOf(viewer), |
| + keys) |
| + if err != nil { |
| + app.fail(writer, request, err) |
| + return |
| + } |
| + answer(writer, states) |
| +} |
| + |
| +// editorState is what an editable page shows of the person's draft, |
| +// and its island. |
| +type editorState struct { |
| + Draft *DraftView |
| + // Saved is ?saved=1: the committed text, the draft still offered. |
| + Saved bool |
| + Island template.JS |
| +} |
| + |
| +// editorFor is a page's editor state for the viewer. A person with a |
| +// draft is shown the draft's text as the page body, so the editor |
| +// mounts over the markup it will edit (level-up §6.8); ?saved=1 shows |
| +// the committed text instead, and carries no island, since it is not |
| +// the text the draft continues. |
| +func (app *app) editorFor(request *http.Request, viewer Viewer, |
| + page *PageView, key DraftKey) (editorState, error) { |
| + ctx := request.Context() |
| + state := editorState{Saved: request.URL.Query().Get("saved") == "1"} |
| + draft, found, err := app.store.OwnDraft(ctx, viewer, key) |
| + if err != nil || (found && state.Saved) { |
| + state.Draft = pointerIf(found, draft) |
| + return state, err |
| + } |
| + if found { |
| + state.Draft = &draft |
| + page.Body = draft.Body |
| + page.HTML, err = app.index.Preview(ctx, ScopeOf(viewer), draft.Body) |
| + if err != nil { |
| + return state, err |
| + } |
| + } |
| + state.Island, err = app.islandFor(ctx, viewer, page.Body, |
| + page.Revision, state.Draft) |
| + return state, err |
| +} |
| + |
| +func pointerIf(found bool, draft DraftView) *DraftView { |
| + if !found { |
| + return nil |
| + } |
| + return &draft |
| +} |
| + |
| +// dayEditor is editorFor for a day: its note's, or an unwritten day's. |
| +// A day re-shown after a refused POST carries no island: its editor is |
| +// the textarea's, holding that tab's text. |
| +func (app *app) dayEditor(request *http.Request, viewer Viewer, |
| + data *dayData) error { |
| + if request.Method != http.MethodGet { |
| + return nil |
| + } |
| + key := DraftKey{Date: data.Page.Date} |
| + if data.Written { |
| + key = DraftKey{PageID: data.Page.ID} |
| + } |
| + state, err := app.editorFor(request, viewer, &data.Page, key) |
| + data.Saved, data.Island = state.Saved, state.Island |
| + return err |
| +} |
diff --git a/internal/mapa/markup/merge.go b/internal/mapa/markup/merge.go| index e7a7d0e..b3f4d4a 100644 |
| --- a/internal/mapa/markup/merge.go |
| +++ b/internal/mapa/markup/merge.go |
| @@ -8,31 +8,59 @@ package markup |
| // Hunk is one stretch of the merged body: settled blocks, or a conflict |
| // with both sides and what they started from. |
| type Hunk struct { |
| - Blocks []Block |
| - Conflict bool |
| - Base []Block |
| - Mine []Block |
| - Theirs []Block |
| + Blocks []Block |
| + // From and At place a settled hunk's blocks: the side they were |
| + // taken from, and the index of the first of them in that side. |
| + From Side |
| + At int |
| + // Conflict marks a hunk both sides changed. Base, Mine and Theirs |
| + // are its three sides, starting at BaseAt, MineAt and TheirAt. |
| + Conflict bool |
| + Base, Mine, Theirs []Block |
| + BaseAt, MineAt, TheirAt int |
| + // texts are the three bodies the hunk came from, shared by every |
| + // hunk of one merge, so Settle can keep their bytes (level-up §6.4). |
| + texts *sides |
| } |
| +// Side is which body a settled block was taken from. |
| +type Side int |
| + |
| +// The two sides a block can come from. A block both sides kept is |
| +// theirs: the current revision's bytes are the anchor. |
| +const ( |
| + FromTheirs Side = iota + 1 |
| + FromMine |
| +) |
| + |
| +// sides is one merge's three bodies, normalised, and their blocks. |
| +type sides struct { |
| + base, mine, theirs string |
| + baseBlocks, mineBlocks, theirsBlocks []Block |
| +} |
| + |
| +// cursor is a position in each of the three bodies' blocks. |
| +type cursor struct{ base, mine, theirs int } |
| + |
| // Merge3 merges mine and theirs, both edited from base. clean reports |
| // that no hunk is a conflict. |
| func Merge3(base, mine, theirs string) (hunks []Hunk, clean bool) { |
| - baseBlocks, mineBlocks, theirBlocks := Parse(base), Parse(mine), |
| - Parse(theirs) |
| - toMine := align(baseBlocks, mineBlocks) |
| - toTheirs := align(baseBlocks, theirBlocks) |
| + texts := &sides{base: normalise(base), mine: normalise(mine), |
| + theirs: normalise(theirs)} |
| + texts.baseBlocks, texts.mineBlocks, texts.theirsBlocks = |
| + Parse(texts.base), Parse(texts.mine), Parse(texts.theirs) |
| + toMine := align(texts.baseBlocks, texts.mineBlocks) |
| + toTheirs := align(texts.baseBlocks, texts.theirsBlocks) |
| clean = true |
| - at, mineAt, theirAt := 0, 0, 0 |
| + at := cursor{} |
| for { |
| - stable := nextStable(at, toMine, toTheirs) |
| - end, mineEnd, theirEnd := len(baseBlocks), len(mineBlocks), |
| - len(theirBlocks) |
| + stable := nextStable(at.base, toMine, toTheirs) |
| + end := cursor{len(texts.baseBlocks), len(texts.mineBlocks), |
| + len(texts.theirsBlocks)} |
| if stable >= 0 { |
| - end, mineEnd, theirEnd = stable, toMine[stable], toTheirs[stable] |
| + end = cursor{stable, toMine[stable], toTheirs[stable]} |
| } |
| - for _, hunk := range resolveStretch(baseBlocks[at:end], |
| - mineBlocks[mineAt:mineEnd], theirBlocks[theirAt:theirEnd]) { |
| + for _, hunk := range texts.resolveStretch(at, end) { |
| if hunk.Conflict || len(hunk.Blocks) > 0 { |
| hunks = append(hunks, hunk) |
| clean = clean && !hunk.Conflict |
| @@ -41,8 +69,8 @@ func Merge3(base, mine, theirs string) (hunks []Hunk, clean bool) { |
| if stable < 0 { |
| return hunks, clean |
| } |
| - hunks = append(hunks, Hunk{Blocks: baseBlocks[stable : stable+1]}) |
| - at, mineAt, theirAt = stable+1, toMine[stable]+1, toTheirs[stable]+1 |
| + hunks = append(hunks, texts.settled(FromTheirs, toTheirs[stable], 1)) |
| + at = cursor{stable + 1, toMine[stable] + 1, toTheirs[stable] + 1} |
| } |
| } |
| @@ -61,13 +89,17 @@ func nextStable(from int, toMine, toTheirs []int) int { |
| // hold the same number of blocks, each was edited in place, so each |
| // position is resolved on its own: Ana's edit to one block and Bo's to |
| // the next do not conflict just because they are neighbours. |
| -func resolveStretch(base, mine, theirs []Block) []Hunk { |
| - if len(base) < 2 || len(mine) != len(base) || len(theirs) != len(base) { |
| - return []Hunk{resolve(base, mine, theirs)} |
| +func (texts *sides) resolveStretch(at, end cursor) []Hunk { |
| + count := end.base - at.base |
| + if count < 2 || end.mine-at.mine != count || |
| + end.theirs-at.theirs != count { |
| + return []Hunk{texts.resolve(at, end)} |
| } |
| - hunks := make([]Hunk, len(base)) |
| - for at := range base { |
| - hunks[at] = resolve(base[at:at+1], mine[at:at+1], theirs[at:at+1]) |
| + hunks := make([]Hunk, count) |
| + for step := range count { |
| + from := cursor{at.base + step, at.mine + step, at.theirs + step} |
| + hunks[step] = texts.resolve(from, |
| + cursor{from.base + 1, from.mine + 1, from.theirs + 1}) |
| } |
| return hunks |
| } |
| @@ -75,14 +107,28 @@ func resolveStretch(base, mine, theirs []Block) []Hunk { |
| // resolve is diff3's rule for one unstable stretch: a side that did not |
| // change it yields to the side that did; two identical changes are one; |
| // anything else is a conflict. |
| -func resolve(base, mine, theirs []Block) Hunk { |
| +func (texts *sides) resolve(at, end cursor) Hunk { |
| + base := texts.baseBlocks[at.base:end.base] |
| + mine := texts.mineBlocks[at.mine:end.mine] |
| + theirs := texts.theirsBlocks[at.theirs:end.theirs] |
| switch { |
| - case sameBlocks(mine, base): |
| - return Hunk{Blocks: theirs} |
| - case sameBlocks(theirs, base), sameBlocks(mine, theirs): |
| - return Hunk{Blocks: mine} |
| + case sameBlocks(mine, base), sameBlocks(mine, theirs): |
| + return texts.settled(FromTheirs, at.theirs, len(theirs)) |
| + case sameBlocks(theirs, base): |
| + return texts.settled(FromMine, at.mine, len(mine)) |
| } |
| - return Hunk{Conflict: true, Base: base, Mine: mine, Theirs: theirs} |
| + return Hunk{Conflict: true, Base: base, Mine: mine, Theirs: theirs, |
| + BaseAt: at.base, MineAt: at.mine, TheirAt: at.theirs, texts: texts} |
| +} |
| + |
| +// settled is a hunk of count blocks taken from one side, from at. |
| +func (texts *sides) settled(from Side, at, count int) Hunk { |
| + blocks := texts.theirsBlocks |
| + if from == FromMine { |
| + blocks = texts.mineBlocks |
| + } |
| + return Hunk{Blocks: blocks[at : at+count], From: from, At: at, |
| + texts: texts} |
| } |
| func sameBlocks(one, other []Block) bool { |
| @@ -142,31 +188,3 @@ const ( |
| KeepTheirs |
| KeepBoth |
| ) |
| - |
| -// Settle joins the hunks into a body, taking each conflict's choice in |
| -// order. It reports false if any conflict has no valid choice. |
| -func Settle(hunks []Hunk, choices []Choice) (string, bool) { |
| - var blocks []Block |
| - next := 0 |
| - for _, hunk := range hunks { |
| - if !hunk.Conflict { |
| - blocks = append(blocks, hunk.Blocks...) |
| - continue |
| - } |
| - if next >= len(choices) { |
| - return "", false |
| - } |
| - switch choices[next] { |
| - case KeepMine: |
| - blocks = append(blocks, hunk.Mine...) |
| - case KeepTheirs: |
| - blocks = append(blocks, hunk.Theirs...) |
| - case KeepBoth: |
| - blocks = append(append(blocks, hunk.Mine...), hunk.Theirs...) |
| - default: |
| - return "", false |
| - } |
| - next++ |
| - } |
| - return Join(blocks), next == len(choices) |
| -} |
diff --git a/internal/mapa/markup/settle.go b/internal/mapa/markup/settle.go| new file mode 100644 |
| index 0000000..4311267 |
| --- /dev/null |
| +++ b/internal/mapa/markup/settle.go |
| @@ -0,0 +1,172 @@ |
| +package markup |
| + |
| +import "strings" |
| + |
| +// Settling a merge keeps bytes (level-up §6.4, D13). The current |
| +// revision ("theirs") is the anchor: its blocks, and the bytes between |
| +// two of its blocks that are still neighbours, are emitted as they are. |
| +// A block taken from mine brings its own source, and the bytes between |
| +// two of mine's neighbours come with them. Only a seam where the two |
| +// sides meet follows Join's rule. The result is parsed again: if it does |
| +// not give the settled blocks, Settle falls back to Join, which is |
| +// correct but tidies spacing. |
| + |
| +// placed is one settled block and its place in the side it came from. |
| +type placed struct { |
| + block Block |
| + from Side |
| + at int |
| +} |
| + |
| +// Settle joins the hunks into a body, taking each conflict's choice in |
| +// order. It reports false if any conflict has no valid choice. |
| +func Settle(hunks []Hunk, choices []Choice) (string, bool) { |
| + var pieces []placed |
| + var texts *sides |
| + next := 0 |
| + for _, hunk := range hunks { |
| + texts = firstSides(texts, hunk.texts) |
| + if !hunk.Conflict { |
| + pieces = appendPieces(pieces, hunk.Blocks, hunk.From, hunk.At) |
| + continue |
| + } |
| + if next >= len(choices) { |
| + return "", false |
| + } |
| + chosen, ok := hunk.chosen(pieces, choices[next]) |
| + if !ok { |
| + return "", false |
| + } |
| + pieces = chosen |
| + next++ |
| + } |
| + return texts.join(pieces), next == len(choices) |
| +} |
| + |
| +func firstSides(found, candidate *sides) *sides { |
| + if found != nil { |
| + return found |
| + } |
| + return candidate |
| +} |
| + |
| +// chosen is pieces with a conflict's chosen side appended. |
| +func (hunk Hunk) chosen(pieces []placed, choice Choice) ([]placed, bool) { |
| + switch choice { |
| + case KeepMine: |
| + return appendPieces(pieces, hunk.Mine, FromMine, hunk.MineAt), true |
| + case KeepTheirs: |
| + return appendPieces(pieces, hunk.Theirs, FromTheirs, |
| + hunk.TheirAt), true |
| + case KeepBoth: |
| + pieces = appendPieces(pieces, hunk.Mine, FromMine, hunk.MineAt) |
| + return appendPieces(pieces, hunk.Theirs, FromTheirs, |
| + hunk.TheirAt), true |
| + } |
| + return pieces, false |
| +} |
| + |
| +func appendPieces(pieces []placed, blocks []Block, from Side, |
| + at int) []placed { |
| + for step, block := range blocks { |
| + pieces = append(pieces, placed{block: block, from: from, |
| + at: at + step}) |
| + } |
| + return pieces |
| +} |
| + |
| +// join is the settled body: the sides' own bytes where they hold, and |
| +// Join where the result would not parse back to the settled blocks. |
| +func (texts *sides) join(pieces []placed) string { |
| + blocks := make([]Block, len(pieces)) |
| + for at, settled := range pieces { |
| + blocks[at] = settled.block |
| + } |
| + if texts == nil || len(pieces) == 0 { |
| + return Join(blocks) |
| + } |
| + kept := texts.keep(pieces) |
| + if sameStructure(Parse(kept), blocks) { |
| + return kept |
| + } |
| + return Join(blocks) |
| +} |
| + |
| +// keep writes the pieces with their sides' bytes between neighbours. |
| +func (texts *sides) keep(pieces []placed) string { |
| + var out strings.Builder |
| + if first := pieces[0]; first.at == 0 { |
| + out.WriteString(texts.text(first.from)[:first.block.Start]) |
| + } |
| + for at, settled := range pieces { |
| + if at > 0 { |
| + out.WriteString(texts.seam(pieces[at-1], settled)) |
| + } |
| + out.WriteString(settled.block.Source) |
| + } |
| + return out.String() |
| +} |
| + |
| +// seam is the bytes between two settled blocks: their side's own, when |
| +// they were neighbours there, and Join's rule anywhere else. |
| +func (texts *sides) seam(before, after placed) string { |
| + if before.from == after.from && after.at == before.at+1 { |
| + blocks := texts.blocks(before.from) |
| + start, end := blocks[before.at].End, blocks[after.at].Start |
| + return texts.text(before.from)[start:end] |
| + } |
| + if before.block.Kind == Item && after.block.Kind == Item { |
| + return "\n" |
| + } |
| + return "\n\n" |
| +} |
| + |
| +func (texts *sides) text(from Side) string { |
| + if from == FromMine { |
| + return texts.mine |
| + } |
| + return texts.theirs |
| +} |
| + |
| +func (texts *sides) blocks(from Side) []Block { |
| + if from == FromMine { |
| + return texts.mineBlocks |
| + } |
| + return texts.theirsBlocks |
| +} |
| + |
| +// sameStructure reports whether parsed is blocks: the same number, and |
| +// each of the same kind, level and source. |
| +func sameStructure(parsed, blocks []Block) bool { |
| + if len(parsed) != len(blocks) { |
| + return false |
| + } |
| + for at := range parsed { |
| + one, other := parsed[at], blocks[at] |
| + if one.Kind != other.Kind || one.Level != other.Level || |
| + one.Ordered != other.Ordered || one.Source != other.Source { |
| + return false |
| + } |
| + } |
| + return true |
| +} |
| + |
| +// Sources is a conflict's three sides as Markdown, each the exact bytes |
| +// of its body from the hunk's first block to its last ("" for a side |
| +// with no blocks). The editor's inline choice shows them (§6.5). |
| +func (hunk Hunk) Sources() (base, mine, theirs string) { |
| + if hunk.texts == nil { |
| + return Join(hunk.Base), Join(hunk.Mine), Join(hunk.Theirs) |
| + } |
| + texts := hunk.texts |
| + return span(texts.base, hunk.Base), span(texts.mine, hunk.Mine), |
| + span(texts.theirs, hunk.Theirs) |
| +} |
| + |
| +// span is the bytes of text that blocks, a run of its own, cover. |
| +func span(text string, blocks []Block) string { |
| + if len(blocks) == 0 { |
| + return "" |
| + } |
| + return text[blocks[0].Start:blocks[len(blocks)-1].End] |
| +} |
diff --git a/internal/mapa/markup/settle_test.go b/internal/mapa/markup/settle_test.go| new file mode 100644 |
| index 0000000..6390cc8 |
| --- /dev/null |
| +++ b/internal/mapa/markup/settle_test.go |
| @@ -0,0 +1,126 @@ |
| +package markup |
| + |
| +import ( |
| + "strings" |
| + "testing" |
| +) |
| + |
| +// Level-up §6.4, D13: a merged body changes bytes only in the blocks |
| +// mine changed and at their seams. Everything else is theirs, byte for |
| +// byte. |
| + |
| +const spacedBase = "# Plan\n\nOne.\n\nTwo.\n\nThree.\n\nFour." |
| + |
| +func mergedClean(t *testing.T, base, mine, theirs string) string { |
| + t.Helper() |
| + hunks, clean := Merge3(base, mine, theirs) |
| + if !clean { |
| + t.Fatalf("a conflict merging\n%q\n%q", mine, theirs) |
| + } |
| + body, ok := Settle(hunks, nil) |
| + if !ok { |
| + t.Fatal("a clean merge did not settle") |
| + } |
| + return body |
| +} |
| + |
| +func TestSettleKeepsTheirSpacingOutsideMineEdits(t *testing.T) { |
| + theirs := "\n# Plan\n\n\n\nOne.\n\n \nTwo.\n\nThree, theirs." + |
| + "\n\n\t\n\nFour." |
| + mine := "# Plan\n\nOne.\n\nTwo.\n\nThree.\n\nFour, mine." |
| + got := mergedClean(t, spacedBase, mine, theirs) |
| + want := "\n# Plan\n\n\n\nOne.\n\n \nTwo.\n\nThree, theirs." + |
| + "\n\nFour, mine." |
| + if got != want { |
| + t.Fatalf("got %q\nwant %q", got, want) |
| + } |
| +} |
| + |
| +func TestSettleKeepsTheirBytesWhenMineChangedNothing(t *testing.T) { |
| + theirs := "# Plan\n\n\n\nOne, theirs.\n\nTwo.\n\nThree.\n\n\nFour." |
| + if got := mergedClean(t, spacedBase, spacedBase, theirs); got != theirs { |
| + t.Fatalf("got %q", got) |
| + } |
| +} |
| + |
| +func TestSettleKeepsMineOwnSeamsBetweenMineBlocks(t *testing.T) { |
| + mine := "# Plan\n\nOne.\n\nNew A.\n\n\n\nNew B.\n\nTwo.\n\nThree." + |
| + "\n\nFour." |
| + theirs := "# Plan\n\n\nOne.\n\nTwo.\n\nThree.\n\n\n\nFour, theirs." |
| + got := mergedClean(t, spacedBase, mine, theirs) |
| + want := "# Plan\n\n\nOne.\n\nNew A.\n\n\n\nNew B.\n\nTwo.\n\nThree." + |
| + "\n\n\n\nFour, theirs." |
| + if got != want { |
| + t.Fatalf("got %q\nwant %q", got, want) |
| + } |
| +} |
| + |
| +func TestSettleKeepsATightListTight(t *testing.T) { |
| + base := "Intro.\n\n- a\n- b\n- c" |
| + mine := "Intro.\n\n- a\n- b, mine\n- c" |
| + theirs := "Intro, theirs.\n\n\n- a\n- b\n- c" |
| + got := mergedClean(t, base, mine, theirs) |
| + if got != "Intro, theirs.\n\n\n- a\n- b, mine\n- c" { |
| + t.Fatalf("got %q", got) |
| + } |
| +} |
| + |
| +// Only the bytes inside the blocks mine changed, and the seams beside |
| +// them, differ from theirs. |
| +func TestSettleChangesOnlyMineBlocksAndTheirSeams(t *testing.T) { |
| + theirs := "# Plan\n\n\n\nOne.\n\n \nTwo.\n\nThree.\n\n\n\nFour." |
| + mine := "# Plan\n\nOne.\n\nTwo, mine.\n\nThree.\n\nFour." |
| + got := mergedClean(t, spacedBase, mine, theirs) |
| + head, tail := "# Plan\n\n\n\nOne.", "Three.\n\n\n\nFour." |
| + if !strings.HasPrefix(got, head) || !strings.HasSuffix(got, tail) || |
| + !strings.Contains(got, "Two, mine.") { |
| + t.Fatalf("got %q", got) |
| + } |
| +} |
| + |
| +// The structure check: a result that would not parse back to the |
| +// settled blocks falls back to Join. |
| +func TestSettleFallsBackToJoinWhenTheBytesWouldNotParse(t *testing.T) { |
| + base := "A.\n\nB." |
| + mine := "A.\n\n```\nmine code" |
| + theirs := "A.\n\nB, theirs." |
| + hunks, clean := Merge3(base, mine, theirs) |
| + if clean { |
| + t.Fatal("two edits to one block merged silently") |
| + } |
| + got, ok := Settle(hunks, []Choice{KeepBoth}) |
| + if !ok { |
| + t.Fatal("a chosen conflict did not settle") |
| + } |
| + want := Join([]Block{{Kind: Paragraph, Source: "A."}, |
| + {Kind: Code, Source: "```\nmine code"}, |
| + {Kind: Paragraph, Source: "B, theirs."}}) |
| + if got != want { |
| + t.Fatalf("got %q, want %q", got, want) |
| + } |
| + placedBlocks := Parse(mine) |
| + if sameStructure(Parse(got), append(placedBlocks, |
| + Block{Kind: Paragraph, Source: "B, theirs."})) { |
| + t.Fatal("the vacuous case: the joined body parses as settled") |
| + } |
| +} |
| + |
| +func TestAConflictsSourcesAreItsExactBytes(t *testing.T) { |
| + base := "One.\n\nTwo.\n\nThree." |
| + mine := "One.\n\nTwo,\nmine. \n\nThree." |
| + theirs := "One.\n\nTwo, theirs.\n\nThree." |
| + hunks, _ := Merge3(base, mine, theirs) |
| + for _, hunk := range hunks { |
| + if !hunk.Conflict { |
| + continue |
| + } |
| + was, ours, others := hunk.Sources() |
| + if was != "Two." || ours != "Two,\nmine. " || |
| + others != "Two, theirs." || hunk.MineAt != 1 { |
| + t.Fatalf("sources %q %q %q at %d", was, ours, others, |
| + hunk.MineAt) |
| + } |
| + return |
| + } |
| + t.Fatal("no conflict") |
| +} |
diff --git a/internal/mapa/private.go b/internal/mapa/private.go| index 7a9badc..00316fd 100644 |
| --- a/internal/mapa/private.go |
| +++ b/internal/mapa/private.go |
| @@ -2,6 +2,7 @@ package mapa |
| import ( |
| "errors" |
| + "html/template" |
| "net/http" |
| "strconv" |
| @@ -41,13 +42,26 @@ func (app *app) listScratch(writer http.ResponseWriter, |
| func (app *app) newScratch(writer http.ResponseWriter, |
| request *http.Request) { |
| + viewer, err := app.viewer(request) |
| + var island template.JS |
| + if err == nil { |
| + island, err = app.islandFor(request.Context(), viewer, "", 0, nil) |
| + } |
| + if err != nil { |
| + app.fail(writer, request, err) |
| + return |
| + } |
| app.showForm(writer, request, http.StatusOK, "scratch_new", |
| pageForm{Action: "/scratch", Label: "New scratch page", |
| - Page: PageView{Kind: KindScratch}}) |
| + Page: PageView{Kind: KindScratch}, Island: island}) |
| } |
| func (app *app) createScratch(writer http.ResponseWriter, |
| request *http.Request) { |
| + if token := request.PostFormValue("first"); token != "" { |
| + app.firstScratch(writer, request, token) |
| + return |
| + } |
| address, _ := app.identity(request) |
| body := request.PostFormValue("body") |
| page, err := app.store.CreateScratch(request.Context(), address, body) |
| @@ -117,8 +131,9 @@ func (app *app) share(writer http.ResponseWriter, request *http.Request) { |
| } |
| address, _ := app.identity(request) |
| shared, err := app.store.MakeTeamPage(request.Context(), address, |
| - ref.ID, chosen, data.Title) |
| - if sayable(err) || errors.Is(err, ErrNothingChosen) { |
| + ref.ID, formInt(request, "revision"), chosen, data.Title) |
| + if sayable(err) || errors.Is(err, ErrNothingChosen) || |
| + errors.Is(err, ErrNoteChanged) { |
| data.Error = err.Error() |
| data.Taken = app.index.TitleHref(request.Context(), data.Title) |
| app.showShare(writer, request, http.StatusUnprocessableEntity, data) |
diff --git a/internal/mapa/share.go b/internal/mapa/share.go| index 14e811a..114e595 100644 |
| --- a/internal/mapa/share.go |
| +++ b/internal/mapa/share.go |
| @@ -12,14 +12,22 @@ import ( |
| // ErrNothingChosen is "Make team page" with no blocks selected. |
| var ErrNothingChosen = errors.New("Choose at least one block to share.") |
| +// ErrNoteChanged is "Make team page" over a revision that is no longer |
| +// the note's: the chosen block numbers named that revision's blocks, so |
| +// they are not used (level-up §6.7). |
| +var ErrNoteChanged = errors.New("Your note changed since these blocks " + |
| + "were shown. Choose them again.") |
| + |
| // MakeTeamPage shares private writing (§3.4, decision 8): the chosen |
| // blocks of one of who's daily or scratch notes become a NEW team page, |
| // at its first revision, and the note gets a link to it in their place. |
| // The note itself is never re-ruled, so no private-era revision ever |
| // becomes team-readable. A taken or date-shaped title asks for another |
| -// (gate 2). |
| +// (gate 2). revision is the note's revision the block numbers index; |
| +// a stale one is refused with ErrNoteChanged and nothing is written. |
| func (store *Store) MakeTeamPage(ctx context.Context, who string, |
| - sourceID int64, chosen []int, rawTitle string) (Page, error) { |
| + sourceID, revision int64, chosen []int, rawTitle string) (Page, |
| + error) { |
| title, err := CleanTitle(rawTitle) |
| if err != nil { |
| return Page{}, err |
| @@ -34,6 +42,9 @@ func (store *Store) MakeTeamPage(ctx context.Context, who string, |
| if err != nil || source.Rung != RungPrivate { |
| return errors.Join(ErrNotFound, err) |
| } |
| + if source.Revision != revision { |
| + return ErrNoteChanged |
| + } |
| record, err := store.OpenPage(source) |
| if err != nil { |
| return err |
diff --git a/internal/mapa/templates/day.html b/internal/mapa/templates/day.html| index 982c479..429ca0e 100644 |
| --- a/internal/mapa/templates/day.html |
| +++ b/internal/mapa/templates/day.html |
| @@ -1,8 +1,8 @@ |
| {{define "content"}}{{$d := .Data}}{{$page := $d.Page}} |
| {{template "mapa-doc-head" dict "Page" $page "Edit" (or (and $d.Written (not $d.Editing) (printf "/d/%s/edit" $page.Date)) "") "Day" $d.Pill}} |
| {{template "notice" $d.Notice}} |
| -{{with $d.Draft}}{{template "mapa-unsaved" dict "Draft" . "Save" (printf "/d/%s/draft/save" $page.Date) "Discard" (printf "/d/%s/draft/discard" $page.Date)}}{{end}} |
| -{{range $d.Orphans}}<div mapa-unsaved role="status"><p><strong>You have unsaved changes to a page that was deleted.</strong></p><form method="post" action="/p/{{.Public}}/draft/scratch"><button rst-btn="primary" type="submit">Save as a scratch page</button></form><form method="post" action="/p/{{.Public}}/draft/discard"><input type="hidden" name="version" value="{{.Version}}"><button rst-btn type="submit">Discard</button></form></div>{{end}} |
| +{{with $d.Draft}}{{template "mapa-unsaved" dict "Draft" . "Save" (printf "/d/%s/draft/save" $page.Date) "Discard" (printf "/d/%s/draft/discard" $page.Date) "Href" (or (and $d.Written (not $d.Editing) $page.Href) "") "Saved" $d.Saved}}{{end}} |
| +{{template "mapa-island" $d.Island}}{{range $d.Orphans}}<div mapa-unsaved role="status"><p><strong>You have unsaved changes to a page that was deleted.</strong></p><form method="post" action="/p/{{.Public}}/draft/scratch"><button rst-btn="primary" type="submit">Save as a scratch page</button></form><form method="post" action="/p/{{.Public}}/draft/discard"><input type="hidden" name="version" value="{{.Version}}"><button rst-btn type="submit">Discard</button></form></div>{{end}} |
| {{range $d.Elsewhere}}<p mapa-unsaved role="status"><span><strong>You have unsaved changes</strong> on another page.</span> <a rst-btn href="/p/{{.Public}}">Open it</a></p>{{end}} |
| {{if $d.Editing}} |
| <form rst-form method="post" action="/d/{{$page.Date}}" mapa-edit-form data-drafts="{{$d.Drafts}}" data-version="{{$d.Version}}"> |
diff --git a/internal/mapa/templates/page.html b/internal/mapa/templates/page.html| index 6a5b5a1..83b910d 100644 |
| --- a/internal/mapa/templates/page.html |
| +++ b/internal/mapa/templates/page.html |
| @@ -1,8 +1,8 @@ |
| {{define "content"}}{{$d := .Data}}{{$page := $d.Page}} |
| {{template "mapa-doc-head" dict "Page" $page "Last" $d.Last "Edit" (printf "%s/edit" $page.Href)}} |
| {{template "notice" $d.Notice}} |
| -{{with $d.Draft}}{{template "mapa-unsaved" dict "Draft" . "Save" (printf "/p/%s/draft/save" $page.Public) "Discard" (printf "/p/%s/draft/discard" $page.Public)}}{{end}} |
| -<article mapa-body> |
| +{{with $d.Draft}}{{template "mapa-unsaved" dict "Draft" . "Save" (printf "/p/%s/draft/save" $page.Public) "Discard" (printf "/p/%s/draft/discard" $page.Public) "Href" $page.Href "Saved" $d.Saved}}{{end}} |
| +{{template "mapa-island" $d.Island}}<article mapa-body> |
| {{if $page.Body}}{{$page.HTML}}{{else}}<p mapa-empty>This page is empty. <a href="{{$page.Href}}/edit">Write something</a>.</p>{{end}} |
| </article> |
| <footer mapa-foot-refs> |
diff --git a/internal/mapa/templates/partials.html b/internal/mapa/templates/partials.html| index 0b83c73..65cf98c 100644 |
| --- a/internal/mapa/templates/partials.html |
| +++ b/internal/mapa/templates/partials.html |
| @@ -27,16 +27,25 @@ |
| </div> |
| {{end}} |
| -{{/* mapa-unsaved: the offer of a draft a closed tab left (§5). Keys: |
| - Draft (DraftView), Save, Discard (form actions). */}} |
| +{{/* mapa-unsaved: the draft bar (§5, level-up §6.8). The page shows |
| + the person's unsaved text, or with Saved (?saved=1) the committed |
| + text. Keys: Draft (DraftView), Save, Discard (form actions), Href |
| + (the page, for "Show the saved version"; "" where nothing is saved |
| + yet), Saved. */}} |
| {{define "mapa-unsaved"}} |
| <div mapa-unsaved role="status"> |
| -<p><strong>You have unsaved changes</strong> from <time datetime="{{.Draft.Updated.Format "2006-01-02T15:04:05Z07:00"}}" title="{{.Draft.Updated.Format "2 January 2006 15:04"}}">{{ago .Draft.Updated}}</time>.</p> |
| +<p><strong>Unsaved changes</strong> from <time datetime="{{.Draft.Updated.Format "2006-01-02T15:04:05Z07:00"}}" title="{{.Draft.Updated.Format "2 January 2006 15:04"}}">{{ago .Draft.Updated}}</time>. {{if .Saved}}You're seeing the saved version.{{else}}You're seeing your unsaved version.{{end}}</p> |
| <form method="post" action="{{.Save}}"><input type="hidden" name="version" value="{{.Draft.Version}}"><button rst-btn="primary" type="submit">Save</button></form> |
| <form method="post" action="{{.Discard}}"><input type="hidden" name="version" value="{{.Draft.Version}}"><button rst-btn type="submit">Discard</button></form> |
| +{{with .Href}}{{if $.Saved}}<a rst-btn href="{{.}}">Show your unsaved version</a>{{else}}<a rst-btn href="{{.}}?saved=1">Show the saved version</a>{{end}}{{end}} |
| </div> |
| {{end}} |
| +{{/* mapa-island: the editor's data (level-up §6.8), JSON written by |
| + encoding/json, which escapes <, >, & and U+2028/9. */}} |
| +{{define "mapa-island"}}{{with .}}<script type="application/json" id="mapa-editor">{{.}}</script> |
| +{{end}}{{end}} |
| + |
| {{/* mapa-editing: "Ana is editing", team pages only (§5). */}} |
| {{define "mapa-editing"}}{{with .}}<p mapa-meta mapa-editing>{{range $i, $who := .}}{{if $i}}, {{end}}{{$who}}{{end}} {{if eq (len .) 1}}is{{else}}are{{end}} editing this page.</p>{{end}}{{end}} |
diff --git a/internal/mapa/templates/scratch_new.html b/internal/mapa/templates/scratch_new.html| index 925172e..64d0625 100644 |
| --- a/internal/mapa/templates/scratch_new.html |
| +++ b/internal/mapa/templates/scratch_new.html |
| @@ -1,6 +1,7 @@ |
| {{define "content"}} |
| {{template "back-nav" dict "Href" "/scratch" "Label" "Scratch"}} |
| {{template "page-header" dict "Title" "New scratch page" "Sub" "Only you can open it. It is saved when you save it, and not before."}} |
| +{{template "mapa-island" .Data.Island}} |
| <form rst-form method="post" action="{{.Data.Action}}" mapa-edit-form> |
| {{template "mapa-editor" dict "Body" .Data.Body "Error" .Data.Error}} |
| {{template "form-foot" dict "Submit" "Save" "CancelHref" "/scratch" "CancelLabel" "Cancel"}} |
diff --git a/internal/mapa/templates/share.html b/internal/mapa/templates/share.html| index f404380..744366e 100644 |
| --- a/internal/mapa/templates/share.html |
| +++ b/internal/mapa/templates/share.html |
| @@ -2,6 +2,7 @@ |
| {{template "back-nav" dict "Href" $d.Page.Href "Label" $d.Page.Label}} |
| {{template "page-header" dict "Title" "Make team page" "Sub" "The blocks you choose become a new team page that everyone in the team can open. Your note keeps a link to it in their place, and stays yours."}} |
| <form rst-form method="post" action="{{$d.Action}}"> |
| +<input type="hidden" name="revision" value="{{$d.Page.Revision}}"> |
| {{template "field-text" dict "Name" "title" "Label" "Title of the new page" "Value" $d.Title "Error" $d.Error "Required" true}} |
| {{with $d.Taken}}<p mapa-meta><a href="{{.}}">Open the page with that title</a></p>{{end}} |
| <fieldset mapa-choose> |
diff --git a/internal/mapa/today.go b/internal/mapa/today.go| index 85c8b9e..89ec0e8 100644 |
| --- a/internal/mapa/today.go |
| +++ b/internal/mapa/today.go |
| @@ -2,6 +2,7 @@ package mapa |
| import ( |
| "errors" |
| + "html/template" |
| "net/http" |
| "strconv" |
| "strings" |
| @@ -81,6 +82,10 @@ type dayData struct { |
| // strip, and ‹ Today › with its month. |
| Week *WeekView |
| Pill *dayPill |
| + // Saved is ?saved=1, the committed text with the draft still |
| + // offered; Island is the editor's data (level-up §6.8). |
| + Saved bool |
| + Island template.JS |
| } |
| // dayCalendar fills in the week strip and the month calendar, both read |
| @@ -129,6 +134,10 @@ func (app *app) showDay(writer http.ResponseWriter, request *http.Request, |
| app.fail(writer, request, err) |
| return |
| } |
| + if err := app.dayEditor(request, viewer, &data); err != nil { |
| + app.fail(writer, request, err) |
| + return |
| + } |
| if request.Method == http.MethodPost { |
| data.Body = request.PostFormValue("body") |
| } |
diff --git a/internal/mapatest/daily_test.go b/internal/mapatest/daily_test.go| index d573b56..0f786a9 100644 |
| --- a/internal/mapatest/daily_test.go |
| +++ b/internal/mapatest/daily_test.go |
| @@ -113,7 +113,8 @@ func TestMakeTeamPageFromADailyNote(t *testing.T) { |
| t.Fatal("the share form offers no blocks") |
| } |
| made := rig.post(t, Ana, "/p/"+share+"/share", |
| - url.Values{"title": {"Known"}, "block": {"1"}}) |
| + url.Values{"title": {"Known"}, "block": {"1"}, |
| + "revision": {formRevision(form)}}) |
| if made.Code != http.StatusSeeOther { |
| t.Fatalf("share: %d", made.Code) |
| } |
| @@ -121,8 +122,10 @@ func TestMakeTeamPageFromADailyNote(t *testing.T) { |
| "The team should know this.") { |
| t.Fatal("Bo cannot read the shared page") |
| } |
| + again := rig.page(t, Ana, "/p/"+share+"/share") |
| taken := rig.post(t, Ana, "/p/"+share+"/share", |
| - url.Values{"title": {"known"}, "block": {"0"}}) |
| + url.Values{"title": {"known"}, "block": {"0"}, |
| + "revision": {formRevision(again)}}) |
| if taken.Code != http.StatusUnprocessableEntity || |
| !strings.Contains(taken.Body.String(), `value="0" checked`) { |
| t.Fatal("a taken title must ask again, keeping the choice") |
| @@ -157,3 +160,9 @@ func TestAPrivatePageIsNotThereForAnyoneElse(t *testing.T) { |
| } |
| } |
| } |
| + |
| +// formRevision is the revision a form names: the one its blocks or its |
| +// text were drawn from. |
| +func formRevision(form string) string { |
| + return between(form, `name="revision" value="`, `"`) |
| +} |
diff --git a/internal/mapatest/drafts_test.go b/internal/mapatest/drafts_test.go| index 8e26b95..aa93602 100644 |
| --- a/internal/mapatest/drafts_test.go |
| +++ b/internal/mapatest/drafts_test.go |
| @@ -59,12 +59,12 @@ func TestGate11AClosedTabsDraftIsOfferedAsSaveOrDiscard(t *testing.T) { |
| acme := rig.createPage(t, Ana, "Acme", "Committed.") |
| rig.autosave(t, Ana, acme, revisionOf(t, rig, acme), "0", "Left open.") |
| offer := rig.page(t, Ana, acme) |
| - if !strings.Contains(offer, "You have unsaved changes") || |
| + if !strings.Contains(offer, "Unsaved changes</strong> from") || |
| !strings.Contains(offer, `action="`+acme+`/draft/save"`) || |
| !strings.Contains(offer, `action="`+acme+`/draft/discard"`) { |
| t.Fatal("the draft is not offered as Save or Discard") |
| } |
| - if strings.Contains(rig.page(t, Bo, acme), "You have unsaved changes") { |
| + if strings.Contains(rig.page(t, Bo, acme), "Unsaved changes</strong>") { |
| t.Fatal("Ana's draft is offered to Bo") |
| } |
| if rig.post(t, Ana, acme+"/draft/save", nil).Code != http.StatusSeeOther { |
| @@ -171,11 +171,11 @@ func TestGate11DraftsAreDiscarded30DaysAfterTheirLastWrite(t *testing.T) { |
| acme := rig.createPage(t, Ana, "Acme", "Text.") |
| rig.autosave(t, Ana, acme, revisionOf(t, rig, acme), "0", "Old draft.") |
| moving.now = moving.now.Add(29 * 24 * time.Hour) |
| - if !strings.Contains(rig.page(t, Ana, acme), "unsaved changes") { |
| + if !strings.Contains(rig.page(t, Ana, acme), "Unsaved changes</strong>") { |
| t.Fatal("a 29-day-old draft is gone") |
| } |
| moving.now = moving.now.Add(2 * 24 * time.Hour) |
| - if strings.Contains(rig.page(t, Ana, acme), "unsaved changes") { |
| + if strings.Contains(rig.page(t, Ana, acme), "Unsaved changes</strong>") { |
| t.Fatal("a 31-day-old draft is still offered") |
| } |
| rig.built.Store.Sweep(context.Background()) |
| @@ -251,7 +251,7 @@ func TestGate11AStaleFirstSaveOfADayKeepsTheNewerDraft(t *testing.T) { |
| laptop.Header().Get("Location")) |
| } |
| offer := rig.page(t, Ana, day) |
| - if !strings.Contains(offer, "You have unsaved changes") || |
| + if !strings.Contains(offer, "Unsaved changes</strong> from") || |
| !strings.Contains(offer, phone["version"].(string)) { |
| t.Fatal("the phone's draft is not offered on the note") |
| } |
diff --git a/internal/mapatest/gate1_test.go b/internal/mapatest/gate1_test.go| index 0d1cad1..6bae5f0 100644 |
| --- a/internal/mapatest/gate1_test.go |
| +++ b/internal/mapatest/gate1_test.go |
| @@ -1,7 +1,9 @@ |
| package mapatest |
| import ( |
| + "fmt" |
| "net/url" |
| + "regexp" |
| "strings" |
| "testing" |
| "time" |
| @@ -109,6 +111,11 @@ func boSees(t *testing.T, rig *rig, acme string) map[string]string { |
| } { |
| seen[path] = rig.page(t, Bo, path) |
| } |
| + // The editor's chip states, for texts Ana's notes type too. |
| + _, states := rig.postJSON(Bo, "/links/resolve", url.Values{"target": { |
| + "Acme", "Acme#^blk", "Zebracorn Plans", "Zebracorn kit", |
| + "Acme Ltd", "2026-11-12"}}) |
| + seen["links resolve"] = fmt.Sprint(states) |
| renamed := rig.post(t, Bo, acme+"/rename", |
| url.Values{"title": {"Acme Holdings"}}) |
| seen["rename"] = renamed.Header().Get("Location") |
| @@ -130,9 +137,10 @@ func TestGate1ScopeLeaksNothing(t *testing.T) { |
| } |
| without, with := boSees(t, quiet, acme), boSees(t, busy, acme) |
| for key, want := range without { |
| - if with[key] != want { |
| + want, got := steadyRevisions(want), steadyRevisions(with[key]) |
| + if got != want { |
| t.Errorf("Bo's %s differs when Ana's private notes hold "+ |
| - "the term:\n%s", key, firstDifference(want, with[key])) |
| + "the term:\n%s", key, firstDifference(want, got)) |
| } |
| } |
| if !strings.Contains(without["/search?q=zebracorn"], "Notes") { |
| @@ -157,6 +165,15 @@ func TestGate1AnaSeesHerOwn(t *testing.T) { |
| } |
| } |
| +// islandRevision is a revision in the editor's island. Revisions are |
| +// random in both worlds (doctrine §6.6), so they say nothing about |
| +// Ana's notes and are compared as one value. |
| +var islandRevision = regexp.MustCompile(`"(base|version)":"[0-9]+"`) |
| + |
| +func steadyRevisions(page string) string { |
| + return islandRevision.ReplaceAllString(page, `"$1":"R"`) |
| +} |
| + |
| func firstDifference(want, got string) string { |
| for at := range min(len(want), len(got)) { |
| if want[at] != got[at] { |
diff --git a/internal/mapatest/gate8_test.go b/internal/mapatest/gate8_test.go| index 2a95fa7..56b1291 100644 |
| --- a/internal/mapatest/gate8_test.go |
| +++ b/internal/mapatest/gate8_test.go |
| @@ -120,6 +120,9 @@ func gate8Steps(t *testing.T, world *rig) []step { |
| posting("/d/{date}", Ana, day, url.Values{"body": {"Saved day."}, |
| "revision": {"0"}}), |
| posting("/preview", Ana, "/preview", url.Values{"body": {"x"}}), |
| + // The editor's chip states: JSON, written nowhere (level-up §6.8). |
| + posting("/links/resolve", Ana, "/links/resolve", |
| + url.Values{"target": {"Acme", "2026-11-12", "Nothing yet"}}), |
| posting("/scratch", Ana, "/scratch", url.Values{"body": {"Mine."}}), |
| posting("/settings", Ana, "/settings", |
| url.Values{"zone": {"Europe/Madrid"}}), |
| @@ -165,9 +168,23 @@ func gate8Later(t *testing.T, acme, notes string) []step { |
| {route: "POST /p/{id}/share", do: func(rig *rig) *http.Response { |
| day := rig.page(t, Ana, "/d/2026-11-12") |
| note := between(day, `href="/p/`, `/share"`) |
| + form := rig.page(t, Ana, "/p/"+note+"/share") |
| return rig.send(Ana, http.MethodPost, "/p/"+note+"/share", |
| - url.Values{"title": {"Shared"}, "block": {"0"}}) |
| + url.Values{"title": {"Shared"}, "block": {"0"}, |
| + "revision": {formRevision(form)}}) |
| }}, |
| + // The closing tab's commit=1, and a new scratch page's first |
| + // autosave (level-up §6.5, D12): each a commit, with its event. |
| + {route: "POST /p/{id}/draft", do: func(rig *rig) *http.Response { |
| + _, reply := rig.autosave(t, Ana, acme, revisionOf(t, rig, acme), |
| + "0", "Closing.") |
| + version, _ := reply["version"].(string) |
| + return rig.send(Ana, http.MethodPost, acme+"/draft", |
| + url.Values{"commit": {"1"}, "version": {version}, |
| + "body": {"Closed."}}) |
| + }}, |
| + posting("/scratch", Ana, "/scratch", url.Values{ |
| + "first": {"gate-eight-token-0001"}, "body": {"First."}}), |
| {route: "POST /p/{id}/draft/scratch", |
| do: func(rig *rig) *http.Response { |
| rig.autosave(t, Ana, acme, revisionOf(t, rig, acme), "0", "E.") |
diff --git a/internal/mapatest/history_panel_test.go b/internal/mapatest/history_panel_test.go| index 2f32a64..f0bee65 100644 |
| --- a/internal/mapatest/history_panel_test.go |
| +++ b/internal/mapatest/history_panel_test.go |
| @@ -202,8 +202,10 @@ func TestHistoryKeepsScope(t *testing.T) { |
| 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), "") |
| + without := steadyRevisions(revisions.ReplaceAllString( |
| + quiet.page(t, Bo, path), "")) |
| + with := steadyRevisions(revisions.ReplaceAllString( |
| + busy.page(t, Bo, path), "")) |
| if without != with { |
| t.Errorf("Bo's %s differs:\n%s", path, |
| firstDifference(without, with)) |
diff --git a/internal/mapatest/island_test.go b/internal/mapatest/island_test.go| new file mode 100644 |
| index 0000000..f634e5d |
| --- /dev/null |
| +++ b/internal/mapatest/island_test.go |
| @@ -0,0 +1,142 @@ |
| +package mapatest |
| + |
| +import ( |
| + "fmt" |
| + "net/http" |
| + "net/url" |
| + "strings" |
| + "testing" |
| +) |
| + |
| +// What the editor is given (level-up §6.8): the JSON island on every |
| +// editable page, the draft served as the page body, and |
| +// POST /links/resolve. L7: none of it writes. |
| + |
| +func TestTheIslandSurvivesABodyThatClosesTheScript(t *testing.T) { |
| + rig := newRig(t) |
| + body := "</script><script>alert(1)</script>\n\n<!-- a b & c -->" |
| + acme := rig.createPage(t, Ana, "Acme", body) |
| + page := rig.page(t, Bo, acme) |
| + if strings.Count(page, "<script>alert(1)") != 0 { |
| + t.Fatal("the body's script reached the page as markup") |
| + } |
| + if got := islandOf(t, page); got.Source != body || got.Draft != nil || |
| + got.Base != revisionOf(t, rig, acme) { |
| + t.Fatalf("the island read back %+v", got) |
| + } |
| + if rig.get(t, Bo, acme).Header().Get("Cache-Control") != "no-store" { |
| + t.Fatal("a page carrying the island may be cached") |
| + } |
| +} |
| + |
| +func TestTheIslandCarriesTheDraftAndThePageShowsIt(t *testing.T) { |
| + rig := newRig(t) |
| + acme := rig.createPage(t, Ana, "Acme", "Saved text. [[Acme]]") |
| + base := revisionOf(t, rig, acme) |
| + _, reply := rig.autosave(t, Ana, acme, base, "0", |
| + "Unsaved text. [[Nothing yet]] [[2026-11-12]]") |
| + page := rig.page(t, Ana, acme) |
| + data := islandOf(t, page) |
| + if data.Draft == nil || data.Draft.Version != reply["version"] || |
| + data.Draft.Base != base || data.Base != base || |
| + !strings.HasPrefix(data.Source, "Unsaved text.") { |
| + t.Fatalf("Ana's island: %+v", data) |
| + } |
| + if data.Links["Nothing yet"].Kind != "pending" || |
| + data.Links["2026-11-12"].Kind != "date" || len(data.Links) != 2 { |
| + t.Fatalf("the island's chips: %+v", data.Links) |
| + } |
| + article := between(page, "<article mapa-body>", "</article>") |
| + if !strings.Contains(article, "Unsaved text.") || |
| + !strings.Contains(page, "You're seeing your unsaved version.") || |
| + !strings.Contains(page, `href="`+acme+`?saved=1"`) { |
| + t.Fatal("the page does not show Ana her draft, with the bar") |
| + } |
| + saved := rig.page(t, Ana, acme+"?saved=1") |
| + if !strings.Contains(between(saved, "<article mapa-body>", |
| + "</article>"), "Saved text.") || |
| + strings.Contains(saved, `id="mapa-editor"`) || |
| + !strings.Contains(saved, "You're seeing the saved version.") { |
| + t.Fatal("?saved=1 does not show the committed text") |
| + } |
| + if strings.Contains(rig.page(t, Bo, acme), "Unsaved text.") { |
| + t.Fatal("Bo is shown Ana's draft") |
| + } |
| +} |
| + |
| +func TestEveryEditablePageCarriesTheIsland(t *testing.T) { |
| + rig := newRig(t) |
| + rig.post(t, Ana, "/d/2026-11-12", url.Values{"body": {"Day."}}) |
| + scratch := rig.post(t, Ana, "/scratch", url.Values{"body": {"Mine."}}) |
| + for path, source := range map[string]string{ |
| + "/d/2026-11-12": "Day.", "/d/2026-11-13": "", |
| + scratch.Header().Get("Location"): "Mine.", "/scratch/new": "", |
| + } { |
| + if got := islandOf(t, rig.page(t, Ana, path)); got.Source != source { |
| + t.Errorf("%s: the island holds %q", path, got.Source) |
| + } |
| + } |
| + if islandOf(t, rig.page(t, Ana, "/d/2026-11-13")).Base != "0" { |
| + t.Fatal("an unwritten day's island has a base") |
| + } |
| +} |
| + |
| +func TestLinksResolveAnswersEachChipsState(t *testing.T) { |
| + rig := newRig(t) |
| + acme := rig.createPage(t, Ana, "Acme", "Customer. ^blk") |
| + code, reply := rig.postJSON(Bo, "/links/resolve", url.Values{ |
| + "target": {"Acme", "acme#^blk", "Acme#^gone", "Not yet", |
| + "2026-11-12", "2026-02-30"}}) |
| + state := func(key string) map[string]any { |
| + found, _ := reply[key].(map[string]any) |
| + return found |
| + } |
| + if code != http.StatusOK || state("Acme")["kind"] != "team" || |
| + state("Acme")["href"] != acme || state("Acme")["title"] != "Acme" || |
| + state("acme#^blk")["kind"] != "block" || |
| + state("acme#^blk")["href"] != acme+"#b-blk" || |
| + state("Acme#^gone")["kind"] != "block gone" || |
| + state("Not yet")["kind"] != "pending" || |
| + state("2026-11-12")["href"] != "/d/2026-11-12" || |
| + state("2026-02-30")["kind"] != "broken" { |
| + t.Fatalf("/links/resolve: %d %v", code, reply) |
| + } |
| + many := url.Values{} |
| + for at := range 33 { |
| + many.Add("target", fmt.Sprint("Page ", at)) |
| + } |
| + if code, _ := rig.postJSON(Bo, "/links/resolve", many); code != |
| + http.StatusUnprocessableEntity { |
| + t.Fatalf("33 targets: %d", code) |
| + } |
| +} |
| + |
| +// L7: /links/resolve, the island's pages, a page with an offered draft |
| +// opened and left, and New scratch page opened and left write nothing. |
| +func TestL7TheEditorsReadsWriteNothing(t *testing.T) { |
| + busy, acme := gate1World(t, true) |
| + _, offered := busy.autosave(t, Ana, acme, revisionOf(t, busy, acme), |
| + "0", "Offered.") |
| + before := tableRowsHash(t, busy) |
| + for _, who := range []string{Ana, Bo} { |
| + for _, path := range []string{acme, acme + "?saved=1", "/", |
| + "/d/2026-11-12", "/d/2026-11-13", "/scratch/new"} { |
| + if code := busy.get(t, who, path).Code; code != http.StatusOK { |
| + t.Fatalf("%s GET %s: %d", who, path, code) |
| + } |
| + } |
| + code, _ := busy.postJSON(who, "/links/resolve", url.Values{ |
| + "target": {"Acme", "Zebracorn Plans", "2026-11-12"}}) |
| + if code != http.StatusOK { |
| + t.Fatalf("%s /links/resolve: %d", who, code) |
| + } |
| + } |
| + if tableRowsHash(t, busy) != before { |
| + t.Fatal("an editor read changed the database's rows") |
| + } |
| + busy.autosave(t, Ana, acme, "0", offered["version"].(string), |
| + "Typed into.") |
| + if tableRowsHash(t, busy) == before { |
| + t.Fatal("the hash is vacuous: a draft write did not change it") |
| + } |
| +} |
diff --git a/internal/mapatest/plaintext_scan_test.go b/internal/mapatest/plaintext_scan_test.go| index 7abac2d..29b2e48 100644 |
| --- a/internal/mapatest/plaintext_scan_test.go |
| +++ b/internal/mapatest/plaintext_scan_test.go |
| @@ -56,7 +56,8 @@ func writeEverything(t *testing.T, store *mapa.Store, index *mapa.Index) { |
| must(err) |
| _, err = store.CreateScratch(ctx, Ana, "scratchpad musing") |
| must(err) |
| - _, err = store.MakeTeamPage(ctx, Ana, daily.ID, []int{1}, "Sharedtitle") |
| + _, err = store.MakeTeamPage(ctx, Ana, daily.ID, daily.Revision, |
| + []int{1}, "Sharedtitle") |
| must(err) |
| writeLater(t, store, index) |
| } |
diff --git a/internal/mapatest/saving_test.go b/internal/mapatest/saving_test.go| new file mode 100644 |
| index 0000000..fd1f112 |
| --- /dev/null |
| +++ b/internal/mapatest/saving_test.go |
| @@ -0,0 +1,396 @@ |
| +package mapatest |
| + |
| +import ( |
| + "encoding/json" |
| + "net/http" |
| + "net/http/httptest" |
| + "net/url" |
| + "strconv" |
| + "strings" |
| + "sync" |
| + "testing" |
| + "time" |
| +) |
| + |
| +// Gate L9, drafts, rebase and commits (level-up §6.5, §7): the server's |
| +// half. The editor's half (the caret, the table, the three tries) is |
| +// editor/'s, in Node and the browser. |
| + |
| +// postJSON is a POST whose answer the script reads. |
| +func (rig *rig) postJSON(who, target string, |
| + form url.Values) (int, map[string]any) { |
| + request := httptest.NewRequest(http.MethodPost, target, |
| + strings.NewReader(form.Encode())) |
| + request.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| + request.Header.Set("Origin", testOrigin) |
| + request.Header.Set("Accept", "application/json") |
| + recorder := httptest.NewRecorder() |
| + rig.built.As(who).ServeHTTP(recorder, request) |
| + reply := map[string]any{} |
| + _ = json.Unmarshal(recorder.Body.Bytes(), &reply) |
| + return recorder.Code, reply |
| +} |
| + |
| +// editorData is the island a page carries (level-up §6.8). |
| +type editorData struct { |
| + Source string `json:"source"` |
| + Base string `json:"base"` |
| + Draft *struct { |
| + Version string `json:"version"` |
| + Base string `json:"base"` |
| + } `json:"draft"` |
| + Links map[string]struct { |
| + Kind, Href, Title string |
| + } `json:"links"` |
| +} |
| + |
| +// islandOf reads the island out of a page, or fails. |
| +func islandOf(t *testing.T, page string) editorData { |
| + t.Helper() |
| + raw := between(page, `<script type="application/json" id="mapa-editor">`, |
| + "</script>") |
| + var data editorData |
| + if err := json.Unmarshal([]byte(raw), &data); err != nil { |
| + t.Fatalf("the island does not parse: %v\n%s", err, raw) |
| + } |
| + return data |
| +} |
| + |
| +// committed is a page's committed text, as Bo's island holds it (Bo |
| +// has no draft in these tests). |
| +func committed(t *testing.T, rig *rig, path string) string { |
| + t.Helper() |
| + return islandOf(t, rig.page(t, Bo, path)).Source |
| +} |
| + |
| +// draftRow is the person's one draft's base and version, as stored. |
| +func (rig *rig) draftRow(t *testing.T) (base, version int64) { |
| + t.Helper() |
| + row := rig.db.G.Raw("SELECT base_revision, version FROM drafts").Row() |
| + if err := row.Scan(&base, &version); err != nil { |
| + t.Fatal(err) |
| + } |
| + return base, version |
| +} |
| + |
| +const fourBlocks = "One.\n\nTwo.\n\nThree.\n\nFour." |
| + |
| +func mergeOf(t *testing.T, reply map[string]any) map[string]any { |
| + t.Helper() |
| + merge, ok := reply["merge"].(map[string]any) |
| + if !ok { |
| + t.Fatalf("no merge in %v", reply) |
| + } |
| + return merge |
| +} |
| + |
| +func TestL9ACleanRebaseMovesTheBaseAndTheCommitIsSaved(t *testing.T) { |
| + rig := newRig(t) |
| + acme := rig.createPage(t, Ana, "Acme", fourBlocks) |
| + first := revisionOf(t, rig, acme) |
| + _, reply := rig.autosave(t, Ana, acme, first, "0", |
| + "One.\n\nTwo, Ana.\n\nThree.\n\nFour.") |
| + if reply["revision"] != first || reply["merge"] != nil { |
| + t.Fatalf("an autosave over the current revision: %v", reply) |
| + } |
| + rig.post(t, Bo, acme, url.Values{"revision": {first}, |
| + "body": {"One.\n\nTwo.\n\nThree, Bo.\n\n\n\nFour."}}) |
| + second := revisionOf(t, rig, acme) |
| + _, reply = rig.autosave(t, Ana, acme, first, |
| + reply["version"].(string), "One.\n\nTwo, Ana!\n\nThree.\n\nFour.") |
| + merge := mergeOf(t, reply) |
| + want := "One.\n\nTwo, Ana!\n\nThree, Bo.\n\n\n\nFour." |
| + if reply["revision"] != second || merge["against"] != second || |
| + merge["body"] != want { |
| + t.Fatalf("the reply's merge: %v", reply) |
| + } |
| + code, rebased := rig.postJSON(Ana, acme+"/draft", url.Values{ |
| + "rebase": {second}, "body": {want}, |
| + "version": {reply["version"].(string)}}) |
| + if code != http.StatusOK || rebased["merge"] != nil { |
| + t.Fatalf("the rebase: %d %v", code, rebased) |
| + } |
| + if base, _ := rig.draftRow(t); idText(base) != second { |
| + t.Fatal("the rebase did not move the draft's base") |
| + } |
| + saved := rig.post(t, Ana, acme+"/draft/save", |
| + url.Values{"version": {rebased["version"].(string)}}) |
| + if saved.Header().Get("Location") != acme { |
| + t.Fatalf("the commit after a rebase went to %q, not Saved", |
| + saved.Header().Get("Location")) |
| + } |
| + if got := committed(t, rig, acme); got != want { |
| + t.Fatalf("the commit did not keep M's bytes: %q", got) |
| + } |
| +} |
| + |
| +func TestL9ARebaseIsRefusedAndMovesNothing(t *testing.T) { |
| + rig := newRig(t) |
| + moving := rig.clocked(t) |
| + acme := rig.createPage(t, Ana, "Acme", fourBlocks) |
| + other := rig.createPage(t, Ana, "Other", "Elsewhere.") |
| + old := revisionOf(t, rig, acme) |
| + if code, _ := rig.postJSON(Ana, acme+"/draft", url.Values{ |
| + "rebase": {old}, "body": {"x"}}); code != |
| + http.StatusUnprocessableEntity { |
| + t.Fatalf("a rebase with no draft: %d", code) |
| + } |
| + moving.now = moving.now.Add(91 * 24 * time.Hour) |
| + rig.post(t, Bo, acme, url.Values{"revision": {old}, |
| + "body": {"One, Bo."}}) |
| + current := revisionOf(t, rig, acme) |
| + _, reply := rig.autosave(t, Ana, acme, current, "0", "Mine.") |
| + version := reply["version"].(string) |
| + for name, form := range map[string]url.Values{ |
| + "a stale version": {"rebase": {current}, "version": {"1"}}, |
| + "another page's revision": {"rebase": {revisionOf(t, rig, other)}, |
| + "version": {version}}, |
| + "a revision past the window": {"rebase": {old}, |
| + "version": {version}}, |
| + } { |
| + form.Set("body", "Moved?") |
| + code, _ := rig.postJSON(Ana, acme+"/draft", form) |
| + base, stored := rig.draftRow(t) |
| + if code < 400 || idText(base) != current || |
| + idText(stored) != version { |
| + t.Errorf("%s: %d, and the draft moved", name, code) |
| + } |
| + } |
| + if !strings.Contains(rig.page(t, Ana, acme), "Mine.") { |
| + t.Fatal("a refused rebase wrote the draft's text") |
| + } |
| +} |
| + |
| +func TestL9AConflictCarriesItsHunksAndResolveAnswersJSON(t *testing.T) { |
| + rig := newRig(t) |
| + acme := rig.createPage(t, Ana, "Acme", fourBlocks) |
| + first := revisionOf(t, rig, acme) |
| + _, reply := rig.autosave(t, Ana, acme, first, "0", |
| + "One.\n\nTwo, Ana.\n\nThree.\n\nFour.") |
| + rig.post(t, Bo, acme, url.Values{"revision": {first}, |
| + "body": {"One.\n\nTwo, Bo.\n\nThree.\n\nFour, Bo."}}) |
| + second := revisionOf(t, rig, acme) |
| + _, reply = rig.autosave(t, Ana, acme, first, |
| + reply["version"].(string), "Zero.\n\nOne.\n\nTwo, Ana.\n\nThree."+ |
| + "\n\nFour.") |
| + merge := mergeOf(t, reply) |
| + hunks, _ := merge["hunks"].([]any) |
| + if merge["conflict"] != true || merge["against"] != second || |
| + len(hunks) != 1 { |
| + t.Fatalf("the conflict reply: %v", merge) |
| + } |
| + hunk := hunks[0].(map[string]any) |
| + if hunk["at"] != 2.0 || hunk["count"] != 1.0 || |
| + hunk["base"] != "Two." || hunk["mine"] != "Two, Ana." || |
| + hunk["theirs"] != "Two, Bo." { |
| + t.Fatalf("the hunk: %v", hunk) |
| + } |
| + events := rig.count(t, "events") |
| + code, resolved := rig.postJSON(Ana, acme+"/resolve", url.Values{ |
| + "current": {second}, "version": {reply["version"].(string)}, |
| + "choice-0": {"mine"}}) |
| + want := "Zero.\n\nOne.\n\nTwo, Ana.\n\nThree.\n\nFour, Bo." |
| + if code != http.StatusOK || resolved["outcome"] != "saved" || |
| + resolved["body"] != want || resolved["revision"] == second { |
| + t.Fatalf("Resolve's JSON: %d %v", code, resolved) |
| + } |
| + if rig.count(t, "events") != events+1 || rig.count(t, "drafts") != 0 || |
| + committed(t, rig, acme) != want { |
| + t.Fatal("Resolve did not commit the choice exactly once") |
| + } |
| +} |
| + |
| +func TestL9AResolveFromAStaleVersionCommitsNothing(t *testing.T) { |
| + rig := newRig(t) |
| + acme := rig.createPage(t, Ana, "Acme", "One.") |
| + first := revisionOf(t, rig, acme) |
| + _, reply := rig.autosave(t, Ana, acme, first, "0", "One, Ana.") |
| + rig.post(t, Bo, acme, url.Values{"revision": {first}, |
| + "body": {"One, Bo."}}) |
| + second := revisionOf(t, rig, acme) |
| + rig.autosave(t, Ana, acme, first, reply["version"].(string), |
| + "One, Ana, again.") |
| + code, resolved := rig.postJSON(Ana, acme+"/resolve", url.Values{ |
| + "current": {second}, "version": {reply["version"].(string)}, |
| + "choice-0": {"mine"}}) |
| + if code != http.StatusOK || resolved["outcome"] != "conflicted" || |
| + resolved["revision"] != second || resolved["body"] != "One, Bo." { |
| + t.Fatalf("a stale Resolve: %d %v", code, resolved) |
| + } |
| + if revisionOf(t, rig, acme) != second { |
| + t.Fatal("a stale Resolve committed") |
| + } |
| +} |
| + |
| +func TestL9CommitOneNeedsTheCurrentVersion(t *testing.T) { |
| + rig := newRig(t) |
| + acme := rig.createPage(t, Ana, "Acme", "One.") |
| + first := revisionOf(t, rig, acme) |
| + _, tabA := rig.autosave(t, Ana, acme, first, "0", "One, tab A.") |
| + offered := tabA["version"].(string) |
| + // Another tab's draft is offered to this one; it never typed. |
| + _, tabB := rig.autosave(t, Ana, acme, first, offered, "One, tab B.") |
| + events := rig.count(t, "events") |
| + code, _ := rig.postJSON(Ana, acme+"/draft", url.Values{"commit": {"1"}, |
| + "version": {offered}, "body": {"One, closing tab A."}}) |
| + if code != http.StatusConflict || rig.count(t, "events") != events || |
| + revisionOf(t, rig, acme) != first { |
| + t.Fatalf("commit=1 with a stale version: %d", code) |
| + } |
| + if _, stored := rig.draftRow(t); idText(stored) != tabB["version"] { |
| + t.Fatal("commit=1 with a stale version wrote the draft") |
| + } |
| + code, saved := rig.postJSON(Ana, acme+"/draft", url.Values{ |
| + "commit": {"1"}, "version": {tabB["version"].(string)}, |
| + "body": {"One, closing tab B."}}) |
| + if code != http.StatusOK || saved["saved"] != true || |
| + committed(t, rig, acme) != "One, closing tab B." || |
| + rig.count(t, "drafts") != 0 { |
| + t.Fatalf("commit=1 from the current version: %d %v", code, saved) |
| + } |
| +} |
| + |
| +// Past the keepalive cap the closing tab sends no text: the draft as |
| +// last autosaved is committed. |
| +func TestL9CommitOneWithoutABodyCommitsTheStoredDraft(t *testing.T) { |
| + rig := newRig(t) |
| + acme := rig.createPage(t, Ana, "Acme", "One.") |
| + _, reply := rig.autosave(t, Ana, acme, revisionOf(t, rig, acme), "0", |
| + "One, autosaved.") |
| + if code, _ := rig.postJSON(Ana, acme+"/draft", url.Values{ |
| + "commit": {"1"}}); code != http.StatusConflict { |
| + t.Fatalf("commit=1 with no version and no text: %d", code) |
| + } |
| + code, _ := rig.postJSON(Ana, acme+"/draft", url.Values{ |
| + "commit": {"1"}, "version": {reply["version"].(string)}}) |
| + if code != http.StatusOK || |
| + committed(t, rig, acme) != "One, autosaved." { |
| + t.Fatalf("commit=1 with no text: %d", code) |
| + } |
| +} |
| + |
| +func TestL9ASaveThatChangesNothingWritesNothing(t *testing.T) { |
| + rig := newRig(t) |
| + acme := rig.createPage(t, Ana, "Acme", "One.\n\nTwo.") |
| + first := revisionOf(t, rig, acme) |
| + day := "/d/2026-11-20" |
| + rig.post(t, Ana, day, url.Values{"body": {"Written."}}) |
| + revisions, events := rig.count(t, "revisions"), rig.count(t, "events") |
| + rig.post(t, Bo, acme, url.Values{"revision": {first}, |
| + "body": {"One.\n\nTwo.\n\n"}}) |
| + rig.post(t, Ana, day, url.Values{"body": {"Written."}, |
| + "revision": {revisionAs(t, rig, Ana, day)}}) |
| + if rig.count(t, "revisions") != revisions || |
| + rig.count(t, "events") != events || revisionOf(t, rig, acme) != first { |
| + t.Fatal("a save of the same text wrote a revision") |
| + } |
| + // Merged, to exactly the current body: Ana's draft changed nothing |
| + // that Bo's revision had not changed too. |
| + _, reply := rig.autosave(t, Ana, acme, first, "0", "One.\n\nTwo, both.") |
| + rig.post(t, Bo, acme, url.Values{"revision": {first}, |
| + "body": {"One.\n\nTwo, both."}}) |
| + revisions, events = rig.count(t, "revisions"), rig.count(t, "events") |
| + saved := rig.post(t, Ana, acme+"/draft/save", |
| + url.Values{"version": {reply["version"].(string)}}) |
| + if saved.Code != http.StatusSeeOther || |
| + rig.count(t, "revisions") != revisions || |
| + rig.count(t, "events") != events || rig.count(t, "drafts") != 0 { |
| + t.Fatal("a merge equal to the current body wrote, or kept the draft") |
| + } |
| +} |
| + |
| +func TestL9MakeTeamPageRefusesAStaleRevision(t *testing.T) { |
| + rig := newRig(t) |
| + day := "/d/2026-11-12" |
| + rig.post(t, Ana, day, url.Values{"body": {"Mine.\n\nShare this."}}) |
| + note := between(rig.page(t, Ana, day), `href="/p/`, `/share"`) |
| + form := rig.page(t, Ana, "/p/"+note+"/share") |
| + rig.post(t, Ana, day, url.Values{"body": {"New first.\n\nMine." + |
| + "\n\nShare this."}, "revision": {revisionAs(t, rig, Ana, day)}}) |
| + pages, events := rig.count(t, "pages"), rig.count(t, "events") |
| + stale := rig.post(t, Ana, "/p/"+note+"/share", url.Values{ |
| + "title": {"Shared"}, "block": {"1"}, |
| + "revision": {formRevision(form)}}) |
| + if stale.Code != http.StatusUnprocessableEntity || |
| + !strings.Contains(stale.Body.String(), "Choose them again") { |
| + t.Fatalf("a stale Make team page: %d", stale.Code) |
| + } |
| + if rig.count(t, "pages") != pages || rig.count(t, "events") != events { |
| + t.Fatal("a stale Make team page wrote something") |
| + } |
| +} |
| + |
| +func TestL9TheFirstScratchCommitIsSingleFlight(t *testing.T) { |
| + rig := newRig(t) |
| + token := "tab-token-0123456789" |
| + if code, reply := rig.postJSON(Ana, "/scratch", url.Values{ |
| + "first": {"tab-empty-0123456789"}, "body": {" \n"}}); code != |
| + http.StatusUnprocessableEntity || reply["empty"] != true || |
| + rig.count(t, "pages") != 0 { |
| + t.Fatalf("an empty first autosave: %d %v", code, reply) |
| + } |
| + var group sync.WaitGroup |
| + replies := make([]map[string]any, 2) |
| + for at := range replies { |
| + group.Add(1) |
| + go func() { |
| + defer group.Done() |
| + _, replies[at] = rig.postJSON(Ana, "/scratch", url.Values{ |
| + "first": {token}, "body": {"First words."}}) |
| + }() |
| + } |
| + group.Wait() |
| + if rig.count(t, "pages") != 1 || replies[0]["page"] == nil || |
| + replies[0]["page"] != replies[1]["page"] { |
| + t.Fatalf("two quick autosaves: %d pages, %v", rig.count(t, "pages"), |
| + replies) |
| + } |
| + code, later := rig.postJSON(Ana, "/scratch", url.Values{ |
| + "first": {token}, "body": {"First words, and more."}, |
| + "version": {eitherVersion(replies[0]["version"], |
| + replies[1]["version"])}}) |
| + if code != http.StatusOK || later["version"] == nil || |
| + rig.count(t, "pages") != 1 || rig.count(t, "drafts") != 1 { |
| + t.Fatalf("a later autosave is not a draft on the page: %d %v", code, |
| + later) |
| + } |
| +} |
| + |
| +// eitherVersion is whichever reply carried a version: the one that became a |
| +// draft on the page the other made. |
| +func eitherVersion(values ...any) string { |
| + for _, value := range values { |
| + if text, ok := value.(string); ok { |
| + return text |
| + } |
| + } |
| + return "0" |
| +} |
| + |
| +func TestL9NoBaseAndGoneReplies(t *testing.T) { |
| + rig := newRig(t) |
| + moving := rig.clocked(t) |
| + acme := rig.createPage(t, Ana, "Acme", "One.") |
| + first := revisionOf(t, rig, acme) |
| + moving.now = moving.now.Add(91 * 24 * time.Hour) |
| + _, reply := rig.autosave(t, Ana, acme, first, "0", "Mine.") |
| + rig.post(t, Bo, acme, url.Values{"revision": {first}, |
| + "body": {"Bo's."}}) |
| + _, reply = rig.autosave(t, Ana, acme, first, reply["version"].(string), |
| + "Mine, still.") |
| + if mergeOf(t, reply)["noBase"] != true { |
| + t.Fatalf("an aged base: %v", reply) |
| + } |
| + rig.post(t, Bo, acme+"/delete", nil) |
| + _, reply = rig.autosave(t, Ana, acme, first, reply["version"].(string), |
| + "Mine, after.") |
| + if mergeOf(t, reply)["gone"] != true || reply["revision"] != nil { |
| + t.Fatalf("a deleted page: %v", reply) |
| + } |
| + _, day := rig.autosave(t, Ana, "/d/2026-11-30", "0", "0", "A day.") |
| + if day["revision"] != nil || day["merge"] != nil || day["version"] == "" { |
| + t.Fatalf("an unwritten day's autosave: %v", day) |
| + } |
| +} |
| + |
| +func idText(value int64) string { return strconv.FormatInt(value, 10) } |