waterui-core 0.5.0

Core functionality for the WaterUI framework
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
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
//! Collection of view-related utilities for managing and transforming UI components.
//!
//! This module provides types and traits for working with collections of views in a type-safe
//! and efficient manner. It includes utilities for type erasure, transformation, and identity
//! tracking of view collections.

use crate::id::Id as RawId;
use crate::{AnyView, View};
use alloc::fmt::Debug;
use alloc::{boxed::Box, collections::BTreeMap, rc::Rc, vec::Vec};
use core::any::type_name;
use core::fmt;
use core::num::NonZeroI32;
use core::ops::{Bound, RangeBounds};
use core::{
    cell::{Cell, RefCell},
    hash::Hash,
};
use nami::collection::Collection;
use nami::watcher::{BoxWatcherGuard, Context, WatcherGuard};
use nami::{Computed, Signal};

use crate::id::{Identifiable, SelfId};

/// A trait for collections that can provide unique identifiers for their elements.
///
/// `Views` extends the `Collection` trait by adding identity tracking capabilities.
/// This allows for efficient diffing and reconciliation of UI elements during updates.
/// Tip: the `get` method of `Collection` should return a unique identifier for each item.
#[diagnostic::on_unimplemented(
    message = "`{Self}` is not a WaterUI view collection",
    label = "expected a collection of views",
    note = "`Views` is implemented by `ForEach`, `Constant`, `Vec` and arrays of views, and `AnyViews`. To turn a data collection into views use `ForEach::new(data, f)` — exposed as `Lazy::for_each` / `List::for_each` — whose items must implement `Identifiable`."
)]
pub trait Views {
    /// The type of unique identifier for items in the collection.
    /// Must implement `Hash` and `Ord` to ensure uniqueness and ordering.
    type Id: 'static + Hash + Ord + Clone;
    /// The type of guard returned when registering a watcher.
    type Guard: WatcherGuard;
    /// The view type that this collection produces for each element.
    type View: View;
    /// Returns the unique identifier for the item at the specified index, or `None` if out of bounds.
    fn get_id(&self, index: usize) -> Option<Self::Id>;
    /// Returns the number of items in the collection as a reactive value.
    fn len(&self) -> Computed<usize>;

    /// Returns `true` if the collection contains no elements.
    fn is_empty(&self) -> bool {
        nami::Signal::get(&self.len()) == 0
    }

    /// Registers a watcher for changes in the specified range of the collection.
    ///
    /// Returns a guard that will unregister the watcher when dropped.
    fn watch(
        &self,
        range: impl RangeBounds<usize>,
        watcher: impl for<'a> Fn(Context<&'a [Self::Id]>) + 'static, // watcher will receive a slice of items, its range is decided by the range parameter
    ) -> Self::Guard;

    /// Returns the view at the specified index, or `None` if the index is out of bounds.
    fn get_view(&self, id: usize) -> Option<Self::View>;
}

/// A type-erased container for `Views` collections.
///
/// `AnyViews` provides a uniform interface to different views collections
/// by wrapping them in a type-erased container. This enables working with
/// heterogeneous view collections through a common interface.
pub struct AnyViews<V>(Box<dyn AnyViewsImpl<View = V>>);

impl<V> Debug for AnyViews<V> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(type_name::<Self>())
    }
}

/// A reference-counted, type-erased container for `Views` collections.
/// `SharedAnyViews` allows multiple owners to share access
/// to the same views collection through reference counting.
pub struct SharedAnyViews<V>(Rc<dyn AnyViewsImpl<View = V>>);

impl<V> Clone for SharedAnyViews<V> {
    fn clone(&self) -> Self {
        Self(self.0.clone())
    }
}

