Skip to main content

lumen_dioxus/data/data_table/
view.rs

1//! `DataTableView`: search, filters, column visibility, density, sorting, and pagination around
2//! an application-rendered table.
3
4// cspell:words fieldset
5
6use dioxus::prelude::*;
7
8use super::model::{
9    DataTableDensity, DataTablePagination, DataTableRow, DataTableSort, DataTableViewColumn,
10    DataTableViewState, data_table_column_visible, data_table_view_page,
11    toggle_data_table_view_sort,
12};
13use crate::data::stat::fill_template;
14use crate::data::table::DataTableViewTableDefaults;
15use crate::hooks::{use_controllable, use_unique_id};
16use crate::{Button, ButtonVariant, Checkbox, Field, Input, Label};
17
18/// Copy for a [`DataTableView`]. `page` uses `{page}`, `{pages}`, and `{count}` placeholders.
19#[derive(Clone, Debug, PartialEq, Eq)]
20pub struct DataTableViewLabels {
21    /// Search label.
22    pub search: String,
23    /// Legend of the column visibility checkboxes.
24    pub columns: String,
25    /// Filter option for every value.
26    pub all: String,
27    /// Density select label.
28    pub density: String,
29    /// Comfortable density option.
30    pub comfortable: String,
31    /// Compact density option.
32    pub compact: String,
33    /// Page size select label.
34    pub page_size: String,
35    /// Previous page button.
36    pub previous: String,
37    /// Next page button.
38    pub next: String,
39    /// Announced when no rows match.
40    pub empty: String,
41    /// Page status, with one-based `{page}`, at least one `{pages}`, and `{count}` matching rows.
42    pub page: String,
43}
44
45impl Default for DataTableViewLabels {
46    fn default() -> Self {
47        Self {
48            search: "Search records".into(),
49            columns: "Columns".into(),
50            all: "All".into(),
51            density: "Density".into(),
52            comfortable: "Comfortable".into(),
53            compact: "Compact".into(),
54            page_size: "Rows per page".into(),
55            previous: "Previous page".into(),
56            next: "Next page".into(),
57            empty: "No matching records".into(),
58            page: "Page {page} of {pages} ยท {count} records".into(),
59        }
60    }
61}
62
63/// What a [`DataTableView`] hands to its `render` callback.
64#[derive(Clone, PartialEq)]
65pub struct DataTableViewResult {
66    /// Rows of the current page, in display order.
67    pub rows: Vec<DataTableRow>,
68    /// Keys of the visible columns, in column order.
69    pub visible_columns: Vec<String>,
70    /// Rows that match the search and filters.
71    pub filtered_count: usize,
72    /// The current view state.
73    pub state: DataTableViewState,
74    /// Activates a header: `(key, multiple)`. A new criterion starts ascending, an existing one
75    /// reverses, and `multiple` keeps the other criteria.
76    pub toggle_sort: Callback<(String, bool)>,
77}
78
79impl DataTableViewResult {
80    /// Whether a column is visible.
81    pub fn is_column_visible(&self, key: &str) -> bool {
82        self.visible_columns.iter().any(|visible| visible == key)
83    }
84
85    /// The direction a column is sorted by, if any, for `aria-sort`.
86    pub fn sort_of(&self, key: &str) -> Option<&DataTableSort> {
87        self.state.sorting.iter().find(|sort| sort.key == key)
88    }
89}
90
91/// Props for [`DataTableView`].
92#[derive(Props, Clone, PartialEq)]
93pub struct DataTableViewProps {
94    /// Accessible name of the view.
95    #[props(into)]
96    pub label: String,
97    /// All records in client mode, or the current page in server mode. Ids must be unique.
98    pub rows: Vec<DataTableRow>,
99    /// Column configuration.
100    pub columns: Vec<DataTableViewColumn>,
101    /// Renders the table for the current page.
102    pub render: Callback<DataTableViewResult, Element>,
103    /// Controlled view state.
104    pub state: Option<DataTableViewState>,
105    /// Initial state when uncontrolled.
106    #[props(default)]
107    pub default_state: DataTableViewState,
108    /// Called with every new state.
109    pub on_state_change: Option<EventHandler<DataTableViewState>>,
110    /// Server mode: the total matching rows. The view then never filters, sorts, or slices
111    /// `rows`; the application loads the page the state describes.
112    pub row_count: Option<usize>,
113    /// Disables every control.
114    #[props(default)]
115    pub disabled: bool,
116    /// Shows the search field. Defaults to true.
117    #[props(default = true)]
118    pub searchable: bool,
119    /// Extra toolbar content.
120    pub toolbar: Option<Element>,
121    /// Localized copy.
122    #[props(default)]
123    pub labels: DataTableViewLabels,
124}
125
126/// A view controller around an application-rendered table, like lumen-react's
127/// `DataTableView`: search, exact-match filters, column visibility, density, sorting, and
128/// pagination, in client or server mode.
129///
130/// A [`Table`](crate::Table) or [`DataTable`](crate::DataTable) that `render` returns keeps its
131/// header row visible unless it sets `sticky_header: false`, and compact density reaches it
132/// through `data-ui-density="compact"` on the view. A `DataTable` there renders no default empty
133/// row, since the view announces empty results; pass `empty` to show one anyway.
134///
135/// Range filters, saved views, column layout controls, and the selection toolbar of
136/// lumen-react are not ported.
137#[component]
138#[allow(clippy::too_many_lines)]
139pub fn DataTableView(props: DataTableViewProps) -> Element {
140    let id = use_unique_id();
141    use_context_provider(|| DataTableViewTableDefaults {
142        sticky_header: true,
143        empty_row: false,
144    });
145    let view = use_controllable(
146        props.state.clone(),
147        || props.default_state.clone(),
148        props.on_state_change,
149    );
150    let state = view.get();
151    let columns = props.columns.clone();
152    let page = data_table_view_page(&props.rows, &columns, &state, props.row_count);
153    let visible_columns: Vec<String> = columns
154        .iter()
155        .filter(|column| data_table_column_visible(&columns, &state, &column.key))
156        .map(|column| column.key.clone())
157        .collect();
158    let disabled = props.disabled;
159    let sort_columns = columns.clone();
160    let toggle_sort = use_callback(move |(key, multiple): (String, bool)| {
161        if disabled
162            || !sort_columns
163                .iter()
164                .any(|column| column.key == key && column.sortable)
165        {
166            return;
167        }
168
169        let mut next = view.peek();
170        next.sorting = toggle_data_table_view_sort(&next.sorting, &key, multiple);
171        view.set(next.first_page());
172    });
173    let result = DataTableViewResult {
174        rows: page
175            .rows
176            .iter()
177            .map(|index| props.rows[*index].clone())
178            .collect(),
179        visible_columns: visible_columns.clone(),
180        filtered_count: page.matching,
181        state: state.clone(),
182        toggle_sort,
183    };
184    let labels = props.labels.clone();
185    let mut sizes = vec![10, 25, 50, 100, state.pagination.page_size];
186    sizes.sort_unstable();
187    sizes.dedup();
188    let page_text = fill_template(
189        &labels.page,
190        &[
191            ("count", &page.matching.to_string()),
192            ("page", &(page.page_index + 1).to_string()),
193            ("pages", &page.pages.to_string()),
194        ],
195    );
196    let page_index = page.page_index;
197    let pages = page.pages;
198    let visible_count = visible_columns.len();
199
200    rsx! {
201        section {
202            aria_label: "{props.label}",
203            class: "ui-data-table-view",
204            "data-density": state.density.as_str(),
205            // Compact density reaches every Table and DataTable inside the view through the
206            // shared density tokens.
207            "data-ui-density": (state.density == DataTableDensity::Compact).then_some("compact"),
208            role: "group",
209            div { class: "ui-data-table-view__toolbar",
210                if props.searchable {
211                    Field { control_id: "{id}-search",
212                        Label { r#for: "{id}-search", "{labels.search}" }
213                        Input {
214                            disabled,
215                            id: "{id}-search",
216                            r#type: "search",
217                            value: "{state.search}",
218                            oninput: move |event: FormEvent| {
219                                let mut next = view.peek();
220                                next.search = event.value();
221                                view.set(next.first_page());
222                            },
223                        }
224                    }
225                }
226                for (index, column) in columns.iter().filter(|column| !column.filter_options.is_empty()).enumerate() {
227                    {
228                        let key = column.key.clone();
229                        let current = state.filter_value(&column.key).to_string();
230
231                        rsx! {
232                            Field { key: "{column.key}", control_id: "{id}-column-{index}",
233                                Label { r#for: "{id}-column-{index}", "{column.label}" }
234                                select {
235                                    class: "ui-select",
236                                    disabled,
237                                    id: "{id}-column-{index}",
238                                    oninput: move |event| view.set(view.peek().with_filter(&key, &event.value()).first_page()),
239                                    option { selected: current.is_empty(), value: "", "{labels.all}" }
240                                    for (value, text) in column.filter_options.iter() {
241                                        option { key: "{value}", selected: current == *value, value: "{value}", "{text}" }
242                                    }
243                                }
244                            }
245                        }
246                    }
247                }
248                Field { control_id: "{id}-density",
249                    Label { r#for: "{id}-density", "{labels.density}" }
250                    select {
251                        class: "ui-select",
252                        disabled,
253                        id: "{id}-density",
254                        oninput: move |event| {
255                            let mut next = view.peek();
256                            next.density = if event.value() == "compact" { DataTableDensity::Compact } else { DataTableDensity::Comfortable };
257                            view.set(next);
258                        },
259                        option { selected: state.density == DataTableDensity::Comfortable, value: "comfortable", "{labels.comfortable}" }
260                        option { selected: state.density == DataTableDensity::Compact, value: "compact", "{labels.compact}" }
261                    }
262                }
263                if let Some(toolbar) = props.toolbar {
264                    {toolbar}
265                }
266            }
267            fieldset { class: "ui-data-table-view__columns", disabled,
268                legend { "{labels.columns}" }
269                for column in columns.iter().filter(|column| column.can_hide) {
270                    {
271                        let key = column.key.clone();
272                        let visible = visible_columns.contains(&column.key);
273
274                        rsx! {
275                            Label { key: "{column.key}",
276                                Checkbox {
277                                    checked: visible,
278                                    disabled: disabled || (visible && visible_count <= 1),
279                                    onchange: move |checked: bool| view.set(view.peek().with_visibility(&key, checked)),
280                                }
281                                "{column.label}"
282                            }
283                        }
284                    }
285                }
286            }
287            {props.render.call(result)}
288            if page.matching == 0 {
289                p { role: "status", "{labels.empty}" }
290            }
291            div { class: "ui-data-table-view__pagination",
292                Field { control_id: "{id}-size",
293                    Label { r#for: "{id}-size", "{labels.page_size}" }
294                    select {
295                        class: "ui-select",
296                        disabled,
297                        id: "{id}-size",
298                        oninput: move |event| {
299                            if let Ok(size) = event.value().parse::<usize>() {
300                                let mut next = view.peek();
301                                next.pagination = DataTablePagination { page_index: 0, page_size: size.max(1) };
302                                view.set(next);
303                            }
304                        },
305                        for size in sizes {
306                            option { key: "{size}", selected: size == state.pagination.page_size, value: "{size}", "{size}" }
307                        }
308                    }
309                }
310                span { aria_live: "polite", role: "status", "{page_text}" }
311                Button {
312                    disabled: disabled || page_index == 0,
313                    variant: ButtonVariant::Outline,
314                    onclick: move |_| {
315                        let mut next = view.peek();
316                        next.pagination.page_index = page_index.saturating_sub(1);
317                        view.set(next);
318                    },
319                    "{labels.previous}"
320                }
321                Button {
322                    disabled: disabled || page_index + 1 >= pages,
323                    variant: ButtonVariant::Outline,
324                    onclick: move |_| {
325                        let mut next = view.peek();
326                        next.pagination.page_index = page_index + 1;
327                        view.set(next);
328                    },
329                    "{labels.next}"
330                }
331            }
332        }
333    }
334}