Skip to main content

xrack_runtime/
list.rs

1use crate::{Node, VecModel};
2use std::{
3    collections::HashMap,
4    fmt,
5    ops::Range,
6    rc::{Rc, Weak},
7};
8
9pub(crate) const MAX_ROWS: usize = 1_000_000;
10
11#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
12pub struct RowKey {
13    pub(crate) model: u64,
14    pub(crate) row: u64,
15}
16
17pub struct RowLifetime(pub(crate) Option<Weak<()>>);
18
19impl RowLifetime {
20    pub(crate) fn is_live(&self, key: RowKey, model: u64, count: usize) -> bool {
21        key.model == model
22            && match &self.0 {
23                Some(lifetime) => lifetime.strong_count() != 0,
24                None => key.row < count as u64,
25            }
26    }
27}
28
29#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
30pub struct ListMetrics {
31    pub row_count: usize,
32    pub first_row: usize,
33}
34
35impl ListMetrics {
36    pub fn row_height(node: &Node) -> f32 {
37        Self::clamp_row_height(node.length("row-height").unwrap_or(32.0))
38    }
39
40    pub fn clamp_row_height(height: f32) -> f32 {
41        height.clamp(12.0, 512.0)
42    }
43
44    pub fn row_height_at(node: &Node, index: usize) -> f32 {
45        node.row_heights
46            .as_ref()
47            .map_or_else(|| Self::row_height(node), |heights| heights.height(index))
48    }
49
50    pub fn selection(node: &Node) -> Option<i64> {
51        if let Some(tree) = &node.tree {
52            return tree
53                .visible_index(node.int("current-key")?)
54                .map(|index| index as i64);
55        }
56        node.int(if node.kind == "TableView" {
57            "current-row"
58        } else {
59            "current-index"
60        })
61    }
62}
63
64/// Resolves stable model row identities without constructing their delegates.
65#[derive(Clone)]
66#[doc(hidden)]
67pub struct ListRowLocator(Rc<dyn RowPositions>);
68
69trait RowPositions {
70    fn first_position(&self, candidates: &[(RowKey, usize)]) -> Option<(usize, usize)>;
71}
72
73impl<M: ListModel> RowPositions for M {
74    fn first_position(&self, candidates: &[(RowKey, usize)]) -> Option<(usize, usize)> {
75        let &(first, hint) = candidates.first()?;
76        let count = self.row_count();
77        if count == 0 || self.row_key(0).model != first.model {
78            return None;
79        }
80        if hint < count && self.row_key(hint) == first {
81            return Some((0, hint));
82        }
83        // Nearby insertions and removals are common, including in deep lists.
84        let nearby = hint.saturating_sub(4)..count.min(hint.saturating_add(5));
85        if let Some(index) = nearby
86            .into_iter()
87            .find(|&index| self.row_key(index) == first)
88        {
89            return Some((0, index));
90        }
91
92        // Resolve all fallback rows in one pass when a whole page was removed.
93        let priorities: HashMap<_, _> = candidates
94            .iter()
95            .enumerate()
96            .map(|(priority, &(key, _))| (key, priority))
97            .collect();
98        let mut best = None;
99        let mut index = 0;
100        self.visit_row_keys(0..count, |key| {
101            if let Some(&priority) = priorities.get(&key)
102                && best.is_none_or(|(previous, _)| priority < previous)
103            {
104                best = Some((priority, index));
105            }
106            index += 1;
107        });
108        best
109    }
110}
111
112impl ListRowLocator {
113    pub fn new(model: Rc<impl ListModel + 'static>) -> Self {
114        Self(model)
115    }
116
117    pub fn first_position(&self, candidates: &[(RowKey, usize)]) -> Option<(usize, usize)> {
118        self.0.first_position(candidates)
119    }
120}
121
122impl PartialEq for ListRowLocator {
123    fn eq(&self, other: &Self) -> bool {
124        Rc::ptr_eq(&self.0, &other.0)
125    }
126}
127
128impl fmt::Debug for ListRowLocator {
129    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
130        formatter
131            .debug_struct("ListRowLocator")
132            .finish_non_exhaustive()
133    }
134}
135
136#[doc(hidden)]
137pub fn standard_list_rows<T: Clone + PartialEq>(
138    model: &VecModel<T>,
139    range: Range<usize>,
140    mut label: impl FnMut(T) -> String,
141) -> Vec<Node> {
142    range
143        .filter_map(|index| {
144            let value = model.row(index)?;
145            let key = model.row_key(index)?;
146            let mut item = Node::new("StandardListItem", None);
147            item.row_key = Some(key);
148            item.properties.insert("text", label(value).into());
149            Some(item)
150        })
151        .collect()
152}
153
154#[doc(hidden)]
155pub fn standard_table_rows<T, const COLUMNS: usize>(
156    model: &VecModel<T>,
157    range: Range<usize>,
158    project: impl Fn(&T) -> [String; COLUMNS],
159) -> Vec<Node> {
160    range
161        .filter_map(|index| {
162            let key = model.row_key(index)?;
163            let cells = model.project_row(index, &project)?;
164            let mut row = Node::new("TableRow", None);
165            row.row_key = Some(key);
166            row.children.extend(cells.map(|text| {
167                let mut cell = Node::new("TableCell", None);
168                cell.properties.insert("text", text.into());
169                cell
170            }));
171            Some(row)
172        })
173        .collect()
174}
175
176pub trait ListModel {
177    type Item: Clone + PartialEq;
178
179    fn row_count(&self) -> usize;
180    fn item(&self, row: usize) -> Self::Item;
181    fn row_key(&self, row: usize) -> RowKey;
182    fn visit_items(&self, mut visit: impl FnMut(usize, RowKey, &Self::Item)) {
183        for index in 0..self.row_count() {
184            visit(index, self.row_key(index), &self.item(index));
185        }
186    }
187    fn visit_row_keys(&self, range: Range<usize>, mut visit: impl FnMut(RowKey)) {
188        for index in range {
189            visit(self.row_key(index));
190        }
191    }
192    fn index_of_key(&self, key: RowKey) -> Option<usize> {
193        (0..self.row_count()).find(|&index| self.row_key(index) == key)
194    }
195    fn row_lifetime(&self, key: RowKey) -> RowLifetime;
196    fn structure_stamp(&self) -> (u64, u64);
197}
198
199impl ListModel for i64 {
200    type Item = i64;
201
202    fn row_count(&self) -> usize {
203        (*self).clamp(0, MAX_ROWS as i64) as usize
204    }
205
206    fn item(&self, row: usize) -> Self::Item {
207        row as i64
208    }
209
210    fn row_key(&self, row: usize) -> RowKey {
211        RowKey {
212            model: 0,
213            row: row as u64,
214        }
215    }
216    fn row_lifetime(&self, _: RowKey) -> RowLifetime {
217        RowLifetime(None)
218    }
219    fn index_of_key(&self, key: RowKey) -> Option<usize> {
220        let index = usize::try_from(key.row).ok()?;
221        (key.model == 0 && index < self.row_count()).then_some(index)
222    }
223    fn structure_stamp(&self) -> (u64, u64) {
224        (0, self.row_count() as u64)
225    }
226}
227
228impl<T: Clone + PartialEq> ListModel for VecModel<T> {
229    type Item = T;
230
231    fn row_count(&self) -> usize {
232        self.len().min(MAX_ROWS)
233    }
234    fn visit_items(&self, visit: impl FnMut(usize, RowKey, &Self::Item)) {
235        self.visit_row_data(self.row_count(), visit);
236    }
237
238    fn item(&self, row: usize) -> Self::Item {
239        self.row(row).expect("row is inside the model range")
240    }
241
242    fn row_key(&self, row: usize) -> RowKey {
243        self.row_key(row).expect("row is inside the model range")
244    }
245
246    fn row_lifetime(&self, key: RowKey) -> RowLifetime {
247        self.row_lifetime(key)
248    }
249    fn index_of_key(&self, key: RowKey) -> Option<usize> {
250        self.row_index(key).filter(|&index| index < MAX_ROWS)
251    }
252    fn visit_row_keys(&self, range: Range<usize>, visit: impl FnMut(RowKey)) {
253        self.visit_row_keys(range, visit);
254    }
255    fn structure_stamp(&self) -> (u64, u64) {
256        self.structure_stamp()
257    }
258}