2024-05-16 02:04:08 +02:00
|
|
|
package widget
|
|
|
|
|
|
|
|
import (
|
2024-05-25 04:58:11 +02:00
|
|
|
"fmt"
|
2024-05-16 02:04:08 +02:00
|
|
|
"html/template"
|
2024-05-25 04:58:11 +02:00
|
|
|
"strings"
|
2024-05-16 02:04:08 +02:00
|
|
|
|
|
|
|
"github.com/glanceapp/glance/internal/assets"
|
|
|
|
)
|
|
|
|
|
2024-05-25 04:58:11 +02:00
|
|
|
type SearchBang struct {
|
|
|
|
Title string
|
|
|
|
Shortcut string
|
|
|
|
URL string
|
|
|
|
}
|
|
|
|
|
2024-05-16 02:04:08 +02:00
|
|
|
type Search struct {
|
2024-05-25 04:58:11 +02:00
|
|
|
widgetBase `yaml:",inline"`
|
|
|
|
cachedHTML template.HTML `yaml:"-"`
|
|
|
|
SearchEngine string `yaml:"search-engine"`
|
|
|
|
Bangs []SearchBang `yaml:"bangs"`
|
2024-06-09 15:18:56 +02:00
|
|
|
NewTab bool `yaml:"new-tab"`
|
2024-07-15 17:30:12 +02:00
|
|
|
Autofocus bool `yaml:"autofocus"`
|
2024-05-25 04:58:11 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
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 02:04:08 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
func (widget *Search) Initialize() error {
|
|
|
|
widget.withTitle("Search").withError(nil)
|
|
|
|
|
2024-05-25 04:58:11 +02:00
|
|
|
if widget.SearchEngine == "" {
|
|
|
|
widget.SearchEngine = "duckduckgo"
|
2024-05-16 02:04:08 +02:00
|
|
|
}
|
|
|
|
|
2024-05-25 04:58:11 +02: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 02:04:08 +02:00
|
|
|
|
2024-05-25 04:58:11 +02:00
|
|
|
widget.cachedHTML = widget.render(widget, assets.SearchTemplate)
|
2024-05-16 02:04:08 +02:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (widget *Search) Render() template.HTML {
|
2024-05-25 04:58:11 +02:00
|
|
|
return widget.cachedHTML
|
2024-05-16 02:04:08 +02:00
|
|
|
}
|