lumen-dioxus 6.0.0

Lumen UI components for Dioxus: web, desktop, mobile, and Dioxus Native (Blitz).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
//! The `DataTable` model: cells, rows, columns, sorting, filtering, pagination, selection, and
//! column visibility, as pure functions the components and applications share.

// cspell:words hideable peekable

use std::cmp::Ordering;

use dioxus::prelude::*;

use crate::data::table::{TableRecordSlot, resolve_table_record_slots};

/// One cell value: the visible text and an optional sort value.
///
/// Mirrors lumen-react's `DataTableCell`: plain values display as text, and a cell can carry a
/// separate `sort_value` (for example the display text `1,200` with the sort value `1200`).
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct DataTableCell {
    /// Visible text.
    pub text: String,
    /// Value used for sorting instead of the text; also rendered as `data-sort-value`.
    pub sort_value: Option<String>,
}

impl DataTableCell {
    /// A cell that displays `text`.
    pub fn new(text: impl Into<String>) -> Self {
        Self {
            text: text.into(),
            sort_value: None,
        }
    }

    /// Sets the value used for sorting.
    #[must_use]
    pub fn with_sort_value(mut self, value: impl Into<String>) -> Self {
        self.sort_value = Some(value.into());
        self
    }

    /// The text sorting compares: the sort value when present, otherwise the visible text.
    pub fn sort_text(&self) -> &str {
        self.sort_value.as_deref().unwrap_or(&self.text)
    }
}

/// Formats a number like JavaScript's `String(number)` for the common range.
pub(crate) fn js_number(value: f64) -> String {
    if value.is_nan() {
        "NaN".to_string()
    } else if value.is_infinite() {
        if value > 0.0 { "Infinity" } else { "-Infinity" }.to_string()
    } else if value == 0.0 {
        "0".to_string()
    } else {
        format!("{value}")
    }
}

impl From<&str> for DataTableCell {
    fn from(value: &str) -> Self {
        Self::new(value)
    }
}

impl From<String> for DataTableCell {
    fn from(value: String) -> Self {
        Self::new(value)
    }
}

impl From<f64> for DataTableCell {
    fn from(value: f64) -> Self {
        Self::new(js_number(value))
    }
}

impl From<i64> for DataTableCell {
    fn from(value: i64) -> Self {
        Self::new(value.to_string())
    }
}

impl From<i32> for DataTableCell {
    fn from(value: i32) -> Self {
        Self::new(value.to_string())
    }
}

impl From<u32> for DataTableCell {
    fn from(value: u32) -> Self {
        Self::new(value.to_string())
    }
}

impl From<bool> for DataTableCell {
    fn from(value: bool) -> Self {
        Self::new(value.to_string())
    }
}

/// One record: an optional id and its cells keyed by column key.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct DataTableRow {
    /// Stable id used for selection, expansion, and `data-value`. Defaults to the row index.
    pub id: Option<String>,
    /// Cells keyed by column key.
    pub cells: Vec<(String, DataTableCell)>,
}

impl DataTableRow {
    /// A row with an id.
    pub fn new(id: impl Into<String>) -> Self {
        Self {
            id: Some(id.into()),
            cells: Vec::new(),
        }
    }

    /// Adds or replaces the cell for a column key.
    #[must_use]
    pub fn cell(mut self, key: impl Into<String>, cell: impl Into<DataTableCell>) -> Self {
        let key = key.into();
        let cell = cell.into();

        if let Some(entry) = self.cells.iter_mut().find(|(existing, _)| *existing == key) {
            entry.1 = cell;
        } else {
            self.cells.push((key, cell));
        }

        self
    }

    /// The cell for a column key.
    pub fn get(&self, key: &str) -> Option<&DataTableCell> {
        self.cells
            .iter()
            .find(|(existing, _)| existing == key)
            .map(|(_, cell)| cell)
    }

    /// The visible text for a column key, or an empty string.
    pub fn text(&self, key: &str) -> &str {
        self.get(key).map_or("", |cell| cell.text.as_str())
    }

    /// The row id, or the index when the row has none.
    pub fn value(&self, index: usize) -> String {
        self.id.clone().unwrap_or_else(|| index.to_string())
    }
}

/// How a column compares values when sorting.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum DataTableSortType {
    /// Natural text order: case-insensitive, with digit runs compared as numbers.
    #[default]
    String,
    /// Numeric order; commas are ignored, like `1,200`.
    Number,
}

impl DataTableSortType {
    /// The `data-ui-datatable-sort-type` value.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::String => "string",
            Self::Number => "number",
        }
    }
}

