gitstack

grindlemire/go-tui code browser

13.8 KB Go 597 lines 2026-04-03 ยท 2dcff81 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
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
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
package tui

import "testing"

func TestModal_NewModal_Defaults(t *testing.T) {
	m := NewModal()

	if m.backdrop != "dim" {
		t.Errorf("expected default backdrop 'dim', got %q", m.backdrop)
	}
	if !m.closeOnEscape {
		t.Error("expected closeOnEscape default true")
	}
	if !m.closeOnBackdrop {
		t.Error("expected closeOnBackdrop default true")
	}
	if !m.trapFocus {
		t.Error("expected trapFocus default true")
	}
}

func TestModal_Render_Closed(t *testing.T) {
	open := NewState(false)
	m := NewModal(WithModalOpen(open))
	m.BindApp(testApp)

	el := m.Render(testApp)
	if !el.IsOverlay() {
		t.Error("expected overlay flag on element")
	}
	if !el.hidden {
		t.Error("expected hidden element when modal is closed")
	}
}

func TestModal_Render_Open(t *testing.T) {
	open := NewState(true)
	m := NewModal(WithModalOpen(open))
	m.BindApp(testApp)

	el := m.Render(testApp)
	if !el.IsOverlay() {
		t.Error("expected overlay flag on element")
	}
	if el.hidden {
		t.Error("expected visible element when modal is open")
	}
	if len(testApp.overlays) == 0 {
		t.Error("expected overlay to be registered")
	}
	// Clean up
	testApp.clearOverlays()
}

func TestModal_KeyMap_Escape(t *testing.T) {
	open := NewState(true)
	m := NewModal(WithModalOpen(open))

	km := m.KeyMap()
	if len(km) == 0 {
		t.Fatal("expected non-empty KeyMap when open")
	}
	// Find and invoke the Escape binding
	fired := false
	for _, b := range km {
		if b.Pattern.Key == KeyEscape {
			b.Handler(KeyEvent{Key: KeyEscape})
			fired = true
			break
		}
	}
	if !fired {
		t.Fatal("no Escape binding found in KeyMap")
	}
	if open.Get() {
		t.Error("expected open to be false after Escape")
	}
}

func TestModal_KeyMap_Closed(t *testing.T) {
	open := NewState(false)
	m := NewModal(WithModalOpen(open))

	km := m.KeyMap()
	if km != nil {
		t.Error("expected nil KeyMap when closed")
	}
}

func TestModal_KeyMap_EscapeDisabled(t *testing.T) {
	open := NewState(true)
	m := NewModal(WithModalOpen(open), WithModalCloseOnEscape(false))

	km := m.KeyMap()
	// Should still have Tab bindings (from trapFocus) but no Escape
	for _, b := range km {
		if b.Pattern.Key == KeyEscape {
			t.Error("expected no Escape binding when closeOnEscape is false")
		}
	}
}

func TestModal_KeyMap_TabFocusCycling(t *testing.T) {
	open := NewState(true)
	m := NewModal(WithModalOpen(open))
	m.BindApp(testApp)

	km := m.KeyMap()
	hasTab := false
	hasShiftTab := false
	for _, b := range km {
		if b.Pattern.Key == KeyTab && b.Pattern.Mod == 0 {
			hasTab = true
		}
		if b.Pattern.Key == KeyTab && b.Pattern.Mod == ModShift {
			hasShiftTab = true
		}
	}
	if !hasTab {
		t.Error("expected Tab binding when trapFocus is true")
	}
	if !hasShiftTab {
		t.Error("expected Shift+Tab binding when trapFocus is true")
	}
}

func TestModal_KeyMap_NoTabWhenTrapFocusDisabled(t *testing.T) {
	open := NewState(true)
	m := NewModal(WithModalOpen(open), WithModalTrapFocus(false))
	m.BindApp(testApp)

	km := m.KeyMap()
	for _, b := range km {
		if b.Pattern.Key == KeyTab {
			t.Error("expected no Tab binding when trapFocus is false")
		}
	}
}

