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