/// One column of a [`DataTable`](crate::DataTable).
#[derive(Clone, PartialEq)]
pub struct DataTableColumn {
    /// Unique key into each row's cells.
    pub key: String,
    /// Header text. Falls back to `label`, then the key.
    pub header: Option<String>,
    /// Alternative header text.
    pub label: Option<String>,
    /// Comparison used for sorting; `None` renders no sort type and compares text.
    pub sort: Option<DataTableSortType>,
    /// Lets users sort by this column.
    pub sortable: bool,
    /// Numeric presentation independent of sorting; `None` follows numeric sort type.
    pub numeric: Option<bool>,
    /// Gives the column extra room: an alias of `record: Some(TableRecordSlot::Wide)`, which
    /// `record` overrides.
    pub wide: bool,
    /// The column's place in a stacked record card. Only the first `Title` column is the title.
    /// Without one, the first column without a slot that isn't secondary becomes the title.
    pub record: Option<TableRecordSlot>,
    /// Hides the column while a `Records` or `Condensed` table is narrow; the title cell repeats
    /// its value. A table without a title column keeps it visible.
    pub secondary: bool,
    /// Rich cell content; sorting still uses the cell value.
    pub render: Option<Callback<(DataTableCell, DataTableRow), Element>>,
}

impl DataTableColumn {
    /// A column with a key and header text.
    pub fn new(key: impl Into<String>, header: impl Into<String>) -> Self {
        Self {
            key: key.into(),
            header: Some(header.into()),
            label: None,
            sort: None,
            sortable: false,
            numeric: None,
            wide: false,
            record: None,
            secondary: false,
            render: None,
        }
    }

    /// Chooses end-aligned tabular figures independently of sorting.
    #[must_use]
    pub fn numeric(mut self, numeric: bool) -> Self {
        self.numeric = Some(numeric);
        self
    }

    /// Resolved presentation, retaining the legacy numeric-sort default.
    pub fn is_numeric(&self) -> bool {
        self.numeric
            .unwrap_or(self.sort == Some(DataTableSortType::Number))
    }

    /// Makes the column sortable with the given comparison.
    #[must_use]
    pub fn sortable(mut self, sort: DataTableSortType) -> Self {
        self.sortable = true;
        self.sort = Some(sort);
        self
    }

    /// Makes the column sortable as text without rendering a sort type.
    #[must_use]
    pub fn sortable_text(mut self) -> Self {
        self.sortable = true;
        self
    }

    /// Gives the column extra room, like `record(TableRecordSlot::Wide)`.
    #[must_use]
    pub fn wide(mut self) -> Self {
        self.wide = true;
        self
    }

    /// Places the column's cells in a stacked record card: the title line, its trailing end, row
    /// actions, a muted meta line, or a full-width line.
    #[must_use]
    pub fn record(mut self, slot: TableRecordSlot) -> Self {
        self.record = Some(slot);
        self
    }

    /// Hides the column while the table is narrow and repeats its value under the title.
    #[must_use]
    pub fn secondary(mut self) -> Self {
        self.secondary = true;
        self
    }

    /// The column's own record slot: `record`, else `Wide` for a wide column.
    pub fn record_slot(&self) -> Option<TableRecordSlot> {
        self.record
            .or_else(|| self.wide.then_some(TableRecordSlot::Wide))
    }

    /// Renders rich cell content.
    #[must_use]
    pub fn with_render(mut self, render: Callback<(DataTableCell, DataTableRow), Element>) -> Self {
        self.render = Some(render);
        self
    }

    /// The header text: `header`, else `label`, else the key.
    pub fn title(&self) -> &str {
        self.header
            .as_deref()
            .or(self.label.as_deref())
            .unwrap_or(&self.key)
    }
}

/// Sort direction.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum DataTableSortDirection {
    /// Smallest first.
    #[default]
    Ascending,
    /// Largest first.
    Descending,
}

impl DataTableSortDirection {
    /// The `aria-sort` value.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Ascending => "ascending",
            Self::Descending => "descending",
        }
    }

    /// The opposite direction.
    #[must_use]
    pub fn reversed(self) -> Self {
        match self {
            Self::Ascending => Self::Descending,
            Self::Descending => Self::Ascending,
        }
    }
}

/// One sort criterion.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DataTableSort {
    /// Column key.
    pub key: String,
    /// Direction.
    pub direction: DataTableSortDirection,
}

impl DataTableSort {
    /// An ascending criterion.
    pub fn ascending(key: impl Into<String>) -> Self {
        Self {
            key: key.into(),
            direction: DataTableSortDirection::Ascending,
        }
    }

    /// A descending criterion.
    pub fn descending(key: impl Into<String>) -> Self {
        Self {
            key: key.into(),
            direction: DataTableSortDirection::Descending,
        }
    }
}

/// Each column's record slot after the title rules of
/// [`resolve_table_record_slots`](crate::resolve_table_record_slots). A `Title` column after the
/// first resolves as if it had no `record`, so a `wide` one is `Wide`, like lumen-core.
pub fn data_table_record_slots(columns: &[DataTableColumn]) -> Vec<Option<TableRecordSlot>> {
    let first_title = columns
        .iter()
        .position(|column| column.record == Some(TableRecordSlot::Title));
    let slots: Vec<(Option<TableRecordSlot>, bool)> = columns
        .iter()
        .enumerate()
        .map(|(index, column)| {
            let slot =
                if column.record == Some(TableRecordSlot::Title) && Some(index) != first_title {
                    column.wide.then_some(TableRecordSlot::Wide)
                } else {
                    column.record_slot()
                };

            (slot, column.secondary)
        })
        .collect();

    resolve_table_record_slots(&slots)
}

