lumen-dioxus 6.0.0

Lumen UI components for Dioxus: web, desktop, mobile, and Dioxus Native (Blitz).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
//! `DataTable`, its sort controls, `DataTableView`, saved views, and column layout controls.

mod layout;
mod model;
mod saved;
mod view;

pub use layout::*;
pub use model::*;
pub use saved::*;
pub use view::*;

use std::fmt::Write as _;

use dioxus::prelude::*;

use super::table::{
    TableLayout, TableRecordSlot, TableRegion, WithoutViewTableDefaults, table_cell_class,
    table_header_class, use_default_empty_row, use_sticky_header,
};
use crate::class::{Glass, compose};
use crate::data::has_content;
use crate::hooks::{use_controllable, use_unique_id};
use crate::icons::lucide;
use crate::{Button, ButtonSize, ButtonVariant, Checkbox, Field, Icon, Label};

/// The empty row's text when `empty` gives none, like lumen-core's `lumenDataTableDefaults`.
const DEFAULT_EMPTY_LABEL: &str = "No records";
/// The loading status text when `loading_label` gives none.
const DEFAULT_LOADING_LABEL: &str = "Loading rows";
/// Placeholder rows while loading without rows.
const DEFAULT_LOADING_ROWS: usize = 3;
/// At most this many placeholder rows render, so a large count cannot stall rendering.
const MAX_LOADING_ROWS: usize = 100;

/// When rows are sorted.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum DataTableSortMode {
    /// The table sorts the rows it renders.
    #[default]
    Client,
    /// The application sorts (for example on a server); headers only report the criteria.
    Manual,
}

impl DataTableSortMode {
    /// The `data-ui-datatable-sort-mode` value.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Client => "client",
            Self::Manual => "manual",
        }
    }
}

