Debian Codegraph @

inputfield.go

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 // mauview - A Go TUI library based on tcell.
2 // Copyright © 2019 Tulir Asokan
3 //
4 // This Source Code Form is subject to the terms of the Mozilla Public
5 // License, v. 2.0. If a copy of the MPL was not distributed with this
6 // file, You can obtain one at http://mozilla.org/MPL/2.0/.
7
8 // Based on https://github.com/rivo/tview/blob/master/inputfield.go
9
10 package mauview
11
12 import (
13 "regexp"
14 "strings"
15 "unicode/utf8"
16
17 "github.com/mattn/go-runewidth"
18
•19 "github.com/gdamore/tcell/v2"
20 )
21
22 // InputField is a single-line user-editable text field.
23 //
24 // Use SetMaskCharacter() to hide input from onlookers (e.g. for password
25 // input).
26 type InputField struct {
27 // Cursor position
28 cursorOffset int
29 // Number of characters (from left) to offset rendering.
30 viewOffset int
31
32 // The text that was entered.
33 text string
34
35 // The text to be displayed in the input area when it is empty.
36 placeholder string
37
38 // The background color of the input area.
39 fieldBackgroundColor tcell.Color
40 // The text color of the input area.
41 fieldTextColor tcell.Color
42 // The text color of the placeholder.
43 placeholderTextColor tcell.Color
44
45 // A character to mask entered text (useful for password fields). A value of 0
46 // disables masking.
47 maskCharacter rune
48
49 // Whether or not to enable vim-style keybindings.
50 vimBindings bool
51
52 // Whether or not the input field is focused.
53 focused bool
54
55 // An optional function which is called when the input has changed.
56 changed func(text string)
57
58 // An optional function which is called when the user presses tab.
59 tabComplete func(text string, pos int)
60 }
61
62 // NewInputField returns a new input field.
63 func NewInputField() *InputField {
64 return &InputField{
65 fieldBackgroundColor: Styles.ContrastBackgroundColor,
66 fieldTextColor: Styles.PrimaryTextColor,
67 placeholderTextColor: Styles.ContrastSecondaryTextColor,
68 }
69 }
70
71 // SetText sets the current text of the input field.
72 func (field *InputField) SetText(text string) *InputField {
73 field.text = text
74 if field.changed != nil {
75 field.changed(text)
76 }
77 return field
78 }
79
80 // SetTextAndMoveCursor sets the current text of the input field and moves the cursor with the width difference.
81 func (field *InputField) SetTextAndMoveCursor(text string) *InputField {
82 oldWidth := runewidth.StringWidth(field.text)
83 field.text = text
84 newWidth := runewidth.StringWidth(field.text)
85 if oldWidth != newWidth {
86 field.cursorOffset += newWidth - oldWidth
87 }
88 if field.changed != nil {
89 field.changed(field.text)
90 }
91 return field
92 }
93
94 // GetText returns the current text of the input field.
95 func (field *InputField) GetText() string {
96 return field.text
97 }
98
99 // SetPlaceholder sets the text to be displayed when the input text is empty.
100 func (field *InputField) SetPlaceholder(text string) *InputField {
101 field.placeholder = text
102 return field
103 }
104
105 // SetBackgroundColor sets the background color of the input area.
106 func (field *InputField) SetBackgroundColor(color tcell.Color) *InputField {
107 field.fieldBackgroundColor = color
108 return field
109 }
110
111 // SetTextColor sets the text color of the input area.
112 func (field *InputField) SetTextColor(color tcell.Color) *InputField {
113 field.fieldTextColor = color
114 return field
115 }
116
117 // SetPlaceholderTextColor sets the text color of placeholder text.
118 func (field *InputField) SetPlaceholderTextColor(color tcell.Color) *InputField {
119 field.placeholderTextColor = color
120 return field
121 }
122
123 // SetMaskCharacter sets a character that masks user input on a screen. A value
124 // of 0 disables masking.
125 func (field *InputField) SetMaskCharacter(mask rune) *InputField {
126 field.maskCharacter = mask
127 return field
128 }
129
130 // SetChangedFunc sets a handler which is called whenever the text of the input
131 // field has changed. It receives the current text (after the change).
132 func (field *InputField) SetChangedFunc(handler func(text string)) *InputField {
133 field.changed = handler
134 return field
135 }
136
137 func (field *InputField) SetTabCompleteFunc(handler func(text string, cursorOffset int)) *InputField {
138 field.tabComplete = handler
139 return field
140 }
141
142 // prepareText prepares the text to be displayed and recalculates the view and cursor offsets.
143 func (field *InputField) prepareText(screen Screen) (text string, placeholder bool) {
144 width, _ := screen.Size()
145 text = field.text
146 if len(text) == 0 && len(field.placeholder) > 0 {
147 text = field.placeholder
148 placeholder = true
149 }
150
151 if !placeholder && field.maskCharacter > 0 {
152 text = strings.Repeat(string(field.maskCharacter), utf8.RuneCountInString(text))
153 }
154 textWidth := runewidth.StringWidth(text)
155 if field.cursorOffset >= textWidth {
156 width--
157 }
158
159 if field.cursorOffset < field.viewOffset {
160 field.viewOffset = field.cursorOffset
161 } else if field.cursorOffset > field.viewOffset+width {
162 field.viewOffset = field.cursorOffset - width
163 } else if textWidth-field.viewOffset < width {
164 field.viewOffset = textWidth - width
165 }
166
167 if field.viewOffset < 0 {
168 field.viewOffset = 0
169 }
170
171 return
172 }
173
174 // drawText draws the text and the cursor.
175 func (field *InputField) drawText(screen Screen, text string, placeholder bool) {
176 width, _ := screen.Size()
177 runes := []rune(text)
178 x := 0
179 style := tcell.StyleDefault.Foreground(field.fieldTextColor).Background(field.fieldBackgroundColor)
180 if placeholder {
181 style = style.Foreground(field.placeholderTextColor)
182 }
183 for pos := field.viewOffset; pos <= width+field.viewOffset && pos < len(runes); pos++ {
184 ch := runes[pos]
185 w := runewidth.RuneWidth(ch)
186 for w > 0 {
187 screen.SetContent(x, 0, ch, nil, style)
188 x++
189 w--
190 }
191 }
192 for ; x <= width; x++ {
193 screen.SetContent(x, 0, ' ', nil, style)
194 }
195 }
196
197 // Draw draws this primitive onto the screen.
198 func (field *InputField) Draw(screen Screen) {
199 width, height := screen.Size()
200 if height < 1 || width < 1 {
201 return
202 }
203
204 text, placeholder := field.prepareText(screen)
205 field.drawText(screen, text, placeholder)
206 if field.focused {
207 field.setCursor(screen)
208 }
209 }
210
211 func (field *InputField) GetCursorOffset() int {
212 return field.cursorOffset
213 }
214
215 func (field *InputField) SetCursorOffset(offset int) *InputField {
216 if offset < 0 {
217 offset = 0
218 } else {
219 width := runewidth.StringWidth(field.text)
220 if offset >= width {
221 offset = width
222 }
223 }
224 field.cursorOffset = offset
225 return field
226 }
227
228 // setCursor sets the cursor position.
229 func (field *InputField) setCursor(screen Screen) {
230 width, _ := screen.Size()
231 x := field.cursorOffset - field.viewOffset
232 if x >= width {
233 x = width - 1
234 } else if x < 0 {
235 x = 0
236 }
237 screen.ShowCursor(x, 0)
238 }
239
240 var (
241 lastWord = regexp.MustCompile(`\S+\s*$`)
242 firstWord = regexp.MustCompile(`^\s*\S+`)
243 )
244
245 func SubstringBefore(s string, w int) string {
246 return runewidth.Truncate(s, w, "")
247 }
248
249 func (field *InputField) TypeRune(ch rune) {
250 leftPart := SubstringBefore(field.text, field.cursorOffset)
251 field.text = leftPart + string(ch) + field.text[len(leftPart):]
252 field.cursorOffset += runewidth.RuneWidth(ch)
253 }
254
255 func (field *InputField) MoveCursorLeft(moveWord bool) {
256 before := SubstringBefore(field.text, field.cursorOffset)
257 if moveWord {
258 found := lastWord.FindString(before)
259 field.cursorOffset -= runewidth.StringWidth(found)
260 } else if len(before) > 0 {
261 beforeRunes := []rune(before)
262 char := beforeRunes[len(beforeRunes)-1]
263 field.cursorOffset -= runewidth.RuneWidth(char)
264 }
265 }
266
267 func (field *InputField) MoveCursorRight(moveWord bool) {
268 before := SubstringBefore(field.text, field.cursorOffset)
269 after := field.text[len(before):]
270 if moveWord {
271 found := firstWord.FindString(after)
272 field.cursorOffset += runewidth.StringWidth(found)
273 } else if len(after) > 0 {
274 char := []rune(after)[0]
275 field.cursorOffset += runewidth.RuneWidth(char)
276 }
277 }
278
279 func (field *InputField) RemoveNextCharacter() {
280 if field.cursorOffset >= runewidth.StringWidth(field.text) {
281 return
282 }
283 leftPart := SubstringBefore(field.text, field.cursorOffset)
284 // Take everything after the left part minus the first character.
285 rightPart := string([]rune(field.text[len(leftPart):])[1:])
286
287 field.text = leftPart + rightPart
288 }
289
290 func (field *InputField) Clear() {
291 field.text = ""
292 field.cursorOffset = 0
293 field.viewOffset = 0
294 }
295
296 func (field *InputField) RemovePreviousWord() {
297 leftPart := SubstringBefore(field.text, field.cursorOffset)
298 rightPart := field.text[len(leftPart):]
299 replacement := lastWord.ReplaceAllString(leftPart, "")
300 field.text = replacement + rightPart
301
302 field.cursorOffset -= runewidth.StringWidth(leftPart) - runewidth.StringWidth(replacement)
303 }
304
305 func (field *InputField) RemovePreviousCharacter() {
306 if field.cursorOffset == 0 {
307 return
308 }
309 leftPart := SubstringBefore(field.text, field.cursorOffset)
310 rightPart := field.text[len(leftPart):]
311
312 // Take everything before the right part minus the last character.
313 leftPartRunes := []rune(leftPart)
314 leftPartRunes = leftPartRunes[0 : len(leftPartRunes)-1]
315 leftPart = string(leftPartRunes)
316
317 // Figure out what character was removed to correctly decrease cursorOffset.
318 removedChar := field.text[len(leftPart) : len(field.text)-len(rightPart)]
319
320 field.text = leftPart + rightPart
321
322 field.cursorOffset -= runewidth.StringWidth(removedChar)
323 }
324
325 func (field *InputField) handleInputChanges(originalText string) {
326 // Trigger changed events.
327 if field.text != originalText && field.changed != nil {
328 field.changed(field.text)
329 }
330
331 // Make sure cursor offset is valid
332 if field.cursorOffset < 0 {
333 field.cursorOffset = 0
334 }
335 width := runewidth.StringWidth(field.text)
336 if field.cursorOffset > width {
337 field.cursorOffset = width
338 }
339 }
340
341 func (field *InputField) OnPasteEvent(event PasteEvent) bool {
342 defer field.handleInputChanges(field.text)
343 leftPart := SubstringBefore(field.text, field.cursorOffset)
344 field.text = leftPart + event.Text() + field.text[len(leftPart):]
345 field.cursorOffset += runewidth.StringWidth(event.Text())
346 return true
347 }
348
349 func (field *InputField) Submit(event KeyEvent) bool {
350 return true
351 }
352
353 // Global options to specify which of the two backspace key codes should remove the whole previous word.
354 // If false, only the previous character will be removed with that key code.
355 var (
356 Backspace1RemovesWord = true
357 Backspace2RemovesWord = false
358 )
359
360 func (field *InputField) OnKeyEvent(event KeyEvent) bool {
361 defer field.handleInputChanges(field.text)
362
363 // Process key event.
364 switch key := event.Key(); key {
365 case tcell.KeyRune:
366 field.TypeRune(event.Rune())
367 case tcell.KeyLeft:
368 field.MoveCursorLeft(event.Modifiers() == tcell.ModCtrl)
369 case tcell.KeyRight:
370 field.MoveCursorRight(event.Modifiers() == tcell.ModCtrl)
371 case tcell.KeyDelete:
372 field.RemoveNextCharacter()
373 case tcell.KeyCtrlU:
374 if field.vimBindings {
375 field.Clear()
376 }
377 case tcell.KeyCtrlW:
378 if field.vimBindings {
379 field.RemovePreviousWord()
380 }
381 case tcell.KeyBackspace:
382 if Backspace1RemovesWord {
383 field.RemovePreviousWord()
384 } else {
385 field.RemovePreviousCharacter()
386 }
387 case tcell.KeyBackspace2:
388 if Backspace2RemovesWord {
389 field.RemovePreviousWord()
390 } else {
391 field.RemovePreviousCharacter()
392 }
393 case tcell.KeyTab:
394 if field.tabComplete != nil {
395 field.tabComplete(field.text, field.cursorOffset)
396 return true
397 }
398 return false
399 default:
400 return false
401 }
402 return true
403 }
404
405 func (field *InputField) Focus() {
406 field.focused = true
407 }
408
409 func (field *InputField) Blur() {
410 field.focused = false
411 }
412
413 func (field *InputField) OnMouseEvent(event MouseEvent) bool {
414 if event.Buttons() == tcell.Button1 {
415 x, _ := event.Position()
416 field.SetCursorOffset(field.viewOffset + x)
417 return true
418 }
419 return false
420 }