func TestModal_KeyMap_OnlyExpectedBindings(t *testing.T) {
	type tc struct {
		trapFocus    bool
		escapeClose  bool
		wantKeys     map[Key]bool // expected specific key bindings
		wantCatchAll bool         // expect AnyKey catch-all
	}

	tests := map[string]tc{
		"trapFocus true, escape true": {
			trapFocus:    true,
			escapeClose:  true,
			wantKeys:     map[Key]bool{KeyEscape: true, KeyTab: true, KeyEnter: true},
			wantCatchAll: true,
		},
		"trapFocus true, escape false": {
			trapFocus:    true,
			escapeClose:  false,
			wantKeys:     map[Key]bool{KeyTab: true, KeyEnter: true},
			wantCatchAll: true,
		},
		"trapFocus false, escape true": {
			trapFocus:    false,
			escapeClose:  true,
			wantKeys:     map[Key]bool{KeyEscape: true, KeyEnter: true},
			wantCatchAll: false,
		},
		"trapFocus false, escape false": {
			trapFocus:    false,
			escapeClose:  false,
			wantKeys:     map[Key]bool{KeyEnter: true},
			wantCatchAll: false,
		},
	}

	for name, tt := range tests {
		t.Run(name, func(t *testing.T) {
			open := NewState(true)
			m := NewModal(
				WithModalOpen(open),
				WithModalTrapFocus(tt.trapFocus),
				WithModalCloseOnEscape(tt.escapeClose),
			)
			m.BindApp(testApp)

			km := m.KeyMap()
			hasCatchAll := false
			for _, b := range km {
				if b.Pattern.AnyKey {
					hasCatchAll = true
					continue
				}
				if !tt.wantKeys[b.Pattern.Key] {
					t.Errorf("unexpected binding for key %v", b.Pattern.Key)
				}
			}
			if hasCatchAll != tt.wantCatchAll {
				t.Errorf("catch-all: got %v, want %v", hasCatchAll, tt.wantCatchAll)
			}
			for key := range tt.wantKeys {
				found := false
				for _, b := range km {
					if b.Pattern.Key == key {
						found = true
						break
					}
				}
				if !found {
					t.Errorf("expected binding for key %v not found", key)
				}
			}
		})
	}
}

func TestModal_FocusRestore_OnlyWhenTrapFocus(t *testing.T) {
	type tc struct {
		trapFocus     bool
		expectRestore bool
	}

	tests := map[string]tc{
		"trapFocus true restores focus": {
			trapFocus:     true,
			expectRestore: true,
		},
		"trapFocus false does not restore focus": {
			trapFocus:     false,
			expectRestore: false,
		},
	}

	for name, tt := range tests {
		t.Run(name, func(t *testing.T) {
			open := NewState(false)
			m := NewModal(
				WithModalOpen(open),
				WithModalTrapFocus(tt.trapFocus),
			)

			app := newTestApp(80, 24)
			m.BindApp(app)

			// Register two focusable elements
			btn1 := New(WithFocusable(true))
			btn2 := New(WithFocusable(true))
			app.focus.Register(btn1)
			app.focus.Register(btn2)
			app.focus.Next() // focus btn1 (index 0)

			originalIdx := app.focus.focusedIndex()

			// Open the modal via Render (triggers save of focus index)
			open.Set(true)
			m.Render(app)

			// Move focus while modal is open
			app.focus.Next() // move to btn2

			movedIdx := app.focus.focusedIndex()
			if movedIdx == originalIdx {
				t.Fatal("focus did not move; test setup is broken")
			}

			// Close the modal via Render (triggers restore)
			open.Set(false)
			m.Render(app)

			finalIdx := app.focus.focusedIndex()
			if tt.expectRestore && finalIdx != originalIdx {
				t.Errorf("expected focus restored to %d, got %d", originalIdx, finalIdx)
			}
			if !tt.expectRestore && finalIdx != movedIdx {
				t.Errorf("expected focus to stay at %d, got %d", movedIdx, finalIdx)
			}
		})
	}
}

func TestModal_HandleMouse_BackdropClick(t *testing.T) {
	open := NewState(true)
	m := NewModal(WithModalOpen(open))
	m.BindApp(testApp)

	// Render the modal to set up the element and overlay
	el := m.Render(testApp)
	// Trigger layout by rendering into a buffer
	buf := NewBuffer(80, 24)
	el.Render(buf, 80, 24)

	// Click on the overlay element itself (backdrop area, no children)
	consumed := m.HandleMouse(MouseEvent{
		Button: MouseLeft,
		Action: MousePress,
		X:      0,
		Y:      0,
	})

	if !consumed {
		t.Error("expected backdrop click to be consumed")
	}
	if open.Get() {
		t.Error("expected open to be false after backdrop click")
	}

	testApp.clearOverlays()
}

