textual 1.0.0-dev

A reactive TUI framework inspired by the Python Textual library
Documentation
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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
//! Reactive attribute system for textual-rs.
//!
//! Provides automatic change detection, repaint/layout invalidation, and
//! watcher dispatch for widget fields annotated with `#[reactive]` or `#[var]`.
//!
//! # Overview
//!
//! This module defines the core types that power the reactive system:
//!
//! - [`ReactiveFlags`] — controls what happens when a reactive field changes
//! - [`ReactiveChange`] — records a single field change with old/new values
//! - [`ReactiveCtx`] — context passed to setters, accumulates changes
//! - [`ReactiveWidget`] — trait implemented by `#[derive(Reactive)]`
//!
//! # Usage
//!
//! ```ignore
//! use textual_macros::Reactive;
//!
//! #[derive(Reactive)]
//! struct MyWidget {
//!     #[reactive]
//!     label: String,
//!
//!     #[reactive(layout)]
//!     size: usize,
//!
//!     #[var]
//!     counter: u32,
//! }
//! ```

use crate::node_id::NodeId;
use std::any::Any;
use std::cell::RefCell;

/// Flags controlling what happens when a reactive field changes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ReactiveFlags {
    /// Request repaint on change (default for `#[reactive]`).
    pub repaint: bool,
    /// Request layout invalidation on change (`#[reactive(layout)]`).
    pub layout: bool,
    /// Call watcher on mount (default for `#[reactive]`, not `#[var]`).
    pub init: bool,
    /// Fire watchers even when old value equals new value.
    ///
    /// Matches Python's `reactive(always_update=True)`. Used for fields like
    /// `Tree.cursor_line` where setting the same value should still trigger
    /// side effects (e.g. scroll-into-view, repaint).
    pub always_update: bool,
}

impl Default for ReactiveFlags {
    fn default() -> Self {
        Self {
            repaint: true,
            layout: false,
            init: true,
            always_update: false,
        }
    }
}

impl ReactiveFlags {
    /// Flags for `#[reactive]`: repaint on change, call watcher on init.
    pub const fn reactive() -> Self {
        Self {
            repaint: true,
            layout: false,
            init: true,
            always_update: false,
        }
    }

    /// Flags for `#[reactive(layout)]`: repaint + layout on change, call watcher on init.
    pub const fn reactive_layout() -> Self {
        Self {
            repaint: true,
            layout: true,
            init: true,
            always_update: false,
        }
    }

    /// Flags for `#[reactive(init = false)]`: repaint on change, no watcher on init.
    pub const fn reactive_no_init() -> Self {
        Self {
            repaint: true,
            layout: false,
            init: false,
            always_update: false,
        }
    }

    /// Flags for `#[reactive(layout, init = false)]`: repaint + layout on change, no watcher on init.
    pub const fn reactive_layout_no_init() -> Self {
        Self {
            repaint: true,
            layout: true,
            init: false,
            always_update: false,
        }
    }

    /// Flags for `#[var]`: no repaint, no layout, no init watcher.
    pub const fn var() -> Self {
        Self {
            repaint: false,
            layout: false,
            init: false,
            always_update: false,
        }
    }

    /// Flags for `reactive(always_update=True)`: repaint on change, call watcher
    /// on init, and fire watchers even when old value equals new value.
    ///
    /// Matches Python's `reactive(always_update=True)` pattern.
    pub const fn reactive_always_update() -> Self {
        Self {
            repaint: true,
            layout: false,
            init: true,
            always_update: true,
        }
    }
}

/// Records a single field change during an event dispatch cycle.
///
/// Stores the field name, flags, and type-erased old/new values so that
/// watcher methods can be called with properly typed arguments.
pub struct ReactiveChange {
    /// The name of the field that changed.
    pub field_name: &'static str,
    /// Flags from the field's reactive annotation.
    pub flags: ReactiveFlags,
    /// The old value before the change, type-erased.
    pub old_value: Box<dyn Any + Send>,
    /// The new value after the change, type-erased.
    pub new_value: Box<dyn Any + Send>,
}

