dioxus-shareables 0.3.0

Hooks for sharing structures between components.
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
//! mod `list` - lists of shared values.
//!
//! See [`List`] for more info.

use crate::shared::{Link, Shareable, Shared};
use std::sync::Arc;

/// A list of shareable values.
///
/// Using a `List<T>` rather than a `Vec<T>` allows components which use only one or two list items
/// to get updated only when the specific list items they use are changed.
///
/// ```rust
/// # use dioxus::prelude::*;
/// use dioxus_shareables::{shareable, List, ListEntry};
///
/// shareable!(Numbers: List<usize> = [3, 5, 7].into_iter().collect());
///
/// #[allow(non_snake_case)]
/// fn ListNumbers(cx: Scope) -> Element {
///     let nums = Numbers.use_rw(&cx); // This component is updated when new items are added to or
///                                     // removed from the list, but not when the individual list
///                                     // items change.
///     let w = nums.clone();
///     cx.render(rsx! {
///         ul {
///             nums.read().iter().map(|n| rsx! { ListItem { num: n } })
///         }
///         button {
///             onclick: move |_| {
///                 let mut w = w.write();
///                 let sum = w.iter().map(|n| *n.share().read()).sum();
///                 w.push(sum)
///             },
///             "Sum"
///         }
///     })
/// }
///
/// #[allow(non_snake_case)]
/// #[inline_props]
/// fn ListItem(cx: Scope, num: ListEntry<usize>) -> Element {
///     let num = num.use_rw(&cx); // This component is updated when this specific entry in the
///                                // list is modified.
///     let w1 = num.clone();
///     let w2 = num.clone();
///     let num = num.read();
///
///     cx.render(rsx! {
///         li {
///             "{num}",
///             button { onclick: move |_| *w1.write() += 1, "+" }
///             button { onclick: move |_| *w2.write() -= 1, "-" }
///         }
///     })
/// }
///
/// ```
///
/// `List` is a [`Vec`] internally, and the methods it implements therefore get their names and
/// behavior from [`Vec`].
///
pub struct List<T>(Vec<ListEntry<T>>);

