diff options
| author | David Schlachter <t480-debian-git@schlachter.ca> | 2026-01-08 01:26:15 -0500 |
|---|---|---|
| committer | David Schlachter <t480-debian-git@schlachter.ca> | 2026-01-08 01:26:15 -0500 |
| commit | bfa6f9641a59e1c388b33d1bc1be2bbe9e4d3a86 (patch) | |
| tree | 5a2936eb159de765c7dd98e4aa8cb995fbd84b0a /main.go | |
| parent | 6d3623e3295ceacf7e1200d05790a9c662b69960 (diff) | |
Prettier view
Diffstat (limited to 'main.go')
| -rw-r--r-- | main.go | 30 |
1 files changed, 29 insertions, 1 deletions
@@ -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 { |
