gitstack

grindlemire/go-tui code browser

5.7 KB Go 203 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
package tui

import (
	"fmt"

	"github.com/grindlemire/go-tui/internal/debug"
)

// focusQuerier is implemented by components that can report their own focus state.
// Used by the dispatch table to evaluate focus-gated key bindings.
type focusQuerier interface {
	IsFocused() bool
}

// dispatchEntry is a handler with its tree position for ordering.
type dispatchEntry struct {
	pattern    KeyPattern
	handler    func(KeyEvent)
	stop       bool
	preempt    bool        // fires before normal handlers (used by modal)
	position   int         // BFS order index from tree walk
	focusCheck func() bool // Non-nil for focus-gated entries; returns true when component is focused
}

// dispatchTable holds all handlers in a single tree-ordered list.
// Handlers are matched against incoming KeyEvents by pattern.
type dispatchTable struct {
	entries []dispatchEntry // All handlers, ordered by tree position
}

// buildDispatchTable walks the element tree, collects KeyMap() from
// all mounted components, validates exclusive conflicts, and builds
// the dispatch table ordered by tree position.
func buildDispatchTable(rootComp Component, root *Element) (*dispatchTable, error) {
	table := &dispatchTable{}
	position := 0

	walkComponents(rootComp, root, func(comp Component) {
		kl, ok := comp.(KeyListener)
		if !ok {
			return
		}
		km := kl.KeyMap()
		if km == nil {
			return
		}

		fq, hasFocusQuery := comp.(focusQuerier)

		for _, binding := range km {
			entry := dispatchEntry{
				pattern:  binding.Pattern,
				handler:  binding.Handler,
				stop:     binding.Stop,
				preempt:  binding.Preempt,
				position: position,
			}
			// For focus-gated bindings, capture the component's focus check
			if binding.Pattern.FocusRequired && hasFocusQuery {
				entry.focusCheck = fq.IsFocused
			}
			table.entries = append(table.entries, entry)
		}
		position++
	})

	if err := table.validate(); err != nil {
		return nil, err
	}

	return table, nil
}

// matchesKey checks if a dispatch entry's key pattern matches a key event,
// without checking focus state.
func (e *dispatchEntry) matchesKey(ke KeyEvent) bool {
	p := e.pattern

	if p.AnyKey {
		return true
	}

	if p.ExcludeMods != 0 && ke.Mod&p.ExcludeMods != 0 {
		return false
	}
	if p.Mod != 0 && ke.Mod != p.Mod {
		return false
	}

	if p.AnyRune && ke.Key == KeyRune {
		return true
	}
	if p.Rune != 0 && ke.Rune == p.Rune && ke.Key == KeyRune {
		return true
	}
	if p.Key != 0 && ke.Key == p.Key {
		return true
	}
	return false
}

// matches checks if a dispatch entry matches a key event, including focus gating.
func (e *dispatchEntry) matches(ke KeyEvent) bool {
	if e.pattern.FocusRequired && e.focusCheck != nil {
		if !e.focusCheck() {
			return false
		}
	}
	return e.matchesKey(ke)
}

// dispatch sends a key event to matching handlers.
// Focus-gated stop handlers take priority: if any active focus-gated stop
// handler matches, it fires exclusively and broadcast handlers are skipped.
// Otherwise, handlers fire in tree order, stopping early if a Stop handler matches.
func (dt *dispatchTable) dispatch(ke KeyEvent) bool {
	if dt == nil {
		return false
	}
	debug.Topic("dispatch", "Key=%s Rune=%q Mod=%s (entries=%d)", ke.Key, ke.Rune, ke.Mod, len(dt.entries))

	// Priority pass: focus-gated stop handlers consume the event exclusively.
	// This ensures a focused input captures keys like 'q' before broadcast
	// handlers (like quit) can intercept them.
	for i := range dt.entries {
		e := &dt.entries[i]
		if e.pattern.FocusRequired && e.stop && e.focusCheck != nil && e.focusCheck() {
			if e.matchesKey(ke) {
				e.handler(ke)
				return true
			}
		}
	}

	// Preemptive pass: overlay handlers that must fire before normal dispatch.
	// Used by modal to block parent handlers from seeing key events.
	for i := range dt.entries {
		if !dt.entries[i].preempt {
			continue
		}
		if dt.entries[i].matches(ke) {
			dt.entries[i].handler(ke)
			if dt.entries[i].stop {
				return true
			}
		}
	}

	// Normal dispatch: broadcast and non-stop handlers in tree order.
	for i := range dt.entries {
		if dt.entries[i].preempt {
			continue // already handled
		}
		if dt.entries[i].matches(ke) {
			debug.Topic("dispatch", "matched entry[%d] pattern={Key=%s Rune=%q Mod=%v ExcludeMods=%v} stop=%v",
				i, dt.entries[i].pattern.Key, dt.entries[i].pattern.Rune, dt.entries[i].pattern.Mod, dt.entries[i].pattern.ExcludeMods, dt.entries[i].stop)
			dt.entries[i].handler(ke)
			if dt.entries[i].stop {
				return true
			}
		}
	}
	return false
}

// validate checks for conflicting Stop handlers. Two active Stop handlers
// for the same key pattern is an error — it's ambiguous which should win.
// A Stop handler + a broadcast handler for the same pattern is fine.
func (dt *dispatchTable) validate() error {
	// Track patterns that already have a Stop handler
	type stopInfo struct {
		position int
	}
	stopPatterns := make(map[KeyPattern]stopInfo)

	for _, entry := range dt.entries {
		if !entry.stop {
			continue
		}
		// Focus-gated entries cannot conflict because only one can be focused at a time
		if entry.pattern.FocusRequired {
			continue
		}
		// Preemptive entries (modal overlay) run in a separate dispatch pass
		// and cannot conflict with normal stop handlers.
		if entry.preempt {
			continue
		}
		// Strip FocusRequired for comparison so focus-gated and broadcast entries
		// with the same key don't conflict
		comparePattern := entry.pattern
		comparePattern.FocusRequired = false
		if existing, conflict := stopPatterns[comparePattern]; conflict {
			return fmt.Errorf(
				"conflicting stop handlers for key pattern %+v at tree positions %d and %d",
				entry.pattern, existing.position, entry.position,
			)
		}
		stopPatterns[comparePattern] = stopInfo{position: entry.position}
	}

	return nil
}