Improve serach function with quick suggestions

This commit is contained in:
2026-05-18 15:10:34 +02:00
parent 8244874fe3
commit a25d5434ac
8 changed files with 545 additions and 61 deletions
+44 -2
View File
@@ -1,6 +1,7 @@
package main
import (
"encoding/json"
"io/fs"
"log"
"net/http"
@@ -21,7 +22,7 @@ type searchResult struct {
type searchPageData struct {
Title string
Crumbs []crumb
ParentURL string
EditMode bool
Query string
Results []searchResult
@@ -65,7 +66,7 @@ func (h *handler) handleSearch(w http.ResponseWriter, r *http.Request) {
}
data := searchPageData{
Title: title,
Crumbs: []crumb{{Name: "search", URL: "/?q=" + query}},
ParentURL: "/",
Query: query,
Results: results,
IndexBuiltAt: builtAt,
@@ -159,6 +160,47 @@ func scoreName(nameLower string, nameTokens []string, qLower string, qTokens []s
return score
}
// handleSearchSuggest serves the JSON typeahead for the header dropdown and
// the editor's link picker. Caps results at 5; reports total so the UI can
// surface a "show all" footer when more matches exist. Empty/whitespace query
// is a no-op (200 with empty results), not a 400 — every keystroke fires this.
func (h *handler) handleSearchSuggest(w http.ResponseWriter, r *http.Request) {
if !h.checkAuth(w, r) {
return
}
query := strings.TrimSpace(r.URL.Query().Get("q"))
type suggestResult struct {
Name string `json:"name"`
Path string `json:"path"`
URL string `json:"url"`
}
type suggestResp struct {
Query string `json:"query"`
Results []suggestResult `json:"results"`
Total int `json:"total"`
}
resp := suggestResp{Query: query, Results: []suggestResult{}}
if query != "" {
all, _ := searchWiki(query)
resp.Total = len(all)
limit := 5
if len(all) < limit {
limit = len(all)
}
for i := 0; i < limit; i++ {
resp.Results = append(resp.Results, suggestResult{
Name: all[i].Name,
Path: all[i].Path,
URL: all[i].URL,
})
}
}
w.Header().Set("Content-Type", "application/json; charset=utf-8")
if err := json.NewEncoder(w).Encode(resp); err != nil {
log.Printf("search suggest encode error: %v", err)
}
}
// handleReindex rebuilds the folder index synchronously and returns 204.
// The frontend reloads the page on success. Serialized via buildMu so a
// double-click waits rather than running two walks in parallel.