diff --git a/dict/main.go b/dict/main.go index 422f92e..a82b718 100644 --- a/dict/main.go +++ b/dict/main.go @@ -69,26 +69,37 @@ func ParseEntry(entry jmdict.JmdictEntry) Entry { } } -func Search(query string) []Entry { +func Search(query string) (exactResults []Entry, otherResults []Entry) { query = strings.TrimSpace(query) - entries := make([]Entry, 0) + exactResults = make([]Entry, 0) + otherResults = make([]Entry, 0) for _, jmdictEntry := range dict.Entries { + exactMatch := false for _, kanji := range jmdictEntry.Kanji { if kanji.Expression == query { + exactMatch = true + goto match + } + if strings.Contains(kanji.Expression, query) { goto match } } + // TODO: Skip if query contains kanji for _, reading := range jmdictEntry.Readings { - if reading.Reading == query { + if strings.Contains(reading.Reading, query) { goto match } } continue match: entry := ParseEntry(jmdictEntry) - entries = append(entries, entry) + if exactMatch { + exactResults = append(exactResults, entry) + } else { + otherResults = append(otherResults, entry) + } } - return entries + return } func main() { @@ -108,16 +119,24 @@ func main() { w.Header().Set("Content-Type", "application/json; charset=utf-8") r.ParseMultipartForm(0) query := r.FormValue("q") - entries := Search(query) - jsonBytes, _ := json.Marshal(entries) + exactResults, otherResults := Search(query) + jsonBytes, _ := json.Marshal(append(exactResults, otherResults...)) fmt.Fprint(w, string(jsonBytes)) return false }, func(w http.ResponseWriter, r *http.Request) any { r.ParseMultipartForm(0) query := r.FormValue("q") - entry := Search(query) - return entry + exactResults, otherResults := Search(query) + return struct { + ExactResults []Entry + OtherResults []Entry + Count int + }{ + ExactResults: exactResults, + OtherResults: otherResults, + Count: len(exactResults) + len(otherResults), + } }, []string{http.MethodGet, http.MethodPost}, )) diff --git a/dict/templates/search.html b/dict/templates/search.html index 7679286..a345fe2 100644 --- a/dict/templates/search.html +++ b/dict/templates/search.html @@ -1,23 +1,8 @@ -
{{ $count := (len .) }}{{ if eq $count 0 }}No results{{ else }}{{ $count }} result{{ if ne $count 1}}s{{ end }}{{ end }}.
-{{ range . -}} -{{- template "definition" (index .Definitions 0) -}}
- {{- else -}} -{{ if eq .Count 0 }}No results{{ else }}{{ .Count }} result{{ if ne .Count 1}}s{{ end }}{{ end }}.
+{{- range .ExactResults -}} +{{- template "word" . -}} +{{- end }} +{{- template "definition" (index .Definitions 0) -}}
+ {{- else -}} +