#[allow(non_camel_case_types)]
pub type share_entry_w<T> = fn(ListEntry<T>) -> Shared<T, super::W>;
pub type Drain<'a, T> = std::iter::Map<std::vec::Drain<'a, ListEntry<T>>, share_entry_w<T>>;
impl<T> List<T> {
    /// See [`Vec::append`]
    pub fn append(&mut self, o: &mut Self) {
        self.0.append(&mut o.0)
    }
    /// See [`Vec::capacity`]
    pub fn capacity(&self) -> usize {
        self.0.capacity()
    }
    /// See [`Vec::clear`]
    pub fn clear(&mut self) {
        self.0.clear()
    }
    /// See [`Vec::dedup`]
    pub fn dedup(&mut self)
    where
        T: PartialEq,
    {
        self.dedup_by(PartialEq::eq)
    }
    /// See [`Vec::dedup_by`]
    pub fn dedup_by<F: FnMut(&T, &T) -> bool>(&mut self, mut f: F) {
        self.0.dedup_by(|r, s| f(&r.0.borrow(), &s.0.borrow()))
    }
    /// See [`Vec::dedup_by_key`]
    pub fn dedup_by_key<K: PartialEq, F: FnMut(&T) -> K>(&mut self, mut f: F) {
        self.0.dedup_by(|r, s| f(&r.0.borrow()) == f(&s.0.borrow()))
    }
    /// See [`Vec::drain`]
    pub fn drain<R: std::ops::RangeBounds<usize>>(&mut self, range: R) -> Drain<T>
    where
        T: 'static,
    {
        self.0.drain(range).map(|l| Shared::from_link(l.0))
    }
    /// See [`Vec::insert`]
    pub fn insert(&mut self, index: usize, element: T) {
        self.0.insert(index, ListEntry::new(element))
    }
    /// See [`Vec::is_empty`]
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }
    /// See [`Vec::len`]
    pub fn len(&self) -> usize {
        self.0.len()
    }
    /// See [`Vec::new`]
    pub fn new() -> Self {
        Self(Vec::new())
    }
    /// See [`Vec::pop`]
    pub fn pop(&mut self) -> Option<Shared<T, super::W>> {
        self.0.pop().map(|l| Shared::from_link(l.0))
    }
    /// See [`Vec::push`]
    pub fn push(&mut self, value: T) {
        self.0.push(ListEntry::new(value))
    }
    /// See [`Vec::remove`]
    pub fn remove(&mut self, index: usize) -> Shared<T, super::W> {
        Shared::from_link(self.0.remove(index).0)
    }
    /// See [`Vec::reserve`]
    pub fn reserve(&mut self, additional: usize) {
        self.0.reserve(additional)
    }
    /// See [`Vec::reserve_exact`]
    pub fn reserve_exact(&mut self, additional: usize) {
        self.0.reserve_exact(additional)
    }
    /// See [`Vec::resize`]
    pub fn resize(&mut self, new_len: usize, t: T)
    where
        T: Clone,
    {
        self.0.resize_with(new_len, || ListEntry::new(t.clone()))
    }
    /// See [`Vec::resize_with`]
    pub fn resize_with<F: FnMut() -> T>(&mut self, new_len: usize, mut f: F) {
        self.0.resize_with(new_len, || ListEntry::new(f()))
    }
    /// See [`Vec::retain`]
    pub fn retain<F: FnMut(&T) -> bool>(&mut self, mut f: F) {
        self.0.retain(|l| f(&l.0.borrow()))
    }
    /// See [`Vec::retain`]
    pub fn retain_mut<F: FnMut(&mut ListEntry<T>) -> bool>(&mut self, f: F)
    where
        T: 'static,
    {
        self.0.retain_mut(f)
    }
    /// See [`Vec::shrink_to`]
    pub fn shrink_to(&mut self, min_capacity: usize) {
        self.0.shrink_to(min_capacity)
    }
    /// See [`Vec::shrink_to_fit`]
    pub fn shrink_to_fit(&mut self) {
        self.0.shrink_to_fit()
    }
    /// See [`Vec::splice`]
    pub fn splice<'a, R: std::ops::RangeBounds<usize>, I: 'a + IntoIterator<Item = T>>(
        &'a mut self,
        range: R,
        replace_with: I,
    ) -> impl 'a + Iterator<Item = Shared<T, super::W>>
    where
        T: 'static,
    {
        self.0
            .splice(range, replace_with.into_iter().map(ListEntry::new))
            .map(|l| Shared::from_link(l.0))
    }
    /// See [`Vec::split_off`]
    pub fn split_off(&mut self, at: usize) -> Self {
        Self(self.0.split_off(at))
    }
    /// See [`Vec::swap_remove`]
    pub fn swap_remove(&mut self, index: usize) -> Shared<T, super::W> {
        Shared::from_link(self.0.swap_remove(index).0)
    }
    /// See ['Vec::truncate`]
    pub fn truncate(&mut self, len: usize) {
        self.0.truncate(len)
    }
    /// See ['Vec::try_reserve`]
    pub fn try_reserve(
        &mut self,
        additional: usize,
    ) -> Result<(), std::collections::TryReserveError> {
        self.0.try_reserve(additional)
    }
    /// See ['Vec::try_reserve_exact`]
    pub fn try_reserve_exact(
        &mut self,
        additional: usize,
    ) -> Result<(), std::collections::TryReserveError> {
        self.0.try_reserve_exact(additional)
    }
    /// See ['Vec::with_capacity`]
    pub fn with_capcity(capacity: usize) -> Self {
        Self(Vec::with_capacity(capacity))
    }
    /// See [`[_]::binary_search`]
    pub fn binary_search(&self, x: &T) -> Result<usize, usize>
    where
        T: Ord,
    {
        self.binary_search_by(|l| x.cmp(l))
    }
    /// See [`[_]::binary_search`]
    pub fn binary_search_by<F: FnMut(&T) -> std::cmp::Ordering>(
        &self,
        mut f: F,
    ) -> Result<usize, usize> {
        self.0.binary_search_by(|l| f(&l.0.borrow()))
    }
    /// See [`[_]::binary_search_by_key`]
    pub fn binary_search_by_key<B: std::cmp::Ord, F: FnMut(&T) -> B>(
        &self,
        b: &B,
        mut f: F,
    ) -> Result<usize, usize> {
        self.0.binary_search_by_key(b, |l| f(&l.0.borrow()))
    }
    /// See [`[_]::contains`]
    pub fn contains(&self, x: &T) -> bool
    where
        T: PartialEq,
    {
        self.0.iter().any(|l| x == &*l.0.borrow())
    }
    /// See [`[_]::ends_with`]
    pub fn ends_with(&self, needle: &[T]) -> bool
    where
        T: PartialEq,
    {
        self.0.len() >= needle.len()
            && std::iter::zip(self.0.iter().rev(), needle.iter().rev())
                .all(|(l, x)| x == &*l.0.borrow())
    }
    /// See [`[_]::fill`]
    ///
    /// Note: This replaces items, rather than changing their value, so components which were
    /// linked to the list before will not (necessarily) update.
    pub fn fill(&mut self, t: T)
    where
        T: Clone,
    {
        self.0.fill_with(|| ListEntry::new(t.clone()))
    }
    /// See [`[_]::fill_with`]
    ///
    /// Note: This replaces items, rather than changing their value, so components which were
    /// linked to the list before will not (necessarily) update.
    pub fn fill_with<F: FnMut() -> T>(&mut self, mut f: F) {
        self.0.fill_with(|| ListEntry::new(f()))
    }
    /// See [`[_]::first`]
    pub fn first(&self) -> Option<ListEntry<T>> {
        self.0.first().cloned()
    }
    /// See [`[_]::get`]
    pub fn get(&self, index: usize) -> Option<ListEntry<T>> {
        self.0.get(index).cloned()
    }
    /// See [`[_]::get_unchecked`]
    ///
    /// # Safety
    ///   * The index must be in bounds for the slice, otherwise this method is u.b.
    pub unsafe fn get_unchecked(&self, index: usize) -> ListEntry<T> {
        self.0.get_unchecked(index).clone()
    }
    /// See [`[_]::iter`]
    pub fn iter(&self) -> <&Self as IntoIterator>::IntoIter {
        self.into_iter()
    }
    /// See [`[_]::last`]
    pub fn last(&self) -> Option<ListEntry<T>> {
        self.0.last().cloned()
    }
    /// See [`[_]::partition_point`]
    pub fn partition_point<P: FnMut(&T) -> bool>(&self, mut pred: P) -> usize {
        self.0.partition_point(|l| pred(&l.0.borrow()))
    }
    /// See [`[_]::reverse`]
    pub fn reverse(&mut self) {
        self.0.reverse()
    }
    /// See [`[_]::rotate_left`]
    pub fn rotate_left(&mut self, mid: usize) {
        self.0.rotate_left(mid)
    }
    /// See [`[_]::rotate_right`]
    pub fn rotate_right(&mut self, mid: usize) {
        self.0.rotate_right(mid)
    }
    /// See [`[_]::sort`]
    pub fn sort(&mut self)
    where
        T: Ord,
    {
        self.sort_by(Ord::cmp)
    }
    /// See [`[_]::sort_by`]
    pub fn sort_by<F: FnMut(&T, &T) -> std::cmp::Ordering>(&mut self, mut f: F) {
        self.0.sort_by(|a, b| f(&a.0.borrow(), &b.0.borrow()))
    }
    /// See [`[_]::sort_by`]
    pub fn sort_by_cached_key<U: Ord, F: FnMut(&T) -> U>(&mut self, mut f: F) {
        self.0.sort_by_cached_key(|a| f(&a.0.borrow()))
    }
    /// See [`[_]::sort_by`]
    pub fn sort_by_key<U: Ord, F: FnMut(&T) -> U>(&mut self, mut f: F) {
        self.0.sort_by_key(|a| f(&a.0.borrow()))
    }
    /// See [`[_]::sort`]
    pub fn sort_unstable(&mut self)
    where
        T: Ord,
    {
        self.sort_unstable_by(Ord::cmp)
    }
    /// See [`[_]::sort_by`]
    pub fn sort_unstable_by<F: FnMut(&T, &T) -> std::cmp::Ordering>(&mut self, mut f: F) {
        self.0
            .sort_unstable_by(|a, b| f(&a.0.borrow(), &b.0.borrow()))
    }
    /// See [`[_]::sort_by`]
    pub fn sort_unstable_by_key<U: Ord, F: FnMut(&T) -> U>(&mut self, mut f: F) {
        self.0.sort_unstable_by_key(|a| f(&a.0.borrow()))
    }
    /// See [`[_]::starts_with`]
    pub fn starts_with(&self, needle: &[T]) -> bool
    where
        T: PartialEq,
    {
        self.0.len() >= needle.len()
            && std::iter::zip(&self.0, needle).all(|(l, x)| x == &*l.0.borrow())
    }
    /// See [`[_]::swap`]
    pub fn swap(&mut self, a: usize, b: usize) {
        self.0.swap(a, b)
    }
}
impl<T> Default for List<T> {
    fn default() -> Self {
        Self::new()
    }
}
impl<'a, T> IntoIterator for &'a List<T> {
    type Item = ListEntry<T>;
    type IntoIter = std::iter::Cloned<std::slice::Iter<'a, ListEntry<T>>>;
    fn into_iter(self) -> Self::IntoIter {
        self.0.iter().cloned()
    }
}
impl<T> FromIterator<T> for List<T> {
    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
        Self(iter.into_iter().map(ListEntry::new).collect())
    }
}
impl<T> Extend<T> for List<T> {
    fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
        self.0.extend(iter.into_iter().map(ListEntry::new))
    }
}
impl<'a, T: 'a + Clone> Extend<&'a T> for List<T> {
    fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
        self.0.extend(iter.into_iter().cloned().map(ListEntry::new))
    }
}

