Skip to main content

lumen_dioxus/data/
table.rs

1//! `Table`: the styled wrapper for a semantic `<table>`, its scroll cue, and the record slots it
2//! shares with [`DataTable`](crate::DataTable).
3
4use std::cell::Cell;
5use std::rc::Rc;
6
7use dioxus::prelude::*;
8
9use crate::class::{Glass, compose};
10use crate::form::merge_described_by;
11use crate::hooks::use_unique_id;
12use crate::icons::{icon_svg, icon_svg_class, lucide};
13
14/// The scroll cue text when [`TableScrollCue::On`] gives none, like lumen-core's
15/// `lumenDataTableDefaults.scrollCueLabel`.
16const DEFAULT_SCROLL_CUE_LABEL: &str = "Scroll horizontally to compare";
17
18/// How a [`Table`] or [`DataTable`](crate::DataTable) adapts to narrow widths.
19#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
20#[non_exhaustive]
21pub enum TableLayout {
22    /// The table scrolls horizontally.
23    #[default]
24    Scroll,
25    /// Rows stack into labelled record cards while the table is under 48rem wide.
26    Records,
27    /// The table keeps its columns and hides secondary ones while it is under 48rem wide; what
28    /// remains scrolls horizontally.
29    Condensed,
30}
31
32impl TableLayout {
33    /// The wrapper class: `ui-table-wrap--records`, `ui-table-wrap--condensed`, or none.
34    pub fn class(self) -> Option<&'static str> {
35        match self {
36            Self::Scroll => None,
37            Self::Records => Some("ui-table-wrap--records"),
38            Self::Condensed => Some("ui-table-wrap--condensed"),
39        }
40    }
41
42    /// Whether a wide table scrolls horizontally, so a scroll cue applies: `Scroll` and
43    /// `Condensed`.
44    pub fn scrolls(self) -> bool {
45        matches!(self, Self::Scroll | Self::Condensed)
46    }
47}
48
49/// Where a column's cells go when a `Records` table stacks into cards, like lumen-core's
50/// `LumenTableRecordSlot`.
51///
52/// Plain [`Table`] authors add [`TableRecordSlot::cell_class`] to their cells;
53/// [`DataTable`](crate::DataTable) adds it for `DataTableColumn::record`.
54#[derive(Clone, Copy, Debug, PartialEq, Eq)]
55#[non_exhaustive]
56pub enum TableRecordSlot {
57    /// The card's heading line; the first column's emphasis while the table is wide.
58    Title,
59    /// The end of the title line, emphasized and without a label.
60    Trailing,
61    /// Row actions: they hug the row end while wide and end the title line in a card.
62    Actions,
63    /// A full-width muted line under the title, without a label.
64    Meta,
65    /// A full-width line with its label above the value.
66    Wide,
67}
68
69impl TableRecordSlot {
70    /// The slot name, such as `title`.
71    pub fn as_str(self) -> &'static str {
72        match self {
73            Self::Title => "title",
74            Self::Trailing => "trailing",
75            Self::Actions => "actions",
76            Self::Meta => "meta",
77            Self::Wide => "wide",
78        }
79    }
80
81    /// The cell class, such as `ui-table__cell--title`.
82    pub fn cell_class(self) -> &'static str {
83        match self {
84            Self::Title => "ui-table__cell--title",
85            Self::Trailing => "ui-table__cell--trailing",
86            Self::Actions => "ui-table__cell--actions",
87            Self::Meta => "ui-table__cell--meta",
88            Self::Wide => "ui-table__cell--wide",
89        }
90    }
91}
92
93/// Each column's record slot, like lumen-core's `resolveLumenTableRecordSlots`, from each column's
94/// `(slot, secondary)` pair. Only the first `Title` is the title; later ones get no slot. When no
95/// column is the title, the first column without a slot of its own that isn't secondary becomes
96/// it, so every card gets a heading that stays visible.
97pub fn resolve_table_record_slots(
98    columns: &[(Option<TableRecordSlot>, bool)],
99) -> Vec<Option<TableRecordSlot>> {
100    let first_title = columns
101        .iter()
102        .position(|(slot, _)| *slot == Some(TableRecordSlot::Title));
103    let mut resolved: Vec<Option<TableRecordSlot>> = columns
104        .iter()
105        .enumerate()
106        .map(|(index, (slot, _))| {
107            slot.filter(|kind| *kind != TableRecordSlot::Title || Some(index) == first_title)
108        })
109        .collect();
110
111    if first_title.is_none()
112        && let Some(index) = columns
113            .iter()
114            .position(|(slot, secondary)| slot.is_none() && !secondary)
115        && let Some(slot) = resolved.get_mut(index)
116    {
117        *slot = Some(TableRecordSlot::Title);
118    }
119
120    resolved
121}
122
123/// The classes of a column's body cells, like lumen-core's `getLumenTableCellClasses`: the slot
124/// class, then `ui-table__cell--secondary`, which a title never gets. `None` when there are none.
125///
126/// Pass `secondary` only when a title column repeats the value while the table is narrow; without
127/// a title nothing repeats it, so the column must stay visible.
128pub fn table_cell_class(slot: Option<TableRecordSlot>, secondary: bool) -> Option<String> {
129    let hidden = secondary && slot != Some(TableRecordSlot::Title);
130    let class = compose([
131        slot.map(TableRecordSlot::cell_class),
132        hidden.then_some("ui-table__cell--secondary"),
133    ]);
134
135    (!class.is_empty()).then_some(class)
136}
137
138/// The classes of a column's header cell, like lumen-core's `getLumenTableHeaderClasses`: only
139/// the title and secondary markers apply to `th`. `None` when there are none.
140pub fn table_header_class(slot: Option<TableRecordSlot>, secondary: bool) -> Option<String> {
141    table_cell_class(
142        slot.filter(|slot| *slot == TableRecordSlot::Title),
143        secondary,
144    )
145}
146
147/// The scroll cue of a [`Table`]: a hint shown while the table is wider than its frame.
148///
149/// `true` and `false` convert into `On` and `Off`; a string converts into `Label`, and an empty
150/// string into `Off`.
151#[derive(Clone, Debug, Default, PartialEq, Eq)]
152#[non_exhaustive]
153pub enum TableScrollCue {
154    /// No cue.
155    #[default]
156    Off,
157    /// A cue that reads `Scroll horizontally to compare`.
158    On,
159    /// A cue with this text.
160    Label(String),
161}
162
163impl TableScrollCue {
164    /// The cue text, or `None` when the cue is off.
165    pub fn label(&self) -> Option<&str> {
166        match self {
167            Self::Off => None,
168            Self::On => Some(DEFAULT_SCROLL_CUE_LABEL),
169            Self::Label(label) => (!label.is_empty()).then_some(label.as_str()),
170        }
171    }
172}
173
174impl From<bool> for TableScrollCue {
175    fn from(value: bool) -> Self {
176        if value { Self::On } else { Self::Off }
177    }
178}
179
180impl From<String> for TableScrollCue {
181    fn from(value: String) -> Self {
182        if value.is_empty() {
183            Self::Off
184        } else {
185            Self::Label(value)
186        }
187    }
188}
189
190impl From<&str> for TableScrollCue {
191    fn from(value: &str) -> Self {
192        Self::from(value.to_string())
193    }
194}
195
196/// Defaults a [`DataTableView`](crate::DataTableView) gives the `Table` or `DataTable` its
197/// `render` callback returns, like lumen-react's `DataTableViewTableContext`. An explicit prop on
198/// that table still wins.
199#[derive(Clone, Copy, Debug, PartialEq, Eq)]
200pub(crate) struct DataTableViewTableDefaults {
201    /// Keeps the header row visible while rows scroll.
202    pub(crate) sticky_header: bool,
203    /// Whether a `DataTable` renders its own empty row. A view announces empty results itself.
204    pub(crate) empty_row: bool,
205}
206
207/// The table's `sticky_header`, or the enclosing view's default when the prop is unset.
208pub(crate) fn use_sticky_header(explicit: Option<bool>) -> bool {
209    let defaults = try_use_context::<DataTableViewTableDefaults>();
210
211    explicit.unwrap_or_else(|| defaults.is_some_and(|defaults| defaults.sticky_header))
212}
213
214/// Whether a `DataTable` without an explicit `empty` renders its default empty row: not inside a
215/// view, which reports empty results in its own status.
216pub(crate) fn use_default_empty_row() -> bool {
217    try_use_context::<DataTableViewTableDefaults>().is_none_or(|defaults| defaults.empty_row)
218}
219
220/// Gives `children` the defaults of a table outside any view, like lumen-react's tables
221/// re-providing an empty `DataTableViewTableContext`: the view's defaults are for the table its
222/// `render` callback returns, not a table nested in one of its cells or details rows.
223#[component]
224pub(crate) fn WithoutViewTableDefaults(children: Element) -> Element {
225    use_context_provider(|| DataTableViewTableDefaults {
226        sticky_header: false,
227        empty_row: true,
228    });
229
230    children
231}
232
233/// The `role`, `tabindex` and `aria-label` a scrolling table frame takes unless its attributes
234/// set them: a focusable `region` named `Table`, or by `aria_labelledby`. The scroll-cue viewport
235/// and a sticky-header frame, whose capped height scrolls, both use them.
236#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
237pub(crate) struct TableRegion {
238    pub(crate) role: Option<&'static str>,
239    pub(crate) tabindex: Option<&'static str>,
240    pub(crate) aria_label: Option<&'static str>,
241}
242
243impl TableRegion {
244    /// The defaults the attributes leave unset.
245    pub(crate) fn defaults(attributes: &[Attribute]) -> Self {
246        let named = |name: &str| attributes.iter().any(|attribute| attribute.name == name);
247
248        Self {
249            role: (!named("role")).then_some("region"),
250            tabindex: (!named("tabindex")).then_some("0"),
251            aria_label: (!named("aria-label") && !named("aria-labelledby")).then_some("Table"),
252        }
253    }
254
255    /// [`TableRegion::defaults`] for a sticky header, else nothing.
256    pub(crate) fn sticky(sticky_header: bool, attributes: &[Attribute]) -> Self {
257        if sticky_header {
258            Self::defaults(attributes)
259        } else {
260            Self::default()
261        }
262    }
263}
264
265/// Whether a viewport scrolls horizontally, like the Lumen web runtime's scroll cue controller:
266/// a measured width, and content more than one pixel wider.
267fn table_overflows(client_width: f64, scroll_width: f64) -> bool {
268    client_width > 0.0 && scroll_width > client_width + 1.0
269}
270
271/// Measures whether the mounted scroll-cue viewport overflows, and stores the answer when it
272/// changed. The width is the last `onresize` content width, or the viewport's own rectangle
273/// before one arrives.
274fn measure_scroll_cue(
275    viewport: Signal<Option<Rc<MountedData>>>,
276    viewport_width: Signal<f64>,
277    mut overflowing: Signal<bool>,
278) {
279    let Some(node) = viewport.peek().clone() else {
280        return;
281    };
282    let measured = *viewport_width.peek();
283
284    spawn(async move {
285        let width = if measured > 0.0 {
286            measured
287        } else {
288            node.get_client_rect()
289                .await
290                .map_or(0.0, |rect| rect.width())
291        };
292        let Ok(scroll) = node.get_scroll_size().await else {
293            return;
294        };
295        let next = table_overflows(width, scroll.width);
296
297        if *overflowing.peek() != next {
298            overflowing.set(next);
299        }
300    });
301}
302
303/// Props for [`Table`].
304#[derive(Props, Clone, PartialEq)]
305pub struct TableProps {
306    /// Narrow-width behavior.
307    #[props(default)]
308    pub layout: TableLayout,
309    /// Keeps the header row visible while rows scroll. Cap the height with the
310    /// `--ui-table-max-height` custom property (default `32rem`) in `style`. Defaults to `true`
311    /// inside a [`DataTableView`](crate::DataTableView), otherwise `false`.
312    pub sticky_header: Option<bool>,
313    /// Keeps the first column visible while the table scrolls.
314    #[props(default)]
315    pub sticky_first_column: bool,
316    /// A hint shown while the table is wider than its frame, with `Scroll` and `Condensed`
317    /// layouts: `true` for the default text, or the text itself.
318    #[props(default, into)]
319    pub scroll_cue: TableScrollCue,
320    /// Glass intensity.
321    #[props(default, into)]
322    pub glass: Glass,
323    /// Extra classes appended after the Lumen classes.
324    #[props(into)]
325    pub class: Option<String>,
326    /// Any other `<div>` or global attribute.
327    #[props(extends = GlobalAttributes, extends = div)]
328    pub attributes: Vec<Attribute>,
329    /// A native `table` with `thead`, `tbody`, `tr`, `th`, and `td` children.
330    pub children: Element,
331}
332
333/// Styles a semantic table for records and comparisons.
334///
335/// Compose it with native table elements; in records layout give each `td` a
336/// `span { class: "ui-table__label", aria_hidden: "true" }` with its column name, and mark the
337/// heading cell with [`TableRecordSlot::cell_class`]. Mark matching numeric `th` and `td`
338/// children with `"data-numeric": "true"` for logical end alignment and tabular figures without
339/// sorting.
340///
341/// With `scroll_cue` or `sticky_header`, the frame becomes a focusable, named `region` (`Table`
342/// unless you pass `aria_label` or `aria_labelledby`; your `role` and `tabindex` win too). The cue
343/// appears while the table overflows. It measures when the frame mounts or resizes and after
344/// every render, so rows or columns that arrive through props update it. Renderers that report
345/// element sizes (`onresize`) show it; elsewhere it stays hidden.
346#[component]
347pub fn Table(mut props: TableProps) -> Element {
348    let message_id = use_unique_id();
349    let mut viewport = use_signal(|| None::<Rc<MountedData>>);
350    let mut viewport_width = use_signal(|| 0.0_f64);
351    let mut overflowing = use_signal(|| false);
352    let sticky_header = use_sticky_header(props.sticky_header);
353    let glass = props.glass.class("ui-table-wrap");
354    let class = compose([
355        Some("ui-table-wrap"),
356        glass.as_deref(),
357        props.layout.class(),
358        props
359            .sticky_first_column
360            .then_some("ui-table-wrap--sticky-column"),
361        sticky_header.then_some("ui-table-wrap--sticky-header"),
362        props.class.as_deref(),
363    ]);
364    let cue = props
365        .layout
366        .scrolls()
367        .then(|| props.scroll_cue.label().map(str::to_string))
368        .flatten();
369    let measure = move || measure_scroll_cue(viewport, viewport_width, overflowing);
370
371    // New rows or columns can widen, narrow, or replace the table without resizing the viewport,
372    // so measure again after every render, once its markup is in place. Like `MessageScroller`, a
373    // render count makes the effect rerun. Before the early return, so hook order stays stable.
374    let renders = use_hook(|| Rc::new(Cell::new(0_u64)));
375    renders.set(renders.get() + 1);
376    let render = renders.get();
377    let active = cue.is_some();
378    use_effect(use_reactive((&render, &active), move |(_, active)| {
379        if active {
380            measure();
381        } else if viewport.peek().is_some() {
382            // The viewport unmounted with the cue. Forget it and its size, so a returning cue
383            // starts hidden and measures only its own new viewport.
384            viewport.set(None);
385            viewport_width.set(0.0);
386            overflowing.set(false);
387        }
388    }));
389
390    let Some(label) = cue else {
391        // A sticky header caps the frame's height and scrolls it, so keyboard users must reach it.
392        let region = TableRegion::sticky(sticky_header, &props.attributes);
393
394        return rsx! {
395            div {
396                aria_label: region.aria_label,
397                class,
398                "data-slot": "table",
399                role: region.role,
400                tabindex: region.tabindex,
401                ..props.attributes,
402                WithoutViewTableDefaults { {props.children} }
403            }
404        };
405    };
406
407    let visible = overflowing();
408    let region = TableRegion::defaults(&props.attributes);
409    let described_by = visible
410        .then(|| merge_described_by(&mut props.attributes, Some(&message_id)))
411        .flatten();
412
413    rsx! {
414        div { class: "ui-table-scroll", "data-ui-scroll-cue": "",
415            div {
416                class: "ui-scroll-cue",
417                "data-scroll-cue-message": "",
418                "data-slot": "scroll-cue",
419                hidden: !visible,
420                id: "{message_id}",
421                {icon_svg(&lucide::MOVE_HORIZONTAL, &icon_svg_class(&lucide::MOVE_HORIZONTAL))}
422                span { "{label}" }
423            }
424            div {
425                aria_describedby: described_by,
426                aria_label: region.aria_label,
427                class,
428                "data-scroll-cue-viewport": "",
429                "data-slot": "table",
430                role: region.role,
431                tabindex: region.tabindex,
432                onmounted: move |event| {
433                    viewport.set(Some(event.data()));
434                    measure();
435                },
436                onresize: move |event| {
437                    if let Ok(size) = event.get_content_box_size() {
438                        viewport_width.set(size.width);
439                    }
440
441                    measure();
442                },
443                ..props.attributes,
444                WithoutViewTableDefaults { {props.children} }
445            }
446        }
447    }
448}
449
450#[cfg(test)]
451mod tests {
452    use super::*;
453
454    #[test]
455    fn layouts_map_to_wrapper_classes() {
456        assert_eq!(TableLayout::default(), TableLayout::Scroll);
457        assert_eq!(TableLayout::Scroll.class(), None);
458        assert_eq!(TableLayout::Records.class(), Some("ui-table-wrap--records"));
459        assert_eq!(
460            TableLayout::Condensed.class(),
461            Some("ui-table-wrap--condensed")
462        );
463        assert!(TableLayout::Scroll.scrolls());
464        assert!(TableLayout::Condensed.scrolls());
465        assert!(!TableLayout::Records.scrolls());
466    }
467
468    #[test]
469    fn the_first_column_without_a_slot_becomes_the_title() {
470        use TableRecordSlot::{Actions, Meta, Title, Wide};
471
472        assert_eq!(
473            resolve_table_record_slots(&[(None, false), (None, false)]),
474            [Some(Title), None]
475        );
476        assert_eq!(
477            resolve_table_record_slots(&[
478                (Some(Wide), false),
479                (None, false),
480                (Some(Actions), false)
481            ]),
482            [Some(Wide), Some(Title), Some(Actions)]
483        );
484        // An explicit title wins, even after other columns without a slot.
485        assert_eq!(
486            resolve_table_record_slots(&[(None, false), (Some(Title), false)]),
487            [None, Some(Title)]
488        );
489        // Every column has a slot: nothing becomes the title.
490        assert_eq!(
491            resolve_table_record_slots(&[(Some(Meta), false), (Some(Wide), false)]),
492            [Some(Meta), Some(Wide)]
493        );
494        // A narrow table hides secondary columns, so none becomes the default title.
495        assert_eq!(
496            resolve_table_record_slots(&[(None, true), (None, false)]),
497            [None, Some(Title)]
498        );
499        assert_eq!(
500            resolve_table_record_slots(&[(None, true), (None, true)]),
501            [None, None]
502        );
503        // Only the first explicit title counts; a later one gets no slot and no default title.
504        assert_eq!(
505            resolve_table_record_slots(&[(None, false), (Some(Title), false), (Some(Title), true)]),
506            [None, Some(Title), None]
507        );
508        assert_eq!(
509            resolve_table_record_slots(&[]),
510            [] as [Option<TableRecordSlot>; 0]
511        );
512    }
513
514    #[test]
515    fn cell_classes_follow_lumen_core() {
516        use TableRecordSlot::{Actions, Meta, Title, Trailing, Wide};
517
518        assert_eq!(table_cell_class(None, false), None);
519        assert_eq!(
520            table_cell_class(Some(Title), false).as_deref(),
521            Some("ui-table__cell--title")
522        );
523        assert_eq!(
524            table_cell_class(Some(Trailing), true).as_deref(),
525            Some("ui-table__cell--trailing ui-table__cell--secondary")
526        );
527        assert_eq!(
528            table_cell_class(None, true).as_deref(),
529            Some("ui-table__cell--secondary")
530        );
531
532        for slot in [Actions, Meta, Trailing, Wide] {
533            assert_eq!(table_header_class(Some(slot), false), None);
534            assert_eq!(
535                table_cell_class(Some(slot), false).as_deref(),
536                Some(slot.cell_class())
537            );
538        }
539
540        // A title stays visible even when its column is marked secondary.
541        assert_eq!(
542            table_header_class(Some(Title), true).as_deref(),
543            Some("ui-table__cell--title")
544        );
545        assert_eq!(
546            table_cell_class(Some(Title), true).as_deref(),
547            Some("ui-table__cell--title")
548        );
549        assert_eq!(
550            table_header_class(Some(Wide), true).as_deref(),
551            Some("ui-table__cell--secondary")
552        );
553        assert_eq!(Title.as_str(), "title");
554    }
555
556    #[test]
557    fn scroll_cues_convert_from_booleans_and_text() {
558        assert_eq!(TableScrollCue::from(false).label(), None);
559        assert_eq!(
560            TableScrollCue::from(true).label(),
561            Some("Scroll horizontally to compare")
562        );
563        assert_eq!(TableScrollCue::from("Swipe").label(), Some("Swipe"));
564        assert_eq!(TableScrollCue::from(""), TableScrollCue::Off);
565        assert_eq!(TableScrollCue::Label(String::new()).label(), None);
566    }
567
568    #[test]
569    fn overflow_needs_a_width_and_more_than_one_pixel() {
570        assert!(!table_overflows(0.0, 500.0));
571        assert!(!table_overflows(400.0, 400.0));
572        assert!(!table_overflows(400.0, 401.0));
573        assert!(table_overflows(400.0, 401.5));
574        assert!(table_overflows(400.0, 800.0));
575        assert!(!table_overflows(f64::NAN, 800.0));
576    }
577}