/// Props for [`DataTable`].
#[derive(Props, Clone, PartialEq)]
pub struct DataTableProps {
    /// Columns. Without valid columns (non-empty, unique keys) the table renders its children.
    #[props(default)]
    pub columns: Vec<DataTableColumn>,
    /// Records. Rows with duplicate or empty ids render no rows.
    #[props(default)]
    pub rows: Vec<DataTableRow>,
    /// Controlled sort criteria; the first entry is the primary sort.
    pub sorting: Option<Vec<DataTableSort>>,
    /// Initial criteria when uncontrolled.
    #[props(default)]
    pub default_sorting: Vec<DataTableSort>,
    /// Initial single criterion when uncontrolled and `default_sorting` is empty.
    pub default_sort: Option<DataTableSort>,
    /// Called with the criteria after a header activation.
    pub on_sorting_change: Option<EventHandler<Vec<DataTableSort>>>,
    /// Called with the primary criterion when it changes.
    pub on_sort_change: Option<EventHandler<Option<DataTableSort>>>,
    /// Who sorts the rows.
    #[props(default)]
    pub sort_mode: DataTableSortMode,
    /// Shift+click or Shift+Enter on a header adds or reverses a secondary criterion.
    #[props(default)]
    pub multi_sort: bool,
    /// Screen-reader text of a sort priority badge. Defaults to `Sort priority {n}, {direction}`.
    pub sort_priority_label: Option<Callback<(usize, DataTableSortDirection), String>>,
    /// Renders a leading checkbox column.
    #[props(default)]
    pub selectable: bool,
    /// Controlled selected row ids.
    pub selected_row_ids: Option<Vec<String>>,
    /// Initially selected row ids when uncontrolled.
    #[props(default)]
    pub default_selected_row_ids: Vec<String>,
    /// Called with the selected row ids.
    pub on_selected_row_ids_change: Option<EventHandler<Vec<String>>>,
    /// Name of the select-all checkbox. Defaults to `Select all rows`.
    #[props(into)]
    pub select_all_label: Option<String>,
    /// Prefix of each row checkbox name. Defaults to `Select row`.
    #[props(into)]
    pub select_row_label: Option<String>,
    /// Form field name of the row checkboxes, so selected row ids submit with a form.
    #[props(into)]
    pub name: Option<String>,
    /// Names a record in disclosure, selection, and details labels. Defaults to the first column.
    pub get_row_label: Option<Callback<DataTableRow, String>>,
    /// Narrow-width behavior.
    #[props(default)]
    pub layout: TableLayout,
    /// Keeps the header row visible while rows scroll. Cap the height with the
    /// `--ui-table-max-height` custom property (default `32rem`) in `style`. The scrolling root
    /// becomes a focusable `region` named `Table` unless you pass `role`, `tabindex`, `aria_label`
    /// or `aria_labelledby`. Defaults to `true` inside a [`DataTableView`], otherwise `false`.
    pub sticky_header: Option<bool>,
    /// Marks the table busy and announces `loading_label`. Without rows, placeholder rows
    /// render instead of the empty row.
    #[props(default)]
    pub loading: bool,
    /// Text of the table's status region while loading. The region stays mounted and empty
    /// otherwise, because screen readers can miss a live region inserted with its text. Defaults
    /// to `Loading rows`.
    #[props(into)]
    pub loading_label: Option<String>,
    /// Placeholder rows while loading without rows, up to 100. Defaults to 3.
    #[props(default = DEFAULT_LOADING_ROWS)]
    pub loading_rows: usize,
    /// Content of the row shown when there are no rows and the table is not loading. Defaults
    /// to `No records`.
    pub empty: Option<Element>,
    /// Renders an expandable details row for a record.
    pub render_details: Option<Callback<DataTableRow, Element>>,
    /// Controlled expanded row ids.
    pub expanded_row_ids: Option<Vec<String>>,
    /// Initially expanded row ids when uncontrolled.
    #[props(default)]
    pub default_expanded_row_ids: Vec<String>,
    /// Called with the expanded row ids.
    pub on_expanded_row_ids_change: Option<EventHandler<Vec<String>>>,
    /// Prefix of the expand button name. Defaults to `Expand record`.
    #[props(into)]
    pub expand_label: Option<String>,
    /// Prefix of the collapse button name. Defaults to `Collapse record`.
    #[props(into)]
    pub collapse_label: Option<String>,
    /// Prefix of the details region name. Defaults to `Record details`.
    #[props(into)]
    pub details_label: Option<String>,
    /// Glass intensity.
    #[props(default, into)]
    pub glass: Glass,
    /// Extra classes appended after the Lumen classes.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<div>` or global attribute.
    #[props(extends = GlobalAttributes, extends = div)]
    pub attributes: Vec<Attribute>,
    /// A static table rendered when there are no valid columns.
    pub children: Element,
}

struct HeaderSort<'a> {
    active: Option<&'a DataTableSort>,
    aria_sort: Option<&'static str>,
    priority: Option<usize>,
}

fn header_sort<'a>(column: &DataTableColumn, criteria: &'a [DataTableSort]) -> HeaderSort<'a> {
    let position = criteria.iter().position(|sort| sort.key == column.key);
    let active = position.and_then(|index| criteria.get(index));
    let ranked = criteria.len() > 1 && active.is_some();
    let priority = position.filter(|_| ranked).map(|index| index + 1);

    if position == Some(0) {
        return HeaderSort {
            active,
            aria_sort: active.map(|sort| sort.direction.as_str()),
            priority,
        };
    }

    HeaderSort {
        active,
        aria_sort: column.sortable.then_some("none"),
        priority,
    }
}

/// A cell's content: the column's `render` output, else the cell text.
fn display_value(column: &DataTableColumn, row: &DataTableRow) -> Element {
    let cell = row.get(&column.key);

    match column.render {
        Some(render) => render.call((cell.cloned().unwrap_or_default(), row.clone())),
        None => rsx! { "{cell.map_or(\"\", |cell| cell.text.as_str())}" },
    }
}

