ftui-runtime 0.4.0

Elm-style runtime loop and subscriptions for FrankenTUI.
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
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
#![forbid(unsafe_code)]

//! Ergonomic binding utilities for connecting [`Observable`] values to UI state.
//!
//! A [`Binding<T>`] encapsulates an observable source plus an optional transform,
//! making it easy to derive display values from reactive state. The [`bind!`] and
//! [`bind_map!`] macros provide syntactic sugar.
//!
//! # Usage
//!
//! ```ignore
//! use ftui_runtime::reactive::{Observable, Binding, bind, bind_map};
//!
//! let count = Observable::new(0);
//!
//! // Direct binding — get() returns the observable's value.
//! let b = bind!(count);
//! assert_eq!(b.get(), 0);
//!
//! // Mapped binding — get() returns the transformed value.
//! let label = bind_map!(count, |c| format!("Count: {c}"));
//! assert_eq!(label.get(), "Count: 0");
//!
//! count.set(5);
//! assert_eq!(b.get(), 5);
//! assert_eq!(label.get(), "Count: 5");
//! ```
//!
//! # Two-Way Bindings
//!
//! [`TwoWayBinding<T>`] connects two `Observable`s so changes to either
//! propagate to the other, with cycle prevention.
//!
//! ```ignore
//! let source = Observable::new(42);
//! let target = Observable::new(0);
//! let _binding = TwoWayBinding::new(&source, &target);
//!
//! source.set(10);
//! assert_eq!(target.get(), 10);
//!
//! target.set(20);
//! assert_eq!(source.get(), 20);
//! ```
//!
//! # Invariants
//!
//! 1. `Binding::get()` always returns the current (not stale) value.
//! 2. A binding's transform is applied on every `get()` call (no caching).
//!    Use [`Computed`] when memoization is needed.
//! 3. `TwoWayBinding` prevents infinite cycles via a re-entrancy guard.
//! 4. Dropping a `TwoWayBinding` cleanly unsubscribes both directions.
//! 5. Bindings are `Clone` when the source `Observable` is (shared state).
//!
//! # Failure Modes
//!
//! - Transform panic: propagates to caller of `get()`.
//! - Source dropped while binding alive: binding still works (Rc keeps inner alive).
//!
//! [`Computed`]: super::Computed

use std::cell::Cell;
use std::rc::Rc;

use super::observable::{Observable, Subscription};

// ---------------------------------------------------------------------------
// Binding<T> — one-way read binding
// ---------------------------------------------------------------------------

/// A read-only binding to an [`Observable`] value with an optional transform.
///
/// Evaluates lazily on each `get()` call. For memoized transforms, prefer
/// [`Computed`](super::Computed).
pub struct Binding<T> {
    eval: Rc<dyn Fn() -> T>,
}

impl<T> Clone for Binding<T> {
    fn clone(&self) -> Self {
        Self {
            eval: Rc::clone(&self.eval),
        }
    }
}

impl<T: std::fmt::Debug + 'static> std::fmt::Debug for Binding<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Binding")
            .field("value", &self.get())
            .finish()
    }
}

impl<T: 'static> Binding<T> {
    /// Create a binding that evaluates `f` on each `get()` call.
    pub fn new(f: impl Fn() -> T + 'static) -> Self {
        Self { eval: Rc::new(f) }
    }

    /// Get the current bound value.
    #[must_use]
    pub fn get(&self) -> T {
        (self.eval)()
    }

    /// Apply a further transform, returning a new `Binding`.
    pub fn then<U: 'static>(self, f: impl Fn(T) -> U + 'static) -> Binding<U> {
        Binding {
            eval: Rc::new(move || f((self.eval)())),
        }
    }
}

/// Create a direct binding to an observable (identity transform).
pub fn bind_observable<T: Clone + PartialEq + 'static>(source: &Observable<T>) -> Binding<T> {
    let src = source.clone();
    Binding {
        eval: Rc::new(move || src.get()),
    }
}

