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                .component("iced_cube::data_table");
1975            if let Some(selected) = selected {
1976                annotated = annotated.selected(selected);
1977            }
1978            annotated.into()
1979        };
1980        #[cfg(not(feature = "icedwright"))]
1981        let _ = position;
1982        row
1983    }
1984
1985    /// Adds the press and double click messages and the context menu.
1986    fn finish_row(
1987        &self,
1988        body: crate::data::interaction::Pressable<'a, Message>,
1989        key: Key,
1990    ) -> Element<'a, Message> {
1991        let Some(on_event) = self.on_event.clone() else {
1992            return body.into();
1993        };
1994        let activate = on_event(Event::Activate(key.clone()));
1995        let press_key = key.clone();
1996        let body: Element<'a, Message> = body
1997            .on_press(move |_| on_event(Event::Press(press_key.clone())))
1998            .on_double_click(Some(activate))
1999            .into();
2000        match &self.menu {
2001            Some(menu) => menu.wrap(key, body),
2002            None => body,
2003        }
2004    }
2005
2006    fn skeleton_row(&self, last: bool, lengths: &[Length]) -> Element<'a, Message> {
2007        let state = self.state;
2008        let bar = || {
2009            container(Space::new())
2010                .width(Length::Fill)
2011                .height(12)
2012                .style(|theme| skeleton_style(&Tokens::of(theme)))
2013        };
2014        let mut cells = row![].height(Length::Fill).align_y(Alignment::Center);
2015        if state.is_selectable() {
2016            cells = cells.push(Space::new().width(CHECK_WIDTH));
2017        }
2018        for length in lengths {
2019            cells = cells.push(container(bar()).width(*length).padding([0.0, space::SM]));
2020        }
2021        if self.row_actions {
2022            cells = cells.push(Space::new().width(ACTIONS_WIDTH));
2023        }
2024        pressable::<Message>(container(cells).height(self.row_height), move |theme, _| {
2025            Look {
2026                divider: (!last).then(|| Tokens::of(theme).border),
2027                ..Look::default()
2028            }
2029        })
2030        .into()
2031    }
2032
2033    fn empty_view(&self) -> Element<'a, Message> {
2034        let state = self.state;
2035        let glyph = if state.is_filtered() {
2036            crate::lucide!(SearchX)
2037        } else {
2038            crate::lucide!(Inbox)
2039        };
2040        let mut content = widget::column![
2041            themed(glyph, 24.0, 1.0, muted),
2042            text(self.empty.clone())
2043                .size(text_size::SM)
2044                .style(|theme| text::Style {
2045                    color: Some(muted(theme)),
2046                }),
2047        ]
2048        .spacing(space::SM)
2049        .align_x(Alignment::Center);
2050        if state.is_filtered() {
2051            content = content.push(
2052                button("Clear filters")
2053                    .variant(button::Variant::Outline)
2054                    .size(button::Size::Sm)
2055                    .on_press_maybe(self.send(Event::ClearFilters)),
2056            );
2057        }
2058        container(content)
2059            .padding(space::XL)
2060            .center_x(Length::Fill)
2061            .into()
2062    }
2063
2064    /// The card height for the visible columns: the first column heads the
2065    /// card, and each other column is a labelled line.
2066    fn card_height(&self) -> f32 {
2067        let lines = self.state.visible_columns().len().max(1);
2068        CARD_PADDING * 2.0 + lines as f32 * CARD_LINE
2069    }
2070
2071    fn cards(self: &Rc<Self>) -> Element<'a, Message> {
2072        let state = self.state;
2073        let has_rows = !self.loading && !state.page_range().is_empty();
2074        let mut bar = row![].spacing(space::MD).align_y(Alignment::Center);
2075        if state.is_selectable() {
2076            let on_event = self.on_event.clone().filter(|_| has_rows);
2077            bar = bar.push(
2078                checkbox(state.page_check_state())
2079                    .label("Select all")
2080                    .on_toggle_maybe(
2081                        on_event
2082                            .map(|on_event| move |checked| on_event(Event::SelectPage(checked))),
2083                    ),
2084            );
2085        }
2086        if has_rows {
2087            bar = bar.push(self.sort_select());
2088        }
2089
2090        let body: Element<'a, Message> = if self.loading {
2091            widget::column((0..SKELETON_ROWS).map(|_| self.skeleton_card()))
2092                .spacing(CARD_GAP)
2093                .into()
2094        } else if state.page_range().is_empty() {
2095            container(self.empty_view())
2096                .style(|theme| frame_style(&Tokens::of(theme)))
2097                .into()
2098        } else {
2099            let page = state.page_indices();
2100            let count = page.len();
2101            let view = Rc::clone(self);
2102            let height = self.card_height();
2103            rows(count, height + CARD_GAP, move |range: Range<usize>| {
2104                widget::column(
2105                    page.get(range)
2106                        .unwrap_or_default()
2107                        .iter()
2108                        .map(|&index| view.card(index, height)),
2109                )
2110                .into()
2111            })
2112            .highlight(self.highlight_position())
2113            .height(self.height)
2114            .into()
2115        };
2116        if !state.is_selectable() && !has_rows {
2117            return body;
2118        }
2119        widget::column![bar, body].spacing(space::SM).into()
2120    }
2121
2122    fn sort_select(&self) -> Element<'a, Message> {
2123        let state = self.state;
2124        let mut options = vec![SortChoice {
2125            sort: None,
2126            label: "Default order".to_owned(),
2127        }];
2128        for column in state
2129            .visible_columns()
2130            .into_iter()
2131            .filter(|column| column.sortable)
2132        {
2133            for direction in Direction::ALL {
2134                let way = match direction {
2135                    Direction::Ascending => "ascending",
2136                    Direction::Descending => "descending",
2137                };
2138                options.push(SortChoice {
2139                    sort: Some((column.id, direction)),
2140                    label: format!("{}, {way}", column.header),
2141                });
2142            }
2143        }
2144        let selected = options
2145            .iter()
2146            .find(|choice| choice.sort == state.sort())
2147            .cloned();
2148        let on_event = self.on_event.clone();
2149        select(options, selected)
2150            .width(Length::Fill)
2151            .on_select_maybe(
2152                on_event
2153                    .map(|on_event| move |choice: SortChoice| on_event(Event::SortBy(choice.sort))),
2154            )
2155            .into()
2156    }
2157
2158    fn card(&self, index: usize, height: f32) -> Element<'a, Message> {
2159        let state = self.state;
2160        let Some(row_data) = state.rows.get(index) else {
2161            return Space::new().into();
2162        };
2163        let key = state.key(row_data);
2164        let columns = state.visible_columns();
2165        let mut lines = widget::column![];
2166
2167        let mut head = row![].spacing(space::SM).align_y(Alignment::Center);
2168        if state.is_selectable() {
2169            head = head.push(self.checkbox_for(&key));
2170        }
2171        if let Some(first) = columns.first() {
2172            let title: Element<'a, Message> =
2173                match self.cells.iter().find(|(id, _)| *id == first.id) {
2174                    Some((_, render)) => container(render(row_data)).width(Length::Fill).into(),
2175                    None => ellipsis(first.text(row_data)).font(semibold()).into(),
2176                };
2177            head = head.push(title);
2178        }
2179        if self.row_actions {
2180            head = head.push(self.actions_for(&key));
2181        }
2182        lines = lines.push(container(head).height(CARD_LINE).center_y(CARD_LINE));
2183
2184        for column in columns.iter().skip(1) {
2185            let label = ellipsis(column.header.clone())
2186                .colour(muted)
2187                .width(Length::FillPortion(2));
2188            let value = container(self.content_for(column, row_data, Horizontal::Right))
2189                .width(Length::FillPortion(3))
2190                .align_x(Horizontal::Right);
2191            lines = lines.push(
2192                container(
2193                    row![label, value]
2194                        .spacing(space::SM)
2195                        .align_y(Alignment::Center),
2196                )
2197                .height(CARD_LINE)
2198                .center_y(CARD_LINE),
2199            );
2200        }
2201
2202        let status = self.row_status(&key);
2203        let card = pressable(
2204            container(lines).padding(CARD_PADDING).height(height),
2205            move |theme, hovered| {
2206                let tokens = Tokens::of(theme);
2207                let style = row_style(&tokens, Status { hovered, ..status });
2208                Look {
2209                    background: style.background,
2210                    border: Border {
2211                        color: style.ring.unwrap_or(tokens.border),
2212                        width: 1.0,
2213                        radius: radius::MD.into(),
2214                    },
2215                    divider: None,
2216                }
2217            },
2218        );
2219        let card = self.finish_row(card, key);
2220        container(card)
2221            .padding(Padding::ZERO.bottom(CARD_GAP))
2222            .into()
2223    }
2224
2225    fn skeleton_card(&self) -> Element<'a, Message> {
2226        let lines = widget::column((0..self.state.visible_columns().len().max(1)).map(|_| {
2227            container(
2228                container(Space::new())
2229                    .width(Length::Fill)
2230                    .height(12)
2231                    .style(|theme| skeleton_style(&Tokens::of(theme))),
2232            )
2233            .height(CARD_LINE)
2234            .center_y(CARD_LINE)
2235            .into()
2236        }));
2237        container(lines)
2238            .padding(CARD_PADDING)
2239            .width(Length::Fill)
2240            .style(|theme| frame_style(&Tokens::of(theme)))
2241            .into()
2242    }
2243
2244    fn footer(&self, narrow: bool) -> Element<'a, Message> {
2245        let state = self.state;
2246        let mut summary = state.showing();
2247        if state.is_selectable() {
2248            summary.push_str(&format!(", {} selected", state.selected.len()));
2249        }
2250        let summary = small(summary);
2251
2252        let on_event = self.on_event.clone().filter(|_| !self.loading);
2253        let sizes = select(state.page_sizes().to_vec(), Some(state.page_size()))
2254            .width(80)
2255            .on_select_maybe(on_event.map(|on_event| move |size| on_event(Event::PageSize(size))));
2256        let has_previous = state.page() > 0;
2257        let has_next = state.page() + 1 < state.page_count();
2258        let pager = row![
2259            small(format!(
2260                "Page {} of {}",
2261                state.page() + 1,
2262                state.page_count()
2263            )),
2264            icon_button(crate::lucide!(ChevronLeft))
2265                .label("Previous page")
2266                .variant(crate::primitives::icon_button::Variant::Outline)
2267                .size(button::Size::Sm)
2268                .on_press_maybe(
2269                    self.send(Event::PreviousPage)
2270                        .filter(|_| has_previous && !self.loading)
2271                ),
2272            icon_button(crate::lucide!(ChevronRight))
2273                .label("Next page")
2274                .variant(crate::primitives::icon_button::Variant::Outline)
2275                .size(button::Size::Sm)
2276                .on_press_maybe(
2277                    self.send(Event::NextPage)
2278                        .filter(|_| has_next && !self.loading)
2279                ),
2280        ]
2281        .spacing(space::SM)
2282        .align_y(Alignment::Center);
2283
2284        if narrow {
2285            return widget::column![
2286                summary,
2287                row![sizes, spacer::horizontal(), pager].align_y(Alignment::Center),
2288            ]
2289            .spacing(space::SM)
2290            .into();
2291        }
2292        row![
2293            summary,
2294            spacer::horizontal(),
2295            small("Rows per page"),
2296            sizes,
2297            pager,
2298        ]
2299        .spacing(space::MD)
2300        .align_y(Alignment::Center)
2301        .into()
2302    }
2303}
2304
2305/// An option in a column filter's select.
2306#[derive(Debug, Clone, PartialEq)]
2307struct FilterChoice {
2308    column: ColumnId,
2309    header: String,
2310    value: Option<String>,
2311}
2312
2313impl fmt::Display for FilterChoice {
2314    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2315        match &self.value {
2316            Some(value) => write!(f, "{}: {value}", self.header),
2317            None => write!(f, "{}: All", self.header),
2318        }
2319    }
2320}
2321
2322/// An option in the sort select shown above cards.
2323#[derive(Debug, Clone, PartialEq)]
2324struct SortChoice {
2325    sort: Option<(ColumnId, Direction)>,
2326    label: String,
2327}
2328
2329impl fmt::Display for SortChoice {
2330    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2331        f.write_str(&self.label)
2332    }
2333}
2334
2335#[cfg(test)]
2336mod tests {
2337    use super::*;
2338    use crate::theme::{dark, light};
2339    use iced::keyboard::{Key, Modifiers};
2340
2341    #[derive(Debug, Clone, PartialEq)]
2342    struct Payment {
2343        id: u32,
2344        status: &'static str,
2345        email: String,
2346        amount: Option<f64>,
2347    }
2348
2349    fn payment(id: u32, status: &'static str, email: &str, amount: f64) -> Payment {
2350        Payment {
2351            id,
2352            status,
2353            email: email.to_owned(),
2354            amount: Some(amount),
2355        }
2356    }
2357
2358    fn columns() -> Vec<Column<Payment>> {
2359        vec![
2360            column("status", "Status", |p: &Payment| p.status.into()).filterable(true),
2361            column("email", "Email", |p: &Payment| p.email.clone().into()),
2362            column("amount", "Amount", |p: &Payment| p.amount.into())
2363                .align(Align::End)
2364                .format(|p| {
2365                    p.amount
2366                        .map_or_else(String::new, |amount| format!("${amount:.2}"))
2367                }),
2368            column("id", "ID", |p: &Payment| p.id.into())
2369                .sortable(false)
2370                .hideable(false),
2371        ]
2372    }
2373
2374    fn payments(count: u32) -> Vec<Payment> {
2375        (1..=count)
2376            .map(|id| {
2377                let status = ["paid", "pending", "failed"][(id % 3) as usize];
2378                payment(
2379                    id,
2380                    status,
2381                    &format!("user{id}@example.com"),
2382                    f64::from(id * 10),
2383                )
2384            })
2385            .collect()
2386    }
2387
2388    fn state(count: u32) -> State<Payment, u32> {
2389        State::new(columns(), payments(count), |p| p.id)
2390    }
2391
2392    fn ids(rows: Vec<&Payment>) -> Vec<u32> {
2393        rows.into_iter().map(|p| p.id).collect()
2394    }
2395
2396    fn selected(output: Option<Output<u32>>) -> Vec<u32> {
2397        match output {
2398            Some(Output::Selected(keys)) => keys,
2399            other => panic!("expected a selection, got {other:?}"),
2400        }
2401    }
2402
2403    #[test]
2404    fn values_display_and_convert() {
2405        assert_eq!(Value::from(12.0).to_string(), "12");
2406        assert_eq!(Value::from(12.5).to_string(), "12.5");
2407        assert_eq!(Value::from(7_u32), Value::Number(7.0));
2408        assert_eq!(Value::from("a"), Value::Text("a".into()));
2409        assert_eq!(Value::from(None::<f64>), Value::Empty);
2410        assert_eq!(Value::from(Some(3_i64)), Value::Number(3.0));
2411        assert_eq!(Value::Empty.to_string(), "");
2412        assert_eq!(Value::default(), Value::Empty);
2413    }
2414
2415    #[test]
2416    fn compare_orders_numbers_then_text_then_empty() {
2417        let mut values = vec![
2418            Value::from("banana"),
2419            Value::Empty,
2420            Value::from(10.0),
2421            Value::from("Apple"),
2422            Value::from(2.0),
2423            Value::from("apple"),
2424        ];
2425        values.sort_by(compare);
2426        assert_eq!(
2427            values,
2428            vec![
2429                Value::from(2.0),
2430                Value::from(10.0),
2431                Value::from("Apple"),
2432                Value::from("apple"),
2433                Value::from("banana"),
2434                Value::Empty,
2435            ]
2436        );
2437    }
2438
2439    #[test]
2440    fn starts_unsorted_on_the_first_page() {
2441        let state = state(23);
2442        assert_eq!(state.len(), 23);
2443        assert_eq!(state.filtered_len(), 23);
2444        assert_eq!(state.page(), 0);
2445        assert_eq!(state.page_size(), 10);
2446        assert_eq!(state.page_count(), 3);
2447        assert_eq!(state.page_range(), 0..10);
2448        assert_eq!(ids(state.page_rows()), (1..=10).collect::<Vec<_>>());
2449        assert_eq!(state.showing(), "Showing 1-10 of 23");
2450        assert_eq!(state.sort(), None);
2451        assert!(!state.is_selectable());
2452        assert!(!state.is_filtered());
2453    }
2454
2455    #[test]
2456    fn an_empty_table_has_one_empty_page() {
2457        let state = state(0);
2458        assert!(state.is_empty());
2459        assert_eq!(state.page_count(), 1);
2460        assert_eq!(state.page_range(), 0..0);
2461        assert_eq!(state.showing(), "Showing 0 of 0");
2462        assert_eq!(state.page_check_state(), CheckState::Unchecked);
2463    }
2464
2465    #[test]
2466    fn header_presses_cycle_ascending_descending_and_unsorted() {
2467        let mut state = state(5).with_page_sizes([5]);
2468        let _ = state.update(Event::Sort("amount"));
2469        assert_eq!(state.sort(), Some(("amount", Direction::Ascending)));
2470        assert_eq!(ids(state.page_rows()), [1, 2, 3, 4, 5]);
2471        let _ = state.update(Event::Sort("amount"));
2472        assert_eq!(state.sort(), Some(("amount", Direction::Descending)));
2473        assert_eq!(ids(state.page_rows()), [5, 4, 3, 2, 1]);
2474        let _ = state.update(Event::Sort("amount"));
2475        assert_eq!(state.sort(), None);
2476        assert_eq!(ids(state.page_rows()), [1, 2, 3, 4, 5]);
2477        let _ = state.update(Event::Sort("email"));
2478        assert_eq!(state.sort(), Some(("email", Direction::Ascending)));
2479    }
2480
2481    #[test]
2482    fn unsortable_and_unknown_columns_are_ignored() {
2483        let mut state = state(5).with_sort("amount", Direction::Descending);
2484        let _ = state.update(Event::Sort("id"));
2485        let _ = state.update(Event::SortBy(Some(("missing", Direction::Ascending))));
2486        assert_eq!(state.sort(), Some(("amount", Direction::Descending)));
2487        let _ = state.update(Event::SortBy(None));
2488        assert_eq!(state.sort(), None);
2489    }
2490
2491    #[test]
2492    fn empty_values_sort_last_both_ways() {
2493        let mut rows = payments(3);
2494        rows[1].amount = None;
2495        let mut state = State::new(columns(), rows, |p| p.id);
2496        let _ = state.update(Event::SortBy(Some(("amount", Direction::Ascending))));
2497        assert_eq!(ids(state.page_rows()), [1, 3, 2]);
2498        let _ = state.update(Event::SortBy(Some(("amount", Direction::Descending))));
2499        assert_eq!(ids(state.page_rows()), [3, 1, 2]);
2500    }
2501
2502    #[test]
2503    fn search_matches_visible_searchable_text_ignoring_case() {
2504        let mut state = state(23);
2505        let _ = state.update(Event::NextPage);
2506        let _ = state.update(Event::Search("USER2".into()));
2507        assert_eq!(state.page(), 0, "a new search starts on the first page");
2508        assert_eq!(ids(state.page_rows()), [2, 20, 21, 22, 23]);
2509        let _ = state.update(Event::Search("$30.00".into()));
2510        assert_eq!(ids(state.page_rows()), [3], "searches the formatted text");
2511        let _ = state.update(Event::Columns(dropdown_menu::Event::Activate("amount")));
2512        assert!(state.is_hidden("amount"));
2513        assert_eq!(state.filtered_len(), 0, "hidden columns are not searched");
2514        assert!(state.is_filtered());
2515    }
2516
2517    #[test]
2518    fn column_filters_offer_distinct_values_and_combine_with_search() {
2519        let mut state = state(9);
2520        assert_eq!(state.options("status"), ["failed", "paid", "pending"]);
2521        assert!(state.options("email").is_empty());
2522        let _ = state.update(Event::Filter("status", Some("paid".into())));
2523        assert_eq!(state.filter("status"), Some("paid"));
2524        assert_eq!(ids(state.page_rows()), [3, 6, 9]);
2525        let _ = state.update(Event::Search("user9".into()));
2526        assert_eq!(ids(state.page_rows()), [9]);
2527        let _ = state.update(Event::Filter("status", None));
2528        assert_eq!(ids(state.page_rows()), [9]);
2529        let _ = state.update(Event::Filter("status", Some("paid".into())));
2530        let _ = state.update(Event::ClearFilters);
2531        assert_eq!(state.filtered_len(), 9);
2532        assert_eq!(state.search(), "");
2533        assert_eq!(state.filter("status"), None);
2534        let _ = state.update(Event::Filter("missing", Some("x".into())));
2535        assert!(!state.is_filtered(), "unknown columns are not filtered");
2536    }
2537
2538    #[test]
2539    fn pages_clamp_and_page_size_keeps_the_first_row_in_view() {
2540        let mut state = state(23);
2541        let _ = state.update(Event::PreviousPage);
2542        assert_eq!(state.page(), 0);
2543        let _ = state.update(Event::Page(9));
2544        assert_eq!(state.page(), 2);
2545        assert_eq!(state.showing(), "Showing 21-23 of 23");
2546        let _ = state.update(Event::NextPage);
2547        assert_eq!(state.page(), 2);
2548        let _ = state.update(Event::Page(1));
2549        let _ = state.update(Event::PageSize(20));
2550        assert_eq!(state.page(), 0, "row 11 is on the first page of 20");
2551        let _ = state.update(Event::PageSize(5));
2552        assert_eq!(state.page(), 0);
2553        let _ = state.update(Event::Page(3));
2554        let _ = state.update(Event::PageSize(0));
2555        assert_eq!(state.page_size(), 1, "at least one row a page");
2556        assert_eq!(state.page(), 15);
2557    }
2558
2559    #[test]
2560    fn page_sizes_can_be_set() {
2561        let state = state(23).with_page_sizes([0, 5, 25]);
2562        assert_eq!(state.page_sizes(), [5, 25]);
2563        assert_eq!(state.page_size(), 5);
2564        assert_eq!(state.page_count(), 5);
2565        let unchanged = self::state(3).with_page_sizes([]);
2566        assert_eq!(unchanged.page_sizes(), PAGE_SIZES);
2567    }
2568
2569    #[test]
2570    fn selection_needs_a_selectable_table() {
2571        let mut state = state(5);
2572        assert!(state.update(Event::Select(1, true)).is_none());
2573        assert!(state.selected().is_empty());
2574    }
2575
2576    #[test]
2577    fn rows_select_and_the_header_acts_on_the_page_only() {
2578        let mut state = state(23).with_selection(true);
2579        assert_eq!(selected(state.update(Event::Select(2, true))), [2]);
2580        assert_eq!(state.page_check_state(), CheckState::Indeterminate);
2581        assert!(state.update(Event::Select(2, true)).is_none(), "no change");
2582        assert!(
2583            state.update(Event::Select(99, true)).is_none(),
2584            "unknown row"
2585        );
2586
2587        let _ = state.update(Event::NextPage);
2588        assert_eq!(state.page_check_state(), CheckState::Unchecked);
2589        assert_eq!(
2590            selected(state.update(Event::SelectPage(true))),
2591            [2, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
2592        );
2593        assert_eq!(state.page_check_state(), CheckState::Checked);
2594        assert_eq!(selected(state.update(Event::SelectPage(false))), [2]);
2595        assert_eq!(
2596            selected(state.update(Event::ClearSelection)),
2597            Vec::<u32>::new()
2598        );
2599        assert!(state.update(Event::ClearSelection).is_none());
2600    }
2601
2602    #[test]
2603    fn selection_follows_keys_through_sorting_and_row_changes() {
2604        let mut state = state(5).with_selection(true);
2605        let _ = state.update(Event::Select(1, true));
2606        let _ = state.update(Event::Select(4, true));
2607        let _ = state.update(Event::Sort("amount"));
2608        let _ = state.update(Event::Sort("amount"));
2609        assert!(state.is_selected(&1) && state.is_selected(&4));
2610        state.retain(|p| p.id != 4);
2611        assert_eq!(state.selected(), [1]);
2612        state.update_row(&1, |p| p.status = "failed");
2613        assert_eq!(state.row(&1).map(|p| p.status), Some("failed"));
2614        state.push(payment(6, "paid", "new@example.com", 5.0));
2615        assert_eq!(state.len(), 5);
2616        assert_eq!(ids(state.page_rows()), [5, 3, 2, 1, 6], "sorted into place");
2617        state.set_rows(payments(2));
2618        assert_eq!(state.selected(), [1]);
2619    }
2620
2621    #[test]
2622    fn arrows_move_through_the_page_and_across_pages() {
2623        let mut state = state(23);
2624        let _ = state.update(Event::Next);
2625        assert_eq!(state.highlighted(), Some(&1));
2626        let _ = state.update(Event::Last);
2627        assert_eq!(state.highlighted(), Some(&10));
2628        let _ = state.update(Event::Next);
2629        assert_eq!(state.page(), 1);
2630        assert_eq!(state.highlighted(), Some(&11));
2631        let _ = state.update(Event::Previous);
2632        assert_eq!(state.page(), 0);
2633        assert_eq!(state.highlighted(), Some(&10));
2634        let _ = state.update(Event::First);
2635        let _ = state.update(Event::Previous);
2636        assert_eq!(state.highlighted(), Some(&1), "stays at the very first row");
2637        let _ = state.update(Event::Page(2));
2638        let _ = state.update(Event::Last);
2639        let _ = state.update(Event::Next);
2640        assert_eq!(state.highlighted(), Some(&23), "stays at the very last row");
2641
2642        let mut fresh = self::state(23);
2643        let _ = fresh.update(Event::Previous);
2644        assert_eq!(fresh.highlighted(), Some(&10));
2645    }
2646
2647    #[test]
2648    fn changing_page_moves_the_highlight_onto_it() {
2649        let mut state = state(23);
2650        let _ = state.update(Event::Press(3));
2651        let _ = state.update(Event::NextPage);
2652        assert_eq!(state.highlighted(), Some(&11));
2653        let _ = state.update(Event::Press(3));
2654        assert_eq!(
2655            state.highlighted(),
2656            Some(&11),
2657            "rows on other pages are ignored"
2658        );
2659        let _ = state.update(Event::Search("zzz".into()));
2660        assert_eq!(state.highlighted(), None);
2661    }
2662
2663    #[test]
2664    fn space_toggles_and_enter_activates_the_highlighted_row() {
2665        let mut state = state(5).with_selection(true);
2666        assert!(state.update(Event::ToggleHighlighted).is_none());
2667        assert!(state.update(Event::ActivateHighlighted).is_none());
2668        let _ = state.update(Event::Press(2));
2669        assert_eq!(selected(state.update(Event::ToggleHighlighted)), [2]);
2670        assert_eq!(
2671            selected(state.update(Event::ToggleHighlighted)),
2672            Vec::<u32>::new()
2673        );
2674        assert_eq!(
2675            state.update(Event::ActivateHighlighted),
2676            Some(Output::Activated(2))
2677        );
2678        assert_eq!(state.update(Event::Activate(4)), Some(Output::Activated(4)));
2679        assert_eq!(state.highlighted(), Some(&4));
2680        assert!(state.update(Event::Activate(40)).is_none());
2681    }
2682
2683    #[test]
2684    fn the_columns_menu_hides_columns_but_never_the_last() {
2685        let mut state = state(3);
2686        let menu: Vec<ColumnId> = state
2687            .columns_menu()
2688            .entries()
2689            .iter()
2690            .filter_map(|entry| entry.as_item().map(|item| item.id))
2691            .collect();
2692        assert_eq!(menu, ["status", "email", "amount"], "ID is not hideable");
2693        let _ = state.update(Event::Columns(dropdown_menu::Event::Open));
2694        let _ = state.update(Event::Columns(dropdown_menu::Event::Activate("email")));
2695        assert!(state.is_hidden("email"));
2696        assert!(!state.columns_menu().is_checked("email"));
2697        assert_eq!(state.visible_columns().len(), 3);
2698        let _ = state.update(Event::Columns(dropdown_menu::Event::Activate("email")));
2699        assert!(!state.is_hidden("email"));
2700
2701        let mut single = State::new(
2702            [column("name", "Name", |p: &Payment| p.email.clone().into())],
2703            payments(1),
2704            |p| p.id,
2705        );
2706        let _ = single.update(Event::Columns(dropdown_menu::Event::Activate("name")));
2707        assert!(!single.is_hidden("name"));
2708        assert!(single.columns_menu().is_checked("name"));
2709    }
2710
2711    #[test]
2712    fn with_hidden_starts_with_columns_hidden() {
2713        let state = state(3).with_hidden(["email"]);
2714        assert!(state.is_hidden("email"));
2715        assert!(!state.columns_menu().is_checked("email"));
2716        assert!(state.columns_menu().is_checked("status"));
2717        let visible: Vec<ColumnId> = state.visible_columns().iter().map(|c| c.id).collect();
2718        assert_eq!(visible, ["status", "amount", "id"]);
2719    }
2720
2721    #[test]
2722    fn focus_is_tracked_and_lands_on_a_row() {
2723        let mut state = state(3);
2724        let _ = state.update(Event::Focus(true));
2725        assert!(state.is_focused());
2726        assert_eq!(state.highlighted(), Some(&1));
2727
2728        let mut selected = self::state(3).with_selection(true);
2729        let _ = selected.update(Event::Select(2, true));
2730        let _ = selected.update(Event::Focus(true));
2731        assert_eq!(selected.highlighted(), Some(&2), "the first selected row");
2732        let _ = selected.update(Event::Focus(false));
2733        assert!(!selected.is_focused());
2734
2735        let empty = &mut self::state(0);
2736        let _ = empty.update(Event::Focus(true));
2737        assert_eq!(empty.highlighted(), None);
2738    }
2739
2740    #[test]
2741    fn columns_read_and_format_cells() {
2742        let columns = columns();
2743        let row = payment(7, "paid", "a@b.c", 12.5);
2744        assert_eq!(columns[2].value(&row), Value::Number(12.5));
2745        assert_eq!(columns[2].text(&row), "$12.50");
2746        assert_eq!(columns[0].text(&row), "paid");
2747        let column = columns[0]
2748            .clone()
2749            .width(120)
2750            .align(Align::Center)
2751            .searchable(false);
2752        assert_eq!(column.width, Length::Fixed(120.0));
2753        assert_eq!(column.align, Align::Center);
2754        assert!(!column.searchable);
2755        assert!(format!("{column:?}").contains("status"));
2756        assert_eq!(Align::ALL.len(), 3);
2757        assert_eq!(Direction::ALL.len(), 2);
2758    }
2759
2760    fn press(keymap: &Keymap<Action>, chord: &str) -> Option<Action> {
2761        let chord: Chord = chord.parse().unwrap();
2762        keymap.resolve(chord.key(), chord.modifiers())
2763    }
2764
2765    #[test]
2766    fn default_keymap_covers_every_action() {
2767        let keymap = default_keymap();
2768        assert_eq!(press(&keymap, "ArrowDown"), Some(Action::Next));
2769        assert_eq!(press(&keymap, "ArrowUp"), Some(Action::Previous));
2770        assert_eq!(press(&keymap, "Home"), Some(Action::First));
2771        assert_eq!(press(&keymap, "End"), Some(Action::Last));
2772        assert_eq!(press(&keymap, "PageDown"), Some(Action::NextPage));
2773        assert_eq!(press(&keymap, "PageUp"), Some(Action::PreviousPage));
2774        assert_eq!(press(&keymap, "Space"), Some(Action::Select));
2775        assert_eq!(press(&keymap, "Enter"), Some(Action::Activate));
2776        assert_eq!(press(&keymap, "Mod+A"), Some(Action::SelectAll));
2777        assert_eq!(press(&keymap, "Escape"), Some(Action::ClearSelection));
2778        for action in <Action as keys::Action>::ALL {
2779            assert!(!keymap.chords(action).is_empty(), "{action:?}");
2780            assert!(keys::Action::description(*action).ends_with('.'));
2781        }
2782        assert_eq!(Keymap::<Action>::defaults(), keymap);
2783    }
2784
2785    #[test]
2786    fn keymap_overrides_and_unbinding() {
2787        let keymap = default_keymap()
2788            .unbind(&Chord::named(Named::Escape))
2789            .bind(Chord::character('j'), Action::Next);
2790        let mut state = state(5).with_selection(true);
2791        let _ = state.update(Event::Select(1, true));
2792        let escape = keys::Event {
2793            key: Key::Named(Named::Escape),
2794            modifiers: Modifiers::empty(),
2795        };
2796        assert_eq!(state.key_event(&keymap, &escape), None);
2797        let j = keys::Event {
2798            key: Key::Character("j".into()),
2799            modifiers: Modifiers::empty(),
2800        };
2801        assert_eq!(state.key_event(&keymap, &j), Some(Event::Next));
2802        assert!(default_keymap().clear().is_empty());
2803    }
2804
2805    #[test]
2806    fn actions_map_to_events_only_when_they_apply() {
2807        let mut state = state(23);
2808        assert_eq!(Action::Next.event(&state), Some(Event::Next));
2809        assert_eq!(Action::PreviousPage.event(&state), None);
2810        assert_eq!(Action::NextPage.event(&state), Some(Event::NextPage));
2811        assert_eq!(Action::Activate.event(&state), None);
2812        assert_eq!(Action::Select.event(&state), None, "not selectable");
2813        assert_eq!(Action::SelectAll.event(&state), None);
2814        let _ = state.update(Event::First);
2815        assert_eq!(
2816            Action::Activate.event(&state),
2817            Some(Event::ActivateHighlighted)
2818        );
2819
2820        let mut selectable = self::state(3).with_selection(true);
2821        assert_eq!(
2822            Action::SelectAll.event(&selectable),
2823            Some(Event::SelectPage(true))
2824        );
2825        assert_eq!(
2826            Action::ClearSelection.event(&selectable),
2827            None,
2828            "nothing selected"
2829        );
2830        let _ = selectable.update(Event::SelectPage(true));
2831        assert_eq!(
2832            Action::ClearSelection.event(&selectable),
2833            Some(Event::ClearSelection)
2834        );
2835        let _ = selectable.update(Event::First);
2836        assert_eq!(
2837            Action::Select.event(&selectable),
2838            Some(Event::ToggleHighlighted)
2839        );
2840
2841        let empty = self::state(0);
2842        for action in [Action::Next, Action::Previous, Action::First, Action::Last] {
2843            assert_eq!(action.event(&empty), None, "{action:?}");
2844        }
2845    }
2846
2847    #[test]
2848    fn rows_are_muted_when_selected_and_ringed_when_highlighted() {
2849        for theme in [light(), dark()] {
2850            let tokens = Tokens::of(&theme);
2851            let idle = row_style(&tokens, Status::default());
2852            assert_eq!(idle.background, None);
2853            assert_eq!(idle.ring, None);
2854            assert_eq!(idle.divider, tokens.border);
2855            let selected = row_style(
2856                &tokens,
2857                Status {
2858                    selected: true,
2859                    hovered: true,
2860                    ..Status::default()
2861                },
2862            );
2863            assert_eq!(selected.background, Some(tokens.muted));
2864            let hovered = row_style(
2865                &tokens,
2866                Status {
2867                    hovered: true,
2868                    ..Status::default()
2869                },
2870            );
2871            assert_eq!(hovered.background, Some(fade(tokens.muted, 0.5)));
2872            let highlighted = row_style(
2873                &tokens,
2874                Status {
2875                    highlighted: true,
2876                    ..Status::default()
2877                },
2878            );
2879            assert_eq!(highlighted.ring, Some(tokens.ring));
2880
2881            let frame = frame_style(&tokens);
2882            assert_eq!(frame.border.color, tokens.border);
2883            assert_eq!(frame.border.radius, radius::MD.into());
2884            assert_eq!(
2885                skeleton_style(&tokens).background,
2886                Some(Background::Color(tokens.muted))
2887            );
2888        }
2889    }
2890
2891    #[test]
2892    fn sort_indicators_show_the_direction() {
2893        assert_eq!(sort_glyph(None), crate::lucide!(ArrowUpDown));
2894        assert_eq!(
2895            sort_glyph(Some(Direction::Ascending)),
2896            crate::lucide!(ArrowUp)
2897        );
2898        assert_eq!(
2899            sort_glyph(Some(Direction::Descending)),
2900            crate::lucide!(ArrowDown)
2901        );
2902    }
2903
2904    #[test]
2905    fn filter_and_sort_choices_read_well() {
2906        let all = FilterChoice {
2907            column: "status",
2908            header: "Status".into(),
2909            value: None,
2910        };
2911        assert_eq!(all.to_string(), "Status: All");
2912        let paid = FilterChoice {
2913            value: Some("paid".into()),
2914            ..all
2915        };
2916        assert_eq!(paid.to_string(), "Status: paid");
2917        let sort = SortChoice {
2918            sort: None,
2919            label: "Default order".into(),
2920        };
2921        assert_eq!(sort.to_string(), "Default order");
2922    }
2923
2924    #[test]
2925    fn resizing_sets_widths_and_a_reset_restores_the_declared_one() {
2926        let mut state = state(3);
2927        assert_eq!(state.width("email"), None);
2928        let _ = state.update(Event::Resize(vec![("status", 120.0), ("email", 300.0)]));
2929        assert_eq!(state.width("status"), Some(120.0));
2930        assert_eq!(state.width("email"), Some(300.0));
2931        let _ = state.update(Event::Resize(vec![("email", 5.0)]));
2932        assert_eq!(
2933            state.width("email"),
2934            Some(MIN_COLUMN_WIDTH),
2935            "never narrower than the minimum"
2936        );
2937        let _ = state.update(Event::Resize(vec![("missing", 90.0), ("id", f32::NAN)]));
2938        assert_eq!(state.width("missing"), None);
2939        assert_eq!(state.width("id"), None);
2940        let _ = state.update(Event::ResetWidth("email"));
2941        assert_eq!(state.width("email"), None);
2942        assert_eq!(
2943            state.width("status"),
2944            None,
2945            "a column only held beside the drag goes back with it"
2946        );
2947        assert_eq!(state.with_width("id", 64.0).width("id"), Some(64.0));
2948    }
2949
2950    #[test]
2951    fn held_columns_stay_while_a_resized_column_remains() {
2952        let mut state = state(3);
2953        let _ = state.update(Event::Resize(vec![("status", 120.0), ("email", 300.0)]));
2954        let _ = state.update(Event::Resize(vec![("status", 150.0)]));
2955        let _ = state.update(Event::ResetWidth("email"));
2956        assert_eq!(
2957            state.width("status"),
2958            Some(150.0),
2959            "the reader resized it since"
2960        );
2961
2962        let _ = state.update(Event::Resize(vec![
2963            ("status", 150.0),
2964            ("email", 200.0),
2965            ("amount", 90.0),
2966        ]));
2967        let _ = state.update(Event::ResetWidth("status"));
2968        assert_eq!(state.width("email"), Some(200.0), "amount is still resized");
2969        let _ = state.update(Event::ResetWidth("amount"));
2970        assert_eq!(state.width("email"), None);
2971    }
2972
2973    #[test]
2974    fn dragged_columns_keep_their_width_and_the_rest_share_the_room() {
2975        let state = state(3)
2976            .with_width("status", 120.0)
2977            .with_width("email", 300.0);
2978        assert_eq!(
2979            state.lengths(800.0),
2980            [
2981                Length::Fixed(120.0),
2982                Length::Fixed(300.0),
2983                Length::FillPortion(1),
2984                Length::FillPortion(1),
2985            ]
2986        );
2987    }
2988
2989    #[test]
2990    fn dragged_columns_shrink_together_when_the_table_narrows() {
2991        let state = state(3)
2992            .with_width("status", 200.0)
2993            .with_width("email", 400.0);
2994        // 600 dragged and two flexing columns at the minimum need 680.
2995        assert_eq!(
2996            state.lengths(380.0),
2997            [
2998                Length::Fixed(100.0),
2999                Length::Fixed(200.0),
3000                Length::FillPortion(1),
3001                Length::FillPortion(1),
3002            ]
3003        );
3004        let lengths = state.lengths(100.0);
3005        assert_eq!(lengths[0], Length::Fixed(MIN_COLUMN_WIDTH));
3006        assert_eq!(lengths[1], Length::Fixed(MIN_COLUMN_WIDTH));
3007    }
3008
3009    #[test]
3010    fn hidden_columns_take_no_room() {
3011        let state = state(3).with_width("status", 200.0).with_hidden(["status"]);
3012        assert_eq!(state.lengths(300.0), [Length::FillPortion(1); 3]);
3013    }
3014
3015    #[test]
3016    fn builder_defaults_and_options() {
3017        let state = state(3);
3018        let table: DataTable<'_, Payment, u32, ()> = data_table(&state);
3019        assert!(table.toolbar && !table.loading && !table.row_actions);
3020        assert!(!table.is_enabled());
3021        assert_eq!(table.height, Length::Shrink);
3022        assert_eq!(table.breakpoint, BREAKPOINT);
3023        assert_eq!(table.keymap, default_keymap());
3024        assert_eq!(table.empty, "No results.");
3025        let table = table
3026            .toolbar(false)
3027            .loading(true)
3028            .empty("Nothing here")
3029            .placeholder("Filter emails...")
3030            .height(300)
3031            .row_height(32.0)
3032            .breakpoint(400.0)
3033            .keymap(Keymap::new())
3034            .row_actions(true)
3035            .cell("status", |p: &Payment| text(p.status).into())
3036            .cell("status", |p: &Payment| text(p.status).into())
3037            .on_event(|_| ());
3038        assert!(!table.toolbar && table.loading && table.row_actions);
3039        assert_eq!(table.cells.len(), 1, "a second renderer replaces the first");
3040        assert_eq!(table.placeholder, "Filter emails...");
3041        assert_eq!(table.height, Length::Fixed(300.0));
3042        assert_eq!(table.row_height, 32.0);
3043        assert!(table.is_enabled());
3044        assert!(format!("{table:?}").contains("DataTable"));
3045    }
3046}