Skip to main content

waft_winui/controls/table_view/
sort.rs

1//! `TableView`'s single-column sort (`controls/dev/TableView/TableView_Sort.cpp`): `SortByColumn`, `ToggleSortDirection` and `ClearSort`, the cancelable `Sorting` before and `Sorted` after, the source axis the table installs for its sorted column, and the selection kept on its item across the reshape; and `TableViewSort`, which carries those requests from code to the table.
2//!
3//! The sort state lives on the columns, as `TableViewColumn::sort_direction`, and the table performs every sort, so sorting from a header click needs no `TableViewSort`. A later editor who keeps sort state in `TableViewSort` makes two answers to what is sorted.
4
5use super::column::TableViewColumn;
6use super::source::SortDirection;
7use super::*;
8use std::fmt;
9use std::rc::Rc;
10use waft_foundation::{App, Handle, HandleId, Ref};
11
12/// A sort the application asks of a table.
13#[derive(Clone, Copy, Debug, PartialEq, Eq)]
14pub(crate) enum SortRequest {
15    /// `SortByColumn`.
16    ByColumn(HandleId, SortDirection),
17    /// `ToggleSortDirection`.
18    Toggle(HandleId),
19    /// `ClearSort`.
20    Clear,
21}
22
23/// The table a sort is given to: it performs a request and answers whether the sort state changed.
24pub(crate) type SortPerformer = Rc<dyn Fn(&mut App, SortRequest) -> bool>;
25
26/// Sorting a `TableView` from code.
27///
28/// The application makes one with [`TableViewSort::new`], and gives it to the table with `TableView::sort`. Until a mounted table holds it, every request answers false.
29pub struct TableViewSort {
30    performer: Option<(HandleId, SortPerformer)>,
31}
32
33impl TableViewSort {
34    /// Creates a sort no table holds yet.
35    pub fn new(app: &mut App) -> Ref<Self> {
36        app.create(Self { performer: None })
37    }
38
39    /// `SortByColumn`: clears any other column's sort, then sorts `column` in `direction`; `None` clears it. Raises `Sorting`, which can cancel, then `Sorted`. Answers whether the sort state changed.
40    pub fn sort_by_column<T: 'static>(
41        self: Handle<Self>,
42        app: &mut App,
43        column: &Ref<TableViewColumn<T>>,
44        direction: SortDirection,
45    ) -> bool {
46        self.perform(app, SortRequest::ByColumn(column.handle().id(), direction))
47    }
48
49    /// `ToggleSortDirection`: the column's next direction in its `SortCycle`, any other column's sort cleared first.
50    pub fn toggle_sort_direction<T: 'static>(
51        self: Handle<Self>,
52        app: &mut App,
53        column: &Ref<TableViewColumn<T>>,
54    ) -> bool {
55        self.perform(app, SortRequest::Toggle(column.handle().id()))
56    }
57
58    /// `ClearSort`: every column's sort, in one change. Answers whether anything was cleared.
59    pub fn clear_sort(self: Handle<Self>, app: &mut App) -> bool {
60        self.perform(app, SortRequest::Clear)
61    }
62
63    /// The table `owner` holds the sort and performs its requests.
64    pub(crate) fn bind(
65        self: Handle<Self>,
66        app: &mut App,
67        owner: HandleId,
68        performer: SortPerformer,
69    ) {
70        app.get_mut(self).performer = Some((owner, performer));
71    }
72
73    /// The table `owner` lets the sort go.
74    pub(crate) fn unbind(self: Handle<Self>, app: &mut App, owner: HandleId) {
75        let sort = app.get_mut(self);
76        if sort
77            .performer
78            .as_ref()
79            .is_some_and(|(held, _)| *held == owner)
80        {
81            sort.performer = None;
82        }
83    }
84
85    fn perform(self: Handle<Self>, app: &mut App, request: SortRequest) -> bool {
86        match app.get(self).performer.clone() {
87            Some((_, performer)) => performer(app, request),
88            None => false,
89        }
90    }
91}
92
93impl fmt::Debug for TableViewSort {
94    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
95        f.debug_struct("TableViewSort")
96            .field("bound", &self.performer.is_some())
97            .finish()
98    }
99}
100
101// MARK: The table's sorting (`TableView_Sort.cpp`)
102
103impl<T: 'static> TableViewState<T> {
104    pub(super) fn sync_sort(self: Handle<Self>, app: &mut App) {
105        let id = self.id_of();
106        let sort = self.widget(app).sort.clone();
107        if app.get(self).sort.handle() == sort.handle() {
108            return;
109        }
110        if let Some(old) = app.get_mut(self).sort.take() {
111            old.unbind(app, id);
112        }
113        if let Some(sort) = &sort {
114            sort.bind(
115                app,
116                id,
117                Rc::new(move |app, request| self.alive(app) && self.perform_sort(app, request)),
118            );
119        }
120        app.get_mut(self).sort = sort;
121    }
122
123    pub(super) fn column_of(
124        self: Handle<Self>,
125        app: &App,
126        id: HandleId,
127    ) -> Option<Handle<TableViewColumn<T>>> {
128        self.owned_columns(app)
129            .into_iter()
130            .find(|column| column.id() == id)
131    }
132
133    pub(super) fn perform_sort(self: Handle<Self>, app: &mut App, request: SortRequest) -> bool {
134        match request {
135            SortRequest::ByColumn(id, direction) => self
136                .column_of(app, id)
137                .is_some_and(|column| self.sort_by_column(app, column, direction)),
138            SortRequest::Toggle(id) => self
139                .column_of(app, id)
140                .is_some_and(|column| self.toggle_sort_direction(app, column)),
141            SortRequest::Clear => self.clear_sort(app),
142        }
143    }
144
145    /// `IsSortRequestStillValid`: the column is still one of ours and can still sort; a `Sorting` handler may have changed either.
146    pub(super) fn is_sort_request_still_valid(
147        self: Handle<Self>,
148        app: &App,
149        column: Handle<TableViewColumn<T>>,
150    ) -> bool {
151        app.contains(column) && column.is_sortable(app) && self.owned_columns(app).contains(&column)
152    }
153
154    /// `SortByColumn`.
155    pub(super) fn sort_by_column(
156        self: Handle<Self>,
157        app: &mut App,
158        column: Handle<TableViewColumn<T>>,
159        direction: SortDirection,
160    ) -> bool {
161        if !column.is_sortable(app) {
162            return false;
163        }
164        let sorted = app.get(self).sorted_column;
165        if direction == SortDirection::None && sorted.is_none() {
166            return false;
167        }
168        if sorted == Some(column) && column.sort_direction(app) == direction {
169            return false;
170        }
171        self.apply_sort(app, column, direction)
172    }
173
174    /// `ToggleSortDirection`: the column's `SortCycle` names the direction an unsorted column opens in, and whether a third click returns to source order.
175    pub(super) fn toggle_sort_direction(
176        self: Handle<Self>,
177        app: &mut App,
178        column: Handle<TableViewColumn<T>>,
179    ) -> bool {
180        if !column.is_sortable(app) {
181            return false;
182        }
183        let cycle = column.sort_cycle(app);
184        let opens_descending = matches!(
185            cycle,
186            TableViewSortCycle::DescendingAscending | TableViewSortCycle::DescendingAscendingNone
187        );
188        let cycles_to_unsorted = matches!(
189            cycle,
190            TableViewSortCycle::AscendingDescendingNone
191                | TableViewSortCycle::DescendingAscendingNone
192        );
193        let (opening, second) = if opens_descending {
194            (SortDirection::Descending, SortDirection::Ascending)
195        } else {
196            (SortDirection::Ascending, SortDirection::Descending)
197        };
198        let current = column.sort_direction(app);
199        let next = if current == opening {
200            second
201        } else if current == second {
202            if cycles_to_unsorted {
203                SortDirection::None
204            } else {
205                opening
206            }
207        } else {
208            opening
209        };
210        self.apply_sort(app, column, next)
211    }
212
213    /// The shared tail of `SortByColumn` and `ToggleSortDirection`: `Sorting`, which can cancel, then the state, the reshape and `Sorted`.
214    pub(super) fn apply_sort(
215        self: Handle<Self>,
216        app: &mut App,
217        column: Handle<TableViewColumn<T>>,
218        direction: SortDirection,
219    ) -> bool {
220        if !self.is_sort_request_still_valid(app, column) {
221            return false;
222        }
223        if self.raise_sorting_and_check_canceled(app, Some(column), direction) {
224            return false;
225        }
226        if !self.is_sort_request_still_valid(app, column) {
227            return false;
228        }
229        self.apply_single_column_sort_state(app, column, direction);
230        self.recompute_sort_and_raise(app, Some(column));
231        true
232    }
233
234    /// `ClearSort`.
235    pub(super) fn clear_sort(self: Handle<Self>, app: &mut App) -> bool {
236        if app.get(self).sorted_column.is_none() {
237            return false;
238        }
239        if self.raise_sorting_and_check_canceled(app, None, SortDirection::None) {
240            return false;
241        }
242        let Some(sorted) = app.get_mut(self).sorted_column.take() else {
243            return false;
244        };
245        if app.contains(sorted) {
246            sorted.set_sort_state(app, SortDirection::None);
247        }
248        self.recompute_sort_and_raise(app, None);
249        true
250    }
251
252    /// `ResetSortStateForNewItemsSource`: silent, for the rows the sort ordered are gone.
253    pub(super) fn reset_sort_state_for_new_items_source(self: Handle<Self>, app: &mut App) {
254        if let Some(sorted) = app.get_mut(self).sorted_column.take()
255            && app.contains(sorted)
256        {
257            sorted.set_sort_state(app, SortDirection::None);
258        }
259        app.get_mut(self).source_sort_token = None;
260    }
261
262    /// `ApplySingleColumnSortState`: every other column's sort is cleared first.
263    pub(super) fn apply_single_column_sort_state(
264        self: Handle<Self>,
265        app: &mut App,
266        column: Handle<TableViewColumn<T>>,
267        direction: SortDirection,
268    ) {
269        if let Some(sorted) = app.get_mut(self).sorted_column.take()
270            && sorted != column
271            && app.contains(sorted)
272        {
273            sorted.set_sort_state(app, SortDirection::None);
274        }
275        column.set_sort_state(app, direction);
276        if direction != SortDirection::None {
277            app.get_mut(self).sorted_column = Some(column);
278        }
279    }
280
281    /// `RaiseSortingAndCheckCanceled`.
282    pub(super) fn raise_sorting_and_check_canceled(
283        self: Handle<Self>,
284        app: &mut App,
285        column: Option<Handle<TableViewColumn<T>>>,
286        direction: SortDirection,
287    ) -> bool {
288        let Some(sorting) = self.widget(app).sorting.clone() else {
289            return false;
290        };
291        let args = TableViewSortingEventArgs {
292            column,
293            direction,
294            cancel: Cell::new(false),
295        };
296        sorting(app, &args);
297        args.cancel()
298    }
299
300    /// `RecomputeSortDPsAndRaiseInternal`: reshapes the rows, keeps the selection on its item, and raises `Sorted`.
301    pub(super) fn recompute_sort_and_raise(
302        self: Handle<Self>,
303        app: &mut App,
304        trigger: Option<Handle<TableViewColumn<T>>>,
305    ) {
306        if !self.alive(app) {
307            return;
308        }
309        // A clear queued earlier and overtaken by a newer sort must not tear that sort down.
310        if trigger.is_none() && app.get(self).sorted_column.is_some() {
311            return;
312        }
313        let direction = trigger
314            .filter(|column| app.contains(*column))
315            .map_or(SortDirection::None, |column| column.sort_direction(app));
316        let selection = self.selection_handle(app);
317        let preserved = selection.and_then(|selection| selection.selected_item(app));
318        let reshaped = self.sync_table_view_source_sort(app, trigger, direction);
319        if reshaped && let (Some(selection), Some(item)) = (selection, preserved) {
320            // Selection is by row, and a re-sort moves every row: it follows the item instead.
321            let row = self
322                .source_handle(app)
323                .view(app)
324                .iter()
325                .position(|&i| i == item);
326            match row {
327                Some(row) => selection.select(app, row),
328                None => selection.deselect_all(app),
329            }
330        }
331        if let Some(sorted) = self.widget(app).sorted.clone() {
332            let args = TableViewSortedEventArgs {
333                column: trigger,
334                direction,
335            };
336            sorted(app, &args);
337        }
338    }
339
340    /// `SyncTableViewSourceSort`: installs, replaces or removes the source axis for the sorted column. Answers whether it reshaped.
341    pub(super) fn sync_table_view_source_sort(
342        self: Handle<Self>,
343        app: &mut App,
344        trigger: Option<Handle<TableViewColumn<T>>>,
345        direction: SortDirection,
346    ) -> bool {
347        let source = self.source_handle(app);
348        let previous = app.get(self).source_sort_token;
349        match trigger {
350            Some(column) => {
351                let Some(compare) = column.sort_comparer(app) else {
352                    return false;
353                };
354                let token = column.id();
355                if direction == SortDirection::None {
356                    source.clear_sort_axis(app, token);
357                    app.get_mut(self).source_sort_token = None;
358                } else {
359                    source.sort_replacing(app, previous, token, compare, direction);
360                    app.get_mut(self).source_sort_token = Some(token);
361                }
362            }
363            None => {
364                let Some(token) = previous else {
365                    return false;
366                };
367                source.clear_sort_axis(app, token);
368                app.get_mut(self).source_sort_token = None;
369            }
370        }
371        true
372    }
373}