impl std::fmt::Debug for ReactiveChange {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ReactiveChange")
            .field("field_name", &self.field_name)
            .field("flags", &self.flags)
            .field("old_value", &"<type-erased>")
            .field("new_value", &"<type-erased>")
            .finish()
    }
}

/// Context passed to reactive setters. Records changes and provides node identity.
///
/// Widgets receive this via the runtime; they don't construct it themselves.
/// The context accumulates all changes that occurred during an event dispatch
/// cycle, and the runtime drains them afterward to call watchers and request
/// repaint/layout invalidation.
pub struct ReactiveCtx {
    node_id: NodeId,
    changes: Vec<ReactiveChange>,
    repaint_requested: bool,
    layout_requested: bool,
}

impl ReactiveCtx {
    /// Create a new reactive context for the given widget node.
    pub fn new(node_id: NodeId) -> Self {
        Self {
            node_id,
            changes: Vec::new(),
            repaint_requested: false,
            layout_requested: false,
        }
    }

    /// The node identity of the widget that owns this context.
    pub fn node_id(&self) -> NodeId {
        self.node_id
    }

    /// Access the recorded changes.
    pub fn changes(&self) -> &[ReactiveChange] {
        &self.changes
    }

    /// Take all recorded changes, leaving the context empty.
    pub fn take_changes(&mut self) -> Vec<ReactiveChange> {
        std::mem::take(&mut self.changes)
    }

    /// Record a field change. Called by the generated setter methods.
    pub fn record_change(
        &mut self,
        field_name: &'static str,
        flags: ReactiveFlags,
        old_value: Box<dyn Any + Send>,
        new_value: Box<dyn Any + Send>,
    ) {
        if flags.repaint {
            self.repaint_requested = true;
        }
        if flags.layout {
            self.layout_requested = true;
        }
        self.changes.push(ReactiveChange {
            field_name,
            flags,
            old_value,
            new_value,
        });
    }

    /// Whether any change requested a repaint.
    pub fn needs_repaint(&self) -> bool {
        self.repaint_requested
    }

    /// Whether any change requested a layout invalidation.
    pub fn needs_layout(&self) -> bool {
        self.layout_requested
    }

    /// Returns `true` if any changes were recorded.
    pub fn has_changes(&self) -> bool {
        !self.changes.is_empty()
    }

    /// Reset repaint/layout flags without touching the recorded changes.
    ///
    /// Used by the app-level reactive bridge after draining changes so that
    /// stale flags from previous hook calls do not accumulate across tick
    /// boundaries.
    pub fn reset_flags(&mut self) {
        self.repaint_requested = false;
        self.layout_requested = false;
    }

    /// Reset the repaint/layout flags (e.g. after the runtime processes them).
    pub fn clear_flags(&mut self) {
        self.repaint_requested = false;
        self.layout_requested = false;
    }
}

impl std::fmt::Debug for ReactiveCtx {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ReactiveCtx")
            .field("node_id", &self.node_id)
            .field("changes", &self.changes.len())
            .field("repaint_requested", &self.repaint_requested)
            .field("layout_requested", &self.layout_requested)
            .finish()
    }
}

/// Static descriptor for a single reactive field on a widget.
///
/// Generated by the derive macro and returned by `reactive_field_descriptors()`.
/// Used by the runtime for init-phase watcher dispatch and introspection.
#[derive(Debug, Clone, Copy)]
pub struct ReactiveFieldDescriptor {
    /// The field name (e.g. `"label"`, `"size"`).
    pub name: &'static str,
    /// The flags from the field's annotation.
    pub flags: ReactiveFlags,
}

/// Trait implemented by `#[derive(Reactive)]` structs.
///
/// The derive macro generates a `reactive_dispatch` implementation that
/// calls the appropriate `watch_{field}` method for each recorded change
/// (when the field was annotated with `#[reactive(watch)]`).
///
/// Widgets that don't use reactive fields can still implement this trait
/// with the default no-op implementation.
pub trait ReactiveWidget {
    /// Called by the runtime after event dispatch to process recorded changes.
    ///
    /// The default implementation does nothing. The derive macro overrides this
    /// to downcast old/new values and call `watch_{field}` methods.
    fn reactive_dispatch(&mut self, _changes: &[ReactiveChange], _ctx: &mut ReactiveCtx) {
        // Default: no-op. The derive macro generates the real dispatch.
    }

