Skip to main content

lumen_dioxus/data/data_table/
mod.rs

1//! `DataTable`, its sort controls, `DataTableView`, saved views, and column layout controls.
2
3mod layout;
4mod model;
5mod saved;
6mod view;
7
8pub use layout::*;
9pub use model::*;
10pub use saved::*;
11pub use view::*;
12
13use std::fmt::Write as _;
14
15use dioxus::prelude::*;
16
17use super::table::{
18    TableLayout, TableRecordSlot, TableRegion, WithoutViewTableDefaults, table_cell_class,
19    table_header_class, use_default_empty_row, use_sticky_header,
20};
21use crate::class::{Glass, compose};
22use crate::data::has_content;
23use crate::hooks::{use_controllable, use_unique_id};
24use crate::icons::lucide;
25use crate::{Button, ButtonSize, ButtonVariant, Checkbox, Field, Icon, Label};
26
27/// The empty row's text when `empty` gives none, like lumen-core's `lumenDataTableDefaults`.
28const DEFAULT_EMPTY_LABEL: &str = "No records";
29/// The loading status text when `loading_label` gives none.
30const DEFAULT_LOADING_LABEL: &str = "Loading rows";
31/// Placeholder rows while loading without rows.
32const DEFAULT_LOADING_ROWS: usize = 3;
33/// At most this many placeholder rows render, so a large count cannot stall rendering.
34const MAX_LOADING_ROWS: usize = 100;
35
36/// When rows are sorted.
37#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
38#[non_exhaustive]
39pub enum DataTableSortMode {
40    /// The table sorts the rows it renders.
41    #[default]
42    Client,
43    /// The application sorts (for example on a server); headers only report the criteria.
44    Manual,
45}
46
47impl DataTableSortMode {
48    /// The `data-ui-datatable-sort-mode` value.
49    pub fn as_str(self) -> &'static str {
50        match self {
51            Self::Client => "client",
52            Self::Manual => "manual",
53        }
54    }
55}
56
57/// Props for [`DataTable`].
58#[derive(Props, Clone, PartialEq)]
59pub struct DataTableProps {
60    /// Columns. Without valid columns (non-empty, unique keys) the table renders its children.
61    #[props(default)]
62    pub columns: Vec<DataTableColumn>,
63    /// Records. Rows with duplicate or empty ids render no rows.
64    #[props(default)]
65    pub rows: Vec<DataTableRow>,
66    /// Controlled sort criteria; the first entry is the primary sort.
67    pub sorting: Option<Vec<DataTableSort>>,
68    /// Initial criteria when uncontrolled.
69    #[props(default)]
70    pub default_sorting: Vec<DataTableSort>,
71    /// Initial single criterion when uncontrolled and `default_sorting` is empty.
72    pub default_sort: Option<DataTableSort>,
73    /// Called with the criteria after a header activation.
74    pub on_sorting_change: Option<EventHandler<Vec<DataTableSort>>>,
75    /// Called with the primary criterion when it changes.
76    pub on_sort_change: Option<EventHandler<Option<DataTableSort>>>,
77    /// Who sorts the rows.
78    #[props(default)]
79    pub sort_mode: DataTableSortMode,
80    /// Shift+click or Shift+Enter on a header adds or reverses a secondary criterion.
81    #[props(default)]
82    pub multi_sort: bool,
83    /// Screen-reader text of a sort priority badge. Defaults to `Sort priority {n}, {direction}`.
84    pub sort_priority_label: Option<Callback<(usize, DataTableSortDirection), String>>,
85    /// Renders a leading checkbox column.
86    #[props(default)]
87    pub selectable: bool,
88    /// Controlled selected row ids.
89    pub selected_row_ids: Option<Vec<String>>,
90    /// Initially selected row ids when uncontrolled.
91    #[props(default)]
92    pub default_selected_row_ids: Vec<String>,
93    /// Called with the selected row ids.
94    pub on_selected_row_ids_change: Option<EventHandler<Vec<String>>>,
95    /// Name of the select-all checkbox. Defaults to `Select all rows`.
96    #[props(into)]
97    pub select_all_label: Option<String>,
98    /// Prefix of each row checkbox name. Defaults to `Select row`.
99    #[props(into)]
100    pub select_row_label: Option<String>,
101    /// Form field name of the row checkboxes, so selected row ids submit with a form.
102    #[props(into)]
103    pub name: Option<String>,
104    /// Names a record in disclosure, selection, and details labels. Defaults to the first column.
105    pub get_row_label: Option<Callback<DataTableRow, String>>,
106    /// Narrow-width behavior.
107    #[props(default)]
108    pub layout: TableLayout,
109    /// Keeps the header row visible while rows scroll. Cap the height with the
110    /// `--ui-table-max-height` custom property (default `32rem`) in `style`. The scrolling root
111    /// becomes a focusable `region` named `Table` unless you pass `role`, `tabindex`, `aria_label`
112    /// or `aria_labelledby`. Defaults to `true` inside a [`DataTableView`], otherwise `false`.
113    pub sticky_header: Option<bool>,
114    /// Marks the table busy and announces `loading_label`. Without rows, placeholder rows
115    /// render instead of the empty row.
116    #[props(default)]
117    pub loading: bool,
118    /// Text of the table's status region while loading. The region stays mounted and empty
119    /// otherwise, because screen readers can miss a live region inserted with its text. Defaults
120    /// to `Loading rows`.
121    #[props(into)]
122    pub loading_label: Option<String>,
123    /// Placeholder rows while loading without rows, up to 100. Defaults to 3.
124    #[props(default = DEFAULT_LOADING_ROWS)]
125    pub loading_rows: usize,
126    /// Content of the row shown when there are no rows and the table is not loading. Defaults
127    /// to `No records`.
128    pub empty: Option<Element>,
129    /// Renders an expandable details row for a record.
130    pub render_details: Option<Callback<DataTableRow, Element>>,
131    /// Controlled expanded row ids.
132    pub expanded_row_ids: Option<Vec<String>>,
133    /// Initially expanded row ids when uncontrolled.
134    #[props(default)]
135    pub default_expanded_row_ids: Vec<String>,
136    /// Called with the expanded row ids.
137    pub on_expanded_row_ids_change: Option<EventHandler<Vec<String>>>,
138    /// Prefix of the expand button name. Defaults to `Expand record`.
139    #[props(into)]
140    pub expand_label: Option<String>,
141    /// Prefix of the collapse button name. Defaults to `Collapse record`.
142    #[props(into)]
143    pub collapse_label: Option<String>,
144    /// Prefix of the details region name. Defaults to `Record details`.
145    #[props(into)]
146    pub details_label: Option<String>,
147    /// Glass intensity.
148    #[props(default, into)]
149    pub glass: Glass,
150    /// Extra classes appended after the Lumen classes.
151    #[props(into)]
152    pub class: Option<String>,
153    /// Any other `<div>` or global attribute.
154    #[props(extends = GlobalAttributes, extends = div)]
155    pub attributes: Vec<Attribute>,
156    /// A static table rendered when there are no valid columns.
157    pub children: Element,
158}
159
160struct HeaderSort<'a> {
161    active: Option<&'a DataTableSort>,
162    aria_sort: Option<&'static str>,
163    priority: Option<usize>,
164}
165
166fn header_sort<'a>(column: &DataTableColumn, criteria: &'a [DataTableSort]) -> HeaderSort<'a> {
167    let position = criteria.iter().position(|sort| sort.key == column.key);
168    let active = position.and_then(|index| criteria.get(index));
169    let ranked = criteria.len() > 1 && active.is_some();
170    let priority = position.filter(|_| ranked).map(|index| index + 1);
171
172    if position == Some(0) {
173        return HeaderSort {
174            active,
175            aria_sort: active.map(|sort| sort.direction.as_str()),
176            priority,
177        };
178    }
179
180    HeaderSort {
181        active,
182        aria_sort: column.sortable.then_some("none"),
183        priority,
184    }
185}
186
187/// A cell's content: the column's `render` output, else the cell text.
188fn display_value(column: &DataTableColumn, row: &DataTableRow) -> Element {
189    let cell = row.get(&column.key);
190
191    match column.render {
192        Some(render) => render.call((cell.cloned().unwrap_or_default(), row.clone())),
193        None => rsx! { "{cell.map_or(\"\", |cell| cell.text.as_str())}" },
194    }
195}
196
197/// The secondary values a title cell repeats while the table is narrow, keyed by column: the
198/// ones that render something, in column order.
199fn folded_values<'a>(
200    secondary: &[&'a DataTableColumn],
201    row: &DataTableRow,
202) -> Vec<(&'a str, Element)> {
203    secondary
204        .iter()
205        .filter_map(|column| {
206            let value = display_value(column, row);
207            let filled = if column.render.is_some() {
208                has_content(&value)
209            } else {
210                !row.text(&column.key).is_empty()
211            };
212
213            filled.then_some((column.key.as_str(), value))
214        })
215        .collect()
216}
217
218/// The column holding the expand toggle, like lumen-core's `resolveLumenTableDisclosureColumn`:
219/// the title, else the first column that isn't secondary, else the first column. A secondary
220/// column hides while narrow and would take the toggle with it.
221fn disclosure_column(columns: &[DataTableColumn], slots: &[Option<TableRecordSlot>]) -> usize {
222    slots
223        .iter()
224        .position(|slot| *slot == Some(TableRecordSlot::Title))
225        .or_else(|| columns.iter().position(|column| !column.secondary))
226        .unwrap_or(0)
227}
228
229/// `{details_id}-{hex code points of the row id joined by -}`, like lumen-react.
230fn detail_region_id(details_id: &str, row_id: &str) -> String {
231    let mut id = details_id.to_string();
232
233    for character in row_id.chars() {
234        let _ = write!(id, "-{:x}", u32::from(character));
235    }
236
237    id
238}
239
240/// Styles dense tabular data: sortable headers (with optional multi-sort), row selection,
241/// expandable record details, loading and empty rows, and records or condensed layouts for
242/// narrow widths.
243///
244/// Without multi-sort, a header cycles ascending, descending, then the original order. Column
245/// `record` slots arrange the stacked record cards; secondary columns hide while the table is
246/// narrow and repeat under the title. Placeholder and empty rows are never selectable, sortable,
247/// or counted.
248///
249/// The root always starts with a visually hidden `role="status"` region, with or without
250/// columns. It holds `loading_label` while `loading` and is empty otherwise.
251///
252/// Selection checkboxes are lumen-dioxus [`Checkbox`]es (`<button role="checkbox">`) instead of
253/// native inputs, so they render the same on Dioxus Native.
254#[component]
255#[allow(clippy::too_many_lines)]
256pub fn DataTable(props: DataTableProps) -> Element {
257    let details_id = use_unique_id();
258    let initial_sorting = if props.default_sorting.is_empty() {
259        props.default_sort.clone().into_iter().collect()
260    } else {
261        valid_data_table_sorting(&props.default_sorting)
262    };
263    let sorting = use_controllable(
264        props.sorting.as_deref().map(valid_data_table_sorting),
265        || initial_sorting,
266        props.on_sorting_change,
267    );
268    let selection = use_controllable(
269        props.selected_row_ids.clone(),
270        || props.default_selected_row_ids.clone(),
271        props.on_selected_row_ids_change,
272    );
273    let expansion = use_controllable(
274        props.expanded_row_ids.clone(),
275        || props.default_expanded_row_ids.clone(),
276        props.on_expanded_row_ids_change,
277    );
278    let sticky_header = use_sticky_header(props.sticky_header);
279    // Inside a DataTableView the view announces empty results, so only an explicit `empty` renders.
280    let default_empty_row = use_default_empty_row();
281    let empty_row = props.empty.is_some() || default_empty_row;
282    let glass = props.glass.class("ui-data-table");
283    let class = compose([
284        Some("ui-data-table"),
285        glass.as_deref(),
286        props.layout.class(),
287        sticky_header.then_some("ui-table-wrap--sticky-header"),
288        props.class.as_deref(),
289    ]);
290    let columns = valid_data_table_columns(&props.columns).to_vec();
291    let loading = props.loading;
292    // Screen readers can miss a live region inserted with its text, so the status region is
293    // always mounted and only its text changes.
294    let status = if loading {
295        props
296            .loading_label
297            .clone()
298            .unwrap_or_else(|| DEFAULT_LOADING_LABEL.to_string())
299    } else {
300        String::new()
301    };
302    // A sticky header caps the root's height and scrolls it, so keyboard users must reach it.
303    let region = TableRegion::sticky(sticky_header, &props.attributes);
304    let root = |body: Element| {
305        rsx! {
306            div {
307                aria_busy: loading.then_some("true"),
308                aria_label: region.aria_label,
309                class: class.clone(),
310                "data-ui-datatable": "true",
311                "data-ui-datatable-name": props.name.clone(),
312                "data-ui-datatable-selectable": props.selectable.then_some("true"),
313                "data-ui-datatable-selection-bound": props.selectable.then_some("true"),
314                "data-ui-datatable-sort-mode": props.sort_mode.as_str(),
315                "data-ui-glass-track": (props.glass != Glass::Off).then_some("true"),
316                role: region.role,
317                tabindex: region.tabindex,
318                ..props.attributes.clone(),
319                span { class: "ui-sr-only", role: "status", "{status}" }
320                WithoutViewTableDefaults { {body} }
321            }
322        }
323    };
324
325    if columns.is_empty() {
326        return root(props.children.clone());
327    }
328
329    let rows: Vec<DataTableRow> = if valid_data_table_rows(&props.rows) {
330        props.rows.clone()
331    } else {
332        Vec::new()
333    };
334    let criteria = sorting.get();
335    let order = sort_data_table_rows(
336        &rows,
337        &columns,
338        &criteria,
339        props.sort_mode == DataTableSortMode::Manual,
340    );
341    let rendered: Vec<String> = order
342        .iter()
343        .map(|index| rows[*index].value(*index))
344        .collect();
345    let selected = selection.get();
346    let expanded = expansion.get();
347    let selectable = props.selectable;
348    let multi_sort = props.multi_sort;
349    let on_sort_change = props.on_sort_change;
350    let records = props.layout == TableLayout::Records;
351    let slots = data_table_record_slots(&columns);
352    // Secondary columns hide while narrow only when a title cell repeats their values.
353    let titled = slots.contains(&Some(TableRecordSlot::Title));
354    let disclosure = disclosure_column(&columns, &slots);
355    // The title cell repeats the other secondary columns while narrow; never itself.
356    let secondary: Vec<&DataTableColumn> = columns
357        .iter()
358        .zip(&slots)
359        .filter(|(column, slot)| column.secondary && **slot != Some(TableRecordSlot::Title))
360        .map(|(column, _)| column)
361        .collect();
362    let column_span = columns.len() + usize::from(selectable);
363    let toggle_sort = move |key: String, additive: bool| {
364        let current = sorting.peek();
365        let next = if multi_sort {
366            next_data_table_sorting(&current, &key, additive)
367        } else {
368            cycle_data_table_sorting(&current, &key)
369        };
370
371        if current.first() != next.first()
372            && let Some(handler) = on_sort_change
373        {
374            handler.call(next.first().cloned());
375        }
376
377        sorting.set(next);
378    };
379    let selected_count = rendered.iter().filter(|id| selected.contains(id)).count();
380    let all_selected = !rendered.is_empty() && selected_count == rendered.len();
381    let select_all_rendered = rendered.clone();
382    let row_label = |row: &DataTableRow, row_id: &str| {
383        props
384            .get_row_label
385            .map(|label| label.call(row.clone()))
386            .filter(|label| !label.is_empty())
387            .or_else(|| {
388                columns
389                    .first()
390                    .map(|column| row.text(&column.key).to_string())
391                    .filter(|text| !text.is_empty())
392            })
393            .unwrap_or_else(|| row_id.to_string())
394    };
395
396    let body = rsx! {
397        table { role: "table",
398            thead { role: "rowgroup",
399                tr { role: "row",
400                    if selectable {
401                        th { class: "ui-data-table__selection", role: "columnheader", scope: "col",
402                            Checkbox {
403                                aria_label: props.select_all_label.clone().unwrap_or_else(|| "Select all rows".to_string()),
404                                checked: all_selected,
405                                "data-ui-datatable-select-all": "",
406                                disabled: rendered.is_empty(),
407                                indeterminate: selected_count > 0 && !all_selected,
408                                onchange: move |_| selection.set(toggle_data_table_ids(&selection.peek(), &select_all_rendered)),
409                            }
410                        }
411                    }
412                    for (column, slot) in columns.iter().zip(slots.iter().copied()) {
413                        {
414                            let header = header_sort(column, &criteria);
415                            let sort_key = column.key.clone();
416                            let key_key = column.key.clone();
417                            let priority_label = header.active.zip(header.priority).map(|(active, priority)| {
418                                props.sort_priority_label.map_or_else(
419                                    || format!("Sort priority {priority}, {}", active.direction.as_str()),
420                                    |label| label.call((priority, active.direction)),
421                                )
422                            });
423
424                            rsx! {
425                                th {
426                                    key: "{column.key}",
427                                    aria_sort: header.aria_sort,
428                                    class: table_header_class(slot, column.secondary && titled),
429                                    "data-numeric": column.is_numeric().to_string(),
430                                    "data-ui-datatable-sort-bound": "true",
431                                    "data-ui-datatable-sort-direction": header.active.map(|sort| sort.direction.as_str()),
432                                    "data-ui-datatable-sort-priority": header.priority.map(|priority| priority.to_string()),
433                                    "data-ui-datatable-sort-type": column.sort.map(DataTableSortType::as_str),
434                                    "data-ui-datatable-sortable": column.sortable.then_some("true"),
435                                    role: "columnheader",
436                                    scope: "col",
437                                    if column.sortable {
438                                        button {
439                                            class: "ui-data-table__sort",
440                                            "data-ui-datatable-sort": "true",
441                                            r#type: "button",
442                                            onclick: move |event| toggle_sort(sort_key.clone(), multi_sort && event.modifiers().shift()),
443                                            onkeydown: move |event| {
444                                                if multi_sort && event.modifiers().shift() && event.key() == Key::Enter {
445                                                    event.prevent_default();
446                                                    toggle_sort(key_key.clone(), true);
447                                                }
448                                            },
449                                            "{column.title()}"
450                                            if let (Some(priority), Some(label)) = (header.priority, priority_label) {
451                                                span { aria_hidden: "true", class: "ui-data-table__sort-priority", "{priority}" }
452                                                span { class: "ui-sr-only", "{label}" }
453                                            }
454                                        }
455                                    } else {
456                                        "{column.title()}"
457                                    }
458                                }
459                            }
460                        }
461                    }
462                }
463            }
464            tbody {
465                aria_hidden: (rows.is_empty() && loading).then_some("true"),
466                role: "rowgroup",
467                if rows.is_empty() && loading {
468                    for index in 0..props.loading_rows.min(MAX_LOADING_ROWS) {
469                        // The body is hidden from assistive technology, so placeholder rows need no table roles.
470                        tr {
471                            key: "skeleton:{index}",
472                            class: "ui-table__skeleton-row",
473                            if selectable {
474                                td { class: "ui-data-table__selection",
475                                    span { class: "ui-skeleton ui-skeleton--text" }
476                                }
477                            }
478                            for (column, slot) in columns.iter().zip(slots.iter().copied()) {
479                                td {
480                                    key: "{column.key}",
481                                    class: table_cell_class(slot, column.secondary && titled),
482                                    span { class: "ui-skeleton ui-skeleton--text" }
483                                }
484                            }
485                        }
486                    }
487                } else if rows.is_empty() && empty_row {
488                    tr { role: "row",
489                        td { class: "ui-table__empty", colspan: "{column_span}", role: "cell",
490                            if let Some(empty) = props.empty.clone() {
491                                {empty}
492                            } else {
493                                "{DEFAULT_EMPTY_LABEL}"
494                            }
495                        }
496                    }
497                }
498                for index in order.iter().copied() {
499                    {
500                        let row = &rows[index];
501                        let row_id = row.value(index);
502                        let open = props.render_details.is_some() && expanded.contains(&row_id);
503                        let is_selected = selectable && selected.contains(&row_id);
504                        let region = detail_region_id(&details_id, &row_id);
505                        let label = row_label(row, &row_id);
506                        let toggle_id = row_id.clone();
507                        let select_id = row_id.clone();
508                        let disclosure_label = if open {
509                            props.collapse_label.clone().unwrap_or_else(|| "Collapse record".to_string())
510                        } else {
511                            props.expand_label.clone().unwrap_or_else(|| "Expand record".to_string())
512                        };
513                        let details_label = props.details_label.clone().unwrap_or_else(|| "Record details".to_string());
514                        let fold = folded_values(&secondary, row);
515
516                        rsx! {
517                            tr {
518                                key: "record:{row_id}",
519                                "data-expanded": open.then_some("true"),
520                                "data-state": is_selected.then_some("selected"),
521                                "data-ui-datatable-row": "true",
522                                "data-value": "{row_id}",
523                                role: "row",
524                                if selectable {
525                                    td { class: "ui-data-table__selection", role: "cell",
526                                        Checkbox {
527                                            aria_label: format!("{}: {label}", props.select_row_label.clone().unwrap_or_else(|| "Select row".to_string())),
528                                            checked: is_selected,
529                                            "data-ui-datatable-row-select": "",
530                                            name: props.name.clone(),
531                                            value: row_id.clone(),
532                                            onchange: move |_| selection.set(toggle_data_table_id(&selection.peek(), &select_id)),
533                                        }
534                                    }
535                                }
536                                for (column_index, (column, slot)) in columns.iter().zip(slots.iter().copied()).enumerate() {
537                                    {
538                                        let cell = row.get(&column.key);
539                                        let toggle_id = toggle_id.clone();
540                                        let folds = slot == Some(TableRecordSlot::Title) && !fold.is_empty();
541
542                                        rsx! {
543                                            td {
544                                                key: "{column.key}",
545                                                class: table_cell_class(slot, column.secondary && titled),
546                                                "data-numeric": column.is_numeric().to_string(),
547                                                // A folded title cell also holds secondary values, so it carries its own value for DOM sorting.
548                                                "data-sort-value": cell
549                                                    .and_then(|cell| cell.sort_value.clone())
550                                                    .or_else(|| folds.then(|| row.text(&column.key).to_owned())),
551                                                role: "cell",
552                                                if records {
553                                                    span { aria_hidden: "true", class: "ui-table__label", "{column.title()}" }
554                                                }
555                                                div { class: "ui-table__value",
556                                                    if column_index == disclosure && props.render_details.is_some() {
557                                                        Button {
558                                                            aria_controls: open.then(|| region.clone()),
559                                                            aria_expanded: if open { "true" } else { "false" },
560                                                            aria_label: "{disclosure_label}: {label}",
561                                                            class: "ui-data-table__expand",
562                                                            size: ButtonSize::Icon,
563                                                            variant: ButtonVariant::Ghost,
564                                                            onclick: move |_| expansion.set(toggle_data_table_id(&expansion.peek(), &toggle_id)),
565                                                            Icon { icon: &lucide::CHEVRON_RIGHT }
566                                                        }
567                                                    }
568                                                    {display_value(column, row)}
569                                                }
570                                                if folds {
571                                                    span { class: "ui-table__meta ui-table__narrow",
572                                                        for (key, value) in fold.iter() {
573                                                            span { key: "{key}", {value.clone()} }
574                                                        }
575                                                    }
576                                                }
577                                            }
578                                        }
579                                    }
580                                }
581                            }
582                            if open {
583                                tr { key: "detail:{row_id}", "data-ui-datatable-detail": "true", role: "row",
584                                    td { class: "ui-table__cell--wide", colspan: "{column_span}", role: "cell",
585                                        section { aria_label: "{details_label}: {label}", id: "{region}",
586                                            if let Some(render) = props.render_details {
587                                                {render.call(row.clone())}
588                                            }
589                                        }
590                                    }
591                                }
592                            }
593                        }
594                    }
595                }
596            }
597        }
598    };
599
600    root(body)
601}
602
603/// Props for [`DataTableSortControls`].
604#[derive(Props, Clone, PartialEq)]
605pub struct DataTableSortControlsProps {
606    /// The table's columns; only sortable ones are offered.
607    pub columns: Vec<DataTableColumn>,
608    /// The current primary criterion.
609    pub sort: Option<DataTableSort>,
610    /// Called with the new criterion, or `None` for the default order.
611    pub on_sort_change: EventHandler<Option<DataTableSort>>,
612    /// Disables both controls.
613    #[props(default)]
614    pub disabled: bool,
615    /// Select label. Defaults to `Sort by`.
616    #[props(default = "Sort by".to_string(), into)]
617    pub label: String,
618    /// Direction button name prefix. Defaults to `Sort direction`.
619    #[props(default = "Sort direction".to_string(), into)]
620    pub direction_label: String,
621    /// Ascending text. Defaults to `Ascending`.
622    #[props(default = "Ascending".to_string(), into)]
623    pub ascending_label: String,
624    /// Descending text. Defaults to `Descending`.
625    #[props(default = "Descending".to_string(), into)]
626    pub descending_label: String,
627    /// Option for no sort. Defaults to `Default order`.
628    #[props(default = "Default order".to_string(), into)]
629    pub placeholder: String,
630    /// Extra classes appended after the Lumen class.
631    #[props(into)]
632    pub class: Option<String>,
633    /// Any other `<div>` or global attribute.
634    #[props(extends = GlobalAttributes, extends = div)]
635    pub attributes: Vec<Attribute>,
636}
637
638/// A select and a direction toggle that drive the same sort as the table headers, for narrow
639/// layouts and toolbars.
640#[component]
641pub fn DataTableSortControls(props: DataTableSortControlsProps) -> Element {
642    let id = use_unique_id();
643    let columns: Vec<DataTableColumn> = valid_data_table_columns(&props.columns)
644        .iter()
645        .filter(|column| column.sortable)
646        .cloned()
647        .collect();
648    let selected = columns
649        .iter()
650        .find(|column| {
651            props
652                .sort
653                .as_ref()
654                .is_some_and(|sort| sort.key == column.key)
655        })
656        .map(|column| column.key.clone());
657    let descending = props
658        .sort
659        .as_ref()
660        .is_some_and(|sort| sort.direction == DataTableSortDirection::Descending);
661    let direction_text = if descending {
662        props.descending_label.clone()
663    } else {
664        props.ascending_label.clone()
665    };
666    let class = compose([Some("ui-data-table__sort-controls"), props.class.as_deref()]);
667    let on_sort_change = props.on_sort_change;
668    let keys: Vec<String> = columns.iter().map(|column| column.key.clone()).collect();
669    let toggle_key = selected.clone();
670    let ascending = props
671        .sort
672        .as_ref()
673        .is_some_and(|sort| sort.direction == DataTableSortDirection::Ascending);
674
675    rsx! {
676        div { class, ..props.attributes,
677            Field { control_id: "{id}",
678                Label { r#for: "{id}", "{props.label}" }
679                select {
680                    class: "ui-select",
681                    disabled: props.disabled,
682                    id: "{id}",
683                    oninput: move |event| {
684                        let value = event.value();
685                        let next = keys.iter().find(|key| **key == value).map(|key| DataTableSort::ascending(key.clone()));
686                        on_sort_change.call(next);
687                    },
688                    option { selected: selected.is_none(), value: "", "{props.placeholder}" }
689                    for column in columns.iter() {
690                        option {
691                            key: "{column.key}",
692                            selected: selected.as_deref() == Some(column.key.as_str()),
693                            value: "{column.key}",
694                            "{column.title()}"
695                        }
696                    }
697                }
698            }
699            Button {
700                aria_label: "{props.direction_label}: {direction_text}",
701                aria_pressed: if descending { "true" } else { "false" },
702                disabled: props.disabled || selected.is_none(),
703                variant: ButtonVariant::Outline,
704                onclick: move |_| {
705                    if let Some(key) = toggle_key.clone() {
706                        let direction = if ascending { DataTableSortDirection::Descending } else { DataTableSortDirection::Ascending };
707                        on_sort_change.call(Some(DataTableSort { key, direction }));
708                    }
709                },
710                Icon { icon: if descending { &lucide::ARROW_DOWN } else { &lucide::ARROW_UP } }
711                "{direction_text}"
712            }
713        }
714    }
715}
716
717#[cfg(test)]
718mod tests {
719    use super::detail_region_id;
720
721    #[test]
722    fn detail_ids_encode_code_points() {
723        assert_eq!(detail_region_id("x", "ada"), "x-61-64-61");
724        assert_eq!(detail_region_id("x", "é 1"), "x-e9-20-31");
725    }
726}