windjammer-ui 0.3.6

Cross-platform UI framework for Windjammer (Web, Desktop, Mobile)
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
//! Fine-grained reactivity system for Windjammer UI
//!
//! This module provides automatic dependency tracking and fine-grained updates.
//! Inspired by Solid.js, Vue 3, and Leptos.
//!
//! # Example
//!
//! ```rust
//! use windjammer_ui::reactivity::*;
//!
//! let count = Signal::new(0);
//! let doubled = Computed::new({
//!     let count = count.clone();
//!     move || count.get() * 2
//! });
//!
//! // Effect runs immediately and re-runs when count changes
//! create_effect({
//!     let doubled = doubled.clone();
//!     move || {
//!         println!("Doubled: {}", doubled.get());
//!     }
//! });
//!
//! count.set(5); // Prints: "Doubled: 10"
//! ```

use std::cell::RefCell;
use std::collections::{HashMap, HashSet};
use std::rc::Rc;
use std::sync::atomic::{AtomicUsize, Ordering};

/// Unique identifier for signals
pub type SignalId = usize;

/// Unique identifier for effects
pub type EffectId = usize;

// Global reactive context (thread-local for single-threaded WASM)
thread_local! {
    static REACTIVE_CONTEXT: RefCell<ReactiveContext> = RefCell::new(ReactiveContext::new());
    static EFFECT_REGISTRY: RefCell<HashMap<EffectId, EffectHandle>> = RefCell::new(HashMap::new());
}

/// Reactive context tracks the current effect being executed
struct ReactiveContext {
    /// The effect currently being executed (for dependency tracking)
    current_effect: Option<EffectId>,
    /// Cleanup functions to run when effects are disposed
    cleanups: HashMap<EffectId, Vec<Box<dyn Fn()>>>,
}

impl ReactiveContext {
    fn new() -> Self {
        Self {
            current_effect: None,
            cleanups: HashMap::new(),
        }
    }
}

/// Handle to an effect for execution
struct EffectHandle {
    f: Rc<dyn Fn()>,
}

/// Core reactive primitive - a value that notifies subscribers when it changes
#[derive(Clone)]
pub struct Signal<T: Clone> {
    id: SignalId,
    value: Rc<RefCell<T>>,
    subscribers: Rc<RefCell<HashSet<EffectId>>>,
}

impl<T: Clone> Signal<T> {
    /// Create a new signal with an initial value
    pub fn new(value: T) -> Self {
        static NEXT_ID: AtomicUsize = AtomicUsize::new(0);
        Self {
            id: NEXT_ID.fetch_add(1, Ordering::Relaxed),
            value: Rc::new(RefCell::new(value)),
            subscribers: Rc::new(RefCell::new(HashSet::new())),
        }
    }

    /// Get the current value (tracks dependency in reactive context)
    pub fn get(&self) -> T {
        // Track this read in the current reactive context
        REACTIVE_CONTEXT.with(|ctx| {
            let ctx = ctx.borrow();
            if let Some(effect_id) = ctx.current_effect {
                self.subscribers.borrow_mut().insert(effect_id);
            }
        });

        self.value.borrow().clone()
    }

    /// Get the current value without tracking (for debugging)
    pub fn get_untracked(&self) -> T {
        self.value.borrow().clone()
    }

    /// Set a new value and notify subscribers
    pub fn set(&self, value: T) {
        *self.value.borrow_mut() = value;
        self.notify();
    }

    /// Update the value using a function and notify subscribers
    pub fn update<F>(&self, f: F)
    where
        F: FnOnce(&mut T),
    {
        f(&mut self.value.borrow_mut());
        self.notify();
    }

