gitstack

grindlemire/go-tui code browser

8.5 KB Go 313 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
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
// Package tui provides the core State type for reactive UI bindings.
//
// State[T] wraps a value and notifies bindings when it changes. This enables
// automatic UI updates without manual SetText() calls.
//
// Thread Safety Rules:
//   - Get() is safe to call from any goroutine
//   - Set() must only be called from the main event loop
//   - For background updates, use channel watchers or App.QueueUpdate()
//
// Example usage:
//
//	count := tui.NewState(0)
//	count.Bind(func(v int) {
//	    span.SetText(fmt.Sprintf("Count: %d", v))
//	})
//	count.Set(count.Get() + 1)  // triggers binding and marks dirty
//
// Batching:
//
// Use Batch() to coalesce multiple Set() calls and avoid redundant binding
// execution:
//
//	app.Batch(func() {
//	    firstName.Set("Bob")
//	    lastName.Set("Smith")
//	})  // Bindings fire once here, not twice
package tui

import (
	"sync"
	"sync/atomic"

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

// batchContext tracks batch state for deferring binding execution.
type batchContext struct {
	mu           sync.Mutex
	depth        int               // nesting depth (0 = not batching)
	pending      map[uint64]func() // pending binding callbacks keyed by binding ID
	pendingOrder []uint64          // order in which bindings were first triggered
}

func newBatchContext() batchContext {
	return batchContext{
		pending: make(map[uint64]func()),
	}
}

// globalBindingID is a global counter for generating unique binding IDs.
// This ensures binding IDs are unique across all State instances.
var globalBindingID atomic.Uint64

// State wraps a value and notifies bindings when it changes.
// State is generic over any type T.
type State[T any] struct {
	mu        sync.RWMutex
	value     T
	bindings  []*binding[T]
	app       *App
	notifying bool // true while executing bindings, prevents re-entrant cycles
}

// binding represents a registered callback that fires when state changes.
type binding[T any] struct {
	id     uint64
	fn     func(T)
	active bool
}

// Unbind is a handle to remove a binding. Call it to prevent
// future callback invocations for the associated binding.
type Unbind func()

// NewState creates a new state with the given initial value.
// The state is created unbound — it will be bound to an App later via
// BindApp (called by generated code during mount).
//
// Example:
//
//	count := tui.NewState(0)           // State[int]
//	name := tui.NewState("hello")      // State[string]
//	items := tui.NewState([]string{})  // State[[]string]
func NewState[T any](initial T) *State[T] {
	return &State[T]{value: initial}
}

// NewStateForApp creates a state bound to the provided app.
func NewStateForApp[T any](app *App, initial T) *State[T] {
	if app == nil {
		panic("tui: nil app in NewStateForApp")
	}
	return &State[T]{value: initial, app: app}
}

// BindApp binds this state to the given app for dirty-marking and batching.
// Panics if app is nil. Idempotent for the same app; overwrites if different.
func (s *State[T]) BindApp(app *App) {
	if app == nil {
		panic("tui: nil app in State.BindApp")
	}
	s.mu.Lock()
	s.app = app
	s.mu.Unlock()
}

// setDirect sets the value without requiring an app.
// No dirty marking, no bindings, no batching.
// Used by framework code for construction-time initialization
// when no app is bound yet and none of those effects are needed.
func (s *State[T]) setDirect(v T) {
	s.mu.Lock()
	s.value = v
	s.mu.Unlock()
}

// Get returns the current value. Thread-safe for reading from any goroutine.
func (s *State[T]) Get() T {
	s.mu.RLock()
	defer s.mu.RUnlock()
	return s.value
}

// Set updates the value, marks dirty, and notifies all bindings.
//
// IMPORTANT: Must be called from main loop only. For background
// updates, use app.QueueUpdate() or channel watchers.
//
// Set automatically calls MarkDirty() to trigger a re-render.
// If called within a Batch(), binding execution is deferred until the
// batch completes.
func (s *State[T]) Set(v T) {
	debug.Log("State.Set: setting value to %v", v)
	s.mu.Lock()
	s.value = v
	// Copy active bindings while holding lock and remove inactive ones
	// to prevent memory leaks from accumulated unbound bindings
	activeBindings := make([]*binding[T], 0, len(s.bindings))
	for _, b := range s.bindings {
		if b.active {
			activeBindings = append(activeBindings, b)
		}
	}
	// Replace bindings slice with only active bindings (cleanup)
	s.bindings = activeBindings
	reentrant := s.notifying
	app := s.app
	s.mu.Unlock()

	// Construction-time Set before app binding: keep value + bindings behavior,
	// but skip dirty marking and batching because no app context exists yet.
	if app == nil {
		if reentrant {
			return
		}
		s.mu.Lock()
		s.notifying = true
		s.mu.Unlock()
		for _, b := range activeBindings {
			b.fn(v)
		}
		s.mu.Lock()
		s.notifying = false
		s.mu.Unlock()
		return
	}

	// Mark dirty on the owning app.
	app.MarkDirty()

	// If this state is already notifying its bindings, a binding callback
	// has triggered a Set on this same state (circular dependency). The value
	// is updated and dirty is marked, but we skip firing bindings again to
	// prevent a stack overflow. Render() will read the correct final value.
	if reentrant {
		debug.Log("State.Set: skipping bindings (re-entrant)")
		return
	}

	// Check if we're in a batch
	batch := &app.batch
	batch.mu.Lock()
	if batch.pending == nil {
		batch.pending = make(map[uint64]func())
	}
	isBatching := batch.depth > 0
	if isBatching {
		// Defer binding execution - store closures keyed by binding ID
		// Later Set() calls to same binding ID will overwrite with new value
		// Track order of first occurrence for deterministic execution order
		for _, b := range activeBindings {
			bindingID := b.id
			bindingFn := b.fn
			capturedValue := v
			if _, exists := batch.pending[bindingID]; !exists {
				// First time seeing this binding, track its order
				batch.pendingOrder = append(batch.pendingOrder, bindingID)
			}
			batch.pending[bindingID] = func() { bindingFn(capturedValue) }
		}
	}
	batch.mu.Unlock()

	// Execute bindings immediately if not batching
	if !isBatching {
		debug.Log("State.Set: executing %d bindings immediately", len(activeBindings))
		s.mu.Lock()
		s.notifying = true
		s.mu.Unlock()
		for _, b := range activeBindings {
			b.fn(v)
		}
		s.mu.Lock()
		s.notifying = false
		s.mu.Unlock()
	} else {
		debug.Log("State.Set: deferred %d bindings (batching)", len(activeBindings))
	}
}

// Update applies a function to the current value and sets the result.
// This is a convenience method for read-modify-write operations.
//
// Example:
//
//	count.Update(func(v int) int { return v + 1 })
func (s *State[T]) Update(fn func(T) T) {
	s.Set(fn(s.Get()))
}

// Bind registers a function to be called when the value changes.
// Returns an Unbind handle to remove the binding.
//
// The binding callback receives the new value as its argument.
// Bindings are executed in registration order.
//
// Example:
//
//	unbind := count.Bind(func(v int) {
//	    fmt.Println("count changed to", v)
//	})
//	// Later, to stop receiving updates:
//	unbind()
func (s *State[T]) Bind(fn func(T)) Unbind {
	// Use global counter to ensure unique IDs across all State instances
	id := globalBindingID.Add(1)

	s.mu.Lock()
	b := &binding[T]{id: id, fn: fn, active: true}
	s.bindings = append(s.bindings, b)
	s.mu.Unlock()

	return func() {
		s.mu.Lock()
		b.active = false
		s.mu.Unlock()
	}
}

// Batch executes fn using this app's batch context.
func (a *App) Batch(fn func()) {
	if a == nil {
		panic("tui: nil app in Batch")
	}
	batch := &a.batch
	batch.mu.Lock()
	if batch.pending == nil {
		batch.pending = make(map[uint64]func())
	}
	batch.depth++
	batch.mu.Unlock()

	defer func() {
		batch.mu.Lock()
		batch.depth--
		shouldExecute := batch.depth == 0 && len(batch.pending) > 0
		var pendingCallbacks []func()
		if shouldExecute {
			// Collect callbacks in the order they were first triggered
			pendingCallbacks = make([]func(), 0, len(batch.pendingOrder))
			for _, id := range batch.pendingOrder {
				if callback, exists := batch.pending[id]; exists {
					pendingCallbacks = append(pendingCallbacks, callback)
				}
			}
			batch.pending = make(map[uint64]func())
			batch.pendingOrder = nil
		}
		batch.mu.Unlock()

		// Execute callbacks outside the lock
		if shouldExecute {
			for _, callback := range pendingCallbacks {
				callback()
			}
		}
	}()

	fn()
}

// TestResetBatch resets this app's batch state for tests.
func (a *App) TestResetBatch() {
	if a == nil {
		panic("tui: nil app in TestResetBatch")
	}
	a.batch.mu.Lock()
	a.batch.depth = 0
	a.batch.pending = make(map[uint64]func())
	a.batch.pendingOrder = nil
	a.batch.mu.Unlock()
}