xengui 0.2.7

a retained-mode gui library in rust
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
// SPDX-License-Identifier: Apache-2.0
use smol_str::SmolStr;
use std::any::Any;
use std::cell::{ Cell, RefCell };
use std::collections::{ HashMap, HashSet };
use std::marker::PhantomData;
use std::rc::Rc;
use crate::RedrawRequester;

#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct ComponentId(SmolStr);

impl ComponentId {
    pub fn root() -> Self {
        Self(SmolStr::new("root"))
    }

    pub fn as_str(&self) -> &str {
        self.0.as_str()
    }
}

#[derive(Clone, Debug)]
pub struct ComponentKey(SmolStr);

impl From<&str> for ComponentKey {
    fn from(v: &str) -> Self {
        Self(SmolStr::new(v))
    }
}

impl From<String> for ComponentKey {
    fn from(v: String) -> Self {
        Self(SmolStr::new(v))
    }
}

impl From<SmolStr> for ComponentKey {
    fn from(v: SmolStr) -> Self {
        Self(v)
    }
}

macro_rules! impl_component_key_from_int {
    ($($t:ty),*) => {
        $(
            impl From<$t> for ComponentKey {
                fn from(v: $t) -> Self {
                    Self(SmolStr::new(v.to_string()))
                }
            }
        )*
    };
}
impl_component_key_from_int!(u8, u16, u32, u64, usize, i8, i16, i32, i64, isize);

struct ComponentState {
    slots: Vec<Rc<RefCell<Box<dyn Any>>>>,
    cursor: usize,
}

impl ComponentState {
    fn new() -> Self {
        Self { slots: Vec::new(), cursor: 0 }
    }
}

thread_local! {
    static HOOK_STORE: RefCell<HashMap<ComponentId, ComponentState>> = RefCell::new(HashMap::new());

    static COMPONENT_STACK: RefCell<Vec<ComponentId>> = const { RefCell::new(Vec::new()) };

    static LIVE_COMPONENTS: RefCell<HashSet<ComponentId>> = RefCell::new(HashSet::new());

    static DIRTY: Cell<bool> = const { Cell::new(false) };

    static REDRAW_HANDLE: RefCell<Option<Rc<dyn RedrawRequester>>> = const { RefCell::new(None) };

    static RENDER_GENERATION: Cell<u64> = const { Cell::new(0) };

    static PENDING_EFFECTS: RefCell<Vec<PendingEffect>> = const { RefCell::new(Vec::new()) };
}

pub fn begin_render() {
    // Lets a render whose reconciliation gets superseded before finishing
    // be identified later, so its queued effects are never executed.
    RENDER_GENERATION.with(|g| g.set(g.get() + 1));
    LIVE_COMPONENTS.with(|s| s.borrow_mut().clear());
    COMPONENT_STACK.with(|s| {
        let mut s = s.borrow_mut();
        debug_assert!(
            s.is_empty(),
            "xengui hooks: component stack is not empty - begin_render/end_render may have been called unevenly"
        );
        s.clear();
    });
}

pub fn end_render() {
    LIVE_COMPONENTS.with(|live| {
        let live = live.borrow();
        HOOK_STORE.with(|store| {
            store.borrow_mut().retain(|id, state| {
                let keep = live.contains(id);
                if !keep {
                    run_unmount_cleanups(state);
                }
                keep
            });
        });
    });
}

// Runs (and clears) every effect cleanup left behind by a component that
// didn't appear in this render pass, since it will never build again.
fn run_unmount_cleanups(state: &ComponentState) {
    for slot in &state.slots {
        let cleanup = slot
            .borrow_mut()
            .downcast_mut::<EffectRecord>()
            .and_then(|record| record.cleanup.take());

        if let Some(cleanup) = cleanup {
            cleanup();
        }
    }
}

pub fn take_dirty() -> bool {
    DIRTY.with(|d| d.replace(false))
}

pub fn set_redraw_handle(handle: Rc<dyn RedrawRequester>) {
    REDRAW_HANDLE.with(|h| {
        *h.borrow_mut() = Some(handle);
    });
}

fn request_redraw() {
    REDRAW_HANDLE.with(|h| {
        if let Some(handle) = h.borrow().as_ref() {
            handle.request_redraw();
        }
    });
}

fn current_component_id() -> ComponentId {
    COMPONENT_STACK.with(|s| {
        s.borrow()
            .last()
            .cloned()
            .unwrap_or_else(|| {
                panic!(
                    "use_state: called outside a component() scope. \
                 use_state can only be used within App::render's root function or \
                 inside a component(key, ...) scope."
                )
            })
    })
}

