mod change;
mod diff;
pub use change::{ChangeLog, CollectionChange, Edit};
pub use diff::{diff, has_duplicate_ids};
pub use crate::id::{Identifiable, IdentifiableExt, SelfId, UseId};
use core::{
fmt,
ops::{Bound, Range, RangeBounds},
};
use alloc::{boxed::Box, rc::Rc, vec::Vec};
use crate::watcher::{Context, WatcherGuard};
pub type ItemId<C> = <C as Collection>::Id;
pub type BoxCollectionWatcher<T> = Box<dyn Fn(Context<&[T]>, &CollectionChange) + 'static>;
#[diagnostic::on_unimplemented(
message = "`{Self}` is not a reactive collection",
label = "expected a `Collection` implementation",
note = "use `nami::collection::List<T>` for an owned reactive sequence; for a sequence derived from a signal such as a `Binding<Vec<T>>`, wrap it in `nami::collection::SignalCollection`"
)]
pub trait Collection: 'static {
type Item: 'static;
type Id: Ord + Clone;
type Guard: CollectionWatcherGuard;
fn get_item(&self, index: usize) -> Option<Self::Item>;
fn count(&self) -> usize;
fn with_range<R>(
&self,
range: impl RangeBounds<usize>,
f: impl FnOnce(&[Self::Item]) -> R,
) -> R;
fn get_id(&self, index: usize) -> Option<Self::Id>;
fn watch(
&self,
range: impl RangeBounds<usize>,
watcher: impl Fn(Context<&[Self::Item]>, &CollectionChange) + 'static,
) -> Self::Guard;
}
pub trait CollectionWatcherGuard: WatcherGuard {
fn set_bounds(&self, start: Bound<usize>, end: Bound<usize>);
fn set_range(&self, range: impl RangeBounds<usize>)
where
Self: Sized,
{
self.set_bounds(range.start_bound().cloned(), range.end_bound().cloned());
}
}
pub type BoxCollectionWatcherGuard = Box<dyn CollectionWatcherGuard>;
impl CollectionWatcherGuard for () {
fn set_bounds(&self, _start: Bound<usize>, _end: Bound<usize>) {}
}
impl<G: CollectionWatcherGuard + ?Sized> CollectionWatcherGuard for Box<G> {
fn set_bounds(&self, start: Bound<usize>, end: Bound<usize>) {
(**self).set_bounds(start, end);
}
}
impl<G: CollectionWatcherGuard + ?Sized> CollectionWatcherGuard for Rc<G> {
fn set_bounds(&self, start: Bound<usize>, end: Bound<usize>) {
(**self).set_bounds(start, end);
}
}
macro_rules! static_collection {
($({$($generics:tt)*} $ty:ty, $id:ty, |$this:ident| $slice:expr, |$item:ident, $index:ident| $make_id:expr;)*) => {$(
impl<$($generics)*> Collection for $ty {
type Item = T;
type Id = $id;
type Guard = ();
fn get_item(&self, index: usize) -> Option<T> {
let $this = self;
$slice.get(index).cloned()
}
fn count(&self) -> usize {
let $this = self;
$slice.len()
}
fn with_range<R>(
&self,
range: impl RangeBounds<usize>,
f: impl FnOnce(&[T]) -> R,
) -> R {
let $this = self;
let slice: &[T] = $slice;
f(&slice[clamp_range(&range, slice.len())])
}
fn get_id(&self, $index: usize) -> Option<$id> {
let $this = self;
$slice.get($index).map(|$item| $make_id)
}
fn watch(
&self,
_range: impl RangeBounds<usize>,
_watcher: impl Fn(Context<&[T]>, &CollectionChange) + 'static,
) {
}
}
)*};
}
static_collection! {
{T: Identifiable + Clone + 'static} Vec<T>, T::Id,
|this| this.as_slice(), |item, _index| item.id();
{T: Clone + 'static} &'static [T], usize,
|this| <[T]>::as_ref(*this), |_item, index| index;
{T: Clone + 'static, const N: usize} [T; N], usize,
|this| this.as_slice(), |_item, index| index;
{T: Clone + 'static} Rc<[T]>, usize,
|this| <[T]>::as_ref(this), |_item, index| index;
{T: Clone + 'static} Box<[T]>, usize,
|this| <[T]>::as_ref(this), |_item, index| index;
}
macro_rules! forward_collection {
($($wrapper:ident),*) => {$(
impl<C: Collection> Collection for $wrapper<C> {
type Item = C::Item;
type Id = C::Id;
type Guard = C::Guard;
fn get_item(&self, index: usize) -> Option<Self::Item> {
(**self).get_item(index)
}
fn count(&self) -> usize {
(**self).count()
}
fn with_range<R>(
&self,
range: impl RangeBounds<usize>,
f: impl FnOnce(&[Self::Item]) -> R,
) -> R {
(**self).with_range(range, f)
}
fn get_id(&self, index: usize) -> Option<Self::Id> {
(**self).get_id(index)
}
fn watch(
&self,
range: impl RangeBounds<usize>,
watcher: impl Fn(Context<&[Self::Item]>, &CollectionChange) + 'static,
) -> Self::Guard {
(**self).watch(range, watcher)
}
}
)*};
}
forward_collection!(Box, Rc);
pub struct AnyCollection<T, Id> {
inner: Box<dyn AnyCollectionImpl<Item = T, Id = Id>>,
}
impl<T, Id> fmt::Debug for AnyCollection<T, Id> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("AnyCollection").finish_non_exhaustive()
}
}
trait AnyCollectionImpl {
type Item;
type Id;
fn get_item(&self, index: usize) -> Option<Self::Item>;
fn count(&self) -> usize;
fn with_bounds(&self, range: (Bound<usize>, Bound<usize>), f: &mut dyn FnMut(&[Self::Item]));
fn get_id(&self, index: usize) -> Option<Self::Id>;
fn watch(
&self,
range: (Bound<usize>, Bound<usize>),
watcher: BoxCollectionWatcher<Self::Item>,
) -> BoxCollectionWatcherGuard;
}
impl<C: Collection> AnyCollectionImpl for C {
type Item = C::Item;
type Id = C::Id;
fn get_item(&self, index: usize) -> Option<Self::Item> {
Collection::get_item(self, index)
}
fn count(&self) -> usize {
Collection::count(self)
}
fn with_bounds(&self, range: (Bound<usize>, Bound<usize>), f: &mut dyn FnMut(&[Self::Item])) {
Collection::with_range(self, range, f);
}
fn get_id(&self, index: usize) -> Option<C::Id> {
Collection::get_id(self, index)
}
fn watch(
&self,
range: (Bound<usize>, Bound<usize>),
watcher: BoxCollectionWatcher<Self::Item>,
) -> BoxCollectionWatcherGuard {
Box::new(Collection::watch(self, range, watcher))
}
}
impl<T: 'static, Id: Ord + Clone> AnyCollection<T, Id> {
pub fn new<C>(collection: C) -> Self
where
C: Collection<Item = T, Id = Id>,
{
Self {
inner: Box::new(collection),
}
}
#[must_use]
pub fn get_item(&self, index: usize) -> Option<T> {
self.inner.get_item(index)
}
#[must_use]
pub fn count(&self) -> usize {
self.inner.count()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.inner.count() == 0
}
pub fn with_range<R>(&self, range: impl RangeBounds<usize>, f: impl FnOnce(&[T]) -> R) -> R {
let mut f = Some(f);
let mut result = None;
self.inner.with_bounds(
(range.start_bound().cloned(), range.end_bound().cloned()),
&mut |items| {
if let Some(f) = f.take() {
result = Some(f(items));
}
},
);
result.expect("a collection must call the `with_range` callback exactly once")
}
#[must_use]
pub fn get_id(&self, index: usize) -> Option<Id> {
self.inner.get_id(index)
}
pub fn watch(
&self,
range: impl RangeBounds<usize>,
watcher: impl Fn(Context<&[T]>, &CollectionChange) + 'static,
) -> BoxCollectionWatcherGuard {
self.inner.watch(
(range.start_bound().cloned(), range.end_bound().cloned()),
Box::new(watcher),
)
}
}
impl<T: 'static, Id: Ord + Clone + 'static> Collection for AnyCollection<T, Id> {
type Item = T;
type Id = Id;
type Guard = BoxCollectionWatcherGuard;
fn get_item(&self, index: usize) -> Option<T> {
Self::get_item(self, index)
}
fn count(&self) -> usize {
Self::count(self)
}
fn with_range<R>(&self, range: impl RangeBounds<usize>, f: impl FnOnce(&[T]) -> R) -> R {
Self::with_range(self, range, f)
}
fn get_id(&self, index: usize) -> Option<Id> {
Self::get_id(self, index)
}
fn watch(
&self,
range: impl RangeBounds<usize>,
watcher: impl Fn(Context<&[T]>, &CollectionChange) + 'static,
) -> BoxCollectionWatcherGuard {
Self::watch(self, range, watcher)
}
}
#[must_use]
pub fn clamp_range(range: &impl RangeBounds<usize>, len: usize) -> Range<usize> {
resolve_range(
range.start_bound().cloned(),
range.end_bound().cloned(),
len,
)
}
#[must_use]
pub fn resolve_range(start: Bound<usize>, end: Bound<usize>, len: usize) -> Range<usize> {
let end = match end {
Bound::Included(n) => n.saturating_add(1),
Bound::Excluded(n) => n,
Bound::Unbounded => len,
}
.min(len);
let start = match start {
Bound::Included(n) => n,
Bound::Excluded(n) => n.saturating_add(1),
Bound::Unbounded => 0,
}
.min(end);
start..end
}