/// Create a mapped binding: `source` value transformed by `map`.
pub fn bind_mapped<S: Clone + PartialEq + 'static, T: 'static>(
    source: &Observable<S>,
    map: impl Fn(&S) -> T + 'static,
) -> Binding<T> {
    let src = source.clone();
    Binding {
        eval: Rc::new(move || src.with(|v| map(v))),
    }
}

/// Create a binding from two observables combined by `map`.
pub fn bind_mapped2<
    S1: Clone + PartialEq + 'static,
    S2: Clone + PartialEq + 'static,
    T: 'static,
>(
    s1: &Observable<S1>,
    s2: &Observable<S2>,
    map: impl Fn(&S1, &S2) -> T + 'static,
) -> Binding<T> {
    let src1 = s1.clone();
    let src2 = s2.clone();
    Binding {
        eval: Rc::new(move || src1.with(|v1| src2.with(|v2| map(v1, v2)))),
    }
}

// ---------------------------------------------------------------------------
// TwoWayBinding<T> — bidirectional sync
// ---------------------------------------------------------------------------

/// Bidirectional binding between two [`Observable`]s of the same type.
///
/// Changes to either observable propagate to the other. A re-entrancy guard
/// prevents infinite update cycles.
///
/// Drop the `TwoWayBinding` to disconnect both directions.
pub struct TwoWayBinding<T: Clone + PartialEq + 'static> {
    _sub_a_to_b: Subscription,
    _sub_b_to_a: Subscription,
    _guard: Rc<Cell<bool>>,
    _phantom: std::marker::PhantomData<T>,
}

impl<T: Clone + PartialEq + 'static> TwoWayBinding<T> {
    /// Create a two-way binding between `a` and `b`.
    ///
    /// Initially syncs `b` to `a`'s current value. Subsequent changes to
    /// either side propagate to the other.
    pub fn new(a: &Observable<T>, b: &Observable<T>) -> Self {
        // Sync initial value: b takes a's value.
        b.set(a.get());

        let syncing = Rc::new(Cell::new(false));

        struct ReentrancyGuard<'a>(&'a Cell<bool>);
        impl<'a> Drop for ReentrancyGuard<'a> {
            fn drop(&mut self) {
                self.0.set(false);
            }
        }

        // a → b
        let b_clone = b.clone();
        let guard_ab = Rc::clone(&syncing);
        let sub_ab = a.subscribe(move |val| {
            if !guard_ab.get() {
                guard_ab.set(true);
                let _guard = ReentrancyGuard(&guard_ab);
                b_clone.set(val.clone());
            }
        });

        // b → a
        let a_clone = a.clone();
        let guard_ba = Rc::clone(&syncing);
        let sub_ba = b.subscribe(move |val| {
            if !guard_ba.get() {
                guard_ba.set(true);
                let _guard = ReentrancyGuard(&guard_ba);
                a_clone.set(val.clone());
            }
        });

        Self {
            _sub_a_to_b: sub_ab,
            _sub_b_to_a: sub_ba,
            _guard: syncing,
            _phantom: std::marker::PhantomData,
        }
    }
}

impl<T: Clone + PartialEq + 'static> std::fmt::Debug for TwoWayBinding<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("TwoWayBinding").finish()
    }
}

// ---------------------------------------------------------------------------
// Macros
// ---------------------------------------------------------------------------

/// Create a direct [`Binding`] to an observable.
///
/// # Examples
///
/// ```ignore
/// let count = Observable::new(0);
/// let b = bind!(count);
/// assert_eq!(b.get(), 0);
/// ```
#[macro_export]
macro_rules! bind {
    ($obs:expr) => {
        $crate::reactive::binding::bind_observable(&$obs)
    };
}

/// Create a mapped [`Binding`] from an observable with a transform function.
///
/// # Examples
///
/// ```ignore
/// let count = Observable::new(0);
/// let label = bind_map!(count, |c| format!("Count: {c}"));
/// assert_eq!(label.get(), "Count: 0");
/// ```
#[macro_export]
macro_rules! bind_map {
    ($obs:expr, $f:expr) => {
        $crate::reactive::binding::bind_mapped(&$obs, $f)
    };
}

