gitstack

grindlemire/go-tui code browser

9.3 KB Go 370 lines 2026-06-05 ยท 49e2fd0 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
package tui

import (
	"testing"
	"time"
)

func TestApp_QueueUpdate_EnqueuesSafely(t *testing.T) {
	app := &App{
		focus:        newFocusManager(),
		buffer:       NewBuffer(80, 24),
		updates:      make(chan Event, 256),
		merged:       make(chan Event, 256),
		watcherQueue: make(chan func(), 256),
		stopCh:       make(chan struct{}),
		stopped:      false,
	}

	var executed bool
	app.QueueUpdate(func() {
		executed = true
	})

	// QueueUpdate sends to updates channel; read directly (no fan-in in test)
	select {
	case ev := <-app.updates:
		app.Dispatch(ev)
		if !executed {
			t.Error("Queued function was not executed correctly")
		}
	case <-time.After(100 * time.Millisecond):
		t.Fatal("QueueUpdate did not enqueue function")
	}
}

func TestApp_QueueUpdate_FromGoroutine(t *testing.T) {
	app := &App{
		focus:        newFocusManager(),
		buffer:       NewBuffer(80, 24),
		updates:      make(chan Event, 256),
		merged:       make(chan Event, 256),
		watcherQueue: make(chan func(), 256),
		stopCh:       make(chan struct{}),
		stopped:      false,
	}

	var executed int
	done := make(chan struct{})

	// Queue from multiple goroutines
	for range 10 {
		go func() {
			app.QueueUpdate(func() {
				executed++
			})
		}()
	}

	// Read all queued functions from updates channel
	go func() {
		for range 10 {
			select {
			case ev := <-app.updates:
				app.Dispatch(ev)
			case <-time.After(100 * time.Millisecond):
				return
			}
		}
		close(done)
	}()

	select {
	case <-done:
		if executed != 10 {
			t.Errorf("Expected 10 executions, got %d", executed)
		}
	case <-time.After(500 * time.Millisecond):
		t.Fatal("Timed out waiting for goroutines to complete")
	}
}

func TestApp_QueueUpdate_DropsWhenFull(t *testing.T) {
	app := &App{
		focus:        newFocusManager(),
		buffer:       NewBuffer(80, 24),
		updates:      make(chan Event, 1),
		merged:       make(chan Event, 1),
		watcherQueue: make(chan func(), 1),
		stopCh:       make(chan struct{}),
	}

	seen := make([]int, 0, 2)
	app.QueueUpdate(func() { seen = append(seen, 1) }) // fits in buffer
	app.QueueUpdate(func() { seen = append(seen, 2) }) // channel full, dropped

	// Drain: only the first update should be present
	select {
	case ev := <-app.updates:
		app.Dispatch(ev)
	case <-time.After(100 * time.Millisecond):
		t.Fatal("expected queued update")
	}

	// Channel should be empty now
	select {
	case <-app.updates:
		t.Fatal("expected channel to be empty after draining one event")
	default:
	}

	if len(seen) != 1 || seen[0] != 1 {
		t.Fatalf("expected only first update to run, got %v", seen)
	}
}

func TestApp_SetGlobalKeyHandler(t *testing.T) {
	app := &App{
		focus:        newFocusManager(),
		buffer:       NewBuffer(80, 24),
		merged:       make(chan Event, 256),
		watcherQueue: make(chan func(), 256),
		stopCh:       make(chan struct{}),
		stopped:      false,
	}

	var handlerCalled bool
	app.SetGlobalKeyHandler(func(e KeyEvent) bool {
		handlerCalled = true
		return true
	})

	if app.globalKeyHandler == nil {
		t.Fatal("SetGlobalKeyHandler should set the handler")
	}

	// Call it
	result := app.globalKeyHandler(KeyEvent{Key: KeyRune, Rune: 'q'})

	if !handlerCalled {
		t.Error("Global key handler was not called")
	}
	if !result {
		t.Error("Global key handler should return true")
	}
}

func TestApp_GlobalKeyHandler_ConsumesEvent(t *testing.T) {
	mockReader := NewMockEventReader(KeyEvent{Key: KeyRune, Rune: 'q'})

	focusable := newMockFocusable("elem", true)
	focusable.handled = false

	app := &App{
		focus:        newFocusManager(),
		buffer:       NewBuffer(80, 24),
		reader:       mockReader,
		merged:       make(chan Event, 256),
		watcherQueue: make(chan func(), 256),
		stopCh:       make(chan struct{}),
		stopped:      false,
	}
	app.focus.Register(focusable)
	app.focus.SetFocus(focusable)

	var globalHandlerCalled bool
	app.SetGlobalKeyHandler(func(e KeyEvent) bool {
		globalHandlerCalled = true
		if e.Rune == 'q' {
			return true // Consume event
		}
		return false
	})

	// Dispatch goes through Dispatch() which handles globalKeyHandler in legacy path
	event := KeyEvent{Key: KeyRune, Rune: 'q'}
	app.Dispatch(event)

	if !globalHandlerCalled {
		t.Error("Global handler was not called")
	}

	if focusable.lastEvent != nil {
		t.Error("Event should have been consumed by global handler")
	}
}