fn push_component(key: ComponentKey) -> ComponentId {
    let id = COMPONENT_STACK.with(|s| {
        match s.borrow().last() {
            Some(parent) =>
                ComponentId(SmolStr::new(format!("{}\u{1f}{}", parent.as_str(), key.0))),
            None => ComponentId(key.0),
        }
    });

    HOOK_STORE.with(|store| {
        let mut store = store.borrow_mut();
        let state = store.entry(id.clone()).or_insert_with(ComponentState::new);
        state.cursor = 0;
    });

    let first_time_this_frame = LIVE_COMPONENTS.with(|s| s.borrow_mut().insert(id.clone()));
    if !first_time_this_frame {
        log::warn!(
            "xengui: duplicate component key '{}' - used twice in the same frame. \
             In dynamic lists, give each item a unique key (like React's 'key' prop).",
            id.as_str()
        );
    }

    COMPONENT_STACK.with(|s| s.borrow_mut().push(id.clone()));
    id
}

fn pop_component() {
    COMPONENT_STACK.with(|s| {
        s.borrow_mut().pop();
    });
}

/// component(key, render).
///
/// ```ignore
/// let mut list_view = View::new().flex_direction(FlexDirection::Column);
/// for item in &items {
///     list_view = list_view.child(component(item.id, || {
///         let (checked, set_checked) = use_state(false);
///         Button::new()
///             .label(if checked { "✓" } else { "" })
///             .on_click(move |_ctx| set_checked.set(!checked))
///     }));
/// }
/// ```
pub fn component<R>(key: impl Into<ComponentKey>, render: impl FnOnce() -> R) -> R {
    push_component(key.into());
    let result = render();
    pop_component();
    result
}

/// Creates a state value that persists across component rebuilds.
///
/// `use_state` returns the current state value together with a setter that can
/// be used to update it. Calling [`SetState::set`] schedules the owning
/// component to be rebuilt with the new value.
///
/// State is preserved as long as the component's identity remains stable. When
/// rendering dynamic lists, assign a stable key to each component to ensure
/// that state is associated with the correct item.
///
/// ## Panics
///
/// Panics if the order of hook invocations changes between rebuilds. Hooks must
/// always be called unconditionally and in the same order on every rebuild.
///
/// ## Example
///
/// ```ignore
/// let (count, set_count) = use_state(0i32);
///
/// View::new().child(
///     Button::new()
///         .label(format!("Count: {count}"))
///         .on_click(move |_ctx| set_count.set(count + 1))
/// );
/// ```
pub fn use_state<T: Clone + 'static>(initial: T) -> (T, SetState<T>) {
    let id = current_component_id();

    let (slot, idx) = HOOK_STORE.with(|store| {
        let mut store = store.borrow_mut();
        let state = store
            .get_mut(&id)
            .expect("use_state: internal error - provided binding used without begin/push");

        let idx = state.cursor;
        state.cursor += 1;

        if idx == state.slots.len() {
            state.slots.push(Rc::new(RefCell::new(Box::new(initial) as Box<dyn Any>)));
        }

        (state.slots[idx].clone(), idx)
    });

    let value = {
        let borrowed = slot.borrow();
        borrowed
            .downcast_ref::<T>()
            .unwrap_or_else(|| {
                panic!(
                    "use_state: hook order broken in component '{}' (slot #{idx}) - do not call use_state conditionally (inside an if/loop). In dynamic lists, wrap each item in a component (e.g., component(key, ...)) to give it its own isolated hook order.",
                    id.as_str()
                )
            })
            .clone()
    };

    (
        value,
        SetState {
            slot,
            _marker: PhantomData,
        },
    )
}

pub struct SetState<T> {
    slot: Rc<RefCell<Box<dyn Any>>>,
    _marker: PhantomData<T>,
}

impl<T> Clone for SetState<T> {
    fn clone(&self) -> Self {
        Self {
            slot: self.slot.clone(),
            _marker: PhantomData,
        }
    }
}

impl<T: 'static> SetState<T> {
    pub fn set(&self, value: T) {
        *self.slot.borrow_mut() = Box::new(value);
        DIRTY.with(|d| d.set(true));
        request_redraw();
    }

    pub fn update(&self, f: impl FnOnce(&mut T)) {
        {
            let mut borrowed = self.slot.borrow_mut();
            let current = borrowed
                .downcast_mut::<T>()
                .expect("use_state: SetState<T> used with the wrong type");

            f(current);
        }
        DIRTY.with(|d| d.set(true));
        request_redraw();
    }
}

pub fn mark_dirty_and_redraw() {
    DIRTY.with(|d| d.set(true));
    request_redraw();
}

