8356
Wx
www-xonecas-io / files
www-xonecas-io / internal / site / search.go
1.6 KB
1package site 2 3import ( 4 "cmp" 5 "fmt" 6 "net/url" 7 "slices" 8 "strings" 9 10 "xonecas.io/site/internal/project" 11) 12 13// Suggestion is one thing the header search offers: a project, or a topic that searches /projects. 14type Suggestion struct{ Label, Note, Href string } 15 16// Suggest is what the header search offers for q: up to 6 projects whose name has q, those that start with it 17// first and then by last commit, and up to 3 topics that have q, commonest first. 18func Suggest(shown []project.Project, q string) []Suggestion { 19 q = strings.ToLower(strings.TrimSpace(q)) 20 if q == "" { 21 return nil 22 } 23 shown = slices.Clone(shown) 24 slices.SortStableFunc(shown, func(a, b project.Project) int { return cmp.Compare(b.Last, a.Last) }) 25 var list, projects []Suggestion 26 counts := map[string]int{} 27 for _, p := range shown { 28 name := strings.ToLower(p.Name) 29 if strings.HasPrefix(name, q) { 30 list = append(list, Suggestion{p.Name, p.Description, "/projects/" + p.Name + "/"}) 31 } else if strings.Contains(name, q) { 32 projects = append(projects, Suggestion{p.Name, p.Description, "/projects/" + p.Name + "/"}) 33 } 34 for _, t := range p.Topics { 35 counts[t]++ 36 } 37 } 38 list = append(list, projects...) 39 list = list[:min(6, len(list))] 40 var topics []string 41 for t := range counts { 42 if strings.Contains(t, q) { 43 topics = append(topics, t) 44 } 45 } 46 slices.SortFunc(topics, func(a, b string) int { return cmp.Or(counts[b]-counts[a], cmp.Compare(a, b)) }) 47 for _, t := range topics[:min(3, len(topics))] { 48 list = append(list, Suggestion{t, fmt.Sprintf("topic · %d projects", counts[t]), "/projects/?q=" + url.QueryEscape(t)}) 49 } 50 return list 51}