/// Create a mapped [`Binding`] from two observables.
///
/// # Examples
///
/// ```ignore
/// let width = Observable::new(10);
/// let height = Observable::new(20);
/// let area = bind_map2!(width, height, |w, h| w * h);
/// assert_eq!(area.get(), 200);
/// ```
#[macro_export]
macro_rules! bind_map2 {
    ($s1:expr, $s2:expr, $f:expr) => {
        $crate::reactive::binding::bind_mapped2(&$s1, &$s2, $f)
    };
}

// ---------------------------------------------------------------------------
// BindingScope — lifecycle management
// ---------------------------------------------------------------------------

/// Collects subscriptions and bindings for a logical scope (e.g., a widget).
///
/// When the scope is dropped, all held subscriptions are released, cleanly
/// disconnecting all reactive bindings associated with that scope.
///
/// # Usage
///
/// ```ignore
/// let mut scope = BindingScope::new();
///
/// let obs = Observable::new(42);
/// scope.subscribe(&obs, |v| println!("value: {v}"));
/// scope.bind(&obs, |v| format!("display: {v}"));
///
/// // When scope drops, all subscriptions are released.
/// ```
///
/// # Invariants
///
/// 1. Subscriptions are released in reverse registration order on drop.
/// 2. After drop, no callbacks from this scope will fire.
/// 3. `clear()` releases all subscriptions immediately (reusable scope).
/// 4. Binding count is always accurate.
pub struct BindingScope {
    subscriptions: Vec<Subscription>,
}

impl BindingScope {
    /// Create an empty binding scope.
    #[must_use]
    pub fn new() -> Self {
        Self {
            subscriptions: Vec::new(),
        }
    }

    /// Add a subscription to this scope. The subscription will be held alive
    /// until the scope is dropped or `clear()` is called.
    pub fn hold(&mut self, sub: Subscription) {
        self.subscriptions.push(sub);
    }

    /// Subscribe to an observable within this scope.
    ///
    /// Returns a reference to the scope for chaining.
    pub fn subscribe<T: Clone + PartialEq + 'static>(
        &mut self,
        source: &Observable<T>,
        callback: impl Fn(&T) + 'static,
    ) -> &mut Self {
        let sub = source.subscribe(callback);
        self.subscriptions.push(sub);
        self
    }

    /// Create a one-way binding within this scope.
    ///
    /// The binding's underlying subscription is held by the scope.
    /// Returns the `Binding<T>` for reading the value.
    pub fn bind<T: Clone + PartialEq + 'static>(&mut self, source: &Observable<T>) -> Binding<T> {
        bind_observable(source)
    }

    /// Create a mapped binding within this scope.
    pub fn bind_map<S: Clone + PartialEq + 'static, T: 'static>(
        &mut self,
        source: &Observable<S>,
        map: impl Fn(&S) -> T + 'static,
    ) -> Binding<T> {
        bind_mapped(source, map)
    }

    /// Number of active subscriptions/bindings in this scope.
    #[must_use]
    pub fn binding_count(&self) -> usize {
        self.subscriptions.len()
    }

    /// Whether the scope has no active bindings.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.subscriptions.is_empty()
    }

    /// Release all subscriptions immediately (scope becomes empty but reusable).
    pub fn clear(&mut self) {
        self.subscriptions.clear();
    }
}

impl Default for BindingScope {
    fn default() -> Self {
        Self::new()
    }
}

impl std::fmt::Debug for BindingScope {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("BindingScope")
            .field("binding_count", &self.subscriptions.len())
            .finish()
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    #[test]
    fn binding_from_observable() {
        let obs = Observable::new(42);
        let b = bind_observable(&obs);
        assert_eq!(b.get(), 42);

        obs.set(100);
        assert_eq!(b.get(), 100);
    }

    #[test]
    fn binding_map() {
        let count = Observable::new(3);
        let label = bind_mapped(&count, |c| format!("items: {c}"));
        assert_eq!(label.get(), "items: 3");

        count.set(7);
        assert_eq!(label.get(), "items: 7");
    }

    #[test]
    fn binding_map2() {
        let w = Observable::new(10);
        let h = Observable::new(20);
        let area = bind_mapped2(&w, &h, |a, b| a * b);
        assert_eq!(area.get(), 200);

        w.set(5);
        assert_eq!(area.get(), 100);
    }