impl<V> SharedAnyViews<V> {
    /// Creates a new type-erased shared view collection from any type implementing the `Views` trait.
    ///
    /// This function wraps the provided collection in a type-erased container using reference counting, allowing
    /// different view collection implementations to be used through a common interface with shared ownership.
    ///
    /// # Parameters
    /// * `contents` - Any collection implementing the `Views` trait with the appropriate item type
    ///
    /// # Returns
    /// A new `SharedAnyViews` instance containing the provided collection
    pub fn new(contents: impl Views<View = V> + 'static) -> Self {
        Self(Rc::new(IntoAnyViews::new(contents)))
    }
}

impl<V> From<AnyViews<V>> for SharedAnyViews<V> {
    fn from(value: AnyViews<V>) -> Self {
        Self(Rc::from(value.0))
    }
}

impl<V> Debug for SharedAnyViews<V> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(type_name::<Self>())
    }
}

impl<V: View> Views for SharedAnyViews<V> {
    type Id = SelfId<RawId>;
    type Guard = BoxWatcherGuard;
    type View = V;
    fn get_id(&self, index: usize) -> Option<Self::Id> {
        self.0.get_id(index).map(SelfId::new)
    }
    fn get_view(&self, index: usize) -> Option<Self::View> {
        self.0.get_view(index)
    }
    fn len(&self) -> Computed<usize> {
        self.0.len()
    }

    fn watch(
        &self,
        range: impl RangeBounds<usize>,
        watcher: impl for<'a> Fn(Context<&'a [Self::Id]>) + 'static, // watcher will receive a slice of items, its range is decided by the range parameter
    ) -> Self::Guard {
        self.0.watch(
            (range.start_bound().cloned(), range.end_bound().cloned()),
            Box::new(move |ctx| {
                let ctx =
                    ctx.map(|value| value.iter().copied().map(SelfId::new).collect::<Vec<_>>());
                watcher(ctx.as_deref());
            }),
        )
    }
}

trait AnyViewsImpl {
    type View;

    fn get_view(&self, index: usize) -> Option<Self::View>;
    fn get_id(&self, index: usize) -> Option<RawId>;
    fn len(&self) -> Computed<usize>;
    #[allow(clippy::type_complexity)]
    fn watch(
        &self,
        range: (Bound<usize>, Bound<usize>),
        watcher: Box<dyn for<'a> Fn(Context<&'a [RawId]>) + 'static>,
    ) -> BoxWatcherGuard;
}

#[derive(Debug)]
struct IdGenerator<Id> {
    map: RefCell<BTreeMap<Id, i32>>,
    counter: Cell<i32>,
}

impl<Id: Hash + Ord> Default for IdGenerator<Id> {
    fn default() -> Self {
        Self::new()
    }
}

impl<Id: Hash + Ord> IdGenerator<Id> {
    pub const fn new() -> Self {
        Self {
            map: RefCell::new(BTreeMap::new()),
            counter: Cell::new(i32::MIN),
        }
    }
    pub fn to_id(&self, value: Id) -> RawId {
        let mut this = self.map.borrow_mut();
        if let Some(&id) = this.get(&value) {
            return RawId::from(NonZeroI32::new(id).expect("stored raw id must never be zero"));
        }
        let mut id = self.counter.get();
        if id == 0 {
            id = 1;
        }

        let mut next = id.checked_add(1).expect("id counter exhausted");
        if next == 0 {
            next = next.checked_add(1).expect("id counter exhausted");
        }
        self.counter.set(next);

        this.insert(value, id);
        RawId::from(NonZeroI32::new(id).expect("generated raw id must never be zero"))
    }
}

struct IntoAnyViews<V>
where
    V: Views,
{
    contents: V,
    id: Rc<IdGenerator<V::Id>>,
}

impl<V> IntoAnyViews<V>
where
    V: Views + 'static,
{
    pub fn new(contents: V) -> Self {
        Self {
            contents,
            id: Rc::default(),
        }
    }
}

