gitstack

grindlemire/go-tui code browser

9.9 KB Go 427 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
427
package tui

import "testing"

// --- Integration test components ---

var (
	_ AppBinder = (*intRoot)(nil)
	_ AppBinder = (*intSidebar)(nil)
	_ AppBinder = (*intSearch)(nil)
)

// intRoot is a root component that mounts two children.
// Its KeyMap changes based on the searchActive state.
type intRoot struct {
	searchActive *State[bool]
	query        *State[string]
}

func newIntRoot() *intRoot {
	return &intRoot{
		searchActive: NewState(false),
		query:        NewState(""),
	}
}

func (r *intRoot) KeyMap() KeyMap {
	km := KeyMap{
		On(Rune('c').Ctrl(), func(ke KeyEvent) {}),
	}
	if !r.searchActive.Get() {
		km = append(km, On(Rune('/'), func(ke KeyEvent) {
			r.searchActive.Set(true)
		}))
	}
	return km
}

func (r *intRoot) Render(app *App) *Element {
	root := New(WithDisplay(DisplayFlex), WithDirection(Row))

	// Mount sidebar at index 0
	el0 := app.Mount(r, 0, func() Component {
		return newIntSidebar(r.query)
	})
	root.AddChild(el0)

	// Conditionally mount search at index 1
	el1 := app.Mount(r, 1, func() Component {
		return newIntSearch(r.searchActive, r.query)
	})
	root.AddChild(el1)

	return root
}

func (r *intRoot) BindApp(app *App) {
	r.searchActive.BindApp(app)
	r.query.BindApp(app)
}

// intSidebar is a child component with a Ctrl+B binding.
type intSidebar struct {
	query    *State[string]
	expanded *State[bool]
}

func newIntSidebar(query *State[string]) *intSidebar {
	return &intSidebar{
		query:    query,
		expanded: NewState(true),
	}
}

func (s *intSidebar) KeyMap() KeyMap {
	return KeyMap{
		On(Rune('b').Ctrl(), func(ke KeyEvent) {
			s.expanded.Set(!s.expanded.Get())
		}),
	}
}

func (s *intSidebar) Render(app *App) *Element {
	return New(WithText("sidebar"))
}

func (s *intSidebar) BindApp(app *App) {
	s.query.BindApp(app)
	s.expanded.BindApp(app)
}

// intSearch is a child component with conditional stop-propagation bindings.
type intSearch struct {
	active *State[bool]
	query  *State[string]
}

func newIntSearch(active *State[bool], query *State[string]) *intSearch {
	return &intSearch{active: active, query: query}
}

func (s *intSearch) KeyMap() KeyMap {
	if !s.active.Get() {
		return nil
	}
	return KeyMap{
		OnStop(AnyRune, func(ke KeyEvent) {
			s.query.Set(s.query.Get() + string(ke.Rune))
		}),
		OnStop(KeyEscape, func(ke KeyEvent) {
			s.active.Set(false)
			s.query.Set("")
		}),
	}
}

func (s *intSearch) Render(app *App) *Element {
	return New(WithText("search"))
}

func (s *intSearch) BindApp(app *App) {
	s.active.BindApp(app)
	s.query.BindApp(app)
}

// intInitComponent tracks Init/cleanup lifecycle.
type intInitComponent struct {
	initCalled   bool
	cleanupCalls int
}

func (c *intInitComponent) Render(app *App) *Element { return New() }
func (c *intInitComponent) Init() func() {
	c.initCalled = true
	return func() { c.cleanupCalls++ }
}

// --- Integration tests ---

func TestIntegration_MountCachesAndDiscoverKeyMaps(t *testing.T) {
	cleanup := setupTestMountState()
	defer cleanup()

	root := newIntRoot()
	el := root.Render(testApp)

	// Verify mount cached two child instances
	ms := testApp.mounts
	if len(ms.cache) != 2 {
		t.Fatalf("mount cache has %d entries, want 2", len(ms.cache))
	}

	// Build dispatch table from the rendered tree
	table, err := buildDispatchTable(root, el)
	if err != nil {
		t.Fatalf("buildDispatchTable: %v", err)
	}

	// Root has: ctrl+c, '/' (since searchActive=false)
	// Sidebar has: ctrl+b
	// Search has: nil (since active=false)
	// Total: 3 entries
	if len(table.entries) != 3 {
		t.Fatalf("dispatch table has %d entries, want 3", len(table.entries))
	}
}

