Repository navigation
Expand file tree
/
Copy pathtui.go
More file actions
488 lines (415 loc) · 12.9 KB
/
Copy pathtui.go
File metadata and controls
488 lines (415 loc) · 12.9 KB
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
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
package treeview
import (
"context"
"fmt"
"slices"
"strings"
"time"
"charm.land/bubbles/v2/viewport"
tea "charm.land/bubbletea/v2"
)
// TuiTreeModelOption represents a functional Option that configures a TuiTreeModel instance directly.
type TuiTreeModelOption[T any] func(*TuiTreeModel[T])
// WithTuiWidth sets the viewport width.
func WithTuiWidth[T any](w int) TuiTreeModelOption[T] {
return func(m *TuiTreeModel[T]) { m.width = w }
}
// WithTuiHeight sets the viewport height.
func WithTuiHeight[T any](h int) TuiTreeModelOption[T] {
return func(m *TuiTreeModel[T]) { m.height = h }
}
// WithTuiAllowResize sets whether the viewport can be resized. Defaults to true.
func WithTuiAllowResize[T any](allowResize bool) TuiTreeModelOption[T] {
return func(m *TuiTreeModel[T]) { m.allowResize = allowResize }
}
// WithTuiNavigationTimeout sets the timeout for navigation operations.
func WithTuiNavigationTimeout[T any](d time.Duration) TuiTreeModelOption[T] {
return func(m *TuiTreeModel[T]) { m.navigationTimeout = d }
}
// WithTuiSearchTimeout sets the timeout for search operations.
func WithTuiSearchTimeout[T any](d time.Duration) TuiTreeModelOption[T] {
return func(m *TuiTreeModel[T]) { m.searchTimeout = d }
}
// WithTuiKeyMap allows callers to override the key bindings used by the model.
func WithTuiKeyMap[T any](k KeyMap) TuiTreeModelOption[T] {
return func(m *TuiTreeModel[T]) { m.keyMap = k }
}
// WithTuiDisableNavBar disables the built-in navigation bar at the bottom of the view.
func WithTuiDisableNavBar[T any](disable bool) TuiTreeModelOption[T] {
return func(m *TuiTreeModel[T]) { m.disableNavBar = disable }
}
// WithTuiAltScreen renders the TUI in the terminal's alternate screen buffer,
// restoring the previous terminal contents when the program exits.
func WithTuiAltScreen[T any](enable bool) TuiTreeModelOption[T] {
return func(m *TuiTreeModel[T]) { m.altScreen = enable }
}
// KeyMap groups key bindings for the interactive TUI. Provide your own via
// WithTuiKeyMap if you need to accommodate non-US layouts or match existing shortcuts.
type KeyMap struct {
// Navigation keys
Quit []string
Up []string
Down []string
Expand []string
Collapse []string
Toggle []string
Reset []string
// Multi-focus keys
ExtendUp []string
ExtendDown []string
// Search keys
SearchStart []string
SearchAccept []string
SearchCancel []string
SearchDelete []string
}
// DefaultKeyMap returns a map of basic key bindings.
func DefaultKeyMap() KeyMap {
return KeyMap{
// Navigation
Quit: []string{"esc"},
Up: []string{"up"},
Down: []string{"down"},
Toggle: []string{"right", "left"},
Reset: []string{"ctrl+r"},
// Multi-focus
ExtendUp: []string{"shift+up"},
ExtendDown: []string{"shift+down"},
// Search
SearchStart: []string{"enter"},
SearchAccept: []string{"enter"},
SearchCancel: []string{"esc"},
SearchDelete: []string{"backspace", "delete"},
}
}
// TuiTreeModel wraps a Tree and exposes it through a Bubble Tea model. It
// handles keyboard navigation, search, and viewport resizing.
//
// Concurrency: All mutating operations are executed within the Tea event loop
// which is single-threaded, so internal state does not need extra locking.
type TuiTreeModel[T any] struct {
*Tree[T]
keyMap KeyMap
width int
height int
allowResize bool
viewport *viewport.Model
searchTerm string
showSearch bool
navigationTimeout time.Duration
searchTimeout time.Duration
disableNavBar bool
altScreen bool
}
// NewTuiTreeModel creates an interactive Bubble Tea TUI model using functional options.
// The zero-value configuration applies sensible defaults:
// - 100ms navigation timeout
// - 300ms search timeout
// - DefaultKeyMap for key bindings
// - DefaultNodeProvider if none specified
//
// Example:
//
// tree := treeview.NewTree(nodes, treeview.WithSearcher(customSearcher))
// model := treeview.NewTuiTreeModel(
// tree,
// treeview.WithTuiWidth(80),
// treeview.WithTuiHeight(25),
// )
func NewTuiTreeModel[T any](tree *Tree[T], opts ...TuiTreeModelOption[T]) *TuiTreeModel[T] {
// Initialize the TUI model with default components
vp := viewport.New(viewport.WithWidth(80), viewport.WithHeight(24))
m := &TuiTreeModel[T]{
Tree: tree,
keyMap: DefaultKeyMap(),
width: 80,
height: 24,
allowResize: true,
viewport: &vp,
searchTerm: "",
showSearch: false,
searchTimeout: 300 * time.Millisecond,
navigationTimeout: 100 * time.Millisecond,
disableNavBar: false,
}
// Apply any provided options
for _, opt := range opts {
if opt != nil {
opt(m)
}
}
// Initialize viewport dimensions
m.updateViewportDimensions()
return m
}
func (m *TuiTreeModel[T]) execWithNavigationTimeout(fn func(context.Context) error) {
ctx, cancel := context.WithTimeout(context.Background(), m.navigationTimeout)
defer cancel()
_ = fn(ctx)
}
// Init initializes the TUI model. Required by the Bubble Tea model interface.
func (m *TuiTreeModel[T]) Init() tea.Cmd {
return nil
}
// Update processes Bubble Tea messages and returns updated model and commands.
func (m *TuiTreeModel[T]) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
// Handle different message types from Bubble Tea
switch msg := msg.(type) {
case tea.KeyMsg:
// Process keyboard input
return m.handleKeypress(msg)
case tea.WindowSizeMsg:
// If resize is not allowed, do nothing
if !m.allowResize {
return m, nil
}
// Terminal was resized, update our dimensions
m.width = msg.Width
m.height = msg.Height
// Recalculate viewport to fit new window
m.updateViewportDimensions()
// No command to return
return m, nil
default:
// Ignore other message types
return m, nil
}
}
func (m *TuiTreeModel[T]) handleKeypress(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
key := msg.String()
// In search mode: prioritize search keys
if m.showSearch {
switch {
case slices.Contains(m.keyMap.SearchAccept, key):
m.showSearch = false
m.updateViewportDimensions()
return m, nil
case slices.Contains(m.keyMap.SearchCancel, key):
m.EndSearch()
return m, nil
case slices.Contains(m.keyMap.SearchDelete, key):
if len(m.searchTerm) > 0 {
m.searchTerm = m.searchTerm[:len(m.searchTerm)-1]
_, _ = m.Search(m.searchTerm)
}
return m, nil
case slices.Contains(m.keyMap.Reset, key):
m.EndSearch()
return m, nil
}
// Add printable characters to search. Prefer msg.Text so keys whose
// String() returns a name (e.g. "space") still contribute the literal
// character typed by the user.
if text := msg.Key().Text; len(text) == 1 && text >= " " && text <= "~" {
m.searchTerm += text
_, _ = m.Search(m.searchTerm)
return m, nil
}
if len(key) == 1 && key >= " " && key <= "~" {
m.searchTerm += key
_, _ = m.Search(m.searchTerm)
return m, nil
}
}
// Normal mode: navigation logic
switch {
case slices.Contains(m.keyMap.Quit, key):
return m, tea.Quit
case slices.Contains(m.keyMap.Up, key):
m.NavigateUp()
return m, nil
case slices.Contains(m.keyMap.Down, key):
m.NavigateDown()
return m, nil
case slices.Contains(m.keyMap.ExtendUp, key):
m.ExtendFocusUp()
return m, nil
case slices.Contains(m.keyMap.ExtendDown, key):
m.ExtendFocusDown()
return m, nil
case slices.Contains(m.keyMap.Expand, key):
m.Expand()
return m, nil
case slices.Contains(m.keyMap.Collapse, key):
m.Collapse()
return m, nil
case slices.Contains(m.keyMap.Toggle, key):
m.Toggle()
return m, nil
case slices.Contains(m.keyMap.SearchStart, key):
m.BeginSearch()
return m, nil
case slices.Contains(m.keyMap.Reset, key):
_ = m.ShowAll(context.Background())
return m, nil
}
return m, nil
}
// NavigateUp moves the focus one visible node up.
func (m *TuiTreeModel[T]) NavigateUp() {
m.execWithNavigationTimeout(func(ctx context.Context) error {
_, err := m.Move(ctx, -1)
return err
})
}
// NavigateDown moves the focus one visible node down.
func (m *TuiTreeModel[T]) NavigateDown() {
m.execWithNavigationTimeout(func(ctx context.Context) error {
_, err := m.Move(ctx, 1)
return err
})
}
// ExtendFocusUp extends the multi-focus selection upward by one node.
func (m *TuiTreeModel[T]) ExtendFocusUp() {
m.execWithNavigationTimeout(func(ctx context.Context) error {
_, err := m.MoveExtend(ctx, -1)
return err
})
}
// ExtendFocusDown extends the multi-focus selection downward by one node.
func (m *TuiTreeModel[T]) ExtendFocusDown() {
m.execWithNavigationTimeout(func(ctx context.Context) error {
_, err := m.MoveExtend(ctx, 1)
return err
})
}
// Toggle expands or collapses all currently focused nodes.
func (m *TuiTreeModel[T]) Toggle() {
m.execWithNavigationTimeout(func(ctx context.Context) error {
for info, err := range m.AllFocused(ctx) {
if err != nil {
return err
}
info.Node.Toggle()
}
return nil
})
}
// Expand expands all currently focused nodes to show their children.
func (m *TuiTreeModel[T]) Expand() {
m.execWithNavigationTimeout(func(ctx context.Context) error {
for info, err := range m.AllFocused(ctx) {
if err != nil {
return err
}
info.Node.Expand()
}
return nil
})
}
// Collapse collapses all currently focused nodes to hide their children.
func (m *TuiTreeModel[T]) Collapse() {
m.execWithNavigationTimeout(func(ctx context.Context) error {
for info, err := range m.AllFocused(ctx) {
if err != nil {
return err
}
info.Node.Collapse()
}
return nil
})
}
// BeginSearch switches the model into search mode and clears previous term.
func (m *TuiTreeModel[T]) BeginSearch() {
m.showSearch = true
m.searchTerm = ""
m.updateViewportDimensions()
}
// EndSearch exits search mode and clears highlights.
func (m *TuiTreeModel[T]) EndSearch() {
m.showSearch = false
m.searchTerm = ""
m.updateViewportDimensions()
m.execWithNavigationTimeout(func(ctx context.Context) error {
return m.ShowAll(ctx)
})
}
// Search updates the term live as the user types and expands the tree so that
// matches are visible. It returns the result slice so external code can, for
// instance, display the hit count.
func (m *TuiTreeModel[T]) Search(term string) ([]*Node[T], error) {
// Update the current search term
m.searchTerm = term
ctx, cancel := context.WithTimeout(context.Background(), m.searchTimeout)
defer cancel()
matches, err := m.SearchAndExpand(ctx, term)
return matches, err
}
// View renders the tree plus an optional search bar and navigation legend.
func (m *TuiTreeModel[T]) View() tea.View {
view := tea.NewView("")
view.AltScreen = m.altScreen
// Render the tree
result, err := renderTreeWithViewport(context.Background(), m.Tree, m.viewport)
if err != nil {
view.SetContent("Error rendering tree: " + err.Error())
return view
}
// Add search UI at the top if in search mode
if m.showSearch {
searchUI := "Search: " + m.searchTerm
result = searchUI + "\n\n" + result
}
// Add navigation bar if not disabled
if !m.disableNavBar {
result += "\n───────────────────────────────────────────────────────────────\n"
result += m.NavBar()
}
view.SetContent(result)
return view
}
// NavBar returns the navigation bar string that shows available keyboard commands.
// This method is exposed so users can create custom navigation bars or extend the default one.
func (m *TuiTreeModel[T]) NavBar() string {
// Collect navigation items based on current mode
var navItems []string
// Show tree navigation
for _, item := range []string{
m.addNavItem(m.keyMap.Up, "Up"),
m.addNavItem(m.keyMap.Down, "Down"),
m.addNavItem(m.keyMap.ExtendUp, "ExtendUp"),
m.addNavItem(m.keyMap.ExtendDown, "ExtendDown"),
m.addNavItem(m.keyMap.Expand, "Expand"),
m.addNavItem(m.keyMap.Collapse, "Collapse"),
m.addNavItem(m.keyMap.Toggle, "Toggle"),
} {
if item != "" {
navItems = append(navItems, item)
}
}
if m.showSearch {
// In search mode: show search-specific actions
navItems = append(navItems, m.addNavItem(m.keyMap.SearchAccept, "Accept"))
navItems = append(navItems, m.addNavItem(m.keyMap.SearchCancel, "Cancel"))
} else {
// In normal mode, add Search Option
navItems = append(navItems, m.addNavItem(m.keyMap.SearchStart, "Search"))
// Add quit Option
navItems = append(navItems, m.addNavItem(m.keyMap.Quit, "Quit"))
}
// Add reset Option
navItems = append(navItems, m.addNavItem(m.keyMap.Reset, "Reset"))
// Join all navigation items with consistent spacing
return strings.Join(navItems, " ")
}
func (m *TuiTreeModel[T]) addNavItem(keys []string, label string) string {
if len(keys) > 0 {
return fmt.Sprintf("%s: %s", strings.Join(keys, "/"), label)
}
return ""
}
func (m *TuiTreeModel[T]) updateViewportDimensions() {
viewHeight := m.height
if !m.disableNavBar {
viewHeight -= 3
}
if m.showSearch {
viewHeight -= 2
}
m.viewport.SetWidth(m.width)
m.viewport.SetHeight(viewHeight)
// Update tree truncation width to match viewport width
m.mu.Lock()
m.truncateWidth = m.width
m.mu.Unlock()
}