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(
17        &self,
18        sorting: &mut VecDeque<(usize, ColumnSort)>,
19        event: TableHeadEvent,
20    ) {
21        let (i, (_, mut sort)) = sorting
22            .iter()
23            .enumerate()
24            .find(|(_, (col_index, _))| col_index == &event.index)
25            .unwrap_or((0, &(event.index, ColumnSort::None)));
26
27        if i == 0 || sort == ColumnSort::None {
28            sort = match sort {
29                ColumnSort::None => ColumnSort::Ascending,
30                ColumnSort::Ascending => ColumnSort::Descending,
31                ColumnSort::Descending => ColumnSort::None,
32            };
33        }
34
35        *sorting = sorting
36            .clone()
37            .into_iter()
38            .filter(|(col_index, sort)| *col_index != event.index && *sort != ColumnSort::None)
39            .collect();
40
41        if sort != ColumnSort::None {
42            sorting.push_front((event.index, sort));
43        }
44
45        if self == &SortingMode::SingleColumn {
46            sorting.truncate(1);
47        }
48    }
49}