    /// Return static descriptors for all reactive fields on this widget.
    ///
    /// Used by the runtime to decide which fields need init-phase watcher
    /// dispatch on mount. The default returns an empty slice.
    fn reactive_field_descriptors(&self) -> &'static [ReactiveFieldDescriptor] {
        &[]
    }
}

// ── Runtime reactive phase ──────────────────────────────────────────

/// Maximum number of reactive iterations before the runtime considers
/// a cycle and stops processing. Protects against infinite watcher loops
/// where one watcher's side-effect triggers another change ad infinitum.
pub const MAX_REACTIVE_ITERATIONS: usize = 100;

/// Outcome of running the reactive phase for a single widget.
#[derive(Debug, Default)]
pub struct ReactivePhaseResult {
    /// Whether any changes were processed.
    pub had_changes: bool,
    /// Whether any change requested a repaint.
    pub needs_repaint: bool,
    /// Whether any change requested a layout invalidation.
    pub needs_layout: bool,
    /// Number of iterations executed.
    pub iterations: usize,
    /// Whether the iteration limit was hit (potential cycle).
    pub cycle_detected: bool,
}

/// Run the reactive phase for a single widget: drain changes, call watchers,
/// and repeat until no new changes are produced (or cycle limit is hit).
///
/// This is the core function called by the event loop after event dispatch.
/// It takes the widget's `ReactiveCtx` (which accumulated changes from setters
/// during event dispatch), drains the changes, calls `reactive_dispatch()`,
/// and iterates if the dispatch produced further changes (e.g. a watcher
/// calling another setter).
pub fn run_reactive_phase(
    widget: &mut dyn ReactiveWidget,
    ctx: &mut ReactiveCtx,
) -> ReactivePhaseResult {
    run_reactive_phase_with_dispatch(ctx, |changes, dispatch_ctx| {
        widget.reactive_dispatch(changes, dispatch_ctx);
    })
}

/// Run the reactive phase with a custom dispatch function.
///
/// This powers runtime integration where watcher dispatch is represented as
/// a queued callback, and also backs [`run_reactive_phase`] for
/// trait-object based widgets.
pub fn run_reactive_phase_with_dispatch(
    ctx: &mut ReactiveCtx,
    mut dispatch: impl FnMut(&[ReactiveChange], &mut ReactiveCtx),
) -> ReactivePhaseResult {
    let mut result = ReactivePhaseResult::default();

    for iteration in 0..MAX_REACTIVE_ITERATIONS {
        if !ctx.has_changes() {
            break;
        }

        result.had_changes = true;
        result.iterations = iteration + 1;

        if ctx.needs_repaint() {
            result.needs_repaint = true;
        }
        if ctx.needs_layout() {
            result.needs_layout = true;
        }

        let changes = ctx.take_changes();
        ctx.clear_flags();
        dispatch(&changes, ctx);
    }

    // Check for cycle: if we hit max iterations and there are still changes.
    if ctx.has_changes() {
        result.cycle_detected = true;
        result.iterations = MAX_REACTIVE_ITERATIONS;
        crate::debug::debug_render(&format!(
            "[reactive] cycle detected: {} iterations exceeded for node {:?}",
            MAX_REACTIVE_ITERATIONS,
            ctx.node_id()
        ));
        // Drain remaining changes to prevent unbounded accumulation.
        let _ = ctx.take_changes();
        ctx.clear_flags();
    }

    // Collect final flags from any remaining state.
    if ctx.needs_repaint() {
        result.needs_repaint = true;
    }
    if ctx.needs_layout() {
        result.needs_layout = true;
    }

    result
}

