reactive_graph 0.2.14

A fine-grained reactive graph for building user interfaces.
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
//! Callbacks define a standard way to store functions and closures. They are useful
//! for component properties, because they can be used to define optional callback functions,
//! which generic props don’t support.
//!
//! The callback types implement [`Copy`], so they can easily be moved into and out of other closures, just like signals.
//!
//! # Types
//! This modules implements 2 callback types:
//! - [`Callback`](reactive_graph::callback::Callback)
//! - [`UnsyncCallback`](reactive_graph::callback::UnsyncCallback)
//!
//! Use `SyncCallback` if the function is not `Sync` and `Send`.

use crate::{
    owner::{LocalStorage, StoredValue},
    traits::{Dispose, WithValue},
    IntoReactiveValue,
};
use std::{fmt, rc::Rc, sync::Arc};

/// A wrapper trait for calling callbacks.
pub trait Callable<In: 'static, Out: 'static = ()> {
    /// calls the callback with the specified argument.
    ///
    /// Returns None if the callback has been disposed
    fn try_run(&self, input: In) -> Option<Out>;
    /// calls the callback with the specified argument.
    ///
    /// # Panics
    /// Panics if you try to run a callback that has been disposed
    fn run(&self, input: In) -> Out;
}

/// A callback type that is not required to be [`Send`] or [`Sync`].
///
/// # Example
/// ```
/// # use reactive_graph::prelude::*; use reactive_graph::callback::*;  let owner = reactive_graph::owner::Owner::new(); owner.set();
/// let _: UnsyncCallback<()> = UnsyncCallback::new(|_| {});
/// let _: UnsyncCallback<(i32, i32)> = (|_x: i32, _y: i32| {}).into();
/// let cb: UnsyncCallback<i32, String> = UnsyncCallback::new(|x: i32| x.to_string());
/// assert_eq!(cb.run(42), "42".to_string());
/// ```
pub struct UnsyncCallback<In: 'static, Out: 'static = ()>(
    StoredValue<Rc<dyn Fn(In) -> Out>, LocalStorage>,
);

impl<In> fmt::Debug for UnsyncCallback<In> {
    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
        fmt.write_str("Callback")
    }
}

impl<In, Out> Copy for UnsyncCallback<In, Out> {}

impl<In, Out> Clone for UnsyncCallback<In, Out> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<In, Out> Dispose for UnsyncCallback<In, Out> {
    fn dispose(self) {
        self.0.dispose();
    }
}

impl<In, Out> UnsyncCallback<In, Out> {
    /// Creates a new callback from the given function.
    pub fn new<F>(f: F) -> UnsyncCallback<In, Out>
    where
        F: Fn(In) -> Out + 'static,
    {
        Self(StoredValue::new_local(Rc::new(f)))
    }

    /// Returns `true` if both callbacks wrap the same underlying function pointer.
    #[inline]
    pub fn matches(&self, other: &Self) -> bool {
        self.0.with_value(|self_value| {
            other
                .0
                .with_value(|other_value| Rc::ptr_eq(self_value, other_value))
        })
    }
}

impl<In: 'static, Out: 'static> Callable<In, Out> for UnsyncCallback<In, Out> {
    fn try_run(&self, input: In) -> Option<Out> {
        self.0.try_with_value(|fun| fun(input))
    }

    fn run(&self, input: In) -> Out {
        self.0.with_value(|fun| fun(input))
    }
}

