reactive_stores 0.5.0-beta2

Stores for holding deeply-nested reactive state while maintaining fine-grained reactive tracking.
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
use crate::{
    KeyMap, StoreField, StoreFieldTrigger,
    path::{StorePath, StorePathSegment},
};
use reactive_graph::{
    signal::{
        ArcTrigger,
        guards::{Mapped, MappedMut, WriteGuard},
    },
    traits::{
        DefinedAt, FlattenOptionRefOption, IsDisposed, Notify, Read,
        ReadUntracked, Track, UntrackableGuard, Write,
    },
};
use std::{
    iter,
    marker::PhantomData,
    ops::{Deref, DerefMut},
    panic::Location,
};

/// Accesses the inner value of an `Option`-typed store field.
///
/// Unlike a plain [`Subfield`](crate::Subfield), this projection is fallible:
/// its [`reader`](StoreField::reader)/[`writer`](StoreField::writer) return
/// `None` when the underlying field is currently `None`, instead of handing
/// back a guard that panics when dereferenced.
pub struct OptionSubfield<Inner, T> {
    #[cfg(any(debug_assertions, leptos_debuginfo))]
    defined_at: &'static Location<'static>,
    path_segment: StorePathSegment,
    inner: Inner,
    ty: PhantomData<T>,
}

impl<Inner, T> Clone for OptionSubfield<Inner, T>
where
    Inner: Clone,
{
    fn clone(&self) -> Self {
        Self {
            #[cfg(any(debug_assertions, leptos_debuginfo))]
            defined_at: self.defined_at,
            path_segment: self.path_segment,
            inner: self.inner.clone(),
            ty: self.ty,
        }
    }
}

impl<Inner, T> Copy for OptionSubfield<Inner, T> where Inner: Copy {}

impl<Inner, T> OptionSubfield<Inner, T> {
    /// Creates an accessor for the inner value of an `Option`-typed field.
    #[track_caller]
    pub fn new(inner: Inner) -> Self {
        Self {
            #[cfg(any(debug_assertions, leptos_debuginfo))]
            defined_at: Location::caller(),
            path_segment: 0.into(),
            inner,
            ty: PhantomData,
        }
    }
}

impl<Inner, T> StoreField for OptionSubfield<Inner, T>
where
    Inner: StoreField<Value = Option<T>>,
    T: 'static,
{
    type Value = T;
    type Reader = Mapped<Inner::Reader, T>;
    type Writer = MappedMut<WriteGuard<Vec<ArcTrigger>, Inner::Writer>, T>;

    fn path(&self) -> impl IntoIterator<Item = StorePathSegment> {
        self.inner
            .path()
            .into_iter()
            .chain(iter::once(self.path_segment))
    }

    fn path_unkeyed(&self) -> impl IntoIterator<Item = StorePathSegment> {
        self.inner
            .path_unkeyed()
            .into_iter()
            .chain(iter::once(self.path_segment))
    }

    fn get_trigger(&self, path: StorePath) -> StoreFieldTrigger {
        self.inner.get_trigger(path)
    }

    fn get_trigger_unkeyed(&self, path: StorePath) -> StoreFieldTrigger {
        self.inner.get_trigger_unkeyed(path)
    }

    fn reader(&self) -> Option<Self::Reader> {
        let inner = self.inner.reader()?;
        // The reader holds the inner lock for its whole lifetime, so the
        // value cannot toggle to `None` before the (lazy) projection runs on
        // deref. Bail out here instead of handing back a guard that would
        // panic in `as_ref().unwrap()`.
        if inner.is_none() {
            return None;
        }
        Some(Mapped::new_with_guard(inner, |t| t.as_ref().unwrap()))
    }

    fn writer(&self) -> Option<Self::Writer> {
        let mut parent = self.inner.writer()?;
        // See `reader`: the write guard holds the inner lock, so a single
        // check here keeps the `as_mut().unwrap()` projection panic-free.
        if parent.is_none() {
            return None;
        }
        // untrack the parent so it doesn't notify its `this` trigger (which
        // would notify siblings); the path triggers are included below.
        parent.untrack();
        let triggers = self.triggers_for_current_path();
        let guard = WriteGuard::new(triggers, parent);
        Some(MappedMut::new(
            guard,
            |t| t.as_ref().unwrap(),
            |t| t.as_mut().unwrap(),
        ))
    }

    #[inline(always)]
    fn keys(&self) -> Option<KeyMap> {
        self.inner.keys()
    }

    #[track_caller]
    fn track_field(&self) {
        let mut full_path = self.path().into_iter().collect::<StorePath>();
        let trigger = self.get_trigger(self.path().into_iter().collect());
        trigger.this.track();
        trigger.children.track();

        while !full_path.is_empty() {
            full_path.pop();
            let inner = self.get_trigger(full_path.clone());
            inner.this.track();
        }
    }
}