func TestIntegration_DispatchBroadcastAndStopPropagation(t *testing.T) {
	cleanup := setupTestMountState()
	defer cleanup()

	root := newIntRoot()
	el := root.Render(testApp)

	table, err := buildDispatchTable(root, el)
	if err != nil {
		t.Fatalf("buildDispatchTable: %v", err)
	}

	// Press '/': root handler fires, searchActive becomes true
	table.dispatch(KeyEvent{Key: KeyRune, Rune: '/'})
	if !root.searchActive.Get() {
		t.Error("expected searchActive=true after '/' dispatch")
	}
}

func TestIntegration_ConditionalKeyMapActivation(t *testing.T) {
	cleanup := setupTestMountState()
	defer cleanup()
	testApp.resetDirty()

	root := newIntRoot()

	// Initial render: search is inactive
	el := root.Render(testApp)

	table, err := buildDispatchTable(root, el)
	if err != nil {
		t.Fatalf("buildDispatchTable (initial): %v", err)
	}

	// Press '/' to activate search
	table.dispatch(KeyEvent{Key: KeyRune, Rune: '/'})
	if !root.searchActive.Get() {
		t.Fatal("expected searchActive=true")
	}

	// Re-render (simulating dirty frame)
	el = root.Render(testApp)

	// Rebuild dispatch table with new KeyMaps
	table, err = buildDispatchTable(root, el)
	if err != nil {
		t.Fatalf("buildDispatchTable (after activation): %v", err)
	}

	// Now search should have stop-propagation bindings:
	// Root: ctrl+c (no '/' since searchActive=true)
	// Sidebar: ctrl+b
	// Search: AnyRune(stop), Escape(stop)
	// Total: 4 entries
	if len(table.entries) != 4 {
		t.Fatalf("dispatch table has %d entries after activation, want 4", len(table.entries))
	}

	// Type a character — should go to search exclusively (stop propagation)
	table.dispatch(KeyEvent{Key: KeyRune, Rune: 'h'})
	if root.query.Get() != "h" {
		t.Errorf("query = %q, want %q", root.query.Get(), "h")
	}

	// Type more
	table.dispatch(KeyEvent{Key: KeyRune, Rune: 'i'})
	if root.query.Get() != "hi" {
		t.Errorf("query = %q, want %q", root.query.Get(), "hi")
	}
}

func TestIntegration_EscapeDeactivatesSearch(t *testing.T) {
	cleanup := setupTestMountState()
	defer cleanup()
	testApp.resetDirty()

	root := newIntRoot()
	root.BindApp(testApp)

	// Activate search
	root.searchActive.Set(true)
	root.query.Set("test")

	el := root.Render(testApp)

	table, err := buildDispatchTable(root, el)
	if err != nil {
		t.Fatalf("buildDispatchTable: %v", err)
	}

	// Press Escape — search deactivates
	table.dispatch(KeyEvent{Key: KeyEscape})

	if root.searchActive.Get() {
		t.Error("expected searchActive=false after Escape")
	}
	if root.query.Get() != "" {
		t.Errorf("expected query=%q after Escape, got %q", "", root.query.Get())
	}

	// Re-render: search should return nil KeyMap
	el = root.Render(testApp)

	table, err = buildDispatchTable(root, el)
	if err != nil {
		t.Fatalf("buildDispatchTable (after deactivation): %v", err)
	}

	// Root: ctrl+c, '/' (back since searchActive=false)
	// Sidebar: ctrl+b
	// Search: nil
	// Total: 3
	if len(table.entries) != 3 {
		t.Fatalf("dispatch table has %d entries after deactivation, want 3", len(table.entries))
	}
}