/// Valid columns: non-empty, unique keys. Anything else yields no columns, like lumen-react.
pub fn valid_data_table_columns(columns: &[DataTableColumn]) -> &[DataTableColumn] {
    let mut keys: Vec<&str> = Vec::with_capacity(columns.len());

    for column in columns {
        if column.key.is_empty() || keys.contains(&column.key.as_str()) {
            return &[];
        }

        keys.push(&column.key);
    }

    columns
}

/// Whether every row has a non-empty, unique id (rows without an id use their index).
pub fn valid_data_table_rows(rows: &[DataTableRow]) -> bool {
    let mut ids = std::collections::HashSet::with_capacity(rows.len());

    rows.iter().enumerate().all(|(index, row)| {
        let id = row.value(index);
        !id.is_empty() && ids.insert(id)
    })
}

/// Unique criteria in priority order; later duplicates of a key are dropped.
pub fn valid_data_table_sorting(sorting: &[DataTableSort]) -> Vec<DataTableSort> {
    let mut criteria: Vec<DataTableSort> = Vec::with_capacity(sorting.len());

    for sort in sorting {
        if !criteria.iter().any(|existing| existing.key == sort.key) {
            criteria.push(sort.clone());
        }
    }

    criteria
}

/// Header activation with multi-sort: a plain activation replaces the criteria with one column
/// (reversing it when it is already primary). Additive activation appends an ascending criterion
/// or reverses an existing one without changing its priority. Without multi-sort, use
/// [`cycle_data_table_sorting`].
pub fn next_data_table_sorting(
    current: &[DataTableSort],
    key: &str,
    additive: bool,
) -> Vec<DataTableSort> {
    if !additive {
        return match current.first() {
            Some(primary) if primary.key == key => vec![DataTableSort {
                key: key.to_string(),
                direction: primary.direction.reversed(),
            }],
            _ => vec![DataTableSort::ascending(key)],
        };
    }

    if current.iter().any(|sort| sort.key == key) {
        current
            .iter()
            .map(|sort| {
                if sort.key == key {
                    DataTableSort {
                        key: sort.key.clone(),
                        direction: sort.direction.reversed(),
                    }
                } else {
                    sort.clone()
                }
            })
            .collect()
    } else {
        let mut next = current.to_vec();
        next.push(DataTableSort::ascending(key));
        next
    }
}

/// Header activation without multi-sort, like Lumen's web runtime: the primary column cycles
/// ascending, descending, then unsorted (the original order); any other column starts ascending
/// and replaces the criteria.
pub fn cycle_data_table_sorting(current: &[DataTableSort], key: &str) -> Vec<DataTableSort> {
    match current.first() {
        Some(primary) if primary.key == key => match primary.direction {
            DataTableSortDirection::Ascending => vec![DataTableSort::descending(key)],
            DataTableSortDirection::Descending => Vec::new(),
        },
        _ => vec![DataTableSort::ascending(key)],
    }
}

/// Adds the id when missing, removes it when present.
pub fn toggle_data_table_id(ids: &[String], id: &str) -> Vec<String> {
    if ids.iter().any(|existing| existing == id) {
        ids.iter()
            .filter(|existing| *existing != id)
            .cloned()
            .collect()
    } else {
        let mut next = ids.to_vec();
        next.push(id.to_string());
        next
    }
}

/// Selects every rendered row, or clears them when all are selected. Ids outside the rendered
/// rows, such as rows on other server pages, are kept.
pub fn toggle_data_table_ids(ids: &[String], rendered: &[String]) -> Vec<String> {
    let all = !rendered.is_empty() && rendered.iter().all(|id| ids.contains(id));

    if all {
        ids.iter()
            .filter(|id| !rendered.contains(id))
            .cloned()
            .collect()
    } else {
        let mut next = ids.to_vec();
        next.extend(rendered.iter().filter(|id| !ids.contains(id)).cloned());
        next
    }
}

/// JavaScript `Number(text)` for decimal, hexadecimal, octal, and binary literals; `None` is NaN.
pub(crate) fn js_to_number(text: &str) -> Option<f64> {
    let trimmed = text.trim();

    if trimmed.is_empty() {
        return Some(0.0);
    }

    let radix = |prefix: &str, radix: u32| {
        trimmed
            .strip_prefix(prefix)
            .or_else(|| trimmed.strip_prefix(&prefix.to_ascii_uppercase()))
            .map(|digits| {
                if digits.is_empty() {
                    return None;
                }

                digits.chars().try_fold(0.0_f64, |total, digit| {
                    digit
                        .to_digit(radix)
                        .map(|value| total * f64::from(radix) + f64::from(value))
                })
            })
    };

    if let Some(value) = radix("0x", 16)
        .or_else(|| radix("0o", 8))
        .or_else(|| radix("0b", 2))
    {
        return value;
    }

    match trimmed {
        "Infinity" | "+Infinity" => return Some(f64::INFINITY),
        "-Infinity" => return Some(f64::NEG_INFINITY),
        _ => {}
    }

    // Rust also reads `inf` and `nan`, which JavaScript does not.
    if trimmed
        .bytes()
        .any(|byte| byte.is_ascii_alphabetic() && byte != b'e' && byte != b'E')
    {
        return None;
    }

    trimmed.parse::<f64>().ok()
}