/// A pointer to an element from a [`List`]
///
/// Note that this cannot be used directly to get access to the value in the list. Instead, one
/// must use either one of the methods [`use_w`](Self::use_w) or [`use_rw`](Self::use_rw).
///
/// `ListEntry` implements [`PartialEq`] _AS A POINTER ONLY_. This is so that the properties of a
/// component depend only on which list entry is referenced, and not on the value.
pub struct ListEntry<T>(Arc<Link<T>>);
impl<T> PartialEq for ListEntry<T> {
    fn eq(&self, o: &Self) -> bool {
        Arc::ptr_eq(&self.0, &o.0)
    }
}
impl<T> Clone for ListEntry<T> {
    fn clone(&self) -> Self {
        Self(self.0.clone())
    }
}
impl<T> ListEntry<T> {
    fn new(t: T) -> Self {
        ListEntry(Arc::new(Link::new(t)))
    }
    /// Get a write-only pointer to the element.
    ///
    /// This is generally how an entry is accessed from the component which owns its `List`.
    /// If the entry was passed down from a parent component, then you generally want to call
    /// [`use_w`](Self::use_w) or [`use_rw`](Self::use_rw) instead.
    pub fn share(&self) -> Shared<T, super::W> {
        Shared::from_link(self.0.clone())
    }
    /// Get a write pointer to the element as a hook.
    ///
    /// This is the expected way to get write-only access to an entry when it is passed down from a
    /// parent component. If you need to access an entry in the component which owns the list it
    /// belongs to, then you generally need to use [`share`](Self::share) instead.
    pub fn use_w<'a, P>(&self, cx: &dioxus_core::Scope<'a, P>) -> &'a mut Shared<T, super::W> {
        let mut opt = Shareable(Some(self.0.clone()));
        Shared::init(cx, &mut opt, || unreachable!(), super::W)
    }
    /// Get a read-write pointer to the element.
    ///
    /// Scope `cx` will be registered as needing update every time the referenced value changes.
    ///
    /// This is the expected ways to get read/write access an entry when it is passed down from a
    /// parent component. If you need to access an entry in the component which owns the list it
    /// belongs to, then you generally need to use [`share`](Self::share) instead.
    pub fn use_rw<'a, P>(&self, cx: &dioxus_core::Scope<'a, P>) -> &'a mut Shared<T, super::RW> {
        let mut opt = Shareable(Some(self.0.clone()));
        Shared::init(cx, &mut opt, || unreachable!(), super::RW)
    }
}