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
//! `Table`: the styled wrapper for a semantic `<table>`, its scroll cue, and the record slots it
//! shares with [`DataTable`](crate::DataTable).

use std::cell::Cell;
use std::rc::Rc;

use dioxus::prelude::*;

use crate::class::{Glass, compose};
use crate::form::merge_described_by;
use crate::hooks::use_unique_id;
use crate::icons::{icon_svg, icon_svg_class, lucide};

/// The scroll cue text when [`TableScrollCue::On`] gives none, like lumen-core's
/// `lumenDataTableDefaults.scrollCueLabel`.
const DEFAULT_SCROLL_CUE_LABEL: &str = "Scroll horizontally to compare";

/// How a [`Table`] or [`DataTable`](crate::DataTable) adapts to narrow widths.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum TableLayout {
    /// The table scrolls horizontally.
    #[default]
    Scroll,
    /// Rows stack into labelled record cards while the table is under 48rem wide.
    Records,
    /// The table keeps its columns and hides secondary ones while it is under 48rem wide; what
    /// remains scrolls horizontally.
    Condensed,
}

impl TableLayout {
    /// The wrapper class: `ui-table-wrap--records`, `ui-table-wrap--condensed`, or none.
    pub fn class(self) -> Option<&'static str> {
        match self {
            Self::Scroll => None,
            Self::Records => Some("ui-table-wrap--records"),
            Self::Condensed => Some("ui-table-wrap--condensed"),
        }
    }

    /// Whether a wide table scrolls horizontally, so a scroll cue applies: `Scroll` and
    /// `Condensed`.
    pub fn scrolls(self) -> bool {
        matches!(self, Self::Scroll | Self::Condensed)
    }
}

/// Where a column's cells go when a `Records` table stacks into cards, like lumen-core's
/// `LumenTableRecordSlot`.
///
/// Plain [`Table`] authors add [`TableRecordSlot::cell_class`] to their cells;
/// [`DataTable`](crate::DataTable) adds it for `DataTableColumn::record`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum TableRecordSlot {
    /// The card's heading line; the first column's emphasis while the table is wide.
    Title,
    /// The end of the title line, emphasized and without a label.
    Trailing,
    /// Row actions: they hug the row end while wide and end the title line in a card.
    Actions,
    /// A full-width muted line under the title, without a label.
    Meta,
    /// A full-width line with its label above the value.
    Wide,
}

impl TableRecordSlot {
    /// The slot name, such as `title`.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Title => "title",
            Self::Trailing => "trailing",
            Self::Actions => "actions",
            Self::Meta => "meta",
            Self::Wide => "wide",
        }
    }

    /// The cell class, such as `ui-table__cell--title`.
    pub fn cell_class(self) -> &'static str {
        match self {
            Self::Title => "ui-table__cell--title",
            Self::Trailing => "ui-table__cell--trailing",
            Self::Actions => "ui-table__cell--actions",
            Self::Meta => "ui-table__cell--meta",
            Self::Wide => "ui-table__cell--wide",
        }
    }
}

/// Each column's record slot, like lumen-core's `resolveLumenTableRecordSlots`, from each column's
/// `(slot, secondary)` pair. Only the first `Title` is the title; later ones get no slot. When no
/// column is the title, the first column without a slot of its own that isn't secondary becomes
/// it, so every card gets a heading that stays visible.
pub fn resolve_table_record_slots(
    columns: &[(Option<TableRecordSlot>, bool)],
) -> Vec<Option<TableRecordSlot>> {
    let first_title = columns
        .iter()
        .position(|(slot, _)| *slot == Some(TableRecordSlot::Title));
    let mut resolved: Vec<Option<TableRecordSlot>> = columns
        .iter()
        .enumerate()
        .map(|(index, (slot, _))| {
            slot.filter(|kind| *kind != TableRecordSlot::Title || Some(index) == first_title)
        })
        .collect();

    if first_title.is_none()
        && let Some(index) = columns
            .iter()
            .position(|(slot, secondary)| slot.is_none() && !secondary)
        && let Some(slot) = resolved.get_mut(index)
    {
        *slot = Some(TableRecordSlot::Title);
    }

    resolved
}