fn chunk_rank(character: char) -> u8 {
    if character.is_ascii_digit() {
        1
    } else if character.is_alphanumeric() {
        2
    } else {
        0
    }
}

/// Natural, case-insensitive comparison that approximates `localeCompare` with
/// `{ numeric: true, sensitivity: "base" }`: digit runs compare as numbers, letters compare by
/// their lowercase form, and punctuation sorts before digits, which sort before letters.
pub fn compare_data_table_text(left: &str, right: &str) -> Ordering {
    let mut a = left.chars().peekable();
    let mut b = right.chars().peekable();

    loop {
        match (a.peek().copied(), b.peek().copied()) {
            (None, None) => return Ordering::Equal,
            (None, Some(_)) => return Ordering::Less,
            (Some(_), None) => return Ordering::Greater,
            (Some(x), Some(y)) if x.is_ascii_digit() && y.is_ascii_digit() => {
                let mut left_digits = String::new();
                let mut right_digits = String::new();

                while let Some(digit) = a.next_if(char::is_ascii_digit) {
                    left_digits.push(digit);
                }

                while let Some(digit) = b.next_if(char::is_ascii_digit) {
                    right_digits.push(digit);
                }

                let left_trimmed = left_digits.trim_start_matches('0');
                let right_trimmed = right_digits.trim_start_matches('0');
                let order = left_trimmed
                    .len()
                    .cmp(&right_trimmed.len())
                    .then_with(|| left_trimmed.cmp(right_trimmed));

                if order != Ordering::Equal {
                    return order;
                }
            }
            (Some(x), Some(y)) => {
                let order = chunk_rank(x)
                    .cmp(&chunk_rank(y))
                    .then_with(|| x.to_lowercase().cmp(y.to_lowercase()));

                if order != Ordering::Equal {
                    return order;
                }

                a.next();
                b.next();
            }
        }
    }
}

/// Compares two cells with a column's sort type. `None` means the values are not comparable
/// (a number column with non-numeric text); [`sort_data_table_rows`] orders those cells after
/// every number.
pub fn compare_data_table_cells(
    left: Option<&DataTableCell>,
    right: Option<&DataTableCell>,
    sort: Option<DataTableSortType>,
) -> Option<Ordering> {
    let left = left.map_or("", DataTableCell::sort_text);
    let right = right.map_or("", DataTableCell::sort_text);

    if sort == Some(DataTableSortType::Number) {
        let left = js_to_number(&left.replace(',', ""))?;
        let right = js_to_number(&right.replace(',', ""))?;

        return left.partial_cmp(&right);
    }

    Some(compare_data_table_text(left, right))
}

/// One row's value for one sort criterion, computed once per sort instead of per comparison.
enum DataTableSortKey<'a> {
    /// Natural text order.
    Text(&'a str),
    /// A number column value; `None` when the text is not a number.
    Number(Option<f64>),
}

impl<'a> DataTableSortKey<'a> {
    fn new(cell: Option<&'a DataTableCell>, sort: Option<DataTableSortType>) -> Self {
        let text = cell.map_or("", DataTableCell::sort_text);

        if sort != Some(DataTableSortType::Number) {
            return Self::Text(text);
        }

        // `-0` ties with `0`, as it does in JavaScript's `a - b`.
        Self::Number(
            js_to_number(&text.replace(',', ""))
                .filter(|number| !number.is_nan())
                .map(|number| if number == 0.0 { 0.0 } else { number }),
        )
    }

    /// A total order: numbers in `direction`, then every value that is not a number, which ties
    /// with the others and follows the numbers in both directions.
    fn compare(&self, other: &Self, direction: DataTableSortDirection) -> Ordering {
        let directed = |order: Ordering| match direction {
            DataTableSortDirection::Ascending => order,
            DataTableSortDirection::Descending => order.reverse(),
        };

        match (self, other) {
            (Self::Text(left), Self::Text(right)) => directed(compare_data_table_text(left, right)),
            (Self::Number(Some(left)), Self::Number(Some(right))) => {
                directed(left.total_cmp(right))
            }
            (Self::Number(Some(_)), Self::Number(None)) => Ordering::Less,
            (Self::Number(None), Self::Number(Some(_))) => Ordering::Greater,
            // Both not numbers, or keys of different columns, which the caller never compares.
            _ => Ordering::Equal,
        }
    }
}

