Skip to main content

next_rust_ui/
table.rs

1//! Tables.
2
3use next_rust_view::{Element, Node, View};
4
5use crate::button::{common_methods, with_parts};
6use crate::{Extra, Radius, apply, attr, root, styled};
7
8/// A data table. `columns` become the header; the children are the rows
9/// (`tr![td![..], ..]`), placed in the body. Wide tables scroll sideways
10/// inside their box instead of breaking the page.
11///
12/// ```
13/// # use next_rust_ui::*; use next_rust_view::*;
14/// let t = Table![columns = ["Name", "Score"], striped = true,
15///     tr![td!["Ada"], td!["98"]],
16///     tr![td!["Grace"], td!["95"]],
17/// ];
18/// let html = render_static(t);
19/// assert!(html.contains(r#"<table class="nr-table nr-table-striped">"#), "{html}");
20/// assert!(html.contains(r#"<th scope="col">Name</th>"#) && html.contains("<tbody><tr><td>Ada</td>"));
21/// ```
22#[derive(Default)]
23pub struct Table {
24    columns: Vec<String>,
25    caption: Option<String>,
26    striped: bool,
27    compact: bool,
28    bordered: bool,
29    hoverable: bool,
30    sticky_header: bool,
31    radius: Option<Radius>,
32    empty: Option<Node>,
33    unstyled: bool,
34    extra: Extra,
35}
36
37impl Table {
38    pub fn new() -> Self {
39        Self::default()
40    }
41    common_methods!();
42    with_parts!();
43
44    /// Header cells, in order.
45    pub fn columns<I, S>(mut self, v: I) -> Self
46    where
47        I: IntoIterator<Item = S>,
48        S: Into<String>,
49    {
50        self.columns = v.into_iter().map(Into::into).collect();
51        self
52    }
53    /// A visible `<caption>` (also the table's accessible name).
54    pub fn caption(mut self, v: impl Into<String>) -> Self {
55        self.caption = Some(v.into());
56        self
57    }
58    pub fn striped(mut self, v: bool) -> Self {
59        self.striped = v;
60        self
61    }
62    pub fn compact(mut self, v: bool) -> Self {
63        self.compact = v;
64        self
65    }
66    /// Lines between cells.
67    pub fn bordered(mut self, v: bool) -> Self {
68        self.bordered = v;
69        self
70    }
71    /// Highlight the row under the pointer.
72    pub fn hoverable(mut self, v: bool) -> Self {
73        self.hoverable = v;
74        self
75    }
76    /// The header stays visible while the body scrolls.
77    pub fn sticky_header(mut self, v: bool) -> Self {
78        self.sticky_header = v;
79        self
80    }
81    pub fn radius(mut self, v: Radius) -> Self {
82        self.radius = Some(v);
83        self
84    }
85    /// Shown across the table when there are no rows.
86    pub fn empty(mut self, v: impl View) -> Self {
87        self.empty = Some(v.into_node());
88        self
89    }
90}
91
92impl View for Table {
93    fn into_node(self) -> Node {
94        let (class, attrs, rows) = self.extra.split();
95        let classes = [
96            "nr-table-wrap",
97            self.radius.map(Radius::class).unwrap_or(""),
98            if self.sticky_header { "nr-table-sticky" } else { "" },
99        ];
100        let mut el = root("div", &classes, self.unstyled, class);
101        apply(&mut el, attrs);
102        let table_classes = [
103            "nr-table",
104            if self.striped { "nr-table-striped" } else { "" },
105            if self.compact { "nr-table-compact" } else { "" },
106            if self.bordered { "nr-table-bordered" } else { "" },
107            if self.hoverable { "nr-table-hoverable" } else { "" },
108        ];
109        let mut table = Element::new("table")
110            .with(attr("class", table_classes.iter().filter(|c| !c.is_empty()).copied().collect::<Vec<_>>().join(" ")));
111        if let Some(caption) = self.caption {
112            table
113                .children
114                .push(Element::new("caption").with(attr("class", "nr-table-caption")).with(caption).into_node());
115        }
116        let width = self.columns.len();
117        if width > 0 {
118            let mut tr = Element::new("tr");
119            for column in self.columns {
120                tr.children.push(Element::new("th").with(attr("scope", "col")).with(column).into_node());
121            }
122            table.children.push(Element::new("thead").with(tr).into_node());
123        }
124        let mut body = Element::new("tbody");
125        let has_rows = rows.iter().any(|r| !matches!(r, Node::Empty | Node::Style(_)));
126        if has_rows {
127            body.children = rows;
128        } else if let Some(empty) = self.empty {
129            let mut cell = Element::new("td").with(attr("class", "nr-table-empty")).with(empty);
130            if width > 1 {
131                cell.set_attr(attr("colspan", width.to_string()));
132            }
133            body.children.push(Element::new("tr").with(cell).into_node());
134        }
135        table.children.push(body.into_node());
136        el.children.push(table.into_node());
137        styled(el)
138    }
139}