1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
|
package main
import (
"database/sql"
"errors"
"fmt"
"html"
"net/http"
"regexp"
"strings"
"github.com/charmbracelet/bubbles/key"
"github.com/charmbracelet/bubbles/textinput"
"github.com/charmbracelet/bubbles/viewport"
tea "github.com/charmbracelet/bubbletea"
"github.com/microcosm-cc/bluemonday"
"github.com/muesli/reflow/wordwrap"
)
type model struct {
wordInput textinput.Model
err error
currentWord string
currentDefinition string
db *sql.DB
c *http.Client
wordAddStatus string
p bluemonday.Policy
vp viewport.Model
ankiDeck string
ankiModel string
apiURL string
}
type (
errMsg error
definitionMsg string
wordAddedMsg string
)
func initialModel(c *http.Client, db *sql.DB, apiURL, ankiDeck, ankiModel, firstWord string) model {
ti := textinput.New()
ti.Placeholder = ""
ti.Focus()
ti.CharLimit = 156
ti.Width = 36
vp := viewport.New(80, 30)
vp.KeyMap = viewport.KeyMap{
PageDown: key.NewBinding(
key.WithKeys("pgdown", " ", "f"),
key.WithHelp("f/pgdn", "page down"),
),
PageUp: key.NewBinding(
key.WithKeys("pgup", "b"),
key.WithHelp("b/pgup", "page up"),
),
}
if firstWord != "" {
ti.SetValue(firstWord)
}
return model{
wordInput: ti,
err: nil,
db: db,
c: c,
wordAddStatus: "",
p: *bluemonday.StrictPolicy(),
vp: vp,
ankiDeck: ankiDeck,
ankiModel: ankiModel,
apiURL: apiURL,
currentWord: firstWord,
}
}
func (m model) Init() tea.Cmd {
cmds := []tea.Cmd{textinput.Blink}
if m.currentWord != "" {
cmds = append(cmds, lookupWord(m.db, m.currentWord))
}
return tea.Batch(cmds...)
}
func lookupWord(db *sql.DB, word string) tea.Cmd {
return func() tea.Msg {
word = strings.TrimSpace(word) // remove leading / trailing whitespace
// Replace apostrophes (possible if copy-pasting) with single quotes
word = strings.ReplaceAll(word, `’`, `'`)
rows, err := db.Query(`select definition from words where word = ?`, word)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
return definitionMsg("")
}
return errMsg(fmt.Errorf("looking up '%s': %s", word, err))
}
defer rows.Close()
var combinedDefinition []string
for rows.Next() {
var definition string
err = rows.Scan(&definition)
if err != nil {
return errMsg(fmt.Errorf("looking up '%s': %s", word, err))
}
combinedDefinition = append(combinedDefinition, definition)
}
if err := rows.Err(); err != nil {
return errMsg(fmt.Errorf("looking up '%s': %s", word, err))
}
return definitionMsg(strings.Join(combinedDefinition, "\n\n"))
}
}
func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
var cmd tea.Cmd
var textPickerLongerCmds []tea.Cmd
switch msg := msg.(type) {
case definitionMsg:
m.currentDefinition = string(msg)
m.err = nil
m.vp.SetContent(formatDefinitionForDisplay(m.p, m.currentDefinition, m.vp.Width))
return m, nil
case wordAddedMsg:
m.wordAddStatus = fmt.Sprintf("✅ Added '%s' to Anki", string(msg))
m.currentWord = ""
m.currentDefinition = ""
m.wordInput.SetValue("")
m.vp.SetContent("")
m.err = nil
case tea.WindowSizeMsg:
// headerHeight is the height of everything above the definition window.
headerHeight := 11
m.vp.Width = msg.Width
m.vp.Height = msg.Height - headerHeight
m.vp.SetContent(formatDefinitionForDisplay(m.p, m.currentDefinition, m.vp.Width))
case tea.KeyMsg:
switch msg.Type {
case tea.KeyCtrlC, tea.KeyCtrlD:
return m, tea.Quit
case tea.KeyEsc:
m.currentWord = ""
m.currentDefinition = ""
m.wordInput.SetValue("")
m.vp.SetContent("")
case tea.KeyEnter:
return m, addCard(m.c, m.apiURL, m.ankiDeck, m.ankiModel, m.currentWord, m.currentDefinition)
}
case errMsg:
m.err = msg
return m, nil
}
if m.wordInput.Value() != m.currentWord {
m.currentWord = m.wordInput.Value()
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(
"\x1b[1;30;42mLook up a word:\x1b[0m\n\n%s\n\n\x1b[1;30;42mStatus:\x1b[0m %s\n\n%s\n\n%s\n%s",
m.wordInput.View(),
formatStatus(m.err, m.wordAddStatus),
"(Ctrl-C to quit, Esc to clear, Enter to add to Anki, PgUp/Down to scroll)",
"\x1b[1;30;42mCurrent definition:\x1b[0m\n",
m.vp.View(),
) + "\n"
}
func formatDefinitionForDisplay(policy bluemonday.Policy, definition string, maxWidth int) string {
// Add a hyphen to the start of each definition
str := strings.ReplaceAll(definition, "<li class=sense>", "<li class=sense>- ")
// Italicize examples
str = strings.ReplaceAll(str, "\t<ul><li><i>", "\n\t<ul><li><i>\x1b[3;39;49m")
str = strings.ReplaceAll(str, "</i></li></ul></li>", "</i></li></ul></li>\x1b[0m")
// Remove all HTML tags
str = policy.Sanitize(str)
// Some Wiktionary entries have HTML entities in them. That's okay for Anki,
// but it's not okay for displaying the plain text in the console interface.
str = html.UnescapeString(str)
// Add some colour to the start of each definition
str = strings.ReplaceAll(str, "\t- ", "\x1b[0;33;49m•\x1b[0m ")
// Limit the width of the displayed definition to 80 characters, or the
// width of the viewport (whichever is smaller).
width := min(maxWidth, 80)
return wordwrap.String(str, width)
}
func formatStatus(lastError error, lastSuccess string) string {
if lastError == nil {
return lastSuccess
}
return fmt.Sprintf("\x1b[0;31;49m%s\x1b[0m", lastError.Error())
}
|