Debian Codegraph @

src/canvas/components/data_table/sortable.rs

raw symbols SCIP
1 use std::{borrow::Cow, marker::PhantomData, num::NonZeroU16};
2
3 use concat_string::concat_string;
4 use itertools::Itertools;
5 use ratatui::widgets::Row;
6 use serde::Deserialize;
7
8 use super::{
9 ColumnHeader, ColumnWidthBounds, DataTable, DataTableColumn, DataTableProps, DataTableState,
10 DataTableStyling, DataToCell,
11 };
12 use crate::{canvas::components::data_table::Column, utils::strings::truncate_to_text};
13
14 /// Denotes the sort order.
15 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
16 #[cfg_attr(
17 feature = "generate_schema",
18 derive(schemars::JsonSchema, strum::VariantArray)
19 )]
20 pub enum SortOrder {
21 Ascending,
22 Descending,
23 }
24
25 impl<'de> Deserialize<'de> for SortOrder {
26 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
27 where
28 D: serde::Deserializer<'de>,
29 {
30 let value = String::deserialize(deserializer)?.to_lowercase();
31 match value.as_str() {
32 "ascending" => Ok(SortOrder::Ascending),
33 "descending" => Ok(SortOrder::Descending),
34 _ => Err(serde::de::Error::custom(
35 "doesn't match any sort order variant",
36 )),
37 }
38 }
39 }
40
41 impl SortOrder {
42 /// Returns the reverse [`SortOrder`].
43 pub fn rev(&self) -> SortOrder {
44 match self {
45 SortOrder::Ascending => SortOrder::Descending,
46 SortOrder::Descending => SortOrder::Ascending,
47 }
48 }
49
50 /// A hack to get a const default.
51 pub const fn const_default() -> Self {
52 Self::Ascending
53 }
54 }
55
56 impl Default for SortOrder {
57 fn default() -> Self {
58 Self::const_default()
59 }
60 }
61
62 /// Denotes the [`DataTable`] is unsorted.
63 pub struct Unsortable;
64
65 /// Denotes the [`DataTable`] is sorted.
66 pub struct Sortable {
67 /// The currently selected sort index.
68 pub sort_index: usize,
69
70 /// The current sorting order.
71 pub order: SortOrder,
72 }
73
74 /// The [`SortType`] trait is meant to be used in the typing of a [`DataTable`]
75 /// to denote whether the table is meant to display/store sorted or unsorted
76 /// data.
77 ///
78 /// Note that the trait is [sealed](https://rust-lang.github.io/api-guidelines/future-proofing.html#sealed-traits-protect-against-downstream-implementations-c-sealed),
79 /// and therefore only [`Unsortable`] and [`Sortable`] can implement it.
80 pub trait SortType: private::Sealed {
81 /// Constructs the table header.
82 fn build_header<H, C>(&self, columns: &[C], widths: &[NonZeroU16]) -> Row<'_>
83 where
84 H: ColumnHeader,
85 C: DataTableColumn<H>,
86 {
87 Row::new(
88 columns
89 .iter()
90 .zip(widths)
91 .map(|(c, &width)| truncate_to_text(&c.header(), width.get())),
92 )
93 }
94 }
95
96 mod private {
97 use super::{Sortable, Unsortable};
98
99 pub trait Sealed {}
100
101 impl Sealed for Unsortable {}
102 impl Sealed for Sortable {}
103 }
104
105 impl SortType for Unsortable {}
106
107 impl SortType for Sortable {
108 fn build_header<H, C>(&self, columns: &[C], widths: &[NonZeroU16]) -> Row<'_>
109 where
110 H: ColumnHeader,
111 C: DataTableColumn<H>,
112 {
113 const UP_ARROW: &str = "â–²";
114 const DOWN_ARROW: &str = "â–¼";
115
116 Row::new(
117 columns
118 .iter()
119 .zip(widths)
120 .enumerate()
121 .map(|(index, (c, &width))| {
122 if index == self.sort_index {
123 let arrow = match self.order {
124 SortOrder::Ascending => UP_ARROW,
125 SortOrder::Descending => DOWN_ARROW,
126 };
127 // TODO: I think I can get away with removing the truncate_to_text call
128 // since I almost always bind to at least the header
129 // size... TODO: Or should we instead truncate but
130 // ALWAYS leave the arrow at the end?
131 truncate_to_text(&concat_string!(c.header(), arrow), width.get())
132 } else {
133 truncate_to_text(&c.header(), width.get())
134 }
135 }),
136 )
137 }
138 }
139
140 pub trait SortsRow {
141 type DataType;
142
143 /// Sorts data.
144 fn sort_data(&self, data: &mut [Self::DataType], descending: bool);
145 }
146
147 /// A wrapper around [`Column`] that also has sorting capabilities.
148 #[derive(Debug, Clone)]
149 pub struct SortColumn<H> {
150 /// The inner column header.
151 column: Column<H>,
152
153 /// The default sort order.
154 pub default_order: SortOrder,
155 }
156
157 impl<D, H> DataTableColumn<H> for SortColumn<H>
158 where
159 H: ColumnHeader + SortsRow<DataType = D>,
160 {
161 #[inline]
162 fn inner(&self) -> &H {
163 self.column.inner()
164 }
165
166 #[inline]
167 fn inner_mut(&mut self) -> &mut H {
168 self.column.inner_mut()
169 }
170
171 #[inline]
172 fn bounds(&self) -> ColumnWidthBounds {
173 self.column.bounds()
174 }
175
176 #[inline]
177 fn bounds_mut(&mut self) -> &mut ColumnWidthBounds {
178 self.column.bounds_mut()
179 }
180
181 #[inline]
182 fn is_hidden(&self) -> bool {
183 self.column.is_hidden()
184 }
185
186 #[inline]
187 fn set_hidden(&mut self, hidden: bool) {
188 self.column.set_hidden(hidden);
189 }
190
191 fn header(&self) -> Cow<'static, str> {
192 self.column.header()
193 }
194
195 fn header_len(&self) -> usize {
196 self.header().len() + 1
197 }
198 }
199
200 impl<D, T> SortColumn<T>
201 where
202 T: ColumnHeader + SortsRow<DataType = D>,
203 {
204 /// Creates a new [`SortColumn`] with a width that follows the header width,
205 /// which has no shortcut and sorts by default in ascending order
206 /// ([`SortOrder::Ascending`]).
207 pub fn new(inner: T) -> Self {
208 Self {
209 column: Column::new(inner),
210 default_order: SortOrder::const_default(),
211 }
212 }
213
214 /// Creates a new [`SortColumn`] with a hard width, which has no shortcut
215 /// and sorts by default in ascending order ([`SortOrder::Ascending`]).
216 pub const fn hard(inner: T, width: u16) -> Self {
217 Self {
218 column: Column::hard(inner, width),
219 default_order: SortOrder::const_default(),
220 }
221 }
222
223 /// Creates a new [`SortColumn`] with a soft width, which has no shortcut
224 /// and sorts by default in ascending order ([`SortOrder::Ascending`]).
225 pub const fn soft(inner: T, max_percentage: Option<f32>) -> Self {
226 Self {
227 column: Column::soft(inner, max_percentage),
228 default_order: SortOrder::const_default(),
229 }
230 }
231
232 /// Sets the default sort order to [`SortOrder::Descending`].
233 pub const fn default_descending(mut self) -> Self {
234 self.default_order = SortOrder::Descending;
235 self
236 }
237
238 /// Given a [`SortColumn`] and the sort order, sort a mutable slice of
239 /// associated data.
240 pub fn sort_by(&self, data: &mut [D], order: SortOrder) {
241 let descending = matches!(order, SortOrder::Descending);
242 self.column.inner().sort_data(data, descending);
243 }
244 }
245
246 pub struct SortDataTableProps {
247 pub inner: DataTableProps,
248 pub sort_index: usize,
249 pub order: SortOrder,
250 }
251
252 /// A type alias for a sortable [`DataTable`].
253 pub type SortDataTable<DataType, H> = DataTable<DataType, H, Sortable, SortColumn<H>>;
254
255 impl<D, H> SortDataTable<D, H>
256 where
257 D: DataToCell<H>,
258 H: ColumnHeader + SortsRow<DataType = D>,
259 {
260 pub fn new_sortable<C: Into<Vec<SortColumn<H>>>>(
261 columns: C, props: SortDataTableProps, styling: DataTableStyling,
262 ) -> Self {
263 Self {
264 columns: columns.into(),
265 state: DataTableState::default(),
266 props: props.inner,
267 styling,
268 sort_type: Sortable {
269 sort_index: props.sort_index,
270 order: props.order,
271 },
272 first_draw: true,
273 first_index: None,
274 data: vec![],
275 _pd: PhantomData,
276 }
277 }
278
279 /// Sets the current sort order.
280 pub fn set_order(&mut self, order: SortOrder) {
281 self.sort_type.order = order;
282 }
283
284 /// Gets the current sort order.
285 pub fn order(&self) -> SortOrder {
286 self.sort_type.order
287 }
288
289 /// Toggles the current sort order.
290 pub fn toggle_order(&mut self) {
291 self.sort_type.order = self.sort_type.order.rev();
292 }
293
294 /// Given some `x` and `y`, if possible, select the corresponding column or
295 /// toggle the column if already selected, and otherwise do nothing.
296 ///
297 /// If there was some update, the corresponding column type will be
298 /// returned. If nothing happens, [`None`] is returned.
299 pub fn try_select_location(&mut self, x: u16, y: u16) -> Option<usize> {
300 if self.state.inner_rect.height > 1 && self.state.inner_rect.y == y {
301 if let Some(index) = self.get_range(x) {
302 self.set_sort_index(index);
303 Some(self.sort_type.sort_index)
304 } else {
305 None
306 }
307 } else {
308 None
309 }
310 }
311
312 /// Updates the sort index, and sets the sort order as appropriate.
313 ///
314 /// If the index is different from the previous one, it will move to the new
315 /// index and set the sort order to the prescribed default sort order.
316 ///
317 /// If the index is the same as the previous one, it will simply toggle the
318 /// current sort order.
319 pub fn set_sort_index(&mut self, index: usize) {
320 if self.sort_type.sort_index == index {
321 self.toggle_order();
322 } else if let Some(col) = self.columns.get(index) {
323 self.sort_type.sort_index = index;
324 self.sort_type.order = col.default_order;
325 }
326 }
327
328 /// Returns the current sort index.
329 pub fn sort_index(&self) -> usize {
330 self.sort_type.sort_index
331 }
332
333 /// Given a `needle` coordinate, select the corresponding index and value.
334 fn get_range(&self, needle: u16) -> Option<usize> {
335 let mut start = self.state.inner_rect.x;
336 let range = self
337 .state
338 .calculated_widths
339 .iter()
340 .map(|width| {
341 let entry_start = start;
342 start += width.get() + 1; // +1 for the gap b/w cols.
343
344 entry_start
345 })
346 .collect_vec();
347
348 match range.binary_search(&needle) {
349 Ok(index) => Some(index),
350 Err(index) => index.checked_sub(1),
351 }
352 }
353 }
354
355 #[cfg(test)]
356 mod test {
357 use super::*;
358 use crate::options::config::flags::TableGap;
359
360 #[derive(Clone, PartialEq, Eq, Debug)]
361 struct TestType {
362 index: usize,
363 data: u64,
364 }
365
366 enum ColumnType {
367 Index,
368 Data,
369 }
370
371 impl DataToCell<ColumnType> for TestType {
372 fn to_cell_text(
373 &self, _column: &ColumnType, _calculated_width: NonZeroU16,
374 ) -> Option<Cow<'static, str>> {
375 None
376 }
377
378 fn column_widths<C: DataTableColumn<ColumnType>>(_data: &[Self], _columns: &[C]) -> Vec<u16>
379 where
380 Self: Sized,
381 {
382 vec![]
383 }
384 }
385
386 impl ColumnHeader for ColumnType {
387 fn text(&self) -> Cow<'static, str> {
388 match self {
389 ColumnType::Index => "Index".into(),
390 ColumnType::Data => "Data".into(),
391 }
392 }
393 }
394
395 impl SortsRow for ColumnType {
396 type DataType = TestType;
397
398 fn sort_data(&self, data: &mut [TestType], descending: bool) {
399 match self {
400 ColumnType::Index => data.sort_by_key(|t| t.index),
401 ColumnType::Data => data.sort_by_key(|t| t.data),
402 }
403
404 if descending {
405 data.reverse();
406 }
407 }
408 }
409
410 #[test]
411 fn test_sorting() {
412 let columns = [
413 SortColumn::new(ColumnType::Index),
414 SortColumn::new(ColumnType::Data),
415 ];
416 let props = {
417 let inner = DataTableProps {
418 title: Some("test".into()),
419 table_gap: TableGap::Space,
420 left_to_right: false,
421 is_basic: false,
422 show_table_scroll_position: true,
423 show_table_scroll_bar: false,
424 show_current_entry_when_unfocused: false,
425 };
426
427 SortDataTableProps {
428 inner,
429 sort_index: 0,
430 order: SortOrder::Descending,
431 }
432 };
433
434 let styling = DataTableStyling::default();
435
436 let mut table = DataTable::new_sortable(columns, props, styling);
437 let mut data = vec![
438 TestType {
439 index: 4,
440 data: 100,
441 },
442 TestType {
443 index: 1,
444 data: 200,
445 },
446 TestType {
447 index: 0,
448 data: 300,
449 },
450 TestType {
451 index: 3,
452 data: 400,
453 },
454 TestType {
455 index: 2,
456 data: 500,
457 },
458 ];
459
460 table
461 .columns
462 .get(table.sort_type.sort_index)
463 .unwrap()
464 .sort_by(&mut data, SortOrder::Ascending);
465 assert_eq!(
466 data,
467 vec![
468 TestType {
469 index: 0,
470 data: 300,
471 },
472 TestType {
473 index: 1,
474 data: 200,
475 },
476 TestType {
477 index: 2,
478 data: 500,
479 },
480 TestType {
481 index: 3,
482 data: 400,
483 },
484 TestType {
485 index: 4,
486 data: 100,
487 },
488 ]
489 );
490
491 table
492 .columns
493 .get(table.sort_type.sort_index)
494 .unwrap()
495 .sort_by(&mut data, SortOrder::Descending);
496 assert_eq!(
497 data,
498 vec![
499 TestType {
500 index: 4,
501 data: 100,
502 },
503 TestType {
504 index: 3,
505 data: 400,
506 },
507 TestType {
508 index: 2,
509 data: 500,
510 },
511 TestType {
512 index: 1,
513 data: 200,
514 },
515 TestType {
516 index: 0,
517 data: 300,
518 },
519 ]
520 );
521
522 table.set_sort_index(1);
523 table
524 .columns
525 .get(table.sort_type.sort_index)
526 .unwrap()
527 .sort_by(&mut data, SortOrder::Ascending);
528 assert_eq!(
529 data,
530 vec![
531 TestType {
532 index: 4,
533 data: 100,
534 },
535 TestType {
536 index: 1,
537 data: 200,
538 },
539 TestType {
540 index: 0,
541 data: 300,
542 },
543 TestType {
544 index: 3,
545 data: 400,
546 },
547 TestType {
548 index: 2,
549 data: 500,
550 },
551 ]
552 );
553 }
554 }