lumen-dioxus 6.0.0

Lumen UI components for Dioxus: web, desktop, mobile, and Dioxus Native (Blitz).
Documentation
//! `DataTableView`: search, filters, column visibility, density, sorting, and pagination around
//! an application-rendered table.

// cspell:words fieldset

use dioxus::prelude::*;

use super::model::{
    DataTableDensity, DataTablePagination, DataTableRow, DataTableSort, DataTableViewColumn,
    DataTableViewState, data_table_column_visible, data_table_view_page,
    toggle_data_table_view_sort,
};
use crate::data::stat::fill_template;
use crate::data::table::DataTableViewTableDefaults;
use crate::hooks::{use_controllable, use_unique_id};
use crate::{Button, ButtonVariant, Checkbox, Field, Input, Label};

/// Copy for a [`DataTableView`]. `page` uses `{page}`, `{pages}`, and `{count}` placeholders.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DataTableViewLabels {
    /// Search label.
    pub search: String,
    /// Legend of the column visibility checkboxes.
    pub columns: String,
    /// Filter option for every value.
    pub all: String,
    /// Density select label.
    pub density: String,
    /// Comfortable density option.
    pub comfortable: String,
    /// Compact density option.
    pub compact: String,
    /// Page size select label.
    pub page_size: String,
    /// Previous page button.
    pub previous: String,
    /// Next page button.
    pub next: String,
    /// Announced when no rows match.
    pub empty: String,
    /// Page status, with one-based `{page}`, at least one `{pages}`, and `{count}` matching rows.
    pub page: String,
}

impl Default for DataTableViewLabels {
    fn default() -> Self {
        Self {
            search: "Search records".into(),
            columns: "Columns".into(),
            all: "All".into(),
            density: "Density".into(),
            comfortable: "Comfortable".into(),
            compact: "Compact".into(),
            page_size: "Rows per page".into(),
            previous: "Previous page".into(),
            next: "Next page".into(),
            empty: "No matching records".into(),
            page: "Page {page} of {pages} ยท {count} records".into(),
        }
    }
}

/// What a [`DataTableView`] hands to its `render` callback.
#[derive(Clone, PartialEq)]
pub struct DataTableViewResult {
    /// Rows of the current page, in display order.
    pub rows: Vec<DataTableRow>,
    /// Keys of the visible columns, in column order.
    pub visible_columns: Vec<String>,
    /// Rows that match the search and filters.
    pub filtered_count: usize,
    /// The current view state.
    pub state: DataTableViewState,
    /// Activates a header: `(key, multiple)`. A new criterion starts ascending, an existing one
    /// reverses, and `multiple` keeps the other criteria.
    pub toggle_sort: Callback<(String, bool)>,
}

impl DataTableViewResult {
    /// Whether a column is visible.
    pub fn is_column_visible(&self, key: &str) -> bool {
        self.visible_columns.iter().any(|visible| visible == key)
    }

    /// The direction a column is sorted by, if any, for `aria-sort`.
    pub fn sort_of(&self, key: &str) -> Option<&DataTableSort> {
        self.state.sorting.iter().find(|sort| sort.key == key)
    }
}

/// Props for [`DataTableView`].
#[derive(Props, Clone, PartialEq)]
pub struct DataTableViewProps {
    /// Accessible name of the view.
    #[props(into)]
    pub label: String,
    /// All records in client mode, or the current page in server mode. Ids must be unique.
    pub rows: Vec<DataTableRow>,
    /// Column configuration.
    pub columns: Vec<DataTableViewColumn>,
    /// Renders the table for the current page.
    pub render: Callback<DataTableViewResult, Element>,
    /// Controlled view state.
    pub state: Option<DataTableViewState>,
    /// Initial state when uncontrolled.
    #[props(default)]
    pub default_state: DataTableViewState,
    /// Called with every new state.
    pub on_state_change: Option<EventHandler<DataTableViewState>>,
    /// Server mode: the total matching rows. The view then never filters, sorts, or slices
    /// `rows`; the application loads the page the state describes.
    pub row_count: Option<usize>,
    /// Disables every control.
    #[props(default)]
    pub disabled: bool,
    /// Shows the search field. Defaults to true.
    #[props(default = true)]
    pub searchable: bool,
    /// Extra toolbar content.
    pub toolbar: Option<Element>,
    /// Localized copy.
    #[props(default)]
    pub labels: DataTableViewLabels,
}