impl<V> AnyViewsImpl for IntoAnyViews<V>
where
    V: Views + 'static,
{
    type View = V::View;

    fn get_view(&self, index: usize) -> Option<Self::View> {
        self.contents.get_view(index)
    }

    fn get_id(&self, index: usize) -> Option<RawId> {
        self.contents.get_id(index).map(|item| self.id.to_id(item))
    }

    fn len(&self) -> Computed<usize> {
        self.contents.len()
    }

    fn watch(
        &self,
        range: (Bound<usize>, Bound<usize>),
        watcher: Box<dyn for<'a> Fn(Context<&'a [RawId]>) + 'static>,
    ) -> BoxWatcherGuard {
        let id = self.id.clone();
        Box::new(self.contents.watch(range, move |ctx| {
            let ctx = ctx.map(|value| {
                value
                    .iter()
                    .map(|data| id.to_id(data.clone()))
                    .collect::<Vec<_>>()
            });
            watcher(ctx.as_deref());
        }))
    }
}
impl<V> AnyViews<V>
where
    V: View,
{
    /// Creates a new type-erased view collection from any type implementing the `Views` trait.
    ///
    /// This function wraps the provided collection in a type-erased container, allowing
    /// different view collection implementations to be used through a common interface.
    ///
    /// # Parameters
    /// * `contents` - Any collection implementing the `Views` trait with the appropriate item type
    ///
    /// # Returns
    /// A new `AnyViews` instance containing the provided collection
    pub fn new<C>(contents: C) -> Self
    where
        C: Views<View = V> + 'static,
    {
        Self(Box::new(IntoAnyViews {
            id: Rc::new(IdGenerator::<C::Id>::new()),
            contents,
        }))
    }
}

impl<V> Views for AnyViews<V>
where
    V: View,
{
    type Id = SelfId<RawId>;
    type Guard = BoxWatcherGuard;
    type View = V;
    fn get_id(&self, index: usize) -> Option<Self::Id> {
        self.0.get_id(index).map(SelfId::new)
    }
    fn get_view(&self, index: usize) -> Option<Self::View> {
        self.0.get_view(index)
    }
    fn len(&self) -> Computed<usize> {
        self.0.len()
    }

    fn watch(
        &self,
        range: impl RangeBounds<usize>,
        watcher: impl for<'a> Fn(Context<&'a [Self::Id]>) + 'static, // watcher will receive a slice of items, its range is decided by the range parameter
    ) -> Self::Guard {
        self.0.watch(
            (range.start_bound().cloned(), range.end_bound().cloned()),
            Box::new(move |ctx| {
                let ctx =
                    ctx.map(|value| value.iter().copied().map(SelfId::new).collect::<Vec<_>>());
                watcher(ctx.as_deref());
            }),
        )
    }
}
/// A utility for transforming elements of a collection with a mapping function.
///
/// `ForEach` applies a transformation function to each element of a source collection,
/// producing a new collection with the transformed elements. This is useful for
/// transforming data models into view representations.
#[derive(Debug, Clone)]
pub struct ForEach<C, F, V>
where
    C: Collection,
    C::Item: Identifiable,
    F: Fn(C::Item) -> V,
    V: View,
{
    data: C,
    generator: F,
}

impl<C, F, V> ForEach<C, F, V>
where
    C: Collection,
    C::Item: Identifiable,
    F: Fn(C::Item) -> V,
    V: View,
{
    /// Creates a new `ForEach` transformation with the provided data collection and generator function.
    ///
    /// # Parameters
    /// * `data` - The source collection containing elements to be transformed
    /// * `generator` - A function that transforms elements from the source collection
    ///
    /// # Returns
    /// A new `ForEach` instance that will apply the transformation when accessed
    pub const fn new(data: C, generator: F) -> Self {
        Self { data, generator }
    }

    /// Consumes the `ForEach` and returns the original data collection and generator function.
    ///
    /// # Returns
    /// A tuple containing the original data collection and generator function
    pub fn into_inner(self) -> (C, F) {
        (self.data, self.generator)
    }
}

#[derive(Clone)]
struct CollectionLenSignal<C>(C);