    /// Notify all subscribers that the value has changed
    fn notify(&self) {
        let subscribers = self.subscribers.borrow().clone();
        for effect_id in subscribers {
            EFFECT_REGISTRY.with(|registry| {
                if let Some(effect) = registry.borrow().get(&effect_id) {
                    (effect.f)();
                }
            });
        }

        // Trigger UI re-render if we're in a WASM context
        #[cfg(target_arch = "wasm32")]
        {
            crate::app_reactive::trigger_rerender();
        }

        // Trigger UI re-render for desktop apps
        #[cfg(all(not(target_arch = "wasm32"), feature = "desktop"))]
        {
            crate::desktop_app_context::trigger_repaint();
        }
    }

    /// Get the signal's unique ID
    pub fn id(&self) -> SignalId {
        self.id
    }
}

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

/// Computed signal - a derived value that automatically updates when dependencies change
#[derive(Clone)]
pub struct Computed<T: Clone> {
    signal: Signal<T>,
    _effect_id: EffectId,
}

impl<T: Clone + 'static> Computed<T> {
    /// Create a new computed value
    pub fn new<F>(compute: F) -> Self
    where
        F: Fn() -> T + 'static,
    {
        let compute = Rc::new(compute);

        // Compute initial value
        let initial_value = compute();
        let signal = Signal::new(initial_value);

        // Create effect that updates signal when dependencies change
        let signal_clone = signal.clone();
        let compute_clone = compute.clone();
        let effect_id = Effect::new(move || {
            let new_value = compute_clone();
            // Use direct assignment to avoid infinite loops
            *signal_clone.value.borrow_mut() = new_value;
        });

        Self {
            signal,
            _effect_id: effect_id,
        }
    }

    /// Get the current computed value (tracks dependency)
    pub fn get(&self) -> T {
        self.signal.get()
    }

    /// Get the current computed value without tracking
    pub fn get_untracked(&self) -> T {
        self.signal.get_untracked()
    }
}

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

/// Effect - a side effect that runs when its dependencies change
pub struct Effect {
    _id: EffectId,
}

impl Effect {
    /// Create a new effect
    #[allow(clippy::new_ret_no_self)]
    pub fn new<F>(f: F) -> EffectId
    where
        F: Fn() + 'static,
    {
        static NEXT_ID: AtomicUsize = AtomicUsize::new(0);
        let id = NEXT_ID.fetch_add(1, Ordering::Relaxed);
        let f: Rc<dyn Fn()> = Rc::new(f);

        // Register effect
        EFFECT_REGISTRY.with(|registry| {
            registry
                .borrow_mut()
                .insert(id, EffectHandle { f: f.clone() });
        });

        // Run effect once to establish dependencies
        Self::run_effect(id, f.clone());

        id
    }

    /// Run an effect with the given ID as the current reactive context
    fn run_effect(id: EffectId, f: Rc<dyn Fn()>) {
        REACTIVE_CONTEXT.with(|ctx| {
            // Save previous effect
            let prev_effect = ctx.borrow().current_effect;

            // Set current effect
            ctx.borrow_mut().current_effect = Some(id);

            // Run the effect
            f();

            // Restore previous effect
            ctx.borrow_mut().current_effect = prev_effect;
        });
    }

    /// Dispose of an effect (stop tracking and run cleanup)
    pub fn dispose(id: EffectId) {
        // Run cleanup functions
        REACTIVE_CONTEXT.with(|ctx| {
            if let Some(cleanups) = ctx.borrow_mut().cleanups.remove(&id) {
                for cleanup in cleanups {
                    cleanup();
                }
            }
        });

        // Remove from registry
        EFFECT_REGISTRY.with(|registry| {
            registry.borrow_mut().remove(&id);
        });
    }
}

/// Register a cleanup function to run when the current effect is disposed
pub fn on_cleanup<F>(cleanup: F)
where
    F: Fn() + 'static,
{
    REACTIVE_CONTEXT.with(|ctx| {
        let mut ctx = ctx.borrow_mut();
        if let Some(effect_id) = ctx.current_effect {
            ctx.cleanups
                .entry(effect_id)
                .or_insert_with(Vec::new)
                .push(Box::new(cleanup));
        }
    });
}

