Skip to main content

orbital_datatable/engine/
sort.rs

1use crate::engine::column::resolve_value;
2use crate::engine::compare::compare_for_sort;
3use crate::types::{DataTableColumnDef, DataTableRowModel, DataTableSort, SortRule};
4
5#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
6pub enum SortDirection {
7    #[default]
8    Asc,
9    Desc,
10}
11
12/// Legacy single-column sort state (prefer [`DataTableSort`]).
13#[derive(Clone, Debug, Default)]
14pub struct SortState {
15    pub field: Option<String>,
16    pub direction: SortDirection,
17}
18
19impl SortState {
20    pub fn from_data_table_sort(sort: &DataTableSort) -> Self {
21        sort.items.first().map_or(Self::default(), |rule| Self {
22            field: Some(rule.field.clone()),
23            direction: rule.direction,
24        })
25    }
26}
27
28impl From<&SortState> for DataTableSort {
29    fn from(state: &SortState) -> Self {
30        DataTableSort::from_sort_state(state)
31    }
32}
33
34pub fn sort_rows_multi(
35    mut rows: Vec<DataTableRowModel>,
36    columns: &[DataTableColumnDef],
37    sort: &DataTableSort,
38) -> Vec<DataTableRowModel> {
39    if sort.items.is_empty() {
40        return rows;
41    }
42
43    rows.sort_by(|a, b| {
44        for rule in &sort.items {
45            let Some(col) = columns.iter().find(|c| c.field == rule.field && c.sortable) else {
46                continue;
47            };
48            let av = resolve_value(col, a);
49            let bv = resolve_value(col, b);
50            let ord = compare_for_sort(col, &av, &bv);
51            let cmp = match rule.direction {
52                SortDirection::Asc => ord,
53                SortDirection::Desc => ord.reverse(),
54            };
55            if cmp != std::cmp::Ordering::Equal {
56                return cmp;
57            }
58        }
59        std::cmp::Ordering::Equal
60    });
61    rows
62}
63
64pub fn sort_rows(
65    rows: Vec<DataTableRowModel>,
66    columns: &[DataTableColumnDef],
67    sort: &SortState,
68) -> Vec<DataTableRowModel> {
69    sort_rows_multi(rows, columns, &DataTableSort::from_sort_state(sort))
70}
71
72/// Apply header click sort: single-column or multi-column (Ctrl/Cmd additive).
73pub fn apply_header_sort(
74    sort: &mut DataTableSort,
75    field: &str,
76    multi_column_enabled: bool,
77    additive: bool,
78) {
79    if multi_column_enabled && additive {
80        if let Some(existing) = sort.items.iter_mut().find(|r| r.field == field) {
81            existing.direction = match existing.direction {
82                SortDirection::Asc => SortDirection::Desc,
83                SortDirection::Desc => SortDirection::Asc,
84            };
85        } else {
86            sort.items.push(SortRule {
87                field: field.to_string(),
88                direction: SortDirection::Asc,
89            });
90        }
91        return;
92    }
93
94    if let Some(existing) = sort.items.first() {
95        if existing.field == field {
96            sort.items = vec![SortRule {
97                field: field.to_string(),
98                direction: match existing.direction {
99                    SortDirection::Asc => SortDirection::Desc,
100                    SortDirection::Desc => SortDirection::Asc,
101                },
102            }];
103            return;
104        }
105    }
106
107    sort.items = vec![SortRule {
108        field: field.to_string(),
109        direction: SortDirection::Asc,
110    }];
111}
112
113#[cfg(test)]
114mod tests {
115    use super::*;
116    use std::collections::HashMap;
117
118    use orbital_data::DataValue;
119
120    #[test]
121    fn sort_desc_reorders_rows() {
122        let rows = vec![
123            DataTableRowModel::from_text_cells("1", HashMap::from([("name".into(), "Ada".into())])),
124            DataTableRowModel::from_text_cells(
125                "2",
126                HashMap::from([("name".into(), "Grace".into())]),
127            ),
128        ];
129        let columns = vec![DataTableColumnDef::new("name", "Name")];
130        let sort = SortState {
131            field: Some("name".into()),
132            direction: SortDirection::Desc,
133        };
134        let sorted = sort_rows(rows, &columns, &sort);
135        assert_eq!(sorted[0].id(), "2");
136        assert_eq!(sorted[1].id(), "1");
137    }
138
139    #[test]
140    fn typed_number_sort() {
141        let rows = vec![
142            DataTableRowModel::new(orbital_data::DataRecord::new(
143                "10",
144                HashMap::from([("n".into(), DataValue::Number(10.0))]),
145            )),
146            DataTableRowModel::new(orbital_data::DataRecord::new(
147                "2",
148                HashMap::from([("n".into(), DataValue::Number(2.0))]),
149            )),
150        ];
151        let columns =
152            vec![DataTableColumnDef::new("n", "N").with_col_type(crate::types::ColumnType::Number)];
153        let sort = SortState {
154            field: Some("n".into()),
155            direction: SortDirection::Asc,
156        };
157        let sorted = sort_rows(rows, &columns, &sort);
158        assert_eq!(sorted[0].id(), "2");
159        assert_eq!(sorted[1].id(), "10");
160    }
161
162    #[test]
163    fn multi_sort_tie_breaks() {
164        let rows = vec![
165            DataTableRowModel::from_text_cells(
166                "1",
167                HashMap::from([("role".into(), "A".into()), ("name".into(), "Bob".into())]),
168            ),
169            DataTableRowModel::from_text_cells(
170                "2",
171                HashMap::from([("role".into(), "A".into()), ("name".into(), "Ada".into())]),
172            ),
173            DataTableRowModel::from_text_cells(
174                "3",
175                HashMap::from([("role".into(), "B".into()), ("name".into(), "Zed".into())]),
176            ),
177        ];
178        let columns = vec![
179            DataTableColumnDef::new("role", "Role"),
180            DataTableColumnDef::new("name", "Name"),
181        ];
182        let sort = DataTableSort {
183            items: vec![
184                SortRule {
185                    field: "role".into(),
186                    direction: SortDirection::Asc,
187                },
188                SortRule {
189                    field: "name".into(),
190                    direction: SortDirection::Asc,
191                },
192            ],
193        };
194        let sorted = sort_rows_multi(rows, &columns, &sort);
195        assert_eq!(sorted[0].id(), "2");
196        assert_eq!(sorted[1].id(), "1");
197        assert_eq!(sorted[2].id(), "3");
198    }
199}