summaryrefslogtreecommitdiff
path: root/main.go
diff options
context:
space:
mode:
Diffstat (limited to 'main.go')
-rw-r--r--main.go30
1 files changed, 29 insertions, 1 deletions
diff --git a/main.go b/main.go
index 235be18..ef4e7ad 100644
--- a/main.go
+++ b/main.go
@@ -7,12 +7,16 @@ import (
"fmt"
"log"
"net/http"
+ "regexp"
+ "strings"
"time"
"github.com/charmbracelet/bubbles/textinput"
+ "github.com/charmbracelet/bubbles/viewport"
tea "github.com/charmbracelet/bubbletea"
_ "github.com/mattn/go-sqlite3"
"github.com/microcosm-cc/bluemonday"
+ "github.com/muesli/reflow/wordwrap"
)
const (
@@ -33,6 +37,7 @@ type model struct {
c *http.Client
wordAddStatus string
p bluemonday.Policy
+ vp viewport.Model
}
type (
@@ -47,6 +52,7 @@ func initialModel(c *http.Client, db *sql.DB) model {
ti.Focus()
ti.CharLimit = 156
ti.Width = 36
+ vp := viewport.New(80, 30)
return model{
wordInput: ti,
@@ -55,6 +61,7 @@ func initialModel(c *http.Client, db *sql.DB) model {
c: c,
wordAddStatus: "(Press 'Enter' to add this word and its definition to Anki)",
p: *bluemonday.StrictPolicy(),
+ vp: vp,
}
}
@@ -82,6 +89,7 @@ func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
switch msg := msg.(type) {
case definitionMsg:
m.currentDefinition = string(msg)
+ m.vp.SetContent(formatDefinitionForDisplay(m.p, m.currentDefinition))
return m, nil
case wordAddedMsg:
m.wordAddStatus = fmt.Sprintf("✅ Added '%s' to Anki", string(msg))
@@ -103,11 +111,17 @@ func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
textPickerLongerCmds = append(textPickerLongerCmds, lookupWord(m.db, m.currentWord))
}
+ var vpCmd tea.Cmd
+ m.vp, vpCmd = m.vp.Update(msg)
+ textPickerLongerCmds = append(textPickerLongerCmds, vpCmd)
+
m.wordInput, cmd = m.wordInput.Update(msg)
textPickerLongerCmds = append(textPickerLongerCmds, cmd)
return m, tea.Batch(textPickerLongerCmds...)
}
+var whitespaceTrimmerRe = regexp.MustCompile(`^[ \t]*$`)
+
func (m model) View() string {
return fmt.Sprintf(
"Look up a word:\n\n%s\n\n%s\n%s\n\n%s\n%s",
@@ -115,10 +129,24 @@ func (m model) View() string {
m.wordAddStatus,
"(esc to quit)",
"Current definition:\n",
- m.p.Sanitize(m.currentDefinition),
+ m.vp.View(),
) + "\n"
}
+func formatDefinitionForDisplay(policy bluemonday.Policy, definition string) string {
+ return wordwrap.String(
+ strings.ReplaceAll(
+ whitespaceTrimmerRe.ReplaceAllLiteralString(
+ policy.Sanitize(definition),
+ "",
+ ),
+ "\n\n",
+ "\n",
+ ),
+ 72,
+ )
+}
+
func main() {
db, err := setupDatabase()
if err != nil {