/// Queued reactive work unit drained by the runtime event loop.
///
/// Widgets enqueue entries during event/lifecycle handlers after recording
/// reactive changes in `ctx`; the runtime drains and processes them during the
/// deterministic reactive phase.
pub struct RuntimeReactiveEntry {
    node_id: NodeId,
    ctx: ReactiveCtx,
}

impl RuntimeReactiveEntry {
    pub fn new(node_id: NodeId, ctx: ReactiveCtx) -> Self {
        Self { node_id, ctx }
    }

    pub fn node_id(&self) -> NodeId {
        self.node_id
    }

    pub fn run_with_dispatch(
        &mut self,
        dispatch: impl FnMut(&[ReactiveChange], &mut ReactiveCtx),
    ) -> ReactivePhaseResult {
        run_reactive_phase_with_dispatch(&mut self.ctx, dispatch)
    }

    pub fn run_without_dispatch(&mut self) -> ReactivePhaseResult {
        run_reactive_phase_with_dispatch(&mut self.ctx, |_changes, _ctx| {})
    }
}

thread_local! {
    static RUNTIME_REACTIVE_QUEUE: RefCell<Vec<RuntimeReactiveEntry>> = const { RefCell::new(Vec::new()) };
}

/// Enqueue a reactive work item to be processed in the runtime reactive phase.
pub fn enqueue_runtime_reactive_entry(entry: RuntimeReactiveEntry) {
    RUNTIME_REACTIVE_QUEUE.with(|queue| queue.borrow_mut().push(entry));
}

/// Drain all queued runtime reactive work items.
pub fn take_runtime_reactive_entries() -> Vec<RuntimeReactiveEntry> {
    RUNTIME_REACTIVE_QUEUE.with(|queue| std::mem::take(&mut *queue.borrow_mut()))
}

#[cfg(test)]
mod tests {
    use super::*;
    use slotmap::SlotMap;

    fn make_node_id() -> NodeId {
        let mut sm: SlotMap<NodeId, ()> = SlotMap::new();
        sm.insert(())
    }

    #[test]
    fn reactive_flags_defaults() {
        let flags = ReactiveFlags::default();
        assert!(flags.repaint);
        assert!(!flags.layout);
        assert!(flags.init);
    }

    #[test]
    fn reactive_flags_reactive() {
        let flags = ReactiveFlags::reactive();
        assert!(flags.repaint);
        assert!(!flags.layout);
        assert!(flags.init);
    }

    #[test]
    fn reactive_flags_reactive_layout() {
        let flags = ReactiveFlags::reactive_layout();
        assert!(flags.repaint);
        assert!(flags.layout);
        assert!(flags.init);
    }

    #[test]
    fn reactive_flags_var() {
        let flags = ReactiveFlags::var();
        assert!(!flags.repaint);
        assert!(!flags.layout);
        assert!(!flags.init);
    }

    #[test]
    fn ctx_new_is_empty() {
        let id = make_node_id();
        let ctx = ReactiveCtx::new(id);
        assert_eq!(ctx.node_id(), id);
        assert!(ctx.changes().is_empty());
        assert!(!ctx.needs_repaint());
        assert!(!ctx.needs_layout());
        assert!(!ctx.has_changes());
    }

    #[test]
    fn ctx_record_change_sets_repaint() {
        let id = make_node_id();
        let mut ctx = ReactiveCtx::new(id);
        ctx.record_change(
            "label",
            ReactiveFlags::reactive(),
            Box::new("old".to_string()),
            Box::new("new".to_string()),
        );
        assert!(ctx.needs_repaint());
        assert!(!ctx.needs_layout());
        assert!(ctx.has_changes());
        assert_eq!(ctx.changes().len(), 1);
        assert_eq!(ctx.changes()[0].field_name, "label");
    }

    #[test]
    fn ctx_record_change_sets_layout() {
        let id = make_node_id();
        let mut ctx = ReactiveCtx::new(id);
        ctx.record_change(
            "size",
            ReactiveFlags::reactive_layout(),
            Box::new(10_usize),
            Box::new(20_usize),
        );
        assert!(ctx.needs_repaint());
        assert!(ctx.needs_layout());
    }