/// The secondary values a title cell repeats while the table is narrow, keyed by column: the
/// ones that render something, in column order.
fn folded_values<'a>(
    secondary: &[&'a DataTableColumn],
    row: &DataTableRow,
) -> Vec<(&'a str, Element)> {
    secondary
        .iter()
        .filter_map(|column| {
            let value = display_value(column, row);
            let filled = if column.render.is_some() {
                has_content(&value)
            } else {
                !row.text(&column.key).is_empty()
            };

            filled.then_some((column.key.as_str(), value))
        })
        .collect()
}

/// The column holding the expand toggle, like lumen-core's `resolveLumenTableDisclosureColumn`:
/// the title, else the first column that isn't secondary, else the first column. A secondary
/// column hides while narrow and would take the toggle with it.
fn disclosure_column(columns: &[DataTableColumn], slots: &[Option<TableRecordSlot>]) -> usize {
    slots
        .iter()
        .position(|slot| *slot == Some(TableRecordSlot::Title))
        .or_else(|| columns.iter().position(|column| !column.secondary))
        .unwrap_or(0)
}

/// `{details_id}-{hex code points of the row id joined by -}`, like lumen-react.
fn detail_region_id(details_id: &str, row_id: &str) -> String {
    let mut id = details_id.to_string();

    for character in row_id.chars() {
        let _ = write!(id, "-{:x}", u32::from(character));
    }

    id
}

