gitstack

grindlemire/go-tui code browser

10.0 KB Go 426 lines 2026-06-03 · d15bb9f raw
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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
package tui

import (
	"time"
	"unicode/utf8"
)

// Input is a single-line text input with cursor management.
// It implements Component, KeyListener, WatcherProvider, and Focusable interfaces.
type Input struct {
	// Configuration (set via options, immutable after construction)
	width            int
	border           BorderStyle
	textStyle        Style
	placeholder      string
	placeholderStyle Style
	cursorRune       rune
	focusColor       *Color
	borderGradient   *Gradient
	focusGradient    *Gradient
	autoFocus        bool
	onSubmit         func(string)
	onChange         func(string)

	// Reactive state
	text      *State[string]
	cursorPos *State[int]
	scrollPos *State[int] // horizontal scroll offset (first visible rune index)
	blink     *State[bool]
	focused   *State[bool]
}

// Interface assertions
var (
	_ Component       = (*Input)(nil)
	_ KeyListener     = (*Input)(nil)
	_ WatcherProvider = (*Input)(nil)
	_ Focusable       = (*Input)(nil)
	_ AppBinder       = (*Input)(nil)
)

// BindApp binds this Input's internal States to the given app.
func (inp *Input) BindApp(app *App) {
	inp.text.BindApp(app)
	inp.cursorPos.BindApp(app)
	inp.scrollPos.BindApp(app)
	inp.blink.BindApp(app)
	inp.focused.BindApp(app)
}

// NewInput creates a new single-line text input.
func NewInput(opts ...InputOption) *Input {
	inp := &Input{
		// Defaults
		width:            20,
		border:           BorderNone,
		textStyle:        Style{},
		placeholder:      "",
		placeholderStyle: Style{}.Dim(),
		cursorRune:       '▌',

		// State
		text:      NewState(""),
		cursorPos: NewState(0),
		scrollPos: NewState(0),
		blink:     NewState(true),
		focused:   NewState(false),
	}
	for _, opt := range opts {
		opt(inp)
	}
	return inp
}

// --- State Access ---

// Text returns the current text content.
func (inp *Input) Text() string {
	return inp.text.Get()
}

// SetText sets the text and moves cursor to end.
func (inp *Input) SetText(s string) {
	inp.text.Set(s)
	inp.cursorPos.Set(utf8.RuneCountInString(s))
}

// Clear clears the input.
func (inp *Input) Clear() {
	inp.text.Set("")
	inp.cursorPos.Set(0)
	inp.scrollPos.Set(0)
}

// --- Component Interface ---

// visibleWidth returns the number of characters visible inside the input.
// Accounts for border taking 1 char on each side.
func (inp *Input) visibleWidth() int {
	w := inp.width
	if inp.border != BorderNone {
		// Border chars are drawn inside the element width, reducing text space
		return w - 2
	}
	return w
}

// ensureCursorVisible adjusts scrollPos so the cursor is within the visible window.
func (inp *Input) ensureCursorVisible() {
	pos := inp.clampCursorPos()
	scroll := inp.scrollPos.Get()
	visible := inp.visibleWidth()
	if visible <= 0 {
		return
	}

	// Cursor is left of the visible window
	if pos < scroll {
		inp.scrollPos.Set(pos)
		return
	}

	// Cursor is right of the visible window.
	// Reserve 1 column for the cursor character itself.
	if pos >= scroll+visible {
		inp.scrollPos.Set(pos - visible + 1)
	}
}

