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