/// Row indexes in display order. Manual mode keeps the given order; client mode sorts stably by
/// each sortable criterion in priority order.
///
/// In a number column, text that is not a number (such as `N/A` or `—`) sorts after the numbers
/// in both directions, in its original order, so the comparison stays a total order.
pub fn sort_data_table_rows(
    rows: &[DataTableRow],
    columns: &[DataTableColumn],
    criteria: &[DataTableSort],
    manual: bool,
) -> Vec<usize> {
    let mut order: Vec<usize> = (0..rows.len()).collect();

    if manual {
        return order;
    }

    let active: Vec<(&DataTableColumn, DataTableSortDirection)> = criteria
        .iter()
        .filter_map(|sort| {
            columns
                .iter()
                .find(|column| column.sortable && column.key == sort.key)
                .map(|column| (column, sort.direction))
        })
        .collect();

    if active.is_empty() {
        return order;
    }

    let keys: Vec<Vec<DataTableSortKey>> = rows
        .iter()
        .map(|row| {
            active
                .iter()
                .map(|(column, _)| DataTableSortKey::new(row.get(&column.key), column.sort))
                .collect()
        })
        .collect();

    order.sort_by(|left, right| {
        keys[*left]
            .iter()
            .zip(&keys[*right])
            .zip(&active)
            .map(|((left, right), (_, direction))| left.compare(right, *direction))
            .find(|order| order.is_ne())
            .unwrap_or_else(|| left.cmp(right))
    });

    order
}

/// Pagination of a [`DataTableViewState`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct DataTablePagination {
    /// Zero-based page.
    pub page_index: usize,
    /// Rows per page, at least 1.
    pub page_size: usize,
}

impl Default for DataTablePagination {
    fn default() -> Self {
        Self {
            page_index: 0,
            page_size: 25,
        }
    }
}

/// Row spacing of a [`DataTableView`](crate::DataTableView).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum DataTableDensity {
    /// Default spacing.
    #[default]
    Comfortable,
    /// Tighter rows.
    Compact,
}

impl DataTableDensity {
    /// The `data-density` value.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Comfortable => "comfortable",
            Self::Compact => "compact",
        }
    }
}

/// An exact-match column filter of a [`DataTableViewState`].
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DataTableFilter {
    /// Column key.
    pub id: String,
    /// Required value.
    pub value: String,
}

/// Serializable view preferences: search, filters, visibility, pagination, sorting, density.
/// Records and selection stay outside the state.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct DataTableViewState {
    /// Case-insensitive search across searchable columns.
    pub search: String,
    /// Exact-match column filters.
    pub filters: Vec<DataTableFilter>,
    /// Column visibility overrides; missing keys are visible.
    pub visibility: Vec<(String, bool)>,
    /// Current page and page size.
    pub pagination: DataTablePagination,
    /// Sort criteria in priority order.
    pub sorting: Vec<DataTableSort>,
    /// Row spacing.
    pub density: DataTableDensity,
}

impl DataTableViewState {
    /// The value of the filter for a column, or an empty string.
    pub fn filter_value(&self, key: &str) -> &str {
        self.filters
            .iter()
            .find(|filter| filter.id == key)
            .map_or("", |filter| filter.value.as_str())
    }

    /// Sets or clears (with an empty value) the filter for a column.
    #[must_use]
    pub fn with_filter(&self, key: &str, value: &str) -> Self {
        let mut next = self.clone();
        next.filters.retain(|filter| filter.id != key);

        if !value.is_empty() {
            next.filters.push(DataTableFilter {
                id: key.to_string(),
                value: value.to_string(),
            });
        }

        next
    }

    /// Sets a column's visibility.
    #[must_use]
    pub fn with_visibility(&self, key: &str, visible: bool) -> Self {
        let mut next = self.clone();

        if let Some(entry) = next
            .visibility
            .iter_mut()
            .find(|(existing, _)| existing == key)
        {
            entry.1 = visible;
        } else {
            next.visibility.push((key.to_string(), visible));
        }

        next
    }

    /// The state after a change to the query (search, filters, sorting, or page size): the page
    /// returns to the first one.
    #[must_use]
    pub fn first_page(mut self) -> Self {
        self.pagination.page_index = 0;
        self
    }
}

/// One column of a [`DataTableView`](crate::DataTableView).
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct DataTableViewColumn {
    /// Unique key into each row's cells.
    pub key: String,
    /// Visible name.
    pub label: String,
    /// Lets users hide the column. Defaults to true.
    pub can_hide: bool,
    /// Lets users sort by the column.
    pub sortable: bool,
    /// Includes the column in the search. Defaults to true.
    pub searchable: bool,
    /// Options of an exact-match filter select, as `(value, label)` pairs.
    pub filter_options: Vec<(String, String)>,
}