    #[test]
    fn ctx_var_change_no_repaint() {
        let id = make_node_id();
        let mut ctx = ReactiveCtx::new(id);
        ctx.record_change(
            "counter",
            ReactiveFlags::var(),
            Box::new(0_u32),
            Box::new(1_u32),
        );
        assert!(!ctx.needs_repaint());
        assert!(!ctx.needs_layout());
        assert!(ctx.has_changes());
    }

    #[test]
    fn ctx_take_changes_drains() {
        let id = make_node_id();
        let mut ctx = ReactiveCtx::new(id);
        ctx.record_change(
            "a",
            ReactiveFlags::reactive(),
            Box::new(0_i32),
            Box::new(1_i32),
        );
        ctx.record_change(
            "b",
            ReactiveFlags::reactive(),
            Box::new(false),
            Box::new(true),
        );
        let changes = ctx.take_changes();
        assert_eq!(changes.len(), 2);
        assert!(ctx.changes().is_empty());
        // Flags remain set even after draining changes.
        assert!(ctx.needs_repaint());
    }

    #[test]
    fn ctx_clear_flags() {
        let id = make_node_id();
        let mut ctx = ReactiveCtx::new(id);
        ctx.record_change(
            "x",
            ReactiveFlags::reactive_layout(),
            Box::new(0_i32),
            Box::new(1_i32),
        );
        assert!(ctx.needs_repaint());
        assert!(ctx.needs_layout());
        ctx.clear_flags();
        assert!(!ctx.needs_repaint());
        assert!(!ctx.needs_layout());
    }

    #[test]
    fn ctx_multiple_changes_accumulate() {
        let id = make_node_id();
        let mut ctx = ReactiveCtx::new(id);
        // First change: var (no repaint)
        ctx.record_change(
            "counter",
            ReactiveFlags::var(),
            Box::new(0_u32),
            Box::new(1_u32),
        );
        assert!(!ctx.needs_repaint());
        // Second change: reactive (repaint)
        ctx.record_change(
            "label",
            ReactiveFlags::reactive(),
            Box::new("a".to_string()),
            Box::new("b".to_string()),
        );
        assert!(ctx.needs_repaint());
        assert_eq!(ctx.changes().len(), 2);
    }

    #[test]
    fn change_old_new_downcast() {
        let id = make_node_id();
        let mut ctx = ReactiveCtx::new(id);
        ctx.record_change(
            "value",
            ReactiveFlags::reactive(),
            Box::new(42_i32),
            Box::new(99_i32),
        );
        let change = &ctx.changes()[0];
        assert_eq!(*change.old_value.downcast_ref::<i32>().unwrap(), 42);
        assert_eq!(*change.new_value.downcast_ref::<i32>().unwrap(), 99);
    }

    #[test]
    fn reactive_widget_default_is_noop() {
        struct Dummy;
        impl ReactiveWidget for Dummy {}
        let mut dummy = Dummy;
        let id = make_node_id();
        let mut ctx = ReactiveCtx::new(id);
        // Should not panic.
        dummy.reactive_dispatch(&[], &mut ctx);
    }

    #[test]
    fn change_debug_impl() {
        let change = ReactiveChange {
            field_name: "test",
            flags: ReactiveFlags::reactive(),
            old_value: Box::new(1_i32),
            new_value: Box::new(2_i32),
        };
        let debug_str = format!("{:?}", change);
        assert!(debug_str.contains("test"));
        assert!(debug_str.contains("type-erased"));
    }

    #[test]
    fn reactive_flags_always_update() {
        let flags = ReactiveFlags::reactive_always_update();
        assert!(flags.repaint);
        assert!(!flags.layout);
        assert!(flags.init);
        assert!(flags.always_update);
    }

    #[test]
    fn reactive_flags_default_not_always_update() {
        assert!(!ReactiveFlags::reactive().always_update);
        assert!(!ReactiveFlags::var().always_update);
        assert!(!ReactiveFlags::reactive_layout().always_update);
    }
}