    #[test]
    fn binding_then_chain() {
        let obs = Observable::new(5);
        let doubled = bind_observable(&obs).then(|v| v * 2);
        assert_eq!(doubled.get(), 10);

        obs.set(3);
        assert_eq!(doubled.get(), 6);
    }

    #[test]
    fn binding_clone_shares_source() {
        let obs = Observable::new(1);
        let b1 = bind_observable(&obs);
        let b2 = b1.clone();

        obs.set(99);
        assert_eq!(b1.get(), 99);
        assert_eq!(b2.get(), 99);
    }

    #[test]
    fn binding_new_custom() {
        let counter = Rc::new(Cell::new(0));
        let c = Rc::clone(&counter);
        let b = Binding::new(move || {
            c.set(c.get() + 1);
            c.get()
        });
        assert_eq!(b.get(), 1);
        assert_eq!(b.get(), 2);
    }

    #[test]
    fn bind_macro() {
        let obs = Observable::new(42);
        let b = bind!(obs);
        assert_eq!(b.get(), 42);
    }

    #[test]
    fn bind_map_macro() {
        let obs = Observable::new(5);
        let b = bind_map!(obs, |v| v * 10);
        assert_eq!(b.get(), 50);
    }

    #[test]
    fn bind_map2_macro() {
        let a = Observable::new(3);
        let b = Observable::new(4);
        let sum = bind_map2!(a, b, |x, y| x + y);
        assert_eq!(sum.get(), 7);
    }

    // ---- Two-way binding tests ----

    #[test]
    fn two_way_initial_sync() {
        let a = Observable::new(10);
        let b = Observable::new(0);
        let _binding = TwoWayBinding::new(&a, &b);
        assert_eq!(b.get(), 10, "b should sync to a's initial value");
    }

    #[test]
    fn two_way_a_to_b() {
        let a = Observable::new(1);
        let b = Observable::new(0);
        let _binding = TwoWayBinding::new(&a, &b);

        a.set(42);
        assert_eq!(b.get(), 42);
    }

    #[test]
    fn two_way_b_to_a() {
        let a = Observable::new(1);
        let b = Observable::new(0);
        let _binding = TwoWayBinding::new(&a, &b);

        b.set(99);
        assert_eq!(a.get(), 99);
    }

    #[test]
    fn two_way_no_cycle() {
        let a = Observable::new(0);
        let b = Observable::new(0);
        let _binding = TwoWayBinding::new(&a, &b);

        // Set a → should propagate to b but not cycle back.
        a.set(5);
        assert_eq!(a.get(), 5);
        assert_eq!(b.get(), 5);

        b.set(10);
        assert_eq!(a.get(), 10);
        assert_eq!(b.get(), 10);
    }

    #[test]
    fn two_way_drop_disconnects() {
        let a = Observable::new(1);
        let b = Observable::new(0);
        {
            let _binding = TwoWayBinding::new(&a, &b);
            a.set(5);
            assert_eq!(b.get(), 5);
        }
        // After drop, changes should not propagate.
        a.set(100);
        assert_eq!(b.get(), 5, "b should not update after binding dropped");
    }

    #[test]
    fn two_way_with_strings() {
        let a = Observable::new(String::from("hello"));
        let b = Observable::new(String::new());
        let _binding = TwoWayBinding::new(&a, &b);

        assert_eq!(b.get(), "hello");
        b.set("world".to_string());
        assert_eq!(a.get(), "world");
    }

    #[test]
    fn multiple_bindings_same_source() {
        let source = Observable::new(0);
        let b1 = bind_observable(&source);
        let b2 = bind_mapped(&source, |v| v * 2);
        let b3 = bind_mapped(&source, |v| format!("{v}"));

        source.set(5);
        assert_eq!(b1.get(), 5);
        assert_eq!(b2.get(), 10);
        assert_eq!(b3.get(), "5");
    }

    #[test]
    fn binding_survives_source_clone() {
        let source = Observable::new(42);
        let b = bind_observable(&source);

        let source2 = source.clone();
        source2.set(99);
        assert_eq!(
            b.get(),
            99,
            "binding should see changes through cloned observable"
        );
    }