/// A view controller around an application-rendered table, like lumen-react's
/// `DataTableView`: search, exact-match filters, column visibility, density, sorting, and
/// pagination, in client or server mode.
///
/// A [`Table`](crate::Table) or [`DataTable`](crate::DataTable) that `render` returns keeps its
/// header row visible unless it sets `sticky_header: false`, and compact density reaches it
/// through `data-ui-density="compact"` on the view. A `DataTable` there renders no default empty
/// row, since the view announces empty results; pass `empty` to show one anyway.
///
/// Range filters, saved views, column layout controls, and the selection toolbar of
/// lumen-react are not ported.
#[component]
#[allow(clippy::too_many_lines)]
pub fn DataTableView(props: DataTableViewProps) -> Element {
    let id = use_unique_id();
    use_context_provider(|| DataTableViewTableDefaults {
        sticky_header: true,
        empty_row: false,
    });
    let view = use_controllable(
        props.state.clone(),
        || props.default_state.clone(),
        props.on_state_change,
    );
    let state = view.get();
    let columns = props.columns.clone();
    let page = data_table_view_page(&props.rows, &columns, &state, props.row_count);
    let visible_columns: Vec<String> = columns
        .iter()
        .filter(|column| data_table_column_visible(&columns, &state, &column.key))
        .map(|column| column.key.clone())
        .collect();
    let disabled = props.disabled;
    let sort_columns = columns.clone();
    let toggle_sort = use_callback(move |(key, multiple): (String, bool)| {
        if disabled
            || !sort_columns
                .iter()
                .any(|column| column.key == key && column.sortable)
        {
            return;
        }

        let mut next = view.peek();
        next.sorting = toggle_data_table_view_sort(&next.sorting, &key, multiple);
        view.set(next.first_page());
    });
    let result = DataTableViewResult {
        rows: page
            .rows
            .iter()
            .map(|index| props.rows[*index].clone())
            .collect(),
        visible_columns: visible_columns.clone(),
        filtered_count: page.matching,
        state: state.clone(),
        toggle_sort,
    };
    let labels = props.labels.clone();
    let mut sizes = vec![10, 25, 50, 100, state.pagination.page_size];
    sizes.sort_unstable();
    sizes.dedup();
    let page_text = fill_template(
        &labels.page,
        &[
            ("count", &page.matching.to_string()),
            ("page", &(page.page_index + 1).to_string()),
            ("pages", &page.pages.to_string()),
        ],
    );
    let page_index = page.page_index;
    let pages = page.pages;
    let visible_count = visible_columns.len();

    rsx! {
        section {
            aria_label: "{props.label}",
            class: "ui-data-table-view",
            "data-density": state.density.as_str(),
            // Compact density reaches every Table and DataTable inside the view through the
            // shared density tokens.
            "data-ui-density": (state.density == DataTableDensity::Compact).then_some("compact"),
            role: "group",
            div { class: "ui-data-table-view__toolbar",
                if props.searchable {
                    Field { control_id: "{id}-search",
                        Label { r#for: "{id}-search", "{labels.search}" }
                        Input {
                            disabled,
                            id: "{id}-search",
                            r#type: "search",
                            value: "{state.search}",
                            oninput: move |event: FormEvent| {
                                let mut next = view.peek();
                                next.search = event.value();
                                view.set(next.first_page());
                            },
                        }
                    }
                }
                for (index, column) in columns.iter().filter(|column| !column.filter_options.is_empty()).enumerate() {
                    {
                        let key = column.key.clone();
                        let current = state.filter_value(&column.key).to_string();

                        rsx! {
                            Field { key: "{column.key}", control_id: "{id}-column-{index}",
                                Label { r#for: "{id}-column-{index}", "{column.label}" }
                                select {
                                    class: "ui-select",
                                    disabled,
                                    id: "{id}-column-{index}",
                                    oninput: move |event| view.set(view.peek().with_filter(&key, &event.value()).first_page()),
                                    option { selected: current.is_empty(), value: "", "{labels.all}" }
                                    for (value, text) in column.filter_options.iter() {
                                        option { key: "{value}", selected: current == *value, value: "{value}", "{text}" }
                                    }
                                }
                            }
                        }
                    }
                }
                Field { control_id: "{id}-density",
                    Label { r#for: "{id}-density", "{labels.density}" }
                    select {
                        class: "ui-select",
                        disabled,
                        id: "{id}-density",
                        oninput: move |event| {
                            let mut next = view.peek();
                            next.density = if event.value() == "compact" { DataTableDensity::Compact } else { DataTableDensity::Comfortable };
                            view.set(next);
                        },
                        option { selected: state.density == DataTableDensity::Comfortable, value: "comfortable", "{labels.comfortable}" }
                        option { selected: state.density == DataTableDensity::Compact, value: "compact", "{labels.compact}" }
                    }
                }
                if let Some(toolbar) = props.toolbar {
                    {toolbar}
                }
            }
            fieldset { class: "ui-data-table-view__columns", disabled,
                legend { "{labels.columns}" }
                for column in columns.iter().filter(|column| column.can_hide) {
                    {
                        let key = column.key.clone();
                        let visible = visible_columns.contains(&column.key);

                        rsx! {
                            Label { key: "{column.key}",
                                Checkbox {
                                    checked: visible,
                                    disabled: disabled || (visible && visible_count <= 1),
                                    onchange: move |checked: bool| view.set(view.peek().with_visibility(&key, checked)),
                                }
                                "{column.label}"
                            }
                        }
                    }
                }
            }
            {props.render.call(result)}
            if page.matching == 0 {
                p { role: "status", "{labels.empty}" }
            }
            div { class: "ui-data-table-view__pagination",
                Field { control_id: "{id}-size",
                    Label { r#for: "{id}-size", "{labels.page_size}" }
                    select {
                        class: "ui-select",
                        disabled,
                        id: "{id}-size",
                        oninput: move |event| {
                            if let Ok(size) = event.value().parse::<usize>() {
                                let mut next = view.peek();
                                next.pagination = DataTablePagination { page_index: 0, page_size: size.max(1) };
                                view.set(next);
                            }
                        },
                        for size in sizes {
                            option { key: "{size}", selected: size == state.pagination.page_size, value: "{size}", "{size}" }
                        }
                    }
                }
                span { aria_live: "polite", role: "status", "{page_text}" }
                Button {
                    disabled: disabled || page_index == 0,
                    variant: ButtonVariant::Outline,
                    onclick: move |_| {
                        let mut next = view.peek();
                        next.pagination.page_index = page_index.saturating_sub(1);
                        view.set(next);
                    },
                    "{labels.previous}"
                }
                Button {
                    disabled: disabled || page_index + 1 >= pages,
                    variant: ButtonVariant::Outline,
                    onclick: move |_| {
                        let mut next = view.peek();
                        next.pagination.page_index = page_index + 1;
                        view.set(next);
                    },
                    "{labels.next}"
                }
            }
        }
    }
}