impl DataTableViewColumn {
    /// A hideable, searchable column.
    pub fn new(key: impl Into<String>, label: impl Into<String>) -> Self {
        Self {
            key: key.into(),
            label: label.into(),
            can_hide: true,
            sortable: false,
            searchable: true,
            filter_options: Vec::new(),
        }
    }

    /// Makes the column sortable.
    #[must_use]
    pub fn sortable(mut self) -> Self {
        self.sortable = true;
        self
    }

    /// Keeps the column always visible.
    #[must_use]
    pub fn always_visible(mut self) -> Self {
        self.can_hide = false;
        self
    }

    /// Adds an exact-match filter with `(value, label)` options.
    #[must_use]
    pub fn with_filter_options(mut self, options: Vec<(String, String)>) -> Self {
        self.filter_options = options;
        self
    }
}

/// The result of applying a [`DataTableViewState`] to rows.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DataTableViewPage {
    /// Indexes of the rows on the current page, in display order.
    pub rows: Vec<usize>,
    /// Rows that match the search and filters.
    pub matching: usize,
    /// Number of pages, at least 1.
    pub pages: usize,
    /// The current page, clamped to the available pages.
    pub page_index: usize,
}

/// Whether a column is shown: always for columns that cannot hide, otherwise unless the state
/// hides it.
pub fn data_table_column_visible(
    columns: &[DataTableViewColumn],
    state: &DataTableViewState,
    key: &str,
) -> bool {
    columns.iter().any(|column| {
        column.key == key
            && (!column.can_hide
                || !state
                    .visibility
                    .iter()
                    .any(|(hidden, visible)| hidden == key && !visible))
    })
}

/// Filters, sorts, and paginates rows on the client, like the `TanStack` model behind
/// lumen-react's `DataTableView`. With `server` true the rows are already one page: nothing is
/// filtered, sorted, or sliced and `row_count` gives the matching total.
pub fn data_table_view_page(
    rows: &[DataTableRow],
    columns: &[DataTableViewColumn],
    state: &DataTableViewState,
    server: Option<usize>,
) -> DataTableViewPage {
    let size = state.pagination.page_size.max(1);

    if let Some(total) = server {
        let pages = total.div_ceil(size).max(1);

        return DataTableViewPage {
            rows: (0..rows.len()).collect(),
            matching: total,
            pages,
            page_index: state.pagination.page_index.min(pages - 1),
        };
    }

    let search = state.search.to_lowercase();
    let mut matching: Vec<usize> = (0..rows.len())
        .filter(|index| {
            let row = &rows[*index];
            let searched = search.is_empty()
                || columns
                    .iter()
                    .filter(|column| column.searchable)
                    .any(|column| row.text(&column.key).to_lowercase().contains(&search));
            let filtered = state.filters.iter().all(|filter| {
                !columns.iter().any(|column| column.key == filter.id)
                    || row.text(&filter.id) == filter.value
            });

            searched && filtered
        })
        .collect();

    let sortable: Vec<&DataTableSort> = state
        .sorting
        .iter()
        .filter(|sort| {
            columns
                .iter()
                .any(|column| column.key == sort.key && column.sortable)
        })
        .collect();

    if !sortable.is_empty() {
        matching.sort_by(|left, right| {
            for sort in &sortable {
                let order = compare_data_table_text(
                    rows[*left].text(&sort.key),
                    rows[*right].text(&sort.key),
                );
                let order = match sort.direction {
                    DataTableSortDirection::Ascending => order,
                    DataTableSortDirection::Descending => order.reverse(),
                };

                if order != Ordering::Equal {
                    return order;
                }
            }

            left.cmp(right)
        });
    }

    let total = matching.len();
    let pages = total.div_ceil(size).max(1);
    let page_index = state.pagination.page_index.min(pages - 1);
    let rows = matching
        .into_iter()
        .skip(page_index * size)
        .take(size)
        .collect();

    DataTableViewPage {
        rows,
        matching: total,
        pages,
        page_index,
    }
}

/// The criteria after a header activation in a [`DataTableView`](crate::DataTableView): a
/// new criterion starts ascending, an existing one reverses, and `multiple` keeps the others.
pub fn toggle_data_table_view_sort(
    sorting: &[DataTableSort],
    key: &str,
    multiple: bool,
) -> Vec<DataTableSort> {
    let active = sorting.iter().find(|sort| sort.key == key);
    let direction = active.map_or(DataTableSortDirection::Ascending, |sort| {
        sort.direction.reversed()
    });
    let mut next: Vec<DataTableSort> = if multiple {
        sorting
            .iter()
            .filter(|sort| sort.key != key)
            .cloned()
            .collect()
    } else {
        Vec::new()
    };

    next.push(DataTableSort {
        key: key.to_string(),
        direction,
    });
    next
}

#[cfg(test)]
mod tests {
    use std::cmp::Ordering;

    use super::*;

    fn rows() -> Vec<DataTableRow> {
        vec![
            DataTableRow::new("ada")
                .cell("name", "Ada")
                .cell("seats", 12),
            DataTableRow::new("grace")
                .cell("name", "grace")
                .cell("seats", DataTableCell::new("1,200").with_sort_value("1200")),
            DataTableRow::new("linus")
                .cell("name", "Linus")
                .cell("seats", 3),
        ]
    }

