dioxus_stores/impls/vec.rs
1use crate::store::Store;
2use dioxus_signals::Writable;
3
4impl<Lens: Writable<Target = Vec<T>> + 'static, T: 'static> Store<Vec<T>, Lens> {
5 /// Pushes an item to the end of the vector. This will only mark the length of the vector as dirty.
6 ///
7 /// # Example
8 /// ```rust, no_run
9 /// use dioxus_stores::*;
10 /// let mut store = use_store(|| vec![1, 2, 3]);
11 /// store.push(4);
12 /// ```
13 pub fn push(&mut self, value: T) {
14 self.selector().mark_dirty_shallow();
15 self.selector().write_untracked().push(value);
16 }
17
18 /// Removes an item from the vector at the specified index and returns it. This will mark items after
19 /// the index and the length of the vector as dirty.
20 ///
21 /// # Example
22 /// ```rust, no_run
23 /// use dioxus_stores::*;
24 /// let mut store = use_store(|| vec![1, 2, 3]);
25 /// let removed = store.remove(1);
26 /// assert_eq!(removed, 2);
27 /// ```
28 pub fn remove(&mut self, index: usize) -> T {
29 self.selector().mark_dirty_shallow();
30 self.selector().mark_dirty_at_and_after_index(index);
31 self.selector().write_untracked().remove(index)
32 }
33
34 /// Inserts an item at the specified index in the vector. This will mark items at and after the index
35 /// and the length of the vector as dirty.
36 ///
37 /// # Example
38 /// ```rust, no_run
39 /// use dioxus_stores::*;
40 /// let mut store = use_store(|| vec![1, 2, 3]);
41 /// store.insert(1, 4);
42 /// ```
43 pub fn insert(&mut self, index: usize, value: T) {
44 self.selector().mark_dirty_shallow();
45 self.selector().mark_dirty_at_and_after_index(index);
46 self.selector().write_untracked().insert(index, value);
47 }
48
49 /// Clears the vector, marking it as dirty.
50 ///
51 /// # Example
52 /// ```rust, no_run
53 /// use dioxus_stores::*;
54 /// let mut store = use_store(|| vec![1, 2, 3]);
55 /// store.clear();
56 /// ```
57 pub fn clear(&mut self) {
58 self.selector().mark_dirty();
59 self.selector().write_untracked().clear();
60 }
61
62 /// Retains only the elements specified by the predicate. This will only mark the length of the vector
63 /// and items after the first removed item as dirty.
64 ///
65 /// # Example
66 /// ```rust, no_run
67 /// use dioxus_stores::*;
68 /// let mut store = use_store(|| vec![1, 2, 3, 4, 5]);
69 /// store.retain(|&x| x % 2 == 0);
70 /// assert_eq!(store.len(), 2);
71 /// ```
72 pub fn retain(&mut self, mut f: impl FnMut(&T) -> bool) {
73 let mut index = 0;
74 let mut first_removed_index = None;
75 self.selector().write_untracked().retain(|item| {
76 let keep = f(item);
77 if !keep {
78 first_removed_index = first_removed_index.or(Some(index));
79 }
80 index += 1;
81 keep
82 });
83 if let Some(index) = first_removed_index {
84 self.selector().mark_dirty_shallow();
85 self.selector().mark_dirty_at_and_after_index(index);
86 }
87 }
88}