impl<C> Signal for CollectionLenSignal<C>
where
    C: Collection + Clone,
{
    type Output = usize;
    type Guard = C::Guard;

    fn get(&self) -> Self::Output {
        self.0.len()
    }

    fn watch(&self, watcher: impl Fn(Context<Self::Output>) + 'static) -> Self::Guard {
        self.0.watch(.., move |ctx| {
            let len = ctx.value().len();
            watcher(ctx.map(move |_| len));
        })
    }
}

impl<C, F, V> Collection for ForEach<C, F, V>
where
    C: Collection,
    C::Item: Identifiable,
    F: 'static + Fn(C::Item) -> V,
    V: View,
{
    type Item = <C::Item as Identifiable>::Id;
    type Guard = C::Guard;
    fn get(&self, index: usize) -> Option<Self::Item> {
        self.data.get(index).map(|item| item.id())
    }

    fn len(&self) -> usize {
        self.data.len()
    }

    fn watch(
        &self,
        range: impl RangeBounds<usize>,
        watcher: impl for<'a> Fn(Context<&'a [Self::Item]>) + 'static, // watcher will receive a slice of items, its range is decided by the range parameter
    ) -> Self::Guard {
        self.data.watch(range, move |ctx| {
            let ctx = ctx.map(|value| value.iter().map(Identifiable::id).collect::<Vec<_>>());

            watcher(ctx.as_deref());
        })
    }
}

impl<C, F, V> Views for ForEach<C, F, V>
where
    C: Collection + Clone,
    C::Item: Identifiable,
    F: 'static + Fn(C::Item) -> V,
    V: View,
{
    type Id = <C::Item as Identifiable>::Id;
    type View = V;
    type Guard = C::Guard;
    fn get_id(&self, index: usize) -> Option<Self::Id> {
        self.data.get(index).map(|item| item.id())
    }
    fn get_view(&self, index: usize) -> Option<Self::View> {
        self.data.get(index).map(|item| (self.generator)(item))
    }
    fn len(&self) -> Computed<usize> {
        Computed::new(CollectionLenSignal(self.data.clone()))
    }
    fn watch(
        &self,
        range: impl RangeBounds<usize>,
        watcher: impl for<'a> Fn(Context<&'a [Self::Id]>) + 'static, // watcher will receive a slice of items, its range is decided by the range parameter
    ) -> Self::Guard {
        self.data.watch(range, move |ctx| {
            let ctx = ctx.map(|value| value.iter().map(Identifiable::id).collect::<Vec<_>>());

            watcher(ctx.as_deref());
        })
    }
}

/// A statically sized collection that never changes, removes, or adds items.
///
/// `Constant` wraps a collection and provides a stable view collection where
/// elements are identified by their index position. This is useful for static
/// lists of views that don't need to be updated or reordered.
#[derive(Debug, Clone)]
pub struct Constant<C>
where
    C: Collection,
    C::Item: View,
{
    value: C,
}

impl<C> Constant<C>
where
    C: Collection,
    C::Item: View,
{
    /// Creates a new `Constant` collection from the provided collection.
    ///
    /// # Parameters
    /// * `value` - The underlying collection to be wrapped as a constant view collection
    ///
    /// # Returns
    /// A new `Constant` instance containing the provided collection
    pub const fn new(value: C) -> Self {
        Self { value }
    }
}

impl<C> Collection for Constant<C>
where
    C: Collection + Clone,
    C::Item: View,
{
    type Item = SelfId<usize>;
    type Guard = ();

    fn get(&self, index: usize) -> Option<Self::Item> {
        if index < self.value.len() {
            Some(SelfId::new(index))
        } else {
            None
        }
    }

    fn len(&self) -> usize {
        self.value.len()
    }

    fn watch(
        &self,
        _range: impl RangeBounds<usize>,
        _watcher: impl for<'a> Fn(Context<&'a [Self::Item]>) + 'static, // watcher will receive a slice of items, its range is decided by the range parameter
    ) -> Self::Guard {
    }
}

