Skip to main content

lumen_dioxus/data/data_table/
layout.rs

1//! Column layout for data tables: width, order, and pinning, with `DataTableLayoutControls`.
2
3// cspell:words fieldset
4
5use std::fmt::Write as _;
6
7use dioxus::prelude::*;
8
9use crate::hooks::use_unique_id;
10use crate::{Button, ButtonVariant, Field, Input, Label};
11
12/// Default column width in pixels.
13pub const DATA_TABLE_LAYOUT_DEFAULT_WIDTH: f64 = 180.0;
14
15/// Narrowest column width in pixels.
16pub const DATA_TABLE_LAYOUT_MIN_WIDTH: f64 = 64.0;
17
18/// Widest column width in pixels.
19pub const DATA_TABLE_LAYOUT_MAX_WIDTH: f64 = 1200.0;
20
21/// The side a column is pinned to.
22#[derive(Clone, Copy, Debug, PartialEq, Eq)]
23pub enum DataTablePin {
24    /// Pinned to the inline start.
25    Start,
26    /// Pinned to the inline end.
27    End,
28}
29
30/// Column preferences: order, widths, and pins. No row values or selection are kept.
31#[derive(Clone, Debug, Default, PartialEq)]
32pub struct DataTableLayoutState {
33    /// Preferred column order; unknown keys are ignored and new keys go last.
34    pub order: Vec<String>,
35    /// Column widths in pixels, from 64 to 1200.
36    pub widths: Vec<(String, f64)>,
37    /// Pinned columns.
38    pub pinned: Vec<(String, DataTablePin)>,
39}
40
41impl DataTableLayoutState {
42    /// The pin of a column.
43    pub fn pin_of(&self, key: &str) -> Option<DataTablePin> {
44        self.pinned
45            .iter()
46            .find(|(pinned, _)| pinned == key)
47            .map(|(_, side)| *side)
48    }
49
50    /// The width of a column, or the default 180 pixels.
51    pub fn width_of(&self, key: &str) -> f64 {
52        self.widths
53            .iter()
54            .find(|(sized, _)| sized == key)
55            .map_or(DATA_TABLE_LAYOUT_DEFAULT_WIDTH, |(_, width)| *width)
56    }
57}
58
59/// Column keys in display order: start-pinned, unpinned, then end-pinned, each following the
60/// preferred order with new keys last.
61pub fn data_table_layout_column_keys(keys: &[String], state: &DataTableLayoutState) -> Vec<String> {
62    let ordered: Vec<&String> = state
63        .order
64        .iter()
65        .filter(|key| keys.contains(key))
66        .chain(keys.iter().filter(|key| !state.order.contains(key)))
67        .collect();
68    let side = |wanted: Option<DataTablePin>| {
69        ordered
70            .iter()
71            .filter(move |key| state.pin_of(key) == wanted)
72            .map(|key| (*key).clone())
73    };
74
75    side(Some(DataTablePin::Start))
76        .chain(side(None))
77        .chain(side(Some(DataTablePin::End)))
78        .collect()
79}
80
81/// Inline CSS for a column's header and cells: a fixed width and, when pinned, a sticky offset
82/// that adds up the widths of the pinned columns before it.
83pub fn data_table_layout_style(keys: &[String], state: &DataTableLayoutState, key: &str) -> String {
84    let width = state.width_of(key);
85    let mut style = format!("width:{width}px;min-width:{width}px;max-width:{width}px");
86    let Some(side) = state.pin_of(key) else {
87        return style;
88    };
89    let columns = data_table_layout_column_keys(keys, state);
90    let index = columns.iter().position(|column| column == key).unwrap_or(0);
91    let neighbors = match side {
92        DataTablePin::Start => &columns[..index],
93        DataTablePin::End => &columns[(index + 1).min(columns.len())..],
94    };
95    let offset: f64 = neighbors
96        .iter()
97        .filter(|neighbor| state.pin_of(neighbor) == Some(side))
98        .map(|neighbor| state.width_of(neighbor))
99        .fold(0.0, |total, width| total + width);
100    let property = match side {
101        DataTablePin::Start => "inset-inline-start",
102        DataTablePin::End => "inset-inline-end",
103    };
104
105    let _ = write!(
106        style,
107        ";position:sticky;z-index:1;background:hsl(var(--surface));{property}:{offset}px"
108    );
109    style
110}
111
112/// The state after resizing a column, or `None` for unknown keys or widths outside 64 to 1200.
113pub fn data_table_layout_resize(
114    keys: &[String],
115    state: &DataTableLayoutState,
116    key: &str,
117    width: f64,
118) -> Option<DataTableLayoutState> {
119    if !keys.iter().any(|known| known == key)
120        || !width.is_finite()
121        || !(DATA_TABLE_LAYOUT_MIN_WIDTH..=DATA_TABLE_LAYOUT_MAX_WIDTH).contains(&width)
122    {
123        return None;
124    }
125
126    let mut next = state.clone();
127    next.widths.retain(|(sized, _)| sized != key);
128    next.widths.push((key.to_string(), width));
129    Some(next)
130}
131
132/// The state after moving a column one place earlier (`-1`) or later (`1`) among the columns
133/// pinned to the same side, or `None` when it cannot move.
134pub fn data_table_layout_move(
135    keys: &[String],
136    state: &DataTableLayoutState,
137    key: &str,
138    direction: isize,
139) -> Option<DataTableLayoutState> {
140    let mut order = data_table_layout_column_keys(keys, state);
141    let index = order.iter().position(|column| column == key)?;
142    let target = index.checked_add_signed(direction)?;
143    let neighbor = order.get(target)?;
144
145    if state.pin_of(neighbor) != state.pin_of(key) {
146        return None;
147    }
148
149    order.swap(index, target);
150
151    Some(DataTableLayoutState {
152        order,
153        ..state.clone()
154    })
155}
156
157/// The state after pinning (or unpinning, with `None`) a column.
158pub fn data_table_layout_pin(
159    keys: &[String],
160    state: &DataTableLayoutState,
161    key: &str,
162    side: Option<DataTablePin>,
163) -> Option<DataTableLayoutState> {
164    if !keys.iter().any(|known| known == key) {
165        return None;
166    }
167
168    let mut pinned: Vec<(String, DataTablePin)> = state
169        .pinned
170        .iter()
171        .filter(|(pinned, _)| pinned != key)
172        .cloned()
173        .collect();
174
175    if let Some(side) = side {
176        pinned.push((key.to_string(), side));
177    }
178
179    Some(DataTableLayoutState {
180        order: data_table_layout_column_keys(keys, state),
181        widths: state.widths.clone(),
182        pinned,
183    })
184}
185
186/// Copy for [`DataTableLayoutControls`].
187#[derive(Clone, Debug, PartialEq, Eq)]
188pub struct DataTableLayoutLabels {
189    /// Legend of the controls.
190    pub region: String,
191    /// Width field label suffix.
192    pub width: String,
193    /// Move earlier button.
194    pub earlier: String,
195    /// Move later button.
196    pub later: String,
197    /// Pin to start button.
198    pub pin_start: String,
199    /// Pin to end button.
200    pub pin_end: String,
201    /// Unpin button.
202    pub unpin: String,
203}
204
205impl Default for DataTableLayoutLabels {
206    fn default() -> Self {
207        Self {
208            region: "Column layout".into(),
209            width: "Width in pixels".into(),
210            earlier: "Move earlier".into(),
211            later: "Move later".into(),
212            pin_start: "Pin to start".into(),
213            pin_end: "Pin to end".into(),
214            unpin: "Unpin".into(),
215        }
216    }
217}
218
219/// Props for [`DataTableLayoutControls`].
220#[derive(Props, Clone, PartialEq)]
221pub struct DataTableLayoutControlsProps {
222    /// The columns as `(key, label)` pairs, in their natural order.
223    pub columns: Vec<(String, String)>,
224    /// The current layout.
225    pub layout: DataTableLayoutState,
226    /// Called with the next layout.
227    pub on_layout_change: EventHandler<DataTableLayoutState>,
228    /// Localized copy.
229    #[props(default)]
230    pub labels: DataTableLayoutLabels,
231    /// Disables every control.
232    #[props(default)]
233    pub disabled: bool,
234}
235
236const VERTICAL_STACK: &str = "ui-stack ui-stack--vertical ui-stack--gap-related ui-stack--align-stretch ui-stack--justify-start";
237const HORIZONTAL_STACK: &str = "ui-stack ui-stack--horizontal ui-stack--gap-related ui-stack--align-stretch ui-stack--justify-start ui-stack--wrap";
238
239/// Width, order, and pin controls for each column. Apply [`data_table_layout_column_keys`] and
240/// [`data_table_layout_style`] to the table's headers and cells.
241#[component]
242#[allow(clippy::too_many_lines)]
243pub fn DataTableLayoutControls(props: DataTableLayoutControlsProps) -> Element {
244    let id = use_unique_id();
245    let keys: Vec<String> = props.columns.iter().map(|(key, _)| key.clone()).collect();
246    let column_keys = data_table_layout_column_keys(&keys, &props.layout);
247    let labels = props.labels.clone();
248    let on_change = props.on_layout_change;
249    let disabled = props.disabled;
250
251    rsx! {
252        fieldset { disabled,
253            legend { "{labels.region}" }
254            div { class: VERTICAL_STACK, "data-direction": "vertical", "data-ui-stack": "true",
255                for (index, key) in column_keys.iter().enumerate() {
256                    {
257                        let label = props
258                            .columns
259                            .iter()
260                            .find(|(column, _)| column == key)
261                            .map_or(key.clone(), |(_, label)| label.clone());
262                        let side = props.layout.pin_of(key);
263                        let neighbor_side = |offset: isize| {
264                            index
265                                .checked_add_signed(offset)
266                                .and_then(|target| column_keys.get(target))
267                                .map(|neighbor| props.layout.pin_of(neighbor))
268                        };
269                        let earlier_disabled = index == 0 || neighbor_side(-1) != Some(side);
270                        let later_disabled = index + 1 == column_keys.len() || neighbor_side(1) != Some(side);
271                        let width = props.layout.width_of(key);
272                        let action = |change: fn(&[String], &DataTableLayoutState, &str) -> Option<DataTableLayoutState>| {
273                            let keys = keys.clone();
274                            let layout = props.layout.clone();
275                            let key = key.clone();
276
277                            move |_: MouseEvent| {
278                                if disabled {
279                                    return;
280                                }
281
282                                if let Some(next) = change(&keys, &layout, &key) {
283                                    on_change.call(next);
284                                }
285                            }
286                        };
287                        let (resize_keys, resize_layout, resize_key) = (keys.clone(), props.layout.clone(), key.clone());
288
289                        rsx! {
290                            div {
291                                key: "{key}",
292                                aria_label: "{label}",
293                                class: HORIZONTAL_STACK,
294                                "data-direction": "horizontal",
295                                "data-ui-stack": "true",
296                                role: "group",
297                                Field { control_id: "{id}-{index}",
298                                    Label { r#for: "{id}-{index}", "{label}: {labels.width}" }
299                                    Input {
300                                        id: "{id}-{index}",
301                                        max: "1200",
302                                        min: "64",
303                                        r#type: "number",
304                                        value: "{width}",
305                                        oninput: move |event: FormEvent| {
306                                            if disabled {
307                                                return;
308                                            }
309
310                                            if let Ok(width) = event.value().trim().parse::<f64>()
311                                                && let Some(next) = data_table_layout_resize(&resize_keys, &resize_layout, &resize_key, width)
312                                            {
313                                                on_change.call(next);
314                                            }
315                                        },
316                                    }
317                                }
318                                Button {
319                                    aria_label: "{label}: {labels.earlier}",
320                                    disabled: earlier_disabled,
321                                    variant: ButtonVariant::Outline,
322                                    onclick: action(|keys, layout, key| data_table_layout_move(keys, layout, key, -1)),
323                                    "{labels.earlier}"
324                                }
325                                Button {
326                                    aria_label: "{label}: {labels.later}",
327                                    disabled: later_disabled,
328                                    variant: ButtonVariant::Outline,
329                                    onclick: action(|keys, layout, key| data_table_layout_move(keys, layout, key, 1)),
330                                    "{labels.later}"
331                                }
332                                Button {
333                                    aria_pressed: if side == Some(DataTablePin::Start) { "true" } else { "false" },
334                                    variant: ButtonVariant::Outline,
335                                    onclick: if side == Some(DataTablePin::Start) {
336                                        action(|keys, layout, key| data_table_layout_pin(keys, layout, key, None))
337                                    } else {
338                                        action(|keys, layout, key| data_table_layout_pin(keys, layout, key, Some(DataTablePin::Start)))
339                                    },
340                                    if side == Some(DataTablePin::Start) { "{labels.unpin}" } else { "{labels.pin_start}" }
341                                }
342                                Button {
343                                    aria_pressed: if side == Some(DataTablePin::End) { "true" } else { "false" },
344                                    variant: ButtonVariant::Outline,
345                                    onclick: if side == Some(DataTablePin::End) {
346                                        action(|keys, layout, key| data_table_layout_pin(keys, layout, key, None))
347                                    } else {
348                                        action(|keys, layout, key| data_table_layout_pin(keys, layout, key, Some(DataTablePin::End)))
349                                    },
350                                    if side == Some(DataTablePin::End) { "{labels.unpin}" } else { "{labels.pin_end}" }
351                                }
352                            }
353                        }
354                    }
355                }
356            }
357        }
358    }
359}
360
361#[cfg(test)]
362mod tests {
363    use super::{
364        DataTableLayoutState, DataTablePin, data_table_layout_column_keys, data_table_layout_move,
365        data_table_layout_pin, data_table_layout_resize, data_table_layout_style,
366    };
367
368    fn keys() -> Vec<String> {
369        ["name", "role", "seats"].map(String::from).to_vec()
370    }
371
372    #[test]
373    fn pinned_columns_lead_and_trail() {
374        let state = DataTableLayoutState {
375            order: vec!["seats".into(), "gone".into()],
376            widths: vec![("name".into(), 240.0)],
377            pinned: vec![
378                ("role".into(), DataTablePin::Start),
379                ("name".into(), DataTablePin::End),
380            ],
381        };
382
383        assert_eq!(
384            data_table_layout_column_keys(&keys(), &state),
385            ["role", "seats", "name"]
386        );
387        assert_eq!(
388            data_table_layout_style(&keys(), &state, "seats"),
389            "width:180px;min-width:180px;max-width:180px"
390        );
391        assert_eq!(
392            data_table_layout_style(&keys(), &state, "name"),
393            "width:240px;min-width:240px;max-width:240px;position:sticky;z-index:1;background:hsl(var(--surface));inset-inline-end:0px"
394        );
395    }
396
397    #[test]
398    fn moves_stay_within_a_pin_side_and_widths_clamp() {
399        let state = DataTableLayoutState {
400            pinned: vec![("name".into(), DataTablePin::Start)],
401            ..DataTableLayoutState::default()
402        };
403
404        assert_eq!(data_table_layout_move(&keys(), &state, "role", -1), None);
405        let moved = data_table_layout_move(&keys(), &state, "role", 1).map(|next| next.order);
406        assert_eq!(
407            moved,
408            Some(["name", "seats", "role"].map(String::from).to_vec())
409        );
410        assert_eq!(
411            data_table_layout_resize(&keys(), &state, "role", 10.0),
412            None
413        );
414        assert_eq!(
415            data_table_layout_resize(&keys(), &state, "missing", 100.0),
416            None
417        );
418        assert!(data_table_layout_resize(&keys(), &state, "role", 300.0).is_some());
419        let unpinned = data_table_layout_pin(&keys(), &state, "name", None).map(|next| next.pinned);
420        assert_eq!(unpinned, Some(Vec::new()));
421    }
422}