glance/internal/widget/search.go

67 lines
1.5 KiB
Go
Raw Normal View History

2024-05-16 03:04:08 +03:00
package widget
import (
2024-05-25 05:58:11 +03:00
"fmt"
2024-05-16 03:04:08 +03:00
"html/template"
2024-05-25 05:58:11 +03:00
"strings"
2024-05-16 03:04:08 +03:00
"github.com/glanceapp/glance/internal/assets"
)
2024-05-25 05:58:11 +03:00
type SearchBang struct {
Title string
Shortcut string
URL string
}
2024-05-16 03:04:08 +03:00
type Search struct {
2024-05-25 05:58:11 +03:00
widgetBase `yaml:",inline"`
cachedHTML template.HTML `yaml:"-"`
SearchEngine string `yaml:"search-engine"`
Bangs []SearchBang `yaml:"bangs"`
}
func convertSearchUrl(url string) string {
// Go's template is being stubborn and continues to escape the curlies in the
// URL regardless of what the type of the variable is so this is my way around it
return strings.ReplaceAll(url, "{QUERY}", "!QUERY!")
}
var searchEngines = map[string]string{
"duckduckgo": "https://duckduckgo.com/?q={QUERY}",
"google": "https://www.google.com/search?q={QUERY}",
2024-05-16 03:04:08 +03:00
}
func (widget *Search) Initialize() error {
widget.withTitle("Search").withError(nil)
2024-05-25 05:58:11 +03:00
if widget.SearchEngine == "" {
widget.SearchEngine = "duckduckgo"
2024-05-16 03:04:08 +03:00
}
2024-05-25 05:58:11 +03:00
if url, ok := searchEngines[widget.SearchEngine]; ok {
widget.SearchEngine = url
}
widget.SearchEngine = convertSearchUrl(widget.SearchEngine)
for i := range widget.Bangs {
if widget.Bangs[i].Shortcut == "" {
return fmt.Errorf("Search bang %d has no shortcut", i+1)
}
if widget.Bangs[i].URL == "" {
return fmt.Errorf("Search bang %d has no URL", i+1)
}
widget.Bangs[i].URL = convertSearchUrl(widget.Bangs[i].URL)
}
2024-05-16 03:04:08 +03:00
2024-05-25 05:58:11 +03:00
widget.cachedHTML = widget.render(widget, assets.SearchTemplate)
2024-05-16 03:04:08 +03:00
return nil
}
func (widget *Search) Render() template.HTML {
2024-05-25 05:58:11 +03:00
return widget.cachedHTML
2024-05-16 03:04:08 +03:00
}