summaryrefslogtreecommitdiff
path: root/ui.go
blob: 62de3cd6d9d56d2005e935a3d7a5e4e68f9a078f (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
package main

import (
	"database/sql"
	"errors"
	"fmt"
	"net/http"
	"regexp"
	"strings"

	"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)

	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 {
		var definition string
		row := db.QueryRow(`select definition from words where word = ? limit 1`, word)
		err := row.Scan(&definition)
		if err != nil {
			if errors.Is(err, sql.ErrNoRows) {
				return definitionMsg("")
			}
			return errMsg(fmt.Errorf("looking up '%s': %s", word, err))
		}
		return definitionMsg(definition)
	}
}

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:
			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)",
		"\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)

	// Add some colour to the start of each definition
	str = strings.ReplaceAll(str, "\t- ", "\x1b[0;33;49m•\x1b[0m ")

	// Replace common HTML entities
	str = strings.ReplaceAll(str, "&#39;", "’")

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