Skip to main content

yse_model/
list.rs

1//! An incremental list model: a current snapshot plus a stream of structural
2//! changes that views can apply without rebuilding.
3
4use crate::{EventStream, Sink};
5use std::cell::RefCell;
6
7/// A structural change to a [`ListModel`].
8#[derive(Clone, Debug, PartialEq, Eq)]
9pub enum ListChange<T> {
10    /// `items` inserted starting at `index`.
11    Insert {
12        /// Index of the first inserted row.
13        index: usize,
14        /// Rows inserted at the index.
15        items: Vec<T>,
16    },
17    /// `len` rows removed starting at `index`.
18    Remove {
19        /// Index of the first removed row.
20        index: usize,
21        /// Number of consecutive rows removed.
22        len: usize,
23    },
24    /// Rows replaced starting at `index`.
25    Update {
26        /// Index of the first replaced row.
27        index: usize,
28        /// Replacement rows in display order.
29        items: Vec<T>,
30    },
31    /// The whole list was replaced.
32    Reset {
33        /// Complete replacement snapshot.
34        items: Vec<T>,
35    },
36}
37
38/// An incremental list model.
39pub struct ListModel<T> {
40    items: RefCell<Vec<T>>,
41    changes: Sink<ListChange<T>>,
42}
43
44impl<T> ListModel<T>
45where
46    T: Clone + 'static,
47{
48    /// Create an empty model.
49    pub fn new() -> Self {
50        Self {
51            items: RefCell::new(Vec::new()),
52            changes: Sink::new(),
53        }
54    }
55
56    /// Create a model from `items`.
57    pub fn from(items: Vec<T>) -> Self {
58        let model = Self::new();
59        model.replace_all(items);
60        model
61    }
62
63    /// Number of rows.
64    pub fn len(&self) -> usize {
65        self.items.borrow().len()
66    }
67
68    /// Whether the model is empty.
69    pub fn is_empty(&self) -> bool {
70        self.items.borrow().is_empty()
71    }
72
73    /// A stream of structural changes.
74    pub fn changes(&self) -> EventStream<ListChange<T>> {
75        self.changes.stream()
76    }
77
78    /// The row at `index`, if any.
79    pub fn get(&self, index: usize) -> Option<T> {
80        self.items.borrow().get(index).cloned()
81    }
82
83    /// A snapshot of the current rows.
84    pub fn snapshot(&self) -> Vec<T> {
85        self.items.borrow().clone()
86    }
87
88    /// Append `item`.
89    pub fn push(&self, item: T) {
90        self.insert(self.len(), item);
91    }
92
93    /// Append every item in `items`.
94    pub fn extend(&self, items: Vec<T>) {
95        if items.is_empty() {
96            return;
97        }
98        let index = self.len();
99        self.items.borrow_mut().extend(items.iter().cloned());
100        self.changes.send(ListChange::Insert { index, items });
101    }
102
103    /// Insert `item` at `index`.
104    pub fn insert(&self, index: usize, item: T) {
105        let mut items = self.items.borrow_mut();
106        if index > items.len() {
107            return;
108        }
109        items.insert(index, item.clone());
110        self.changes.send(ListChange::Insert {
111            index,
112            items: vec![item],
113        });
114    }
115
116    /// Remove the row at `index`; returns whether a row was removed.
117    pub fn remove(&self, index: usize) -> bool {
118        self.remove_range(index, 1)
119    }
120
121    /// Remove `len` rows starting at `index`; returns whether anything was
122    /// removed.
123    pub fn remove_range(&self, index: usize, len: usize) -> bool {
124        let mut items = self.items.borrow_mut();
125        if index >= items.len() || len == 0 {
126            return false;
127        }
128        let end = (index + len).min(items.len());
129        items.drain(index..end);
130        self.changes.send(ListChange::Remove {
131            index,
132            len: end - index,
133        });
134        true
135    }
136
137    /// Replace the row at `index`; returns whether the row existed.
138    pub fn set(&self, index: usize, item: T) -> bool {
139        let mut items = self.items.borrow_mut();
140        let Some(slot) = items.get_mut(index) else {
141            return false;
142        };
143        *slot = item.clone();
144        self.changes.send(ListChange::Update {
145            index,
146            items: vec![item],
147        });
148        true
149    }
150
151    /// Remove every row.
152    pub fn clear(&self) {
153        let len = self.items.borrow().len();
154        if len == 0 {
155            return;
156        }
157        self.items.borrow_mut().clear();
158        self.changes.send(ListChange::Remove { index: 0, len });
159    }
160
161    /// Replace the entire list.
162    pub fn replace_all(&self, items: Vec<T>) {
163        *self.items.borrow_mut() = items.clone();
164        self.changes.send(ListChange::Reset { items });
165    }
166
167    /// Sort the list in place with `compare`, emitting a single `Reset`.
168    pub fn sort_by<F>(&self, compare: F)
169    where
170        F: FnMut(&T, &T) -> std::cmp::Ordering,
171    {
172        let mut items = self.items.borrow_mut();
173        items.sort_by(compare);
174        let snapshot = items.clone();
175        drop(items);
176        self.changes.send(ListChange::Reset { items: snapshot });
177    }
178
179    /// Remove every row that does not satisfy `keep`, emitting one `Remove`
180    /// change per contiguous removed run (in ascending index order).
181    pub fn retain<F>(&self, mut keep: F)
182    where
183        F: FnMut(&T) -> bool,
184    {
185        let mut items = self.items.borrow_mut();
186        let mut runs: Vec<(usize, usize)> = Vec::new();
187        let mut run_start: Option<usize> = None;
188        for (index, item) in items.iter().enumerate() {
189            if keep(item) {
190                if let Some(start) = run_start.take() {
191                    runs.push((start, index - start));
192                }
193            } else if run_start.is_none() {
194                run_start = Some(index);
195            }
196        }
197        if let Some(start) = run_start {
198            runs.push((start, items.len() - start));
199        }
200        // Remove from the end so earlier indices stay valid.
201        for (index, len) in runs.iter().rev() {
202            items.drain(*index..*index + *len);
203        }
204        drop(items);
205        // Descending order keeps earlier indices valid for the view.
206        runs.reverse();
207        for (index, len) in runs {
208            self.changes.send(ListChange::Remove { index, len });
209        }
210    }
211}
212
213impl<T> Default for ListModel<T>
214where
215    T: Clone + 'static,
216{
217    fn default() -> Self {
218        Self::new()
219    }
220}