Skip to main content

iced_cube/data/
data_table.rs

1//! Records in rows and columns, with sorting, filtering, selection and
2//! pages.
3//!
4//! [`State`] owns the rows, the [`Column`]s that read them, and everything
5//! the reader changes: the sort, the search and column filters, the page,
6//! the selection and which columns are hidden. Its
7//! [`update`](State::update) is pure, so it is tested without a renderer.
8//! The view only builds the rows of the current page that are in view, and
9//! the header stays put while they scroll.
10//!
11//! Narrower than its [breakpoint](DataTable::breakpoint), the table turns
12//! into a stack of cards, one per row, with each column as a labelled line,
13//! so it never overflows a phone screen.
14//!
15//! The table resolves its keys through a [`Keymap`] of [`Action`]s while it
16//! has focus, which it takes when pressed; see [`default_keymap`].
17
18use std::cmp::Ordering;
19use std::collections::HashSet;
20use std::fmt;
21use std::hash::Hash;
22use std::ops::Range;
23use std::rc::Rc;
24
25use iced::alignment::Horizontal;
26use iced::keyboard::key::Named;
27use iced::widget::{self, Space, container, responsive, row, space as spacer, text};
28use iced::{Alignment, Background, Border, Color, Element, Length, Padding, Theme};
29
30use crate::data::ellipsis::ellipsis;
31use crate::data::interaction::{Look, RowMenu, pressable, ringed, row_menu, scope};
32use crate::data::rows::rows;
33use crate::forms::select::select;
34use crate::icon::{Glyph, themed};
35use crate::keys::{self, Chord, Keymap};
36use crate::overlay::context_menu;
37use crate::overlay::dropdown_menu::{self, checkbox_item, dropdown_menu};
38use crate::primitives::button::{self, button};
39use crate::primitives::checkbox::{CheckState, checkbox};
40use crate::primitives::icon_button::icon_button;
41use crate::primitives::input::{Shortcuts, input};
42use crate::theme::{Tokens, fade, radius, semibold, space, text_size};
43
44/// Height of the header row.
45pub const HEADER_HEIGHT: f32 = 40.0;
46/// Height of every body row.
47pub const ROW_HEIGHT: f32 = 44.0;
48/// Below this width, in logical pixels, rows become cards.
49pub const BREAKPOINT: f32 = 560.0;
50/// The page sizes offered unless the state sets its own.
51pub const PAGE_SIZES: [usize; 4] = [10, 20, 50, 100];
52/// Placeholder rows shown while loading.
53pub const SKELETON_ROWS: usize = 5;
54/// Height of one labelled line in a card.
55pub const CARD_LINE: f32 = 28.0;
56const CARD_PADDING: f32 = 12.0;
57const CARD_GAP: f32 = 8.0;
58const CHECK_WIDTH: f32 = 40.0;
59const ACTIONS_WIDTH: f32 = 44.0;
60
61/// Names a column. Sorting, filters and hiding refer to columns by it.
62pub type ColumnId = &'static str;
63
64/// A cell's value, which sorting, searching and filtering read.
65#[derive(Debug, Clone, PartialEq, Default)]
66pub enum Value {
67    #[default]
68    Empty,
69    Text(String),
70    Number(f64),
71}
72
73impl fmt::Display for Value {
74    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
75        match self {
76            Value::Empty => Ok(()),
77            Value::Text(value) => f.write_str(value),
78            Value::Number(value) if value.fract() == 0.0 && value.abs() < 1e15 => {
79                write!(f, "{}", *value as i64)
80            }
81            Value::Number(value) => write!(f, "{value}"),
82        }
83    }
84}
85
86impl From<&str> for Value {
87    fn from(value: &str) -> Self {
88        Value::Text(value.to_owned())
89    }
90}
91
92impl From<String> for Value {
93    fn from(value: String) -> Self {
94        Value::Text(value)
95    }
96}
97
98impl From<f64> for Value {
99    fn from(value: f64) -> Self {
100        Value::Number(value)
101    }
102}
103
104macro_rules! number {
105    ($($ty:ty),*) => {$(
106        impl From<$ty> for Value {
107            fn from(value: $ty) -> Self {
108                Value::Number(value as f64)
109            }
110        }
111    )*};
112}
113
114number!(f32, i32, i64, u32, u64, usize);
115
116impl<T: Into<Value>> From<Option<T>> for Value {
117    fn from(value: Option<T>) -> Self {
118        value.map_or(Value::Empty, Into::into)
119    }
120}
121
122/// Orders two values: numbers by size, text alphabetically ignoring case,
123/// and numbers before text.
124pub fn compare(a: &Value, b: &Value) -> Ordering {
125    match (a, b) {
126        (Value::Empty, Value::Empty) => Ordering::Equal,
127        (Value::Empty, _) => Ordering::Greater,
128        (_, Value::Empty) => Ordering::Less,
129        (Value::Number(a), Value::Number(b)) => a.total_cmp(b),
130        (Value::Number(_), Value::Text(_)) => Ordering::Less,
131        (Value::Text(_), Value::Number(_)) => Ordering::Greater,
132        (Value::Text(a), Value::Text(b)) => a
133            .to_lowercase()
134            .cmp(&b.to_lowercase())
135            .then_with(|| a.cmp(b)),
136    }
137}
138
139/// Which way a column is sorted.
140#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
141pub enum Direction {
142    Ascending,
143    Descending,
144}
145
146impl Direction {
147    pub const ALL: [Direction; 2] = [Direction::Ascending, Direction::Descending];
148}
149
150/// How a column's header and cells line up.
151#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
152pub enum Align {
153    #[default]
154    Start,
155    Center,
156    /// For numbers, such as amounts.
157    End,
158}
159
160impl Align {
161    pub const ALL: [Align; 3] = [Align::Start, Align::Center, Align::End];
162
163    fn horizontal(self) -> Horizontal {
164        match self {
165            Align::Start => Horizontal::Left,
166            Align::Center => Horizontal::Center,
167            Align::End => Horizontal::Right,
168        }
169    }
170}
171
172/// One column: its header, how it reads a row, and how it is shown.
173pub struct Column<Row> {
174    pub id: ColumnId,
175    pub header: String,
176    pub width: Length,
177    pub align: Align,
178    pub sortable: bool,
179    pub hideable: bool,
180    /// Offers a filter of the column's distinct values in the toolbar.
181    pub filterable: bool,
182    /// Whether the search box looks in this column.
183    pub searchable: bool,
184    value: fn(&Row) -> Value,
185    format: Option<fn(&Row) -> String>,
186}
187
188/// A sortable, searchable and hideable column that fills an equal share
189/// of the width. `value` reads the cell from a row.
190pub fn column<Row>(
191    id: ColumnId,
192    header: impl Into<String>,
193    value: fn(&Row) -> Value,
194) -> Column<Row> {
195    Column {
196        id,
197        header: header.into(),
198        width: Length::FillPortion(1),
199        align: Align::Start,
200        sortable: true,
201        hideable: true,
202        filterable: false,
203        searchable: true,
204        value,
205        format: None,
206    }
207}
208
209impl<Row> Clone for Column<Row> {
210    fn clone(&self) -> Self {
211        Self {
212            header: self.header.clone(),
213            ..*self
214        }
215    }
216}
217
218impl<Row> fmt::Debug for Column<Row> {
219    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
220        f.debug_struct("Column")
221            .field("id", &self.id)
222            .field("header", &self.header)
223            .field("width", &self.width)
224            .field("align", &self.align)
225            .field("sortable", &self.sortable)
226            .field("hideable", &self.hideable)
227            .field("filterable", &self.filterable)
228            .field("searchable", &self.searchable)
229            .finish_non_exhaustive()
230    }
231}
232
233impl<Row> Column<Row> {
234    /// A fixed width in pixels, or a share of the room with
235    /// `Length::FillPortion`.
236    pub fn width(mut self, width: impl Into<Length>) -> Self {
237        self.width = width.into();
238        self
239    }
240
241    pub fn align(mut self, align: Align) -> Self {
242        self.align = align;
243        self
244    }
245
246    pub fn sortable(mut self, sortable: bool) -> Self {
247        self.sortable = sortable;
248        self
249    }
250
251    pub fn hideable(mut self, hideable: bool) -> Self {
252        self.hideable = hideable;
253        self
254    }
255
256    pub fn filterable(mut self, filterable: bool) -> Self {
257        self.filterable = filterable;
258        self
259    }
260
261    pub fn searchable(mut self, searchable: bool) -> Self {
262        self.searchable = searchable;
263        self
264    }
265
266    /// The text shown, searched and filtered on, in place of the value's
267    /// own, such as an amount with its currency. Sorting still uses the
268    /// value.
269    pub fn format(mut self, format: fn(&Row) -> String) -> Self {
270        self.format = Some(format);
271        self
272    }
273
274    /// The cell's value in `row`.
275    pub fn value(&self, row: &Row) -> Value {
276        (self.value)(row)
277    }
278
279    /// The cell's text in `row`.
280    pub fn text(&self, row: &Row) -> String {
281        match self.format {
282            Some(format) => format(row),
283            None => (self.value)(row).to_string(),
284        }
285    }
286}
287
288/// Everything that changes a table.
289#[derive(Debug, Clone, PartialEq)]
290pub enum Event<Key> {
291    /// A header was pressed: unsorted, then ascending, then descending.
292    Sort(ColumnId),
293    /// Sorts by a column in a direction, or restores the row order.
294    SortBy(Option<(ColumnId, Direction)>),
295    Search(String),
296    /// Keeps only rows whose cell in the column shows this text, or clears
297    /// the column's filter.
298    Filter(ColumnId, Option<String>),
299    /// Clears the search and every filter.
300    ClearFilters,
301    PageSize(usize),
302    /// Goes to a page, counting from zero.
303    Page(usize),
304    NextPage,
305    PreviousPage,
306    /// A row's checkbox changed.
307    Select(Key, bool),
308    /// The header checkbox changed: selects or clears the rows on the page.
309    SelectPage(bool),
310    ClearSelection,
311    /// The pointer pressed a row.
312    Press(Key),
313    /// A row was double clicked.
314    Activate(Key),
315    /// Highlights the next row, moving to the next page after the last.
316    Next,
317    /// Highlights the previous row, moving to the previous page before the
318    /// first.
319    Previous,
320    First,
321    Last,
322    ToggleHighlighted,
323    ActivateHighlighted,
324    /// Navigation and choices in the Columns menu.
325    Columns(dropdown_menu::Event<ColumnId>),
326    /// The table gained or lost focus. The widget sends this itself.
327    Focus(bool),
328}
329
330/// What the app may need to act on after an [`Event`].
331#[derive(Debug, Clone, PartialEq)]
332pub enum Output<Key> {
333    /// A row was activated with Enter or a double click.
334    Activated(Key),
335    /// The selection changed. Holds every selected key, in row order.
336    Selected(Vec<Key>),
337}
338
339/// The rows, the columns and how the reader is looking at them.
340#[derive(Debug, Clone)]
341pub struct State<Row, Key> {
342    rows: Vec<Row>,
343    columns: Vec<Column<Row>>,
344    key: fn(&Row) -> Key,
345    hidden: HashSet<ColumnId>,
346    columns_menu: dropdown_menu::State<ColumnId>,
347    sort: Option<(ColumnId, Direction)>,
348    search: String,
349    filters: Vec<(ColumnId, String)>,
350    options: Vec<(ColumnId, Vec<String>)>,
351    /// Indices into `rows` that pass the filters, in sorted order.
352    order: Vec<usize>,
353    page: usize,
354    page_size: usize,
355    page_sizes: Vec<usize>,
356    selectable: bool,
357    selected: HashSet<Key>,
358    highlighted: Option<Key>,
359    focused: bool,
360}
361
362impl<Row, Key: Clone + Eq + Hash> State<Row, Key> {
363    /// A table over `rows`, showing `columns` in order. `key` gives each
364    /// row an identity that survives sorting and new rows, such as an id.
365    pub fn new(
366        columns: impl IntoIterator<Item = Column<Row>>,
367        rows: impl IntoIterator<Item = Row>,
368        key: fn(&Row) -> Key,
369    ) -> Self {
370        let mut state = Self {
371            rows: rows.into_iter().collect(),
372            columns: columns.into_iter().collect(),
373            key,
374            hidden: HashSet::new(),
375            columns_menu: dropdown_menu::State::new([]),
376            sort: None,
377            search: String::new(),
378            filters: Vec::new(),
379            options: Vec::new(),
380            order: Vec::new(),
381            page: 0,
382            page_size: PAGE_SIZES[0],
383            page_sizes: PAGE_SIZES.to_vec(),
384            selectable: false,
385            selected: HashSet::new(),
386            highlighted: None,
387            focused: false,
388        };
389        state.rebuild_menu();
390        state.refresh();
391        state
392    }
393
394    /// Adds a checkbox to every row and a select-all box to the header.
395    pub fn with_selection(mut self, selectable: bool) -> Self {
396        self.selectable = selectable;
397        self
398    }
399
400    /// The sizes offered in the footer. The first is used to start with.
401    pub fn with_page_sizes(mut self, sizes: impl IntoIterator<Item = usize>) -> Self {
402        let sizes: Vec<usize> = sizes.into_iter().filter(|&size| size > 0).collect();
403        if let Some(&first) = sizes.first() {
404            self.page_size = first;
405            self.page_sizes = sizes;
406        }
407        self.refresh();
408        self
409    }
410
411    pub fn with_sort(mut self, column: ColumnId, direction: Direction) -> Self {
412        let _ = self.update(Event::SortBy(Some((column, direction))));
413        self
414    }
415
416    /// Starts with these columns hidden.
417    pub fn with_hidden(mut self, columns: impl IntoIterator<Item = ColumnId>) -> Self {
418        self.hidden = columns.into_iter().collect();
419        self.rebuild_menu();
420        self.refresh();
421        self
422    }
423
424    pub fn rows(&self) -> &[Row] {
425        &self.rows
426    }
427
428    pub fn columns(&self) -> &[Column<Row>] {
429        &self.columns
430    }
431
432    /// The columns on screen, in order.
433    pub fn visible_columns(&self) -> Vec<&Column<Row>> {
434        self.columns
435            .iter()
436            .filter(|column| !self.hidden.contains(column.id))
437            .collect()
438    }
439
440    pub fn column(&self, id: ColumnId) -> Option<&Column<Row>> {
441        self.columns.iter().find(|column| column.id == id)
442    }
443
444    pub fn is_hidden(&self, id: ColumnId) -> bool {
445        self.hidden.contains(id)
446    }
447
448    /// The Columns menu, with a check for each hideable column.
449    pub fn columns_menu(&self) -> &dropdown_menu::State<ColumnId> {
450        &self.columns_menu
451    }
452
453    pub fn key(&self, row: &Row) -> Key {
454        (self.key)(row)
455    }
456
457    pub fn row(&self, key: &Key) -> Option<&Row> {
458        self.rows.iter().find(|row| (self.key)(row) == *key)
459    }
460
461    /// Replaces every row. The sort, filters and selection of rows that
462    /// remain are kept.
463    pub fn set_rows(&mut self, rows: impl IntoIterator<Item = Row>) {
464        self.rows = rows.into_iter().collect();
465        self.refresh();
466    }
467
468    pub fn push(&mut self, row: Row) {
469        self.rows.push(row);
470        self.refresh();
471    }
472
473    /// Changes the row with this key, if there is one.
474    pub fn update_row(&mut self, key: &Key, change: impl FnOnce(&mut Row)) {
475        let Some(row) = self.rows.iter_mut().find(|row| (self.key)(row) == *key) else {
476            return;
477        };
478        change(row);
479        self.refresh();
480    }
481
482    /// Keeps only the rows for which `keep` returns true.
483    pub fn retain(&mut self, keep: impl FnMut(&Row) -> bool) {
484        self.rows.retain(keep);
485        self.refresh();
486    }
487
488    pub fn sort(&self) -> Option<(ColumnId, Direction)> {
489        self.sort
490    }
491
492    pub fn search(&self) -> &str {
493        &self.search
494    }
495
496    /// The text a column is filtered to, if any.
497    pub fn filter(&self, column: ColumnId) -> Option<&str> {
498        self.filters
499            .iter()
500            .find(|(id, _)| *id == column)
501            .map(|(_, value)| value.as_str())
502    }
503
504    /// Whether the search or any filter hides rows.
505    pub fn is_filtered(&self) -> bool {
506        !self.search.trim().is_empty() || !self.filters.is_empty()
507    }
508
509    /// The distinct texts of a filterable column, to choose from.
510    pub fn options(&self, column: ColumnId) -> &[String] {
511        self.options
512            .iter()
513            .find(|(id, _)| *id == column)
514            .map_or(&[], |(_, options)| options.as_slice())
515    }
516
517    /// How many rows pass the search and filters.
518    pub fn filtered_len(&self) -> usize {
519        self.order.len()
520    }
521
522    pub fn len(&self) -> usize {
523        self.rows.len()
524    }
525
526    pub fn is_empty(&self) -> bool {
527        self.rows.is_empty()
528    }
529
530    /// The current page, counting from zero.
531    pub fn page(&self) -> usize {
532        self.page
533    }
534
535    pub fn page_size(&self) -> usize {
536        self.page_size
537    }
538
539    pub fn page_sizes(&self) -> &[usize] {
540        &self.page_sizes
541    }
542
543    /// How many pages the filtered rows fill; at least one.
544    pub fn page_count(&self) -> usize {
545        self.order.len().div_ceil(self.page_size).max(1)
546    }
547
548    /// Positions of the current page's rows among the filtered rows.
549    pub fn page_range(&self) -> Range<usize> {
550        let start = (self.page * self.page_size).min(self.order.len());
551        start..(start + self.page_size).min(self.order.len())
552    }
553
554    /// The rows on the current page, in order.
555    pub fn page_rows(&self) -> Vec<&Row> {
556        self.page_indices()
557            .into_iter()
558            .filter_map(|index| self.rows.get(index))
559            .collect()
560    }
561
562    /// The keys of the rows on the current page, in order.
563    pub fn page_keys(&self) -> Vec<Key> {
564        self.page_rows().into_iter().map(self.key).collect()
565    }
566
567    /// "Showing 1-10 of 243", for the footer.
568    pub fn showing(&self) -> String {
569        let range = self.page_range();
570        if range.is_empty() {
571            return format!("Showing 0 of {}", self.order.len());
572        }
573        format!(
574            "Showing {}-{} of {}",
575            range.start + 1,
576            range.end,
577            self.order.len()
578        )
579    }
580
581    pub fn is_selectable(&self) -> bool {
582        self.selectable
583    }
584
585    pub fn is_selected(&self, key: &Key) -> bool {
586        self.selected.contains(key)
587    }
588
589    /// Every selected key, on any page, in row order.
590    pub fn selected(&self) -> Vec<Key> {
591        self.rows
592            .iter()
593            .map(self.key)
594            .filter(|key| self.selected.contains(key))
595            .collect()
596    }
597
598    /// The header checkbox: checked when every row on the page is
599    /// selected, indeterminate when some are.
600    pub fn page_check_state(&self) -> CheckState {
601        let keys = self.page_keys();
602        let count = keys
603            .iter()
604            .filter(|key| self.selected.contains(key))
605            .count();
606        match count {
607            0 => CheckState::Unchecked,
608            n if n == keys.len() => CheckState::Checked,
609            _ => CheckState::Indeterminate,
610        }
611    }
612
613    /// The row the keyboard acts on.
614    pub fn highlighted(&self) -> Option<&Key> {
615        self.highlighted.as_ref()
616    }
617
618    pub fn is_focused(&self) -> bool {
619        self.focused
620    }
621
622    /// Applies an event and returns what the app may need to act on.
623    pub fn update(&mut self, event: Event<Key>) -> Option<Output<Key>> {
624        match event {
625            Event::Sort(id) => {
626                let next = match self.sort {
627                    Some((sorted, Direction::Ascending)) if sorted == id => {
628                        Some((id, Direction::Descending))
629                    }
630                    Some((sorted, Direction::Descending)) if sorted == id => None,
631                    _ => Some((id, Direction::Ascending)),
632                };
633                self.sort_by(next);
634            }
635            Event::SortBy(sort) => self.sort_by(sort),
636            Event::Search(search) => {
637                self.search = search;
638                self.page = 0;
639                self.refresh();
640            }
641            Event::Filter(id, value) => {
642                self.filters.retain(|(column, _)| *column != id);
643                if let Some(value) = value.filter(|_| self.column(id).is_some()) {
644                    self.filters.push((id, value));
645                }
646                self.page = 0;
647                self.refresh();
648            }
649            Event::ClearFilters => {
650                self.search.clear();
651                self.filters.clear();
652                self.page = 0;
653                self.refresh();
654            }
655            Event::PageSize(size) => {
656                let first = self.page_range().start;
657                self.page_size = size.max(1);
658                self.page = first / self.page_size;
659                self.refresh();
660            }
661            Event::Page(page) => self.go_to(page),
662            Event::NextPage => self.go_to(self.page + 1),
663            Event::PreviousPage => self.go_to(self.page.saturating_sub(1)),
664            Event::Select(key, selected) => return self.select([key], selected),
665            Event::SelectPage(selected) => return self.select(self.page_keys(), selected),
666            Event::ClearSelection => {
667                let changed = !self.selected.is_empty();
668                self.selected.clear();
669                return changed.then(|| Output::Selected(Vec::new()));
670            }
671            Event::Press(key) => self.highlight(key),
672            Event::Activate(key) => {
673                if !self.page_keys().contains(&key) {
674                    return None;
675                }
676                self.highlighted = Some(key.clone());
677                return Some(Output::Activated(key));
678            }
679            Event::Next => self.step(true),
680            Event::Previous => self.step(false),
681            Event::First => self.highlighted = self.page_keys().first().cloned(),
682            Event::Last => self.highlighted = self.page_keys().last().cloned(),
683            Event::ToggleHighlighted => {
684                let key = self.highlighted.clone()?;
685                let selected = !self.selected.contains(&key);
686                return self.select([key], selected);
687            }
688            Event::ActivateHighlighted => return self.highlighted.clone().map(Output::Activated),
689            Event::Columns(event) => {
690                if let Some(dropdown_menu::Output::Toggled(id, shown)) =
691                    self.columns_menu.update(event)
692                {
693                    self.show_column(id, shown);
694                }
695            }
696            Event::Focus(focused) => {
697                self.focused = focused;
698                // Focus lands on the first selected row of the page, or its
699                // first row, so the keyboard has somewhere to start.
700                if focused && self.highlighted.is_none() {
701                    let keys = self.page_keys();
702                    self.highlighted = keys
703                        .iter()
704                        .find(|key| self.selected.contains(*key))
705                        .or(keys.first())
706                        .cloned();
707                }
708            }
709        }
710        None
711    }
712
713    /// Turns a key press into an event through `keymap`.
714    pub fn key_event(&self, keymap: &Keymap<Action>, key: &keys::Event) -> Option<Event<Key>> {
715        keymap
716            .resolve_event(key)
717            .and_then(|action| action.event(self))
718    }
719
720    fn page_indices(&self) -> Vec<usize> {
721        self.order
722            .get(self.page_range())
723            .map(<[usize]>::to_vec)
724            .unwrap_or_default()
725    }
726
727    fn sort_by(&mut self, sort: Option<(ColumnId, Direction)>) {
728        let valid = sort.filter(|(id, _)| self.column(id).is_some_and(|column| column.sortable));
729        if sort.is_some() && valid.is_none() {
730            return;
731        }
732        self.sort = valid;
733        self.page = 0;
734        self.refresh();
735    }
736
737    fn go_to(&mut self, page: usize) {
738        self.page = page.min(self.page_count() - 1);
739        let keys = self.page_keys();
740        if self
741            .highlighted
742            .as_ref()
743            .is_some_and(|key| !keys.contains(key))
744        {
745            self.highlighted = keys.first().cloned();
746        }
747    }
748
749    fn highlight(&mut self, key: Key) {
750        if self.page_keys().contains(&key) {
751            self.highlighted = Some(key);
752        }
753    }
754
755    fn step(&mut self, forward: bool) {
756        let keys = self.page_keys();
757        let current = self
758            .highlighted
759            .as_ref()
760            .and_then(|key| keys.iter().position(|page| page == key));
761        let target = match (current, forward) {
762            (None, true) => keys.first().cloned(),
763            (None, false) => keys.last().cloned(),
764            (Some(index), true) if index + 1 < keys.len() => keys.get(index + 1).cloned(),
765            (Some(index), false) if index > 0 => keys.get(index - 1).cloned(),
766            (Some(_), true) if self.page + 1 < self.page_count() => {
767                self.page += 1;
768                self.page_keys().first().cloned()
769            }
770            (Some(_), false) if self.page > 0 => {
771                self.page -= 1;
772                self.page_keys().last().cloned()
773            }
774            (Some(_), _) => self.highlighted.clone(),
775        };
776        if target.is_some() {
777            self.highlighted = target;
778        }
779    }
780
781    fn select(
782        &mut self,
783        keys: impl IntoIterator<Item = Key>,
784        selected: bool,
785    ) -> Option<Output<Key>> {
786        if !self.selectable {
787            return None;
788        }
789        let mut changed = false;
790        for key in keys {
791            if self.row(&key).is_none() {
792                continue;
793            }
794            changed |= if selected {
795                self.selected.insert(key)
796            } else {
797                self.selected.remove(&key)
798            };
799        }
800        changed.then(|| Output::Selected(self.selected()))
801    }
802
803    /// Shows or hides a column. The last visible column cannot be hidden.
804    fn show_column(&mut self, id: ColumnId, shown: bool) {
805        if shown {
806            let _ = self.hidden.remove(id);
807        } else if self.visible_columns().len() > 1 {
808            let _ = self.hidden.insert(id);
809        } else {
810            self.columns_menu.set_checked(id, true);
811        }
812        self.refresh();
813    }
814
815    fn rebuild_menu(&mut self) {
816        let items = self
817            .columns
818            .iter()
819            .filter(|column| column.hideable)
820            .map(|column| {
821                checkbox_item(
822                    column.id,
823                    column.header.clone(),
824                    !self.hidden.contains(column.id),
825                )
826            });
827        self.columns_menu = dropdown_menu::State::new(items);
828    }
829
830    /// Recomputes the filtered, sorted order and everything that depends on
831    /// the rows.
832    fn refresh(&mut self) {
833        self.options = self
834            .columns
835            .iter()
836            .filter(|column| column.filterable)
837            .map(|column| {
838                let mut values: Vec<(Value, String)> = self
839                    .rows
840                    .iter()
841                    .map(|row| (column.value(row), column.text(row)))
842                    .collect();
843                values.sort_by(|a, b| compare(&a.0, &b.0));
844                let mut texts: Vec<String> = Vec::new();
845                for (_, text) in values {
846                    if !texts.contains(&text) {
847                        texts.push(text);
848                    }
849                }
850                (column.id, texts)
851            })
852            .collect();
853
854        let query = self.search.trim().to_lowercase();
855        let searched: Vec<&Column<Row>> = self
856            .columns
857            .iter()
858            .filter(|column| column.searchable && !self.hidden.contains(column.id))
859            .collect();
860        let filters: Vec<(&Column<Row>, &str)> = self
861            .filters
862            .iter()
863            .filter_map(|(id, value)| {
864                self.columns
865                    .iter()
866                    .find(|column| column.id == *id)
867                    .map(|column| (column, value.as_str()))
868            })
869            .collect();
870        let mut order: Vec<usize> = self
871            .rows
872            .iter()
873            .enumerate()
874            .filter(|(_, row)| {
875                filters
876                    .iter()
877                    .all(|(column, value)| column.text(row) == *value)
878            })
879            .filter(|(_, row)| {
880                query.is_empty()
881                    || searched
882                        .iter()
883                        .any(|column| column.text(row).to_lowercase().contains(&query))
884            })
885            .map(|(index, _)| index)
886            .collect();
887
888        if let Some((id, direction)) = self.sort
889            && let Some(column) = self.column(id)
890        {
891            let keys: Vec<Value> = self.rows.iter().map(|row| column.value(row)).collect();
892            order.sort_by(|&a, &b| {
893                let (a, b) = (&keys[a], &keys[b]);
894                match (a, b) {
895                    (Value::Empty, Value::Empty) => Ordering::Equal,
896                    (Value::Empty, _) => Ordering::Greater,
897                    (_, Value::Empty) => Ordering::Less,
898                    _ if direction == Direction::Descending => compare(b, a),
899                    _ => compare(a, b),
900                }
901            });
902        }
903        self.order = order;
904
905        let keys: HashSet<Key> = self.rows.iter().map(self.key).collect();
906        self.selected.retain(|key| keys.contains(key));
907        self.page = self.page.min(self.page_count() - 1);
908        let page = self.page_keys();
909        if self
910            .highlighted
911            .as_ref()
912            .is_some_and(|key| !page.contains(key))
913        {
914            self.highlighted = None;
915        }
916    }
917}
918
919/// What a data table keyboard shortcut does.
920#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
921pub enum Action {
922    Next,
923    Previous,
924    First,
925    Last,
926    NextPage,
927    PreviousPage,
928    Select,
929    Activate,
930    SelectAll,
931    ClearSelection,
932}
933
934impl Action {
935    /// The [`Event`] this action sends to `state`, or `None` when it does
936    /// nothing, so the key is left for others.
937    pub fn event<Row, Key: Clone + Eq + Hash>(self, state: &State<Row, Key>) -> Option<Event<Key>> {
938        let rows = !state.page_range().is_empty();
939        let highlighted = state.highlighted().is_some();
940        let selectable = state.is_selectable();
941        match self {
942            Action::Next => rows.then_some(Event::Next),
943            Action::Previous => rows.then_some(Event::Previous),
944            Action::First => rows.then_some(Event::First),
945            Action::Last => rows.then_some(Event::Last),
946            Action::NextPage => (state.page() + 1 < state.page_count()).then_some(Event::NextPage),
947            Action::PreviousPage => (state.page() > 0).then_some(Event::PreviousPage),
948            Action::Select => (selectable && highlighted).then_some(Event::ToggleHighlighted),
949            Action::Activate => highlighted.then_some(Event::ActivateHighlighted),
950            Action::SelectAll => (selectable && rows).then_some(Event::SelectPage(true)),
951            Action::ClearSelection => {
952                (selectable && !state.selected.is_empty()).then_some(Event::ClearSelection)
953            }
954        }
955    }
956}
957
958impl keys::Action for Action {
959    const ALL: &'static [Self] = &[
960        Action::Next,
961        Action::Previous,
962        Action::First,
963        Action::Last,
964        Action::NextPage,
965        Action::PreviousPage,
966        Action::Select,
967        Action::Activate,
968        Action::SelectAll,
969        Action::ClearSelection,
970    ];
971
972    fn defaults() -> Keymap<Self> {
973        default_keymap()
974    }
975
976    fn name(self) -> &'static str {
977        match self {
978            Action::Next => "Next",
979            Action::Previous => "Previous",
980            Action::First => "First",
981            Action::Last => "Last",
982            Action::NextPage => "NextPage",
983            Action::PreviousPage => "PreviousPage",
984            Action::Select => "Select",
985            Action::Activate => "Activate",
986            Action::SelectAll => "SelectAll",
987            Action::ClearSelection => "ClearSelection",
988        }
989    }
990
991    fn description(self) -> &'static str {
992        match self {
993            Action::Next => "Highlights the next row, going on to the next page after the last.",
994            Action::Previous => "Highlights the previous row, going back a page before the first.",
995            Action::First => "Highlights the first row on the page.",
996            Action::Last => "Highlights the last row on the page.",
997            Action::NextPage => "Shows the next page.",
998            Action::PreviousPage => "Shows the previous page.",
999            Action::Select => "Selects or clears the highlighted row.",
1000            Action::Activate => "Activates the highlighted row.",
1001            Action::SelectAll => "Selects every row on the page.",
1002            Action::ClearSelection => "Clears the selection.",
1003        }
1004    }
1005}
1006
1007/// The default data table shortcuts:
1008///
1009/// | Keys | Action |
1010/// | --- | --- |
1011/// | `ArrowDown` | [`Action::Next`] |
1012/// | `ArrowUp` | [`Action::Previous`] |
1013/// | `Home` | [`Action::First`] |
1014/// | `End` | [`Action::Last`] |
1015/// | `PageDown` | [`Action::NextPage`] |
1016/// | `PageUp` | [`Action::PreviousPage`] |
1017/// | `Space` | [`Action::Select`] |
1018/// | `Enter` | [`Action::Activate`] |
1019/// | `Mod+A` (Ctrl, or Cmd on macOS) | [`Action::SelectAll`] |
1020/// | `Escape` | [`Action::ClearSelection`] |
1021///
1022/// The table resolves these itself, only while it has focus, so they never
1023/// clash with other components. Pass a changed keymap with
1024/// [`DataTable::keymap`].
1025pub fn default_keymap() -> Keymap<Action> {
1026    Keymap::new()
1027        .bind(Chord::named(Named::ArrowDown), Action::Next)
1028        .bind(Chord::named(Named::ArrowUp), Action::Previous)
1029        .bind(Chord::named(Named::Home), Action::First)
1030        .bind(Chord::named(Named::End), Action::Last)
1031        .bind(Chord::named(Named::PageDown), Action::NextPage)
1032        .bind(Chord::named(Named::PageUp), Action::PreviousPage)
1033        .bind(Chord::named(Named::Space), Action::Select)
1034        .bind(Chord::named(Named::Enter), Action::Activate)
1035        .bind(Chord::character('a').command(), Action::SelectAll)
1036        .bind(Chord::named(Named::Escape), Action::ClearSelection)
1037}
1038
1039/// How a row is shown.
1040#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
1041pub struct Status {
1042    pub selected: bool,
1043    pub hovered: bool,
1044    /// Carries the keyboard highlight while the table has focus.
1045    pub highlighted: bool,
1046}
1047
1048/// The colours of a row.
1049#[derive(Debug, Clone, Copy, PartialEq)]
1050pub struct RowStyle {
1051    pub background: Option<Color>,
1052    /// The ring around the row carrying the keyboard highlight.
1053    pub ring: Option<Color>,
1054    /// The line between rows.
1055    pub divider: Color,
1056}
1057
1058/// Resolves a row's colours: muted when selected, a lighter tint under the
1059/// pointer.
1060pub fn row_style(tokens: &Tokens, status: Status) -> RowStyle {
1061    let background = if status.selected {
1062        Some(tokens.muted)
1063    } else if status.hovered {
1064        Some(fade(tokens.muted, 0.5))
1065    } else {
1066        None
1067    };
1068    RowStyle {
1069        background,
1070        ring: status.highlighted.then_some(tokens.ring),
1071        divider: tokens.border,
1072    }
1073}
1074
1075/// The frame around the table: a subtle border with rounded corners.
1076pub fn frame_style(tokens: &Tokens) -> container::Style {
1077    container::Style {
1078        border: Border {
1079            color: tokens.border,
1080            width: 1.0,
1081            radius: radius::MD.into(),
1082        },
1083        ..container::Style::default()
1084    }
1085}
1086
1087/// A placeholder bar in a loading row.
1088pub fn skeleton_style(tokens: &Tokens) -> container::Style {
1089    container::Style {
1090        background: Some(Background::Color(tokens.muted)),
1091        border: Border {
1092            radius: radius::SM.into(),
1093            ..Border::default()
1094        },
1095        ..container::Style::default()
1096    }
1097}
1098
1099/// The sort indicator for a column: arrows up and down while unsorted, or
1100/// the direction.
1101pub fn sort_glyph(direction: Option<Direction>) -> Glyph {
1102    match direction {
1103        None => crate::lucide!(ArrowUpDown),
1104        Some(Direction::Ascending) => crate::lucide!(ArrowUp),
1105        Some(Direction::Descending) => crate::lucide!(ArrowDown),
1106    }
1107}
1108
1109type OnEvent<'a, Key, Message> = dyn Fn(Event<Key>) -> Message + 'a;
1110type Cell<'a, Row, Message> = Box<dyn Fn(&'a Row) -> Element<'a, Message> + 'a>;
1111type BuildMenu<'a, Key, Message> =
1112    dyn FnOnce(Keymap<context_menu::Action>) -> RowMenu<'a, Key, Message> + 'a;
1113
1114/// A data table builder. Convert it into an [`Element`] to render.
1115pub struct DataTable<'a, Row, Key, Message> {
1116    state: &'a State<Row, Key>,
1117    cells: Vec<(ColumnId, Cell<'a, Row, Message>)>,
1118    toolbar: bool,
1119    placeholder: String,
1120    loading: bool,
1121    empty: String,
1122    height: Length,
1123    row_height: f32,
1124    breakpoint: f32,
1125    keymap: Keymap<Action>,
1126    shortcuts: Shortcuts,
1127    menu: Option<Box<BuildMenu<'a, Key, Message>>>,
1128    menu_keymap: Keymap<context_menu::Action>,
1129    row_actions: bool,
1130    on_event: Option<Box<OnEvent<'a, Key, Message>>>,
1131}
1132
1133/// Renders `state`. Without [`on_event`](DataTable::on_event) every control
1134/// renders disabled.
1135pub fn data_table<Row, Key, Message>(state: &State<Row, Key>) -> DataTable<'_, Row, Key, Message> {
1136    DataTable {
1137        state,
1138        cells: Vec::new(),
1139        toolbar: true,
1140        placeholder: "Search...".to_owned(),
1141        loading: false,
1142        empty: "No results.".to_owned(),
1143        height: Length::Shrink,
1144        row_height: ROW_HEIGHT,
1145        breakpoint: BREAKPOINT,
1146        keymap: default_keymap(),
1147        shortcuts: Shortcuts::all(),
1148        menu: None,
1149        menu_keymap: context_menu::default_keymap(),
1150        row_actions: false,
1151        on_event: None,
1152    }
1153}
1154
1155impl<Row: fmt::Debug, Key: fmt::Debug, Message> fmt::Debug for DataTable<'_, Row, Key, Message> {
1156    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1157        f.debug_struct("DataTable")
1158            .field("state", self.state)
1159            .field("toolbar", &self.toolbar)
1160            .field("loading", &self.loading)
1161            .field("height", &self.height)
1162            .field("breakpoint", &self.breakpoint)
1163            .field("keymap", &self.keymap)
1164            .finish_non_exhaustive()
1165    }
1166}
1167
1168impl<'a, Row, Key, Message> DataTable<'a, Row, Key, Message> {
1169    /// Draws the cells of a column with `render`, such as a badge or a
1170    /// progress bar, in place of its text. Keep it within a row's height.
1171    pub fn cell(
1172        mut self,
1173        column: ColumnId,
1174        render: impl Fn(&'a Row) -> Element<'a, Message> + 'a,
1175    ) -> Self {
1176        self.cells.retain(|(id, _)| *id != column);
1177        self.cells.push((column, Box::new(render)));
1178        self
1179    }
1180
1181    /// Shows the search box, column filters and Columns menu above the
1182    /// table. On by default.
1183    pub fn toolbar(mut self, toolbar: bool) -> Self {
1184        self.toolbar = toolbar;
1185        self
1186    }
1187
1188    /// The search box placeholder.
1189    pub fn placeholder(mut self, placeholder: impl Into<String>) -> Self {
1190        self.placeholder = placeholder.into();
1191        self
1192    }
1193
1194    /// Shows placeholder rows in place of the data.
1195    pub fn loading(mut self, loading: bool) -> Self {
1196        self.loading = loading;
1197        self
1198    }
1199
1200    /// The message shown when no rows pass the search and filters.
1201    pub fn empty(mut self, message: impl Into<String>) -> Self {
1202        self.empty = message.into();
1203        self
1204    }
1205
1206    /// A fixed or filling height scrolls the rows under the header.
1207    /// Defaults to shrinking to fit the page.
1208    pub fn height(mut self, height: impl Into<Length>) -> Self {
1209        self.height = height.into();
1210        self
1211    }
1212
1213    /// The height of each row, such as 32 for a compact table. Defaults to
1214    /// [`ROW_HEIGHT`]. Custom cells must fit inside it.
1215    pub fn row_height(mut self, height: f32) -> Self {
1216        self.row_height = height;
1217        self
1218    }
1219
1220    /// The width below which rows become cards. Defaults to [`BREAKPOINT`].
1221    pub fn breakpoint(mut self, width: f32) -> Self {
1222        self.breakpoint = width;
1223        self
1224    }
1225
1226    /// Replaces the [`default_keymap`] the focused table resolves keys with.
1227    pub fn keymap(mut self, keymap: Keymap<Action>) -> Self {
1228        self.keymap = keymap;
1229        self
1230    }
1231
1232    /// Sets which editing [`Shortcut`](crate::primitives::input::Shortcut)s
1233    /// the search field handles. All of them by default.
1234    pub fn shortcuts(mut self, shortcuts: Shortcuts) -> Self {
1235        self.shortcuts = shortcuts;
1236        self
1237    }
1238
1239    pub fn on_event(mut self, on_event: impl Fn(Event<Key>) -> Message + 'a) -> Self {
1240        self.on_event = Some(Box::new(on_event));
1241        self
1242    }
1243
1244    /// Gives every row the context menu of `menu`, keyed by row key. It
1245    /// opens on a right-click or a long press, and on the highlighted row
1246    /// with its opening chord while the table has focus.
1247    pub fn context_menu<MenuId>(
1248        mut self,
1249        menu: &'a context_menu::State<MenuId, Key>,
1250        on_event: impl Fn(context_menu::Event<MenuId, Key>) -> Message + 'a,
1251    ) -> Self
1252    where
1253        MenuId: Copy + PartialEq + 'a,
1254        Key: Clone + PartialEq + 'a,
1255        Message: Clone + 'a,
1256    {
1257        let on_event: Rc<dyn Fn(context_menu::Event<MenuId, Key>) -> Message + 'a> =
1258            Rc::new(on_event);
1259        self.menu = Some(Box::new(move |keymap| row_menu(menu, keymap, on_event)));
1260        self
1261    }
1262
1263    /// Replaces the context menu's default keymap.
1264    pub fn context_menu_keymap(mut self, keymap: Keymap<context_menu::Action>) -> Self {
1265        self.menu_keymap = keymap;
1266        self
1267    }
1268
1269    /// Adds a button at the end of each row that opens its context menu,
1270    /// for touch screens and anyone who does not right-click.
1271    pub fn row_actions(mut self, row_actions: bool) -> Self {
1272        self.row_actions = row_actions;
1273        self
1274    }
1275
1276    pub fn is_enabled(&self) -> bool {
1277        self.on_event.is_some()
1278    }
1279}
1280
1281impl<'a, Row, Key, Message> From<DataTable<'a, Row, Key, Message>> for Element<'a, Message>
1282where
1283    Row: 'a,
1284    Key: Clone + Eq + Hash + 'a,
1285    Message: Clone + 'a,
1286{
1287    fn from(table: DataTable<'a, Row, Key, Message>) -> Self {
1288        let DataTable {
1289            state,
1290            cells,
1291            toolbar,
1292            placeholder,
1293            loading,
1294            empty,
1295            height,
1296            row_height,
1297            breakpoint,
1298            keymap,
1299            shortcuts,
1300            menu,
1301            menu_keymap,
1302            row_actions,
1303            on_event,
1304        } = table;
1305        let on_event: Option<Rc<OnEvent<'a, Key, Message>>> = on_event.map(Rc::from);
1306        let menu = menu
1307            .filter(|_| on_event.is_some())
1308            .map(|build| build(menu_keymap));
1309        let view = Rc::new(View {
1310            state,
1311            cells,
1312            toolbar,
1313            placeholder,
1314            loading,
1315            empty,
1316            height,
1317            row_height: row_height.max(1.0),
1318            keymap,
1319            shortcuts,
1320            row_actions: row_actions && menu.is_some(),
1321            menu,
1322            on_event,
1323        });
1324        responsive(move |size| view.body(size.width < breakpoint))
1325            .height(Length::Shrink)
1326            .into()
1327    }
1328}
1329
1330/// Everything the table's parts are built from, shared by the layouts.
1331struct View<'a, Row, Key, Message> {
1332    state: &'a State<Row, Key>,
1333    cells: Vec<(ColumnId, Cell<'a, Row, Message>)>,
1334    toolbar: bool,
1335    placeholder: String,
1336    loading: bool,
1337    empty: String,
1338    height: Length,
1339    row_height: f32,
1340    keymap: Keymap<Action>,
1341    shortcuts: Shortcuts,
1342    menu: Option<RowMenu<'a, Key, Message>>,
1343    row_actions: bool,
1344    on_event: Option<Rc<OnEvent<'a, Key, Message>>>,
1345}
1346
1347fn muted(theme: &Theme) -> Color {
1348    Tokens::of(theme).muted_foreground
1349}
1350
1351fn small<'a>(label: impl text::IntoFragment<'a>) -> text::Text<'a> {
1352    text(label)
1353        .size(text_size::SM)
1354        .wrapping(text::Wrapping::None)
1355        .style(|theme| text::Style {
1356            color: Some(muted(theme)),
1357        })
1358}
1359
1360impl<'a, Row, Key, Message> View<'a, Row, Key, Message>
1361where
1362    Row: 'a,
1363    Key: Clone + Eq + Hash + 'a,
1364    Message: Clone + 'a,
1365{
1366    fn send(&self, event: Event<Key>) -> Option<Message> {
1367        self.on_event.as_ref().map(|on_event| on_event(event))
1368    }
1369
1370    fn body(self: &Rc<Self>, narrow: bool) -> Element<'a, Message> {
1371        let mut parts = widget::column![].spacing(space::MD);
1372        if self.toolbar {
1373            parts = parts.push(self.toolbar(narrow));
1374        }
1375        let grid = if narrow { self.cards() } else { self.table() };
1376        parts
1377            .push(self.scoped(grid))
1378            .push(self.footer(narrow))
1379            .into()
1380    }
1381
1382    /// Lets the grid take focus and resolve its keys while it has it.
1383    fn scoped(self: &Rc<Self>, grid: Element<'a, Message>) -> Element<'a, Message> {
1384        let Some(on_event) = self.on_event.clone() else {
1385            return grid;
1386        };
1387        let view = Rc::clone(self);
1388        let on_focus = on_event.clone();
1389        scope(grid)
1390            .on_focus(move |focused| on_focus(Event::Focus(focused)))
1391            .on_key(move |key| {
1392                let state = view.state;
1393                let opened = view
1394                    .menu
1395                    .as_ref()
1396                    .zip(state.highlighted().cloned())
1397                    .and_then(|(menu, target)| menu.key(key, target));
1398                opened.or_else(|| {
1399                    state
1400                        .key_event(&view.keymap, key)
1401                        .map(|event| on_event(event))
1402                })
1403            })
1404            .into()
1405    }
1406
1407    fn toolbar(&self, narrow: bool) -> Element<'a, Message> {
1408        let state = self.state;
1409        let search = {
1410            let on_event = self.on_event.clone();
1411            input(&self.placeholder, state.search())
1412                .icon(crate::lucide!(Search))
1413                .shortcuts(self.shortcuts)
1414                .width(if narrow {
1415                    Length::Fill
1416                } else {
1417                    Length::Fixed(240.0)
1418                })
1419                .on_input_maybe(
1420                    on_event.map(|on_event| move |query| on_event(Event::Search(query))),
1421                )
1422        };
1423
1424        let filters = state
1425            .columns
1426            .iter()
1427            .filter(|column| column.filterable && !state.is_hidden(column.id))
1428            .map(|column| self.filter(column, narrow));
1429
1430        let columns_menu: Element<'a, Message> = {
1431            let trigger = button("Columns")
1432                .trailing_icon(crate::lucide!(ChevronDown))
1433                .variant(button::Variant::Outline)
1434                .on_press_maybe(self.send(Event::Columns(dropdown_menu::Event::Toggle)));
1435            let menu = dropdown_menu(state.columns_menu(), trigger)
1436                .align(crate::overlay::anchored::Align::End)
1437                .width(200.0);
1438            match self.on_event.clone() {
1439                Some(on_event) => menu
1440                    .on_event(move |event| on_event(Event::Columns(event)))
1441                    .into(),
1442                None => menu.into(),
1443            }
1444        };
1445
1446        if narrow {
1447            return widget::column![
1448                search,
1449                row(filters)
1450                    .push(columns_menu)
1451                    .spacing(space::SM)
1452                    .align_y(Alignment::Center),
1453            ]
1454            .spacing(space::SM)
1455            .into();
1456        }
1457        row![search]
1458            .extend(filters)
1459            .push(spacer::horizontal())
1460            .push(columns_menu)
1461            .spacing(space::SM)
1462            .align_y(Alignment::Center)
1463            .into()
1464    }
1465
1466    fn filter(&self, column: &Column<Row>, narrow: bool) -> Element<'a, Message> {
1467        let state = self.state;
1468        let choice = |value: Option<&str>| FilterChoice {
1469            column: column.id,
1470            header: column.header.clone(),
1471            value: value.map(str::to_owned),
1472        };
1473        let options: Vec<FilterChoice> = std::iter::once(choice(None))
1474            .chain(
1475                state
1476                    .options(column.id)
1477                    .iter()
1478                    .map(|value| choice(Some(value))),
1479            )
1480            .collect();
1481        let selected = choice(state.filter(column.id));
1482        let on_event = self.on_event.clone();
1483        select(options, Some(selected))
1484            .width(if narrow {
1485                Length::Fill
1486            } else {
1487                Length::Fixed(170.0)
1488            })
1489            .on_select_maybe(on_event.map(|on_event| {
1490                move |choice: FilterChoice| on_event(Event::Filter(choice.column, choice.value))
1491            }))
1492            .into()
1493    }
1494
1495    fn table(self: &Rc<Self>) -> Element<'a, Message> {
1496        let state = self.state;
1497        let columns = state.visible_columns();
1498
1499        let mut header = row![].height(Length::Fill).align_y(Alignment::Center);
1500        if state.is_selectable() {
1501            let page_empty = state.page_range().is_empty();
1502            let on_event = self
1503                .on_event
1504                .clone()
1505                .filter(|_| !page_empty && !self.loading);
1506            header = header.push(
1507                container(checkbox(state.page_check_state()).on_toggle_maybe(
1508                    on_event.map(|on_event| move |checked| on_event(Event::SelectPage(checked))),
1509                ))
1510                .center_x(CHECK_WIDTH),
1511            );
1512        }
1513        for column in &columns {
1514            header = header.push(self.header_cell(column));
1515        }
1516        if self.row_actions {
1517            header = header.push(Space::new().width(ACTIONS_WIDTH));
1518        }
1519        let divider = container(Space::new())
1520            .width(Length::Fill)
1521            .height(1)
1522            .style(|theme| container::Style {
1523                background: Some(Background::Color(Tokens::of(theme).border)),
1524                ..container::Style::default()
1525            });
1526        let header = widget::column![container(header).height(HEADER_HEIGHT), divider];
1527
1528        container(self.table_body(header.into()))
1529            .width(Length::Fill)
1530            .clip(true)
1531            .style(|theme| frame_style(&Tokens::of(theme)))
1532            .into()
1533    }
1534
1535    fn header_cell(&self, column: &Column<Row>) -> Element<'a, Message> {
1536        let state = self.state;
1537        let align = column.align.horizontal();
1538        let label = ellipsis(column.header.clone())
1539            .font(semibold())
1540            .width(Length::Shrink)
1541            .colour(muted);
1542        let cell = |content: Element<'a, Message>| -> Element<'a, Message> {
1543            container(content)
1544                .width(column.width)
1545                .height(Length::Fill)
1546                .padding([0.0, space::SM])
1547                .align_x(align)
1548                .center_y(Length::Fill)
1549                .into()
1550        };
1551        if !column.sortable {
1552            return cell(label.into());
1553        }
1554        let direction = state
1555            .sort()
1556            .filter(|(id, _)| *id == column.id)
1557            .map(|(_, direction)| direction);
1558        let indicator = themed(sort_glyph(direction), 14.0, 1.0, move |theme| {
1559            let tokens = Tokens::of(theme);
1560            if direction.is_some() {
1561                tokens.foreground
1562            } else {
1563                tokens.muted_foreground
1564            }
1565        });
1566        let content = row![label, indicator]
1567            .spacing(space::XS)
1568            .align_y(Alignment::Center);
1569        let press = pressable(
1570            container(content).padding([4.0, space::XS]),
1571            |theme, hovered| Look {
1572                background: hovered.then(|| Tokens::of(theme).accent),
1573                border: Border {
1574                    radius: radius::SM.into(),
1575                    ..Border::default()
1576                },
1577                divider: None,
1578            },
1579        );
1580        let press = match self.on_event.clone() {
1581            Some(on_event) => {
1582                let id = column.id;
1583                press.on_press(move |_| on_event(Event::Sort(id)))
1584            }
1585            None => press,
1586        };
1587        container(press)
1588            .width(column.width)
1589            .height(Length::Fill)
1590            .padding([0.0, space::XS])
1591            .align_x(align)
1592            .center_y(Length::Fill)
1593            .into()
1594    }
1595
1596    /// The header above the rows of the page, placeholder rows while
1597    /// loading, or the empty message.
1598    fn table_body(self: &Rc<Self>, header: Element<'a, Message>) -> Element<'a, Message> {
1599        let state = self.state;
1600        if self.loading {
1601            let skeleton =
1602                (0..SKELETON_ROWS).map(|index| self.skeleton_row(index + 1 == SKELETON_ROWS));
1603            return widget::column(std::iter::once(header).chain(skeleton)).into();
1604        }
1605        let page = state.page_indices();
1606        if page.is_empty() {
1607            return widget::column![header, self.empty_view()].into();
1608        }
1609        let highlight = self.highlight_position();
1610        let count = page.len();
1611        let view = Rc::clone(self);
1612        rows(count, self.row_height, move |range: Range<usize>| {
1613            widget::column(
1614                page.get(range.clone())
1615                    .unwrap_or_default()
1616                    .iter()
1617                    .zip(range)
1618                    .map(|(&index, position)| view.table_row(index, position + 1 == count)),
1619            )
1620            .into()
1621        })
1622        .header(header)
1623        .highlight(highlight)
1624        .height(self.height)
1625        .into()
1626    }
1627
1628    fn highlight_position(&self) -> Option<usize> {
1629        let key = self.state.highlighted()?;
1630        self.state.page_keys().iter().position(|page| page == key)
1631    }
1632
1633    fn row_status(&self, key: &Key) -> Status {
1634        let state = self.state;
1635        let target = self.menu.as_ref().and_then(RowMenu::target);
1636        Status {
1637            selected: state.is_selectable() && state.is_selected(key),
1638            hovered: false,
1639            highlighted: ringed(
1640                target.as_ref(),
1641                key,
1642                state.is_focused() && state.highlighted() == Some(key),
1643            ),
1644        }
1645    }
1646
1647    fn checkbox_for(&self, key: &Key) -> Element<'a, Message> {
1648        let selected = self.state.is_selected(key);
1649        let on_event = self.on_event.clone();
1650        let key = key.clone();
1651        checkbox(selected)
1652            .on_toggle_maybe(
1653                on_event.map(|on_event| move |checked| on_event(Event::Select(key, checked))),
1654            )
1655            .into()
1656    }
1657
1658    fn actions_for(&self, key: &Key) -> Element<'a, Message> {
1659        let open = self.menu.as_ref().map(|menu| menu.open(key.clone()));
1660        icon_button(crate::lucide!(Ellipsis))
1661            .label("Row actions")
1662            .tooltip(None)
1663            .size(button::Size::Sm)
1664            .on_press_maybe(open)
1665            .into()
1666    }
1667
1668    fn content_for(
1669        &self,
1670        column: &Column<Row>,
1671        row: &'a Row,
1672        align: Horizontal,
1673    ) -> Element<'a, Message> {
1674        if let Some((_, render)) = self.cells.iter().find(|(id, _)| *id == column.id) {
1675            return render(row);
1676        }
1677        ellipsis(column.text(row)).align_x(align).into()
1678    }
1679
1680    fn table_row(&self, index: usize, last: bool) -> Element<'a, Message> {
1681        let state = self.state;
1682        let Some(row_data) = state.rows.get(index) else {
1683            return Space::new().into();
1684        };
1685        let key = state.key(row_data);
1686        let mut cells = row![].height(Length::Fill).align_y(Alignment::Center);
1687        if state.is_selectable() {
1688            cells = cells.push(container(self.checkbox_for(&key)).center_x(CHECK_WIDTH));
1689        }
1690        for column in state.visible_columns() {
1691            cells = cells.push(
1692                container(self.content_for(column, row_data, column.align.horizontal()))
1693                    .width(column.width)
1694                    .padding([0.0, space::SM])
1695                    .align_x(column.align.horizontal())
1696                    .center_y(Length::Fill),
1697            );
1698        }
1699        if self.row_actions {
1700            cells = cells.push(container(self.actions_for(&key)).center_x(ACTIONS_WIDTH));
1701        }
1702        let status = self.row_status(&key);
1703        let body = pressable(
1704            container(cells).height(self.row_height),
1705            move |theme, hovered| {
1706                let style = row_style(&Tokens::of(theme), Status { hovered, ..status });
1707                Look {
1708                    background: style.background,
1709                    border: Border {
1710                        color: style.ring.unwrap_or(Color::TRANSPARENT),
1711                        width: if style.ring.is_some() { 1.0 } else { 0.0 },
1712                        radius: radius::SM.into(),
1713                    },
1714                    divider: (!last).then_some(style.divider),
1715                }
1716            },
1717        );
1718        self.finish_row(body, key)
1719    }
1720
1721    /// Adds the press and double click messages and the context menu.
1722    fn finish_row(
1723        &self,
1724        body: crate::data::interaction::Pressable<'a, Message>,
1725        key: Key,
1726    ) -> Element<'a, Message> {
1727        let Some(on_event) = self.on_event.clone() else {
1728            return body.into();
1729        };
1730        let activate = on_event(Event::Activate(key.clone()));
1731        let press_key = key.clone();
1732        let body: Element<'a, Message> = body
1733            .on_press(move |_| on_event(Event::Press(press_key.clone())))
1734            .on_double_click(Some(activate))
1735            .into();
1736        match &self.menu {
1737            Some(menu) => menu.wrap(key, body),
1738            None => body,
1739        }
1740    }
1741
1742    fn skeleton_row(&self, last: bool) -> Element<'a, Message> {
1743        let state = self.state;
1744        let bar = || {
1745            container(Space::new())
1746                .width(Length::Fill)
1747                .height(12)
1748                .style(|theme| skeleton_style(&Tokens::of(theme)))
1749        };
1750        let mut cells = row![].height(Length::Fill).align_y(Alignment::Center);
1751        if state.is_selectable() {
1752            cells = cells.push(Space::new().width(CHECK_WIDTH));
1753        }
1754        for column in state.visible_columns() {
1755            cells = cells.push(
1756                container(bar())
1757                    .width(column.width)
1758                    .padding([0.0, space::SM]),
1759            );
1760        }
1761        if self.row_actions {
1762            cells = cells.push(Space::new().width(ACTIONS_WIDTH));
1763        }
1764        pressable::<Message>(container(cells).height(self.row_height), move |theme, _| {
1765            Look {
1766                divider: (!last).then(|| Tokens::of(theme).border),
1767                ..Look::default()
1768            }
1769        })
1770        .into()
1771    }
1772
1773    fn empty_view(&self) -> Element<'a, Message> {
1774        let state = self.state;
1775        let glyph = if state.is_filtered() {
1776            crate::lucide!(SearchX)
1777        } else {
1778            crate::lucide!(Inbox)
1779        };
1780        let mut content = widget::column![
1781            themed(glyph, 24.0, 1.0, muted),
1782            text(self.empty.clone())
1783                .size(text_size::SM)
1784                .style(|theme| text::Style {
1785                    color: Some(muted(theme)),
1786                }),
1787        ]
1788        .spacing(space::SM)
1789        .align_x(Alignment::Center);
1790        if state.is_filtered() {
1791            content = content.push(
1792                button("Clear filters")
1793                    .variant(button::Variant::Outline)
1794                    .size(button::Size::Sm)
1795                    .on_press_maybe(self.send(Event::ClearFilters)),
1796            );
1797        }
1798        container(content)
1799            .padding(space::XL)
1800            .center_x(Length::Fill)
1801            .into()
1802    }
1803
1804    /// The card height for the visible columns: the first column heads the
1805    /// card, and each other column is a labelled line.
1806    fn card_height(&self) -> f32 {
1807        let lines = self.state.visible_columns().len().max(1);
1808        CARD_PADDING * 2.0 + lines as f32 * CARD_LINE
1809    }
1810
1811    fn cards(self: &Rc<Self>) -> Element<'a, Message> {
1812        let state = self.state;
1813        let has_rows = !self.loading && !state.page_range().is_empty();
1814        let mut bar = row![].spacing(space::MD).align_y(Alignment::Center);
1815        if state.is_selectable() {
1816            let on_event = self.on_event.clone().filter(|_| has_rows);
1817            bar = bar.push(
1818                checkbox(state.page_check_state())
1819                    .label("Select all")
1820                    .on_toggle_maybe(
1821                        on_event
1822                            .map(|on_event| move |checked| on_event(Event::SelectPage(checked))),
1823                    ),
1824            );
1825        }
1826        if has_rows {
1827            bar = bar.push(self.sort_select());
1828        }
1829
1830        let body: Element<'a, Message> = if self.loading {
1831            widget::column((0..SKELETON_ROWS).map(|_| self.skeleton_card()))
1832                .spacing(CARD_GAP)
1833                .into()
1834        } else if state.page_range().is_empty() {
1835            container(self.empty_view())
1836                .style(|theme| frame_style(&Tokens::of(theme)))
1837                .into()
1838        } else {
1839            let page = state.page_indices();
1840            let count = page.len();
1841            let view = Rc::clone(self);
1842            let height = self.card_height();
1843            rows(count, height + CARD_GAP, move |range: Range<usize>| {
1844                widget::column(
1845                    page.get(range)
1846                        .unwrap_or_default()
1847                        .iter()
1848                        .map(|&index| view.card(index, height)),
1849                )
1850                .into()
1851            })
1852            .highlight(self.highlight_position())
1853            .height(self.height)
1854            .into()
1855        };
1856        if !state.is_selectable() && !has_rows {
1857            return body;
1858        }
1859        widget::column![bar, body].spacing(space::SM).into()
1860    }
1861
1862    fn sort_select(&self) -> Element<'a, Message> {
1863        let state = self.state;
1864        let mut options = vec![SortChoice {
1865            sort: None,
1866            label: "Default order".to_owned(),
1867        }];
1868        for column in state
1869            .visible_columns()
1870            .into_iter()
1871            .filter(|column| column.sortable)
1872        {
1873            for direction in Direction::ALL {
1874                let way = match direction {
1875                    Direction::Ascending => "ascending",
1876                    Direction::Descending => "descending",
1877                };
1878                options.push(SortChoice {
1879                    sort: Some((column.id, direction)),
1880                    label: format!("{}, {way}", column.header),
1881                });
1882            }
1883        }
1884        let selected = options
1885            .iter()
1886            .find(|choice| choice.sort == state.sort())
1887            .cloned();
1888        let on_event = self.on_event.clone();
1889        select(options, selected)
1890            .width(Length::Fill)
1891            .on_select_maybe(
1892                on_event
1893                    .map(|on_event| move |choice: SortChoice| on_event(Event::SortBy(choice.sort))),
1894            )
1895            .into()
1896    }
1897
1898    fn card(&self, index: usize, height: f32) -> Element<'a, Message> {
1899        let state = self.state;
1900        let Some(row_data) = state.rows.get(index) else {
1901            return Space::new().into();
1902        };
1903        let key = state.key(row_data);
1904        let columns = state.visible_columns();
1905        let mut lines = widget::column![];
1906
1907        let mut head = row![].spacing(space::SM).align_y(Alignment::Center);
1908        if state.is_selectable() {
1909            head = head.push(self.checkbox_for(&key));
1910        }
1911        if let Some(first) = columns.first() {
1912            let title: Element<'a, Message> =
1913                match self.cells.iter().find(|(id, _)| *id == first.id) {
1914                    Some((_, render)) => container(render(row_data)).width(Length::Fill).into(),
1915                    None => ellipsis(first.text(row_data)).font(semibold()).into(),
1916                };
1917            head = head.push(title);
1918        }
1919        if self.row_actions {
1920            head = head.push(self.actions_for(&key));
1921        }
1922        lines = lines.push(container(head).height(CARD_LINE).center_y(CARD_LINE));
1923
1924        for column in columns.iter().skip(1) {
1925            let label = ellipsis(column.header.clone())
1926                .colour(muted)
1927                .width(Length::FillPortion(2));
1928            let value = container(self.content_for(column, row_data, Horizontal::Right))
1929                .width(Length::FillPortion(3))
1930                .align_x(Horizontal::Right);
1931            lines = lines.push(
1932                container(
1933                    row![label, value]
1934                        .spacing(space::SM)
1935                        .align_y(Alignment::Center),
1936                )
1937                .height(CARD_LINE)
1938                .center_y(CARD_LINE),
1939            );
1940        }
1941
1942        let status = self.row_status(&key);
1943        let card = pressable(
1944            container(lines).padding(CARD_PADDING).height(height),
1945            move |theme, hovered| {
1946                let tokens = Tokens::of(theme);
1947                let style = row_style(&tokens, Status { hovered, ..status });
1948                Look {
1949                    background: style.background,
1950                    border: Border {
1951                        color: style.ring.unwrap_or(tokens.border),
1952                        width: 1.0,
1953                        radius: radius::MD.into(),
1954                    },
1955                    divider: None,
1956                }
1957            },
1958        );
1959        let card = self.finish_row(card, key);
1960        container(card)
1961            .padding(Padding::ZERO.bottom(CARD_GAP))
1962            .into()
1963    }
1964
1965    fn skeleton_card(&self) -> Element<'a, Message> {
1966        let lines = widget::column((0..self.state.visible_columns().len().max(1)).map(|_| {
1967            container(
1968                container(Space::new())
1969                    .width(Length::Fill)
1970                    .height(12)
1971                    .style(|theme| skeleton_style(&Tokens::of(theme))),
1972            )
1973            .height(CARD_LINE)
1974            .center_y(CARD_LINE)
1975            .into()
1976        }));
1977        container(lines)
1978            .padding(CARD_PADDING)
1979            .width(Length::Fill)
1980            .style(|theme| frame_style(&Tokens::of(theme)))
1981            .into()
1982    }
1983
1984    fn footer(&self, narrow: bool) -> Element<'a, Message> {
1985        let state = self.state;
1986        let mut summary = state.showing();
1987        if state.is_selectable() {
1988            summary.push_str(&format!(", {} selected", state.selected.len()));
1989        }
1990        let summary = small(summary);
1991
1992        let on_event = self.on_event.clone().filter(|_| !self.loading);
1993        let sizes = select(state.page_sizes().to_vec(), Some(state.page_size()))
1994            .width(80)
1995            .on_select_maybe(on_event.map(|on_event| move |size| on_event(Event::PageSize(size))));
1996        let has_previous = state.page() > 0;
1997        let has_next = state.page() + 1 < state.page_count();
1998        let pager = row![
1999            small(format!(
2000                "Page {} of {}",
2001                state.page() + 1,
2002                state.page_count()
2003            )),
2004            icon_button(crate::lucide!(ChevronLeft))
2005                .label("Previous page")
2006                .variant(crate::primitives::icon_button::Variant::Outline)
2007                .size(button::Size::Sm)
2008                .on_press_maybe(
2009                    self.send(Event::PreviousPage)
2010                        .filter(|_| has_previous && !self.loading)
2011                ),
2012            icon_button(crate::lucide!(ChevronRight))
2013                .label("Next page")
2014                .variant(crate::primitives::icon_button::Variant::Outline)
2015                .size(button::Size::Sm)
2016                .on_press_maybe(
2017                    self.send(Event::NextPage)
2018                        .filter(|_| has_next && !self.loading)
2019                ),
2020        ]
2021        .spacing(space::SM)
2022        .align_y(Alignment::Center);
2023
2024        if narrow {
2025            return widget::column![
2026                summary,
2027                row![sizes, spacer::horizontal(), pager].align_y(Alignment::Center),
2028            ]
2029            .spacing(space::SM)
2030            .into();
2031        }
2032        row![
2033            summary,
2034            spacer::horizontal(),
2035            small("Rows per page"),
2036            sizes,
2037            pager,
2038        ]
2039        .spacing(space::MD)
2040        .align_y(Alignment::Center)
2041        .into()
2042    }
2043}
2044
2045/// An option in a column filter's select.
2046#[derive(Debug, Clone, PartialEq)]
2047struct FilterChoice {
2048    column: ColumnId,
2049    header: String,
2050    value: Option<String>,
2051}
2052
2053impl fmt::Display for FilterChoice {
2054    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2055        match &self.value {
2056            Some(value) => write!(f, "{}: {value}", self.header),
2057            None => write!(f, "{}: All", self.header),
2058        }
2059    }
2060}
2061
2062/// An option in the sort select shown above cards.
2063#[derive(Debug, Clone, PartialEq)]
2064struct SortChoice {
2065    sort: Option<(ColumnId, Direction)>,
2066    label: String,
2067}
2068
2069impl fmt::Display for SortChoice {
2070    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2071        f.write_str(&self.label)
2072    }
2073}
2074
2075#[cfg(test)]
2076mod tests {
2077    use super::*;
2078    use crate::theme::{dark, light};
2079    use iced::keyboard::{Key, Modifiers};
2080
2081    #[derive(Debug, Clone, PartialEq)]
2082    struct Payment {
2083        id: u32,
2084        status: &'static str,
2085        email: String,
2086        amount: Option<f64>,
2087    }
2088
2089    fn payment(id: u32, status: &'static str, email: &str, amount: f64) -> Payment {
2090        Payment {
2091            id,
2092            status,
2093            email: email.to_owned(),
2094            amount: Some(amount),
2095        }
2096    }
2097
2098    fn columns() -> Vec<Column<Payment>> {
2099        vec![
2100            column("status", "Status", |p: &Payment| p.status.into()).filterable(true),
2101            column("email", "Email", |p: &Payment| p.email.clone().into()),
2102            column("amount", "Amount", |p: &Payment| p.amount.into())
2103                .align(Align::End)
2104                .format(|p| {
2105                    p.amount
2106                        .map_or_else(String::new, |amount| format!("${amount:.2}"))
2107                }),
2108            column("id", "ID", |p: &Payment| p.id.into())
2109                .sortable(false)
2110                .hideable(false),
2111        ]
2112    }
2113
2114    fn payments(count: u32) -> Vec<Payment> {
2115        (1..=count)
2116            .map(|id| {
2117                let status = ["paid", "pending", "failed"][(id % 3) as usize];
2118                payment(
2119                    id,
2120                    status,
2121                    &format!("user{id}@example.com"),
2122                    f64::from(id * 10),
2123                )
2124            })
2125            .collect()
2126    }
2127
2128    fn state(count: u32) -> State<Payment, u32> {
2129        State::new(columns(), payments(count), |p| p.id)
2130    }
2131
2132    fn ids(rows: Vec<&Payment>) -> Vec<u32> {
2133        rows.into_iter().map(|p| p.id).collect()
2134    }
2135
2136    fn selected(output: Option<Output<u32>>) -> Vec<u32> {
2137        match output {
2138            Some(Output::Selected(keys)) => keys,
2139            other => panic!("expected a selection, got {other:?}"),
2140        }
2141    }
2142
2143    #[test]
2144    fn values_display_and_convert() {
2145        assert_eq!(Value::from(12.0).to_string(), "12");
2146        assert_eq!(Value::from(12.5).to_string(), "12.5");
2147        assert_eq!(Value::from(7_u32), Value::Number(7.0));
2148        assert_eq!(Value::from("a"), Value::Text("a".into()));
2149        assert_eq!(Value::from(None::<f64>), Value::Empty);
2150        assert_eq!(Value::from(Some(3_i64)), Value::Number(3.0));
2151        assert_eq!(Value::Empty.to_string(), "");
2152        assert_eq!(Value::default(), Value::Empty);
2153    }
2154
2155    #[test]
2156    fn compare_orders_numbers_then_text_then_empty() {
2157        let mut values = vec![
2158            Value::from("banana"),
2159            Value::Empty,
2160            Value::from(10.0),
2161            Value::from("Apple"),
2162            Value::from(2.0),
2163            Value::from("apple"),
2164        ];
2165        values.sort_by(compare);
2166        assert_eq!(
2167            values,
2168            vec![
2169                Value::from(2.0),
2170                Value::from(10.0),
2171                Value::from("Apple"),
2172                Value::from("apple"),
2173                Value::from("banana"),
2174                Value::Empty,
2175            ]
2176        );
2177    }
2178
2179    #[test]
2180    fn starts_unsorted_on_the_first_page() {
2181        let state = state(23);
2182        assert_eq!(state.len(), 23);
2183        assert_eq!(state.filtered_len(), 23);
2184        assert_eq!(state.page(), 0);
2185        assert_eq!(state.page_size(), 10);
2186        assert_eq!(state.page_count(), 3);
2187        assert_eq!(state.page_range(), 0..10);
2188        assert_eq!(ids(state.page_rows()), (1..=10).collect::<Vec<_>>());
2189        assert_eq!(state.showing(), "Showing 1-10 of 23");
2190        assert_eq!(state.sort(), None);
2191        assert!(!state.is_selectable());
2192        assert!(!state.is_filtered());
2193    }
2194
2195    #[test]
2196    fn an_empty_table_has_one_empty_page() {
2197        let state = state(0);
2198        assert!(state.is_empty());
2199        assert_eq!(state.page_count(), 1);
2200        assert_eq!(state.page_range(), 0..0);
2201        assert_eq!(state.showing(), "Showing 0 of 0");
2202        assert_eq!(state.page_check_state(), CheckState::Unchecked);
2203    }
2204
2205    #[test]
2206    fn header_presses_cycle_ascending_descending_and_unsorted() {
2207        let mut state = state(5).with_page_sizes([5]);
2208        let _ = state.update(Event::Sort("amount"));
2209        assert_eq!(state.sort(), Some(("amount", Direction::Ascending)));
2210        assert_eq!(ids(state.page_rows()), [1, 2, 3, 4, 5]);
2211        let _ = state.update(Event::Sort("amount"));
2212        assert_eq!(state.sort(), Some(("amount", Direction::Descending)));
2213        assert_eq!(ids(state.page_rows()), [5, 4, 3, 2, 1]);
2214        let _ = state.update(Event::Sort("amount"));
2215        assert_eq!(state.sort(), None);
2216        assert_eq!(ids(state.page_rows()), [1, 2, 3, 4, 5]);
2217        let _ = state.update(Event::Sort("email"));
2218        assert_eq!(state.sort(), Some(("email", Direction::Ascending)));
2219    }
2220
2221    #[test]
2222    fn unsortable_and_unknown_columns_are_ignored() {
2223        let mut state = state(5).with_sort("amount", Direction::Descending);
2224        let _ = state.update(Event::Sort("id"));
2225        let _ = state.update(Event::SortBy(Some(("missing", Direction::Ascending))));
2226        assert_eq!(state.sort(), Some(("amount", Direction::Descending)));
2227        let _ = state.update(Event::SortBy(None));
2228        assert_eq!(state.sort(), None);
2229    }
2230
2231    #[test]
2232    fn empty_values_sort_last_both_ways() {
2233        let mut rows = payments(3);
2234        rows[1].amount = None;
2235        let mut state = State::new(columns(), rows, |p| p.id);
2236        let _ = state.update(Event::SortBy(Some(("amount", Direction::Ascending))));
2237        assert_eq!(ids(state.page_rows()), [1, 3, 2]);
2238        let _ = state.update(Event::SortBy(Some(("amount", Direction::Descending))));
2239        assert_eq!(ids(state.page_rows()), [3, 1, 2]);
2240    }
2241
2242    #[test]
2243    fn search_matches_visible_searchable_text_ignoring_case() {
2244        let mut state = state(23);
2245        let _ = state.update(Event::NextPage);
2246        let _ = state.update(Event::Search("USER2".into()));
2247        assert_eq!(state.page(), 0, "a new search starts on the first page");
2248        assert_eq!(ids(state.page_rows()), [2, 20, 21, 22, 23]);
2249        let _ = state.update(Event::Search("$30.00".into()));
2250        assert_eq!(ids(state.page_rows()), [3], "searches the formatted text");
2251        let _ = state.update(Event::Columns(dropdown_menu::Event::Activate("amount")));
2252        assert!(state.is_hidden("amount"));
2253        assert_eq!(state.filtered_len(), 0, "hidden columns are not searched");
2254        assert!(state.is_filtered());
2255    }
2256
2257    #[test]
2258    fn column_filters_offer_distinct_values_and_combine_with_search() {
2259        let mut state = state(9);
2260        assert_eq!(state.options("status"), ["failed", "paid", "pending"]);
2261        assert!(state.options("email").is_empty());
2262        let _ = state.update(Event::Filter("status", Some("paid".into())));
2263        assert_eq!(state.filter("status"), Some("paid"));
2264        assert_eq!(ids(state.page_rows()), [3, 6, 9]);
2265        let _ = state.update(Event::Search("user9".into()));
2266        assert_eq!(ids(state.page_rows()), [9]);
2267        let _ = state.update(Event::Filter("status", None));
2268        assert_eq!(ids(state.page_rows()), [9]);
2269        let _ = state.update(Event::Filter("status", Some("paid".into())));
2270        let _ = state.update(Event::ClearFilters);
2271        assert_eq!(state.filtered_len(), 9);
2272        assert_eq!(state.search(), "");
2273        assert_eq!(state.filter("status"), None);
2274        let _ = state.update(Event::Filter("missing", Some("x".into())));
2275        assert!(!state.is_filtered(), "unknown columns are not filtered");
2276    }
2277
2278    #[test]
2279    fn pages_clamp_and_page_size_keeps_the_first_row_in_view() {
2280        let mut state = state(23);
2281        let _ = state.update(Event::PreviousPage);
2282        assert_eq!(state.page(), 0);
2283        let _ = state.update(Event::Page(9));
2284        assert_eq!(state.page(), 2);
2285        assert_eq!(state.showing(), "Showing 21-23 of 23");
2286        let _ = state.update(Event::NextPage);
2287        assert_eq!(state.page(), 2);
2288        let _ = state.update(Event::Page(1));
2289        let _ = state.update(Event::PageSize(20));
2290        assert_eq!(state.page(), 0, "row 11 is on the first page of 20");
2291        let _ = state.update(Event::PageSize(5));
2292        assert_eq!(state.page(), 0);
2293        let _ = state.update(Event::Page(3));
2294        let _ = state.update(Event::PageSize(0));
2295        assert_eq!(state.page_size(), 1, "at least one row a page");
2296        assert_eq!(state.page(), 15);
2297    }
2298
2299    #[test]
2300    fn page_sizes_can_be_set() {
2301        let state = state(23).with_page_sizes([0, 5, 25]);
2302        assert_eq!(state.page_sizes(), [5, 25]);
2303        assert_eq!(state.page_size(), 5);
2304        assert_eq!(state.page_count(), 5);
2305        let unchanged = self::state(3).with_page_sizes([]);
2306        assert_eq!(unchanged.page_sizes(), PAGE_SIZES);
2307    }
2308
2309    #[test]
2310    fn selection_needs_a_selectable_table() {
2311        let mut state = state(5);
2312        assert!(state.update(Event::Select(1, true)).is_none());
2313        assert!(state.selected().is_empty());
2314    }
2315
2316    #[test]
2317    fn rows_select_and_the_header_acts_on_the_page_only() {
2318        let mut state = state(23).with_selection(true);
2319        assert_eq!(selected(state.update(Event::Select(2, true))), [2]);
2320        assert_eq!(state.page_check_state(), CheckState::Indeterminate);
2321        assert!(state.update(Event::Select(2, true)).is_none(), "no change");
2322        assert!(
2323            state.update(Event::Select(99, true)).is_none(),
2324            "unknown row"
2325        );
2326
2327        let _ = state.update(Event::NextPage);
2328        assert_eq!(state.page_check_state(), CheckState::Unchecked);
2329        assert_eq!(
2330            selected(state.update(Event::SelectPage(true))),
2331            [2, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
2332        );
2333        assert_eq!(state.page_check_state(), CheckState::Checked);
2334        assert_eq!(selected(state.update(Event::SelectPage(false))), [2]);
2335        assert_eq!(
2336            selected(state.update(Event::ClearSelection)),
2337            Vec::<u32>::new()
2338        );
2339        assert!(state.update(Event::ClearSelection).is_none());
2340    }
2341
2342    #[test]
2343    fn selection_follows_keys_through_sorting_and_row_changes() {
2344        let mut state = state(5).with_selection(true);
2345        let _ = state.update(Event::Select(1, true));
2346        let _ = state.update(Event::Select(4, true));
2347        let _ = state.update(Event::Sort("amount"));
2348        let _ = state.update(Event::Sort("amount"));
2349        assert!(state.is_selected(&1) && state.is_selected(&4));
2350        state.retain(|p| p.id != 4);
2351        assert_eq!(state.selected(), [1]);
2352        state.update_row(&1, |p| p.status = "failed");
2353        assert_eq!(state.row(&1).map(|p| p.status), Some("failed"));
2354        state.push(payment(6, "paid", "new@example.com", 5.0));
2355        assert_eq!(state.len(), 5);
2356        assert_eq!(ids(state.page_rows()), [5, 3, 2, 1, 6], "sorted into place");
2357        state.set_rows(payments(2));
2358        assert_eq!(state.selected(), [1]);
2359    }
2360
2361    #[test]
2362    fn arrows_move_through_the_page_and_across_pages() {
2363        let mut state = state(23);
2364        let _ = state.update(Event::Next);
2365        assert_eq!(state.highlighted(), Some(&1));
2366        let _ = state.update(Event::Last);
2367        assert_eq!(state.highlighted(), Some(&10));
2368        let _ = state.update(Event::Next);
2369        assert_eq!(state.page(), 1);
2370        assert_eq!(state.highlighted(), Some(&11));
2371        let _ = state.update(Event::Previous);
2372        assert_eq!(state.page(), 0);
2373        assert_eq!(state.highlighted(), Some(&10));
2374        let _ = state.update(Event::First);
2375        let _ = state.update(Event::Previous);
2376        assert_eq!(state.highlighted(), Some(&1), "stays at the very first row");
2377        let _ = state.update(Event::Page(2));
2378        let _ = state.update(Event::Last);
2379        let _ = state.update(Event::Next);
2380        assert_eq!(state.highlighted(), Some(&23), "stays at the very last row");
2381
2382        let mut fresh = self::state(23);
2383        let _ = fresh.update(Event::Previous);
2384        assert_eq!(fresh.highlighted(), Some(&10));
2385    }
2386
2387    #[test]
2388    fn changing_page_moves_the_highlight_onto_it() {
2389        let mut state = state(23);
2390        let _ = state.update(Event::Press(3));
2391        let _ = state.update(Event::NextPage);
2392        assert_eq!(state.highlighted(), Some(&11));
2393        let _ = state.update(Event::Press(3));
2394        assert_eq!(
2395            state.highlighted(),
2396            Some(&11),
2397            "rows on other pages are ignored"
2398        );
2399        let _ = state.update(Event::Search("zzz".into()));
2400        assert_eq!(state.highlighted(), None);
2401    }
2402
2403    #[test]
2404    fn space_toggles_and_enter_activates_the_highlighted_row() {
2405        let mut state = state(5).with_selection(true);
2406        assert!(state.update(Event::ToggleHighlighted).is_none());
2407        assert!(state.update(Event::ActivateHighlighted).is_none());
2408        let _ = state.update(Event::Press(2));
2409        assert_eq!(selected(state.update(Event::ToggleHighlighted)), [2]);
2410        assert_eq!(
2411            selected(state.update(Event::ToggleHighlighted)),
2412            Vec::<u32>::new()
2413        );
2414        assert_eq!(
2415            state.update(Event::ActivateHighlighted),
2416            Some(Output::Activated(2))
2417        );
2418        assert_eq!(state.update(Event::Activate(4)), Some(Output::Activated(4)));
2419        assert_eq!(state.highlighted(), Some(&4));
2420        assert!(state.update(Event::Activate(40)).is_none());
2421    }
2422
2423    #[test]
2424    fn the_columns_menu_hides_columns_but_never_the_last() {
2425        let mut state = state(3);
2426        let menu: Vec<ColumnId> = state
2427            .columns_menu()
2428            .entries()
2429            .iter()
2430            .filter_map(|entry| entry.as_item().map(|item| item.id))
2431            .collect();
2432        assert_eq!(menu, ["status", "email", "amount"], "ID is not hideable");
2433        let _ = state.update(Event::Columns(dropdown_menu::Event::Open));
2434        let _ = state.update(Event::Columns(dropdown_menu::Event::Activate("email")));
2435        assert!(state.is_hidden("email"));
2436        assert!(!state.columns_menu().is_checked("email"));
2437        assert_eq!(state.visible_columns().len(), 3);
2438        let _ = state.update(Event::Columns(dropdown_menu::Event::Activate("email")));
2439        assert!(!state.is_hidden("email"));
2440
2441        let mut single = State::new(
2442            [column("name", "Name", |p: &Payment| p.email.clone().into())],
2443            payments(1),
2444            |p| p.id,
2445        );
2446        let _ = single.update(Event::Columns(dropdown_menu::Event::Activate("name")));
2447        assert!(!single.is_hidden("name"));
2448        assert!(single.columns_menu().is_checked("name"));
2449    }
2450
2451    #[test]
2452    fn with_hidden_starts_with_columns_hidden() {
2453        let state = state(3).with_hidden(["email"]);
2454        assert!(state.is_hidden("email"));
2455        assert!(!state.columns_menu().is_checked("email"));
2456        assert!(state.columns_menu().is_checked("status"));
2457        let visible: Vec<ColumnId> = state.visible_columns().iter().map(|c| c.id).collect();
2458        assert_eq!(visible, ["status", "amount", "id"]);
2459    }
2460
2461    #[test]
2462    fn focus_is_tracked_and_lands_on_a_row() {
2463        let mut state = state(3);
2464        let _ = state.update(Event::Focus(true));
2465        assert!(state.is_focused());
2466        assert_eq!(state.highlighted(), Some(&1));
2467
2468        let mut selected = self::state(3).with_selection(true);
2469        let _ = selected.update(Event::Select(2, true));
2470        let _ = selected.update(Event::Focus(true));
2471        assert_eq!(selected.highlighted(), Some(&2), "the first selected row");
2472        let _ = selected.update(Event::Focus(false));
2473        assert!(!selected.is_focused());
2474
2475        let empty = &mut self::state(0);
2476        let _ = empty.update(Event::Focus(true));
2477        assert_eq!(empty.highlighted(), None);
2478    }
2479
2480    #[test]
2481    fn columns_read_and_format_cells() {
2482        let columns = columns();
2483        let row = payment(7, "paid", "a@b.c", 12.5);
2484        assert_eq!(columns[2].value(&row), Value::Number(12.5));
2485        assert_eq!(columns[2].text(&row), "$12.50");
2486        assert_eq!(columns[0].text(&row), "paid");
2487        let column = columns[0]
2488            .clone()
2489            .width(120)
2490            .align(Align::Center)
2491            .searchable(false);
2492        assert_eq!(column.width, Length::Fixed(120.0));
2493        assert_eq!(column.align, Align::Center);
2494        assert!(!column.searchable);
2495        assert!(format!("{column:?}").contains("status"));
2496        assert_eq!(Align::ALL.len(), 3);
2497        assert_eq!(Direction::ALL.len(), 2);
2498    }
2499
2500    fn press(keymap: &Keymap<Action>, chord: &str) -> Option<Action> {
2501        let chord: Chord = chord.parse().unwrap();
2502        keymap.resolve(chord.key(), chord.modifiers())
2503    }
2504
2505    #[test]
2506    fn default_keymap_covers_every_action() {
2507        let keymap = default_keymap();
2508        assert_eq!(press(&keymap, "ArrowDown"), Some(Action::Next));
2509        assert_eq!(press(&keymap, "ArrowUp"), Some(Action::Previous));
2510        assert_eq!(press(&keymap, "Home"), Some(Action::First));
2511        assert_eq!(press(&keymap, "End"), Some(Action::Last));
2512        assert_eq!(press(&keymap, "PageDown"), Some(Action::NextPage));
2513        assert_eq!(press(&keymap, "PageUp"), Some(Action::PreviousPage));
2514        assert_eq!(press(&keymap, "Space"), Some(Action::Select));
2515        assert_eq!(press(&keymap, "Enter"), Some(Action::Activate));
2516        assert_eq!(press(&keymap, "Mod+A"), Some(Action::SelectAll));
2517        assert_eq!(press(&keymap, "Escape"), Some(Action::ClearSelection));
2518        for action in <Action as keys::Action>::ALL {
2519            assert!(!keymap.chords(action).is_empty(), "{action:?}");
2520            assert!(keys::Action::description(*action).ends_with('.'));
2521        }
2522        assert_eq!(Keymap::<Action>::defaults(), keymap);
2523    }
2524
2525    #[test]
2526    fn keymap_overrides_and_unbinding() {
2527        let keymap = default_keymap()
2528            .unbind(&Chord::named(Named::Escape))
2529            .bind(Chord::character('j'), Action::Next);
2530        let mut state = state(5).with_selection(true);
2531        let _ = state.update(Event::Select(1, true));
2532        let escape = keys::Event {
2533            key: Key::Named(Named::Escape),
2534            modifiers: Modifiers::empty(),
2535        };
2536        assert_eq!(state.key_event(&keymap, &escape), None);
2537        let j = keys::Event {
2538            key: Key::Character("j".into()),
2539            modifiers: Modifiers::empty(),
2540        };
2541        assert_eq!(state.key_event(&keymap, &j), Some(Event::Next));
2542        assert!(default_keymap().clear().is_empty());
2543    }
2544
2545    #[test]
2546    fn actions_map_to_events_only_when_they_apply() {
2547        let mut state = state(23);
2548        assert_eq!(Action::Next.event(&state), Some(Event::Next));
2549        assert_eq!(Action::PreviousPage.event(&state), None);
2550        assert_eq!(Action::NextPage.event(&state), Some(Event::NextPage));
2551        assert_eq!(Action::Activate.event(&state), None);
2552        assert_eq!(Action::Select.event(&state), None, "not selectable");
2553        assert_eq!(Action::SelectAll.event(&state), None);
2554        let _ = state.update(Event::First);
2555        assert_eq!(
2556            Action::Activate.event(&state),
2557            Some(Event::ActivateHighlighted)
2558        );
2559
2560        let mut selectable = self::state(3).with_selection(true);
2561        assert_eq!(
2562            Action::SelectAll.event(&selectable),
2563            Some(Event::SelectPage(true))
2564        );
2565        assert_eq!(
2566            Action::ClearSelection.event(&selectable),
2567            None,
2568            "nothing selected"
2569        );
2570        let _ = selectable.update(Event::SelectPage(true));
2571        assert_eq!(
2572            Action::ClearSelection.event(&selectable),
2573            Some(Event::ClearSelection)
2574        );
2575        let _ = selectable.update(Event::First);
2576        assert_eq!(
2577            Action::Select.event(&selectable),
2578            Some(Event::ToggleHighlighted)
2579        );
2580
2581        let empty = self::state(0);
2582        for action in [Action::Next, Action::Previous, Action::First, Action::Last] {
2583            assert_eq!(action.event(&empty), None, "{action:?}");
2584        }
2585    }
2586
2587    #[test]
2588    fn rows_are_muted_when_selected_and_ringed_when_highlighted() {
2589        for theme in [light(), dark()] {
2590            let tokens = Tokens::of(&theme);
2591            let idle = row_style(&tokens, Status::default());
2592            assert_eq!(idle.background, None);
2593            assert_eq!(idle.ring, None);
2594            assert_eq!(idle.divider, tokens.border);
2595            let selected = row_style(
2596                &tokens,
2597                Status {
2598                    selected: true,
2599                    hovered: true,
2600                    ..Status::default()
2601                },
2602            );
2603            assert_eq!(selected.background, Some(tokens.muted));
2604            let hovered = row_style(
2605                &tokens,
2606                Status {
2607                    hovered: true,
2608                    ..Status::default()
2609                },
2610            );
2611            assert_eq!(hovered.background, Some(fade(tokens.muted, 0.5)));
2612            let highlighted = row_style(
2613                &tokens,
2614                Status {
2615                    highlighted: true,
2616                    ..Status::default()
2617                },
2618            );
2619            assert_eq!(highlighted.ring, Some(tokens.ring));
2620
2621            let frame = frame_style(&tokens);
2622            assert_eq!(frame.border.color, tokens.border);
2623            assert_eq!(frame.border.radius, radius::MD.into());
2624            assert_eq!(
2625                skeleton_style(&tokens).background,
2626                Some(Background::Color(tokens.muted))
2627            );
2628        }
2629    }
2630
2631    #[test]
2632    fn sort_indicators_show_the_direction() {
2633        assert_eq!(sort_glyph(None), crate::lucide!(ArrowUpDown));
2634        assert_eq!(
2635            sort_glyph(Some(Direction::Ascending)),
2636            crate::lucide!(ArrowUp)
2637        );
2638        assert_eq!(
2639            sort_glyph(Some(Direction::Descending)),
2640            crate::lucide!(ArrowDown)
2641        );
2642    }
2643
2644    #[test]
2645    fn filter_and_sort_choices_read_well() {
2646        let all = FilterChoice {
2647            column: "status",
2648            header: "Status".into(),
2649            value: None,
2650        };
2651        assert_eq!(all.to_string(), "Status: All");
2652        let paid = FilterChoice {
2653            value: Some("paid".into()),
2654            ..all
2655        };
2656        assert_eq!(paid.to_string(), "Status: paid");
2657        let sort = SortChoice {
2658            sort: None,
2659            label: "Default order".into(),
2660        };
2661        assert_eq!(sort.to_string(), "Default order");
2662    }
2663
2664    #[test]
2665    fn builder_defaults_and_options() {
2666        let state = state(3);
2667        let table: DataTable<'_, Payment, u32, ()> = data_table(&state);
2668        assert!(table.toolbar && !table.loading && !table.row_actions);
2669        assert!(!table.is_enabled());
2670        assert_eq!(table.height, Length::Shrink);
2671        assert_eq!(table.breakpoint, BREAKPOINT);
2672        assert_eq!(table.keymap, default_keymap());
2673        assert_eq!(table.empty, "No results.");
2674        let table = table
2675            .toolbar(false)
2676            .loading(true)
2677            .empty("Nothing here")
2678            .placeholder("Filter emails...")
2679            .height(300)
2680            .row_height(32.0)
2681            .breakpoint(400.0)
2682            .keymap(Keymap::new())
2683            .row_actions(true)
2684            .cell("status", |p: &Payment| text(p.status).into())
2685            .cell("status", |p: &Payment| text(p.status).into())
2686            .on_event(|_| ());
2687        assert!(!table.toolbar && table.loading && table.row_actions);
2688        assert_eq!(table.cells.len(), 1, "a second renderer replaces the first");
2689        assert_eq!(table.placeholder, "Filter emails...");
2690        assert_eq!(table.height, Length::Fixed(300.0));
2691        assert_eq!(table.row_height, 32.0);
2692        assert!(table.is_enabled());
2693        assert!(format!("{table:?}").contains("DataTable"));
2694    }
2695}