impl<Inner, T> DefinedAt for OptionSubfield<Inner, T> {
    fn defined_at(&self) -> Option<&'static Location<'static>> {
        #[cfg(any(debug_assertions, leptos_debuginfo))]
        {
            Some(self.defined_at)
        }
        #[cfg(not(any(debug_assertions, leptos_debuginfo)))]
        {
            None
        }
    }
}

impl<Inner, T> IsDisposed for OptionSubfield<Inner, T>
where
    Inner: IsDisposed,
{
    fn is_disposed(&self) -> bool {
        self.inner.is_disposed()
    }
}

impl<Inner, T> Notify for OptionSubfield<Inner, T>
where
    Inner: StoreField<Value = Option<T>>,
    T: 'static,
{
    #[track_caller]
    fn notify(&self) {
        let trigger = self.get_trigger(self.path().into_iter().collect());
        trigger.this.notify();
        trigger.children.notify();
    }
}

impl<Inner, T> Track for OptionSubfield<Inner, T>
where
    Inner: StoreField<Value = Option<T>> + Track + 'static,
    T: 'static,
{
    #[track_caller]
    fn track(&self) {
        self.track_field();
    }
}

impl<Inner, T> ReadUntracked for OptionSubfield<Inner, T>
where
    Inner: StoreField<Value = Option<T>>,
    T: 'static,
{
    type Value = <Self as StoreField>::Reader;

    fn try_read_untracked(&self) -> Option<Self::Value> {
        self.reader()
    }
}

impl<Inner, T> Write for OptionSubfield<Inner, T>
where
    Inner: StoreField<Value = Option<T>>,
    T: 'static,
{
    type Value = T;

    fn try_write(&self) -> Option<impl UntrackableGuard<Target = Self::Value>> {
        self.writer()
    }

    fn try_write_untracked(
        &self,
    ) -> Option<impl DerefMut<Target = Self::Value>> {
        self.writer().map(|mut writer| {
            writer.untrack();
            writer
        })
    }
}

/// Extends optional store fields, with the ability to unwrap or map over them.
pub trait OptionStoreExt
where
    Self: StoreField<Value = Option<Self::Output>>,
{
    /// The inner type of the `Option<_>` this field holds.
    type Output;

    /// Provides access to the inner value, as a subfield, unwrapping the outer value.
    ///
    /// The returned field reads and writes fallibly: if the outer value becomes
    /// `None` before the projection runs, its reader/writer yield `None` rather
    /// than panicking.
    fn unwrap(self) -> OptionSubfield<Self, Self::Output>;

    /// Inverts a subfield of an `Option` to an `Option` of a subfield.
    fn invert(self) -> Option<OptionSubfield<Self, Self::Output>> {
        self.map(|f| f)
    }

    /// Reactively maps over the field.
    ///
    /// This returns `None` if the subfield is currently `None`,
    /// and a new store subfield with the inner value if it is `Some`. This can be used in some
    /// other reactive context, which will cause it to re-run if the field toggles between `None`
    /// and `Some(_)`.
    fn map<U>(
        self,
        map_fn: impl FnOnce(OptionSubfield<Self, Self::Output>) -> U,
    ) -> Option<U>;

    /// Unreactively maps over the field.
    ///
    /// This returns `None` if the subfield is currently `None`,
    /// and a new store subfield with the inner value if it is `Some`. This is an unreactive variant of
    /// `[OptionStoreExt::map]`, and will not cause the reactive context to re-run if the field changes.
    fn map_untracked<U>(
        self,
        map_fn: impl FnOnce(OptionSubfield<Self, Self::Output>) -> U,
    ) -> Option<U>;
}

impl<T, S> OptionStoreExt for S
where
    S: StoreField<Value = Option<T>> + Read + ReadUntracked,
    <S as Read>::Value: Deref<Target = Option<T>>,
    <S as ReadUntracked>::Value: Deref<Target = Option<T>>,
{
    type Output = T;

    fn unwrap(self) -> OptionSubfield<Self, Self::Output> {
        OptionSubfield::new(self)
    }

    fn map<U>(
        self,
        map_fn: impl FnOnce(OptionSubfield<S, T>) -> U,
    ) -> Option<U> {
        if self.try_read().as_deref().flatten().is_some() {
            Some(map_fn(self.unwrap()))
        } else {
            None
        }
    }

    fn map_untracked<U>(
        self,
        map_fn: impl FnOnce(OptionSubfield<S, T>) -> U,
    ) -> Option<U> {
        if self.try_read_untracked().as_deref().flatten().is_some() {
            Some(map_fn(self.unwrap()))
        } else {
            None
        }
    }
}

