1use 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
14const DEFAULT_SCROLL_CUE_LABEL: &str = "Scroll horizontally to compare";
17
18#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
20#[non_exhaustive]
21pub enum TableLayout {
22 #[default]
24 Scroll,
25 Records,
27 Condensed,
30}
31
32impl TableLayout {
33 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 pub fn scrolls(self) -> bool {
45 matches!(self, Self::Scroll | Self::Condensed)
46 }
47}
48
49#[derive(Clone, Copy, Debug, PartialEq, Eq)]
55#[non_exhaustive]
56pub enum TableRecordSlot {
57 Title,
59 Trailing,
61 Actions,
63 Meta,
65 Wide,
67}
68
69impl TableRecordSlot {
70 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 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
93pub 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
123pub 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
138pub 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#[derive(Clone, Debug, Default, PartialEq, Eq)]
152#[non_exhaustive]
153pub enum TableScrollCue {
154 #[default]
156 Off,
157 On,
159 Label(String),
161}
162
163impl TableScrollCue {
164 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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
200pub(crate) struct DataTableViewTableDefaults {
201 pub(crate) sticky_header: bool,
203 pub(crate) empty_row: bool,
205}
206
207pub(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
214pub(crate) fn use_default_empty_row() -> bool {
217 try_use_context::<DataTableViewTableDefaults>().is_none_or(|defaults| defaults.empty_row)
218}
219
220#[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#[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 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 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
265fn table_overflows(client_width: f64, scroll_width: f64) -> bool {
268 client_width > 0.0 && scroll_width > client_width + 1.0
269}
270
271fn 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#[derive(Props, Clone, PartialEq)]
305pub struct TableProps {
306 #[props(default)]
308 pub layout: TableLayout,
309 pub sticky_header: Option<bool>,
313 #[props(default)]
315 pub sticky_first_column: bool,
316 #[props(default, into)]
319 pub scroll_cue: TableScrollCue,
320 #[props(default, into)]
322 pub glass: Glass,
323 #[props(into)]
325 pub class: Option<String>,
326 #[props(extends = GlobalAttributes, extends = div)]
328 pub attributes: Vec<Attribute>,
329 pub children: Element,
331}
332
333#[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 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 viewport.set(None);
385 viewport_width.set(0.0);
386 overflowing.set(false);
387 }
388 }));
389
390 let Some(label) = cue else {
391 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 assert_eq!(
486 resolve_table_record_slots(&[(None, false), (Some(Title), false)]),
487 [None, Some(Title)]
488 );
489 assert_eq!(
491 resolve_table_record_slots(&[(Some(Meta), false), (Some(Wide), false)]),
492 [Some(Meta), Some(Wide)]
493 );
494 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 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 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}