    fn columns() -> Vec<DataTableColumn> {
        vec![
            DataTableColumn::new("name", "Name").sortable_text(),
            DataTableColumn::new("seats", "Seats").sortable(DataTableSortType::Number),
        ]
    }

    #[test]
    fn header_activation_replaces_or_extends_criteria() {
        let one = next_data_table_sorting(&[], "name", false);
        assert_eq!(one, [DataTableSort::ascending("name")]);
        assert_eq!(
            next_data_table_sorting(&one, "name", false),
            [DataTableSort::descending("name")]
        );
        assert_eq!(
            next_data_table_sorting(&one, "seats", false),
            [DataTableSort::ascending("seats")]
        );

        let two = next_data_table_sorting(&one, "seats", true);
        assert_eq!(
            two,
            [
                DataTableSort::ascending("name"),
                DataTableSort::ascending("seats")
            ]
        );
        assert_eq!(
            next_data_table_sorting(&two, "name", true),
            [
                DataTableSort::descending("name"),
                DataTableSort::ascending("seats")
            ]
        );
    }

    #[test]
    fn single_sort_headers_cycle_ascending_descending_and_unsorted() {
        let ascending = cycle_data_table_sorting(&[], "name");
        assert_eq!(ascending, [DataTableSort::ascending("name")]);

        let descending = cycle_data_table_sorting(&ascending, "name");
        assert_eq!(descending, [DataTableSort::descending("name")]);

        // The third activation restores the original order.
        assert_eq!(
            cycle_data_table_sorting(&descending, "name"),
            [] as [DataTableSort; 0]
        );
        assert_eq!(
            cycle_data_table_sorting(&descending, "seats"),
            [DataTableSort::ascending("seats")]
        );

        // Only the primary criterion cycles; a secondary one from controlled sorting starts over.
        let both = [
            DataTableSort::descending("name"),
            DataTableSort::descending("seats"),
        ];
        assert_eq!(
            cycle_data_table_sorting(&both, "seats"),
            [DataTableSort::ascending("seats")]
        );
        assert_eq!(
            cycle_data_table_sorting(&both, "name"),
            [] as [DataTableSort; 0]
        );
    }

    #[test]
    fn record_slots_alias_wide_and_default_the_title() {
        let columns = vec![
            DataTableColumn::new("name", "Name").wide(),
            DataTableColumn::new("email", "Email").secondary(),
            DataTableColumn::new("status", "Status").record(TableRecordSlot::Trailing),
            DataTableColumn::new("notes", "Notes")
                .wide()
                .record(TableRecordSlot::Meta),
        ];

        assert_eq!(columns[0].record_slot(), Some(TableRecordSlot::Wide));
        assert_eq!(columns[3].record_slot(), Some(TableRecordSlot::Meta));
        assert!(columns[1].secondary);
        // The only column without a slot is secondary, so no column becomes the default title.
        assert_eq!(
            data_table_record_slots(&columns),
            [
                Some(TableRecordSlot::Wide),
                None,
                Some(TableRecordSlot::Trailing),
                Some(TableRecordSlot::Meta),
            ]
        );

        let titled = vec![
            DataTableColumn::new("name", "Name"),
            DataTableColumn::new("team", "Team").record(TableRecordSlot::Title),
        ];
        assert_eq!(
            data_table_record_slots(&titled),
            [None, Some(TableRecordSlot::Title)]
        );

        // A second title resolves as if it had no `record`: its `wide` alias, or nothing.
        let duplicated = vec![
            DataTableColumn::new("name", "Name").record(TableRecordSlot::Title),
            DataTableColumn::new("team", "Team")
                .wide()
                .record(TableRecordSlot::Title),
            DataTableColumn::new("role", "Role").record(TableRecordSlot::Title),
        ];
        assert_eq!(
            data_table_record_slots(&duplicated),
            [
                Some(TableRecordSlot::Title),
                Some(TableRecordSlot::Wide),
                None
            ]
        );
    }

    #[test]
    fn rows_sort_by_type_and_priority_and_stay_stable() {
        let rows = rows();
        let columns = columns();

        assert_eq!(
            sort_data_table_rows(
                &rows,
                &columns,
                &[DataTableSort::descending("seats")],
                false
            ),
            [1, 0, 2]
        );
        assert_eq!(
            sort_data_table_rows(&rows, &columns, &[DataTableSort::ascending("name")], false),
            [0, 1, 2]
        );
        assert_eq!(
            sort_data_table_rows(&rows, &columns, &[DataTableSort::descending("seats")], true),
            [0, 1, 2]
        );
        // Unknown or unsortable keys keep the original order.
        assert_eq!(
            sort_data_table_rows(&rows, &columns, &[DataTableSort::ascending("role")], false),
            [0, 1, 2]
        );
    }