#[cfg(test)]
mod tests {
    use crate::{self as reactive_stores, Patch as _, Store};
    use any_spawner::Executor;
    use reactive_graph::{
        effect::Effect,
        traits::{Get, Read, ReadUntracked, Set, Write},
    };
    use reactive_stores_macro::Patch;
    use std::sync::{
        Arc,
        atomic::{AtomicUsize, Ordering},
    };

    pub async fn tick() {
        Executor::tick().await;
    }

    #[derive(Debug, Clone, Store)]
    pub struct User {
        pub name: Option<Name>,
    }

    #[derive(Debug, Clone, Store)]
    pub struct Name {
        pub first_name: Option<String>,
    }

    #[tokio::test]
    async fn substores_reachable_through_option() {
        use crate::OptionStoreExt;

        _ = any_spawner::Executor::init_tokio();

        let combined_count = Arc::new(AtomicUsize::new(0));

        let store = Store::new(User { name: None });

        Effect::new_sync({
            let combined_count = Arc::clone(&combined_count);
            move |prev: Option<()>| {
                if prev.is_none() {
                    println!("first run");
                } else {
                    println!("next run");
                }

                if store.name().read().is_some() {
                    println!(
                        "inner value = {:?}",
                        *store.name().unwrap().first_name().read()
                    );
                } else {
                    println!("no inner value");
                }

                combined_count.fetch_add(1, Ordering::Relaxed);
            }
        });

        tick().await;
        store.name().set(Some(Name {
            first_name: Some("Greg".into()),
        }));
        tick().await;
        store.name().set(None);
        tick().await;
        store.name().set(Some(Name {
            first_name: Some("Bob".into()),
        }));
        tick().await;
        store
            .name()
            .unwrap()
            .first_name()
            .write()
            .as_mut()
            .unwrap()
            .push_str("!!!");
        tick().await;
        assert_eq!(combined_count.load(Ordering::Relaxed), 5);
        assert_eq!(
            store
                .name()
                .read_untracked()
                .as_ref()
                .unwrap()
                .first_name
                .as_ref()
                .unwrap(),
            "Bob!!!"
        );
    }

    #[tokio::test]
    async fn mapping_over_optional_store_field() {
        use crate::OptionStoreExt;

        _ = any_spawner::Executor::init_tokio();

        let parent_count = Arc::new(AtomicUsize::new(0));
        let inner_count = Arc::new(AtomicUsize::new(0));

        let store = Store::new(User { name: None });

        Effect::new_sync({
            let parent_count = Arc::clone(&parent_count);
            move |prev: Option<()>| {
                if prev.is_none() {
                    println!("parent: first run");
                } else {
                    println!("parent: next run");
                }

                println!("  is_some = {}", store.name().read().is_some());
                parent_count.fetch_add(1, Ordering::Relaxed);
            }
        });
        Effect::new_sync({
            let inner_count = Arc::clone(&inner_count);
            move |prev: Option<()>| {
                if prev.is_none() {
                    println!("inner: first run");
                } else {
                    println!("inner: next run");
                }

                println!(
                    "store inner value length = {:?}",
                    store.name().map(|inner| inner
                        .first_name()
                        .get()
                        .unwrap_or_default()
                        .len())
                );
                inner_count.fetch_add(1, Ordering::Relaxed);
            }
        });

        tick().await;
        assert_eq!(parent_count.load(Ordering::Relaxed), 1);
        assert_eq!(inner_count.load(Ordering::Relaxed), 1);

        store.name().set(Some(Name {
            first_name: Some("Greg".into()),
        }));
        tick().await;
        assert_eq!(parent_count.load(Ordering::Relaxed), 2);
        assert_eq!(inner_count.load(Ordering::Relaxed), 2);

        println!("\nUpdating first name only");
        store
            .name()
            .unwrap()
            .first_name()
            .write()
            .as_mut()
            .unwrap()
            .push_str("!!!");

        tick().await;
        assert_eq!(parent_count.load(Ordering::Relaxed), 3);
        assert_eq!(inner_count.load(Ordering::Relaxed), 3);
    }