func TestApp_GlobalKeyHandler_PassesEvent(t *testing.T) {
	focusable := newMockFocusable("elem", true)
	focusable.handled = true

	app := &App{
		focus:        newFocusManager(),
		buffer:       NewBuffer(80, 24),
		merged:       make(chan Event, 256),
		watcherQueue: make(chan func(), 256),
		stopCh:       make(chan struct{}),
		stopped:      false,
	}
	app.focus.Register(focusable)
	app.focus.SetFocus(focusable)

	var globalHandlerCalled bool
	app.SetGlobalKeyHandler(func(e KeyEvent) bool {
		globalHandlerCalled = true
		// Don't consume - let it pass through
		return false
	})

	// Dispatch goes through Dispatch() which handles globalKeyHandler in legacy path
	event := KeyEvent{Key: KeyRune, Rune: 'j'}
	app.Dispatch(event)

	if !globalHandlerCalled {
		t.Error("Global handler was not called")
	}

	if focusable.lastEvent == nil {
		t.Error("Event should have been passed to focused element")
	}
}

func TestApp_EventBatching(t *testing.T) {
	// Reset dirty flag for clean test
	testApp.resetDirty()

	mockReader := NewMockEventReader()

	app := &App{
		focus:        newFocusManager(),
		buffer:       NewBuffer(80, 24),
		reader:       mockReader,
		root:         New(),
		merged:       make(chan Event, 256),
		watcherQueue: make(chan func(), 256),
		stopCh:       make(chan struct{}),
		stopped:      false,
	}

	// Queue multiple events directly to merged (simulating fan-in output)
	for range 5 {
		app.merged <- UpdateEvent{fn: func() {
			testApp.MarkDirty()
		}}
	}

	// Process one batch manually (simulating the Run() loop logic)
	// Block until at least one event arrives
	select {
	case ev := <-app.merged:
		app.Dispatch(ev)
	case <-time.After(100 * time.Millisecond):
		t.Fatal("Expected event in queue")
	}

	// Drain additional queued events
drain:
	for {
		select {
		case ev := <-app.merged:
			app.Dispatch(ev)
		default:
			break drain
		}
	}

	// Only check dirty once, clear it
	var renderCount int
	if testApp.checkAndClearDirty() {
		// Would call Render() here in the real loop
		renderCount++
	}

	// Should only have rendered once despite multiple events
	if renderCount != 1 {
		t.Errorf("Expected 1 render after batched events, got %d", renderCount)
	}
}

func TestRenderInline_PreservesEraseToEOL(t *testing.T) {
	// Regression test for the v0.15.0 bug: the inline coordinate translation
	// in renderInline must preserve EraseToEOL. The bug manifested as cursor
	// trails and placeholder bleed in inline mode.
	//
	// Sets up a minimal App in inline mode, arranges a buffer where Diff()
	// emits EraseToEOL, and calls renderInline directly. Verifies the mock
	// terminal received and applied the erase.
	//
	// To verify the test catches regressions: remove EraseToEOL from the
	// CellChange literal in renderInline (app_render.go:128) and re-run.
	// This test must FAIL.

	const w = 20
	term := NewMockTerminal(80, 24)
	buf := NewBuffer(w, 3)
	inlineStartRow := 5

	// Arrange front=wide, back=narrow so Diff() emits EraseToEOL.
	buf.SetString(0, 0, "hello world", NewStyle())
	buf.Swap()               // front โ† "hello world"
	for x := 2; x < w; x++ { // narrow back: space-fill tail
		buf.SetRune(x, 0, ' ', NewStyle())
	}
	buf.SetString(0, 0, "hi", NewStyle()) // back โ† "hi"

	// Pre-populate mock terminal with correct unchanged cells + stale tail.
	term.SetCell(0, 0+inlineStartRow, NewCell('h', NewStyle()))
	term.SetCell(1, 0+inlineStartRow, NewCell('i', NewStyle()))
	for x := 2; x < w; x++ {
		term.SetCell(x, 0+inlineStartRow, NewCell('X', NewStyle()))
	}

	// Build a minimal App and call renderInline directly.
	app := &App{
		terminal:       term,
		buffer:         buf,
		inlineStartRow: inlineStartRow,
		inlineHeight:   3,
	}
	app.renderInline()

	// After renderInline: tail must be blank (EraseToEOL cleared it).
	for x := 2; x < w; x++ {
		if c := term.CellAt(x, 0+inlineStartRow); c.Rune != ' ' {
			t.Errorf("cell (%d, %d): got %q, want space โ€” EraseToEOL not applied. "+
				"Check app_render.go:128 copies EraseToEOL.",
				x, 0+inlineStartRow, string(c.Rune))
			return
		}
	}

	// Cols 0-1 ("hi") must be intact.
	if c := term.CellAt(0, 0+inlineStartRow); c.Rune != 'h' {
		t.Errorf("col 0: got %q, want 'h'", string(c.Rune))
	}
	if c := term.CellAt(1, 0+inlineStartRow); c.Rune != 'i' {
		t.Errorf("col 1: got %q, want 'i'", string(c.Rune))
	}
}

func TestPostRenderHook(t *testing.T) {
	type tc struct {
		render func(a *App)
	}

	tests := map[string]tc{
		"fires after renderFrame": {render: func(a *App) { a.renderFrame() }},
		"fires after RenderFull":  {render: func(a *App) { a.RenderFull() }},
	}

	for name, tt := range tests {
		t.Run(name, func(t *testing.T) {
			called := 0
			a := &App{
				terminal:       NewMockTerminal(80, 24),
				focus:          newFocusManager(),
				buffer:         NewBuffer(80, 24),
				merged:         make(chan Event, 256),
				watcherQueue:   make(chan func(), 256),
				stopCh:         make(chan struct{}),
				mounts:         newMountState(),
				batch:          newBatchContext(),
				postRenderHook: func() { called++ },
			}
			tt.render(a)
			if called != 1 {
				t.Fatalf("postRenderHook called %d times, want 1", called)
			}
		})
	}
}