func TestModal_HandleMouse_BackdropClickDisabled(t *testing.T) {
	open := NewState(true)
	m := NewModal(WithModalOpen(open), WithModalCloseOnBackdropClick(false))
	m.BindApp(testApp)

	el := m.Render(testApp)
	buf := NewBuffer(80, 24)
	el.Render(buf, 80, 24)

	consumed := m.HandleMouse(MouseEvent{
		Button: MouseLeft,
		Action: MousePress,
		X:      0,
		Y:      0,
	})

	if !consumed {
		t.Error("expected backdrop click to be consumed even when close is disabled")
	}
	if !open.Get() {
		t.Error("expected open to remain true when backdrop click is disabled")
	}

	testApp.clearOverlays()
}

func TestModal_HandleMouse_ChildOnActivate(t *testing.T) {
	open := NewState(true)
	activated := false
	m := NewModal(
		WithModalOpen(open),
		WithModalElementOptions(WithDirection(Column)),
	)
	m.BindApp(testApp)

	el := m.Render(testApp)
	// Add a child button with onActivate and explicit size
	btn := New(WithOnActivate(func() { activated = true }), WithWidth(10), WithHeight(1))
	el.AddChild(btn)

	// Trigger layout
	buf := NewBuffer(80, 24)
	el.Render(buf, 80, 24)

	// Click within the button's rendered bounds
	btnRect := btn.Rect()
	consumed := m.HandleMouse(MouseEvent{
		Button: MouseLeft,
		Action: MousePress,
		X:      btnRect.X,
		Y:      btnRect.Y,
	})

	if !consumed {
		t.Error("expected child click to be consumed")
	}
	if !activated {
		t.Error("expected onActivate to be called")
	}

	testApp.clearOverlays()
}

func TestModal_KeyMap_EnterActivatesFocused(t *testing.T) {
	open := NewState(true)
	activated := false

	m := NewModal(WithModalOpen(open))
	m.BindApp(testApp)

	// Create a focusable element with onActivate
	btn := New(WithOnActivate(func() { activated = true }), WithFocusable(true))
	testApp.focus = newFocusManager()
	testApp.focus.Register(btn)
	testApp.focus.Next() // focus the button

	km := m.KeyMap()
	// Find the Enter binding
	for _, b := range km {
		if b.Pattern.Key == KeyEnter {
			b.Handler(KeyEvent{Key: KeyEnter})
			break
		}
	}

	if !activated {
		t.Error("expected Enter to trigger onActivate on focused element")
	}
}

func TestModal_HandleMouse_ClosedNoOp(t *testing.T) {
	open := NewState(false)
	m := NewModal(WithModalOpen(open))
	m.BindApp(testApp)

	consumed := m.HandleMouse(MouseEvent{
		Button: MouseLeft,
		Action: MousePress,
		X:      5,
		Y:      5,
	})

	if consumed {
		t.Error("expected mouse event to not be consumed when modal is closed")
	}
}

// testModalRoot is a minimal root component that wraps a Modal for testing.
type testModalRoot struct {
	modal *Modal
}

func (r *testModalRoot) Render(app *App) *Element {
	root := New()
	el := r.modal.Render(app)
	root.AddChild(el)
	return root
}

// newTestApp creates a lightweight App with a mock terminal and buffer for modal tests.
func newTestApp(width, height int) *App {
	return &App{
		terminal:     NewMockTerminal(width, height),
		buffer:       NewBuffer(width, height),
		stopCh:       make(chan struct{}),
		merged:       make(chan Event, 256),
		watcherQueue: make(chan func(), 256),
		focus:        newFocusManager(),
		mounts:       newMountState(),
		batch:        newBatchContext(),
	}
}

