lumen-dioxus 6.0.0

Lumen UI components for Dioxus: web, desktop, mobile, and Dioxus Native (Blitz).
Documentation
//! `DataTableSavedViews`: apply, save, update, remove, and reset saved table views.

use dioxus::prelude::*;

use super::model::DataTableViewState;
use crate::hooks::use_unique_id;
use crate::{Button, ButtonVariant, Field, Input, Label};

/// A named, saved [`DataTableViewState`].
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DataTableSavedView {
    /// Unique, non-empty id.
    pub id: String,
    /// Visible name.
    pub label: String,
    /// The saved preferences.
    pub state: DataTableViewState,
}

/// Copy for [`DataTableSavedViews`].
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DataTableSavedViewsLabels {
    /// Accessible name of the region.
    pub region: String,
    /// Saved view select label.
    pub view: String,
    /// Placeholder option while no saved view is active.
    pub custom: String,
    /// New view name label.
    pub name: String,
    /// Save button.
    pub save: String,
    /// Update button.
    pub update: String,
    /// Remove button.
    pub remove: String,
    /// Reset button.
    pub reset: String,
}

impl Default for DataTableSavedViewsLabels {
    fn default() -> Self {
        Self {
            region: "Saved record views".into(),
            view: "Saved view".into(),
            custom: "Custom view".into(),
            name: "New view name".into(),
            save: "Save new view".into(),
            update: "Update view".into(),
            remove: "Remove view".into(),
            reset: "Reset view".into(),
        }
    }
}

/// Most characters of a new view name.
pub const DATA_TABLE_SAVED_VIEW_NAME_LIMIT: usize = 120;

/// The state a saved view stores: the preferences, starting on the first page.
pub fn data_table_saved_state(state: &DataTableViewState) -> DataTableViewState {
    state.clone().first_page()
}

/// Props for [`DataTableSavedViews`].
#[derive(Props, Clone, PartialEq)]
pub struct DataTableSavedViewsProps {
    /// Saved views with unique, non-empty ids; views with an empty or repeated id are skipped.
    pub views: Vec<DataTableSavedView>,
    /// The current view state, used by save and update.
    pub state: DataTableViewState,
    /// The applied saved view.
    #[props(into)]
    pub active_id: Option<String>,
    /// The state the reset button applies.
    pub reset_state: DataTableViewState,
    /// Called with a state to apply and the saved view id, or `None` after a reset.
    pub on_apply: EventHandler<(DataTableViewState, Option<String>)>,
    /// Called with a trimmed name and the state to save.
    pub on_save: EventHandler<(String, DataTableViewState)>,
    /// Shows an update button for the active view.
    pub on_update: Option<EventHandler<(String, DataTableViewState)>>,
    /// Shows a remove button for the active view.
    pub on_remove: Option<EventHandler<String>>,
    /// Disables every control.
    #[props(default)]
    pub disabled: bool,
    /// Localized copy.
    #[props(default)]
    pub labels: DataTableSavedViewsLabels,
}

/// Apply, save, update, remove, and reset saved table views. Persistence is the application's:
/// the component calls back and stores nothing itself.
#[component]
#[allow(clippy::too_many_lines)]
pub fn DataTableSavedViews(props: DataTableSavedViewsProps) -> Element {
    let id = use_unique_id();
    let mut name = use_signal(String::new);
    let mut seen = std::collections::HashSet::new();
    let views: Vec<DataTableSavedView> = props
        .views
        .iter()
        .filter(|view| !view.id.trim().is_empty() && seen.insert(view.id.clone()))
        .cloned()
        .collect();
    let active = props
        .active_id
        .as_ref()
        .and_then(|active| views.iter().find(|view| view.id == *active))
        .cloned();
    let labels = props.labels.clone();
    let disabled = props.disabled;
    let on_apply = props.on_apply;
    let on_save = props.on_save;
    let state = props.state.clone();
    let update_state = state.clone();
    let reset_state = props.reset_state.clone();
    let apply_views = views.clone();
    let (update_active, remove_active) = (active.clone(), active.clone());

    rsx! {
        section {
            aria_busy: if disabled { "true" } else { "false" },
            aria_label: "{labels.region}",
            class: "ui-data-table-view__saved",
            Field { control_id: "{id}-view",
                Label { r#for: "{id}-view", "{labels.view}" }
                select {
                    class: "ui-select",
                    disabled,
                    id: "{id}-view",
                    oninput: move |event| {
                        if let Some(view) = apply_views.iter().find(|view| view.id == event.value()) {
                            on_apply.call((data_table_saved_state(&view.state), Some(view.id.clone())));
                        }
                    },
                    option { disabled: true, selected: active.is_none(), value: "", "{labels.custom}" }
                    for view in views.iter() {
                        option {
                            key: "{view.id}",
                            selected: active.as_ref().is_some_and(|active| active.id == view.id),
                            value: "{view.id}",
                            "{view.label}"
                        }
                    }
                }
            }
            Field { control_id: "{id}-name",
                Label { r#for: "{id}-name", "{labels.name}" }
                Input {
                    disabled,
                    id: "{id}-name",
                    maxlength: "{DATA_TABLE_SAVED_VIEW_NAME_LIMIT}",
                    value: "{name}",
                    oninput: move |event: FormEvent| name.set(event.value().chars().take(DATA_TABLE_SAVED_VIEW_NAME_LIMIT).collect()),
                }
            }
            Button {
                disabled: disabled || name.read().trim().is_empty(),
                onclick: move |_| {
                    let trimmed = name.peek().trim().to_string();

                    if !disabled && !trimmed.is_empty() {
                        on_save.call((trimmed, data_table_saved_state(&state)));
                    }
                },
                "{labels.save}"
            }
            if let Some(on_update) = props.on_update {
                Button {
                    disabled: disabled || active.is_none(),
                    variant: ButtonVariant::Outline,
                    onclick: move |_| {
                        if let (false, Some(active)) = (disabled, update_active.as_ref()) {
                            on_update.call((active.id.clone(), data_table_saved_state(&update_state)));
                        }
                    },
                    "{labels.update}"
                }
            }
            if let Some(on_remove) = props.on_remove {
                Button {
                    disabled: disabled || active.is_none(),
                    variant: ButtonVariant::Outline,
                    onclick: move |_| {
                        if let (false, Some(active)) = (disabled, remove_active.as_ref()) {
                            on_remove.call(active.id.clone());
                        }
                    },
                    "{labels.remove}"
                }
            }
            Button {
                disabled,
                variant: ButtonVariant::Outline,
                onclick: move |_| {
                    if !disabled {
                        on_apply.call((data_table_saved_state(&reset_state), None));
                    }
                },
                "{labels.reset}"
            }
        }
    }
}