macro_rules! impl_unsync_callable_from_fn {
    ($($arg:ident),*) => {
        impl<F, $($arg,)* T, Out> From<F> for UnsyncCallback<($($arg,)*), Out>
        where
            F: Fn($($arg),*) -> T + 'static,
            T: Into<Out> + 'static,
            $($arg: 'static,)*
        {
            fn from(f: F) -> Self {
                paste::paste!(
                    Self::new(move |($([<$arg:lower>],)*)| f($([<$arg:lower>]),*).into())
                )
            }
        }
    };
}

impl_unsync_callable_from_fn!();
impl_unsync_callable_from_fn!(P1);
impl_unsync_callable_from_fn!(P1, P2);
impl_unsync_callable_from_fn!(P1, P2, P3);
impl_unsync_callable_from_fn!(P1, P2, P3, P4);
impl_unsync_callable_from_fn!(P1, P2, P3, P4, P5);
impl_unsync_callable_from_fn!(P1, P2, P3, P4, P5, P6);
impl_unsync_callable_from_fn!(P1, P2, P3, P4, P5, P6, P7);
impl_unsync_callable_from_fn!(P1, P2, P3, P4, P5, P6, P7, P8);
impl_unsync_callable_from_fn!(P1, P2, P3, P4, P5, P6, P7, P8, P9);
impl_unsync_callable_from_fn!(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10);
impl_unsync_callable_from_fn!(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11);
impl_unsync_callable_from_fn!(
    P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12
);

/// A callback type that is [`Send`] + [`Sync`].
///
/// # Example
/// ```
/// # use reactive_graph::prelude::*; use reactive_graph::callback::*;  let owner = reactive_graph::owner::Owner::new(); owner.set();
/// let _: Callback<()> = Callback::new(|_| {});
/// let _: Callback<(i32, i32)> = (|_x: i32, _y: i32| {}).into();
/// let cb: Callback<i32, String> = Callback::new(|x: i32| x.to_string());
/// assert_eq!(cb.run(42), "42".to_string());
/// ```
pub struct Callback<In, Out = ()>(
    StoredValue<Arc<dyn Fn(In) -> Out + Send + Sync>>,
)
where
    In: 'static,
    Out: 'static;

impl<In, Out> fmt::Debug for Callback<In, Out> {
    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
        fmt.write_str("SyncCallback")
    }
}

impl<In, Out> Callable<In, Out> for Callback<In, Out> {
    fn try_run(&self, input: In) -> Option<Out> {
        self.0.try_with_value(|fun| fun(input))
    }

    fn run(&self, input: In) -> Out {
        self.0.with_value(|f| f(input))
    }
}

impl<In, Out> Clone for Callback<In, Out> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<In, Out> Dispose for Callback<In, Out> {
    fn dispose(self) {
        self.0.dispose();
    }
}

impl<In, Out> Copy for Callback<In, Out> {}