impl<V> Views for Constant<V>
where
    V: Collection + Clone,
    V::Item: View,
{
    type Id = SelfId<usize>;
    type Guard = ();
    type View = V::Item;

    fn len(&self) -> Computed<usize> {
        Computed::constant(self.value.len())
    }

    fn get_id(&self, index: usize) -> Option<Self::Id> {
        if index < self.value.len() {
            Some(SelfId::new(index))
        } else {
            None
        }
    }

    fn get_view(&self, index: usize) -> Option<Self::View> {
        self.value.get(index)
    }

    fn watch(
        &self,
        _range: impl RangeBounds<usize>,
        _watcher: impl for<'a> Fn(Context<&'a [Self::Id]>) + 'static, // watcher will receive a slice of items, its range is decided by the range parameter
    ) -> Self::Guard {
        // No-op for Constant
    }
}

impl<V: View + Clone> Views for Vec<V> {
    type Id = SelfId<usize>;
    type Guard = ();
    type View = V;

    fn len(&self) -> Computed<usize> {
        Computed::constant(self.as_slice().len())
    }

    fn get_id(&self, index: usize) -> Option<Self::Id> {
        if index < self.as_slice().len() {
            Some(SelfId::new(index))
        } else {
            None
        }
    }

    fn get_view(&self, index: usize) -> Option<Self::View> {
        self.as_slice().get(index).cloned()
    }

    fn watch(
        &self,
        _range: impl RangeBounds<usize>,
        _watcher: impl for<'a> Fn(Context<&'a [Self::Id]>) + 'static, // watcher will receive a slice of items, its range is decided by the range parameter
    ) -> Self::Guard {
        // No-op for Vec
    }
}

impl<V: View + Clone, const N: usize> Views for [V; N] {
    type Id = SelfId<usize>;
    type Guard = ();
    type View = V;

    fn len(&self) -> Computed<usize> {
        Computed::constant(self.as_ref().len())
    }

    fn get_id(&self, index: usize) -> Option<Self::Id> {
        if index < self.as_ref().len() {
            Some(SelfId::new(index))
        } else {
            None
        }
    }

    fn get_view(&self, index: usize) -> Option<Self::View> {
        Collection::get(self, index)
    }

    fn watch(
        &self,
        _range: impl RangeBounds<usize>,
        _watcher: impl for<'a> Fn(Context<&'a [Self::Id]>) + 'static, // watcher will receive a slice of items, its range is decided by the range parameter
    ) -> Self::Guard {
        // No-op for arrays
    }
}

/// A view collection that transforms views from a source collection using a mapping function.
///
/// `Map` wraps an existing view collection and applies a transformation function to each
/// view when it is accessed, allowing for lazy transformation of views.
#[derive(Debug, Clone)]
pub struct Map<C, F> {
    source: C,
    f: F,
}

impl<C, F, V> Map<C, F>
where
    C: Views,
    F: Fn(C::View) -> V,
    V: View,
{
    /// Creates a new `Map` that transforms views from the source collection.
    ///
    /// # Parameters
    /// * `source` - The source view collection to map over
    /// * `f` - The transformation function to apply to each view
    ///
    /// # Returns
    /// A new `Map` instance that will apply the transformation to views
    #[must_use]
    pub const fn new(source: C, f: F) -> Self {
        Self { source, f }
    }
}

impl<C, F, V> Views for Map<C, F>
where
    C: Views,
    F: Clone + Fn(C::View) -> V,
    V: View,
{
    type Id = C::Id;
    type Guard = C::Guard;
    type View = V;

    fn len(&self) -> Computed<usize> {
        self.source.len()
    }

    fn get_id(&self, index: usize) -> Option<Self::Id> {
        self.source.get_id(index)
    }

    fn get_view(&self, index: usize) -> Option<Self::View> {
        self.source.get_view(index).map(&self.f)
    }

    fn watch(
        &self,
        range: impl RangeBounds<usize>,
        watcher: impl for<'a> Fn(Context<&'a [Self::Id]>) + 'static, // watcher will receive a slice of items, its range is decided by the range parameter
    ) -> Self::Guard {
        self.source.watch(range, watcher)
    }
}