func TestIntegration_SweepCleansUnmountedComponents(t *testing.T) {
	cleanup := setupTestMountState()
	defer cleanup()

	parent := &mockParent{}
	initComp := &intInitComponent{}

	// Mount the component
	testApp.Mount(parent, 0, func() Component { return initComp })

	if !initComp.initCalled {
		t.Fatal("Init should have been called on first mount")
	}

	ms := testApp.mounts

	// Simulate a render where the component is not active (e.g., removed by if)
	ms.activeKeys = make(map[mountKey]bool)
	ms.sweep()

	if initComp.cleanupCalls != 1 {
		t.Errorf("cleanup called %d times, want 1", initComp.cleanupCalls)
	}
	if len(ms.cache) != 0 {
		t.Errorf("cache has %d entries after sweep, want 0", len(ms.cache))
	}
}

func TestIntegration_SharedStatePropagation(t *testing.T) {
	cleanup := setupTestMountState()
	defer cleanup()
	testApp.resetDirty()

	root := newIntRoot()

	// Initial render
	root.Render(testApp)

	// The query state is shared between root, sidebar, and search.
	// Setting it from search should be visible to sidebar.
	root.query.Set("hello")

	if root.query.Get() != "hello" {
		t.Errorf("query = %q, want %q", root.query.Get(), "hello")
	}

	// Re-render and verify the shared state is accessible
	el := root.Render(testApp)

	// walkComponents should find all 3 components
	var found []Component
	walkComponents(root, el, func(c Component) {
		found = append(found, c)
	})

	// root + sidebar + search = 3
	if len(found) != 3 {
		t.Fatalf("walkComponents found %d components, want 3", len(found))
	}
}

func TestIntegration_DispatchTableRebuiltOnStateChange(t *testing.T) {
	cleanup := setupTestMountState()
	defer cleanup()
	testApp.resetDirty()

	root := newIntRoot()

	// Phase 1: searchActive=false
	el := root.Render(testApp)

	table1, err := buildDispatchTable(root, el)
	if err != nil {
		t.Fatalf("buildDispatchTable phase 1: %v", err)
	}
	count1 := len(table1.entries)

	// Phase 2: activate search
	root.searchActive.Set(true)
	el = root.Render(testApp)

	table2, err := buildDispatchTable(root, el)
	if err != nil {
		t.Fatalf("buildDispatchTable phase 2: %v", err)
	}
	count2 := len(table2.entries)

	// Phase 1: 3 entries (ctrl+c, '/', ctrl+b)
	// Phase 2: 4 entries (ctrl+c, ctrl+b, AnyRune(stop), Escape(stop))
	if count1 != 3 {
		t.Errorf("phase 1 entry count = %d, want 3", count1)
	}
	if count2 != 4 {
		t.Errorf("phase 2 entry count = %d, want 4", count2)
	}

	// Phase 2 should have different entries than phase 1
	if count1 == count2 {
		t.Error("dispatch table should change after state change and re-render")
	}
}

func TestIntegration_CtrlBTogglesSidebar(t *testing.T) {
	cleanup := setupTestMountState()
	defer cleanup()

	root := newIntRoot()
	el := root.Render(testApp)

	table, err := buildDispatchTable(root, el)
	if err != nil {
		t.Fatalf("buildDispatchTable: %v", err)
	}

	// Find the sidebar component in the cache
	var sidebar *intSidebar
	walkComponents(root, el, func(c Component) {
		if s, ok := c.(*intSidebar); ok {
			sidebar = s
		}
	})
	if sidebar == nil {
		t.Fatal("sidebar component not found in tree")
	}

	if !sidebar.expanded.Get() {
		t.Error("sidebar should start expanded")
	}

	// Press Ctrl+B to toggle sidebar
	table.dispatch(KeyEvent{Key: KeyRune, Rune: 'b', Mod: ModCtrl})

	if sidebar.expanded.Get() {
		t.Error("sidebar should be collapsed after Ctrl+B")
	}

	// Press again to toggle back
	table.dispatch(KeyEvent{Key: KeyRune, Rune: 'b', Mod: ModCtrl})

	if !sidebar.expanded.Get() {
		t.Error("sidebar should be expanded after second Ctrl+B")
	}
}