diff --git a/golink.go b/golink.go index 08bdf99..041c55c 100644 --- a/golink.go +++ b/golink.go @@ -1139,8 +1139,11 @@ type SearchResult struct { DetailTarget string `json:"detailTarget"` } +// searchLimitJSON is the cap on results returned to the JSON/JS autocomplete. +const searchLimitJSON = 8 + // searchLimitHTML is the cap on results returned to the server-rendered -// /.search HTML page. +// /.search HTML page (the no-JS fallback and "More results" destination). const searchLimitHTML = 100 // runSearch performs a search query end-to-end: parse the input, fuzzy @@ -1215,8 +1218,15 @@ func (s *Server) runSearch(cu string, raw string, limit int) (parsed searchInput return in, results, limitHit } -// searchPageData is the data passed to searchTmpl for the server-rendered -// page, shared by /.search and /.all. +// acceptsJSON reports whether the request's Accept header prefers JSON. +// We use a simple substring match against "application/json"; the full +// RFC 9110 q-value algorithm is overkill here. +func acceptsJSON(r *http.Request) bool { + return strings.Contains(r.Header.Get("Accept"), "application/json") +} + +// searchPageData is the data passed to searchTmpl for the no-JS +// server-rendered page, shared by /.search and /.all. type searchPageData struct { Query string // the raw, untrimmed user input Parsed searchInput // parsed form, for showing "search mode" in the UI @@ -1233,8 +1243,9 @@ func (d searchPageData) TableView() bool { return d.All || d.Parsed.FilterOnly() } -// serveSearch handles GET /.search, returning a server-rendered HTML results -// page for the parsed query. +// serveSearch handles GET /.search. Depending on the Accept header it either +// returns a JSON autocomplete response (for the JS combobox) or a fully +// server-rendered HTML page (the no-JS fallback and "More results" target). func (s *Server) serveSearch(w http.ResponseWriter, r *http.Request) { raw := r.URL.Query().Get("q") // Defend against absurdly long inputs; the fuzzy matcher is linear @@ -1244,13 +1255,42 @@ func (s *Server) serveSearch(w http.ResponseWriter, r *http.Request) { } cu, err := s.currentUser(r) if err != nil && !s.allowUnknownUsers { - http.Error(w, err.Error(), http.StatusInternalServerError) - return + // For the HTML page, surface the error. For the JSON endpoint, + // autocomplete is a best-effort UI aid; failing to resolve the + // user just means template expansion that references .User + // will fall back to the raw Long. + if !acceptsJSON(r) { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } } limit := searchLimitHTML + if acceptsJSON(r) { + limit = searchLimitJSON + } parsed, results, limitHit := s.runSearch(cu.login, raw, limit) + if acceptsJSON(r) { + w.Header().Set("Content-Type", "application/json") + w.Header().Set("Cache-Control", "no-store") + _ = json.NewEncoder(w).Encode(struct { + Query string `json:"query"` + ShortQuery string `json:"shortQuery"` + IncludeLong bool `json:"includeLong"` + Results []SearchResult `json:"results"` + LimitHit bool `json:"limitHit"` + }{ + Query: raw, + ShortQuery: parsed.ShortQuery, + IncludeLong: parsed.IncludeLong, + Results: results, + LimitHit: limitHit, + }) + return + } + + // HTML page (no JS). if err := s.searchTmpl.Execute(w, searchPageData{ Query: raw, Parsed: parsed, diff --git a/golink_test.go b/golink_test.go index db3ac2d..698250f 100644 --- a/golink_test.go +++ b/golink_test.go @@ -1108,6 +1108,268 @@ func TestServeSearchHTMLLimit100(t *testing.T) { } } +func TestServeSearchJSON(t *testing.T) { + s := newTestServer(t) + links := []*Link{ + {Short: "who", Long: "http://who/"}, + {Short: "wholesale", Long: "http://wholesale/"}, + {Short: "template", Long: "http://example.com/{{.Path}}"}, + {Short: "no-path", Long: "http://example.com/path"}, + {Short: "unrelated", Long: "https://docs.google.com/internal"}, + } + for _, l := range links { + if err := s.db.Save(l); err != nil { + t.Fatal(err) + } + } + s.stats.mu.Lock() + s.stats.clicks = ClickStats{"who": 7} + s.stats.mu.Unlock() + + decode := func(t *testing.T, body string) (shortQuery string, includeLong bool, results []SearchResult) { + t.Helper() + var payload struct { + Query string `json:"query"` + ShortQuery string `json:"shortQuery"` + IncludeLong bool `json:"includeLong"` + Results []SearchResult `json:"results"` + } + if err := json.Unmarshal([]byte(body), &payload); err != nil { + t.Fatalf("decode JSON: %v\nbody=%s", err, body) + } + return payload.ShortQuery, payload.IncludeLong, payload.Results + } + + do := func(t *testing.T, rawQuery string) (int, string, http.Header) { + t.Helper() + r := httptest.NewRequest("GET", "/.search?q="+url.QueryEscape(rawQuery), nil) + r.Header.Set("Accept", "application/json") + w := httptest.NewRecorder() + s.Handler().ServeHTTP(w, r) + return w.Code, w.Body.String(), w.Header() + } + + t.Run("simple top-match", func(t *testing.T) { + code, body, hdr := do(t, "who") + if code != http.StatusOK { + t.Fatalf("status = %d; body=%s", code, body) + } + if ct := hdr.Get("Content-Type"); !strings.Contains(ct, "application/json") { + t.Errorf("Content-Type = %q, want application/json", ct) + } + sq, il, rs := decode(t, body) + if sq != "who" || il { + t.Errorf("parsed query = (%q, includeLong=%v), want (who, false)", sq, il) + } + if len(rs) == 0 || rs[0].Short != "who" { + t.Errorf("top result = %v, want who first", rs) + } + if rs[0].Rendered != "http://who/" { + t.Errorf("rendered = %q, want http://who/", rs[0].Rendered) + } + if rs[0].Target != "/who" { + t.Errorf("target = %q, want /who", rs[0].Target) + } + if rs[0].NumClicks != 7 { + t.Errorf("numClicks = %d, want 7", rs[0].NumClicks) + } + }) + + t.Run("path and query are forwarded into expandLink and Target", func(t *testing.T) { + code, body, _ := do(t, "template/foo?x=1&y=2") + if code != http.StatusOK { + t.Fatalf("status=%d body=%s", code, body) + } + _, _, rs := decode(t, body) + if len(rs) == 0 || rs[0].Short != "template" { + t.Fatalf("top result = %v, want template", rs) + } + // Rendered should have Path substituted AND the query merged. + // Compare via URL parsing because query key order is not fixed. + u, err := url.Parse(rs[0].Rendered) + if err != nil { + t.Fatalf("parse rendered %q: %v", rs[0].Rendered, err) + } + if u.Path != "/foo" { + t.Errorf("rendered path = %q, want /foo (from Path substitution)", u.Path) + } + gotQ := u.Query() + if gotQ.Get("x") != "1" || gotQ.Get("y") != "2" { + t.Errorf("rendered query = %v, want x=1 & y=2", gotQ) + } + // Target preserves user's path and query so click routes through golink. + tu, err := url.Parse(rs[0].Target) + if err != nil { + t.Fatalf("parse target %q: %v", rs[0].Target, err) + } + if tu.Path != "/template/foo" { + t.Errorf("target path = %q, want /template/foo", tu.Path) + } + if tu.Query().Get("x") != "1" || tu.Query().Get("y") != "2" { + t.Errorf("target query = %v, want x=1 & y=2", tu.Query()) + } + }) + + t.Run("default path-append behaviour for non-template long (no trailing slash)", func(t *testing.T) { + // Long = http://example.com/path, user query = "no-path/extra" + // Expect rendered = http://example.com/path/extra. + code, body, _ := do(t, "no-path/extra") + if code != http.StatusOK { + t.Fatalf("status=%d body=%s", code, body) + } + _, _, rs := decode(t, body) + if len(rs) == 0 || rs[0].Short != "no-path" { + t.Fatalf("top result = %v", rs) + } + want := "http://example.com/path/extra" + if rs[0].Rendered != want { + t.Errorf("rendered = %q, want %q", rs[0].Rendered, want) + } + }) + + t.Run("includeLong prefix", func(t *testing.T) { + code, body, _ := do(t, "?google") + if code != http.StatusOK { + t.Fatalf("status=%d body=%s", code, body) + } + sq, il, rs := decode(t, body) + if !il { + t.Errorf("IncludeLong = false, want true") + } + if sq != "google" { + t.Errorf("ShortQuery = %q, want google", sq) + } + // "unrelated" has "google" in its Long; should appear. + found := false + for _, r := range rs { + if r.Short == "unrelated" { + found = true + break + } + } + if !found { + t.Errorf("expected unrelated in results for ?google: %v", rs) + } + }) + + t.Run("empty query returns empty results", func(t *testing.T) { + code, body, _ := do(t, "") + if code != http.StatusOK { + t.Fatalf("status=%d body=%s", code, body) + } + _, _, rs := decode(t, body) + if len(rs) != 0 { + t.Errorf("empty query returned %d results, want 0", len(rs)) + } + }) + + t.Run("match positions returned", func(t *testing.T) { + _, body, _ := do(t, "wh") + _, _, rs := decode(t, body) + if len(rs) == 0 { + t.Fatalf("no results") + } + if len(rs[0].ShortMatchedIndexes) != 2 { + t.Errorf("ShortMatchedIndexes = %v, want 2 positions", rs[0].ShortMatchedIndexes) + } + if len(rs[0].LongMatchedIndexes) != 0 { + t.Errorf("LongMatchedIndexes = %v, want empty (not includeLong)", rs[0].LongMatchedIndexes) + } + }) + + t.Run("includeLong returns long match positions", func(t *testing.T) { + // Short "unrelated" does not contain "example" (no fuzzy match + // on short). Long "https://docs.google.com/internal" also + // doesn't literally contain "example" so that's a poor test + // candidate. Use "unrelated" with query "google": short + // has no subsequence match for "google"; long does. + _, body, _ := do(t, "?google") + _, _, rs := decode(t, body) + // Find the "unrelated" entry. + var found *SearchResult + for i := range rs { + if rs[i].Short == "unrelated" { + found = &rs[i] + break + } + } + if found == nil { + t.Fatalf("unrelated not in results: %v", rs) + } + if len(found.LongMatchedIndexes) == 0 { + t.Errorf("LongMatchedIndexes for unrelated = %v; want non-empty", found.LongMatchedIndexes) + } + if len(found.ShortMatchedIndexes) != 0 { + t.Errorf("ShortMatchedIndexes for unrelated = %v; want empty (short didn't match)", found.ShortMatchedIndexes) + } + }) +} + +// TestServeSearchLimitHit verifies that the server reports limitHit +// when the result set is truncated, and doesn't when it isn't. +func TestServeSearchLimitHit(t *testing.T) { + s := newTestServer(t) + // Populate enough matching links to exceed the JSON limit (8) but + // not the HTML limit (100). + for i := 0; i < 20; i++ { + short := fmt.Sprintf("aaa-%02d", i) + if err := s.db.Save(&Link{Short: short, Long: "http://ex/"}); err != nil { + t.Fatal(err) + } + } + + // JSON should flag limitHit=true (20 > 8). + r := httptest.NewRequest("GET", "/.search?q=a", nil) + r.Header.Set("Accept", "application/json") + w := httptest.NewRecorder() + s.Handler().ServeHTTP(w, r) + var payload struct { + LimitHit bool `json:"limitHit"` + Results []SearchResult `json:"results"` + } + if err := json.Unmarshal(w.Body.Bytes(), &payload); err != nil { + t.Fatal(err) + } + if !payload.LimitHit { + t.Errorf("expected limitHit=true for 20 matches at JSON limit 8; got false (%d results)", len(payload.Results)) + } + + // HTML should NOT flag the limit (20 < 100). Look for the absence + // of our "Results truncated" string. + r = httptest.NewRequest("GET", "/.search?q=a", nil) + w = httptest.NewRecorder() + s.Handler().ServeHTTP(w, r) + body := w.Body.String() + if strings.Contains(body, "Results truncated") { + t.Errorf("HTML page for 20 matches should not mention truncation; body=%s", body) + } +} + +// TestSearchResultHasDetailTarget confirms each result carries the +// /.detail/{short} URL so the client can honor Alt+Enter. +func TestSearchResultHasDetailTarget(t *testing.T) { + s := newTestServer(t) + s.db.Save(&Link{Short: "weird name", Long: "http://ex/"}) + r := httptest.NewRequest("GET", "/.search?q="+url.QueryEscape("weird"), nil) + r.Header.Set("Accept", "application/json") + w := httptest.NewRecorder() + s.Handler().ServeHTTP(w, r) + var payload struct { + Results []SearchResult `json:"results"` + } + if err := json.Unmarshal(w.Body.Bytes(), &payload); err != nil { + t.Fatal(err) + } + if len(payload.Results) == 0 { + t.Fatal("no results") + } + got := payload.Results[0].DetailTarget + want := "/.detail/weird%20name" // short is path-escaped + if got != want { + t.Errorf("DetailTarget = %q, want %q", got, want) + } +} + func TestParseAdvertiseTags(t *testing.T) { tests := []struct { name string diff --git a/package.json b/package.json index 617d1c1..4fe3ffb 100644 --- a/package.json +++ b/package.json @@ -1,8 +1,8 @@ { "name": "golink", "scripts": { - "start:css": "tailwindcss --watch -o static/base.css", - "build:css": "tailwindcss -o static/base.css" + "start:css": "tailwindcss --watch -i static/base.src.css -o static/base.css", + "build:css": "tailwindcss -i static/base.src.css -o static/base.css" }, "devDependencies": { "@tailwindcss/forms": "^0.5.3", diff --git a/static/base.css b/static/base.css index 4543e6a..0095ee8 100644 --- a/static/base.css +++ b/static/base.css @@ -1171,6 +1171,239 @@ select { margin-bottom: 0; } +.gl-header-top { + display: flex; + align-items: center; + gap: 1rem; + flex-wrap: wrap; +} + +.gl-header-tagline { + margin-top: 0.25rem; +} + +.gl-search { + position: relative; + flex: 0 1 200px; + width: 200px; + min-width: 0; + max-width: 200px; + margin: 0; +} + +.gl-search:focus-within { + flex-basis: 560px; + width: min(560px, 100%); + max-width: 560px; +} + +.gl-search-input { + width: 100%; + padding: 0.4rem 0.6rem; + border: 1px solid rgb(218 214 213); + border-radius: 0.375rem; + background-color: #fff; + font-size: 0.95rem; + line-height: 1.4; + box-sizing: border-box; +} + +.gl-search-input::-moz-placeholder { + color: rgb(112 110 109); + opacity: 1; + text-align: left; +} + +.gl-search-input::placeholder { + color: rgb(112 110 109); + opacity: 1; + text-align: left; +} + +.gl-search-input[aria-expanded="true"]::-moz-placeholder { + color: transparent; +} + +.gl-search-input[aria-expanded="true"]::placeholder { + color: transparent; +} + +.gl-search-input:focus { + outline: 2px solid rgba(63, 93, 179, 0.4); + outline-offset: 0; + border-color: rgba(63, 93, 179, 1); +} + +.gl-search-listbox { + position: absolute; + top: calc(100% + 2px); + left: 0; + right: 0; + margin: 0; + padding: 0; + list-style: none; + background: #fff; + border: 1px solid rgb(218 214 213); + border-radius: 0.375rem; + box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08); + max-height: min(82vh, calc(100dvh - 1rem)); + overflow-y: auto; + scrollbar-gutter: stable; + z-index: 50; +} + +.gl-search-listbox[hidden] { + display: none; +} + +.gl-search-option { + padding: 0.5rem 0.75rem; + cursor: pointer; + border-bottom: 1px solid rgb(238 235 234); + display: flex; + flex-direction: column; + gap: 0.1rem; +} + +.gl-search-option:last-child { + border-bottom: 0; +} + +.gl-search-option.is-active, + .gl-search-option[aria-selected="true"] { + background-color: #e9eef9; +} + +.gl-search-short { + font-weight: 600; + color: #111827; +} + +.gl-search-rendered { + font-size: 0.85rem; + color: rgb(112 110 109); + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.gl-search mark { + background: transparent; + color: rgb(63 93 179); + font-weight: 700; + padding: 0; +} + +.gl-search-tip { + padding: 0.5rem 0.75rem; + border-bottom: 1px solid rgb(238 235 234); + background-color: rgb(247 245 244); +} + +.gl-search-tip:last-child { + border-bottom: 0; +} + +.gl-search-tip-title { + display: block; + font-weight: 500; + font-size: 0.8rem; + color: rgb(97 95 94); +} + +.gl-search-tip-text { + display: block; + font-size: 0.78rem; + color: rgb(125 123 122); + margin-top: 0.12rem; + line-height: 1.35; +} + +.gl-search-tip code { + font-size: 0.76rem; +} + +/* The "Full results" footer is a role=option like other suggestions, + so it inherits .gl-search-option padding/hover, but we give it a + subtle visual separator and a muted default background so it reads + as a secondary action. */ + +.gl-search-footer { + position: sticky; + bottom: 0; + z-index: 1; + border-top: 1px solid rgb(238 235 234); + background-color: rgb(247 245 244); + text-align: left; + font-size: 0.85rem; + color: rgb(63 93 179); +} + +.gl-search-footer .gl-search-more { + font-weight: 600; +} + +@media (max-width: 640px) { + .gl-search, + .gl-search:focus-within { + flex-basis: 100%; + width: 100%; + max-width: none; + } +} + +/* Input on the server-rendered /.search page. Similar look to the + header combobox but full-width and free of listbox chrome. */ + +.gl-search-page-form { + margin: 0 0 1rem 0; + max-width: 560px; +} + +.gl-search-page-input { + width: 100%; + padding: 0.4rem 0.6rem; + border: 1px solid rgb(218 214 213); + border-radius: 0.375rem; + background-color: #fff; + font-size: 0.95rem; + line-height: 1.4; + box-sizing: border-box; +} + +.gl-search-page-input:focus { + outline: 2px solid rgba(63, 93, 179, 0.4); + outline-offset: 0; + border-color: rgba(63, 93, 179, 1); +} + +/* Wrapped template text on /.search rows. Template strings can be very long + and include no natural break points, so allow both normal wrapping and + forced token breaks to keep them inside the row. */ + +.gl-search-template-line { + white-space: normal; + overflow-wrap: anywhere; +} + +.gl-search-template-code { + white-space: pre-wrap; + word-break: break-word; + overflow-wrap: anywhere; +} + +.sr-only { + position: absolute; + width: 1px; + height: 1px; + padding: 0; + margin: -1px; + overflow: hidden; + clip: rect(0, 0, 0, 0); + white-space: nowrap; + border-width: 0; +} + .invisible { visibility: hidden; } @@ -1203,6 +1436,11 @@ select { margin-right: 1rem; } +.-mx-2 { + margin-left: -0.5rem; + margin-right: -0.5rem; +} + .mb-6 { margin-bottom: 1.5rem; } @@ -1259,12 +1497,8 @@ select { width: 5rem; } -.max-w-screen-lg { - max-width: 1024px; -} - -.max-w-\[75vw\] { - max-width: 75vw; +.min-w-0 { + min-width: 0px; } .max-w-full { @@ -1275,6 +1509,14 @@ select { max-width: 64rem; } +.max-w-screen-lg { + max-width: 1024px; +} + +.max-w-\[75vw\] { + max-width: 75vw; +} + .flex-1 { flex: 1 1 0%; } @@ -1291,10 +1533,18 @@ select { flex-wrap: wrap; } +.items-start { + align-items: flex-start; +} + .items-center { align-items: center; } +.gap-2 { + gap: 0.5rem; +} + .overflow-auto { overflow: auto; } @@ -1350,14 +1600,14 @@ select { border-color: rgb(75 112 204 / var(--tw-border-opacity)); } -.border-red-500 { +.border-orange-50 { --tw-border-opacity: 1; - border-color: rgb(178 45 48 / var(--tw-border-opacity)); + border-color: rgb(254 227 192 / var(--tw-border-opacity)); } -.border-orange-50 { +.border-red-500 { --tw-border-opacity: 1; - border-color: rgb(254 227 192 / var(--tw-border-opacity)); + border-color: rgb(178 45 48 / var(--tw-border-opacity)); } .bg-gray-100 { @@ -1370,30 +1620,20 @@ select { background-color: rgb(75 112 204 / var(--tw-bg-opacity)); } -.bg-red-500 { +.bg-orange-0 { --tw-bg-opacity: 1; - background-color: rgb(178 45 48 / var(--tw-bg-opacity)); + background-color: rgb(255 250 238 / var(--tw-bg-opacity)); } -.bg-orange-0 { +.bg-red-500 { --tw-bg-opacity: 1; - background-color: rgb(255 250 238 / var(--tw-bg-opacity)); + background-color: rgb(178 45 48 / var(--tw-bg-opacity)); } .p-2 { padding: 0.5rem; } -.px-2 { - padding-left: 0.5rem; - padding-right: 0.5rem; -} - -.py-2 { - padding-top: 0.5rem; - padding-bottom: 0.5rem; -} - .px-4 { padding-left: 1rem; padding-right: 1rem; @@ -1404,23 +1644,29 @@ select { padding-bottom: 1rem; } +.px-2 { + padding-left: 0.5rem; + padding-right: 0.5rem; +} + +.py-2 { + padding-top: 0.5rem; + padding-bottom: 0.5rem; +} + .py-3 { padding-top: 0.75rem; padding-bottom: 0.75rem; } -.pt-6 { - padding-top: 1.5rem; +.pt-4 { + padding-top: 1rem; } .pb-2 { padding-bottom: 0.5rem; } -.pt-4 { - padding-top: 1rem; -} - .pb-1 { padding-bottom: 0.25rem; } @@ -1429,10 +1675,18 @@ select { padding-top: 0.5rem; } +.pt-6 { + padding-top: 1.5rem; +} + .pr-4 { padding-right: 1rem; } +.pt-1 { + padding-top: 0.25rem; +} + .text-left { text-align: left; } @@ -1449,31 +1703,31 @@ select { vertical-align: text-top; } +.text-2xl { + font-size: 1.5rem; + line-height: 2rem; +} + .text-xl { font-size: 1.25rem; line-height: 1.75rem; } -.text-xs { - font-size: 0.75rem; - line-height: 1rem; -} - .text-sm { font-size: 0.875rem; line-height: 1.25rem; } -.text-2xl { - font-size: 1.5rem; - line-height: 2rem; -} - .text-lg { font-size: 1.125rem; line-height: 1.75rem; } +.text-xs { + font-size: 0.75rem; + line-height: 1rem; +} + .font-bold { font-weight: 700; } @@ -1482,17 +1736,17 @@ select { text-transform: uppercase; } -.leading-normal { - line-height: 1.5; +.tabular-nums { + --tw-numeric-spacing: tabular-nums; + font-variant-numeric: var(--tw-ordinal) var(--tw-slashed-zero) var(--tw-numeric-figure) var(--tw-numeric-spacing) var(--tw-numeric-fraction); } .leading-6 { line-height: 1.5rem; } -.text-gray-500 { - --tw-text-opacity: 1; - color: rgb(112 110 109 / var(--tw-text-opacity)); +.leading-normal { + line-height: 1.5; } .text-gray-700 { @@ -1505,6 +1759,11 @@ select { color: rgb(255 255 255 / var(--tw-text-opacity)); } +.text-gray-500 { + --tw-text-opacity: 1; + color: rgb(112 110 109 / var(--tw-text-opacity)); +} + .text-blue-600 { --tw-text-opacity: 1; color: rgb(63 93 179 / var(--tw-text-opacity)); @@ -1515,6 +1774,12 @@ select { color: rgb(178 45 48 / var(--tw-text-opacity)); } +/* + * golink search combobox and search-page styles. Plain hand-written CSS (no + * @apply) in the components layer so Tailwind utilities can still override them + * on a given element. (.sr-only is Tailwind's own utility; don't redefine it.) + */ + .placeholder\:text-gray-400::-moz-placeholder { --tw-text-opacity: 1; color: rgb(175 172 171 / var(--tw-text-opacity)); @@ -1535,11 +1800,6 @@ select { border-color: rgb(148 8 33 / var(--tw-border-opacity)); } -.hover\:bg-gray-100:hover { - --tw-bg-opacity: 1; - background-color: rgb(247 245 244 / var(--tw-bg-opacity)); -} - .hover\:bg-blue-600:hover { --tw-bg-opacity: 1; background-color: rgb(63 93 179 / var(--tw-bg-opacity)); @@ -1550,6 +1810,11 @@ select { background-color: rgb(148 8 33 / var(--tw-bg-opacity)); } +.hover\:bg-gray-100:hover { + --tw-bg-opacity: 1; + background-color: rgb(247 245 244 / var(--tw-bg-opacity)); +} + .hover\:fill-blue-500:hover { fill: rgba(75, 112, 204); } @@ -1589,4 +1854,4 @@ select { .md\:max-w-\[40vw\] { max-width: 40vw; } -} \ No newline at end of file +} diff --git a/static/base.src.css b/static/base.src.css new file mode 100644 index 0000000..58c89de --- /dev/null +++ b/static/base.src.css @@ -0,0 +1,218 @@ +@tailwind base; +@tailwind components; +@tailwind utilities; + +/* + * golink search combobox and search-page styles. Plain hand-written CSS (no + * @apply) in the components layer so Tailwind utilities can still override them + * on a given element. (.sr-only is Tailwind's own utility; don't redefine it.) + */ +@layer components { + .gl-header-top { + display: flex; + align-items: center; + gap: 1rem; + flex-wrap: wrap; + } + + .gl-header-tagline { + margin-top: 0.25rem; + } + + .gl-search { + position: relative; + flex: 0 1 200px; + width: 200px; + min-width: 0; + max-width: 200px; + margin: 0; + } + + .gl-search:focus-within { + flex-basis: 560px; + width: min(560px, 100%); + max-width: 560px; + } + + .gl-search-input { + width: 100%; + padding: 0.4rem 0.6rem; + border: 1px solid rgb(218 214 213); + border-radius: 0.375rem; + background-color: #fff; + font-size: 0.95rem; + line-height: 1.4; + box-sizing: border-box; + } + + .gl-search-input::placeholder { + color: rgb(112 110 109); + opacity: 1; + text-align: left; + } + + .gl-search-input[aria-expanded="true"]::placeholder { + color: transparent; + } + + .gl-search-input:focus { + outline: 2px solid rgba(63, 93, 179, 0.4); + outline-offset: 0; + border-color: rgba(63, 93, 179, 1); + } + + .gl-search-listbox { + position: absolute; + top: calc(100% + 2px); + left: 0; + right: 0; + margin: 0; + padding: 0; + list-style: none; + background: #fff; + border: 1px solid rgb(218 214 213); + border-radius: 0.375rem; + box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08); + max-height: min(82vh, calc(100dvh - 1rem)); + overflow-y: auto; + scrollbar-gutter: stable; + z-index: 50; + } + + .gl-search-listbox[hidden] { + display: none; + } + + .gl-search-option { + padding: 0.5rem 0.75rem; + cursor: pointer; + border-bottom: 1px solid rgb(238 235 234); + display: flex; + flex-direction: column; + gap: 0.1rem; + } + + .gl-search-option:last-child { + border-bottom: 0; + } + + .gl-search-option.is-active, + .gl-search-option[aria-selected="true"] { + background-color: #e9eef9; + } + + .gl-search-short { + font-weight: 600; + color: #111827; + } + + .gl-search-rendered { + font-size: 0.85rem; + color: rgb(112 110 109); + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + } + + .gl-search mark { + background: transparent; + color: rgb(63 93 179); + font-weight: 700; + padding: 0; + } + + .gl-search-tip { + padding: 0.5rem 0.75rem; + border-bottom: 1px solid rgb(238 235 234); + background-color: rgb(247 245 244); + } + + .gl-search-tip:last-child { + border-bottom: 0; + } + + .gl-search-tip-title { + display: block; + font-weight: 500; + font-size: 0.8rem; + color: rgb(97 95 94); + } + + .gl-search-tip-text { + display: block; + font-size: 0.78rem; + color: rgb(125 123 122); + margin-top: 0.12rem; + line-height: 1.35; + } + + .gl-search-tip code { + font-size: 0.76rem; + } + + /* The "Full results" footer is a role=option like other suggestions, + so it inherits .gl-search-option padding/hover, but we give it a + subtle visual separator and a muted default background so it reads + as a secondary action. */ + .gl-search-footer { + position: sticky; + bottom: 0; + z-index: 1; + border-top: 1px solid rgb(238 235 234); + background-color: rgb(247 245 244); + text-align: left; + font-size: 0.85rem; + color: rgb(63 93 179); + } + + .gl-search-footer .gl-search-more { + font-weight: 600; + } + + @media (max-width: 640px) { + .gl-search, + .gl-search:focus-within { + flex-basis: 100%; + width: 100%; + max-width: none; + } + } + + /* Input on the server-rendered /.search page. Similar look to the + header combobox but full-width and free of listbox chrome. */ + .gl-search-page-form { + margin: 0 0 1rem 0; + max-width: 560px; + } + + .gl-search-page-input { + width: 100%; + padding: 0.4rem 0.6rem; + border: 1px solid rgb(218 214 213); + border-radius: 0.375rem; + background-color: #fff; + font-size: 0.95rem; + line-height: 1.4; + box-sizing: border-box; + } + + .gl-search-page-input:focus { + outline: 2px solid rgba(63, 93, 179, 0.4); + outline-offset: 0; + border-color: rgba(63, 93, 179, 1); + } + + /* Wrapped template text on /.search rows. Template strings can be very long + and include no natural break points, so allow both normal wrapping and + forced token breaks to keep them inside the row. */ + .gl-search-template-line { + white-space: normal; + overflow-wrap: anywhere; + } + + .gl-search-template-code { + white-space: pre-wrap; + word-break: break-word; + overflow-wrap: anywhere; + } +} diff --git a/static/search.js b/static/search.js new file mode 100644 index 0000000..04e0d93 --- /dev/null +++ b/static/search.js @@ -0,0 +1,581 @@ +// golink autocomplete combobox. +// +// Progressive enhancement: the
in base.html works +// without JS (server renders an HTML results page). This script hijacks +// keystrokes on the input and renders a WAI-ARIA combobox with a listbox +// popup, following the APG pattern at +// https://www.w3.org/WAI/ARIA/apg/patterns/combobox/examples/combobox-autocomplete-list/ +// +// Keyboard model: +// - Printable chars: debounced fetch of /.search?q=... ; popup opens +// - ArrowDown/ArrowUp: move active option (wraps; includes "Full results" +// as the last selectable option) +// - Home/End: first/last option +// - Enter: activate the currently active option (navigate to its target +// or, for the "more results" option, to the /.search page) +// - Cmd/Ctrl/middle-click + Enter/click: open target in a new tab +// - Shift + Enter/click: open target in a new window +// - Alt + Enter/click: jump to the link-details page (/.detail/{short}) +// rather than following the link +// - Escape: close popup, keep input focus and value +// - Tab: close popup, allow normal focus movement +// +// Per APG, DOM focus stays on the input at all times; the "selected" +// option is tracked via aria-activedescendant. + +(function () { + "use strict"; + + var input = document.getElementById("gl-search-input"); + var listbox = document.getElementById("gl-search-listbox"); + var live = document.getElementById("gl-search-live"); + var form = input && input.form; + if (!input || !listbox || !form) return; + + var DEBOUNCE_MS = 80; + var TIP_ITEMS = [ + { + title: "Type to search short links", + text: "Start typing any short name to see fuzzy matches.", + }, + { + title: "Prefix with ? to search destinations", + text: "Use ?docs to also match destination URL bodies.", + }, + { + title: "Keyboard shortcuts", + text: "Use ↑/↓ to move and Enter to open the selected result.", + }, + { + title: "More actions", + text: "Use Alt+Enter for details, Cmd/Ctrl+Enter for a new tab, and Shift+Enter for a new window.", + }, + ]; + // Sentinel activeIndex value for the "Full results" footer option. + // It lives conceptually at results.length; we encode that explicitly + // so results.length === 0 with an active footer also works. + var MORE_INDEX = -2; + var state = { + query: "", // the raw query string the current results are for + results: [], // latest SearchResult[] from server + hasMore: false, // whether a "full results" option is present + showTips: false, // whether the empty-state tips popup is showing + activeIndex: -1, // 0..results.length-1 for a result, + // MORE_INDEX for the "full results" footer, + // -1 for nothing active + debounceTimer: null, + controller: null, // AbortController for in-flight fetch + lastAnnouncedCount: null, + }; + + // Escape text for safe insertion into HTML. We intentionally build + // the listbox with innerHTML so we can wrap matched characters in + // elements; everything user-supplied is run through this first. + function esc(s) { + return String(s) + .replace(/&/g, "&") + .replace(//g, ">") + .replace(/"/g, """) + .replace(/'/g, "'"); + } + + function tipsHTML() { + var html = ""; + for (var i = 0; i < TIP_ITEMS.length; i++) { + html += + ''; + } + return html; + } + + // Wrap matched rune positions in . Positions are into the rune + // sequence of `str`; we iterate code points so that multi-byte chars + // don't break alignment. + function highlight(str, positions) { + if (!positions || !positions.length) return esc(str); + var posSet = new Set(positions); + var out = ""; + // Use Array.from to iterate by code point. + var codePoints = Array.from(str); + for (var p = 0; p < codePoints.length; p++) { + var ch = esc(codePoints[p]); + if (posSet.has(p)) { + out += "" + ch + ""; + } else { + out += ch; + } + } + return out; + } + + // Position arrays already come split per-field from the server. + function splitPositions(result) { + return { + short: result.shortMatchedIndexes || [], + long: result.longMatchedIndexes || [], + }; + } + + // parseQuery mirrors the server-side search input parsing enough for the + // client to tell whether the user is editing the short name or only the + // path/query suffix after a '/'. + function parseQuery(raw) { + var s = String(raw || "").replace(/^[ \t]+/, ""); + var hasNonLeadingQuestion = s.indexOf("?") > 0; + if (s.charAt(0) === "?") { + s = s.slice(1); + } + var qmark = s.indexOf("?"); + if (qmark >= 0) { + s = s.slice(0, qmark); + } + var slash = s.indexOf("/"); + if (slash >= 0) { + return { + shortQuery: s.slice(0, slash), + hasSlash: true, + hasNonLeadingQuestion: hasNonLeadingQuestion, + }; + } + return { + shortQuery: s, + hasSlash: false, + hasNonLeadingQuestion: hasNonLeadingQuestion, + }; + } + + function activeResultShort() { + if (state.activeIndex < 0) return ""; + var r = state.results[state.activeIndex]; + return r ? r.short : ""; + } + + // preserveSelectionAfterSlash reports whether a selected result should stay + // selected across a suggestions refresh. This is only true when the user is + // editing after (or has just typed) a '/' or a non-leading '?' and the + // short-query portion has not changed, meaning only the link template/path + // preview is changing. + function preserveSelectionAfterSlash(prevRaw, nextRaw) { + var prev = parseQuery(prevRaw); + var next = parseQuery(nextRaw); + return (next.hasSlash || next.hasNonLeadingQuestion) && + next.shortQuery !== "" && + prev.shortQuery === next.shortQuery; + } + + // navigate handles opening `target` according to the modifier keys held + // when the event fired. Mirrors standard browser link behavior: + // - Cmd (macOS), Ctrl (other), or middle-click: new background tab + // - Shift: new window + // - Otherwise: current tab + // The second parameter is the original event (KeyboardEvent or + // MouseEvent); falsy values default to current-tab navigation. + function navigate(target, ev) { + if (!target) return; + var meta = !!(ev && (ev.metaKey || ev.ctrlKey)); + var middle = !!(ev && ev.type === "mouseup" && ev.button === 1); + var shift = !!(ev && ev.shiftKey); + if (meta || middle) { + window.open(target, "_blank", "noopener,noreferrer"); + return; + } + if (shift) { + window.open( + target, + "_blank", + "noopener,noreferrer,width=" + + (window.screen && window.screen.availWidth ? window.screen.availWidth : 1024) + + ",height=" + + (window.screen && window.screen.availHeight ? window.screen.availHeight : 768), + ); + return; + } + window.location.href = target; + } + + // Resolve a "selectable option index" to {kind, target}. + // kind "result": resolve against state.results[idx], honoring Alt + // which swaps the navigation target for the detail page. + // kind "more": the /.search page. + // If ev has Alt held and the option is a result, DetailTarget is + // returned; otherwise the regular Target. + function targetForIndex(idx, ev) { + if (idx === MORE_INDEX) { + if (!state.query) return null; + return "/.search?q=" + encodeURIComponent(state.query); + } + var r = state.results[idx]; + if (!r) return null; + var alt = !!(ev && ev.altKey); + return alt && r.detailTarget ? r.detailTarget : r.target; + } + + // activatable returns the list of activeIndex values the user can + // currently navigate to, in display order. Used for ArrowUp/Down/Home/End. + function activatable() { + var list = []; + for (var i = 0; i < state.results.length; i++) list.push(i); + if (state.hasMore) list.push(MORE_INDEX); + return list; + } + + // domIdForIndex returns the DOM id for the option at the given virtual + // index (so aria-activedescendant can point at it). + function domIdForIndex(idx) { + if (idx === MORE_INDEX) return "gl-search-more"; + if (idx < 0) return ""; + return "gl-search-opt-" + idx; + } + + function render() { + if (state.showTips) { + listbox.innerHTML = tipsHTML(); + listbox.hidden = false; + input.setAttribute("aria-expanded", "true"); + input.setAttribute("aria-activedescendant", ""); + return; + } + if (!state.results.length && !state.hasMore) { + listbox.innerHTML = ""; + listbox.hidden = true; + input.setAttribute("aria-expanded", "false"); + input.setAttribute("aria-activedescendant", ""); + return; + } + var html = ""; + for (var i = 0; i < state.results.length; i++) { + var r = state.results[i]; + var isActive = i === state.activeIndex; + var optionId = "gl-search-opt-" + i; + var positions = splitPositions(r); + var shortHtml = highlight(r.short, positions.short); + var renderedHtml = positions.long.length + ? highlight(r.rendered, positions.long) + : esc(r.rendered); + html += + '
  • ' + + 'go/' + shortHtml + '' + + '→ ' + renderedHtml + '' + + '
  • '; + } + // "Full results" footer, modelled as a role="option" so it's + // reachable via ArrowUp/ArrowDown. Alt modifier doesn't apply to + // this option (there's no detail page for a query). + if (state.hasMore) { + var moreHref = "/.search?q=" + encodeURIComponent(state.query); + var moreActive = state.activeIndex === MORE_INDEX; + html += + ''; + } + listbox.innerHTML = html; + listbox.hidden = false; + input.setAttribute("aria-expanded", "true"); + input.setAttribute("aria-activedescendant", domIdForIndex(state.activeIndex)); + } + + function hidePopup() { + listbox.hidden = true; + input.setAttribute("aria-expanded", "false"); + input.setAttribute("aria-activedescendant", ""); + } + + function announce(count) { + if (count === state.lastAnnouncedCount) return; + state.lastAnnouncedCount = count; + if (count === 0) { + live.textContent = "No suggestions."; + } else if (count === 1) { + live.textContent = "1 suggestion available."; + } else { + live.textContent = count + " suggestions available."; + } + } + + function close() { + state.query = ""; + state.results = []; + state.hasMore = false; + state.showTips = false; + state.activeIndex = -1; + state.lastAnnouncedCount = null; + if (state.controller) { + state.controller.abort(); + state.controller = null; + } + render(); + } + + function showTips() { + if (state.controller) { + state.controller.abort(); + state.controller = null; + } + state.query = ""; + state.results = []; + state.hasMore = false; + state.showTips = true; + state.activeIndex = -1; + render(); + live.textContent = "Search tips shown."; + } + + // setActiveByPosition moves to the nth activatable option (wrapping + // both ends). Position can be negative (for wrap-up) or >= length + // (for wrap-down). + function setActiveByPosition(pos) { + var list = activatable(); + if (!list.length) { + state.activeIndex = -1; + return; + } + var n = list.length; + var wrapped = ((pos % n) + n) % n; + state.activeIndex = list[wrapped]; + render(); + var el = document.getElementById(domIdForIndex(state.activeIndex)); + if (el && el.scrollIntoView) { + el.scrollIntoView({ block: "nearest" }); + } + } + + // moveActive shifts the active option by +1 or -1, wrapping. + function moveActive(delta) { + var list = activatable(); + if (!list.length) return; + var curPos = list.indexOf(state.activeIndex); + if (curPos === -1) { + // Nothing active yet -> start at either end depending on direction. + setActiveByPosition(delta > 0 ? 0 : list.length - 1); + return; + } + setActiveByPosition(curPos + delta); + } + + function fetchResults(q) { + if (state.controller) state.controller.abort(); + if (!q.trim()) { + showTips(); + return; + } + state.showTips = false; + var preserveShort = preserveSelectionAfterSlash(state.query, q) + ? activeResultShort() + : ""; + var ctrl = new AbortController(); + state.controller = ctrl; + var url = "/.search?q=" + encodeURIComponent(q); + fetch(url, { + headers: { Accept: "application/json" }, + signal: ctrl.signal, + credentials: "same-origin", + }) + .then(function (resp) { + if (!resp.ok) throw new Error("search HTTP " + resp.status); + return resp.json(); + }) + .then(function (data) { + // Ignore stale responses (input has changed since this fetch + // started). We already abort on new input, but guard anyway. + if (ctrl !== state.controller) return; + state.query = q; + state.results = Array.isArray(data.results) ? data.results : []; + state.showTips = false; + // Surface "Full results" whenever the server indicates there + // were more matches beyond the returned set. Also show it + // unconditionally when there's at least one result, so users + // have a keyboard-reachable path to the full search page even + // if they happened to land on a query that returned < 8 hits. + state.hasMore = !!data.limitHit || state.results.length > 0; + if (preserveShort) { + var preservedIdx = -1; + for (var i = 0; i < state.results.length; i++) { + if (state.results[i].short === preserveShort) { + preservedIdx = i; + break; + } + } + if (preservedIdx >= 0) { + state.activeIndex = preservedIdx; + } else { + state.activeIndex = state.results.length + ? 0 + : state.hasMore ? MORE_INDEX : -1; + } + } else { + // Pre-activate the first result so Enter navigates to it. + state.activeIndex = state.results.length + ? 0 + : state.hasMore ? MORE_INDEX : -1; + } + render(); + announce(state.results.length); + }) + .catch(function (err) { + if (err && err.name === "AbortError") return; + // On error, just close the popup; don't spam the user. + // The no-JS form fallback (Enter submits to /.search) still works. + close(); + }); + } + + input.addEventListener("input", function () { + var q = input.value; + clearTimeout(state.debounceTimer); + state.debounceTimer = setTimeout(function () { + fetchResults(q); + }, DEBOUNCE_MS); + }); + + input.addEventListener("keydown", function (e) { + switch (e.key) { + case "ArrowDown": + if (listbox.hidden) { + e.preventDefault(); + if (state.results.length || state.hasMore || state.showTips) { + render(); + } else if (input.value.trim()) { + fetchResults(input.value); + } + if (!state.showTips && state.activeIndex === -1) { + setActiveByPosition(0); + } + } else if (!state.showTips) { + e.preventDefault(); + moveActive(1); + } + break; + case "ArrowUp": + if (!listbox.hidden && !state.showTips) { + e.preventDefault(); + moveActive(-1); + } + break; + case "Home": + if (!listbox.hidden && !state.showTips) { + e.preventDefault(); + setActiveByPosition(0); + } + break; + case "End": + if (!listbox.hidden && !state.showTips) { + e.preventDefault(); + setActiveByPosition(activatable().length - 1); + } + break; + case "Escape": + if (!listbox.hidden) { + e.preventDefault(); + hidePopup(); + } + break; + case "Tab": + if (!listbox.hidden) close(); + break; + case "Enter": + // If an option is active, navigate to its target (honoring + // modifier keys). Otherwise fall through to the form's default + // submit handler, which lands on /.search for a full search. + if (state.activeIndex !== -1) { + var target = targetForIndex(state.activeIndex, e); + if (target) { + e.preventDefault(); + navigate(target, e); + } + } + break; + } + }); + + // Clicking an option navigates to its target. Honor Cmd/Ctrl/Shift/Alt + // and middle-click. + listbox.addEventListener("click", function (e) { + var li = e.target.closest("li[role=option]"); + if (!li) return; + e.preventDefault(); + var kind = li.getAttribute("data-kind"); + var target; + if (kind === "more") { + target = li.getAttribute("data-target"); + } else { + var alt = !!e.altKey; + var detail = li.getAttribute("data-detail-target"); + target = alt && detail ? detail : li.getAttribute("data-target"); + } + navigate(target, e); + }); + + // Middle-click (button 1) doesn't reliably fire "click"; use "auxclick". + listbox.addEventListener("auxclick", function (e) { + if (e.button !== 1) return; + var li = e.target.closest("li[role=option]"); + if (!li) return; + e.preventDefault(); + var kind = li.getAttribute("data-kind"); + var target = kind === "more" + ? li.getAttribute("data-target") + : (e.altKey + ? (li.getAttribute("data-detail-target") || li.getAttribute("data-target")) + : li.getAttribute("data-target")); + if (target) window.open(target, "_blank", "noopener,noreferrer"); + }); + + // Hovering an option activates it (mouse + keyboard parity). + listbox.addEventListener("mousemove", function (e) { + if (state.showTips) return; + var li = e.target.closest("li[role=option]"); + if (!li) return; + var kind = li.getAttribute("data-kind"); + var newIdx; + if (kind === "more") { + newIdx = MORE_INDEX; + } else { + var i = parseInt(li.getAttribute("data-index"), 10); + if (Number.isNaN(i)) return; + newIdx = i; + } + if (newIdx !== state.activeIndex) { + state.activeIndex = newIdx; + // Update visual/ARIA state without re-scrolling. + var opts = listbox.querySelectorAll("li[role=option]"); + for (var o = 0; o < opts.length; o++) { + var thisIdx = opts[o].getAttribute("data-kind") === "more" + ? MORE_INDEX + : parseInt(opts[o].getAttribute("data-index"), 10); + var active = thisIdx === newIdx; + opts[o].setAttribute("aria-selected", active ? "true" : "false"); + opts[o].classList.toggle("is-active", active); + } + input.setAttribute("aria-activedescendant", domIdForIndex(newIdx)); + } + }); + + // Close when clicking outside the form. + document.addEventListener("mousedown", function (e) { + if (!form.contains(e.target)) close(); + }); + + // Re-open popup on focus if we have a current query with cached results. + input.addEventListener("focus", function () { + if (!input.value.trim()) { + showTips(); + return; + } + if (state.results.length || state.hasMore) render(); + }); +})(); diff --git a/tailwind.config.js b/tailwind.config.js index 509e19e..4867e67 100644 --- a/tailwind.config.js +++ b/tailwind.config.js @@ -1,5 +1,5 @@ module.exports = { - content: ["./tmpl/*.html"], + content: ["./tmpl/*.html", "./static/*.js"], theme: { colors: { blue: { diff --git a/tmpl/base.html b/tmpl/base.html index 792bba8..4c1b4e0 100644 --- a/tmpl/base.html +++ b/tmpl/base.html @@ -8,11 +8,37 @@ - +
    -
    -

    {{go}}/

    - A private shortlink service for your tailnet +
    +
    +

    {{go}}/

    + {{/* + Search combobox. Server-rendered form (GET /.search) works with + JS disabled; search.js progressively enhances it into a + WAI-ARIA combobox with a listbox popup. + */}} + + + + +
    + +
    +
    A private shortlink service for your tailnet
    @@ -38,4 +64,5 @@

    {{go}}/

    +