func TestModal_RenderFull_RepopulatesOverlays(t *testing.T) {
	open := NewState(true)
	modal := NewModal(WithModalOpen(open))
	rootComp := &testModalRoot{modal: modal}

	app := newTestApp(80, 24)
	modal.BindApp(app)
	app.rootComponent = rootComp

	// First render populates overlays
	app.MarkDirty()
	app.Render()
	if len(app.overlays) == 0 {
		t.Fatal("expected overlay after initial Render()")
	}

	// RenderFull should re-render the component tree and repopulate overlays
	app.RenderFull()
	if len(app.overlays) == 0 {
		t.Error("RenderFull() cleared overlays without re-registering them; open modal vanishes on full redraw")
	}
}

func TestModal_RenderFull_NeedsFocusInit(t *testing.T) {
	open := NewState(false)
	modal := NewModal(WithModalOpen(open))
	rootComp := &testModalRoot{modal: modal}

	app := newTestApp(80, 24)
	modal.BindApp(app)
	app.rootComponent = rootComp

	// Initial render with modal closed
	app.MarkDirty()
	app.Render()
	if len(app.overlays) != 0 {
		t.Fatal("expected no overlays when modal is closed")
	}

	// Open the modal; next render should set needsFocusInit
	open.Set(true)

	// Use RenderFull to verify it processes needsFocusInit
	app.RenderFull()
	if len(app.overlays) == 0 {
		t.Fatal("expected overlay after opening modal")
	}
	for _, ov := range app.overlays {
		if ov.needsFocusInit {
			t.Error("RenderFull() did not process needsFocusInit; focus won't auto-enter the modal on full redraw")
		}
	}
}

func TestModal_KeyMap_InlineMode(t *testing.T) {
	open := NewState(true)
	m := NewModal(WithModalOpen(open))

	app := newTestApp(80, 24)
	app.inlineHeight = 10
	app.inAlternateScreen = false
	m.BindApp(app)

	// In inline mode, registerOverlay silently skips the overlay
	m.Render(app)
	if len(app.overlays) != 0 {
		t.Fatal("expected no overlay in inline mode")
	}

	// KeyMap should return nil since the modal is not rendered
	km := m.KeyMap()
	if km != nil {
		t.Errorf("expected nil KeyMap in inline mode, got %d bindings", len(km))
	}

	// After entering alternate screen, KeyMap should return bindings
	app.inAlternateScreen = true
	km = m.KeyMap()
	if km == nil {
		t.Error("expected non-nil KeyMap in alternate screen mode")
	}
}

func TestModal_WithModalBackdrop_InvalidPanics(t *testing.T) {
	defer func() {
		if r := recover(); r == nil {
			t.Error("expected panic for invalid backdrop value")
		}
	}()
	WithModalBackdrop("typo")
}

func TestModal_Options(t *testing.T) {
	type tc struct {
		opts     []ModalOption
		backdrop string
		escape   bool
		click    bool
		focus    bool
	}

	tests := map[string]tc{
		"all defaults": {
			opts:     nil,
			backdrop: "dim",
			escape:   true,
			click:    true,
			focus:    true,
		},
		"custom backdrop": {
			opts:     []ModalOption{WithModalBackdrop("blank")},
			backdrop: "blank",
			escape:   true,
			click:    true,
			focus:    true,
		},
		"no escape": {
			opts:     []ModalOption{WithModalCloseOnEscape(false)},
			backdrop: "dim",
			escape:   false,
			click:    true,
			focus:    true,
		},
		"no backdrop click": {
			opts:     []ModalOption{WithModalCloseOnBackdropClick(false)},
			backdrop: "dim",
			escape:   true,
			click:    false,
			focus:    true,
		},
		"no focus trap": {
			opts:     []ModalOption{WithModalTrapFocus(false)},
			backdrop: "dim",
			escape:   true,
			click:    true,
			focus:    false,
		},
	}

	for name, tt := range tests {
		t.Run(name, func(t *testing.T) {
			m := NewModal(tt.opts...)
			if m.backdrop != tt.backdrop {
				t.Errorf("backdrop: got %q, want %q", m.backdrop, tt.backdrop)
			}
			if m.closeOnEscape != tt.escape {
				t.Errorf("closeOnEscape: got %v, want %v", m.closeOnEscape, tt.escape)
			}
			if m.closeOnBackdrop != tt.click {
				t.Errorf("closeOnBackdrop: got %v, want %v", m.closeOnBackdrop, tt.click)
			}
			if m.trapFocus != tt.focus {
				t.Errorf("trapFocus: got %v, want %v", m.trapFocus, tt.focus)
			}
		})
	}
}