/// The classes of a column's body cells, like lumen-core's `getLumenTableCellClasses`: the slot
/// class, then `ui-table__cell--secondary`, which a title never gets. `None` when there are none.
///
/// Pass `secondary` only when a title column repeats the value while the table is narrow; without
/// a title nothing repeats it, so the column must stay visible.
pub fn table_cell_class(slot: Option<TableRecordSlot>, secondary: bool) -> Option<String> {
    let hidden = secondary && slot != Some(TableRecordSlot::Title);
    let class = compose([
        slot.map(TableRecordSlot::cell_class),
        hidden.then_some("ui-table__cell--secondary"),
    ]);

    (!class.is_empty()).then_some(class)
}

/// The classes of a column's header cell, like lumen-core's `getLumenTableHeaderClasses`: only
/// the title and secondary markers apply to `th`. `None` when there are none.
pub fn table_header_class(slot: Option<TableRecordSlot>, secondary: bool) -> Option<String> {
    table_cell_class(
        slot.filter(|slot| *slot == TableRecordSlot::Title),
        secondary,
    )
}

/// The scroll cue of a [`Table`]: a hint shown while the table is wider than its frame.
///
/// `true` and `false` convert into `On` and `Off`; a string converts into `Label`, and an empty
/// string into `Off`.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum TableScrollCue {
    /// No cue.
    #[default]
    Off,
    /// A cue that reads `Scroll horizontally to compare`.
    On,
    /// A cue with this text.
    Label(String),
}

impl TableScrollCue {
    /// The cue text, or `None` when the cue is off.
    pub fn label(&self) -> Option<&str> {
        match self {
            Self::Off => None,
            Self::On => Some(DEFAULT_SCROLL_CUE_LABEL),
            Self::Label(label) => (!label.is_empty()).then_some(label.as_str()),
        }
    }
}

impl From<bool> for TableScrollCue {
    fn from(value: bool) -> Self {
        if value { Self::On } else { Self::Off }
    }
}

impl From<String> for TableScrollCue {
    fn from(value: String) -> Self {
        if value.is_empty() {
            Self::Off
        } else {
            Self::Label(value)
        }
    }
}

impl From<&str> for TableScrollCue {
    fn from(value: &str) -> Self {
        Self::from(value.to_string())
    }
}

/// Defaults a [`DataTableView`](crate::DataTableView) gives the `Table` or `DataTable` its
/// `render` callback returns, like lumen-react's `DataTableViewTableContext`. An explicit prop on
/// that table still wins.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct DataTableViewTableDefaults {
    /// Keeps the header row visible while rows scroll.
    pub(crate) sticky_header: bool,
    /// Whether a `DataTable` renders its own empty row. A view announces empty results itself.
    pub(crate) empty_row: bool,
}

/// The table's `sticky_header`, or the enclosing view's default when the prop is unset.
pub(crate) fn use_sticky_header(explicit: Option<bool>) -> bool {
    let defaults = try_use_context::<DataTableViewTableDefaults>();

    explicit.unwrap_or_else(|| defaults.is_some_and(|defaults| defaults.sticky_header))
}

/// Whether a `DataTable` without an explicit `empty` renders its default empty row: not inside a
/// view, which reports empty results in its own status.
pub(crate) fn use_default_empty_row() -> bool {
    try_use_context::<DataTableViewTableDefaults>().is_none_or(|defaults| defaults.empty_row)
}

/// Gives `children` the defaults of a table outside any view, like lumen-react's tables
/// re-providing an empty `DataTableViewTableContext`: the view's defaults are for the table its
/// `render` callback returns, not a table nested in one of its cells or details rows.
#[component]
pub(crate) fn WithoutViewTableDefaults(children: Element) -> Element {
    use_context_provider(|| DataTableViewTableDefaults {
        sticky_header: false,
        empty_row: true,
    });

    children
}