macro_rules! impl_callable_from_fn {
    ($($arg:ident),*) => {
        impl<F, $($arg,)* T, Out> From<F> for Callback<($($arg,)*), Out>
        where
            F: Fn($($arg),*) -> T + Send + Sync + 'static,
            T: Into<Out> + 'static,
            $($arg: Send + Sync + 'static,)*
        {
            fn from(f: F) -> Self {
                paste::paste!(
                    Self::new(move |($([<$arg:lower>],)*)| f($([<$arg:lower>]),*).into())
                )
            }
        }
    };
}

impl_callable_from_fn!();
impl_callable_from_fn!(P1);
impl_callable_from_fn!(P1, P2);
impl_callable_from_fn!(P1, P2, P3);
impl_callable_from_fn!(P1, P2, P3, P4);
impl_callable_from_fn!(P1, P2, P3, P4, P5);
impl_callable_from_fn!(P1, P2, P3, P4, P5, P6);
impl_callable_from_fn!(P1, P2, P3, P4, P5, P6, P7);
impl_callable_from_fn!(P1, P2, P3, P4, P5, P6, P7, P8);
impl_callable_from_fn!(P1, P2, P3, P4, P5, P6, P7, P8, P9);
impl_callable_from_fn!(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10);
impl_callable_from_fn!(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11);
impl_callable_from_fn!(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12);

impl<In: 'static, Out: 'static> Callback<In, Out> {
    /// Creates a new callback from the given function.
    #[track_caller]
    pub fn new<F>(fun: F) -> Self
    where
        F: Fn(In) -> Out + Send + Sync + 'static,
    {
        Self(StoredValue::new(Arc::new(fun)))
    }

    /// Returns `true` if both callbacks wrap the same underlying function pointer.
    #[inline]
    pub fn matches(&self, other: &Self) -> bool {
        self.0
            .try_with_value(|self_value| {
                other.0.try_with_value(|other_value| {
                    Arc::ptr_eq(self_value, other_value)
                })
            })
            .flatten()
            .unwrap_or(false)
    }
}

#[doc(hidden)]
pub struct __IntoReactiveValueMarkerCallbackSingleParam;

#[doc(hidden)]
pub struct __IntoReactiveValueMarkerCallbackStrOutputToString;

impl<I, O, F>
    IntoReactiveValue<
        Callback<I, O>,
        __IntoReactiveValueMarkerCallbackSingleParam,
    > for F
where
    F: Fn(I) -> O + Send + Sync + 'static,
{
    #[track_caller]
    fn into_reactive_value(self) -> Callback<I, O> {
        Callback::new(self)
    }
}

impl<I, O, F>
    IntoReactiveValue<
        UnsyncCallback<I, O>,
        __IntoReactiveValueMarkerCallbackSingleParam,
    > for F
where
    F: Fn(I) -> O + 'static,
{
    #[track_caller]
    fn into_reactive_value(self) -> UnsyncCallback<I, O> {
        UnsyncCallback::new(self)
    }
}

impl<I, F>
    IntoReactiveValue<
        Callback<I, String>,
        __IntoReactiveValueMarkerCallbackStrOutputToString,
    > for F
where
    F: Fn(I) -> &'static str + Send + Sync + 'static,
{
    #[track_caller]
    fn into_reactive_value(self) -> Callback<I, String> {
        Callback::new(move |i| self(i).to_string())
    }
}

impl<I, F>
    IntoReactiveValue<
        UnsyncCallback<I, String>,
        __IntoReactiveValueMarkerCallbackStrOutputToString,
    > for F
where
    F: Fn(I) -> &'static str + 'static,
{
    #[track_caller]
    fn into_reactive_value(self) -> UnsyncCallback<I, String> {
        UnsyncCallback::new(move |i| self(i).to_string())
    }
}

#[cfg(test)]
mod tests {
    use super::Callable;
    use crate::{
        callback::{Callback, UnsyncCallback},
        owner::Owner,
        traits::Dispose,
        IntoReactiveValue,
    };

    struct NoClone {}

    #[test]
    fn clone_callback() {
        let owner = Owner::new();
        owner.set();

        let callback = Callback::new(move |_no_clone: NoClone| NoClone {});
        let _cloned = callback;
    }

    #[test]
    fn clone_unsync_callback() {
        let owner = Owner::new();
        owner.set();

        let callback =
            UnsyncCallback::new(move |_no_clone: NoClone| NoClone {});
        let _cloned = callback;
    }

    #[test]
    fn runback_from() {
        let owner = Owner::new();
        owner.set();

        let _callback: Callback<(), String> = (|| "test").into();
        let _callback: Callback<(i32, String), String> =
            (|num, s| format!("{num} {s}")).into();
        // Single params should work without needing the (foo,) tuple using IntoReactiveValue:
        let _callback: Callback<usize, &'static str> =
            (|_usize| "test").into_reactive_value();
        let _callback: Callback<usize, String> =
            (|_usize| "test").into_reactive_value();
    }

    #[test]
    fn sync_callback_from() {
        let owner = Owner::new();
        owner.set();

        let _callback: UnsyncCallback<(), String> = (|| "test").into();
        let _callback: UnsyncCallback<(i32, String), String> =
            (|num, s| format!("{num} {s}")).into();
        // Single params should work without needing the (foo,) tuple using IntoReactiveValue:
        let _callback: UnsyncCallback<usize, &'static str> =
            (|_usize| "test").into_reactive_value();
        let _callback: UnsyncCallback<usize, String> =
            (|_usize| "test").into_reactive_value();
    }

    #[test]
    fn sync_callback_try_run() {
        let owner = Owner::new();
        owner.set();

        let callback = Callback::new(move |arg| arg);
        assert_eq!(callback.try_run((0,)), Some((0,)));
        callback.dispose();
        assert_eq!(callback.try_run((0,)), None);
    }

    #[test]
    fn unsync_callback_try_run() {
        let owner = Owner::new();
        owner.set();

        let callback = UnsyncCallback::new(move |arg| arg);
        assert_eq!(callback.try_run((0,)), Some((0,)));
        callback.dispose();
        assert_eq!(callback.try_run((0,)), None);
    }

    #[test]
    fn callback_matches_same() {
        let owner = Owner::new();
        owner.set();

        let callback1 = Callback::new(|x: i32| x * 2);
        let callback2 = callback1;
        assert!(callback1.matches(&callback2));
    }

    #[test]
    fn callback_matches_different() {
        let owner = Owner::new();
        owner.set();

        let callback1 = Callback::new(|x: i32| x * 2);
        let callback2 = Callback::new(|x: i32| x + 1);
        assert!(!callback1.matches(&callback2));
    }

    #[test]
    fn unsync_callback_matches_same() {
        let owner = Owner::new();
        owner.set();

        let callback1 = UnsyncCallback::new(|x: i32| x * 2);
        let callback2 = callback1;
        assert!(callback1.matches(&callback2));
    }

    #[test]
    fn unsync_callback_matches_different() {
        let owner = Owner::new();
        owner.set();

        let callback1 = UnsyncCallback::new(|x: i32| x * 2);
        let callback2 = UnsyncCallback::new(|x: i32| x + 1);
        assert!(!callback1.matches(&callback2));
    }
}