Skip to main content

xrack_runtime/
list.rs

1use crate::property::{ReadWatch, with_read_watch};
2use crate::{
3    Date, ListSelectionKeys, Node, Orientation, Property, TableRows, Time, Value, VecModel,
4};
5use std::{
6    cell::Cell,
7    cmp::Ordering as Comparison,
8    collections::HashMap,
9    fmt,
10    ops::Range,
11    rc::{Rc, Weak},
12    sync::atomic::{AtomicU64, Ordering},
13};
14
15pub(crate) const MAX_ROWS: usize = 1_000_000;
16
17thread_local! {
18    static ROW_SOURCE_WATCH: Cell<Option<Rc<ReadWatch>>> = const { Cell::new(None) };
19}
20
21fn with_row_source_watch<T>(render: impl FnOnce(&ReadWatch) -> T) -> T {
22    struct Restore(Option<Rc<ReadWatch>>);
23    impl Drop for Restore {
24        fn drop(&mut self) {
25            ROW_SOURCE_WATCH.set(self.0.take());
26        }
27    }
28
29    let watch = Rc::new(ReadWatch::default());
30    let _restore = Restore(ROW_SOURCE_WATCH.replace(Some(watch.clone())));
31    with_read_watch(&watch, || render(&watch))
32}
33
34/// Sample an ordinary repeat's model once, then reject writes to that model source during rendering.
35#[doc(hidden)]
36pub fn try_render_rows_from_source<M, E>(
37    source: impl FnOnce() -> Result<M, E>,
38    render: impl FnOnce(M) -> Result<Vec<Node>, E>,
39) -> Result<Vec<Node>, E> {
40    with_row_source_watch(|watch| {
41        let model = source()?;
42        watch.clear_changes();
43        watch.freeze();
44        let rows = render(model)?;
45        Ok(if watch.changed() { Vec::new() } else { rows })
46    })
47}
48
49/// Stop before another lookup if rendering changed the order or an already sampled item.
50pub(crate) fn try_render_stable_rows<M: ListModel, E>(
51    model: &M,
52    stamp: (u64, u64),
53    indices: impl IntoIterator<Item = usize>,
54    mut render: impl FnMut(usize) -> Result<Node, E>,
55) -> Result<Vec<Node>, E> {
56    let watch = ROW_SOURCE_WATCH.with(|slot| {
57        let watch = slot.take();
58        slot.set(watch.clone());
59        watch
60    });
61    if let Some(watch) = &watch {
62        // Row synchronization and row content bindings have their own cache dependencies.
63        watch.freeze();
64        if watch.changed() {
65            return Ok(Vec::new());
66        }
67    }
68    crate::property::watch_reads(|items| {
69        let mut nodes = Vec::new();
70        for index in indices {
71            // Observe model rows while allowing delegates to synchronize their own caches.
72            model.track_item(index);
73            nodes.push(items.without_new_reads(|| render(index))?);
74            if items.changed()
75                || model.structure_stamp() != stamp
76                || watch.as_ref().is_some_and(|watch| watch.changed())
77            {
78                return Ok(Vec::new());
79            }
80        }
81        Ok(nodes)
82    })
83}
84
85#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
86pub struct RowKey {
87    pub(crate) model: u64,
88    pub(crate) row: u64,
89    pub(crate) scope: u64,
90}
91
92/// Direction of an index lookup between the source model and a displayed view.
93#[derive(Clone, Copy, Debug)]
94#[doc(hidden)]
95pub enum ViewIndex {
96    FromSource,
97    ToSource,
98}
99
100impl ViewIndex {
101    pub fn parse(name: &str) -> Option<Self> {
102        match name {
103            "view-index-for-source" => Some(Self::FromSource),
104            "source-index-for-view" => Some(Self::ToSource),
105            _ => None,
106        }
107    }
108
109    pub fn try_query<E>(
110        self,
111        index: i64,
112        lookup: impl FnOnce(usize, Self) -> Result<Option<usize>, E>,
113    ) -> Result<i64, E> {
114        let Ok(index) = usize::try_from(index) else {
115            return Ok(-1);
116        };
117        Ok(lookup(index, self)?
118            .and_then(|index| i64::try_from(index).ok())
119            .unwrap_or(-1))
120    }
121
122    pub fn query(self, index: i64, lookup: impl FnOnce(usize, Self) -> Option<usize>) -> i64 {
123        self.try_query(index, |index, direction| {
124            Ok::<_, std::convert::Infallible>(lookup(index, direction))
125        })
126        .unwrap_or_else(|error| match error {})
127    }
128}
129
130impl RowKey {
131    pub(crate) fn in_view(self, scope: u64) -> Self {
132        Self { scope, ..self }
133    }
134
135    #[doc(hidden)]
136    pub fn has_view_scope(self) -> bool {
137        self.scope != 0
138    }
139}
140
141type RenderRows = dyn Fn(Range<usize>, &TableColumnWindow, Option<&Node>) -> Vec<Node>;
142
143struct RowRenderer {
144    scope: u64,
145    rows: Box<RenderRows>,
146    offsets: [Property<Option<f32>>; 2],
147    selection: Cell<Option<(Option<usize>, usize)>>,
148    tree_root: Cell<Option<(i64, Option<RowKey>)>>,
149}
150
151/// Materializes a single view in its component instance, including views in delegates.
152#[doc(hidden)]
153#[derive(Clone)]
154pub struct ListRowRenderer(Rc<RowRenderer>);
155
156impl Node {
157    /// Render rows through the virtual view at this path in the current base scene.
158    #[doc(hidden)]
159    pub fn list_rows_at(&self, path: &[usize], rows: Range<usize>) -> Vec<Node> {
160        let Some(node) = self.at_path(path) else {
161            return Vec::new();
162        };
163        let end = node
164            .list
165            .map_or(rows.end, |list| rows.end.min(list.row_count));
166        node.list_row_renderer
167            .as_ref()
168            .map_or_else(Vec::new, |renderer| {
169                renderer.render_in_scene(node, rows.start..end, &TableColumnWindow::default())
170            })
171    }
172
173    /// Recover the visual index, source key and delegate from a prepared row.
174    #[doc(hidden)]
175    pub fn list_event_row(&self, slot: usize) -> Option<(usize, RowKey, &Node)> {
176        let index = self.list?.first_row.checked_add(slot)?;
177        let row = self.child_at(slot)?;
178        Some((index, row.row_key?, row.child_at(0)?))
179    }
180}
181
182impl ListRowRenderer {
183    pub fn new(rows: impl Fn(Range<usize>) -> Vec<Node> + 'static) -> Self {
184        Self::with_columns(move |range, _| rows(range))
185    }
186
187    pub fn with_columns(
188        rows: impl Fn(Range<usize>, &TableColumnWindow) -> Vec<Node> + 'static,
189    ) -> Self {
190        Self::with_columns_in_scene(move |range, columns, _| rows(range, columns))
191    }
192
193    #[doc(hidden)]
194    pub fn with_columns_and_stamp(
195        rows: impl Fn(Range<usize>, &TableColumnWindow, Option<(u64, u64)>) -> Vec<Node> + 'static,
196    ) -> Self {
197        Self::with_columns_in_scene(move |range, columns, scene| {
198            rows(
199                range,
200                columns,
201                scene.and_then(|node| node.standard_list_stamp),
202            )
203        })
204    }
205
206    #[doc(hidden)]
207    pub fn with_columns_in_scene(
208        rows: impl Fn(Range<usize>, &TableColumnWindow, Option<&Node>) -> Vec<Node> + 'static,
209    ) -> Self {
210        static NEXT_VIEW: AtomicU64 = AtomicU64::new(1);
211        let scope = NEXT_VIEW
212            .try_update(Ordering::Relaxed, Ordering::Relaxed, |id| id.checked_add(1))
213            .expect("virtual view identities exhausted");
214        Self(Rc::new(RowRenderer {
215            scope,
216            rows: Box::new(rows),
217            offsets: Default::default(),
218            selection: Cell::default(),
219            tree_root: Cell::default(),
220        }))
221    }
222
223    pub fn render(&self, rows: Range<usize>) -> Vec<Node> {
224        self.render_in_columns(rows, &TableColumnWindow::default())
225    }
226
227    pub fn render_in_columns(&self, rows: Range<usize>, columns: &TableColumnWindow) -> Vec<Node> {
228        (self.0.rows)(rows, columns, None)
229    }
230
231    /// Materialize against the projection recorded by the scene that requested the rows.
232    #[doc(hidden)]
233    pub fn render_in_scene(
234        &self,
235        scene: &Node,
236        rows: Range<usize>,
237        columns: &TableColumnWindow,
238    ) -> Vec<Node> {
239        with_row_source_watch(|watch| {
240            let rows = (self.0.rows)(rows, columns, Some(scene));
241            if watch.changed() { Vec::new() } else { rows }
242        })
243    }
244
245    pub fn scope(&self) -> u64 {
246        self.0.scope
247    }
248
249    pub fn offset(&self, axis: Orientation) -> Option<f32> {
250        self.0.offsets[usize::from(axis == Orientation::Vertical)].get(|| None)
251    }
252
253    pub fn set_offset(&self, axis: Orientation, offset: f32) {
254        self.0.offsets[usize::from(axis == Orientation::Vertical)].set_if_changed(Some(offset));
255    }
256
257    pub fn selection_changed(&self, selected: Option<usize>, columns: usize) -> bool {
258        self.0
259            .selection
260            .get()
261            .is_some_and(|previous| previous != (selected, columns))
262    }
263
264    pub fn remember_selection(&self, selected: Option<usize>, columns: usize) {
265        self.0.selection.set(Some((selected, columns)));
266    }
267
268    pub fn tree_root_changed(&self, root: (i64, Option<RowKey>)) -> bool {
269        self.0
270            .tree_root
271            .get()
272            .is_some_and(|previous| previous != root)
273    }
274
275    pub fn remember_tree_root(&self, root: (i64, Option<RowKey>)) {
276        self.0.tree_root.set(Some(root));
277    }
278}
279
280/// Visible columns in declaration order. The default requests every column.
281#[doc(hidden)]
282#[derive(Clone, Debug, Default, PartialEq, Eq)]
283pub struct TableColumnWindow(Option<Rc<VisibleColumns>>);
284
285#[derive(Debug, PartialEq, Eq)]
286struct VisibleColumns {
287    indices: Box<[usize]>,
288    count: usize,
289}
290
291impl TableColumnWindow {
292    pub fn new(visible: impl IntoIterator<Item = bool>) -> Self {
293        let mut indices = Vec::new();
294        let mut count = 0;
295        for (index, visible) in visible.into_iter().enumerate() {
296            if visible {
297                indices.push(index);
298            }
299            count = index + 1;
300        }
301        Self((indices.len() != count).then(|| {
302            Rc::new(VisibleColumns {
303                indices: indices.into_boxed_slice(),
304                count,
305            })
306        }))
307    }
308
309    pub fn includes(&self, column: usize) -> bool {
310        self.dense_index(column).is_some()
311    }
312
313    pub fn dense_index(&self, column: usize) -> Option<usize> {
314        self.0.as_ref().map_or(Some(column), |visible| {
315            visible.indices.binary_search(&column).ok()
316        })
317    }
318
319    pub fn logical_index(&self, index: usize) -> usize {
320        self.0
321            .as_ref()
322            .map_or(index, |visible| visible.indices[index])
323    }
324
325    pub fn logical_len(&self, materialized: usize) -> usize {
326        self.0
327            .as_ref()
328            .map_or(materialized, |visible| visible.count)
329    }
330
331    pub fn columns(&self, count: usize) -> impl Iterator<Item = usize> + '_ {
332        self.0
333            .iter()
334            .flat_map(move |visible| {
335                visible
336                    .indices
337                    .iter()
338                    .copied()
339                    .take_while(move |&index| index < count)
340            })
341            .chain(0..if self.0.is_none() { count } else { 0 })
342    }
343}
344
345impl PartialEq for ListRowRenderer {
346    fn eq(&self, other: &Self) -> bool {
347        Rc::ptr_eq(&self.0, &other.0)
348    }
349}
350
351impl fmt::Debug for ListRowRenderer {
352    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
353        formatter
354            .debug_struct("ListRowRenderer")
355            .finish_non_exhaustive()
356    }
357}
358
359pub struct RowLifetime(pub(crate) Option<Weak<()>>);
360
361impl RowLifetime {
362    pub(crate) fn is_live(&self, key: RowKey, model: u64, count: usize) -> bool {
363        key.model == model
364            && match &self.0 {
365                Some(lifetime) => lifetime.strong_count() != 0,
366                None => key.row < count as u64,
367            }
368    }
369}
370
371#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
372pub struct ListMetrics {
373    pub row_count: usize,
374    pub first_row: usize,
375}
376
377impl ListMetrics {
378    /// Validate a row request against the model order used for layout.
379    #[doc(hidden)]
380    pub fn matches_scene_order(scene: Option<&Node>, stamp: Option<(u64, u64)>) -> bool {
381        scene.is_none_or(|node| node.standard_list_stamp == stamp)
382    }
383
384    pub fn row_height(node: &Node) -> f32 {
385        Self::clamp_row_height(node.length("row-height").unwrap_or(32.0))
386    }
387
388    pub fn clamp_row_height(height: f32) -> f32 {
389        height.clamp(12.0, 512.0)
390    }
391
392    pub fn row_height_at(node: &Node, index: usize) -> f32 {
393        node.row_heights
394            .as_ref()
395            .map_or_else(|| Self::row_height(node), |heights| heights.height(index))
396    }
397
398    pub fn selection(node: &Node) -> Option<i64> {
399        if let Some(tree) = &node.tree {
400            return tree
401                .visible_index(node.int("current-key")?)
402                .map(|index| index as i64);
403        }
404        node.int(if node.kind == "TableView" {
405            "current-row"
406        } else {
407            "current-index"
408        })
409    }
410
411    #[doc(hidden)]
412    pub fn effective_index(index: i64, count: usize) -> i64 {
413        match usize::try_from(index) {
414            Ok(position) if position < count => index,
415            _ => -1,
416        }
417    }
418
419    /// Check that a selection position still belongs to the rendered model order.
420    #[doc(hidden)]
421    pub fn has_row_in_model(node: &Node, index: usize, live_stamp: Option<(u64, u64)>) -> bool {
422        node.standard_list_stamp == live_stamp
423            && node.list.is_some_and(|list| index < list.row_count)
424    }
425}
426
427/// Resolves stable model row identities without constructing their delegates.
428#[derive(Clone)]
429#[doc(hidden)]
430pub struct ListRowLocator(Rc<dyn RowPositions>);
431
432trait RowPositions {
433    fn business_position(&self, _key: i64) -> Option<usize> {
434        None
435    }
436
437    fn first_position(&self, candidates: &[(RowKey, usize)]) -> Option<(usize, usize)>;
438    fn key_at(&self, index: usize) -> Option<RowKey>;
439    fn position_of_source_key(&self, key: RowKey, source_index: usize) -> Option<usize>;
440}
441
442impl<M: ListModel> RowPositions for M {
443    fn position_of_source_key(&self, key: RowKey, source_index: usize) -> Option<usize> {
444        self.index_of_source_key(key, source_index)
445    }
446
447    fn key_at(&self, index: usize) -> Option<RowKey> {
448        ListModel::key_at(self, index)
449    }
450
451    fn first_position(&self, candidates: &[(RowKey, usize)]) -> Option<(usize, usize)> {
452        let &(first, hint) = candidates.first()?;
453        let count = self.row_count();
454        if count == 0 || self.row_key(0).model != first.model {
455            return None;
456        }
457        if hint < count && self.row_key(hint) == first {
458            return Some((0, hint));
459        }
460        // Nearby insertions and removals are common, including in deep lists.
461        let nearby = hint.saturating_sub(4)..count.min(hint.saturating_add(5));
462        if let Some(index) = nearby
463            .into_iter()
464            .find(|&index| self.row_key(index) == first)
465        {
466            return Some((0, index));
467        }
468
469        // Resolve all fallback rows in one pass when a whole page was removed.
470        let priorities: HashMap<_, _> = candidates
471            .iter()
472            .enumerate()
473            .map(|(priority, &(key, _))| (key, priority))
474            .collect();
475        let mut best = None;
476        let mut index = 0;
477        self.visit_row_keys(0..count, |key| {
478            if let Some(&priority) = priorities.get(&key)
479                && best.is_none_or(|(previous, _)| priority < previous)
480            {
481                best = Some((priority, index));
482            }
483            index += 1;
484        });
485        best
486    }
487}
488
489struct KeyedPositions {
490    positions: Rc<dyn RowPositions>,
491    locate: Box<dyn Fn(i64) -> Option<usize>>,
492}
493
494impl RowPositions for KeyedPositions {
495    fn business_position(&self, key: i64) -> Option<usize> {
496        (self.locate)(key)
497    }
498
499    fn first_position(&self, candidates: &[(RowKey, usize)]) -> Option<(usize, usize)> {
500        self.positions.first_position(candidates)
501    }
502
503    fn key_at(&self, index: usize) -> Option<RowKey> {
504        self.positions.key_at(index)
505    }
506
507    fn position_of_source_key(&self, key: RowKey, source_index: usize) -> Option<usize> {
508        self.positions.position_of_source_key(key, source_index)
509    }
510}
511
512impl ListRowLocator {
513    pub fn new(model: Rc<impl ListModel + 'static>) -> Self {
514        Self(model)
515    }
516
517    /// Resolve keys against this frame's model and displayed order.
518    pub fn with_business_keys<T: Clone + PartialEq + 'static>(
519        self,
520        keys: Rc<ListSelectionKeys>,
521        model: Rc<VecModel<T>>,
522        order: Option<crate::TableRowPositions>,
523        key_of: impl Fn(&T) -> i64 + 'static,
524    ) -> Self {
525        let stamp = model.contents_stamp();
526        let key_of = Rc::new(key_of);
527        Self(Rc::new(KeyedPositions {
528            positions: self.0,
529            locate: Box::new(move |key| {
530                if model.contents_stamp() != stamp {
531                    return None;
532                }
533                let key_of = key_of.clone();
534                let source = keys.find(&model, key, move |row| key_of(row))?;
535                match &order {
536                    Some(order) => order.visual_index(source),
537                    None => Some(source),
538                }
539            }),
540        }))
541    }
542
543    pub fn business_position(&self, key: i64) -> Option<usize> {
544        self.0.business_position(key)
545    }
546
547    pub fn first_position(&self, candidates: &[(RowKey, usize)]) -> Option<(usize, usize)> {
548        self.0.first_position(candidates)
549    }
550
551    pub fn key_at(&self, index: usize) -> Option<RowKey> {
552        self.0.key_at(index)
553    }
554
555    pub(crate) fn position_of_source_key(&self, key: RowKey, source_index: usize) -> Option<usize> {
556        self.0.position_of_source_key(key, source_index)
557    }
558}
559
560impl PartialEq for ListRowLocator {
561    fn eq(&self, other: &Self) -> bool {
562        Rc::ptr_eq(&self.0, &other.0)
563    }
564}
565
566impl fmt::Debug for ListRowLocator {
567    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
568        formatter
569            .debug_struct("ListRowLocator")
570            .finish_non_exhaustive()
571    }
572}
573
574type FindListText = dyn Fn(usize, &dyn Fn(&str) -> bool) -> Option<usize>;
575
576/// Searches the model order captured by a prepared view, without creating delegates.
577#[derive(Clone)]
578#[doc(hidden)]
579pub struct ListTextSearch(Rc<FindListText>);
580
581impl ListTextSearch {
582    pub fn new<T: 'static>(
583        model: VecModel<T>,
584        order: Option<crate::TableRowPositions>,
585        label: impl Fn(&T) -> &str + 'static,
586    ) -> Self {
587        let stamp = model.structure_stamp();
588        let count = order
589            .as_ref()
590            .map_or_else(|| model.len(), crate::TableRowPositions::row_count)
591            .min(MAX_ROWS);
592        Self(Rc::new(move |start, matches| {
593            if model.structure_stamp() != stamp {
594                return None;
595            }
596            let find = |range: Range<usize>| {
597                if let Some(order) = &order {
598                    range.into_iter().find(|&index| {
599                        order.source_index(index).and_then(|source| {
600                            model.project_row_untracked(source, |row| matches(label(row)))
601                        }) == Some(true)
602                    })
603                } else {
604                    model.position_untracked(range, |row| matches(label(row)))
605                }
606            };
607            let start = start.min(count);
608            find(start..count).or_else(|| find(0..start))
609        }))
610    }
611
612    pub fn find(&self, start: usize, matches: impl Fn(&str) -> bool) -> Option<usize> {
613        (self.0)(start, &matches)
614    }
615}
616
617impl PartialEq for ListTextSearch {
618    fn eq(&self, other: &Self) -> bool {
619        Rc::ptr_eq(&self.0, &other.0)
620    }
621}
622
623impl fmt::Debug for ListTextSearch {
624    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
625        formatter
626            .debug_struct("ListTextSearch")
627            .finish_non_exhaustive()
628    }
629}
630
631#[doc(hidden)]
632pub fn standard_list_rows<T: Clone + PartialEq>(
633    model: &VecModel<T>,
634    range: Range<usize>,
635    label: impl FnMut(T) -> String,
636) -> Vec<Node> {
637    standard_list_rows_at(model, range, label)
638}
639
640#[doc(hidden)]
641pub fn standard_list_rows_in_view<T: Clone + PartialEq>(
642    rows: &TableRows<VecModel<T>>,
643    range: Range<usize>,
644    label: impl FnMut(T) -> String,
645) -> Vec<Node> {
646    standard_list_rows_at(
647        rows.source(),
648        range.filter_map(|row| rows.positions().source_index(row)),
649        label,
650    )
651}
652
653fn standard_list_rows_at<T: Clone + PartialEq>(
654    model: &VecModel<T>,
655    indices: impl Iterator<Item = usize>,
656    mut label: impl FnMut(T) -> String,
657) -> Vec<Node> {
658    indices
659        .filter_map(|index| {
660            let value = model.row(index)?;
661            let key = model.row_key(index)?;
662            let mut item = Node::new("StandardListItem", None);
663            item.set_row_key(Some(key));
664            item.properties.insert("text", label(value).into());
665            Some(item)
666        })
667        .collect()
668}
669
670#[doc(hidden)]
671pub fn standard_table_rows<T, const COLUMNS: usize>(
672    model: &VecModel<T>,
673    range: Range<usize>,
674    project: impl Fn(&T) -> [String; COLUMNS],
675) -> Vec<Node> {
676    standard_table_rows_with_header(model, range, |item| (None, project(item)))
677}
678
679#[doc(hidden)]
680pub fn standard_table_rows_with_header<T, const COLUMNS: usize>(
681    model: &VecModel<T>,
682    range: Range<usize>,
683    project: impl Fn(&T) -> (Option<String>, [String; COLUMNS]),
684) -> Vec<Node> {
685    standard_table_rows_at(model, range, [None; COLUMNS], project)
686}
687
688#[doc(hidden)]
689pub fn standard_table_rows_in_order<T, const COLUMNS: usize>(
690    rows: &TableRows<VecModel<T>>,
691    range: Range<usize>,
692    project: impl Fn(&T) -> (Option<String>, [String; COLUMNS]),
693) -> Vec<Node> {
694    standard_table_rows_with_editors_in_order(rows, range, [None; COLUMNS], project)
695}
696
697#[doc(hidden)]
698pub fn standard_table_rows_with_editors_in_order<T, const COLUMNS: usize>(
699    rows: &TableRows<VecModel<T>>,
700    range: Range<usize>,
701    editors: [Option<TableCellEditor>; COLUMNS],
702    project: impl Fn(&T) -> (Option<String>, [String; COLUMNS]),
703) -> Vec<Node> {
704    standard_table_rows_at(
705        rows.source(),
706        range.filter_map(|index| rows.positions().source_index(index)),
707        editors,
708        project,
709    )
710}
711
712/// Build only the visible cells and retain their declaration-order addresses.
713#[doc(hidden)]
714pub fn project_standard_table_rows<T: Clone + PartialEq>(
715    rows: &TableRows<VecModel<T>>,
716    range: Range<usize>,
717    columns: &TableColumnWindow,
718    column_count: usize,
719    header: impl Fn(&T) -> Option<String>,
720    cell: impl Fn(&T, usize) -> String,
721    editor: impl Fn(usize) -> Option<TableCellEditor>,
722) -> Vec<Node> {
723    try_project_standard_table_rows(rows, range, columns, column_count, header, cell, |column| {
724        Ok::<_, std::convert::Infallible>(editor(column))
725    })
726    .unwrap_or_else(|error| match error {})
727}
728
729#[doc(hidden)]
730pub fn try_project_standard_table_rows<T: Clone + PartialEq, E>(
731    rows: &TableRows<VecModel<T>>,
732    range: Range<usize>,
733    columns: &TableColumnWindow,
734    column_count: usize,
735    header: impl Fn(&T) -> Option<String>,
736    cell: impl Fn(&T, usize) -> String,
737    editor: impl Fn(usize) -> Result<Option<TableCellEditor>, E>,
738) -> Result<Vec<Node>, E> {
739    try_render_standard_table_rows(
740        || Ok(rows.clone()),
741        range,
742        columns,
743        None,
744        column_count,
745        header,
746        cell,
747        editor,
748    )
749}
750
751/// Resolve the row order and abandon it if an editor binding invalidates a dependency.
752#[doc(hidden)]
753pub fn render_standard_table_rows<T: Clone + PartialEq>(
754    rows: impl FnOnce() -> TableRows<VecModel<T>>,
755    range: Range<usize>,
756    columns: &TableColumnWindow,
757    expected_stamp: Option<(u64, u64)>,
758    column_count: usize,
759    header: impl Fn(&T) -> Option<String>,
760    cell: impl Fn(&T, usize) -> String,
761    editor: impl Fn(usize) -> Option<TableCellEditor>,
762) -> Vec<Node> {
763    try_render_standard_table_rows(
764        || Ok::<_, std::convert::Infallible>(rows()),
765        range,
766        columns,
767        expected_stamp,
768        column_count,
769        header,
770        cell,
771        |column| Ok(editor(column)),
772    )
773    .unwrap_or_else(|error| match error {})
774}
775
776#[doc(hidden)]
777pub fn try_render_standard_table_rows<T: Clone + PartialEq, E>(
778    rows: impl FnOnce() -> Result<TableRows<VecModel<T>>, E>,
779    range: Range<usize>,
780    columns: &TableColumnWindow,
781    expected_stamp: Option<(u64, u64)>,
782    column_count: usize,
783    header: impl Fn(&T) -> Option<String>,
784    cell: impl Fn(&T, usize) -> String,
785    editor: impl Fn(usize) -> Result<Option<TableCellEditor>, E>,
786) -> Result<Vec<Node>, E> {
787    crate::property::watch_reads(|reads| {
788        let rows = rows()?;
789        if expected_stamp.is_some_and(|stamp| stamp != rows.positions().stamp()) {
790            return Ok(Vec::new());
791        }
792        let row_count = rows.row_count();
793        let range = range.start..range.end.min(row_count);
794        if range.is_empty() || reads.changed() {
795            return Ok(Vec::new());
796        }
797        let mut visible = Vec::new();
798        for column in columns.columns(column_count) {
799            visible.push((column, editor(column)?));
800            if reads.changed() {
801                return Ok(Vec::new());
802            }
803        }
804        Ok(materialize_standard_table_rows(
805            &rows, range, columns, &visible, header, cell,
806        ))
807    })
808}
809
810fn materialize_standard_table_rows<T>(
811    rows: &TableRows<VecModel<T>>,
812    range: Range<usize>,
813    columns: &TableColumnWindow,
814    visible: &[(usize, Option<TableCellEditor>)],
815    header: impl Fn(&T) -> Option<String>,
816    cell: impl Fn(&T, usize) -> String,
817) -> Vec<Node> {
818    let model = rows.source();
819    range
820        .filter_map(|index| {
821            let index = rows.positions().source_index(index)?;
822            let key = model.row_key(index)?;
823            model.project_row(index, |item| {
824                let mut row = projected_table_row(key, header(item));
825                row.table_column_window = columns.clone();
826                row.children.extend(
827                    visible
828                        .iter()
829                        .map(|&(column, editor)| projected_table_cell(cell(item, column), editor)),
830                );
831                row
832            })
833        })
834        .collect()
835}
836
837/// The model field type used to validate a projected cell's text draft.
838#[doc(hidden)]
839#[derive(Clone, Copy, Debug, PartialEq, Eq)]
840pub enum TableCellEditor {
841    String,
842    Int,
843    Float,
844    Bool,
845    Date,
846    Time,
847}
848
849impl TableCellEditor {
850    pub fn parse(self, text: &str) -> Option<Value> {
851        match self {
852            Self::String => String::parse_cell(text).map(Value::String),
853            Self::Int => i64::parse_cell(text).map(Value::Int),
854            Self::Float => f64::parse_cell(text).map(Value::Float),
855            Self::Bool => bool::parse_cell(text).map(Value::Bool),
856            Self::Date => Date::parse_cell(text).map(Value::Date),
857            Self::Time => Time::parse_cell(text).map(Value::Time),
858        }
859    }
860
861    pub fn accepts(self, text: &str) -> bool {
862        self == Self::String || self.parse(text).is_some()
863    }
864}
865
866/// The field operations used by standard tables.
867#[doc(hidden)]
868pub trait TableField: fmt::Display + Sized {
869    const EDITOR: TableCellEditor;
870
871    fn parse_cell(text: &str) -> Option<Self>;
872    fn compare_cells(&self, other: &Self) -> Comparison;
873
874    fn cell_text(&self) -> String {
875        self.to_string()
876    }
877
878    fn matches_cell_text(&self, text: &str) -> bool {
879        self.cell_text() == text
880    }
881}
882
883macro_rules! ordered_table_field {
884    ($ty:ty, $editor:ident, $parse:expr) => {
885        impl TableField for $ty {
886            const EDITOR: TableCellEditor = TableCellEditor::$editor;
887
888            fn parse_cell(text: &str) -> Option<Self> {
889                $parse(text)
890            }
891
892            fn compare_cells(&self, other: &Self) -> Comparison {
893                self.cmp(other)
894            }
895        }
896    };
897}
898
899ordered_table_field!(i64, Int, |text: &str| text.trim().parse().ok());
900ordered_table_field!(bool, Bool, crate::table_paste_bool);
901ordered_table_field!(Date, Date, |text: &str| {
902    let [year, month, day] = parse_cell_parts(text.trim(), '-')?;
903    Date::new(year, month, day)
904});
905ordered_table_field!(Time, Time, |text: &str| {
906    let [hour, minute, second] = parse_cell_parts(text.trim(), ':')?;
907    Time::new(hour, minute, second)
908});
909
910impl TableField for String {
911    const EDITOR: TableCellEditor = TableCellEditor::String;
912
913    fn parse_cell(text: &str) -> Option<Self> {
914        Some(text.to_owned())
915    }
916
917    fn compare_cells(&self, other: &Self) -> Comparison {
918        self.cmp(other)
919    }
920
921    fn matches_cell_text(&self, text: &str) -> bool {
922        self == text
923    }
924}
925
926impl TableField for f64 {
927    const EDITOR: TableCellEditor = TableCellEditor::Float;
928
929    fn parse_cell(text: &str) -> Option<Self> {
930        text.trim()
931            .parse::<Self>()
932            .ok()
933            .filter(|value| value.is_finite())
934    }
935
936    fn compare_cells(&self, other: &Self) -> Comparison {
937        self.total_cmp(other)
938    }
939}
940
941fn parse_cell_parts(text: &str, separator: char) -> Option<[i64; 3]> {
942    let mut parts = text.split(separator);
943    let values = [
944        parts.next()?.parse().ok()?,
945        parts.next()?.parse().ok()?,
946        parts.next()?.parse().ok()?,
947    ];
948    parts.next().is_none().then_some(values)
949}
950
951fn standard_table_rows_at<T, const COLUMNS: usize>(
952    model: &VecModel<T>,
953    indices: impl Iterator<Item = usize>,
954    editors: [Option<TableCellEditor>; COLUMNS],
955    project: impl Fn(&T) -> (Option<String>, [String; COLUMNS]),
956) -> Vec<Node> {
957    indices
958        .filter_map(|index| {
959            let key = model.row_key(index)?;
960            let (header, cells) = model.project_row(index, &project)?;
961            let mut row = projected_table_row(key, header);
962            row.children.extend(
963                cells
964                    .into_iter()
965                    .zip(editors)
966                    .map(|(text, editor)| projected_table_cell(text, editor)),
967            );
968            Some(row)
969        })
970        .collect()
971}
972
973fn projected_table_row(key: RowKey, header: Option<String>) -> Node {
974    let mut row = Node::new("TableRow", None);
975    row.set_row_key(Some(key));
976    if let Some(header) = header {
977        row.properties.insert("row-header-text", header.into());
978    }
979    row
980}
981
982fn projected_table_cell(text: String, editor: Option<TableCellEditor>) -> Node {
983    let mut cell = Node::new("TableCell", None);
984    cell.properties.insert("text", text.into());
985    if editor.is_some() {
986        cell.properties.insert("editable", true.into());
987        cell.table_cell_editor = editor;
988    }
989    cell
990}
991
992pub trait ListModel {
993    type Item: Clone + PartialEq;
994
995    fn row_count(&self) -> usize;
996    fn item(&self, row: usize) -> Self::Item;
997    /// Track changes to this item when preparing an operation for a live row.
998    #[doc(hidden)]
999    fn track_item(&self, row: usize) {
1000        let _ = self.item(row);
1001    }
1002    /// Validate the source slot before watching the item. Cleanup events can
1003    /// follow the identity, while ordinary events require the original slot.
1004    #[doc(hidden)]
1005    fn event_row_index(&self, index: usize, key: RowKey, follow_row: bool) -> Option<usize> {
1006        if follow_row {
1007            self.index_of_source_key(key, index)
1008        } else {
1009            (self.key_at(index) == Some(key)).then_some(index)
1010        }
1011    }
1012    fn row_key(&self, row: usize) -> RowKey;
1013    #[doc(hidden)]
1014    fn key_at(&self, index: usize) -> Option<RowKey> {
1015        (index < self.row_count()).then(|| self.row_key(index))
1016    }
1017    fn visit_items(&self, mut visit: impl FnMut(usize, RowKey, &Self::Item)) {
1018        for index in 0..self.row_count() {
1019            visit(index, self.row_key(index), &self.item(index));
1020        }
1021    }
1022    fn visit_row_keys(&self, range: Range<usize>, mut visit: impl FnMut(RowKey)) {
1023        for index in range {
1024            visit(self.row_key(index));
1025        }
1026    }
1027    fn index_of_key(&self, key: RowKey) -> Option<usize> {
1028        (0..self.row_count()).find(|&index| self.row_key(index) == key)
1029    }
1030    #[doc(hidden)]
1031    fn index_of_source_key(&self, key: RowKey, source_index: usize) -> Option<usize> {
1032        if source_index < self.row_count() && self.row_key(source_index) == key {
1033            Some(source_index)
1034        } else {
1035            self.index_of_key(key)
1036        }
1037    }
1038    fn row_lifetime(&self, key: RowKey) -> RowLifetime;
1039    fn structure_stamp(&self) -> (u64, u64);
1040    /// Identify the model revision, including changes to its row values.
1041    #[doc(hidden)]
1042    fn contents_stamp(&self) -> (u64, u64) {
1043        self.structure_stamp()
1044    }
1045    #[doc(hidden)]
1046    fn source_structure_stamp(&self) -> (u64, u64) {
1047        self.structure_stamp()
1048    }
1049    #[doc(hidden)]
1050    fn visit_source_row_keys(&self, visit: impl FnMut(RowKey)) {
1051        self.visit_row_keys(0..self.row_count(), visit);
1052    }
1053}
1054
1055impl ListModel for i64 {
1056    type Item = i64;
1057
1058    fn row_count(&self) -> usize {
1059        (*self).clamp(0, MAX_ROWS as i64) as usize
1060    }
1061
1062    fn item(&self, row: usize) -> Self::Item {
1063        row as i64
1064    }
1065
1066    fn track_item(&self, _: usize) {}
1067
1068    fn row_key(&self, row: usize) -> RowKey {
1069        RowKey {
1070            model: 0,
1071            row: row as u64,
1072            scope: 0,
1073        }
1074    }
1075    fn row_lifetime(&self, _: RowKey) -> RowLifetime {
1076        RowLifetime(None)
1077    }
1078    fn index_of_key(&self, key: RowKey) -> Option<usize> {
1079        let index = usize::try_from(key.row).ok()?;
1080        (key.model == 0 && index < self.row_count()).then_some(index)
1081    }
1082    fn structure_stamp(&self) -> (u64, u64) {
1083        (0, self.row_count() as u64)
1084    }
1085}
1086
1087impl<T: Clone + PartialEq> ListModel for VecModel<T> {
1088    type Item = T;
1089
1090    fn row_count(&self) -> usize {
1091        self.len().min(MAX_ROWS)
1092    }
1093    fn visit_items(&self, visit: impl FnMut(usize, RowKey, &Self::Item)) {
1094        self.visit_row_data(self.row_count(), visit);
1095    }
1096
1097    fn item(&self, row: usize) -> Self::Item {
1098        self.row(row).expect("row is inside the model range")
1099    }
1100
1101    fn track_item(&self, row: usize) {
1102        self.project_row(row, |_| ());
1103    }
1104
1105    fn row_key(&self, row: usize) -> RowKey {
1106        self.row_key(row).expect("row is inside the model range")
1107    }
1108
1109    fn row_lifetime(&self, key: RowKey) -> RowLifetime {
1110        self.row_lifetime(key)
1111    }
1112    fn index_of_key(&self, key: RowKey) -> Option<usize> {
1113        self.row_index(key).filter(|&index| index < MAX_ROWS)
1114    }
1115    fn visit_row_keys(&self, range: Range<usize>, visit: impl FnMut(RowKey)) {
1116        self.visit_row_keys(range, visit);
1117    }
1118    fn structure_stamp(&self) -> (u64, u64) {
1119        self.structure_stamp()
1120    }
1121    fn contents_stamp(&self) -> (u64, u64) {
1122        self.contents_stamp()
1123    }
1124}
1125
1126#[cfg(test)]
1127mod tests {
1128    use super::*;
1129
1130    #[test]
1131    fn list_text_search_walks_model_labels_and_rejects_an_old_order() {
1132        let model = VecModel::from(
1133            (0..50_000)
1134                .map(|i| format!("Record {i:05}"))
1135                .collect::<Vec<_>>(),
1136        );
1137        let search = ListTextSearch::new(model.clone(), None, String::as_str);
1138        let visits = Cell::new(0);
1139        assert_eq!(
1140            search.find(49_998, |label| {
1141                visits.set(visits.get() + 1);
1142                label == "Record 49999"
1143            }),
1144            Some(49_999)
1145        );
1146        assert_eq!(visits.get(), 2);
1147        assert_eq!(
1148            search.find(49_999, |label| label == "Record 00000"),
1149            Some(0)
1150        );
1151        assert!(model.set_row(49_999, "Updated".into()));
1152        assert_eq!(
1153            search.find(49_999, |label| label == "Updated"),
1154            Some(49_999)
1155        );
1156        model.push("Record 50000".into());
1157        assert_eq!(search.find(0, |label| label == "Updated"), None);
1158    }
1159
1160    #[test]
1161    fn standard_table_projects_values_and_editor_flags_only_for_requested_columns() {
1162        use std::cell::RefCell;
1163
1164        let model = Rc::new(VecModel::from(vec!["A".to_owned(), "B".to_owned()]));
1165        let rows = crate::TableRowOrder::default().rows(model.clone());
1166        let values = RefCell::new(Vec::new());
1167        let flags = RefCell::new(Vec::new());
1168        let view = project_standard_table_rows(
1169            &rows,
1170            0..2,
1171            &TableColumnWindow::new(vec![true, false, true, false]),
1172            4,
1173            |item| Some(item.clone()),
1174            |item, column| {
1175                values.borrow_mut().push((item.clone(), column));
1176                format!("{item}:{column}")
1177            },
1178            |column| {
1179                flags.borrow_mut().push(column);
1180                Some(TableCellEditor::String)
1181            },
1182        );
1183        assert_eq!(*flags.borrow(), [0, 2]);
1184        assert_eq!(
1185            values
1186                .borrow()
1187                .iter()
1188                .map(|(_, column)| *column)
1189                .collect::<Vec<_>>(),
1190            [0, 2, 0, 2]
1191        );
1192        assert_eq!(view[1].row_key, model.row_key(1));
1193        assert_eq!(view[1].text("row-header-text"), Some("B"));
1194        assert_eq!(view[1].child_at(2).unwrap().text("text"), Some("B:2"));
1195        assert_eq!(
1196            view[1].child_at(2).unwrap().table_cell_editor,
1197            Some(TableCellEditor::String)
1198        );
1199        assert!(view[1].child_at(1).is_none());
1200        assert_eq!(view[1].children.len(), 2);
1201    }
1202
1203    #[test]
1204    fn projected_cell_values_validate_scalar_ranges_and_preserve_strings() {
1205        use TableCellEditor::*;
1206        assert_eq!(
1207            String.parse("  device  "),
1208            Some(Value::String("  device  ".into()))
1209        );
1210        assert_eq!(Int.parse(" -42 "), Some(Value::Int(-42)));
1211        assert!(!Int.accepts("9223372036854775808"));
1212        assert_eq!(Float.parse("1.25e2"), Some(Value::Float(125.0)));
1213        for text in ["NaN", "inf", "1e500"] {
1214            assert!(!Float.accepts(text));
1215        }
1216        assert_eq!(Bool.parse("true"), Some(Value::Bool(true)));
1217        assert_eq!(Bool.parse("0"), Some(Value::Bool(false)));
1218        assert!(!Bool.accepts("2"));
1219        assert_eq!(
1220            Date.parse("2000-02-29"),
1221            crate::Date::new(2000, 2, 29).map(Value::Date)
1222        );
1223        assert!(!Date.accepts("1900-02-29"));
1224        assert!(!Date.accepts("2000-02-29-01"));
1225        assert_eq!(
1226            Time.parse("23:59:59"),
1227            crate::Time::new(23, 59, 59).map(Value::Time)
1228        );
1229        assert!(!Time.accepts("24:00:00"));
1230        assert!(!Time.accepts("12:34"));
1231    }
1232}