Phase 1 step 7: ⌘K's groups and dates
Level-up §4.6. /search/suggest and GET /search?q= answer in groups: Pages (team titles and aliases; an alias hit reads "Old title of <title>"), In the text (team pages by their words, the snippet with UTF-16 match ranges, never HTML), and Your notes (the viewer's own daily and scratch pages, "Only you see these"), each group ranked as before and capped on its own. A typed date adds one row, resolved in the viewer's zone, taking the place of that day's note in Your notes. Create stays last and unchanged (base §6.3). Each partition is ranked on its own with the same team-only statistics, so the order is the one the combined ranking gave, and Your notes reads only searchPartitions' own partition. The palette is restyled after the mock-up in a new palette.css: one box, grouped listbox options with aria-activedescendant, a polite count, ⌘↵ to create, Esc closing at once with focus back on its opener, the hint foot hidden on phones. Snippets are marked with <mark> built from text nodes. Gates: gate 1 adds Bo's own scratch page and the groups and date row to its byte-identical comparison, and checks Your notes holds only the viewer's own pages; L7 hashes every table's rows around the search GETs; a browser walk of ⌘K by keyboard.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
14 files changed,
+1,107
−140
internal/mapa/handlers_search.go+25 −5internal/mapa/rank.go+13 −44internal/mapa/search.go+69 −25internal/mapa/search_groups_test.go+134 −0internal/mapa/search_test.go+8 −8internal/mapa/snippet.go+148 −0internal/mapa/static/mapa.js+201 −50internal/mapa/static/palette.css+231 −0internal/mapa/templates/search.html+26 −6internal/mapa/templates/shell.html+1 −0internal/mapatest/gate1_test.go+7 −0internal/mapatest/palette_browser_test.go+82 −0internal/mapatest/palette_test.go+160 −0internal/mapatest/speed_test.go+2 −2
diff --git a/internal/mapa/handlers_search.go b/internal/mapa/handlers_search.go| index c6f209e..fdebf16 100644 |
| --- a/internal/mapa/handlers_search.go |
| +++ b/internal/mapa/handlers_search.go |
| @@ -3,6 +3,7 @@ package mapa |
| import ( |
| "encoding/json" |
| "net/http" |
| + "time" |
| "github.com/go-chi/chi/v5" |
| ) |
| @@ -10,9 +11,11 @@ import ( |
| // Search's screens (§6): GET /search?q= is the whole page, and works with |
| // scripts off; ⌘K and [[ autocomplete read the two JSON answers. |
| -// searchLimit and suggestLimit are how many results each shows. |
| +// searchLimit and paletteLimit are how many results each group of the |
| +// search page and of ⌘K shows; suggestLimit is [['s. |
| const ( |
| searchLimit = 50 |
| + paletteLimit = 5 |
| suggestLimit = 8 |
| ) |
| @@ -29,8 +32,7 @@ func (app *app) searchPage(writer http.ResponseWriter, |
| app.fail(writer, request, err) |
| return |
| } |
| - results, err := app.index.Search(request.Context(), ScopeOf(viewer), |
| - request.URL.Query().Get("q"), searchLimit) |
| + results, err := app.search(request, viewer, searchLimit) |
| if err != nil { |
| app.fail(writer, request, err) |
| return |
| @@ -39,6 +41,25 @@ func (app *app) searchPage(writer http.ResponseWriter, |
| Title: "Search", Nav: nav("/search"), Viewer: viewer, Data: results}) |
| } |
| +// search is the query's groups, and its typed-date row, resolved in the |
| +// viewer's own zone (level-up §4.6). |
| +func (app *app) search(request *http.Request, viewer Viewer, |
| + limit int) (Results, error) { |
| + query := request.URL.Query().Get("q") |
| + results, err := app.index.Search(request.Context(), ScopeOf(viewer), |
| + query, limit) |
| + if err != nil { |
| + return results, err |
| + } |
| + zone := viewer.TimeZone |
| + if zone == nil { |
| + zone = time.UTC |
| + } |
| + today := todayIn(app.store.now(), zone) |
| + results.withDate(dateRow(typedDate(query, today), today)) |
| + return results, nil |
| +} |
| + |
| // searchSuggest is ⌘K's answer: the same search, fewer hits. |
| func (app *app) searchSuggest(writer http.ResponseWriter, |
| request *http.Request) { |
| @@ -47,8 +68,7 @@ func (app *app) searchSuggest(writer http.ResponseWriter, |
| app.fail(writer, request, err) |
| return |
| } |
| - results, err := app.index.Search(request.Context(), ScopeOf(viewer), |
| - request.URL.Query().Get("q"), suggestLimit) |
| + results, err := app.search(request, viewer, paletteLimit) |
| if err != nil { |
| app.fail(writer, request, err) |
| return |
diff --git a/internal/mapa/rank.go b/internal/mapa/rank.go| index b91115c..1c8f67d 100644 |
| --- a/internal/mapa/rank.go |
| +++ b/internal/mapa/rank.go |
| @@ -3,9 +3,6 @@ package mapa |
| import ( |
| "math" |
| "sort" |
| - "strings" |
| - |
| - "amadan.net/oficina/mapa/internal/mapa/markup" |
| ) |
| // BM25's usual constants. |
| @@ -47,22 +44,25 @@ type scored struct { |
| score float64 |
| } |
| -// bodyHits ranks the pages whose words hold every token, the last one |
| -// as a prefix. One typed letter searches titles only: as a prefix it |
| -// would stand for most of the dictionary. |
| -func (index *Index) bodyHits(scope Scope, tokens []string, |
| - limit int) []Hit { |
| +// bodyHits ranks one partition's pages whose words hold every token, |
| +// the last one as a prefix, leaving out the pages already taken. One |
| +// typed letter searches titles only: as a prefix it would stand for |
| +// most of the dictionary. |
| +func (index *Index) bodyHits(part *partition, tokens []string, limit int, |
| + taken map[int64]bool) []Hit { |
| last := tokens[len(tokens)-1] |
| if len(tokens) == 1 && len([]rune(last)) < 2 { |
| return nil |
| } |
| - stats := index.stats() |
| - var candidates []scored |
| - for _, part := range index.searchPartitions(scope) { |
| - candidates = append(candidates, part.match(tokens, stats)...) |
| + candidates := part.match(tokens, index.stats()) |
| + kept := candidates[:0] |
| + for _, candidate := range candidates { |
| + if !taken[candidate.pageID] { |
| + kept = append(kept, candidate) |
| + } |
| } |
| // The backlink boost re-orders the head of the list only. |
| - head := topK(candidates, limit*4, better) |
| + head := topK(kept, limit*4, better) |
| for number := range head { |
| head[number].score += index.boost(head[number].pageID) |
| } |
| @@ -163,34 +163,3 @@ func (part *partition) prefixed(prefix string) []string { |
| return one < other |
| }) |
| } |
| - |
| -// snippet is the first block that holds a token, cut to fit. |
| -func snippet(page *entry, tokens []string) string { |
| - for _, block := range page.blocks { |
| - text := strings.Join(strings.Fields(markup.Words(block)), " ") |
| - for _, found := range wordsOf(text) { |
| - for _, token := range tokens { |
| - if strings.HasPrefix(found.fold, token) { |
| - return around(text, found.start) |
| - } |
| - } |
| - } |
| - } |
| - return "" |
| -} |
| - |
| -// around is up to 160 characters of text near byte offset at. |
| -func around(text string, at int) string { |
| - runes := []rune(text) |
| - center := len([]rune(text[:at])) |
| - start := max(0, center-50) |
| - end := min(len(runes), start+160) |
| - out := string(runes[start:end]) |
| - if start > 0 { |
| - out = "…" + out |
| - } |
| - if end < len(runes) { |
| - out += "…" |
| - } |
| - return out |
| -} |
diff --git a/internal/mapa/search.go b/internal/mapa/search.go| index 4a91984..8319a49 100644 |
| --- a/internal/mapa/search.go |
| +++ b/internal/mapa/search.go |
| @@ -16,21 +16,60 @@ import ( |
| // Hit is one search result. |
| type Hit struct { |
| - ID int64 `json:"-"` |
| - Label string `json:"label"` |
| - Href string `json:"href"` |
| - Kind string `json:"kind"` |
| - Snippet string `json:"snippet,omitempty"` |
| - // Via is the alias a title hit matched, when it was not the title. |
| + ID int64 `json:"-"` |
| + Label string `json:"label"` |
| + Href string `json:"href"` |
| + Kind string `json:"kind"` |
| + Snippet *Snippet `json:"snippet,omitempty"` |
| + // Via is the alias a title hit matched, when it was not the title: |
| + // "Old title of <Label>". |
| Via string `json:"via,omitempty"` |
| } |
| -// Results is a search's answer, and the "Create" offer: the query as a |
| -// title, when no team page holds it and it could be one. |
| +// Results is a search's answer in ⌘K's groups (level-up §4.6). Pages |
| +// is team titles and aliases; Text is team pages found by their words; |
| +// Notes is the viewer's own daily and scratch pages, and only theirs. |
| +// Date is the typed-date row, and Create the "Create" offer: the query |
| +// as a title, when no team page holds it and it could be one. |
| type Results struct { |
| - Query string `json:"query"` |
| - Hits []Hit `json:"hits"` |
| - Create string `json:"create,omitempty"` |
| + Query string `json:"query"` |
| + Date *DateHit `json:"date,omitempty"` |
| + Pages []Hit `json:"pages"` |
| + Text []Hit `json:"text"` |
| + Notes []Hit `json:"notes"` |
| + Create string `json:"create,omitempty"` |
| +} |
| + |
| +// All is every hit, group by group. |
| +func (results Results) All() []Hit { |
| + all := append([]Hit{}, results.Pages...) |
| + return append(append(all, results.Text...), results.Notes...) |
| +} |
| + |
| +// Count is how many rows answer the query: the hits and the date row, |
| +// not the Create offer. |
| +func (results Results) Count() int { |
| + count := len(results.Pages) + len(results.Text) + len(results.Notes) |
| + if results.Date != nil { |
| + count++ |
| + } |
| + return count |
| +} |
| + |
| +// withDate adds the row for a typed date, and takes the viewer's note |
| +// for that day out of Notes: one row per day. |
| +func (results *Results) withDate(row *DateHit) { |
| + if row == nil { |
| + return |
| + } |
| + results.Date = row |
| + notes := results.Notes[:0] |
| + for _, hit := range results.Notes { |
| + if hit.Href != row.Href { |
| + notes = append(notes, hit) |
| + } |
| + } |
| + results.Notes = notes |
| } |
| // titleRow is one team title or alias. |
| @@ -77,7 +116,7 @@ func (index *Index) rebuildTitles() { |
| index.titleRows, index.titlesDirty = rows, false |
| } |
| -// Search answers query for scope, at most limit hits. |
| +// Search answers query for scope, at most limit hits in each group. |
| func (index *Index) Search(ctx context.Context, scope Scope, query string, |
| limit int) (Results, error) { |
| if err := index.Sync(ctx); err != nil { |
| @@ -85,21 +124,27 @@ func (index *Index) Search(ctx context.Context, scope Scope, query string, |
| } |
| index.mutex.RLock() |
| defer index.mutex.RUnlock() |
| - results := Results{Query: strings.TrimSpace(query)} |
| + results := Results{Query: strings.TrimSpace(query), Pages: []Hit{}, |
| + Text: []Hit{}, Notes: []Hit{}} |
| tokens := queryWords(query) |
| if len(tokens) == 0 { |
| return results, nil |
| } |
| - results.Hits = index.titleHits(scope, query, tokens, limit) |
| + results.Pages = index.titleHits(query, tokens, limit) |
| + results.Notes = index.dayHits(scope, query, limit) |
| taken := map[int64]bool{} |
| - for _, hit := range results.Hits { |
| + for _, hit := range results.All() { |
| taken[hit.ID] = true |
| } |
| - for _, hit := range index.bodyHits(scope, tokens, limit) { |
| - if len(results.Hits) < limit && !taken[hit.ID] { |
| - results.Hits = append(results.Hits, hit) |
| + for _, part := range index.searchPartitions(scope) { |
| + hits := index.bodyHits(part, tokens, limit, taken) |
| + if part == index.teamTerms { |
| + results.Text = append(results.Text, hits...) |
| + } else { |
| + results.Notes = append(results.Notes, hits...) |
| } |
| } |
| + results.Notes = results.Notes[:min(limit, len(results.Notes))] |
| results.Create = index.createOffer(query) |
| return results, nil |
| } |
| @@ -134,8 +179,8 @@ func (index *Index) createOffer(query string) string { |
| // titleHits is the team titles and aliases every token starts a word |
| // of: the exact title first, then titles the query begins, then the |
| -// rest, each page once. Then the viewer's own days, by date prefix. |
| -func (index *Index) titleHits(scope Scope, query string, tokens []string, |
| +// rest, each page once. |
| +func (index *Index) titleHits(query string, tokens []string, |
| limit int) []Hit { |
| whole := Fold(query) |
| best := map[int64]titleMatch{} |
| @@ -155,8 +200,7 @@ func (index *Index) titleHits(scope Scope, query string, tokens []string, |
| best[row.pageID] = match |
| } |
| } |
| - hits := index.rankedTitles(best, limit) |
| - return append(hits, index.dayHits(scope, query, limit-len(hits))...) |
| + return index.rankedTitles(best, limit) |
| } |
| // titleMatch is a page's best matching title or alias. |
| @@ -182,7 +226,7 @@ func (index *Index) rankedTitles(best map[int64]titleMatch, |
| for _, match := range best { |
| matches = append(matches, match) |
| } |
| - var hits []Hit |
| + hits := []Hit{} |
| for _, match := range topK(matches, limit, titleMatch.before) { |
| page := index.pages[match.row.pageID] |
| hit := Hit{ID: page.id, Label: page.label(), Href: page.href(), |
| @@ -218,7 +262,7 @@ func (index *Index) dayHits(scope Scope, query string, limit int) []Hit { |
| query = strings.TrimSpace(query) |
| if scope.Member == 0 || limit <= 0 || query == "" || |
| query[0] < '0' || query[0] > '9' { |
| - return nil |
| + return []Hit{} |
| } |
| var dates []string |
| for date := range index.days[scope.Member] { |
| @@ -227,7 +271,7 @@ func (index *Index) dayHits(scope Scope, query string, limit int) []Hit { |
| } |
| } |
| sort.Sort(sort.Reverse(sort.StringSlice(dates))) |
| - var hits []Hit |
| + hits := []Hit{} |
| for _, date := range dates[:min(limit, len(dates))] { |
| page := index.pages[index.days[scope.Member][date]] |
| hits = append(hits, Hit{ID: page.id, Label: page.label(), |
diff --git a/internal/mapa/search_groups_test.go b/internal/mapa/search_groups_test.go| new file mode 100644 |
| index 0000000..23a3c5d |
| --- /dev/null |
| +++ b/internal/mapa/search_groups_test.go |
| @@ -0,0 +1,134 @@ |
| +package mapa |
| + |
| +import ( |
| + "strings" |
| + "testing" |
| +) |
| + |
| +func groupLabels(hits []Hit) string { |
| + var out []string |
| + for _, hit := range hits { |
| + out = append(out, hit.Label) |
| + } |
| + return strings.Join(out, " | ") |
| +} |
| + |
| +// ⌘K's groups (level-up §4.6): team titles and aliases under Pages, team |
| +// pages found by their words under In the text, and the viewer's own |
| +// daily and scratch pages under Your notes, each page once. |
| +func TestSearchAnswersInGroups(t *testing.T) { |
| + store := testStore(t) |
| + index := NewIndex(store) |
| + mustCreate(t, store, "Brightwater Labs", "") |
| + old := mustCreate(t, store, "Bright ideas", "") |
| + store.Rename(ctx(), ana, old.ID, "Halden Robotics") |
| + mustCreate(t, store, "Q4 renewals", "The biggest is Brightwater Labs.") |
| + mustCreate(t, store, "Pilot", "Brightwater pilot.") |
| + store.SaveDaily(ctx(), ana, "2026-11-12", 0, "Tom: Brightwater signs.") |
| + store.CreateScratch(ctx(), ana, "brightwater musings") |
| + store.CreateScratch(ctx(), bo, "brightwater, as Bo has it") |
| + got := search(t, index, scopeOf(t, store, ana), "brigh") |
| + if groupLabels(got.Pages) != "Brightwater Labs | Halden Robotics" || |
| + got.Pages[1].Via != "Bright ideas" || got.Pages[0].Via != "" { |
| + t.Fatalf("pages: %+v", got.Pages) |
| + } |
| + if groupLabels(got.Text) != "Pilot | Q4 renewals" { |
| + t.Fatalf("in the text: %q", groupLabels(got.Text)) |
| + } |
| + notes := groupLabels(got.Notes) |
| + if !strings.Contains(notes, "Thursday 12 November 2026") || |
| + !strings.Contains(notes, "brightwater musings") || |
| + strings.Contains(notes, "Bo") || len(got.Notes) != 2 { |
| + t.Fatalf("Ana's notes: %q", notes) |
| + } |
| + for _, hit := range got.Notes { |
| + if hit.Kind == KindPage || hit.Snippet == nil { |
| + t.Fatalf("a note that is not Ana's own, or unmarked: %+v", hit) |
| + } |
| + } |
| + if got.Create != "brigh" || got.Count() != 6 { |
| + t.Fatalf("create %q, count %d", got.Create, got.Count()) |
| + } |
| +} |
| + |
| +// Each group holds at most the limit, so one group's many hits do not |
| +// crowd out the others. |
| +func TestEachGroupHasItsOwnLimit(t *testing.T) { |
| + store := testStore(t) |
| + index := NewIndex(store) |
| + for _, title := range []string{"Kelp one", "Kelp two", "Kelp three"} { |
| + mustCreate(t, store, title, "") |
| + } |
| + for _, title := range []string{"Alpha", "Beta", "Gamma"} { |
| + mustCreate(t, store, title, "kelp farming") |
| + } |
| + for range 3 { |
| + store.CreateScratch(ctx(), ana, "kelp notes") |
| + } |
| + results, err := index.Search(ctx(), scopeOf(t, store, ana), "kelp", 2) |
| + if err != nil || len(results.Pages) != 2 || len(results.Text) != 2 || |
| + len(results.Notes) != 2 { |
| + t.Fatalf("%+v %v", results, err) |
| + } |
| +} |
| + |
| +// The date row takes the place of the note for that day: one row a day. |
| +func TestTheDateRowReplacesThatDaysNote(t *testing.T) { |
| + store := testStore(t) |
| + index := NewIndex(store) |
| + store.SaveDaily(ctx(), ana, "2026-11-12", 0, "written") |
| + results := search(t, index, scopeOf(t, store, ana), "2026-11-12") |
| + if len(results.Notes) != 1 { |
| + t.Fatalf("the day is not among Ana's notes: %+v", results.Notes) |
| + } |
| + results.withDate(dateRow("2026-11-12", "2026-11-14")) |
| + if len(results.Notes) != 0 || results.Date == nil || |
| + results.Count() != 1 { |
| + t.Fatalf("%+v", results) |
| + } |
| +} |
| + |
| +// The snippet marks what the query typed of each word, in UTF-16 units, |
| +// and the parts a template renders join back to the text. |
| +func TestTheSnippetMarksTheMatch(t *testing.T) { |
| + store := testStore(t) |
| + index := NewIndex(store) |
| + mustCreate(t, store, "Zed", "😀 Ünïcode ünion and unity, unbound.") |
| + hit := search(t, index, Scope{}, "un").Text[0] |
| + snip := hit.Snippet |
| + if snip.Text != "😀 Ünïcode ünion and unity, unbound." { |
| + t.Fatalf("text %q", snip.Text) |
| + } |
| + var marked []string |
| + for _, part := range snip.Parts() { |
| + if part.Marked { |
| + marked = append(marked, part.Text) |
| + } |
| + } |
| + if strings.Join(marked, ",") != "Ün,ün,un,un" { |
| + t.Fatalf("marked %q, marks %v", marked, snip.Marks) |
| + } |
| + // The emoji is two UTF-16 units, so "Ün" starts at 3. |
| + if snip.Marks[0] != [2]int{3, 5} { |
| + t.Fatalf("marks %v", snip.Marks) |
| + } |
| +} |
| + |
| +// A long block is cut around the match, and the marks follow the cut. |
| +func TestALongSnippetIsCutAroundTheMatch(t *testing.T) { |
| + store := testStore(t) |
| + index := NewIndex(store) |
| + body := strings.Repeat("filler ", 60) + "zebracorn " + |
| + strings.Repeat("after ", 60) |
| + mustCreate(t, store, "Long", body) |
| + snip := search(t, index, Scope{}, "zebra").Text[0].Snippet |
| + runes := []rune(snip.Text) |
| + if runes[0] != '…' || runes[len(runes)-1] != '…' || |
| + len(runes) != snippetWidth+2 || len(snip.Marks) != 1 { |
| + t.Fatalf("%q %v", snip.Text, snip.Marks) |
| + } |
| + at := snip.Marks[0] |
| + if string(runes[at[0]:at[1]]) != "zebra" { |
| + t.Fatalf("marked %q", string(runes[at[0]:at[1]])) |
| + } |
| +} |
diff --git a/internal/mapa/search_test.go b/internal/mapa/search_test.go| index eb860df..290f577 100644 |
| --- a/internal/mapa/search_test.go |
| +++ b/internal/mapa/search_test.go |
| @@ -7,7 +7,7 @@ import ( |
| func labels(results Results) string { |
| var out []string |
| - for _, hit := range results.Hits { |
| + for _, hit := range results.All() { |
| out = append(out, hit.Label) |
| } |
| return strings.Join(out, " | ") |
| @@ -44,9 +44,9 @@ func TestAnAliasFindsItsPageAndSaysSo(t *testing.T) { |
| page := mustCreate(t, store, "Acme", "") |
| store.Rename(ctx(), ana, page.ID, "Brightwater") |
| results := search(t, index, Scope{}, "acm") |
| - if len(results.Hits) != 1 || results.Hits[0].Label != "Brightwater" || |
| - results.Hits[0].Via != "Acme" { |
| - t.Fatalf("hits %+v", results.Hits) |
| + if len(results.All()) != 1 || results.Pages[0].Label != "Brightwater" || |
| + results.Pages[0].Via != "Acme" { |
| + t.Fatalf("hits %+v", results.All()) |
| } |
| } |
| @@ -82,7 +82,7 @@ func TestPrivatePagesAreSearchedByTheirOwnerOnly(t *testing.T) { |
| } |
| store.SetTimeZone(ctx(), bo, "UTC") |
| if got := search(t, index, scopeOf(t, store, bo), "zebracorn"); len( |
| - got.Hits) != 0 { |
| + got.All()) != 0 { |
| t.Fatalf("Bo found %q", labels(got)) |
| } |
| if got := labels(search(t, index, scopeOf(t, store, ana), |
| @@ -109,8 +109,8 @@ func TestTheIndexFollowsEditsDeletesAndRenames(t *testing.T) { |
| page := mustCreate(t, store, "Acme", "alpha") |
| search(t, index, Scope{}, "alpha") |
| store.Commit(ctx(), bo, page.ID, page.Revision, "beta") |
| - if len(search(t, index, Scope{}, "alpha").Hits) != 0 || |
| - len(search(t, index, Scope{}, "beta").Hits) != 1 { |
| + if len(search(t, index, Scope{}, "alpha").All()) != 0 || |
| + len(search(t, index, Scope{}, "beta").All()) != 1 { |
| t.Fatal("an edit did not reach the index") |
| } |
| store.Rename(ctx(), bo, page.ID, "Zenith") |
| @@ -118,7 +118,7 @@ func TestTheIndexFollowsEditsDeletesAndRenames(t *testing.T) { |
| t.Fatal("a rename did not reach the titles") |
| } |
| store.Delete(ctx(), bo, page.ID) |
| - if len(search(t, index, Scope{}, "beta").Hits) != 0 { |
| + if len(search(t, index, Scope{}, "beta").All()) != 0 { |
| t.Fatal("a deleted page is still found") |
| } |
| } |
diff --git a/internal/mapa/snippet.go b/internal/mapa/snippet.go| new file mode 100644 |
| index 0000000..cf0f861 |
| --- /dev/null |
| +++ b/internal/mapa/snippet.go |
| @@ -0,0 +1,148 @@ |
| +package mapa |
| + |
| +import ( |
| + "strings" |
| + "unicode/utf16" |
| + |
| + "amadan.net/oficina/mapa/internal/mapa/markup" |
| +) |
| + |
| +// Snippet is "In the text" (level-up §4.6): a block's words near a |
| +// match, and the spans to mark. Marks are [start, end) offsets in |
| +// UTF-16 code units, which is how a script indexes a string, so the |
| +// script marks the text by slicing it and never parses markup. |
| +type Snippet struct { |
| + Text string `json:"text"` |
| + Marks [][2]int `json:"marks"` |
| +} |
| + |
| +// SnippetPart is a run of a snippet's text, marked or not: what the |
| +// scriptless page renders. |
| +type SnippetPart struct { |
| + Text string |
| + Marked bool |
| +} |
| + |
| +// snippetWidth is how many characters a snippet holds, and lead how many |
| +// of them come before the match. |
| +const ( |
| + snippetWidth = 160 |
| + snippetLead = 50 |
| +) |
| + |
| +// snippet is the first block that holds a token, cut to fit, with every |
| +// word a token starts marked; nil if no block holds one. |
| +func snippet(page *entry, tokens []string) *Snippet { |
| + for _, block := range page.blocks { |
| + text := strings.Join(strings.Fields(markup.Words(block)), " ") |
| + found := wordsOf(text) |
| + for _, item := range found { |
| + if longestToken(item.fold, tokens) != "" { |
| + return marked(text, found, item.start, tokens) |
| + } |
| + } |
| + } |
| + return nil |
| +} |
| + |
| +// marked is up to snippetWidth characters of text near byte offset at. |
| +func marked(text string, found []word, at int, tokens []string) *Snippet { |
| + start, end := window(text, at) |
| + out := &Snippet{Marks: [][2]int{}} |
| + if start > 0 { |
| + out.Text = "…" |
| + } |
| + lead := units(out.Text) |
| + out.Text += text[start:end] |
| + if end < len(text) { |
| + out.Text += "…" |
| + } |
| + for _, item := range found { |
| + if item.start >= end { |
| + break |
| + } |
| + token := longestToken(item.fold, tokens) |
| + if token == "" || item.start < start { |
| + continue |
| + } |
| + stop := item.start + prefixBytes(text[item.start:item.end], token) |
| + if stop > end { |
| + break |
| + } |
| + out.Marks = append(out.Marks, [2]int{ |
| + lead + units(text[start:item.start]), |
| + lead + units(text[start:stop])}) |
| + } |
| + return out |
| +} |
| + |
| +// window is the byte span of up to snippetWidth runes of text, starting |
| +// snippetLead runes before byte offset at. |
| +func window(text string, at int) (int, int) { |
| + var starts []int |
| + for offset := range text { |
| + starts = append(starts, offset) |
| + } |
| + center := len([]rune(text[:at])) |
| + first := max(0, center-snippetLead) |
| + last := first + snippetWidth |
| + if last >= len(starts) { |
| + return starts[first], len(text) |
| + } |
| + return starts[first], starts[last] |
| +} |
| + |
| +// longestToken is the longest token folded starts, or "". |
| +func longestToken(folded string, tokens []string) string { |
| + best := "" |
| + for _, token := range tokens { |
| + if len(token) > len(best) && strings.HasPrefix(folded, token) { |
| + best = token |
| + } |
| + } |
| + return best |
| +} |
| + |
| +// prefixBytes is how many bytes of word, as written, fold to token: the |
| +// part of the word the query typed. |
| +func prefixBytes(word, token string) int { |
| + for offset := range word { |
| + if offset > 0 && len(Fold(word[:offset])) >= len(token) { |
| + return offset |
| + } |
| + } |
| + return len(word) |
| +} |
| + |
| +// units is text's length in UTF-16 code units. |
| +func units(text string) int { |
| + count := 0 |
| + for _, char := range text { |
| + count += utf16.RuneLen(char) |
| + } |
| + return count |
| +} |
| + |
| +// Parts is the snippet as runs, marked and not, for a template. |
| +func (snip *Snippet) Parts() []SnippetPart { |
| + var parts []SnippetPart |
| + runes := []rune(snip.Text) |
| + at, place := 0, 0 |
| + take := func(stop int, marked bool) { |
| + begin := place |
| + for place < len(runes) && at < stop { |
| + at += utf16.RuneLen(runes[place]) |
| + place++ |
| + } |
| + if place > begin { |
| + parts = append(parts, SnippetPart{Text: string(runes[begin:place]), |
| + Marked: marked}) |
| + } |
| + } |
| + for _, span := range snip.Marks { |
| + take(span[0], false) |
| + take(span[1], true) |
| + } |
| + take(units(snip.Text), false) |
| + return parts |
| +} |
diff --git a/internal/mapa/static/mapa.js b/internal/mapa/static/mapa.js| index 36790a0..359e922 100644 |
| --- a/internal/mapa/static/mapa.js |
| +++ b/internal/mapa/static/mapa.js |
| @@ -339,43 +339,132 @@ |
| }; |
| // ---- ⌘K ---------------------------------------------------------------- |
| + // One box over titles, aliases, text and dates (level-up §4.6): a modal |
| + // <dialog> whose input is a combobox over a grouped listbox. The answer |
| + // is /search/suggest's JSON: Pages, In the text, Your notes, a typed |
| + // date's row, and Create last. Snippets come with match ranges and are |
| + // marked here from text nodes; nothing from the server is parsed as |
| + // markup. |
| + |
| + // Lucide's outlines, as paths: the icons are the only colour (Calma). |
| + var PALETTE_ICONS = { |
| + search: ["M19 11a8 8 0 1 1-16 0 8 8 0 0 1 16 0Z", "m21 21-4.3-4.3"], |
| + page: ["M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z", |
| + "M14 2v4a2 2 0 0 0 2 2h4", "M10 9H8", "M16 13H8", "M16 17H8"], |
| + daily: ["M8 2v4", "M16 2v4", "M3 10h18", |
| + "M5 4h14a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2Z"], |
| + scratch: ["M16 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V8Z", |
| + "M15 3v4a2 2 0 0 0 2 2h4"], |
| + create: ["M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z", |
| + "M14 2v4a2 2 0 0 0 2 2h4", "M9 15h6", "M12 12v6"] |
| + }; |
| + |
| + function paletteIcon(name) { |
| + var space = "http://www.w3.org/2000/svg"; |
| + var svg = document.createElementNS(space, "svg"); |
| + svg.setAttribute("viewBox", "0 0 24 24"); |
| + svg.setAttribute("aria-hidden", "true"); |
| + svg.setAttribute("mapa-palette-svg", ""); |
| + PALETTE_ICONS[name].forEach(function (shape) { |
| + var path = document.createElementNS(space, "path"); |
| + path.setAttribute("d", shape); |
| + svg.appendChild(path); |
| + }); |
| + return svg; |
| + } |
| + |
| + function paletteElement(tag, attributes, text) { |
| + var element = document.createElement(tag); |
| + Object.keys(attributes || {}).forEach(function (name) { |
| + element.setAttribute(name, attributes[name]); |
| + }); |
| + if (text) element.textContent = text; |
| + return element; |
| + } |
| + |
| + // markSnippet appends a snippet's text to parent, each range in a |
| + // <mark>. Ranges are UTF-16 offsets, which is how a string slices. |
| + function markSnippet(parent, snippet) { |
| + var text = snippet.text, at = 0; |
| + parent.appendChild(document.createTextNode("“")); |
| + (snippet.marks || []).forEach(function (range) { |
| + if (range[0] < at || range[1] > text.length) return; |
| + parent.appendChild(document.createTextNode(text.slice(at, range[0]))); |
| + parent.appendChild(paletteElement("mark", {}, text.slice(range[0], range[1]))); |
| + at = range[1]; |
| + }); |
| + parent.appendChild(document.createTextNode(text.slice(at) + "”")); |
| + } |
| function Palette() { |
| - this.dialog = document.createElement("dialog"); |
| - this.dialog.setAttribute("mapa-palette", ""); |
| - this.dialog.setAttribute("aria-label", "Search Mapa"); |
| - this.input = document.createElement("input"); |
| - this.input.type = "search"; |
| - this.input.setAttribute("rst-input", ""); |
| - this.input.setAttribute("aria-label", "Search pages"); |
| - this.input.placeholder = "Search pages, or type a title to create one"; |
| - this.list = document.createElement("ul"); |
| - this.list.setAttribute("mapa-palette-results", ""); |
| - this.list.setAttribute("role", "listbox"); |
| - this.dialog.appendChild(this.input); |
| + var palette = this; |
| + this.dialog = paletteElement("dialog", { "mapa-palette": "", "aria-label": "Search Mapa" }); |
| + var box = paletteElement("div", { "mapa-palette-box": "" }); |
| + box.appendChild(paletteIcon("search")); |
| + this.input = paletteElement("input", { |
| + type: "search", role: "combobox", "aria-label": "Search pages, or type a title to create one", |
| + placeholder: "Search, or type a title to create one", "aria-expanded": "false", |
| + "aria-controls": "mapa-palette-list", "aria-autocomplete": "list", |
| + autocomplete: "off", spellcheck: "false", enterkeyhint: "go" |
| + }); |
| + box.appendChild(this.input); |
| + var esc = paletteElement("button", { type: "button", "mapa-palette-esc": "", "aria-label": "Close" }, "esc"); |
| + esc.addEventListener("click", function () { palette.dialog.close(); }); |
| + box.appendChild(esc); |
| + this.list = paletteElement("div", { |
| + id: "mapa-palette-list", role: "listbox", "aria-label": "Results", "mapa-palette-results": "" |
| + }); |
| + this.count = paletteElement("div", { "mapa-sr": "", role: "status", "aria-live": "polite" }); |
| + this.dialog.appendChild(box); |
| this.dialog.appendChild(this.list); |
| + this.dialog.appendChild(this.foot()); |
| + this.dialog.appendChild(this.count); |
| document.body.appendChild(this.dialog); |
| - this.links = []; |
| + this.options = []; |
| this.chosen = 0; |
| - var palette = this; |
| + this.create = ""; |
| // No debounce: an answer takes about a millisecond at 10,000 pages, |
| // and §6.1's budget is 100 ms from keystroke to paint. A stale |
| // answer is dropped when it arrives (fetch compares the query). |
| this.input.addEventListener("input", function () { palette.fetch(); }); |
| this.input.addEventListener("keydown", function (event) { palette.keys(event); }); |
| + // Esc closes (the dialog's own cancel), as does a click outside it; |
| + // either way focus goes back to what opened it. |
| + this.dialog.addEventListener("click", function (event) { |
| + if (event.target === palette.dialog) palette.dialog.close(); |
| + }); |
| + this.dialog.addEventListener("close", function () { |
| + var opener = palette.opener; |
| + palette.opener = null; |
| + if (opener && opener.isConnected && opener.focus) opener.focus(); |
| + }); |
| } |
| + // foot is the keyboard hints, hidden on phones by palette.css. |
| + Palette.prototype.foot = function () { |
| + var foot = paletteElement("div", { "mapa-palette-foot": "", "aria-hidden": "true" }); |
| + [[["↑", "↓"], "to move"], [["↵"], "to open"], [["⌘", "↵"], "to create"], |
| + [[], "Type a date, like “friday”, to open that day"]].forEach(function (hint) { |
| + var item = paletteElement("span"); |
| + hint[0].forEach(function (key) { item.appendChild(paletteElement("kbd", { "mapa-kbd": "" }, key)); }); |
| + item.appendChild(document.createTextNode(hint[1])); |
| + foot.appendChild(item); |
| + }); |
| + return foot; |
| + }; |
| + |
| Palette.prototype.open = function () { |
| + if (this.dialog.open) { this.input.focus(); return; } |
| + this.opener = document.activeElement; |
| this.input.value = ""; |
| - this.list.textContent = ""; |
| - this.links = []; |
| + this.render({}); |
| this.dialog.showModal(); |
| this.input.focus(); |
| }; |
| Palette.prototype.fetch = function () { |
| var palette = this, query = this.input.value; |
| - if (!query.trim()) { this.render({ hits: [] }); return; } |
| + if (!query.trim()) { this.render({}); return; } |
| fetch("/search/suggest?q=" + encodeURIComponent(query), { credentials: "same-origin" }) |
| .then(function (response) { |
| if (response.redirected || !response.ok) { |
| @@ -390,56 +479,118 @@ |
| .catch(function () {}); |
| }; |
| + // render replaces the list with the reply's groups: the typed date |
| + // first, then Pages, In the text and Your notes, and Create last. |
| Palette.prototype.render = function (reply) { |
| var palette = this; |
| this.list.textContent = ""; |
| - this.links = []; |
| - (reply.hits || []).forEach(function (hit) { |
| - palette.add(hit.label, hit.href, hit.snippet || hit.via || ""); |
| - }); |
| - if (reply.create) { |
| - palette.add("Create “" + reply.create + "”", |
| - "/new?title=" + encodeURIComponent(reply.create), "A new team page"); |
| + this.options = []; |
| + this.create = reply.create ? "/new?title=" + encodeURIComponent(reply.create) : ""; |
| + if (reply.date) { |
| + this.group("A date", null, [{ icon: "daily", main: reply.date.label, sub: "Your note", href: reply.date.href }]); |
| } |
| + this.group("Pages", "", (reply.pages || []).map(function (hit) { |
| + return hit.via ? { icon: "page", main: hit.via, sub: "Old title of " + hit.label, href: hit.href } |
| + : { icon: "page", main: hit.label, sub: "Team page", href: hit.href }; |
| + })); |
| + this.group("In the text", "", (reply.text || []).map(function (hit) { |
| + return { icon: "page", main: hit.label, snippet: hit.snippet, href: hit.href }; |
| + })); |
| + this.group("Your notes", "Only you see these", (reply.notes || []).map(function (hit) { |
| + var daily = hit.kind === "daily"; |
| + return { icon: daily ? "daily" : "scratch", main: hit.label, snippet: hit.snippet, |
| + sub: daily ? "Your daily note" : "Your scratch page", href: hit.href }; |
| + })); |
| + var found = this.options.length; |
| + if (this.create) { |
| + this.group("Create", null, [{ icon: "create", main: "Create “" + reply.create + "”", |
| + sub: "A new team page with this title", href: this.create, dashed: true }]); |
| + } |
| + this.input.setAttribute("aria-expanded", this.options.length ? "true" : "false"); |
| this.chosen = 0; |
| - this.mark(); |
| + this.choose(0, false); |
| + this.announce(reply, found); |
| }; |
| - Palette.prototype.add = function (label, href, detail) { |
| - var row = document.createElement("li"); |
| - row.setAttribute("role", "option"); |
| - var link = document.createElement("a"); |
| - link.href = href; |
| - link.textContent = label; |
| - row.appendChild(link); |
| - if (detail) { |
| - var more = document.createElement("span"); |
| - more.setAttribute("mapa-meta", ""); |
| - more.textContent = detail; |
| - row.appendChild(more); |
| + // group adds a labelled group of options, with a visible heading and |
| + // its aside unless aside is null: the date and Create rows speak for |
| + // themselves. |
| + Palette.prototype.group = function (name, aside, rows) { |
| + if (!rows.length) return; |
| + var palette = this; |
| + var group = paletteElement("div", { role: "group", "aria-label": name, "mapa-palette-group": "" }); |
| + if (aside !== null) { |
| + var head = paletteElement("div", { "mapa-palette-head": "", "aria-hidden": "true" }); |
| + head.appendChild(paletteElement("span", {}, name)); |
| + if (aside) head.appendChild(paletteElement("span", {}, aside)); |
| + group.appendChild(head); |
| } |
| - this.list.appendChild(row); |
| - this.links.push(link); |
| + rows.forEach(function (row) { group.appendChild(palette.option(row)); }); |
| + this.list.appendChild(group); |
| }; |
| - Palette.prototype.mark = function () { |
| - var rows = this.list.children; |
| - for (var index = 0; index < rows.length; index++) { |
| - rows[index].setAttribute("aria-selected", index === this.chosen ? "true" : "false"); |
| + Palette.prototype.option = function (row) { |
| + var palette = this, index = this.options.length; |
| + var link = paletteElement("a", { |
| + href: row.href, role: "option", id: "mapa-palette-option-" + index, |
| + "aria-selected": "false", tabindex: "-1", "mapa-palette-option": "" |
| + }); |
| + var icon = paletteElement("span", row.dashed ? { "mapa-palette-ic": "dash" } : { "mapa-palette-ic": "" }); |
| + icon.appendChild(paletteIcon(row.icon)); |
| + var main = paletteElement("span", { "mapa-palette-main": "" }); |
| + main.appendChild(paletteElement("span", {}, row.main)); |
| + var sub = paletteElement("small"); |
| + if (row.snippet) markSnippet(sub, row.snippet); else sub.textContent = row.sub; |
| + main.appendChild(sub); |
| + link.appendChild(icon); |
| + link.appendChild(main); |
| + link.addEventListener("pointermove", function () { |
| + if (palette.chosen !== index) palette.choose(index, false); |
| + }); |
| + this.options.push(link); |
| + return link; |
| + }; |
| + |
| + // choose makes option index the active one: aria-selected on it, and |
| + // the input's aria-activedescendant naming it. |
| + Palette.prototype.choose = function (index, scroll) { |
| + var before = this.options[this.chosen]; |
| + if (before) before.setAttribute("aria-selected", "false"); |
| + this.chosen = index; |
| + var now = this.options[index]; |
| + if (!now) { this.input.removeAttribute("aria-activedescendant"); return; } |
| + now.setAttribute("aria-selected", "true"); |
| + this.input.setAttribute("aria-activedescendant", now.id); |
| + if (scroll) now.scrollIntoView({ block: "nearest" }); |
| + }; |
| + |
| + // announce tells a screen reader how many pages answer ("3 pages"). |
| + Palette.prototype.announce = function (reply, found) { |
| + var message = ""; |
| + if (this.input.value.trim()) { |
| + message = found === 1 ? "1 page" : (found || "No") + " pages"; |
| + if (reply.create) message += ", or create “" + reply.create + "”"; |
| } |
| + if (this.count.textContent !== message) this.count.textContent = message; |
| }; |
| Palette.prototype.keys = function (event) { |
| - if (event.key === "ArrowDown" || event.key === "ArrowUp") { |
| - if (this.links.length === 0) return; |
| - var step = event.key === "ArrowDown" ? 1 : -1; |
| - this.chosen = (this.chosen + step + this.links.length) % this.links.length; |
| - this.mark(); |
| + var count = this.options.length; |
| + if (event.key === "Escape") { |
| + // At once: a search field's own Esc would only clear the text. |
| event.preventDefault(); |
| + this.dialog.close(); |
| + } else if (event.key === "ArrowDown" || event.key === "ArrowUp") { |
| + event.preventDefault(); |
| + if (count === 0) return; |
| + var step = event.key === "ArrowDown" ? 1 : -1; |
| + this.choose((this.chosen + step + count) % count, true); |
| } else if (event.key === "Enter") { |
| event.preventDefault(); |
| - if (this.links[this.chosen]) { |
| - window.location.assign(this.links[this.chosen].href); |
| + if ((event.metaKey || event.ctrlKey) && this.create) { |
| + window.location.assign(this.create); |
| + } else if (this.options[this.chosen]) { |
| + window.location.assign(this.options[this.chosen].href); |
| } else if (this.input.value.trim()) { |
| window.location.assign("/search?q=" + encodeURIComponent(this.input.value)); |
| } |
diff --git a/internal/mapa/static/palette.css b/internal/mapa/static/palette.css| new file mode 100644 |
| index 0000000..a87cf07 |
| --- /dev/null |
| +++ b/internal/mapa/static/palette.css |
| @@ -0,0 +1,231 @@ |
| +/* palette.css: ⌘K (level-up §4.6), after the mock-up's box, and the |
| + search page's groups. Calma: only icons carry colour; the selected |
| + row takes the accent's soft wash, as the sidebar's current item does. |
| + The system face only (estilo decision 9). It loads after mapa.css, |
| + whose older palette rules it overrides. */ |
| + |
| +dialog[mapa-palette] { |
| + box-sizing: border-box; |
| + inline-size: min(640px, calc(100vw - 24px)); |
| + max-block-size: calc(100dvh - 24px); |
| + margin: min(14vh, 120px) auto auto; |
| + padding: 0; |
| + border: 1px solid var(--rst-line); |
| + border-radius: 16px; |
| + background: var(--rst-surface); |
| + color: var(--rst-text); |
| + font-family: var(--rst-font); |
| + box-shadow: var(--rst-shadow-pop), |
| + 0 40px 80px -30px light-dark(rgb(20 24 33 / 0.35), rgb(0 0 0 / 0.7)); |
| + overflow: hidden; |
| +} |
| +dialog[mapa-palette][open] { display: flex; flex-direction: column; } |
| +dialog[mapa-palette]::backdrop { |
| + background: light-dark(rgb(20 24 33 / 0.28), rgb(0 0 0 / 0.5)); |
| + -webkit-backdrop-filter: blur(2px); |
| + backdrop-filter: blur(2px); |
| +} |
| + |
| +[mapa-palette-box] { |
| + display: flex; |
| + align-items: center; |
| + gap: 12px; |
| + flex: none; |
| + padding: 0 16px; |
| + block-size: 56px; |
| + border-block-end: 1px solid var(--rst-line); |
| +} |
| +svg[mapa-palette-svg] { |
| + inline-size: 16px; |
| + block-size: 16px; |
| + flex: none; |
| + fill: none; |
| + stroke: currentColor; |
| + stroke-width: 1.75; |
| + stroke-linecap: round; |
| + stroke-linejoin: round; |
| +} |
| +[mapa-palette-box] > svg[mapa-palette-svg] { |
| + inline-size: 20px; |
| + block-size: 20px; |
| + color: var(--rst-text-muted); |
| +} |
| +dialog[mapa-palette] [mapa-palette-box] input { |
| + flex: 1; |
| + min-inline-size: 0; |
| + inline-size: auto; |
| + margin: 0; |
| + padding: 0; |
| + border: 0; |
| + outline: none; |
| + background: none; |
| + color: var(--rst-text); |
| + font: 500 18px var(--rst-font); |
| + -webkit-appearance: none; |
| + appearance: none; |
| +} |
| +[mapa-palette-box] input::-webkit-search-cancel-button { display: none; } |
| +[mapa-palette-box] input::placeholder { color: var(--rst-text-faint); } |
| +button[mapa-palette-esc] { |
| + display: inline-grid; |
| + place-items: center; |
| + min-inline-size: 32px; |
| + min-block-size: 24px; |
| + padding: 1px 6px; |
| + border: 1px solid var(--rst-line); |
| + border-block-end-width: 2px; |
| + border-radius: 5px; |
| + background: var(--rst-surface); |
| + color: var(--rst-text-muted); |
| + font: 500 11px/16px var(--rst-font); |
| + cursor: pointer; |
| +} |
| +button[mapa-palette-esc]:focus-visible, |
| +a[mapa-palette-option]:focus-visible { |
| + outline: 2px solid var(--rst-accent); |
| + outline-offset: -2px; |
| +} |
| + |
| +dialog[mapa-palette] [mapa-palette-results] { |
| + flex: 1 1 auto; |
| + min-block-size: 0; |
| + max-block-size: min(56vh, 440px); |
| + margin: 0; |
| + padding: 6px; |
| + overflow: auto; |
| + overscroll-behavior: contain; |
| + border: 0; |
| + border-radius: 0; |
| + box-shadow: none; |
| + background: none; |
| +} |
| +[mapa-palette-group] + [mapa-palette-group]:has(a[href^="/new?"]) { |
| + margin-block-start: 4px; |
| + padding-block-start: 4px; |
| + border-block-start: 1px solid var(--rst-line); |
| +} |
| +[mapa-palette-head] { |
| + display: flex; |
| + align-items: center; |
| + justify-content: space-between; |
| + gap: 8px; |
| + padding: 10px 10px 4px; |
| + color: var(--rst-text-muted); |
| + font-size: 11.5px; |
| + font-weight: 600; |
| +} |
| + |
| +a[mapa-palette-option] { |
| + box-sizing: border-box; |
| + display: grid; |
| + grid-template-columns: 28px minmax(0, 1fr); |
| + align-items: center; |
| + column-gap: 10px; |
| + min-block-size: 44px; |
| + padding: 3px 10px 3px 4px; |
| + border-radius: 8px; |
| + color: var(--rst-text); |
| + font-weight: 400; |
| + text-decoration: none; |
| + cursor: pointer; |
| +} |
| +a[mapa-palette-option][aria-selected="true"] { |
| + background: var(--rst-accent-soft); |
| +} |
| +[mapa-palette-ic] { |
| + display: inline-grid; |
| + place-items: center; |
| + inline-size: 28px; |
| + block-size: 28px; |
| + box-sizing: border-box; |
| + border: 1px solid var(--rst-line); |
| + border-radius: 7px; |
| + background: var(--rst-surface); |
| + color: var(--rst-text-muted); |
| +} |
| +[mapa-palette-ic="dash"] { |
| + border-style: dashed; |
| + border-color: var(--rst-line-strong); |
| +} |
| +a[mapa-palette-option][aria-selected="true"] [mapa-palette-ic] { |
| + color: var(--rst-accent); |
| + border-color: color-mix(in oklab, var(--rst-accent) 40%, var(--rst-line)); |
| +} |
| +[mapa-palette-main] { display: grid; min-inline-size: 0; } |
| +[mapa-palette-main] > span, |
| +[mapa-palette-main] > small { |
| + overflow: hidden; |
| + text-overflow: ellipsis; |
| + white-space: nowrap; |
| +} |
| +[mapa-palette-main] > span { font-size: 14.5px; line-height: 20px; } |
| +[mapa-palette-main] > small { |
| + color: var(--rst-text-muted); |
| + font-size: 12px; |
| + line-height: 16px; |
| +} |
| +[mapa-palette-main] mark, |
| +[mapa-snippet] mark { |
| + background: none; |
| + color: var(--rst-text); |
| + font-weight: 650; |
| +} |
| + |
| +[mapa-palette-foot] { |
| + display: flex; |
| + flex-wrap: wrap; |
| + gap: 6px 16px; |
| + align-items: center; |
| + flex: none; |
| + padding: 9px 16px; |
| + border-block-start: 1px solid var(--rst-line); |
| + background: color-mix(in oklab, var(--rst-surface-2) 40%, var(--rst-surface)); |
| + color: var(--rst-text-muted); |
| + font-size: 12px; |
| +} |
| +[mapa-palette-foot] span { display: inline-flex; align-items: center; gap: 5px; } |
| +[mapa-palette-foot] span:last-child { margin-inline-start: auto; } |
| + |
| +@media (max-width: 799.98px) { |
| + dialog[mapa-palette] { margin-block-start: 12px; } |
| + [mapa-palette-foot] { display: none; } |
| + dialog[mapa-palette] [mapa-palette-results] { |
| + max-block-size: calc(100dvh - 24px - 58px); |
| + } |
| +} |
| +@media (pointer: coarse) { |
| + a[mapa-palette-option] { min-block-size: 48px; } |
| + button[mapa-palette-esc] { min-block-size: 32px; } |
| +} |
| + |
| +/* ---- The search page, without script: the same groups. */ |
| +[mapa-search-hint] { margin-block: var(--rst-sp-2) 0; } |
| +[mapa-search-head] { |
| + display: flex; |
| + align-items: baseline; |
| + justify-content: space-between; |
| + gap: var(--rst-sp-2); |
| + margin: var(--rst-sp-4) 0 var(--rst-sp-2); |
| + color: var(--rst-text-muted); |
| + font-size: var(--rst-fs-sm); |
| + font-weight: 600; |
| +} |
| +[mapa-search-head] [mapa-meta] { font-weight: 400; } |
| +[mapa-results] > li[mapa-result] { |
| + display: grid; |
| + grid-template-columns: 28px minmax(0, 1fr); |
| + align-items: start; |
| + column-gap: var(--rst-sp-3); |
| +} |
| +[mapa-result-ic] { |
| + display: inline-grid; |
| + place-items: center; |
| + inline-size: 28px; |
| + block-size: 28px; |
| + box-sizing: border-box; |
| + border: 1px solid var(--rst-line); |
| + border-radius: 7px; |
| + color: var(--rst-accent); |
| +} |
| +[mapa-result-ic] svg { inline-size: 16px; block-size: 16px; } |
| +[mapa-create] [mapa-meta] { margin-inline-start: var(--rst-sp-2); } |
diff --git a/internal/mapa/templates/search.html b/internal/mapa/templates/search.html| index ba28a6a..02236ef 100644 |
| --- a/internal/mapa/templates/search.html |
| +++ b/internal/mapa/templates/search.html |
| @@ -6,15 +6,35 @@ |
| <input rst-input type="search" id="q" name="q" value="{{$r.Query}}" autocomplete="off" autofocus mapa-search-box> |
| <button rst-btn="primary" type="submit">{{icon "search"}} Search</button> |
| </div> |
| +<p mapa-meta mapa-search-hint>Type a date, like “friday”, to open that day.</p> |
| </form> |
| {{if $r.Query}} |
| -{{with $r.Create}}<p mapa-create><a rst-btn href="/new?title={{.}}">{{icon "plus"}} Create “{{.}}”</a></p>{{end}} |
| -{{with $r.Hits}} |
| +{{with $r.Date}}<section mapa-search-group aria-label="A date"> |
| <ul mapa-list mapa-results> |
| -{{range .}}<li mapa-result><div><a href="{{.Href}}">{{.Label}}</a> <span mapa-meta>{{if eq .Kind "page"}}Team page{{else if eq .Kind "daily"}}Your daily note{{else}}Your scratch page{{end}}{{with .Via}}, also called {{.}}{{end}}</span></div>{{with .Snippet}}<p mapa-meta>{{.}}</p>{{end}}</li> |
| +<li mapa-result mapa-date-row><span mapa-result-ic>{{icon "calendar"}}</span><div><a href="{{.Href}}">{{.Label}}</a> <span mapa-meta>Your note</span></div></li> |
| +</ul> |
| +</section>{{end}} |
| +{{with $r.Pages}}<section mapa-search-group aria-labelledby="group-pages"> |
| +<h2 mapa-search-head id="group-pages">Pages</h2> |
| +<ul mapa-list mapa-results> |
| +{{range .}}<li mapa-result><span mapa-result-ic>{{icon "file-text"}}</span><div>{{if .Via}}<a href="{{.Href}}">{{.Via}}</a> <span mapa-meta>Old title of {{.Label}}</span>{{else}}<a href="{{.Href}}">{{.Label}}</a> <span mapa-meta>Team page</span>{{end}}</div></li> |
| {{end}}</ul> |
| -{{else}} |
| -<p mapa-meta>Nothing matches “{{$r.Query}}”.</p> |
| -{{end}} |
| +</section>{{end}} |
| +{{with $r.Text}}<section mapa-search-group aria-labelledby="group-text"> |
| +<h2 mapa-search-head id="group-text">In the text</h2> |
| +<ul mapa-list mapa-results> |
| +{{range .}}<li mapa-result><span mapa-result-ic>{{icon "file-text"}}</span><div><a href="{{.Href}}">{{.Label}}</a>{{template "search-snippet" .Snippet}}</div></li> |
| +{{end}}</ul> |
| +</section>{{end}} |
| +{{with $r.Notes}}<section mapa-search-group aria-labelledby="group-notes"> |
| +<h2 mapa-search-head id="group-notes">Your notes <span mapa-meta>Only you see these</span></h2> |
| +<ul mapa-list mapa-results> |
| +{{range .}}<li mapa-result><span mapa-result-ic>{{if eq .Kind "daily"}}{{icon "calendar"}}{{else}}{{icon "sticky-note"}}{{end}}</span><div><a href="{{.Href}}">{{.Label}}</a>{{if .Snippet}}{{template "search-snippet" .Snippet}}{{else}} <span mapa-meta>{{if eq .Kind "daily"}}Your daily note{{else}}Your scratch page{{end}}</span>{{end}}</div></li> |
| +{{end}}</ul> |
| +</section>{{end}} |
| +{{if not $r.Count}}<p mapa-meta>Nothing matches “{{$r.Query}}”.</p>{{end}} |
| +{{with $r.Create}}<p mapa-create><a rst-btn href="/new?title={{.}}">{{icon "file-plus"}} Create “{{.}}”</a> <span mapa-meta>A new team page with this title</span></p>{{end}} |
| {{end}} |
| {{end}} |
| + |
| +{{define "search-snippet"}}{{with .}}<p mapa-meta mapa-snippet>{{range .Parts}}{{if .Marked}}<mark>{{.Text}}</mark>{{else}}{{.Text}}{{end}}{{end}}</p>{{end}}{{end}} |
diff --git a/internal/mapa/templates/shell.html b/internal/mapa/templates/shell.html| index d64ceac..95abfb9 100644 |
| --- a/internal/mapa/templates/shell.html |
| +++ b/internal/mapa/templates/shell.html |
| @@ -16,6 +16,7 @@ |
| <link rel="stylesheet" href="{{asset "static/savestatus.css"}}"> |
| <link rel="stylesheet" href="{{asset "static/mapa.css"}}"> |
| <link rel="stylesheet" href="{{asset "static/frame.css"}}"> |
| +<link rel="stylesheet" href="{{asset "static/palette.css"}}"> |
| <script defer src="{{asset "static/rastrillo.js"}}"></script> |
| <script defer src="{{asset "static/busy.js"}}"></script> |
| <script defer src="{{asset "static/chrome.js"}}"></script> |
diff --git a/internal/mapatest/gate1_test.go b/internal/mapatest/gate1_test.go| index 0ffaea6..d0ba9b4 100644 |
| --- a/internal/mapatest/gate1_test.go |
| +++ b/internal/mapatest/gate1_test.go |
| @@ -32,6 +32,9 @@ func gate1World(t *testing.T, private bool) (*rig, string) { |
| rig.post(t, Ana, "/scratch", url.Values{"body": {body}}) |
| } |
| } |
| + // Bo's own note, in both worlds: ⌘K's "Your notes" holds it for him, |
| + // and never for Ana. Written first, so its nonce is the same in both. |
| + rig.post(t, Bo, "/scratch", url.Values{"body": {"zebracorn musings"}}) |
| acme := rig.createPage(t, Ana, "Acme", "Acme is a customer. ^blk") |
| aside("first private aside") |
| rig.createPage(t, Ana, "Notes", "We met the acme folks about "+ |
| @@ -97,6 +100,10 @@ func boSees(t *testing.T, rig *rig, acme string) map[string]string { |
| "/search?q=zebracorn+feed", "/search?q=acme+ltd", |
| "/search/suggest?q=zeb", "/search/suggest?q=acme", |
| "/search/suggest?q=Zebracorn+Plans", "/search/suggest?q=acme+ltd", |
| + "/search/suggest?q=zebracorn", "/search/suggest?q=today", |
| + "/search/suggest?q=thursday", "/search/suggest?q=12+nov", |
| + "/search/suggest?q=2026-11-12", "/search/suggest?q=2026", |
| + "/search?q=2026-11-12", "/search?q=today", |
| "/links/suggest?q=zeb", "/links/suggest?q=ac", |
| acme, "/pages", "/d/2026-11-12", |
| } { |
diff --git a/internal/mapatest/palette_browser_test.go b/internal/mapatest/palette_browser_test.go| new file mode 100644 |
| index 0000000..d59d15d |
| --- /dev/null |
| +++ b/internal/mapatest/palette_browser_test.go |
| @@ -0,0 +1,82 @@ |
| +//go:build browser |
| + |
| +package mapatest |
| + |
| +import ( |
| + "strings" |
| + "testing" |
| + |
| + "amadan.net/rastrillo/rastrillo/harness" |
| + "github.com/chromedp/chromedp" |
| + "github.com/chromedp/chromedp/kb" |
| +) |
| + |
| +// sideSearch is the sidebar's Search, on screen from 800px. |
| +const sideSearch = `[mapa-side] a[href="/search"]` |
| + |
| +// ⌘K by keyboard alone (level-up §4.6, §6.12, L10): opened from Search, |
| +// a typed date's row first and active, the count announced, the arrows |
| +// moving aria-activedescendant, Esc closing with focus back on Search, |
| +// and ⌘↵ (Ctrl+Enter) creating. |
| +func TestThePaletteByKeyboard(t *testing.T) { |
| + rig, _ := browserRig(t, 0) |
| + drive(t, rig, scripts(true), chromedp.EmulateViewport(1280, 800), |
| + chromedp.Navigate(rig.Origin+"/"), |
| + chromedp.WaitVisible(sideSearch), press(sideSearch), |
| + chromedp.WaitVisible("dialog[mapa-palette] input"), |
| + chromedp.SendKeys("dialog[mapa-palette] input", "today"), |
| + chromedp.WaitVisible(`[mapa-palette-results] a[href^="/d/"]`), |
| + ) |
| + parts := strings.Split(read(t, rig, |
| + chromedp.Evaluate[string](paletteState)), "|") |
| + if parts[0] != "mapa-palette-option-0" || |
| + !strings.HasPrefix(parts[1], "/d/") || |
| + !strings.HasPrefix(parts[2], "1 page, or create") || |
| + parts[3] != "true" { |
| + t.Fatalf("the date row is not first and active: %q", parts) |
| + } |
| + drive(t, rig, chromedp.KeyEvent(kb.ArrowDown)) |
| + parts = strings.Split(read(t, rig, |
| + chromedp.Evaluate[string](paletteState)), "|") |
| + if parts[0] != "mapa-palette-option-1" || |
| + parts[1] != "/new?title=today" { |
| + t.Fatalf("ArrowDown did not move to Create: %q", parts) |
| + } |
| + drive(t, rig, chromedp.KeyEvent(kb.Escape), |
| + chromedp.WaitNotVisible("dialog[mapa-palette]")) |
| + if back := read(t, rig, chromedp.Evaluate[bool]( |
| + `document.activeElement.matches('`+sideSearch+`')`)); !back { |
| + t.Fatal("Esc did not return focus to Search") |
| + } |
| + createByKeyboard(t, rig) |
| +} |
| + |
| +// createByKeyboard opens ⌘K with Ctrl+K and creates with Ctrl+Enter. |
| +func createByKeyboard(t *testing.T, rig *harness.Rig) { |
| + t.Helper() |
| + drive(t, rig, |
| + chromedp.KeyEvent("k", chromedp.KeyModifiers(chromedp.ModifierCtrl)), |
| + chromedp.WaitVisible("dialog[mapa-palette] input"), |
| + chromedp.SendKeys("dialog[mapa-palette] input", "Kelp farm"), |
| + chromedp.WaitVisible(`[mapa-palette-results] a[href^="/new?"]`), |
| + chromedp.KeyEvent("\r", chromedp.KeyModifiers( |
| + chromedp.ModifierCtrl)), |
| + chromedp.WaitVisible(`input[name="title"]`), |
| + ) |
| + title := read(t, rig, chromedp.Value(`input[name="title"]`)) |
| + if title != "Kelp farm" { |
| + t.Fatalf("⌘↵ created %q", title) |
| + } |
| +} |
| + |
| +// paletteState is the active option's id and href, the live count, and |
| +// whether the hints' foot is on screen. |
| +const paletteState = `(function () { |
| + var input = document.querySelector("dialog[mapa-palette] input"); |
| + var id = input.getAttribute("aria-activedescendant") || ""; |
| + var option = document.getElementById(id); |
| + var live = document.querySelector("dialog[mapa-palette] [role=status]"); |
| + var foot = document.querySelector("[mapa-palette-foot]"); |
| + return [id, option ? option.getAttribute("href") : "", live.textContent, |
| + foot.getClientRects().length > 0].join("|"); |
| +})()` |
diff --git a/internal/mapatest/palette_test.go b/internal/mapatest/palette_test.go| new file mode 100644 |
| index 0000000..c83467b |
| --- /dev/null |
| +++ b/internal/mapatest/palette_test.go |
| @@ -0,0 +1,160 @@ |
| +package mapatest |
| + |
| +import ( |
| + "crypto/sha256" |
| + "encoding/json" |
| + "fmt" |
| + "net/http" |
| + "net/url" |
| + "strings" |
| + "testing" |
| +) |
| + |
| +// ⌘K's groups and date row (level-up §4.6), from the outside. |
| + |
| +// paletteAnswer is /search/suggest's JSON, as the palette reads it. |
| +type paletteAnswer struct { |
| + Query string `json:"query"` |
| + Date *struct { |
| + Date, Label, Href string |
| + } `json:"date"` |
| + Pages, Text, Notes []struct { |
| + Label, Href, Kind, Via string |
| + Snippet *struct { |
| + Text string `json:"text"` |
| + Marks [][2]int `json:"marks"` |
| + } `json:"snippet"` |
| + } |
| + Create string `json:"create"` |
| +} |
| + |
| +func suggestAs(t *testing.T, rig *rig, who, query string) paletteAnswer { |
| + t.Helper() |
| + var answer paletteAnswer |
| + body := rig.page(t, who, "/search/suggest?q="+url.QueryEscape(query)) |
| + if err := json.Unmarshal([]byte(body), &answer); err != nil { |
| + t.Fatalf("%s: %v", body, err) |
| + } |
| + return answer |
| +} |
| + |
| +// Gate 1, extended (L6): "Your notes" only ever holds the viewer's own |
| +// pages. Bo's holds his scratch page and none of Ana's; Ana's holds hers |
| +// and not Bo's. Byte-identity across the worlds is boSees's. |
| +func TestGate1YourNotesAreOnlyYours(t *testing.T) { |
| + busy, _ := gate1World(t, true) |
| + bo := suggestAs(t, busy, Bo, "zebracorn") |
| + if len(bo.Notes) != 1 || bo.Notes[0].Label != "zebracorn musings" { |
| + t.Fatalf("Bo's notes: %+v", bo.Notes) |
| + } |
| + ana := suggestAs(t, busy, Ana, "zebracorn") |
| + var labels []string |
| + for _, hit := range ana.Notes { |
| + labels = append(labels, hit.Label) |
| + } |
| + got := strings.Join(labels, " | ") |
| + if strings.Contains(got, "musings") || |
| + !strings.Contains(got, "Thursday 12 November 2026") || |
| + !strings.Contains(got, "Zebracorn.") { |
| + t.Fatalf("Ana's notes: %q", got) |
| + } |
| + for _, hit := range append(bo.Pages, bo.Text...) { |
| + if hit.Kind != "page" { |
| + t.Fatalf("a private page among the team's: %+v", hit) |
| + } |
| + } |
| + if day := suggestAs(t, busy, Bo, "2026-11-12"); len(day.Notes) != 0 || |
| + day.Date == nil || day.Date.Href != "/d/2026-11-12" { |
| + t.Fatalf("Bo's 12 November: %+v", day) |
| + } |
| +} |
| + |
| +// The groups and the date row, as the palette receives them: "thursday" |
| +// is today, in the viewer's zone, and the text hit's mark is the match. |
| +func TestThePaletteAnswersInGroups(t *testing.T) { |
| + busy, _ := gate1World(t, true) |
| + today := suggestAs(t, busy, Ana, "thursday") |
| + if today.Date == nil || today.Date.Label != "Thursday 12 November" || |
| + today.Date.Href != "/d/2026-11-12" { |
| + t.Fatalf("thursday: %+v", today.Date) |
| + } |
| + answer := suggestAs(t, busy, Bo, "zebracorn f") |
| + if len(answer.Text) == 0 || answer.Text[0].Snippet == nil { |
| + t.Fatalf("in the text: %+v", answer.Text) |
| + } |
| + snip := answer.Text[0].Snippet |
| + runes := []rune(snip.Text) |
| + for _, mark := range snip.Marks { |
| + word := strings.ToLower(string(runes[mark[0]:mark[1]])) |
| + if word != "zebracorn" && word != "f" { |
| + t.Fatalf("marked %q in %q", word, snip.Text) |
| + } |
| + } |
| + page := busy.page(t, Bo, "/search?q=zebracorn") |
| + for _, want := range []string{">In the text</h2>", "<mark>zebracorn</mark>", |
| + "Your notes", "Only you see these", "zebracorn musings"} { |
| + if !strings.Contains(page, want) { |
| + t.Fatalf("the search page has no %q", want) |
| + } |
| + } |
| +} |
| + |
| +// L7: ⌘K's GETs, the date row's included, write nothing: every table's |
| +// rows hash the same before and after. |
| +func TestL7ThePaletteWritesNothing(t *testing.T) { |
| + busy, _ := gate1World(t, true) |
| + before := tableRowsHash(t, busy) |
| + for _, query := range []string{"today", "tomorrow", "next friday", |
| + "12 nov", "2026-11-20", "zebracorn", "acme", "z"} { |
| + for _, who := range []string{Ana, Bo} { |
| + for _, path := range []string{"/search/suggest", "/search"} { |
| + target := path + "?q=" + url.QueryEscape(query) |
| + code := busy.get(t, who, target).Code |
| + if code != http.StatusOK { |
| + t.Fatalf("GET %s: %d", target, code) |
| + } |
| + } |
| + } |
| + } |
| + if after := tableRowsHash(t, busy); after != before { |
| + t.Fatal("a search GET changed the database's rows") |
| + } |
| + busy.post(t, Bo, "/scratch", url.Values{"body": {"a real write"}}) |
| + if tableRowsHash(t, busy) == before { |
| + t.Fatal("the hash is vacuous: a write did not change it") |
| + } |
| +} |
| + |
| +// tableRowsHash hashes every row of every table, not the file's bytes: |
| +// the WAL and checkpoints move those without a write. |
| +func tableRowsHash(t *testing.T, rig *rig) string { |
| + t.Helper() |
| + var tables []string |
| + err := rig.db.G.Raw("SELECT name FROM sqlite_master WHERE type = " + |
| + "'table' ORDER BY name").Scan(&tables).Error |
| + if err != nil || len(tables) == 0 { |
| + t.Fatalf("tables %v: %v", tables, err) |
| + } |
| + digest := sha256.New() |
| + for _, table := range tables { |
| + rows, err := rig.db.G.Raw(`SELECT * FROM "` + table + `"`).Rows() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + columns, _ := rows.Columns() |
| + values := make([]any, len(columns)) |
| + pointers := make([]any, len(columns)) |
| + for at := range values { |
| + pointers[at] = &values[at] |
| + } |
| + fmt.Fprintf(digest, "%s\n", table) |
| + for rows.Next() { |
| + if err := rows.Scan(pointers...); err != nil { |
| + t.Fatal(err) |
| + } |
| + fmt.Fprintf(digest, "%v\n", values) |
| + } |
| + rows.Close() |
| + } |
| + return fmt.Sprintf("%x", digest.Sum(nil)) |
| +} |
diff --git a/internal/mapatest/speed_test.go b/internal/mapatest/speed_test.go| index f60b6db..2c2aae8 100644 |
| --- a/internal/mapatest/speed_test.go |
| +++ b/internal/mapatest/speed_test.go |
| @@ -189,7 +189,7 @@ func TestAnotherProcesssWriteArrivesWithoutAReaderPaying(t *testing.T) { |
| writer, reader := openApp(t, path), openApp(t, path) |
| ctx := context.Background() |
| if hits, _ := reader.Index.Search(ctx, mapa.Scope{}, "quillon", |
| - 8); len(hits.Hits) != 0 { |
| + 8); len(hits.All()) != 0 { |
| t.Fatal("found before it was written") |
| } |
| if _, err := writer.Store.CreateTeamPage(ctx, Ana, "Quillon", |
| @@ -205,7 +205,7 @@ func TestAnotherProcesssWriteArrivesWithoutAReaderPaying(t *testing.T) { |
| } |
| before := reader.Index.CatchUps() |
| hits, err := reader.Index.Search(ctx, mapa.Scope{}, "quillon", 8) |
| - if err != nil || len(hits.Hits) != 1 { |
| + if err != nil || len(hits.All()) != 1 { |
| t.Fatalf("the write is not found: %+v, %v", hits, err) |
| } |
| if reader.Index.CatchUps() != before { |