/// The `role`, `tabindex` and `aria-label` a scrolling table frame takes unless its attributes
/// set them: a focusable `region` named `Table`, or by `aria_labelledby`. The scroll-cue viewport
/// and a sticky-header frame, whose capped height scrolls, both use them.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) struct TableRegion {
    pub(crate) role: Option<&'static str>,
    pub(crate) tabindex: Option<&'static str>,
    pub(crate) aria_label: Option<&'static str>,
}

impl TableRegion {
    /// The defaults the attributes leave unset.
    pub(crate) fn defaults(attributes: &[Attribute]) -> Self {
        let named = |name: &str| attributes.iter().any(|attribute| attribute.name == name);

        Self {
            role: (!named("role")).then_some("region"),
            tabindex: (!named("tabindex")).then_some("0"),
            aria_label: (!named("aria-label") && !named("aria-labelledby")).then_some("Table"),
        }
    }

    /// [`TableRegion::defaults`] for a sticky header, else nothing.
    pub(crate) fn sticky(sticky_header: bool, attributes: &[Attribute]) -> Self {
        if sticky_header {
            Self::defaults(attributes)
        } else {
            Self::default()
        }
    }
}

/// Whether a viewport scrolls horizontally, like the Lumen web runtime's scroll cue controller:
/// a measured width, and content more than one pixel wider.
fn table_overflows(client_width: f64, scroll_width: f64) -> bool {
    client_width > 0.0 && scroll_width > client_width + 1.0
}

/// Measures whether the mounted scroll-cue viewport overflows, and stores the answer when it
/// changed. The width is the last `onresize` content width, or the viewport's own rectangle
/// before one arrives.
fn measure_scroll_cue(
    viewport: Signal<Option<Rc<MountedData>>>,
    viewport_width: Signal<f64>,
    mut overflowing: Signal<bool>,
) {
    let Some(node) = viewport.peek().clone() else {
        return;
    };
    let measured = *viewport_width.peek();

    spawn(async move {
        let width = if measured > 0.0 {
            measured
        } else {
            node.get_client_rect()
                .await
                .map_or(0.0, |rect| rect.width())
        };
        let Ok(scroll) = node.get_scroll_size().await else {
            return;
        };
        let next = table_overflows(width, scroll.width);

        if *overflowing.peek() != next {
            overflowing.set(next);
        }
    });
}

/// Props for [`Table`].
#[derive(Props, Clone, PartialEq)]
pub struct TableProps {
    /// 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`. Defaults to `true`
    /// inside a [`DataTableView`](crate::DataTableView), otherwise `false`.
    pub sticky_header: Option<bool>,
    /// Keeps the first column visible while the table scrolls.
    #[props(default)]
    pub sticky_first_column: bool,
    /// A hint shown while the table is wider than its frame, with `Scroll` and `Condensed`
    /// layouts: `true` for the default text, or the text itself.
    #[props(default, into)]
    pub scroll_cue: TableScrollCue,
    /// 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 native `table` with `thead`, `tbody`, `tr`, `th`, and `td` children.
    pub children: Element,
}

