Skip to main content

rok_ui_hooks/
deps.rs

1//! Dependency declarations for `use_effect` / `use_memo`.
2//!
3//! A deps argument is a tuple whose elements are either **handles**
4//! ([`ReadSignal`](crate::ReadSignal) / [`Memo`](crate::Memo)) or **plain values**.
5//! The library re-evaluates the tuple on every notification, so a handle element
6//! turns into the signal's *current value*:
7//!
8//! | deps        | meaning                                                        |
9//! |-------------|----------------------------------------------------------------|
10//! | `()`        | no declared deps — automatic fine-grained tracking             |
11//! | `(count,)`  | re-run when `count`'s **value** changes (React `[count]`)      |
12//! | `(0i32,)`   | constant — run on mount only (React `[]`)                      |
13//! | `(a, b, 0)` | mixed handles and constants                                    |
14
15use std::any::Any;
16
17use crate::memo::Memo;
18use crate::signal::ReadSignal;
19
20/// One element of a deps tuple.
21///
22/// Implemented for every `T: Clone + PartialEq` (a constant) and for handles
23/// ([`ReadSignal`], [`Memo`]) where the *current value* is read instead.
24pub trait DepItem {
25    /// The value this element contributes to the comparison.
26    type Out: PartialEq + 'static;
27    /// Read the element's current value.
28    fn current(&self) -> Self::Out;
29}
30
31impl<T: Clone + PartialEq + 'static> DepItem for T {
32    type Out = T;
33    fn current(&self) -> T {
34        self.clone()
35    }
36}
37
38impl<T: Clone + PartialEq + 'static> DepItem for ReadSignal<T> {
39    type Out = T;
40    fn current(&self) -> T {
41        self.get()
42    }
43}
44
45impl<T: Clone + PartialEq + 'static> DepItem for Memo<T> {
46    type Out = T;
47    fn current(&self) -> T {
48        self.get()
49    }
50}
51
52/// A whole deps tuple, evaluated and compared as a unit.
53pub trait Deps {
54    /// The tuple of current values produced by [`Deps::eval`].
55    type Out: PartialEq + 'static;
56    /// Re-evaluate the deps. Called inside the observer context (tracked) and
57    /// outside it (untracked comparison), so context alone decides whether the
58    /// reads subscribe.
59    fn eval(&self) -> Self::Out;
60    /// `true` for `()`: the gate is always open, i.e. plain automatic tracking.
61    fn is_auto_track() -> bool
62    where
63        Self: Sized,
64    {
65        false
66    }
67}
68
69impl Deps for () {
70    type Out = ();
71    fn eval(&self) {}
72
73    fn is_auto_track() -> bool {
74        true
75    }
76}
77
78macro_rules! impl_deps {
79    ($(($ty:ident, $idx:tt)),+ $(,)?) => {
80        impl<$($ty: DepItem),+> Deps for ($($ty,)+) {
81            type Out = ($(<$ty as DepItem>::Out,)+);
82            fn eval(&self) -> Self::Out {
83                ($(<$ty as DepItem>::current(&self.$idx),)+)
84            }
85        }
86    };
87}
88
89impl_deps!((A, 0));
90impl_deps!((A, 0), (B, 1));
91impl_deps!((A, 0), (B, 1), (C, 2));
92impl_deps!((A, 0), (B, 1), (C, 2), (D, 3));
93impl_deps!((A, 0), (B, 1), (C, 2), (D, 3), (E, 4));
94impl_deps!((A, 0), (B, 1), (C, 2), (D, 3), (E, 4), (F, 5));
95impl_deps!((A, 0), (B, 1), (C, 2), (D, 3), (E, 4), (F, 5), (G, 6));
96impl_deps!(
97    (A, 0),
98    (B, 1),
99    (C, 2),
100    (D, 3),
101    (E, 4),
102    (F, 5),
103    (G, 6),
104    (H, 7)
105);
106
107/// Type-erased [`Deps`], so non-generic `Computation`s can hold one.
108pub(crate) trait DepsAny {
109    fn eval(&self) -> Box<dyn Any>;
110    /// `prev` is `None` on the very first (mount) run.
111    fn should_run(&self, prev: Option<&dyn Any>, next: &dyn Any) -> bool;
112}
113
114pub(crate) struct DepsBox<D>(pub D);
115
116impl<D: Deps> DepsAny for DepsBox<D> {
117    fn eval(&self) -> Box<dyn Any> {
118        Box::new(self.0.eval())
119    }
120
121    fn should_run(&self, prev: Option<&dyn Any>, next: &dyn Any) -> bool {
122        if D::is_auto_track() {
123            return true;
124        }
125        let Some(prev) = prev else { return true };
126        match (
127            prev.downcast_ref::<<D as Deps>::Out>(),
128            next.downcast_ref::<<D as Deps>::Out>(),
129        ) {
130            (Some(p), Some(n)) => p != n,
131            _ => true,
132        }
133    }
134}