fn current_generation() -> u64 {
    RENDER_GENERATION.with(Cell::get)
}

/// Object-safe equality for an effect's whole dependency list, so
/// `use_effect` can accept `()`, arrays, or slices without needing one
/// concrete type shared across every call site.
trait StoredDeps: Any {
    fn eq_dyn(&self, other: &dyn StoredDeps) -> bool;
    fn as_any(&self) -> &dyn Any;
}

impl<T: PartialEq + 'static> StoredDeps for T {
    fn eq_dyn(&self, other: &dyn StoredDeps) -> bool {
        other
            .as_any()
            .downcast_ref::<T>()
            .is_some_and(|o| self == o)
    }

    fn as_any(&self) -> &dyn Any {
        self
    }
}

/// Opaque, erased snapshot of a `use_effect` dependency list, stored
/// between renders to decide whether the effect needs to run again.
pub struct DepsSnapshot(Box<dyn StoredDeps>);

fn deps_changed(old: &DepsSnapshot, new: &DepsSnapshot) -> bool {
    !old.0.eq_dyn(new.0.as_ref())
}

/// Converts a dependency list passed to [`use_effect`] into a comparable,
/// erased snapshot. Implemented for `()` (no dependencies - runs once),
/// owned arrays, and array/slice references.
pub trait EffectDeps {
    fn snapshot(self) -> DepsSnapshot;
}

impl EffectDeps for () {
    fn snapshot(self) -> DepsSnapshot {
        DepsSnapshot(Box::new(()))
    }
}

impl<T: PartialEq + 'static, const N: usize> EffectDeps for [T; N] {
    fn snapshot(self) -> DepsSnapshot {
        DepsSnapshot(Box::new(self))
    }
}

impl<T: PartialEq + Clone + 'static, const N: usize> EffectDeps for &[T; N] {
    fn snapshot(self) -> DepsSnapshot {
        DepsSnapshot(Box::new(self.clone()))
    }
}

impl<T: PartialEq + Clone + 'static> EffectDeps for &[T] {
    fn snapshot(self) -> DepsSnapshot {
        DepsSnapshot(Box::new(self.to_vec()))
    }
}

/// Normalizes a `use_effect` closure's return value: `()` means no
/// cleanup, anything callable once becomes the cleanup that runs before
/// the next execution (or on unmount).
pub trait EffectCleanup {
    fn into_cleanup(self) -> Option<Box<dyn FnOnce()>>;
}

impl EffectCleanup for () {
    fn into_cleanup(self) -> Option<Box<dyn FnOnce()>> {
        None
    }
}

impl<F: FnOnce() + 'static> EffectCleanup for F {
    fn into_cleanup(self) -> Option<Box<dyn FnOnce()>> {
        Some(Box::new(self))
    }
}

struct EffectRecord {
    deps: Option<DepsSnapshot>,
    cleanup: Option<Box<dyn FnOnce()>>,
    mounted: bool,
    pending: bool,
}

type BoxedEffectFn = Box<dyn FnOnce() -> Option<Box<dyn FnOnce()>>>;

struct PendingEffect {
    slot: Rc<RefCell<Box<dyn Any>>>,
    new_deps: DepsSnapshot,
    run: BoxedEffectFn,
    generation: u64,
}

/// Runs a side effect after this component's tree has actually been
/// committed, similar to React's `useEffect`.
///
/// `effect` runs once after the first successful render, and again
/// whenever `deps` changes value (compared by equality, not identity).
/// Returning a closure from `effect` registers it as cleanup, run right
/// before the next execution and when the component is unmounted.
///
/// ## Panics
///
/// Panics if called outside a `component()` scope, or if the order of
/// hook invocations changes between rebuilds (see [`use_state`]).
pub fn use_effect<F, R, D>(effect: F, deps: D)
    where F: FnOnce() -> R + 'static, R: EffectCleanup + 'static, D: EffectDeps
{
    let id = current_component_id();
    let new_deps = deps.snapshot();

    let (slot, idx) = HOOK_STORE.with(|store| {
        let mut store = store.borrow_mut();
        let state = store
            .get_mut(&id)
            .expect("use_effect: internal error - provided binding used without begin/push");

        let idx = state.cursor;
        state.cursor += 1;

        if idx == state.slots.len() {
            state.slots.push(
                Rc::new(
                    RefCell::new(
                        Box::new(EffectRecord {
                            deps: None,
                            cleanup: None,
                            mounted: false,
                            pending: false,
                        }) as Box<dyn Any>
                    )
                )
            );
        }

        (state.slots[idx].clone(), idx)
    });

    let should_run = {
        let borrowed = slot.borrow();
        let record = borrowed
            .downcast_ref::<EffectRecord>()
            .unwrap_or_else(|| {
                panic!(
                    "use_effect: hook order broken in component '{}' (slot #{idx}) - do not call use_effect conditionally.",
                    id.as_str()
                )
            });

        match &record.deps {
            None => true,
            Some(old_deps) => deps_changed(old_deps, &new_deps),
        }
    };

    if !should_run {
        return;
    }

    slot
        .borrow_mut()
        .downcast_mut::<EffectRecord>()
        .expect("use_effect: internal error").pending = true;

    let run: BoxedEffectFn = Box::new(move || effect().into_cleanup());

    PENDING_EFFECTS.with(|q| {
        q.borrow_mut().push(PendingEffect {
            slot,
            new_deps,
            run,
            generation: current_generation(),
        });
    });
}

