Add search highlighting

This commit is contained in:
Elnu 2023-07-23 15:00:31 -07:00
parent b20cdaf819
commit 3965b59893
3 changed files with 33 additions and 7 deletions

View file

@ -5,6 +5,7 @@ import (
"encoding/gob"
"encoding/json"
"fmt"
"html/template"
"log"
"net/http"
"os"
@ -213,6 +214,13 @@ func ParseEntry(entry *jmdict.JmdictEntry, furiganaInfo *string) Entry {
}
}
func highlight(input, substring string) template.HTML {
// Replace all occurrences of substring with the highlighted version
replacement := fmt.Sprintf("<mark>%s</mark>", substring)
result := strings.ReplaceAll(input, substring, replacement)
return template.HTML(result)
}
func Search(query string) queryResult {
query = strings.TrimSpace(query)
exactResults := make([]Entry, 0)
@ -286,6 +294,12 @@ func main() {
return
}
fmt.Println("JMdict loaded!")
httputils.DefaultTemplateFuncs = template.FuncMap{
"highlight": func(input string) string {
return input
},
}
httputils.TemplateFuncs = httputils.DefaultTemplateFuncs
r := mux.NewRouter()
r.HandleFunc("/", httputils.GenerateHandler(
func(w http.ResponseWriter, r *http.Request) bool { return true },
@ -326,15 +340,20 @@ func main() {
},
httputils.NewTemplateSet("index.html", "search.html"),
// template data
func(w http.ResponseWriter, r *http.Request) (template string, data any) {
func(w http.ResponseWriter, r *http.Request) (templateName string, data any) {
if r.Header.Get("HX-Request") == "" {
template = "search.html"
templateName = "search.html"
} else {
template = "search"
templateName = "search"
}
// Only runs if handler returns true
query := mux.Vars(r)["query"]
data = Search(query)
httputils.TemplateFuncs = template.FuncMap{
"highlight": func(input string) template.HTML {
return highlight(input, strings.TrimSpace(query))
},
}
return
},
[]string{http.MethodGet},

View file

@ -1,3 +1,3 @@
{{- define "definition" -}}
{{ if .PartOfSpeech }}<small><chip>{{ .PartOfSpeech }}</chip></small><br>{{ end }}{{ .Definition -}}
{{ if .PartOfSpeech }}<small><chip>{{ .PartOfSpeech }}</chip></small><br>{{ end }}{{ highlight .Definition -}}
{{ end }}