summaryrefslogtreecommitdiff
path: root/ui.go
blob: 5e6817146c66cb7500a92955c463c33ef54de532 (plain)
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
package main

import (
	"database/sql"
	"fmt"
	"html"
	"net/http"
	"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 {
	db *sql.DB
	c  *http.Client
	p  bluemonday.Policy

	wordInput          textinput.Model
	definitionViewport viewport.Model

	ankiDeck          string
	ankiModel         string
	apiURL            string
	rawDictionaryPath string

	dictionaryReady bool

	currentWord       string
	currentDefinition string
	statusString      string
	err               error
}

type (
	errMsg        error
	definitionMsg string
	wordAddedMsg  string
	isDBEmptyMsg  bool
)

func initialModel(c *http.Client, db *sql.DB, apiURL, ankiDeck, ankiModel, rawDictionary, firstWord string) model {
	input := textinput.New()
	input.Placeholder = ""
	input.Focus()
	input.CharLimit = 156
	input.Width = 36

	if firstWord != "" {
		input.SetValue(firstWord)
	}

	textbox := viewport.New(80, 30)
	textbox.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"),
		),
	}

	return model{
		db: db,
		c:  c,
		p:  *bluemonday.StrictPolicy(),

		wordInput:          input,
		definitionViewport: textbox,

		ankiDeck:          ankiDeck,
		ankiModel:         ankiModel,
		apiURL:            apiURL,
		rawDictionaryPath: rawDictionary,

		currentWord: firstWord,
	}
}

func (m model) Init() tea.Cmd {
	cmds := []tea.Cmd{textinput.Blink}
	cmds = append(cmds, isDatabaseEmpty(m.db))
	return tea.Batch(cmds...)
}

func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
	var cmd tea.Cmd

	var textPickerLongerCmds []tea.Cmd

	switch msg := msg.(type) {
	case isDBEmptyMsg:
		if bool(msg) {
			// set up the database
			return m, populateDictionary(m.rawDictionaryPath, m.db)
		} else {
			m.dictionaryReady = true
			if m.currentWord != "" {
				textPickerLongerCmds = append(textPickerLongerCmds, lookupWord(m.db, m.currentWord))
			}
		}
	case definitionMsg:
		m.currentDefinition = string(msg)
		m.err = nil
		m.definitionViewport.SetContent(formatDefinitionForDisplay(m.p, m.currentDefinition, m.definitionViewport.Width))
		return m, nil
	case wordAddedMsg:
		m.statusString = fmt.Sprintf("✅ Added '%s' to Anki", string(msg))
		m.currentWord = ""
		m.currentDefinition = ""
		m.wordInput.SetValue("")
		m.definitionViewport.SetContent("")
		m.err = nil
	case tea.WindowSizeMsg:
		// headerHeight is the height of everything above the definition window.
		headerHeight := 11
		m.wordInput.Width = msg.Width
		m.definitionViewport.Width = msg.Width
		m.definitionViewport.Height = msg.Height - headerHeight
		m.definitionViewport.SetContent(formatDefinitionForDisplay(m.p, m.currentDefinition, m.definitionViewport.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.definitionViewport.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.definitionViewport, vpCmd = m.definitionViewport.Update(msg)
	textPickerLongerCmds = append(textPickerLongerCmds, vpCmd)

	m.wordInput, cmd = m.wordInput.Update(msg)
	textPickerLongerCmds = append(textPickerLongerCmds, cmd)
	return m, tea.Batch(textPickerLongerCmds...)
}

func (m model) View() string {
	if m.dictionaryReady {
		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.statusString),
			"(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.definitionViewport.View(),
		) + "\n"
	}
	if m.err != nil {
		return fmt.Sprintf("Failed to load dictionary! Error:\n\n%s\n\nExit with Control-C.\n", m.err)
	}
	return fmt.Sprintln("Preparing dictionary...")
}

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())
}