/// Runs every effect queued by the render that was just committed to the
/// tree. Must be called after reconciliation completes, never during
/// widget building - the reconciler's own commit point is the intended
/// caller.
pub fn run_pending_effects() {
    let generation = current_generation();
    let pending = PENDING_EFFECTS.with(|q| std::mem::take(&mut *q.borrow_mut()));

    for entry in pending {
        // An effect queued by a render that got superseded before its
        // reconciliation finished was never actually committed, so it
        // must not run.
        if entry.generation != generation {
            continue;
        }

        let old_cleanup = {
            let mut boxed = entry.slot.borrow_mut();
            let record = boxed.downcast_mut::<EffectRecord>().expect("use_effect: internal error");
            record.pending = false;
            record.cleanup.take()
        };

        if let Some(cleanup) = old_cleanup {
            cleanup();
        }

        let new_cleanup = (entry.run)();

        let mut boxed = entry.slot.borrow_mut();
        let record = boxed.downcast_mut::<EffectRecord>().expect("use_effect: internal error");
        record.deps = Some(entry.new_deps);
        record.cleanup = new_cleanup;
        record.mounted = true;
    }
}

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

    #[test]
    fn runs_once_on_mount_and_skips_unchanged_deps() {
        let log = Rc::new(RefCell::new(Vec::<String>::new()));

        let build = || {
            component("effect_mount_root", || {
                let log = log.clone();
                use_effect(move || {
                    log.borrow_mut().push("mount".to_string());
                }, ());
            });
        };

        begin_render();
        build();
        end_render();
        run_pending_effects();

        begin_render();
        build();
        end_render();
        run_pending_effects();

        assert_eq!(*log.borrow(), vec!["mount".to_string()]);
    }

    #[test]
    fn reruns_when_deps_change() {
        let log = Rc::new(RefCell::new(Vec::<String>::new()));

        let build = |value: i32| {
            component("effect_deps_root", || {
                let log = log.clone();
                use_effect(
                    move || {
                        log.borrow_mut().push(format!("run:{value}"));
                    },
                    [value]
                );
            });
        };

        begin_render();
        build(1);
        end_render();
        run_pending_effects();

        begin_render();
        build(1);
        end_render();
        run_pending_effects();

        begin_render();
        build(2);
        end_render();
        run_pending_effects();

        assert_eq!(*log.borrow(), vec!["run:1".to_string(), "run:2".to_string()]);
    }

    #[test]
    fn cleanup_runs_before_rerun_and_on_unmount() {
        let log = Rc::new(RefCell::new(Vec::<String>::new()));

        let build_child = |value: i32| {
            component("effect_cleanup_child", || {
                let log = log.clone();
                use_effect(
                    move || {
                        log.borrow_mut().push(format!("run:{value}"));
                        move || {
                            log.borrow_mut().push(format!("cleanup:{value}"));
                        }
                    },
                    [value]
                );
            });
        };

        begin_render();
        component("effect_cleanup_root", || build_child(1));
        end_render();
        run_pending_effects();

        begin_render();
        component("effect_cleanup_root", || build_child(2));
        end_render();
        run_pending_effects();

        assert_eq!(
            *log.borrow(),
            vec!["run:1".to_string(), "cleanup:1".to_string(), "run:2".to_string()]
        );

        // Third render omits the child entirely, so its cleanup must fire
        // once during end_render's unmount pass.
        begin_render();
        component("effect_cleanup_root", || {});
        end_render();
        run_pending_effects();

        assert_eq!(
            *log.borrow(),
            vec![
                "run:1".to_string(),
                "cleanup:1".to_string(),
                "run:2".to_string(),
                "cleanup:2".to_string()
            ]
        );
    }
}