/// Styles dense tabular data: sortable headers (with optional multi-sort), row selection,
/// expandable record details, loading and empty rows, and records or condensed layouts for
/// narrow widths.
///
/// Without multi-sort, a header cycles ascending, descending, then the original order. Column
/// `record` slots arrange the stacked record cards; secondary columns hide while the table is
/// narrow and repeat under the title. Placeholder and empty rows are never selectable, sortable,
/// or counted.
///
/// The root always starts with a visually hidden `role="status"` region, with or without
/// columns. It holds `loading_label` while `loading` and is empty otherwise.
///
/// Selection checkboxes are lumen-dioxus [`Checkbox`]es (`<button role="checkbox">`) instead of
/// native inputs, so they render the same on Dioxus Native.
#[component]
#[allow(clippy::too_many_lines)]
pub fn DataTable(props: DataTableProps) -> Element {
    let details_id = use_unique_id();
    let initial_sorting = if props.default_sorting.is_empty() {
        props.default_sort.clone().into_iter().collect()
    } else {
        valid_data_table_sorting(&props.default_sorting)
    };
    let sorting = use_controllable(
        props.sorting.as_deref().map(valid_data_table_sorting),
        || initial_sorting,
        props.on_sorting_change,
    );
    let selection = use_controllable(
        props.selected_row_ids.clone(),
        || props.default_selected_row_ids.clone(),
        props.on_selected_row_ids_change,
    );
    let expansion = use_controllable(
        props.expanded_row_ids.clone(),
        || props.default_expanded_row_ids.clone(),
        props.on_expanded_row_ids_change,
    );
    let sticky_header = use_sticky_header(props.sticky_header);
    // Inside a DataTableView the view announces empty results, so only an explicit `empty` renders.
    let default_empty_row = use_default_empty_row();
    let empty_row = props.empty.is_some() || default_empty_row;
    let glass = props.glass.class("ui-data-table");
    let class = compose([
        Some("ui-data-table"),
        glass.as_deref(),
        props.layout.class(),
        sticky_header.then_some("ui-table-wrap--sticky-header"),
        props.class.as_deref(),
    ]);
    let columns = valid_data_table_columns(&props.columns).to_vec();
    let loading = props.loading;
    // Screen readers can miss a live region inserted with its text, so the status region is
    // always mounted and only its text changes.
    let status = if loading {
        props
            .loading_label
            .clone()
            .unwrap_or_else(|| DEFAULT_LOADING_LABEL.to_string())
    } else {
        String::new()
    };
    // A sticky header caps the root's height and scrolls it, so keyboard users must reach it.
    let region = TableRegion::sticky(sticky_header, &props.attributes);
    let root = |body: Element| {
        rsx! {
            div {
                aria_busy: loading.then_some("true"),
                aria_label: region.aria_label,
                class: class.clone(),
                "data-ui-datatable": "true",
                "data-ui-datatable-name": props.name.clone(),
                "data-ui-datatable-selectable": props.selectable.then_some("true"),
                "data-ui-datatable-selection-bound": props.selectable.then_some("true"),
                "data-ui-datatable-sort-mode": props.sort_mode.as_str(),
                "data-ui-glass-track": (props.glass != Glass::Off).then_some("true"),
                role: region.role,
                tabindex: region.tabindex,
                ..props.attributes.clone(),
                span { class: "ui-sr-only", role: "status", "{status}" }
                WithoutViewTableDefaults { {body} }
            }
        }
    };

    if columns.is_empty() {
        return root(props.children.clone());
    }

    let rows: Vec<DataTableRow> = if valid_data_table_rows(&props.rows) {
        props.rows.clone()
    } else {
        Vec::new()
    };
    let criteria = sorting.get();
    let order = sort_data_table_rows(
        &rows,
        &columns,
        &criteria,
        props.sort_mode == DataTableSortMode::Manual,
    );
    let rendered: Vec<String> = order
        .iter()
        .map(|index| rows[*index].value(*index))
        .collect();
    let selected = selection.get();
    let expanded = expansion.get();
    let selectable = props.selectable;
    let multi_sort = props.multi_sort;
    let on_sort_change = props.on_sort_change;
    let records = props.layout == TableLayout::Records;
    let slots = data_table_record_slots(&columns);
    // Secondary columns hide while narrow only when a title cell repeats their values.
    let titled = slots.contains(&Some(TableRecordSlot::Title));
    let disclosure = disclosure_column(&columns, &slots);
    // The title cell repeats the other secondary columns while narrow; never itself.
    let secondary: Vec<&DataTableColumn> = columns
        .iter()
        .zip(&slots)
        .filter(|(column, slot)| column.secondary && **slot != Some(TableRecordSlot::Title))
        .map(|(column, _)| column)
        .collect();
    let column_span = columns.len() + usize::from(selectable);
    let toggle_sort = move |key: String, additive: bool| {
        let current = sorting.peek();
        let next = if multi_sort {
            next_data_table_sorting(&current, &key, additive)
        } else {
            cycle_data_table_sorting(&current, &key)
        };

        if current.first() != next.first()
            && let Some(handler) = on_sort_change
        {
            handler.call(next.first().cloned());
        }

        sorting.set(next);
    };
    let selected_count = rendered.iter().filter(|id| selected.contains(id)).count();
    let all_selected = !rendered.is_empty() && selected_count == rendered.len();
    let select_all_rendered = rendered.clone();
    let row_label = |row: &DataTableRow, row_id: &str| {
        props
            .get_row_label
            .map(|label| label.call(row.clone()))
            .filter(|label| !label.is_empty())
            .or_else(|| {
                columns
                    .first()
                    .map(|column| row.text(&column.key).to_string())
                    .filter(|text| !text.is_empty())
            })
            .unwrap_or_else(|| row_id.to_string())
    };

    let body = rsx! {
        table { role: "table",
            thead { role: "rowgroup",
                tr { role: "row",
                    if selectable {
                        th { class: "ui-data-table__selection", role: "columnheader", scope: "col",
                            Checkbox {
                                aria_label: props.select_all_label.clone().unwrap_or_else(|| "Select all rows".to_string()),
                                checked: all_selected,
                                "data-ui-datatable-select-all": "",
                                disabled: rendered.is_empty(),
                                indeterminate: selected_count > 0 && !all_selected,
                                onchange: move |_| selection.set(toggle_data_table_ids(&selection.peek(), &select_all_rendered)),
                            }
                        }
                    }
                    for (column, slot) in columns.iter().zip(slots.iter().copied()) {
                        {
                            let header = header_sort(column, &criteria);
                            let sort_key = column.key.clone();
                            let key_key = column.key.clone();
                            let priority_label = header.active.zip(header.priority).map(|(active, priority)| {
                                props.sort_priority_label.map_or_else(
                                    || format!("Sort priority {priority}, {}", active.direction.as_str()),
                                    |label| label.call((priority, active.direction)),
                                )
                            });

                            rsx! {
                                th {
                                    key: "{column.key}",
                                    aria_sort: header.aria_sort,
                                    class: table_header_class(slot, column.secondary && titled),
                                    "data-numeric": column.is_numeric().to_string(),
                                    "data-ui-datatable-sort-bound": "true",
                                    "data-ui-datatable-sort-direction": header.active.map(|sort| sort.direction.as_str()),
                                    "data-ui-datatable-sort-priority": header.priority.map(|priority| priority.to_string()),
                                    "data-ui-datatable-sort-type": column.sort.map(DataTableSortType::as_str),
                                    "data-ui-datatable-sortable": column.sortable.then_some("true"),
                                    role: "columnheader",
                                    scope: "col",
                                    if column.sortable {
                                        button {
                                            class: "ui-data-table__sort",
                                            "data-ui-datatable-sort": "true",
                                            r#type: "button",
                                            onclick: move |event| toggle_sort(sort_key.clone(), multi_sort && event.modifiers().shift()),
                                            onkeydown: move |event| {
                                                if multi_sort && event.modifiers().shift() && event.key() == Key::Enter {
                                                    event.prevent_default();
                                                    toggle_sort(key_key.clone(), true);
                                                }
                                            },
                                            "{column.title()}"
                                            if let (Some(priority), Some(label)) = (header.priority, priority_label) {
                                                span { aria_hidden: "true", class: "ui-data-table__sort-priority", "{priority}" }
                                                span { class: "ui-sr-only", "{label}" }
                                            }
                                        }
                                    } else {
                                        "{column.title()}"
                                    }
                                }
                            }
                        }
                    }
                }
            }
            tbody {
                aria_hidden: (rows.is_empty() && loading).then_some("true"),
                role: "rowgroup",
                if rows.is_empty() && loading {
                    for index in 0..props.loading_rows.min(MAX_LOADING_ROWS) {
                        // The body is hidden from assistive technology, so placeholder rows need no table roles.
                        tr {
                            key: "skeleton:{index}",
                            class: "ui-table__skeleton-row",
                            if selectable {
                                td { class: "ui-data-table__selection",
                                    span { class: "ui-skeleton ui-skeleton--text" }
                                }
                            }
                            for (column, slot) in columns.iter().zip(slots.iter().copied()) {
                                td {
                                    key: "{column.key}",
                                    class: table_cell_class(slot, column.secondary && titled),
                                    span { class: "ui-skeleton ui-skeleton--text" }
                                }
                            }
                        }
                    }
                } else if rows.is_empty() && empty_row {
                    tr { role: "row",
                        td { class: "ui-table__empty", colspan: "{column_span}", role: "cell",
                            if let Some(empty) = props.empty.clone() {
                                {empty}
                            } else {
                                "{DEFAULT_EMPTY_LABEL}"
                            }
                        }
                    }
                }
                for index in order.iter().copied() {
                    {
                        let row = &rows[index];
                        let row_id = row.value(index);
                        let open = props.render_details.is_some() && expanded.contains(&row_id);
                        let is_selected = selectable && selected.contains(&row_id);
                        let region = detail_region_id(&details_id, &row_id);
                        let label = row_label(row, &row_id);
                        let toggle_id = row_id.clone();
                        let select_id = row_id.clone();
                        let disclosure_label = if open {
                            props.collapse_label.clone().unwrap_or_else(|| "Collapse record".to_string())
                        } else {
                            props.expand_label.clone().unwrap_or_else(|| "Expand record".to_string())
                        };
                        let details_label = props.details_label.clone().unwrap_or_else(|| "Record details".to_string());
                        let fold = folded_values(&secondary, row);

                        rsx! {
                            tr {
                                key: "record:{row_id}",
                                "data-expanded": open.then_some("true"),
                                "data-state": is_selected.then_some("selected"),
                                "data-ui-datatable-row": "true",
                                "data-value": "{row_id}",
                                role: "row",
                                if selectable {
                                    td { class: "ui-data-table__selection", role: "cell",
                                        Checkbox {
                                            aria_label: format!("{}: {label}", props.select_row_label.clone().unwrap_or_else(|| "Select row".to_string())),
                                            checked: is_selected,
                                            "data-ui-datatable-row-select": "",
                                            name: props.name.clone(),
                                            value: row_id.clone(),
                                            onchange: move |_| selection.set(toggle_data_table_id(&selection.peek(), &select_id)),
                                        }
                                    }
                                }
                                for (column_index, (column, slot)) in columns.iter().zip(slots.iter().copied()).enumerate() {
                                    {
                                        let cell = row.get(&column.key);
                                        let toggle_id = toggle_id.clone();
                                        let folds = slot == Some(TableRecordSlot::Title) && !fold.is_empty();

                                        rsx! {
                                            td {
                                                key: "{column.key}",
                                                class: table_cell_class(slot, column.secondary && titled),
                                                "data-numeric": column.is_numeric().to_string(),
                                                // A folded title cell also holds secondary values, so it carries its own value for DOM sorting.
                                                "data-sort-value": cell
                                                    .and_then(|cell| cell.sort_value.clone())
                                                    .or_else(|| folds.then(|| row.text(&column.key).to_owned())),
                                                role: "cell",
                                                if records {
                                                    span { aria_hidden: "true", class: "ui-table__label", "{column.title()}" }
                                                }
                                                div { class: "ui-table__value",
                                                    if column_index == disclosure && props.render_details.is_some() {
                                                        Button {
                                                            aria_controls: open.then(|| region.clone()),
                                                            aria_expanded: if open { "true" } else { "false" },
                                                            aria_label: "{disclosure_label}: {label}",
                                                            class: "ui-data-table__expand",
                                                            size: ButtonSize::Icon,
                                                            variant: ButtonVariant::Ghost,
                                                            onclick: move |_| expansion.set(toggle_data_table_id(&expansion.peek(), &toggle_id)),
                                                            Icon { icon: &lucide::CHEVRON_RIGHT }
                                                        }
                                                    }
                                                    {display_value(column, row)}
                                                }
                                                if folds {
                                                    span { class: "ui-table__meta ui-table__narrow",
                                                        for (key, value) in fold.iter() {
                                                            span { key: "{key}", {value.clone()} }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            if open {
                                tr { key: "detail:{row_id}", "data-ui-datatable-detail": "true", role: "row",
                                    td { class: "ui-table__cell--wide", colspan: "{column_span}", role: "cell",
                                        section { aria_label: "{details_label}: {label}", id: "{region}",
                                            if let Some(render) = props.render_details {
                                                {render.call(row.clone())}
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    };

    root(body)
}

/// Props for [`DataTableSortControls`].
#[derive(Props, Clone, PartialEq)]
pub struct DataTableSortControlsProps {
    /// The table's columns; only sortable ones are offered.
    pub columns: Vec<DataTableColumn>,
    /// The current primary criterion.
    pub sort: Option<DataTableSort>,
    /// Called with the new criterion, or `None` for the default order.
    pub on_sort_change: EventHandler<Option<DataTableSort>>,
    /// Disables both controls.
    #[props(default)]
    pub disabled: bool,
    /// Select label. Defaults to `Sort by`.
    #[props(default = "Sort by".to_string(), into)]
    pub label: String,
    /// Direction button name prefix. Defaults to `Sort direction`.
    #[props(default = "Sort direction".to_string(), into)]
    pub direction_label: String,
    /// Ascending text. Defaults to `Ascending`.
    #[props(default = "Ascending".to_string(), into)]
    pub ascending_label: String,
    /// Descending text. Defaults to `Descending`.
    #[props(default = "Descending".to_string(), into)]
    pub descending_label: String,
    /// Option for no sort. Defaults to `Default order`.
    #[props(default = "Default order".to_string(), into)]
    pub placeholder: String,
    /// Extra classes appended after the Lumen class.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<div>` or global attribute.
    #[props(extends = GlobalAttributes, extends = div)]
    pub attributes: Vec<Attribute>,
}

/// A select and a direction toggle that drive the same sort as the table headers, for narrow
/// layouts and toolbars.
#[component]
pub fn DataTableSortControls(props: DataTableSortControlsProps) -> Element {
    let id = use_unique_id();
    let columns: Vec<DataTableColumn> = valid_data_table_columns(&props.columns)
        .iter()
        .filter(|column| column.sortable)
        .cloned()
        .collect();
    let selected = columns
        .iter()
        .find(|column| {
            props
                .sort
                .as_ref()
                .is_some_and(|sort| sort.key == column.key)
        })
        .map(|column| column.key.clone());
    let descending = props
        .sort
        .as_ref()
        .is_some_and(|sort| sort.direction == DataTableSortDirection::Descending);
    let direction_text = if descending {
        props.descending_label.clone()
    } else {
        props.ascending_label.clone()
    };
    let class = compose([Some("ui-data-table__sort-controls"), props.class.as_deref()]);
    let on_sort_change = props.on_sort_change;
    let keys: Vec<String> = columns.iter().map(|column| column.key.clone()).collect();
    let toggle_key = selected.clone();
    let ascending = props
        .sort
        .as_ref()
        .is_some_and(|sort| sort.direction == DataTableSortDirection::Ascending);

    rsx! {
        div { class, ..props.attributes,
            Field { control_id: "{id}",
                Label { r#for: "{id}", "{props.label}" }
                select {
                    class: "ui-select",
                    disabled: props.disabled,
                    id: "{id}",
                    oninput: move |event| {
                        let value = event.value();
                        let next = keys.iter().find(|key| **key == value).map(|key| DataTableSort::ascending(key.clone()));
                        on_sort_change.call(next);
                    },
                    option { selected: selected.is_none(), value: "", "{props.placeholder}" }
                    for column in columns.iter() {
                        option {
                            key: "{column.key}",
                            selected: selected.as_deref() == Some(column.key.as_str()),
                            value: "{column.key}",
                            "{column.title()}"
                        }
                    }
                }
            }
            Button {
                aria_label: "{props.direction_label}: {direction_text}",
                aria_pressed: if descending { "true" } else { "false" },
                disabled: props.disabled || selected.is_none(),
                variant: ButtonVariant::Outline,
                onclick: move |_| {
                    if let Some(key) = toggle_key.clone() {
                        let direction = if ascending { DataTableSortDirection::Descending } else { DataTableSortDirection::Ascending };
                        on_sort_change.call(Some(DataTableSort { key, direction }));
                    }
                },
                Icon { icon: if descending { &lucide::ARROW_DOWN } else { &lucide::ARROW_UP } }
                "{direction_text}"
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::detail_region_id;

    #[test]
    fn detail_ids_encode_code_points() {
        assert_eq!(detail_region_id("x", "ada"), "x-61-64-61");
        assert_eq!(detail_region_id("x", "é 1"), "x-e9-20-31");
    }
}