/// Create a reactive scope that tracks dependencies
pub fn create_effect<F>(f: F) -> EffectId
where
    F: Fn() + 'static,
{
    Effect::new(f)
}

/// Create a computed value
pub fn create_computed<T, F>(compute: F) -> Computed<T>
where
    T: Clone + 'static,
    F: Fn() -> T + 'static,
{
    Computed::new(compute)
}

/// Create a signal
pub fn create_signal<T: Clone>(value: T) -> Signal<T> {
    Signal::new(value)
}

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

    #[test]
    fn test_signal_basic() {
        let count = Signal::new(0);
        assert_eq!(count.get(), 0);

        count.set(5);
        assert_eq!(count.get(), 5);

        count.update(|c| *c += 10);
        assert_eq!(count.get(), 15);
    }

    #[test]
    fn test_signal_effect() {
        let count = Signal::new(0);
        let result = Rc::new(RefCell::new(0));

        let result_clone = result.clone();
        let count_clone = count.clone();
        Effect::new(move || {
            *result_clone.borrow_mut() = count_clone.get() * 2;
        });

        assert_eq!(*result.borrow(), 0);

        count.set(5);
        assert_eq!(*result.borrow(), 10);

        count.set(10);
        assert_eq!(*result.borrow(), 20);
    }

    #[test]
    fn test_computed() {
        let count = Signal::new(5);
        let count_clone = count.clone();
        let doubled = Computed::new(move || count_clone.get() * 2);

        assert_eq!(doubled.get(), 10);

        count.set(10);
        assert_eq!(doubled.get(), 20);

        count.set(7);
        assert_eq!(doubled.get(), 14);
    }

    #[test]
    fn test_multiple_dependencies() {
        let a = Signal::new(2);
        let b = Signal::new(3);

        let a_clone = a.clone();
        let b_clone = b.clone();
        let sum = Computed::new(move || a_clone.get() + b_clone.get());

        assert_eq!(sum.get(), 5);

        a.set(10);
        assert_eq!(sum.get(), 13);

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

    #[test]
    fn test_effect_runs_immediately() {
        let ran = Rc::new(RefCell::new(false));
        let ran_clone = ran.clone();

        Effect::new(move || {
            *ran_clone.borrow_mut() = true;
        });

        assert!(*ran.borrow());
    }

    #[test]
    fn test_untracked_read() {
        let count = Signal::new(0);
        let effect_count = Rc::new(RefCell::new(0));

        let effect_count_clone = effect_count.clone();
        let count_clone = count.clone();
        Effect::new(move || {
            // This should not trigger on untracked changes
            let _ = count_clone.get_untracked();
            *effect_count_clone.borrow_mut() += 1;
        });

        assert_eq!(*effect_count.borrow(), 1); // Initial run

        count.set(5);
        assert_eq!(*effect_count.borrow(), 1); // Should not re-run
    }

    #[test]
    fn test_nested_effects() {
        let count = Signal::new(0);
        let doubled = Rc::new(RefCell::new(0));
        let quadrupled = Rc::new(RefCell::new(0));

        // First effect: doubled = count * 2
        let doubled_clone = doubled.clone();
        let count_clone = count.clone();
        Effect::new(move || {
            *doubled_clone.borrow_mut() = count_clone.get() * 2;
        });

        // Second effect: quadrupled = doubled * 2
        let quadrupled_clone = quadrupled.clone();
        let doubled_clone2 = doubled.clone();
        Effect::new(move || {
            *quadrupled_clone.borrow_mut() = *doubled_clone2.borrow() * 2;
        });

        assert_eq!(*doubled.borrow(), 0);
        assert_eq!(*quadrupled.borrow(), 0);

        count.set(5);
        assert_eq!(*doubled.borrow(), 10);
        // Note: quadrupled won't update automatically because it doesn't depend on a signal
        // This is expected behavior - effects only track signal reads
    }
}