gitstack

grindlemire/go-tui code browser

2.4 KB Go 119 lines 2026-03-01 · e7061ab 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
package tui

import (
	"testing"
	"time"
)

type testWatcherComponent struct {
	watchers []Watcher
}

func (t *testWatcherComponent) Render(app *App) *Element { return New() }
func (t *testWatcherComponent) Watchers() []Watcher      { return t.watchers }

func TestCollectComponentWatchers(t *testing.T) {
	type tc struct {
		setup    func() *Element
		expected int
	}

	tests := map[string]tc{
		"single component with one watcher": {
			setup: func() *Element {
				root := New()
				comp := &testWatcherComponent{
					watchers: []Watcher{
						OnTimer(time.Second, func() {}),
					},
				}
				child := New()
				child.component = comp
				root.AddChild(child)
				return root
			},
			expected: 1,
		},
		"nested components with multiple watchers": {
			setup: func() *Element {
				root := New()
				comp1 := &testWatcherComponent{
					watchers: []Watcher{OnTimer(time.Second, func() {})},
				}
				comp2 := &testWatcherComponent{
					watchers: []Watcher{
						OnTimer(time.Second, func() {}),
						OnTimer(time.Millisecond*500, func() {}),
					},
				}

				child1 := New()
				child1.component = comp1

				child2 := New()
				child2.component = comp2
				child1.AddChild(child2)

				root.AddChild(child1)
				return root
			},
			expected: 3,
		},
		"no components": {
			setup: func() *Element {
				root := New()
				root.AddChild(New())
				root.AddChild(New())
				return root
			},
			expected: 0,
		},
		"component without WatcherProvider": {
			setup: func() *Element {
				root := New()
				// Use a component that doesn't implement WatcherProvider
				comp := &simpleComponent{}
				child := New()
				child.component = comp
				root.AddChild(child)
				return root
			},
			expected: 0,
		},
		"nil root": {
			setup: func() *Element {
				return nil
			},
			expected: 0,
		},
		"component on root element": {
			setup: func() *Element {
				root := New()
				comp := &testWatcherComponent{
					watchers: []Watcher{
						OnTimer(time.Second, func() {}),
					},
				}
				root.component = comp
				return root
			},
			expected: 1,
		},
	}

	for name, tt := range tests {
		t.Run(name, func(t *testing.T) {
			root := tt.setup()
			watchers := collectComponentWatchers(nil, root)

			if len(watchers) != tt.expected {
				t.Fatalf("expected %d watchers, got %d", tt.expected, len(watchers))
			}
		})
	}
}

// simpleComponent implements Component but not WatcherProvider
type simpleComponent struct{}

func (s *simpleComponent) Render(app *App) *Element { return New() }