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