    // ---- BindingScope tests ----

    #[test]
    fn scope_holds_subscriptions() {
        let obs = Observable::new(0);
        let seen = Rc::new(Cell::new(0));

        let mut scope = BindingScope::new();
        let s = Rc::clone(&seen);
        scope.subscribe(&obs, move |v| s.set(*v));
        assert_eq!(scope.binding_count(), 1);

        obs.set(42);
        assert_eq!(seen.get(), 42);
    }

    #[test]
    fn scope_drop_releases_subscriptions() {
        let obs = Observable::new(0);
        let seen = Rc::new(Cell::new(0));

        {
            let mut scope = BindingScope::new();
            let s = Rc::clone(&seen);
            scope.subscribe(&obs, move |v| s.set(*v));
            obs.set(1);
            assert_eq!(seen.get(), 1);
        }

        // After scope dropped, subscription should be gone.
        obs.set(99);
        assert_eq!(
            seen.get(),
            1,
            "callback should not fire after scope dropped"
        );
    }

    #[test]
    fn scope_clear_releases() {
        let obs = Observable::new(0);
        let seen = Rc::new(Cell::new(0));

        let mut scope = BindingScope::new();
        let s = Rc::clone(&seen);
        scope.subscribe(&obs, move |v| s.set(*v));
        assert_eq!(scope.binding_count(), 1);

        scope.clear();
        assert_eq!(scope.binding_count(), 0);
        assert!(scope.is_empty());

        obs.set(42);
        assert_eq!(seen.get(), 0, "callback should not fire after clear");
    }

    #[test]
    fn scope_multiple_subscriptions() {
        let obs = Observable::new(0);
        let count = Rc::new(Cell::new(0));

        let mut scope = BindingScope::new();
        for _ in 0..5 {
            let c = Rc::clone(&count);
            scope.subscribe(&obs, move |_| c.set(c.get() + 1));
        }
        assert_eq!(scope.binding_count(), 5);

        obs.set(1);
        assert_eq!(count.get(), 5, "all 5 callbacks should fire");
    }

    #[test]
    fn scope_bind_returns_binding() {
        let obs = Observable::new(42);
        let mut scope = BindingScope::new();
        let b = scope.bind(&obs);
        assert_eq!(b.get(), 42);

        obs.set(7);
        assert_eq!(b.get(), 7);
    }

    #[test]
    fn scope_bind_map() {
        let obs = Observable::new(3);
        let mut scope = BindingScope::new();
        let b = scope.bind_map(&obs, |v| v * 10);
        assert_eq!(b.get(), 30);
    }

    #[test]
    fn scope_reusable_after_clear() {
        let obs = Observable::new(0);
        let mut scope = BindingScope::new();

        let seen1 = Rc::new(Cell::new(false));
        let s1 = Rc::clone(&seen1);
        scope.subscribe(&obs, move |_| s1.set(true));
        scope.clear();

        let seen2 = Rc::new(Cell::new(false));
        let s2 = Rc::clone(&seen2);
        scope.subscribe(&obs, move |_| s2.set(true));

        obs.set(1);
        assert!(!seen1.get(), "first subscription should be gone");
        assert!(seen2.get(), "second subscription should be active");
    }

    #[test]
    fn scope_hold_external_subscription() {
        let obs = Observable::new(0);
        let seen = Rc::new(Cell::new(0));

        let mut scope = BindingScope::new();
        let s = Rc::clone(&seen);
        let sub = obs.subscribe(move |v| s.set(*v));
        scope.hold(sub);

        obs.set(5);
        assert_eq!(seen.get(), 5);

        drop(scope);
        obs.set(99);
        assert_eq!(
            seen.get(),
            5,
            "held subscription should be released on scope drop"
        );
    }

    #[test]
    fn scope_debug_format() {
        let mut scope = BindingScope::new();
        let obs = Observable::new(0);
        scope.subscribe(&obs, |_| {});
        scope.subscribe(&obs, |_| {});
        let debug = format!("{scope:?}");
        assert!(debug.contains("binding_count: 2"));
    }
}