leptos_struct_table/
sorting.rs

1use crate::{ColumnSort, TableHeadEvent};
2use std::collections::VecDeque;
3
4/// Sorting mode
5#[derive(PartialEq, Eq, Clone, Copy, Debug, Default)]
6pub enum SortingMode {
7    /// The table can be sorted by only one single column at a time
8    SingleColumn,
9
10    /// The table can be sorted by multiple columns ordered by priority
11    #[default]
12    MultiColumn,
13}
14
15impl SortingMode {
16    pub fn update_sorting_from_event<Column>(
17        &self,
18        sorting: &mut VecDeque<(Column, ColumnSort)>,
19        event: TableHeadEvent<Column>,
20    ) where
21        Column: Eq + Clone + Copy,
22    {
23        let (i, &(_, mut sort)) = sorting
24            .iter()
25            .enumerate()
26            .find(|(_, (col_index, _))| col_index == &event.index)
27            .unwrap_or((0, &(event.index, ColumnSort::None)));
28
29        if i == 0 || sort == ColumnSort::None {
30            sort = match sort {
31                ColumnSort::None => ColumnSort::Ascending,
32                ColumnSort::Ascending => ColumnSort::Descending,
33                ColumnSort::Descending => ColumnSort::None,
34            };
35        }
36
37        *sorting = sorting
38            .clone()
39            .into_iter()
40            .filter(|(col_index, sort)| *col_index != event.index && *sort != ColumnSort::None)
41            .collect();
42
43        if sort != ColumnSort::None {
44            sorting.push_front((event.index, sort));
45        }
46
47        if self == &SortingMode::SingleColumn {
48            sorting.truncate(1);
49        }
50    }
51}