/// Extension trait providing additional utilities for types implementing `Views`.
///
/// This trait provides convenient methods for transforming and manipulating view collections,
/// such as mapping views to different types.
pub trait ViewsExt: Views {
    /// Transforms each view in the collection using the provided mapping function.
    ///
    /// # Parameters
    /// * `f` - A function that transforms each view from the source type to a new view type
    ///
    /// # Returns
    /// A new `Map` view collection that applies the transformation to each element
    fn map<F, V>(self, f: F) -> Map<Self, F>
    where
        Self: Sized,
        F: Fn(Self::View) -> V,
        V: View,
    {
        Map::new(self, f)
    }

    /// Erases the specific type of the view collection, returning a type-erased `AnyViews`.
    fn erase(self) -> AnyViews<AnyView>
    where
        Self: 'static + Sized,
    {
        AnyViews::new(self.map(AnyView::new))
    }
}

impl<T: Views> ViewsExt for T {}

#[cfg(test)]
mod tests {
    use super::*;
    use alloc::{rc::Rc, vec, vec::Vec};
    use core::cell::RefCell;
    use nami::{Signal, SignalExt, binding, collection::List};

    #[derive(Clone, Debug)]
    struct TestItem {
        id: i32,
    }

    impl Identifiable for TestItem {
        type Id = i32;

        fn id(&self) -> Self::Id {
            self.id
        }
    }

    #[derive(Clone)]
    struct ReactiveLenViews {
        len_signal: nami::Binding<usize>,
    }

    impl Views for ReactiveLenViews {
        type Id = SelfId<usize>;
        type Guard = ();
        type View = ();

        fn get_id(&self, index: usize) -> Option<Self::Id> {
            (index < self.len_signal.get()).then_some(SelfId::new(index))
        }

        fn len(&self) -> Computed<usize> {
            self.len_signal.computed()
        }

        fn watch(
            &self,
            _range: impl RangeBounds<usize>,
            _watcher: impl for<'a> Fn(Context<&'a [Self::Id]>) + 'static,
        ) -> Self::Guard {
        }

        fn get_view(&self, index: usize) -> Option<Self::View> {
            (index < self.len_signal.get()).then_some(())
        }
    }

    #[test]
    fn len_tracks_reactive_len_signal() {
        let len_signal = binding(2usize);
        let views = ReactiveLenViews {
            len_signal: len_signal.clone(),
        };

        assert_eq!(views.len().get(), 2);
        len_signal.set(5);
        assert_eq!(views.len().get(), 5);
    }

    #[test]
    fn map_preserves_reactive_len() {
        let len_signal = binding(1usize);
        let views = ReactiveLenViews {
            len_signal: len_signal.clone(),
        };
        let mapped = views.map(|view| view);

        assert_eq!(mapped.len().get(), 1);
        len_signal.set(4);
        assert_eq!(mapped.len().get(), 4);
    }

    #[test]
    fn for_each_watch_uses_requested_range() {
        let list = List::from(vec![
            TestItem { id: 1 },
            TestItem { id: 2 },
            TestItem { id: 3 },
            TestItem { id: 4 },
        ]);
        let views = ForEach::new(list.clone(), |_item| ());

        let snapshots: Rc<RefCell<Vec<Vec<i32>>>> = Rc::new(RefCell::new(Vec::new()));
        let snapshots_ref = snapshots.clone();

        let _guard = Views::watch(&views, 1..3, move |ctx: Context<&[i32]>| {
            snapshots_ref.borrow_mut().push(ctx.into_value().to_vec());
        });

        assert_eq!(snapshots.borrow().as_slice(), &[vec![2, 3]]);

        list.insert(0, TestItem { id: 9 });
        let borrowed = snapshots.borrow();
        let latest_snapshot = borrowed.last().expect("watch should emit after insert");
        assert_eq!(latest_snapshot.as_slice(), &[1, 2]);
    }
}