Skip to main content

glory_ui/each/
source.rs

1//! Source adapters. Keyed members keep their direct aliases; vectors keep row cages.
2use super::*;
3use glory_core::{Bond, Cage, KeyedEntry, KeyedList, RowToken, RuntimeId, Vary};
4use std::borrow::Cow;
5
6mod sealed {
7    pub trait Source {}
8    pub trait Input {}
9}
10
11/// A stable keyed source for the shared Each controller.
12#[doc(hidden)]
13pub trait Source: sealed::Source + 'static {
14    type Key: Clone + Eq + Hash + 'static;
15    type Row;
16    type Seed;
17    type Data: 'static;
18    type Ownership: super::Ownership;
19    fn validate(&self, runtime: RuntimeId) -> Result;
20    fn refresh(&mut self) -> Result<usize>;
21    fn key(&self, index: usize) -> Self::Key;
22    fn prepare(&self, index: usize, key: &Self::Key) -> Result<Self::Seed>;
23    fn row(&self, seed: Self::Seed, owner: &CoreScope) -> (Self::Row, Self::Data);
24    fn update(&self, index: usize, data: &mut Self::Data);
25}
26
27/// Input conversion performs no reactive reads or mounting.
28pub trait IntoSource: sealed::Input {
29    type Source;
30    #[doc(hidden)]
31    fn into_source(self) -> Self::Source;
32}
33
34pub struct Members<K: 'static, T: 'static> {
35    source: KeyedList<K, T>,
36    tokens: Vec<RowToken<K>>,
37}
38impl<K, T> sealed::Input for KeyedList<K, T> {}
39impl<K, T> IntoSource for KeyedList<K, T> {
40    type Source = Members<K, T>;
41    fn into_source(self) -> Self::Source {
42        Members {
43            source: self,
44            tokens: Vec::new(),
45        }
46    }
47}
48impl<K, T> sealed::Source for Members<K, T> {}
49impl<K: Clone + Eq + Hash + 'static, T: 'static> Source for Members<K, T> {
50    type Key = u64;
51    type Row = KeyedEntry<K, T>;
52    type Seed = KeyedEntry<K, T>;
53    type Data = ();
54    type Ownership = super::Direct;
55    fn validate(&self, runtime: RuntimeId) -> Result {
56        if self.source.runtime() != runtime || !self.source.is_alive() {
57            return Err(glory_render::Error::InvalidProps("foreign or disposed list").into());
58        }
59        Ok(())
60    }
61    fn refresh(&mut self) -> Result<usize> {
62        self.tokens = self.source.try_with_order(<[_]>::to_vec)?;
63        Ok(self.tokens.len())
64    }
65    fn key(&self, index: usize) -> u64 {
66        self.tokens[index].id()
67    }
68    fn prepare(&self, index: usize, _: &u64) -> Result<Self::Seed> {
69        Ok(self.source.entry(&self.tokens[index])?)
70    }
71    fn row(&self, seed: Self::Seed, _: &CoreScope) -> (Self::Row, ()) {
72        (seed, ())
73    }
74    fn update(&self, _: usize, _: &mut ()) {}
75}
76
77/// A vector needs an explicit stable key before it can render rows.
78pub struct Unkeyed<T: 'static>(pub(super) Vary<Vec<T>>);
79macro_rules! input {
80    ($ty:ty) => {
81        impl<T: Clone + 'static> sealed::Input for $ty {}
82        impl<T: Clone + 'static> IntoSource for $ty {
83            type Source = Unkeyed<T>;
84            fn into_source(self) -> Self::Source {
85                Unkeyed(self.into())
86            }
87        }
88    };
89}
90input!(Vec<T>);
91input!(Vary<Vec<T>>);
92input!(Cage<Vec<T>>);
93input!(Bond<Vec<T>>);
94
95pub struct Values<T: 'static, K, F> {
96    pub(super) source: Vary<Vec<T>>,
97    pub(super) key: F,
98    pub(super) items: Vec<T>,
99    pub(super) marker: std::marker::PhantomData<K>,
100}
101
102/// Reactive vector row. Both handles belong to the row's data Owner.
103pub struct ValueRow<K, T: 'static> {
104    key: K,
105    pub value: Cage<T>,
106    pub index: Cage<usize>,
107}
108impl<K: Clone, T> Clone for ValueRow<K, T> {
109    fn clone(&self) -> Self {
110        Self {
111            key: self.key.clone(),
112            value: self.value,
113            index: self.index,
114        }
115    }
116}
117impl<K, T> ValueRow<K, T> {
118    pub fn key(&self) -> &K {
119        &self.key
120    }
121    pub fn try_with_untracked<R>(
122        &self,
123        read: impl FnOnce(&T) -> R,
124    ) -> std::result::Result<R, glory_core::AccessError> {
125        self.value.try_with_untracked(read)
126    }
127    pub fn update<R>(
128        &self,
129        edit: impl FnOnce(&mut T) -> R,
130    ) -> std::result::Result<R, glory_core::AccessError> {
131        self.value.try_revise(edit)
132    }
133    pub fn field<U: 'static>(
134        &self,
135        name: impl Into<Cow<'static, str>>,
136        get: impl for<'a> Fn(&'a T) -> &'a U + 'static,
137        get_mut: impl for<'a> Fn(&'a mut T) -> &'a mut U + 'static,
138    ) -> Cage<U> {
139        self.value.field(name, get, get_mut)
140    }
141}
142impl<T, K, F> sealed::Source for Values<T, K, F> {}
143fn validate<T>(source: &Vary<Vec<T>>, runtime: RuntimeId) -> Result {
144    let valid = match source {
145        Vary::Value(_) => true,
146        Vary::Cage(value) => value.runtime() == runtime && value.is_alive(),
147        Vary::Bond(value) => value.runtime() == runtime && value.is_alive(),
148    };
149    if valid {
150        Ok(())
151    } else {
152        Err(glory_render::Error::InvalidProps("foreign or disposed list").into())
153    }
154}
155impl<T, K, F> Source for Values<T, K, F>
156where
157    T: Clone + 'static,
158    K: Clone + Eq + Hash + 'static,
159    F: Fn(&T) -> K + 'static,
160{
161    type Key = K;
162    type Row = ValueRow<K, T>;
163    type Seed = (usize, K);
164    type Data = (Cage<T>, Cage<usize>);
165    type Ownership = super::Reactive;
166    fn validate(&self, runtime: RuntimeId) -> Result {
167        validate(&self.source, runtime)
168    }
169    fn refresh(&mut self) -> Result<usize> {
170        self.items = self.source.try_get()?;
171        Ok(self.items.len())
172    }
173    fn key(&self, index: usize) -> K {
174        (self.key)(&self.items[index])
175    }
176    fn prepare(&self, index: usize, key: &K) -> Result<Self::Seed> {
177        Ok((index, key.clone()))
178    }
179    fn row(&self, (index, key): Self::Seed, owner: &CoreScope) -> (Self::Row, Self::Data) {
180        let value = owner.cage(self.items[index].clone());
181        let position = owner.cage(index);
182        (
183            ValueRow {
184                key,
185                value,
186                index: position,
187            },
188            (value, position),
189        )
190    }
191    fn update(&self, index: usize, (value, position): &mut Self::Data) {
192        value.revise(|value| *value = self.items[index].clone());
193        if position.get_untracked() != index {
194            position.revise(|value| *value = index);
195        }
196    }
197}
198
199#[doc(hidden)]
200pub trait Initial: Source {
201    type Value;
202    fn initial(&self, index: usize) -> Result<Self::Value>;
203}
204impl<T, K, F> Initial for Values<T, K, F>
205where
206    T: Clone + 'static,
207    K: Clone + Eq + Hash + 'static,
208    F: Fn(&T) -> K + 'static,
209{
210    type Value = T;
211    fn initial(&self, index: usize) -> Result<T> {
212        Ok(self.items[index].clone())
213    }
214}
215impl<K: Clone + Eq + Hash + 'static, T: Clone + 'static> Initial for Members<K, T> {
216    type Value = T;
217    fn initial(&self, index: usize) -> Result<T> {
218        Ok(self
219            .source
220            .entry(&self.tokens[index])?
221            .try_with_untracked(Clone::clone)?)
222    }
223}
224pub struct Seeds<S>(pub(super) S);
225impl<S> sealed::Source for Seeds<S> {}
226impl<S: Initial> Source for Seeds<S> {
227    type Key = S::Key;
228    type Row = S::Value;
229    type Seed = S::Value;
230    type Data = ();
231    type Ownership = super::Direct;
232    fn validate(&self, runtime: RuntimeId) -> Result {
233        self.0.validate(runtime)
234    }
235    fn refresh(&mut self) -> Result<usize> {
236        self.0.refresh()
237    }
238    fn key(&self, index: usize) -> Self::Key {
239        self.0.key(index)
240    }
241    fn prepare(&self, index: usize, _: &Self::Key) -> Result<Self::Seed> {
242        self.0.initial(index)
243    }
244    fn row(&self, seed: Self::Seed, _: &CoreScope) -> (Self::Row, ()) {
245        (seed, ())
246    }
247    fn update(&self, _: usize, _: &mut ()) {}
248}