Skip to main content

lumen_dioxus/data/data_table/
model.rs

1//! The `DataTable` model: cells, rows, columns, sorting, filtering, pagination, selection, and
2//! column visibility, as pure functions the components and applications share.
3
4// cspell:words hideable peekable
5
6use std::cmp::Ordering;
7
8use dioxus::prelude::*;
9
10use crate::data::table::{TableRecordSlot, resolve_table_record_slots};
11
12/// One cell value: the visible text and an optional sort value.
13///
14/// Mirrors lumen-react's `DataTableCell`: plain values display as text, and a cell can carry a
15/// separate `sort_value` (for example the display text `1,200` with the sort value `1200`).
16#[derive(Clone, Debug, Default, PartialEq, Eq)]
17pub struct DataTableCell {
18    /// Visible text.
19    pub text: String,
20    /// Value used for sorting instead of the text; also rendered as `data-sort-value`.
21    pub sort_value: Option<String>,
22}
23
24impl DataTableCell {
25    /// A cell that displays `text`.
26    pub fn new(text: impl Into<String>) -> Self {
27        Self {
28            text: text.into(),
29            sort_value: None,
30        }
31    }
32
33    /// Sets the value used for sorting.
34    #[must_use]
35    pub fn with_sort_value(mut self, value: impl Into<String>) -> Self {
36        self.sort_value = Some(value.into());
37        self
38    }
39
40    /// The text sorting compares: the sort value when present, otherwise the visible text.
41    pub fn sort_text(&self) -> &str {
42        self.sort_value.as_deref().unwrap_or(&self.text)
43    }
44}
45
46/// Formats a number like JavaScript's `String(number)` for the common range.
47pub(crate) fn js_number(value: f64) -> String {
48    if value.is_nan() {
49        "NaN".to_string()
50    } else if value.is_infinite() {
51        if value > 0.0 { "Infinity" } else { "-Infinity" }.to_string()
52    } else if value == 0.0 {
53        "0".to_string()
54    } else {
55        format!("{value}")
56    }
57}
58
59impl From<&str> for DataTableCell {
60    fn from(value: &str) -> Self {
61        Self::new(value)
62    }
63}
64
65impl From<String> for DataTableCell {
66    fn from(value: String) -> Self {
67        Self::new(value)
68    }
69}
70
71impl From<f64> for DataTableCell {
72    fn from(value: f64) -> Self {
73        Self::new(js_number(value))
74    }
75}
76
77impl From<i64> for DataTableCell {
78    fn from(value: i64) -> Self {
79        Self::new(value.to_string())
80    }
81}
82
83impl From<i32> for DataTableCell {
84    fn from(value: i32) -> Self {
85        Self::new(value.to_string())
86    }
87}
88
89impl From<u32> for DataTableCell {
90    fn from(value: u32) -> Self {
91        Self::new(value.to_string())
92    }
93}
94
95impl From<bool> for DataTableCell {
96    fn from(value: bool) -> Self {
97        Self::new(value.to_string())
98    }
99}
100
101/// One record: an optional id and its cells keyed by column key.
102#[derive(Clone, Debug, Default, PartialEq, Eq)]
103pub struct DataTableRow {
104    /// Stable id used for selection, expansion, and `data-value`. Defaults to the row index.
105    pub id: Option<String>,
106    /// Cells keyed by column key.
107    pub cells: Vec<(String, DataTableCell)>,
108}
109
110impl DataTableRow {
111    /// A row with an id.
112    pub fn new(id: impl Into<String>) -> Self {
113        Self {
114            id: Some(id.into()),
115            cells: Vec::new(),
116        }
117    }
118
119    /// Adds or replaces the cell for a column key.
120    #[must_use]
121    pub fn cell(mut self, key: impl Into<String>, cell: impl Into<DataTableCell>) -> Self {
122        let key = key.into();
123        let cell = cell.into();
124
125        if let Some(entry) = self.cells.iter_mut().find(|(existing, _)| *existing == key) {
126            entry.1 = cell;
127        } else {
128            self.cells.push((key, cell));
129        }
130
131        self
132    }
133
134    /// The cell for a column key.
135    pub fn get(&self, key: &str) -> Option<&DataTableCell> {
136        self.cells
137            .iter()
138            .find(|(existing, _)| existing == key)
139            .map(|(_, cell)| cell)
140    }
141
142    /// The visible text for a column key, or an empty string.
143    pub fn text(&self, key: &str) -> &str {
144        self.get(key).map_or("", |cell| cell.text.as_str())
145    }
146
147    /// The row id, or the index when the row has none.
148    pub fn value(&self, index: usize) -> String {
149        self.id.clone().unwrap_or_else(|| index.to_string())
150    }
151}
152
153/// How a column compares values when sorting.
154#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
155#[non_exhaustive]
156pub enum DataTableSortType {
157    /// Natural text order: case-insensitive, with digit runs compared as numbers.
158    #[default]
159    String,
160    /// Numeric order; commas are ignored, like `1,200`.
161    Number,
162}
163
164impl DataTableSortType {
165    /// The `data-ui-datatable-sort-type` value.
166    pub fn as_str(self) -> &'static str {
167        match self {
168            Self::String => "string",
169            Self::Number => "number",
170        }
171    }
172}
173
174/// One column of a [`DataTable`](crate::DataTable).
175#[derive(Clone, PartialEq)]
176pub struct DataTableColumn {
177    /// Unique key into each row's cells.
178    pub key: String,
179    /// Header text. Falls back to `label`, then the key.
180    pub header: Option<String>,
181    /// Alternative header text.
182    pub label: Option<String>,
183    /// Comparison used for sorting; `None` renders no sort type and compares text.
184    pub sort: Option<DataTableSortType>,
185    /// Lets users sort by this column.
186    pub sortable: bool,
187    /// Numeric presentation independent of sorting; `None` follows numeric sort type.
188    pub numeric: Option<bool>,
189    /// Gives the column extra room: an alias of `record: Some(TableRecordSlot::Wide)`, which
190    /// `record` overrides.
191    pub wide: bool,
192    /// The column's place in a stacked record card. Only the first `Title` column is the title.
193    /// Without one, the first column without a slot that isn't secondary becomes the title.
194    pub record: Option<TableRecordSlot>,
195    /// Hides the column while a `Records` or `Condensed` table is narrow; the title cell repeats
196    /// its value. A table without a title column keeps it visible.
197    pub secondary: bool,
198    /// Rich cell content; sorting still uses the cell value.
199    pub render: Option<Callback<(DataTableCell, DataTableRow), Element>>,
200}
201
202impl DataTableColumn {
203    /// A column with a key and header text.
204    pub fn new(key: impl Into<String>, header: impl Into<String>) -> Self {
205        Self {
206            key: key.into(),
207            header: Some(header.into()),
208            label: None,
209            sort: None,
210            sortable: false,
211            numeric: None,
212            wide: false,
213            record: None,
214            secondary: false,
215            render: None,
216        }
217    }
218
219    /// Chooses end-aligned tabular figures independently of sorting.
220    #[must_use]
221    pub fn numeric(mut self, numeric: bool) -> Self {
222        self.numeric = Some(numeric);
223        self
224    }
225
226    /// Resolved presentation, retaining the legacy numeric-sort default.
227    pub fn is_numeric(&self) -> bool {
228        self.numeric
229            .unwrap_or(self.sort == Some(DataTableSortType::Number))
230    }
231
232    /// Makes the column sortable with the given comparison.
233    #[must_use]
234    pub fn sortable(mut self, sort: DataTableSortType) -> Self {
235        self.sortable = true;
236        self.sort = Some(sort);
237        self
238    }
239
240    /// Makes the column sortable as text without rendering a sort type.
241    #[must_use]
242    pub fn sortable_text(mut self) -> Self {
243        self.sortable = true;
244        self
245    }
246
247    /// Gives the column extra room, like `record(TableRecordSlot::Wide)`.
248    #[must_use]
249    pub fn wide(mut self) -> Self {
250        self.wide = true;
251        self
252    }
253
254    /// Places the column's cells in a stacked record card: the title line, its trailing end, row
255    /// actions, a muted meta line, or a full-width line.
256    #[must_use]
257    pub fn record(mut self, slot: TableRecordSlot) -> Self {
258        self.record = Some(slot);
259        self
260    }
261
262    /// Hides the column while the table is narrow and repeats its value under the title.
263    #[must_use]
264    pub fn secondary(mut self) -> Self {
265        self.secondary = true;
266        self
267    }
268
269    /// The column's own record slot: `record`, else `Wide` for a wide column.
270    pub fn record_slot(&self) -> Option<TableRecordSlot> {
271        self.record
272            .or_else(|| self.wide.then_some(TableRecordSlot::Wide))
273    }
274
275    /// Renders rich cell content.
276    #[must_use]
277    pub fn with_render(mut self, render: Callback<(DataTableCell, DataTableRow), Element>) -> Self {
278        self.render = Some(render);
279        self
280    }
281
282    /// The header text: `header`, else `label`, else the key.
283    pub fn title(&self) -> &str {
284        self.header
285            .as_deref()
286            .or(self.label.as_deref())
287            .unwrap_or(&self.key)
288    }
289}
290
291/// Sort direction.
292#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
293pub enum DataTableSortDirection {
294    /// Smallest first.
295    #[default]
296    Ascending,
297    /// Largest first.
298    Descending,
299}
300
301impl DataTableSortDirection {
302    /// The `aria-sort` value.
303    pub fn as_str(self) -> &'static str {
304        match self {
305            Self::Ascending => "ascending",
306            Self::Descending => "descending",
307        }
308    }
309
310    /// The opposite direction.
311    #[must_use]
312    pub fn reversed(self) -> Self {
313        match self {
314            Self::Ascending => Self::Descending,
315            Self::Descending => Self::Ascending,
316        }
317    }
318}
319
320/// One sort criterion.
321#[derive(Clone, Debug, PartialEq, Eq)]
322pub struct DataTableSort {
323    /// Column key.
324    pub key: String,
325    /// Direction.
326    pub direction: DataTableSortDirection,
327}
328
329impl DataTableSort {
330    /// An ascending criterion.
331    pub fn ascending(key: impl Into<String>) -> Self {
332        Self {
333            key: key.into(),
334            direction: DataTableSortDirection::Ascending,
335        }
336    }
337
338    /// A descending criterion.
339    pub fn descending(key: impl Into<String>) -> Self {
340        Self {
341            key: key.into(),
342            direction: DataTableSortDirection::Descending,
343        }
344    }
345}
346
347/// Each column's record slot after the title rules of
348/// [`resolve_table_record_slots`](crate::resolve_table_record_slots). A `Title` column after the
349/// first resolves as if it had no `record`, so a `wide` one is `Wide`, like lumen-core.
350pub fn data_table_record_slots(columns: &[DataTableColumn]) -> Vec<Option<TableRecordSlot>> {
351    let first_title = columns
352        .iter()
353        .position(|column| column.record == Some(TableRecordSlot::Title));
354    let slots: Vec<(Option<TableRecordSlot>, bool)> = columns
355        .iter()
356        .enumerate()
357        .map(|(index, column)| {
358            let slot =
359                if column.record == Some(TableRecordSlot::Title) && Some(index) != first_title {
360                    column.wide.then_some(TableRecordSlot::Wide)
361                } else {
362                    column.record_slot()
363                };
364
365            (slot, column.secondary)
366        })
367        .collect();
368
369    resolve_table_record_slots(&slots)
370}
371
372/// Valid columns: non-empty, unique keys. Anything else yields no columns, like lumen-react.
373pub fn valid_data_table_columns(columns: &[DataTableColumn]) -> &[DataTableColumn] {
374    let mut keys: Vec<&str> = Vec::with_capacity(columns.len());
375
376    for column in columns {
377        if column.key.is_empty() || keys.contains(&column.key.as_str()) {
378            return &[];
379        }
380
381        keys.push(&column.key);
382    }
383
384    columns
385}
386
387/// Whether every row has a non-empty, unique id (rows without an id use their index).
388pub fn valid_data_table_rows(rows: &[DataTableRow]) -> bool {
389    let mut ids = std::collections::HashSet::with_capacity(rows.len());
390
391    rows.iter().enumerate().all(|(index, row)| {
392        let id = row.value(index);
393        !id.is_empty() && ids.insert(id)
394    })
395}
396
397/// Unique criteria in priority order; later duplicates of a key are dropped.
398pub fn valid_data_table_sorting(sorting: &[DataTableSort]) -> Vec<DataTableSort> {
399    let mut criteria: Vec<DataTableSort> = Vec::with_capacity(sorting.len());
400
401    for sort in sorting {
402        if !criteria.iter().any(|existing| existing.key == sort.key) {
403            criteria.push(sort.clone());
404        }
405    }
406
407    criteria
408}
409
410/// Header activation with multi-sort: a plain activation replaces the criteria with one column
411/// (reversing it when it is already primary). Additive activation appends an ascending criterion
412/// or reverses an existing one without changing its priority. Without multi-sort, use
413/// [`cycle_data_table_sorting`].
414pub fn next_data_table_sorting(
415    current: &[DataTableSort],
416    key: &str,
417    additive: bool,
418) -> Vec<DataTableSort> {
419    if !additive {
420        return match current.first() {
421            Some(primary) if primary.key == key => vec![DataTableSort {
422                key: key.to_string(),
423                direction: primary.direction.reversed(),
424            }],
425            _ => vec![DataTableSort::ascending(key)],
426        };
427    }
428
429    if current.iter().any(|sort| sort.key == key) {
430        current
431            .iter()
432            .map(|sort| {
433                if sort.key == key {
434                    DataTableSort {
435                        key: sort.key.clone(),
436                        direction: sort.direction.reversed(),
437                    }
438                } else {
439                    sort.clone()
440                }
441            })
442            .collect()
443    } else {
444        let mut next = current.to_vec();
445        next.push(DataTableSort::ascending(key));
446        next
447    }
448}
449
450/// Header activation without multi-sort, like Lumen's web runtime: the primary column cycles
451/// ascending, descending, then unsorted (the original order); any other column starts ascending
452/// and replaces the criteria.
453pub fn cycle_data_table_sorting(current: &[DataTableSort], key: &str) -> Vec<DataTableSort> {
454    match current.first() {
455        Some(primary) if primary.key == key => match primary.direction {
456            DataTableSortDirection::Ascending => vec![DataTableSort::descending(key)],
457            DataTableSortDirection::Descending => Vec::new(),
458        },
459        _ => vec![DataTableSort::ascending(key)],
460    }
461}
462
463/// Adds the id when missing, removes it when present.
464pub fn toggle_data_table_id(ids: &[String], id: &str) -> Vec<String> {
465    if ids.iter().any(|existing| existing == id) {
466        ids.iter()
467            .filter(|existing| *existing != id)
468            .cloned()
469            .collect()
470    } else {
471        let mut next = ids.to_vec();
472        next.push(id.to_string());
473        next
474    }
475}
476
477/// Selects every rendered row, or clears them when all are selected. Ids outside the rendered
478/// rows, such as rows on other server pages, are kept.
479pub fn toggle_data_table_ids(ids: &[String], rendered: &[String]) -> Vec<String> {
480    let all = !rendered.is_empty() && rendered.iter().all(|id| ids.contains(id));
481
482    if all {
483        ids.iter()
484            .filter(|id| !rendered.contains(id))
485            .cloned()
486            .collect()
487    } else {
488        let mut next = ids.to_vec();
489        next.extend(rendered.iter().filter(|id| !ids.contains(id)).cloned());
490        next
491    }
492}
493
494/// JavaScript `Number(text)` for decimal, hexadecimal, octal, and binary literals; `None` is NaN.
495pub(crate) fn js_to_number(text: &str) -> Option<f64> {
496    let trimmed = text.trim();
497
498    if trimmed.is_empty() {
499        return Some(0.0);
500    }
501
502    let radix = |prefix: &str, radix: u32| {
503        trimmed
504            .strip_prefix(prefix)
505            .or_else(|| trimmed.strip_prefix(&prefix.to_ascii_uppercase()))
506            .map(|digits| {
507                if digits.is_empty() {
508                    return None;
509                }
510
511                digits.chars().try_fold(0.0_f64, |total, digit| {
512                    digit
513                        .to_digit(radix)
514                        .map(|value| total * f64::from(radix) + f64::from(value))
515                })
516            })
517    };
518
519    if let Some(value) = radix("0x", 16)
520        .or_else(|| radix("0o", 8))
521        .or_else(|| radix("0b", 2))
522    {
523        return value;
524    }
525
526    match trimmed {
527        "Infinity" | "+Infinity" => return Some(f64::INFINITY),
528        "-Infinity" => return Some(f64::NEG_INFINITY),
529        _ => {}
530    }
531
532    // Rust also reads `inf` and `nan`, which JavaScript does not.
533    if trimmed
534        .bytes()
535        .any(|byte| byte.is_ascii_alphabetic() && byte != b'e' && byte != b'E')
536    {
537        return None;
538    }
539
540    trimmed.parse::<f64>().ok()
541}
542
543fn chunk_rank(character: char) -> u8 {
544    if character.is_ascii_digit() {
545        1
546    } else if character.is_alphanumeric() {
547        2
548    } else {
549        0
550    }
551}
552
553/// Natural, case-insensitive comparison that approximates `localeCompare` with
554/// `{ numeric: true, sensitivity: "base" }`: digit runs compare as numbers, letters compare by
555/// their lowercase form, and punctuation sorts before digits, which sort before letters.
556pub fn compare_data_table_text(left: &str, right: &str) -> Ordering {
557    let mut a = left.chars().peekable();
558    let mut b = right.chars().peekable();
559
560    loop {
561        match (a.peek().copied(), b.peek().copied()) {
562            (None, None) => return Ordering::Equal,
563            (None, Some(_)) => return Ordering::Less,
564            (Some(_), None) => return Ordering::Greater,
565            (Some(x), Some(y)) if x.is_ascii_digit() && y.is_ascii_digit() => {
566                let mut left_digits = String::new();
567                let mut right_digits = String::new();
568
569                while let Some(digit) = a.next_if(char::is_ascii_digit) {
570                    left_digits.push(digit);
571                }
572
573                while let Some(digit) = b.next_if(char::is_ascii_digit) {
574                    right_digits.push(digit);
575                }
576
577                let left_trimmed = left_digits.trim_start_matches('0');
578                let right_trimmed = right_digits.trim_start_matches('0');
579                let order = left_trimmed
580                    .len()
581                    .cmp(&right_trimmed.len())
582                    .then_with(|| left_trimmed.cmp(right_trimmed));
583
584                if order != Ordering::Equal {
585                    return order;
586                }
587            }
588            (Some(x), Some(y)) => {
589                let order = chunk_rank(x)
590                    .cmp(&chunk_rank(y))
591                    .then_with(|| x.to_lowercase().cmp(y.to_lowercase()));
592
593                if order != Ordering::Equal {
594                    return order;
595                }
596
597                a.next();
598                b.next();
599            }
600        }
601    }
602}
603
604/// Compares two cells with a column's sort type. `None` means the values are not comparable
605/// (a number column with non-numeric text); [`sort_data_table_rows`] orders those cells after
606/// every number.
607pub fn compare_data_table_cells(
608    left: Option<&DataTableCell>,
609    right: Option<&DataTableCell>,
610    sort: Option<DataTableSortType>,
611) -> Option<Ordering> {
612    let left = left.map_or("", DataTableCell::sort_text);
613    let right = right.map_or("", DataTableCell::sort_text);
614
615    if sort == Some(DataTableSortType::Number) {
616        let left = js_to_number(&left.replace(',', ""))?;
617        let right = js_to_number(&right.replace(',', ""))?;
618
619        return left.partial_cmp(&right);
620    }
621
622    Some(compare_data_table_text(left, right))
623}
624
625/// One row's value for one sort criterion, computed once per sort instead of per comparison.
626enum DataTableSortKey<'a> {
627    /// Natural text order.
628    Text(&'a str),
629    /// A number column value; `None` when the text is not a number.
630    Number(Option<f64>),
631}
632
633impl<'a> DataTableSortKey<'a> {
634    fn new(cell: Option<&'a DataTableCell>, sort: Option<DataTableSortType>) -> Self {
635        let text = cell.map_or("", DataTableCell::sort_text);
636
637        if sort != Some(DataTableSortType::Number) {
638            return Self::Text(text);
639        }
640
641        // `-0` ties with `0`, as it does in JavaScript's `a - b`.
642        Self::Number(
643            js_to_number(&text.replace(',', ""))
644                .filter(|number| !number.is_nan())
645                .map(|number| if number == 0.0 { 0.0 } else { number }),
646        )
647    }
648
649    /// A total order: numbers in `direction`, then every value that is not a number, which ties
650    /// with the others and follows the numbers in both directions.
651    fn compare(&self, other: &Self, direction: DataTableSortDirection) -> Ordering {
652        let directed = |order: Ordering| match direction {
653            DataTableSortDirection::Ascending => order,
654            DataTableSortDirection::Descending => order.reverse(),
655        };
656
657        match (self, other) {
658            (Self::Text(left), Self::Text(right)) => directed(compare_data_table_text(left, right)),
659            (Self::Number(Some(left)), Self::Number(Some(right))) => {
660                directed(left.total_cmp(right))
661            }
662            (Self::Number(Some(_)), Self::Number(None)) => Ordering::Less,
663            (Self::Number(None), Self::Number(Some(_))) => Ordering::Greater,
664            // Both not numbers, or keys of different columns, which the caller never compares.
665            _ => Ordering::Equal,
666        }
667    }
668}
669
670/// Row indexes in display order. Manual mode keeps the given order; client mode sorts stably by
671/// each sortable criterion in priority order.
672///
673/// In a number column, text that is not a number (such as `N/A` or `—`) sorts after the numbers
674/// in both directions, in its original order, so the comparison stays a total order.
675pub fn sort_data_table_rows(
676    rows: &[DataTableRow],
677    columns: &[DataTableColumn],
678    criteria: &[DataTableSort],
679    manual: bool,
680) -> Vec<usize> {
681    let mut order: Vec<usize> = (0..rows.len()).collect();
682
683    if manual {
684        return order;
685    }
686
687    let active: Vec<(&DataTableColumn, DataTableSortDirection)> = criteria
688        .iter()
689        .filter_map(|sort| {
690            columns
691                .iter()
692                .find(|column| column.sortable && column.key == sort.key)
693                .map(|column| (column, sort.direction))
694        })
695        .collect();
696
697    if active.is_empty() {
698        return order;
699    }
700
701    let keys: Vec<Vec<DataTableSortKey>> = rows
702        .iter()
703        .map(|row| {
704            active
705                .iter()
706                .map(|(column, _)| DataTableSortKey::new(row.get(&column.key), column.sort))
707                .collect()
708        })
709        .collect();
710
711    order.sort_by(|left, right| {
712        keys[*left]
713            .iter()
714            .zip(&keys[*right])
715            .zip(&active)
716            .map(|((left, right), (_, direction))| left.compare(right, *direction))
717            .find(|order| order.is_ne())
718            .unwrap_or_else(|| left.cmp(right))
719    });
720
721    order
722}
723
724/// Pagination of a [`DataTableViewState`].
725#[derive(Clone, Copy, Debug, PartialEq, Eq)]
726pub struct DataTablePagination {
727    /// Zero-based page.
728    pub page_index: usize,
729    /// Rows per page, at least 1.
730    pub page_size: usize,
731}
732
733impl Default for DataTablePagination {
734    fn default() -> Self {
735        Self {
736            page_index: 0,
737            page_size: 25,
738        }
739    }
740}
741
742/// Row spacing of a [`DataTableView`](crate::DataTableView).
743#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
744#[non_exhaustive]
745pub enum DataTableDensity {
746    /// Default spacing.
747    #[default]
748    Comfortable,
749    /// Tighter rows.
750    Compact,
751}
752
753impl DataTableDensity {
754    /// The `data-density` value.
755    pub fn as_str(self) -> &'static str {
756        match self {
757            Self::Comfortable => "comfortable",
758            Self::Compact => "compact",
759        }
760    }
761}
762
763/// An exact-match column filter of a [`DataTableViewState`].
764#[derive(Clone, Debug, PartialEq, Eq)]
765pub struct DataTableFilter {
766    /// Column key.
767    pub id: String,
768    /// Required value.
769    pub value: String,
770}
771
772/// Serializable view preferences: search, filters, visibility, pagination, sorting, density.
773/// Records and selection stay outside the state.
774#[derive(Clone, Debug, Default, PartialEq, Eq)]
775pub struct DataTableViewState {
776    /// Case-insensitive search across searchable columns.
777    pub search: String,
778    /// Exact-match column filters.
779    pub filters: Vec<DataTableFilter>,
780    /// Column visibility overrides; missing keys are visible.
781    pub visibility: Vec<(String, bool)>,
782    /// Current page and page size.
783    pub pagination: DataTablePagination,
784    /// Sort criteria in priority order.
785    pub sorting: Vec<DataTableSort>,
786    /// Row spacing.
787    pub density: DataTableDensity,
788}
789
790impl DataTableViewState {
791    /// The value of the filter for a column, or an empty string.
792    pub fn filter_value(&self, key: &str) -> &str {
793        self.filters
794            .iter()
795            .find(|filter| filter.id == key)
796            .map_or("", |filter| filter.value.as_str())
797    }
798
799    /// Sets or clears (with an empty value) the filter for a column.
800    #[must_use]
801    pub fn with_filter(&self, key: &str, value: &str) -> Self {
802        let mut next = self.clone();
803        next.filters.retain(|filter| filter.id != key);
804
805        if !value.is_empty() {
806            next.filters.push(DataTableFilter {
807                id: key.to_string(),
808                value: value.to_string(),
809            });
810        }
811
812        next
813    }
814
815    /// Sets a column's visibility.
816    #[must_use]
817    pub fn with_visibility(&self, key: &str, visible: bool) -> Self {
818        let mut next = self.clone();
819
820        if let Some(entry) = next
821            .visibility
822            .iter_mut()
823            .find(|(existing, _)| existing == key)
824        {
825            entry.1 = visible;
826        } else {
827            next.visibility.push((key.to_string(), visible));
828        }
829
830        next
831    }
832
833    /// The state after a change to the query (search, filters, sorting, or page size): the page
834    /// returns to the first one.
835    #[must_use]
836    pub fn first_page(mut self) -> Self {
837        self.pagination.page_index = 0;
838        self
839    }
840}
841
842/// One column of a [`DataTableView`](crate::DataTableView).
843#[derive(Clone, Debug, Default, PartialEq, Eq)]
844pub struct DataTableViewColumn {
845    /// Unique key into each row's cells.
846    pub key: String,
847    /// Visible name.
848    pub label: String,
849    /// Lets users hide the column. Defaults to true.
850    pub can_hide: bool,
851    /// Lets users sort by the column.
852    pub sortable: bool,
853    /// Includes the column in the search. Defaults to true.
854    pub searchable: bool,
855    /// Options of an exact-match filter select, as `(value, label)` pairs.
856    pub filter_options: Vec<(String, String)>,
857}
858
859impl DataTableViewColumn {
860    /// A hideable, searchable column.
861    pub fn new(key: impl Into<String>, label: impl Into<String>) -> Self {
862        Self {
863            key: key.into(),
864            label: label.into(),
865            can_hide: true,
866            sortable: false,
867            searchable: true,
868            filter_options: Vec::new(),
869        }
870    }
871
872    /// Makes the column sortable.
873    #[must_use]
874    pub fn sortable(mut self) -> Self {
875        self.sortable = true;
876        self
877    }
878
879    /// Keeps the column always visible.
880    #[must_use]
881    pub fn always_visible(mut self) -> Self {
882        self.can_hide = false;
883        self
884    }
885
886    /// Adds an exact-match filter with `(value, label)` options.
887    #[must_use]
888    pub fn with_filter_options(mut self, options: Vec<(String, String)>) -> Self {
889        self.filter_options = options;
890        self
891    }
892}
893
894/// The result of applying a [`DataTableViewState`] to rows.
895#[derive(Clone, Debug, PartialEq, Eq)]
896pub struct DataTableViewPage {
897    /// Indexes of the rows on the current page, in display order.
898    pub rows: Vec<usize>,
899    /// Rows that match the search and filters.
900    pub matching: usize,
901    /// Number of pages, at least 1.
902    pub pages: usize,
903    /// The current page, clamped to the available pages.
904    pub page_index: usize,
905}
906
907/// Whether a column is shown: always for columns that cannot hide, otherwise unless the state
908/// hides it.
909pub fn data_table_column_visible(
910    columns: &[DataTableViewColumn],
911    state: &DataTableViewState,
912    key: &str,
913) -> bool {
914    columns.iter().any(|column| {
915        column.key == key
916            && (!column.can_hide
917                || !state
918                    .visibility
919                    .iter()
920                    .any(|(hidden, visible)| hidden == key && !visible))
921    })
922}
923
924/// Filters, sorts, and paginates rows on the client, like the `TanStack` model behind
925/// lumen-react's `DataTableView`. With `server` true the rows are already one page: nothing is
926/// filtered, sorted, or sliced and `row_count` gives the matching total.
927pub fn data_table_view_page(
928    rows: &[DataTableRow],
929    columns: &[DataTableViewColumn],
930    state: &DataTableViewState,
931    server: Option<usize>,
932) -> DataTableViewPage {
933    let size = state.pagination.page_size.max(1);
934
935    if let Some(total) = server {
936        let pages = total.div_ceil(size).max(1);
937
938        return DataTableViewPage {
939            rows: (0..rows.len()).collect(),
940            matching: total,
941            pages,
942            page_index: state.pagination.page_index.min(pages - 1),
943        };
944    }
945
946    let search = state.search.to_lowercase();
947    let mut matching: Vec<usize> = (0..rows.len())
948        .filter(|index| {
949            let row = &rows[*index];
950            let searched = search.is_empty()
951                || columns
952                    .iter()
953                    .filter(|column| column.searchable)
954                    .any(|column| row.text(&column.key).to_lowercase().contains(&search));
955            let filtered = state.filters.iter().all(|filter| {
956                !columns.iter().any(|column| column.key == filter.id)
957                    || row.text(&filter.id) == filter.value
958            });
959
960            searched && filtered
961        })
962        .collect();
963
964    let sortable: Vec<&DataTableSort> = state
965        .sorting
966        .iter()
967        .filter(|sort| {
968            columns
969                .iter()
970                .any(|column| column.key == sort.key && column.sortable)
971        })
972        .collect();
973
974    if !sortable.is_empty() {
975        matching.sort_by(|left, right| {
976            for sort in &sortable {
977                let order = compare_data_table_text(
978                    rows[*left].text(&sort.key),
979                    rows[*right].text(&sort.key),
980                );
981                let order = match sort.direction {
982                    DataTableSortDirection::Ascending => order,
983                    DataTableSortDirection::Descending => order.reverse(),
984                };
985
986                if order != Ordering::Equal {
987                    return order;
988                }
989            }
990
991            left.cmp(right)
992        });
993    }
994
995    let total = matching.len();
996    let pages = total.div_ceil(size).max(1);
997    let page_index = state.pagination.page_index.min(pages - 1);
998    let rows = matching
999        .into_iter()
1000        .skip(page_index * size)
1001        .take(size)
1002        .collect();
1003
1004    DataTableViewPage {
1005        rows,
1006        matching: total,
1007        pages,
1008        page_index,
1009    }
1010}
1011
1012/// The criteria after a header activation in a [`DataTableView`](crate::DataTableView): a
1013/// new criterion starts ascending, an existing one reverses, and `multiple` keeps the others.
1014pub fn toggle_data_table_view_sort(
1015    sorting: &[DataTableSort],
1016    key: &str,
1017    multiple: bool,
1018) -> Vec<DataTableSort> {
1019    let active = sorting.iter().find(|sort| sort.key == key);
1020    let direction = active.map_or(DataTableSortDirection::Ascending, |sort| {
1021        sort.direction.reversed()
1022    });
1023    let mut next: Vec<DataTableSort> = if multiple {
1024        sorting
1025            .iter()
1026            .filter(|sort| sort.key != key)
1027            .cloned()
1028            .collect()
1029    } else {
1030        Vec::new()
1031    };
1032
1033    next.push(DataTableSort {
1034        key: key.to_string(),
1035        direction,
1036    });
1037    next
1038}
1039
1040#[cfg(test)]
1041mod tests {
1042    use std::cmp::Ordering;
1043
1044    use super::*;
1045
1046    fn rows() -> Vec<DataTableRow> {
1047        vec![
1048            DataTableRow::new("ada")
1049                .cell("name", "Ada")
1050                .cell("seats", 12),
1051            DataTableRow::new("grace")
1052                .cell("name", "grace")
1053                .cell("seats", DataTableCell::new("1,200").with_sort_value("1200")),
1054            DataTableRow::new("linus")
1055                .cell("name", "Linus")
1056                .cell("seats", 3),
1057        ]
1058    }
1059
1060    fn columns() -> Vec<DataTableColumn> {
1061        vec![
1062            DataTableColumn::new("name", "Name").sortable_text(),
1063            DataTableColumn::new("seats", "Seats").sortable(DataTableSortType::Number),
1064        ]
1065    }
1066
1067    #[test]
1068    fn header_activation_replaces_or_extends_criteria() {
1069        let one = next_data_table_sorting(&[], "name", false);
1070        assert_eq!(one, [DataTableSort::ascending("name")]);
1071        assert_eq!(
1072            next_data_table_sorting(&one, "name", false),
1073            [DataTableSort::descending("name")]
1074        );
1075        assert_eq!(
1076            next_data_table_sorting(&one, "seats", false),
1077            [DataTableSort::ascending("seats")]
1078        );
1079
1080        let two = next_data_table_sorting(&one, "seats", true);
1081        assert_eq!(
1082            two,
1083            [
1084                DataTableSort::ascending("name"),
1085                DataTableSort::ascending("seats")
1086            ]
1087        );
1088        assert_eq!(
1089            next_data_table_sorting(&two, "name", true),
1090            [
1091                DataTableSort::descending("name"),
1092                DataTableSort::ascending("seats")
1093            ]
1094        );
1095    }
1096
1097    #[test]
1098    fn single_sort_headers_cycle_ascending_descending_and_unsorted() {
1099        let ascending = cycle_data_table_sorting(&[], "name");
1100        assert_eq!(ascending, [DataTableSort::ascending("name")]);
1101
1102        let descending = cycle_data_table_sorting(&ascending, "name");
1103        assert_eq!(descending, [DataTableSort::descending("name")]);
1104
1105        // The third activation restores the original order.
1106        assert_eq!(
1107            cycle_data_table_sorting(&descending, "name"),
1108            [] as [DataTableSort; 0]
1109        );
1110        assert_eq!(
1111            cycle_data_table_sorting(&descending, "seats"),
1112            [DataTableSort::ascending("seats")]
1113        );
1114
1115        // Only the primary criterion cycles; a secondary one from controlled sorting starts over.
1116        let both = [
1117            DataTableSort::descending("name"),
1118            DataTableSort::descending("seats"),
1119        ];
1120        assert_eq!(
1121            cycle_data_table_sorting(&both, "seats"),
1122            [DataTableSort::ascending("seats")]
1123        );
1124        assert_eq!(
1125            cycle_data_table_sorting(&both, "name"),
1126            [] as [DataTableSort; 0]
1127        );
1128    }
1129
1130    #[test]
1131    fn record_slots_alias_wide_and_default_the_title() {
1132        let columns = vec![
1133            DataTableColumn::new("name", "Name").wide(),
1134            DataTableColumn::new("email", "Email").secondary(),
1135            DataTableColumn::new("status", "Status").record(TableRecordSlot::Trailing),
1136            DataTableColumn::new("notes", "Notes")
1137                .wide()
1138                .record(TableRecordSlot::Meta),
1139        ];
1140
1141        assert_eq!(columns[0].record_slot(), Some(TableRecordSlot::Wide));
1142        assert_eq!(columns[3].record_slot(), Some(TableRecordSlot::Meta));
1143        assert!(columns[1].secondary);
1144        // The only column without a slot is secondary, so no column becomes the default title.
1145        assert_eq!(
1146            data_table_record_slots(&columns),
1147            [
1148                Some(TableRecordSlot::Wide),
1149                None,
1150                Some(TableRecordSlot::Trailing),
1151                Some(TableRecordSlot::Meta),
1152            ]
1153        );
1154
1155        let titled = vec![
1156            DataTableColumn::new("name", "Name"),
1157            DataTableColumn::new("team", "Team").record(TableRecordSlot::Title),
1158        ];
1159        assert_eq!(
1160            data_table_record_slots(&titled),
1161            [None, Some(TableRecordSlot::Title)]
1162        );
1163
1164        // A second title resolves as if it had no `record`: its `wide` alias, or nothing.
1165        let duplicated = vec![
1166            DataTableColumn::new("name", "Name").record(TableRecordSlot::Title),
1167            DataTableColumn::new("team", "Team")
1168                .wide()
1169                .record(TableRecordSlot::Title),
1170            DataTableColumn::new("role", "Role").record(TableRecordSlot::Title),
1171        ];
1172        assert_eq!(
1173            data_table_record_slots(&duplicated),
1174            [
1175                Some(TableRecordSlot::Title),
1176                Some(TableRecordSlot::Wide),
1177                None
1178            ]
1179        );
1180    }
1181
1182    #[test]
1183    fn rows_sort_by_type_and_priority_and_stay_stable() {
1184        let rows = rows();
1185        let columns = columns();
1186
1187        assert_eq!(
1188            sort_data_table_rows(
1189                &rows,
1190                &columns,
1191                &[DataTableSort::descending("seats")],
1192                false
1193            ),
1194            [1, 0, 2]
1195        );
1196        assert_eq!(
1197            sort_data_table_rows(&rows, &columns, &[DataTableSort::ascending("name")], false),
1198            [0, 1, 2]
1199        );
1200        assert_eq!(
1201            sort_data_table_rows(&rows, &columns, &[DataTableSort::descending("seats")], true),
1202            [0, 1, 2]
1203        );
1204        // Unknown or unsortable keys keep the original order.
1205        assert_eq!(
1206            sort_data_table_rows(&rows, &columns, &[DataTableSort::ascending("role")], false),
1207            [0, 1, 2]
1208        );
1209    }
1210
1211    #[test]
1212    fn natural_text_order_compares_numbers_and_ignores_case() {
1213        assert_eq!(compare_data_table_text("item 2", "item 10"), Ordering::Less);
1214        assert_eq!(compare_data_table_text("Apple", "apple"), Ordering::Equal);
1215        assert_eq!(compare_data_table_text("b", "A"), Ordering::Greater);
1216        assert_eq!(compare_data_table_text("007", "7"), Ordering::Equal);
1217        assert_eq!(compare_data_table_text("-x", "1"), Ordering::Less);
1218        assert_eq!(compare_data_table_text("1", "a"), Ordering::Less);
1219        let long = "9".repeat(100_000);
1220        assert_eq!(compare_data_table_text(&long, &long), Ordering::Equal);
1221    }
1222
1223    #[test]
1224    fn numbers_parse_like_javascript() {
1225        assert_eq!(js_to_number(" 12 "), Some(12.0));
1226        assert_eq!(js_to_number(""), Some(0.0));
1227        assert_eq!(js_to_number("0x10"), Some(16.0));
1228        assert_eq!(js_to_number("1e3"), Some(1000.0));
1229        assert_eq!(js_to_number("Infinity"), Some(f64::INFINITY));
1230        assert_eq!(js_to_number("inf"), None);
1231        assert_eq!(js_to_number("12px"), None);
1232        assert_eq!(
1233            compare_data_table_cells(
1234                Some(&"abc".into()),
1235                Some(&"1".into()),
1236                Some(DataTableSortType::Number)
1237            ),
1238            None
1239        );
1240    }
1241
1242    #[test]
1243    fn ids_toggle_and_select_all_keeps_other_pages() {
1244        let ids = vec!["a".to_string()];
1245        assert_eq!(toggle_data_table_id(&ids, "b"), ["a", "b"]);
1246        assert_eq!(toggle_data_table_id(&ids, "a"), Vec::<String>::new());
1247
1248        let rendered = vec!["b".to_string(), "c".to_string()];
1249        assert_eq!(toggle_data_table_ids(&ids, &rendered), ["a", "b", "c"]);
1250        let all = vec!["a".to_string(), "b".to_string(), "c".to_string()];
1251        assert_eq!(toggle_data_table_ids(&all, &rendered), ["a"]);
1252    }
1253
1254    #[test]
1255    fn invalid_columns_and_rows_are_rejected() {
1256        let duplicate = vec![
1257            DataTableColumn::new("a", "A"),
1258            DataTableColumn::new("a", "B"),
1259        ];
1260        assert!(valid_data_table_columns(&duplicate).is_empty());
1261        assert_eq!(valid_data_table_columns(&columns()).len(), 2);
1262        assert!(!valid_data_table_rows(&[
1263            DataTableRow::new("x"),
1264            DataTableRow::new("x")
1265        ]));
1266        assert!(!valid_data_table_rows(&[DataTableRow::new("")]));
1267        assert!(valid_data_table_rows(&rows()));
1268    }
1269
1270    #[test]
1271    fn views_search_filter_sort_and_paginate() {
1272        let rows: Vec<DataTableRow> = (0..30)
1273            .map(|index| {
1274                DataTableRow::new(format!("r{index}"))
1275                    .cell("name", format!("Item {index}"))
1276                    .cell("status", if index % 3 == 0 { "Open" } else { "Closed" })
1277            })
1278            .collect();
1279        let columns = vec![
1280            DataTableViewColumn::new("name", "Name").sortable(),
1281            DataTableViewColumn::new("status", "Status"),
1282        ];
1283        let mut state = DataTableViewState {
1284            pagination: DataTablePagination {
1285                page_index: 0,
1286                page_size: 4,
1287            },
1288            ..DataTableViewState::default()
1289        };
1290
1291        let page = data_table_view_page(&rows, &columns, &state, None);
1292        assert_eq!((page.matching, page.pages, page.rows.len()), (30, 8, 4));
1293
1294        state = state.with_filter("status", "Open");
1295        let page = data_table_view_page(&rows, &columns, &state, None);
1296        assert_eq!((page.matching, page.pages), (10, 3));
1297
1298        state.search = "item 2".into();
1299        let page = data_table_view_page(&rows, &columns, &state, None);
1300        assert_eq!(page.rows, [21, 24, 27]);
1301
1302        state.sorting = toggle_data_table_view_sort(&state.sorting, "name", false);
1303        state.sorting = toggle_data_table_view_sort(&state.sorting, "name", false);
1304        let page = data_table_view_page(&rows, &columns, &state, None);
1305        assert_eq!(page.rows, [27, 24, 21]);
1306
1307        // Pages past the end clamp to the last page.
1308        state.pagination.page_index = 99;
1309        assert_eq!(
1310            data_table_view_page(&rows, &columns, &state, None).page_index,
1311            0
1312        );
1313        assert_eq!(
1314            data_table_view_page(&rows, &columns, &state, Some(0)).pages,
1315            1
1316        );
1317    }
1318
1319    #[test]
1320    fn visibility_respects_columns_that_cannot_hide() {
1321        let columns = vec![
1322            DataTableViewColumn::new("name", "Name").always_visible(),
1323            DataTableViewColumn::new("status", "Status"),
1324        ];
1325        let state = DataTableViewState::default()
1326            .with_visibility("name", false)
1327            .with_visibility("status", false);
1328
1329        assert!(data_table_column_visible(&columns, &state, "name"));
1330        assert!(!data_table_column_visible(&columns, &state, "status"));
1331        assert!(!data_table_column_visible(&columns, &state, "missing"));
1332    }
1333}