Skip to main content

lumen_dioxus/data/data_table/
saved.rs

1//! `DataTableSavedViews`: apply, save, update, remove, and reset saved table views.
2
3use dioxus::prelude::*;
4
5use super::model::DataTableViewState;
6use crate::hooks::use_unique_id;
7use crate::{Button, ButtonVariant, Field, Input, Label};
8
9/// A named, saved [`DataTableViewState`].
10#[derive(Clone, Debug, PartialEq, Eq)]
11pub struct DataTableSavedView {
12    /// Unique, non-empty id.
13    pub id: String,
14    /// Visible name.
15    pub label: String,
16    /// The saved preferences.
17    pub state: DataTableViewState,
18}
19
20/// Copy for [`DataTableSavedViews`].
21#[derive(Clone, Debug, PartialEq, Eq)]
22pub struct DataTableSavedViewsLabels {
23    /// Accessible name of the region.
24    pub region: String,
25    /// Saved view select label.
26    pub view: String,
27    /// Placeholder option while no saved view is active.
28    pub custom: String,
29    /// New view name label.
30    pub name: String,
31    /// Save button.
32    pub save: String,
33    /// Update button.
34    pub update: String,
35    /// Remove button.
36    pub remove: String,
37    /// Reset button.
38    pub reset: String,
39}
40
41impl Default for DataTableSavedViewsLabels {
42    fn default() -> Self {
43        Self {
44            region: "Saved record views".into(),
45            view: "Saved view".into(),
46            custom: "Custom view".into(),
47            name: "New view name".into(),
48            save: "Save new view".into(),
49            update: "Update view".into(),
50            remove: "Remove view".into(),
51            reset: "Reset view".into(),
52        }
53    }
54}
55
56/// Most characters of a new view name.
57pub const DATA_TABLE_SAVED_VIEW_NAME_LIMIT: usize = 120;
58
59/// The state a saved view stores: the preferences, starting on the first page.
60pub fn data_table_saved_state(state: &DataTableViewState) -> DataTableViewState {
61    state.clone().first_page()
62}
63
64/// Props for [`DataTableSavedViews`].
65#[derive(Props, Clone, PartialEq)]
66pub struct DataTableSavedViewsProps {
67    /// Saved views with unique, non-empty ids; views with an empty or repeated id are skipped.
68    pub views: Vec<DataTableSavedView>,
69    /// The current view state, used by save and update.
70    pub state: DataTableViewState,
71    /// The applied saved view.
72    #[props(into)]
73    pub active_id: Option<String>,
74    /// The state the reset button applies.
75    pub reset_state: DataTableViewState,
76    /// Called with a state to apply and the saved view id, or `None` after a reset.
77    pub on_apply: EventHandler<(DataTableViewState, Option<String>)>,
78    /// Called with a trimmed name and the state to save.
79    pub on_save: EventHandler<(String, DataTableViewState)>,
80    /// Shows an update button for the active view.
81    pub on_update: Option<EventHandler<(String, DataTableViewState)>>,
82    /// Shows a remove button for the active view.
83    pub on_remove: Option<EventHandler<String>>,
84    /// Disables every control.
85    #[props(default)]
86    pub disabled: bool,
87    /// Localized copy.
88    #[props(default)]
89    pub labels: DataTableSavedViewsLabels,
90}
91
92/// Apply, save, update, remove, and reset saved table views. Persistence is the application's:
93/// the component calls back and stores nothing itself.
94#[component]
95#[allow(clippy::too_many_lines)]
96pub fn DataTableSavedViews(props: DataTableSavedViewsProps) -> Element {
97    let id = use_unique_id();
98    let mut name = use_signal(String::new);
99    let mut seen = std::collections::HashSet::new();
100    let views: Vec<DataTableSavedView> = props
101        .views
102        .iter()
103        .filter(|view| !view.id.trim().is_empty() && seen.insert(view.id.clone()))
104        .cloned()
105        .collect();
106    let active = props
107        .active_id
108        .as_ref()
109        .and_then(|active| views.iter().find(|view| view.id == *active))
110        .cloned();
111    let labels = props.labels.clone();
112    let disabled = props.disabled;
113    let on_apply = props.on_apply;
114    let on_save = props.on_save;
115    let state = props.state.clone();
116    let update_state = state.clone();
117    let reset_state = props.reset_state.clone();
118    let apply_views = views.clone();
119    let (update_active, remove_active) = (active.clone(), active.clone());
120
121    rsx! {
122        section {
123            aria_busy: if disabled { "true" } else { "false" },
124            aria_label: "{labels.region}",
125            class: "ui-data-table-view__saved",
126            Field { control_id: "{id}-view",
127                Label { r#for: "{id}-view", "{labels.view}" }
128                select {
129                    class: "ui-select",
130                    disabled,
131                    id: "{id}-view",
132                    oninput: move |event| {
133                        if let Some(view) = apply_views.iter().find(|view| view.id == event.value()) {
134                            on_apply.call((data_table_saved_state(&view.state), Some(view.id.clone())));
135                        }
136                    },
137                    option { disabled: true, selected: active.is_none(), value: "", "{labels.custom}" }
138                    for view in views.iter() {
139                        option {
140                            key: "{view.id}",
141                            selected: active.as_ref().is_some_and(|active| active.id == view.id),
142                            value: "{view.id}",
143                            "{view.label}"
144                        }
145                    }
146                }
147            }
148            Field { control_id: "{id}-name",
149                Label { r#for: "{id}-name", "{labels.name}" }
150                Input {
151                    disabled,
152                    id: "{id}-name",
153                    maxlength: "{DATA_TABLE_SAVED_VIEW_NAME_LIMIT}",
154                    value: "{name}",
155                    oninput: move |event: FormEvent| name.set(event.value().chars().take(DATA_TABLE_SAVED_VIEW_NAME_LIMIT).collect()),
156                }
157            }
158            Button {
159                disabled: disabled || name.read().trim().is_empty(),
160                onclick: move |_| {
161                    let trimmed = name.peek().trim().to_string();
162
163                    if !disabled && !trimmed.is_empty() {
164                        on_save.call((trimmed, data_table_saved_state(&state)));
165                    }
166                },
167                "{labels.save}"
168            }
169            if let Some(on_update) = props.on_update {
170                Button {
171                    disabled: disabled || active.is_none(),
172                    variant: ButtonVariant::Outline,
173                    onclick: move |_| {
174                        if let (false, Some(active)) = (disabled, update_active.as_ref()) {
175                            on_update.call((active.id.clone(), data_table_saved_state(&update_state)));
176                        }
177                    },
178                    "{labels.update}"
179                }
180            }
181            if let Some(on_remove) = props.on_remove {
182                Button {
183                    disabled: disabled || active.is_none(),
184                    variant: ButtonVariant::Outline,
185                    onclick: move |_| {
186                        if let (false, Some(active)) = (disabled, remove_active.as_ref()) {
187                            on_remove.call(active.id.clone());
188                        }
189                    },
190                    "{labels.remove}"
191                }
192            }
193            Button {
194                disabled,
195                variant: ButtonVariant::Outline,
196                onclick: move |_| {
197                    if !disabled {
198                        on_apply.call((data_table_saved_state(&reset_state), None));
199                    }
200                },
201                "{labels.reset}"
202            }
203        }
204    }
205}