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};
const DEFAULT_SCROLL_CUE_LABEL: &str = "Scroll horizontally to compare";
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum TableLayout {
#[default]
Scroll,
Records,
Condensed,
}
impl TableLayout {
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"),
}
}
pub fn scrolls(self) -> bool {
matches!(self, Self::Scroll | Self::Condensed)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum TableRecordSlot {
Title,
Trailing,
Actions,
Meta,
Wide,
}
impl TableRecordSlot {
pub fn as_str(self) -> &'static str {
match self {
Self::Title => "title",
Self::Trailing => "trailing",
Self::Actions => "actions",
Self::Meta => "meta",
Self::Wide => "wide",
}
}
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",
}
}
}
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
}
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)
}
pub fn table_header_class(slot: Option<TableRecordSlot>, secondary: bool) -> Option<String> {
table_cell_class(
slot.filter(|slot| *slot == TableRecordSlot::Title),
secondary,
)
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum TableScrollCue {
#[default]
Off,
On,
Label(String),
}
impl TableScrollCue {
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())
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct DataTableViewTableDefaults {
pub(crate) sticky_header: bool,
pub(crate) empty_row: bool,
}
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))
}
pub(crate) fn use_default_empty_row() -> bool {
try_use_context::<DataTableViewTableDefaults>().is_none_or(|defaults| defaults.empty_row)
}
#[component]
pub(crate) fn WithoutViewTableDefaults(children: Element) -> Element {
use_context_provider(|| DataTableViewTableDefaults {
sticky_header: false,
empty_row: true,
});
children
}
#[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 {
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"),
}
}
pub(crate) fn sticky(sticky_header: bool, attributes: &[Attribute]) -> Self {
if sticky_header {
Self::defaults(attributes)
} else {
Self::default()
}
}
}
fn table_overflows(client_width: f64, scroll_width: f64) -> bool {
client_width > 0.0 && scroll_width > client_width + 1.0
}
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);
}
});
}
#[derive(Props, Clone, PartialEq)]
pub struct TableProps {
#[props(default)]
pub layout: TableLayout,
pub sticky_header: Option<bool>,
#[props(default)]
pub sticky_first_column: bool,
#[props(default, into)]
pub scroll_cue: TableScrollCue,
#[props(default, into)]
pub glass: Glass,
#[props(into)]
pub class: Option<String>,
#[props(extends = GlobalAttributes, extends = div)]
pub attributes: Vec<Attribute>,
pub children: Element,
}
#[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);
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() {
viewport.set(None);
viewport_width.set(0.0);
overflowing.set(false);
}
}));
let Some(label) = cue else {
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)]
);
assert_eq!(
resolve_table_record_slots(&[(None, false), (Some(Title), false)]),
[None, Some(Title)]
);
assert_eq!(
resolve_table_record_slots(&[(Some(Meta), false), (Some(Wide), false)]),
[Some(Meta), Some(Wide)]
);
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]
);
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())
);
}
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));
}
}