Skip to main content

xrack_runtime/
list.rs

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