gitstack

grindlemire/go-tui code browser

2.5 KB Go 95 lines 2026-03-09 · f761d8a 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
package tui

// --- Focus Tree Discovery API ---

// SetOnFocusableAdded sets a callback called when a focusable descendant is added.
// This is used by App to auto-register focusable elements.
func (e *Element) SetOnFocusableAdded(fn func(Focusable)) {
	e.onFocusableAdded = fn
}

// WalkFocusables calls fn for each tab-navigable element in the tree.
// Only elements with tabStop=true are included (not all focusable elements).
// This is used by focusManager to build the Tab navigation cycle.
func (e *Element) WalkFocusables(fn func(Focusable)) {
	if e.hidden {
		return
	}
	if e.IsTabStop() {
		fn(e)
	}
	for _, child := range e.children {
		child.WalkFocusables(fn)
	}
}

// --- OnUpdate Hook API ---

// SetOnUpdate sets a function called before each render.
// Useful for polling channels, updating animations, etc.
func (e *Element) SetOnUpdate(fn func()) {
	e.onUpdate = fn
}

// --- Watcher API ---

// AddWatcher attaches a watcher (timer, channel watcher) to this element.
// Watchers are started automatically when the element tree is set as app root.
func (e *Element) AddWatcher(w Watcher) {
	e.watchers = append(e.watchers, w)
}

// Watchers returns the watchers attached to this element.
func (e *Element) Watchers() []Watcher {
	return e.watchers
}

// WalkWatchers calls fn for each watcher in the element tree.
// This is used by App.SetRoot to discover and start all watchers.
func (e *Element) WalkWatchers(fn func(Watcher)) {
	if e.hidden {
		return
	}
	for _, w := range e.watchers {
		fn(w)
	}
	for _, child := range e.children {
		child.WalkWatchers(fn)
	}
}

// --- Hit Testing API ---

// ElementAt finds the deepest element containing the point (x, y).
// Returns nil if no element contains the point.
// Children are checked in reverse order since last child renders on top.
func (e *Element) ElementAt(x, y int) *Element {
	if e.hidden {
		return nil
	}
	bounds := e.Rect()
	if !bounds.Contains(x, y) {
		return nil
	}

	// Check children in reverse order (last child renders on top)
	for i := len(e.children) - 1; i >= 0; i-- {
		if hit := e.children[i].ElementAt(x, y); hit != nil {
			return hit
		}
	}

	// No child hit, this element is the target
	return e
}

// ElementAtPoint finds the deepest element containing the point (x, y).
// Returns nil if no element contains the point.
// Returns the element as Focusable for mouse event dispatch.
func (e *Element) ElementAtPoint(x, y int) Focusable {
	elem := e.ElementAt(x, y)
	if elem == nil {
		return nil
	}
	return elem
}