    #[test]
    fn natural_text_order_compares_numbers_and_ignores_case() {
        assert_eq!(compare_data_table_text("item 2", "item 10"), Ordering::Less);
        assert_eq!(compare_data_table_text("Apple", "apple"), Ordering::Equal);
        assert_eq!(compare_data_table_text("b", "A"), Ordering::Greater);
        assert_eq!(compare_data_table_text("007", "7"), Ordering::Equal);
        assert_eq!(compare_data_table_text("-x", "1"), Ordering::Less);
        assert_eq!(compare_data_table_text("1", "a"), Ordering::Less);
        let long = "9".repeat(100_000);
        assert_eq!(compare_data_table_text(&long, &long), Ordering::Equal);
    }

    #[test]
    fn numbers_parse_like_javascript() {
        assert_eq!(js_to_number(" 12 "), Some(12.0));
        assert_eq!(js_to_number(""), Some(0.0));
        assert_eq!(js_to_number("0x10"), Some(16.0));
        assert_eq!(js_to_number("1e3"), Some(1000.0));
        assert_eq!(js_to_number("Infinity"), Some(f64::INFINITY));
        assert_eq!(js_to_number("inf"), None);
        assert_eq!(js_to_number("12px"), None);
        assert_eq!(
            compare_data_table_cells(
                Some(&"abc".into()),
                Some(&"1".into()),
                Some(DataTableSortType::Number)
            ),
            None
        );
    }

    #[test]
    fn ids_toggle_and_select_all_keeps_other_pages() {
        let ids = vec!["a".to_string()];
        assert_eq!(toggle_data_table_id(&ids, "b"), ["a", "b"]);
        assert_eq!(toggle_data_table_id(&ids, "a"), Vec::<String>::new());

        let rendered = vec!["b".to_string(), "c".to_string()];
        assert_eq!(toggle_data_table_ids(&ids, &rendered), ["a", "b", "c"]);
        let all = vec!["a".to_string(), "b".to_string(), "c".to_string()];
        assert_eq!(toggle_data_table_ids(&all, &rendered), ["a"]);
    }

    #[test]
    fn invalid_columns_and_rows_are_rejected() {
        let duplicate = vec![
            DataTableColumn::new("a", "A"),
            DataTableColumn::new("a", "B"),
        ];
        assert!(valid_data_table_columns(&duplicate).is_empty());
        assert_eq!(valid_data_table_columns(&columns()).len(), 2);
        assert!(!valid_data_table_rows(&[
            DataTableRow::new("x"),
            DataTableRow::new("x")
        ]));
        assert!(!valid_data_table_rows(&[DataTableRow::new("")]));
        assert!(valid_data_table_rows(&rows()));
    }

    #[test]
    fn views_search_filter_sort_and_paginate() {
        let rows: Vec<DataTableRow> = (0..30)
            .map(|index| {
                DataTableRow::new(format!("r{index}"))
                    .cell("name", format!("Item {index}"))
                    .cell("status", if index % 3 == 0 { "Open" } else { "Closed" })
            })
            .collect();
        let columns = vec![
            DataTableViewColumn::new("name", "Name").sortable(),
            DataTableViewColumn::new("status", "Status"),
        ];
        let mut state = DataTableViewState {
            pagination: DataTablePagination {
                page_index: 0,
                page_size: 4,
            },
            ..DataTableViewState::default()
        };

        let page = data_table_view_page(&rows, &columns, &state, None);
        assert_eq!((page.matching, page.pages, page.rows.len()), (30, 8, 4));

        state = state.with_filter("status", "Open");
        let page = data_table_view_page(&rows, &columns, &state, None);
        assert_eq!((page.matching, page.pages), (10, 3));

        state.search = "item 2".into();
        let page = data_table_view_page(&rows, &columns, &state, None);
        assert_eq!(page.rows, [21, 24, 27]);

        state.sorting = toggle_data_table_view_sort(&state.sorting, "name", false);
        state.sorting = toggle_data_table_view_sort(&state.sorting, "name", false);
        let page = data_table_view_page(&rows, &columns, &state, None);
        assert_eq!(page.rows, [27, 24, 21]);

        // Pages past the end clamp to the last page.
        state.pagination.page_index = 99;
        assert_eq!(
            data_table_view_page(&rows, &columns, &state, None).page_index,
            0
        );
        assert_eq!(
            data_table_view_page(&rows, &columns, &state, Some(0)).pages,
            1
        );
    }

    #[test]
    fn visibility_respects_columns_that_cannot_hide() {
        let columns = vec![
            DataTableViewColumn::new("name", "Name").always_visible(),
            DataTableViewColumn::new("status", "Status"),
        ];
        let state = DataTableViewState::default()
            .with_visibility("name", false)
            .with_visibility("status", false);

        assert!(data_table_column_visible(&columns, &state, "name"));
        assert!(!data_table_column_visible(&columns, &state, "status"));
        assert!(!data_table_column_visible(&columns, &state, "missing"));
    }
}