    #[tokio::test]
    async fn patch() {
        use crate::OptionStoreExt;

        _ = any_spawner::Executor::init_tokio();

        #[derive(Debug, Clone, Store, Patch)]
        struct Outer {
            inner: Option<Inner>,
        }

        #[derive(Debug, Clone, Store, Patch)]
        struct Inner {
            first: String,
            second: String,
        }

        let store = Store::new(Outer {
            inner: Some(Inner {
                first: "A".to_owned(),
                second: "B".to_owned(),
            }),
        });

        let parent_count = Arc::new(AtomicUsize::new(0));
        let inner_first_count = Arc::new(AtomicUsize::new(0));
        let inner_second_count = Arc::new(AtomicUsize::new(0));

        Effect::new_sync({
            let parent_count = Arc::clone(&parent_count);
            move |prev: Option<()>| {
                if prev.is_none() {
                    println!("parent: first run");
                } else {
                    println!("parent: next run");
                }

                println!("  value = {:?}", store.inner().get());
                parent_count.fetch_add(1, Ordering::Relaxed);
            }
        });
        Effect::new_sync({
            let inner_first_count = Arc::clone(&inner_first_count);
            move |prev: Option<()>| {
                if prev.is_none() {
                    println!("inner_first: first run");
                } else {
                    println!("inner_first: next run");
                }

                // note: we specifically want to test whether using `.patch()`
                // correctly limits notifications on the first field when only the second
                // field has changed
                //
                // `.map()` would also track the parent field (to track when it changed from Some
                // to None), which would mean the notification numbers were always the same
                //
                // so here, we'll do `.map_untracked()`, but in general in a real case you'd want
                // to use `.map()` so that if the parent switches to None you do track that
                println!(
                    "  value = {:?}",
                    store.inner().map_untracked(|inner| inner.first().get())
                );
                inner_first_count.fetch_add(1, Ordering::Relaxed);
            }
        });
        Effect::new_sync({
            let inner_second_count = Arc::clone(&inner_second_count);
            move |prev: Option<()>| {
                if prev.is_none() {
                    println!("inner_second: first run");
                } else {
                    println!("inner_second: next run");
                }

                println!(
                    "  value = {:?}",
                    store.inner().map(|inner| inner.second().get())
                );
                inner_second_count.fetch_add(1, Ordering::Relaxed);
            }
        });

        tick().await;
        assert_eq!(parent_count.load(Ordering::Relaxed), 1);
        assert_eq!(inner_first_count.load(Ordering::Relaxed), 1);
        assert_eq!(inner_second_count.load(Ordering::Relaxed), 1);

        println!("\npatching with A/C");
        store.patch(Outer {
            inner: Some(Inner {
                first: "A".to_string(),
                second: "C".to_string(),
            }),
        });

        tick().await;
        assert_eq!(parent_count.load(Ordering::Relaxed), 2);
        assert_eq!(inner_first_count.load(Ordering::Relaxed), 1);
        assert_eq!(inner_second_count.load(Ordering::Relaxed), 2);

        store.patch(Outer { inner: None });

        tick().await;
        assert_eq!(parent_count.load(Ordering::Relaxed), 3);
        assert_eq!(inner_first_count.load(Ordering::Relaxed), 2);
        assert_eq!(inner_second_count.load(Ordering::Relaxed), 3);

        println!("\npatching with A/B");
        store.patch(Outer {
            inner: Some(Inner {
                first: "A".to_string(),
                second: "B".to_string(),
            }),
        });

        tick().await;
        assert_eq!(parent_count.load(Ordering::Relaxed), 4);
        assert_eq!(inner_first_count.load(Ordering::Relaxed), 2);
        assert_eq!(inner_second_count.load(Ordering::Relaxed), 4);
    }

    #[test]
    fn unwrap_reads_as_none_after_option_is_cleared() {
        use crate::OptionStoreExt;
        use reactive_graph::owner::Owner;

        #[derive(Debug, Clone, Store)]
        struct State {
            value: Option<i32>,
        }

        let owner = Owner::new();
        owner.set();

        let store = Store::new(State { value: Some(1) });

        // Capture the unwrapped inner field while the option is `Some`.
        let inner = OptionStoreExt::unwrap(store.value());
        assert_eq!(inner.try_read_untracked().map(|g| *g), Some(1));

        // Another writer clears the option after the inner field was captured.
        *store.value().write() = None;

        // The previously valid projection must now read as `None` instead of
        // panicking with "called `Option::unwrap()` on a `None` value".
        let guard = inner.try_read_untracked();
        assert!(guard.is_none());
        // Forcing the (lazy) projection must not panic.
        assert!(guard.map(|g| *g).is_none());

        // The writer side is fallible in the same way.
        assert!(inner.try_write().is_none());
    }
}