/// Styles a semantic table for records and comparisons.
///
/// Compose it with native table elements; in records layout give each `td` a
/// `span { class: "ui-table__label", aria_hidden: "true" }` with its column name, and mark the
/// heading cell with [`TableRecordSlot::cell_class`]. Mark matching numeric `th` and `td`
/// children with `"data-numeric": "true"` for logical end alignment and tabular figures without
/// sorting.
///
/// With `scroll_cue` or `sticky_header`, the frame becomes a focusable, named `region` (`Table`
/// unless you pass `aria_label` or `aria_labelledby`; your `role` and `tabindex` win too). The cue
/// appears while the table overflows. It measures when the frame mounts or resizes and after
/// every render, so rows or columns that arrive through props update it. Renderers that report
/// element sizes (`onresize`) show it; elsewhere it stays hidden.
#[component]
pub fn Table(mut props: TableProps) -> Element {
    let message_id = use_unique_id();
    let mut viewport = use_signal(|| None::<Rc<MountedData>>);
    let mut viewport_width = use_signal(|| 0.0_f64);
    let mut overflowing = use_signal(|| false);
    let sticky_header = use_sticky_header(props.sticky_header);
    let glass = props.glass.class("ui-table-wrap");
    let class = compose([
        Some("ui-table-wrap"),
        glass.as_deref(),
        props.layout.class(),
        props
            .sticky_first_column
            .then_some("ui-table-wrap--sticky-column"),
        sticky_header.then_some("ui-table-wrap--sticky-header"),
        props.class.as_deref(),
    ]);
    let cue = props
        .layout
        .scrolls()
        .then(|| props.scroll_cue.label().map(str::to_string))
        .flatten();
    let measure = move || measure_scroll_cue(viewport, viewport_width, overflowing);

    // New rows or columns can widen, narrow, or replace the table without resizing the viewport,
    // so measure again after every render, once its markup is in place. Like `MessageScroller`, a
    // render count makes the effect rerun. Before the early return, so hook order stays stable.
    let renders = use_hook(|| Rc::new(Cell::new(0_u64)));
    renders.set(renders.get() + 1);
    let render = renders.get();
    let active = cue.is_some();
    use_effect(use_reactive((&render, &active), move |(_, active)| {
        if active {
            measure();
        } else if viewport.peek().is_some() {
            // The viewport unmounted with the cue. Forget it and its size, so a returning cue
            // starts hidden and measures only its own new viewport.
            viewport.set(None);
            viewport_width.set(0.0);
            overflowing.set(false);
        }
    }));

    let Some(label) = cue else {
        // A sticky header caps the frame's height and scrolls it, so keyboard users must reach it.
        let region = TableRegion::sticky(sticky_header, &props.attributes);

        return rsx! {
            div {
                aria_label: region.aria_label,
                class,
                "data-slot": "table",
                role: region.role,
                tabindex: region.tabindex,
                ..props.attributes,
                WithoutViewTableDefaults { {props.children} }
            }
        };
    };

    let visible = overflowing();
    let region = TableRegion::defaults(&props.attributes);
    let described_by = visible
        .then(|| merge_described_by(&mut props.attributes, Some(&message_id)))
        .flatten();

    rsx! {
        div { class: "ui-table-scroll", "data-ui-scroll-cue": "",
            div {
                class: "ui-scroll-cue",
                "data-scroll-cue-message": "",
                "data-slot": "scroll-cue",
                hidden: !visible,
                id: "{message_id}",
                {icon_svg(&lucide::MOVE_HORIZONTAL, &icon_svg_class(&lucide::MOVE_HORIZONTAL))}
                span { "{label}" }
            }
            div {
                aria_describedby: described_by,
                aria_label: region.aria_label,
                class,
                "data-scroll-cue-viewport": "",
                "data-slot": "table",
                role: region.role,
                tabindex: region.tabindex,
                onmounted: move |event| {
                    viewport.set(Some(event.data()));
                    measure();
                },
                onresize: move |event| {
                    if let Ok(size) = event.get_content_box_size() {
                        viewport_width.set(size.width);
                    }

                    measure();
                },
                ..props.attributes,
                WithoutViewTableDefaults { {props.children} }
            }
        }
    }
}

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

    #[test]
    fn layouts_map_to_wrapper_classes() {
        assert_eq!(TableLayout::default(), TableLayout::Scroll);
        assert_eq!(TableLayout::Scroll.class(), None);
        assert_eq!(TableLayout::Records.class(), Some("ui-table-wrap--records"));
        assert_eq!(
            TableLayout::Condensed.class(),
            Some("ui-table-wrap--condensed")
        );
        assert!(TableLayout::Scroll.scrolls());
        assert!(TableLayout::Condensed.scrolls());
        assert!(!TableLayout::Records.scrolls());
    }

    #[test]
    fn the_first_column_without_a_slot_becomes_the_title() {
        use TableRecordSlot::{Actions, Meta, Title, Wide};

        assert_eq!(
            resolve_table_record_slots(&[(None, false), (None, false)]),
            [Some(Title), None]
        );
        assert_eq!(
            resolve_table_record_slots(&[
                (Some(Wide), false),
                (None, false),
                (Some(Actions), false)
            ]),
            [Some(Wide), Some(Title), Some(Actions)]
        );
        // An explicit title wins, even after other columns without a slot.
        assert_eq!(
            resolve_table_record_slots(&[(None, false), (Some(Title), false)]),
            [None, Some(Title)]
        );
        // Every column has a slot: nothing becomes the title.
        assert_eq!(
            resolve_table_record_slots(&[(Some(Meta), false), (Some(Wide), false)]),
            [Some(Meta), Some(Wide)]
        );
        // A narrow table hides secondary columns, so none becomes the default title.
        assert_eq!(
            resolve_table_record_slots(&[(None, true), (None, false)]),
            [None, Some(Title)]
        );
        assert_eq!(
            resolve_table_record_slots(&[(None, true), (None, true)]),
            [None, None]
        );
        // Only the first explicit title counts; a later one gets no slot and no default title.
        assert_eq!(
            resolve_table_record_slots(&[(None, false), (Some(Title), false), (Some(Title), true)]),
            [None, Some(Title), None]
        );
        assert_eq!(
            resolve_table_record_slots(&[]),
            [] as [Option<TableRecordSlot>; 0]
        );
    }

    #[test]
    fn cell_classes_follow_lumen_core() {
        use TableRecordSlot::{Actions, Meta, Title, Trailing, Wide};

        assert_eq!(table_cell_class(None, false), None);
        assert_eq!(
            table_cell_class(Some(Title), false).as_deref(),
            Some("ui-table__cell--title")
        );
        assert_eq!(
            table_cell_class(Some(Trailing), true).as_deref(),
            Some("ui-table__cell--trailing ui-table__cell--secondary")
        );
        assert_eq!(
            table_cell_class(None, true).as_deref(),
            Some("ui-table__cell--secondary")
        );

        for slot in [Actions, Meta, Trailing, Wide] {
            assert_eq!(table_header_class(Some(slot), false), None);
            assert_eq!(
                table_cell_class(Some(slot), false).as_deref(),
                Some(slot.cell_class())
            );
        }

        // A title stays visible even when its column is marked secondary.
        assert_eq!(
            table_header_class(Some(Title), true).as_deref(),
            Some("ui-table__cell--title")
        );
        assert_eq!(
            table_cell_class(Some(Title), true).as_deref(),
            Some("ui-table__cell--title")
        );
        assert_eq!(
            table_header_class(Some(Wide), true).as_deref(),
            Some("ui-table__cell--secondary")
        );
        assert_eq!(Title.as_str(), "title");
    }

    #[test]
    fn scroll_cues_convert_from_booleans_and_text() {
        assert_eq!(TableScrollCue::from(false).label(), None);
        assert_eq!(
            TableScrollCue::from(true).label(),
            Some("Scroll horizontally to compare")
        );
        assert_eq!(TableScrollCue::from("Swipe").label(), Some("Swipe"));
        assert_eq!(TableScrollCue::from(""), TableScrollCue::Off);
        assert_eq!(TableScrollCue::Label(String::new()).label(), None);
    }

    #[test]
    fn overflow_needs_a_width_and_more_than_one_pixel() {
        assert!(!table_overflows(0.0, 500.0));
        assert!(!table_overflows(400.0, 400.0));
        assert!(!table_overflows(400.0, 401.0));
        assert!(table_overflows(400.0, 401.5));
        assert!(table_overflows(400.0, 800.0));
        assert!(!table_overflows(f64::NAN, 800.0));
    }
}