// Render returns the element tree for the input.
func (inp *Input) Render(app *App) *Element {
	totalHeight := 1
	if inp.border != BorderNone {
		totalHeight += 2
	}

	opts := []Option{
		WithDirection(Row),
		WithHeight(totalHeight),
		WithFocusable(true),
		WithAutoFocus(inp.autoFocus),
	}
	if inp.width > 0 {
		opts = append(opts, WithWidth(inp.width))
	}
	if inp.border != BorderNone {
		opts = append(opts, WithBorder(inp.border))
		if inp.focused.Get() {
			if inp.focusGradient != nil {
				opts = append(opts, WithBorderGradient(*inp.focusGradient))
			} else if inp.focusColor != nil {
				opts = append(opts, WithBorderStyle(NewStyle().Foreground(*inp.focusColor)))
			}
		} else if inp.borderGradient != nil {
			opts = append(opts, WithBorderGradient(*inp.borderGradient))
		}
	}
	root := New(opts...)

	// Wire Element focus/blur to component focus/blur
	root.SetOnFocus(func(e *Element) {
		inp.Focus()
	})
	root.SetOnBlur(func(e *Element) {
		inp.Blur()
	})

	// Render placeholder or content
	if inp.text.Get() == "" && inp.placeholder != "" && !inp.focused.Get() {
		root.AddChild(New(WithText(inp.placeholder), WithTextStyle(inp.placeholderStyle)))
	} else {
		root.AddChild(New(WithText(inp.displayText()), WithTextStyle(inp.textStyle)))
	}

	return root
}

// --- Focusable Interface ---

// IsFocusable returns true since Input can receive focus.
func (inp *Input) IsFocusable() bool {
	return true
}

// IsTabStop returns true since Input participates in Tab navigation.
func (inp *Input) IsTabStop() bool {
	return true
}

// Focus is called when the input gains focus. Idempotent.
func (inp *Input) Focus() {
	if inp.focused.Get() {
		return
	}
	inp.focused.Set(true)
	inp.blink.Set(true)
}

// Blur is called when the input loses focus. Idempotent.
func (inp *Input) Blur() {
	if !inp.focused.Get() {
		return
	}
	inp.focused.Set(false)
}

// IsFocused returns whether this input is currently focused.
func (inp *Input) IsFocused() bool {
	return inp.focused.Get()
}

// HandleEvent processes keyboard events.
func (inp *Input) HandleEvent(e Event) bool {
	ke, ok := e.(KeyEvent)
	if !ok {
		return false
	}

	for _, binding := range inp.KeyMap() {
		entry := dispatchEntry{pattern: binding.Pattern}
		if entry.matchesKey(ke) {
			binding.Handler(ke)
			return binding.Stop
		}
	}
	return false
}

// --- KeyListener Interface ---

// KeyMap returns the key bindings for the input.
func (inp *Input) KeyMap() KeyMap {
	return KeyMap{
		OnFocused(AnyRune, inp.insertChar),
		OnFocused(KeyBackspace, inp.backspace),
		OnFocused(KeyDelete, inp.delete),
		OnFocused(KeyLeft, inp.moveLeft),
		OnFocused(KeyRight, inp.moveRight),
		OnFocused(KeyHome, inp.moveHome),
		OnFocused(KeyEnd, inp.moveEnd),
		OnFocused(KeyEnter, inp.submit),
		OnFocused(KeyEscape, func(ke KeyEvent) {
			if app := ke.App(); app != nil {
				app.BlurFocused()
			}
		}),
	}
}

// --- WatcherProvider Interface ---

// Watchers returns watchers for cursor blink.
func (inp *Input) Watchers() []Watcher {
	return []Watcher{
		OnTimer(500*time.Millisecond, func() {
			if inp.focused.Get() {
				inp.blink.Set(!inp.blink.Get())
			}
		}),
	}
}

// --- Key Handlers ---

// insertChar inserts a character at the cursor position.
func (inp *Input) insertChar(ke KeyEvent) {
	runes := []rune(inp.text.Get())
	pos := inp.clampCursorPos()
	newRunes := make([]rune, 0, len(runes)+1)
	newRunes = append(newRunes, runes[:pos]...)
	newRunes = append(newRunes, ke.Rune)
	newRunes = append(newRunes, runes[pos:]...)
	inp.text.Set(string(newRunes))
	inp.cursorPos.Set(pos + 1)
	inp.blink.Set(true)
	inp.ensureCursorVisible()
	if inp.onChange != nil {
		inp.onChange(inp.text.Get())
	}
}

// backspace deletes the character before the cursor.
func (inp *Input) backspace(ke KeyEvent) {
	runes := []rune(inp.text.Get())
	pos := inp.clampCursorPos()
	if pos > 0 {
		newRunes := append(runes[:pos-1], runes[pos:]...)
		inp.text.Set(string(newRunes))
		newPos := pos - 1
		inp.cursorPos.Set(newPos)
		// Pin cursor to the right edge while text exceeds visible width,
		// so each delete scrolls one more character into view.
		visible := inp.visibleWidth()
		if len(newRunes) >= visible && newPos >= visible {
			inp.scrollPos.Set(newPos - visible + 1)
		} else {
			inp.scrollPos.Set(0)
		}
		if inp.onChange != nil {
			inp.onChange(inp.text.Get())
		}
	}
}

// delete deletes the character at the cursor.
func (inp *Input) delete(ke KeyEvent) {
	runes := []rune(inp.text.Get())
	pos := inp.clampCursorPos()
	if pos < len(runes) {
		newRunes := append(runes[:pos], runes[pos+1:]...)
		inp.text.Set(string(newRunes))
		visible := inp.visibleWidth()
		if len(newRunes) >= visible && pos >= visible {
			inp.scrollPos.Set(pos - visible + 1)
		} else {
			inp.scrollPos.Set(0)
		}
		if inp.onChange != nil {
			inp.onChange(inp.text.Get())
		}
	}
}

// moveLeft moves cursor left.
func (inp *Input) moveLeft(ke KeyEvent) {
	pos := inp.cursorPos.Get()
	if pos > 0 {
		inp.cursorPos.Set(pos - 1)
		inp.blink.Set(true)
		inp.ensureCursorVisible()
	}
}

// moveRight moves cursor right.
func (inp *Input) moveRight(ke KeyEvent) {
	pos := inp.cursorPos.Get()
	if pos < utf8.RuneCountInString(inp.text.Get()) {
		inp.cursorPos.Set(pos + 1)
		inp.blink.Set(true)
		inp.ensureCursorVisible()
	}
}

// moveHome moves cursor to start.
func (inp *Input) moveHome(ke KeyEvent) {
	inp.cursorPos.Set(0)
	inp.blink.Set(true)
	inp.ensureCursorVisible()
}

// moveEnd moves cursor to end.
func (inp *Input) moveEnd(ke KeyEvent) {
	inp.cursorPos.Set(utf8.RuneCountInString(inp.text.Get()))
	inp.blink.Set(true)
	inp.ensureCursorVisible()
}

// submit calls the onSubmit callback.
func (inp *Input) submit(ke KeyEvent) {
	if inp.onSubmit != nil {
		inp.onSubmit(inp.text.Get())
	}
}

// --- Display ---

// displayText returns a viewport-clamped slice of the text with cursor overlay.
func (inp *Input) displayText() string {
	text := inp.text.Get()
	runes := []rune(text)
	pos := inp.clampCursorPos()
	visible := inp.visibleWidth()

	inp.ensureCursorVisible()
	scroll := min(
		// Clamp scroll to valid range
		max(

			inp.scrollPos.Get(), 0), len(runes))

	if !inp.focused.Get() {
		if len(runes) == 0 {
			return " "
		}
		// Show viewport slice
		end := min(scroll+visible, len(runes))
		return string(runes[scroll:end])
	}

	// Build the visible slice with cursor inserted
	cursor := inp.cursorRune
	if !inp.blink.Get() {
		cursor = ' '
	}

	// Insert cursor into the full rune slice at pos
	withCursor := make([]rune, 0, len(runes)+1)
	withCursor = append(withCursor, runes[:pos]...)
	withCursor = append(withCursor, cursor)
	withCursor = append(withCursor, runes[pos:]...)

	// The cursor insertion shifts indices after pos by 1.
	// Adjust scroll start: characters before cursor are unshifted,
	// characters at/after cursor position are shifted by 1.
	viewStart := scroll
	if scroll > pos {
		viewStart = scroll + 1
	}

	// visible+1 because the cursor character takes a column
	viewEnd := min(viewStart+visible+1, len(withCursor))

	return string(withCursor[viewStart:viewEnd])
}

func (inp *Input) clampCursorPos() int {
	pos := inp.cursorPos.Get()
	if pos < 0 {
		return 0
	}
	max := utf8.RuneCountInString(inp.text.Get())
	if pos > max {
		return max
	}
	return pos
}