lumen-dioxus 6.0.0

Lumen UI components for Dioxus: web, desktop, mobile, and Dioxus Native (Blitz).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
//! Column layout for data tables: width, order, and pinning, with `DataTableLayoutControls`.

// cspell:words fieldset

use std::fmt::Write as _;

use dioxus::prelude::*;

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

/// Default column width in pixels.
pub const DATA_TABLE_LAYOUT_DEFAULT_WIDTH: f64 = 180.0;

/// Narrowest column width in pixels.
pub const DATA_TABLE_LAYOUT_MIN_WIDTH: f64 = 64.0;

/// Widest column width in pixels.
pub const DATA_TABLE_LAYOUT_MAX_WIDTH: f64 = 1200.0;

/// The side a column is pinned to.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DataTablePin {
    /// Pinned to the inline start.
    Start,
    /// Pinned to the inline end.
    End,
}

/// Column preferences: order, widths, and pins. No row values or selection are kept.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct DataTableLayoutState {
    /// Preferred column order; unknown keys are ignored and new keys go last.
    pub order: Vec<String>,
    /// Column widths in pixels, from 64 to 1200.
    pub widths: Vec<(String, f64)>,
    /// Pinned columns.
    pub pinned: Vec<(String, DataTablePin)>,
}

impl DataTableLayoutState {
    /// The pin of a column.
    pub fn pin_of(&self, key: &str) -> Option<DataTablePin> {
        self.pinned
            .iter()
            .find(|(pinned, _)| pinned == key)
            .map(|(_, side)| *side)
    }

    /// The width of a column, or the default 180 pixels.
    pub fn width_of(&self, key: &str) -> f64 {
        self.widths
            .iter()
            .find(|(sized, _)| sized == key)
            .map_or(DATA_TABLE_LAYOUT_DEFAULT_WIDTH, |(_, width)| *width)
    }
}

/// Column keys in display order: start-pinned, unpinned, then end-pinned, each following the
/// preferred order with new keys last.
pub fn data_table_layout_column_keys(keys: &[String], state: &DataTableLayoutState) -> Vec<String> {
    let ordered: Vec<&String> = state
        .order
        .iter()
        .filter(|key| keys.contains(key))
        .chain(keys.iter().filter(|key| !state.order.contains(key)))
        .collect();
    let side = |wanted: Option<DataTablePin>| {
        ordered
            .iter()
            .filter(move |key| state.pin_of(key) == wanted)
            .map(|key| (*key).clone())
    };

    side(Some(DataTablePin::Start))
        .chain(side(None))
        .chain(side(Some(DataTablePin::End)))
        .collect()
}

/// Inline CSS for a column's header and cells: a fixed width and, when pinned, a sticky offset
/// that adds up the widths of the pinned columns before it.
pub fn data_table_layout_style(keys: &[String], state: &DataTableLayoutState, key: &str) -> String {
    let width = state.width_of(key);
    let mut style = format!("width:{width}px;min-width:{width}px;max-width:{width}px");
    let Some(side) = state.pin_of(key) else {
        return style;
    };
    let columns = data_table_layout_column_keys(keys, state);
    let index = columns.iter().position(|column| column == key).unwrap_or(0);
    let neighbors = match side {
        DataTablePin::Start => &columns[..index],
        DataTablePin::End => &columns[(index + 1).min(columns.len())..],
    };
    let offset: f64 = neighbors
        .iter()
        .filter(|neighbor| state.pin_of(neighbor) == Some(side))
        .map(|neighbor| state.width_of(neighbor))
        .fold(0.0, |total, width| total + width);
    let property = match side {
        DataTablePin::Start => "inset-inline-start",
        DataTablePin::End => "inset-inline-end",
    };

    let _ = write!(
        style,
        ";position:sticky;z-index:1;background:hsl(var(--surface));{property}:{offset}px"
    );
    style
}

/// The state after resizing a column, or `None` for unknown keys or widths outside 64 to 1200.
pub fn data_table_layout_resize(
    keys: &[String],
    state: &DataTableLayoutState,
    key: &str,
    width: f64,
) -> Option<DataTableLayoutState> {
    if !keys.iter().any(|known| known == key)
        || !width.is_finite()
        || !(DATA_TABLE_LAYOUT_MIN_WIDTH..=DATA_TABLE_LAYOUT_MAX_WIDTH).contains(&width)
    {
        return None;
    }

    let mut next = state.clone();
    next.widths.retain(|(sized, _)| sized != key);
    next.widths.push((key.to_string(), width));
    Some(next)
}

/// The state after moving a column one place earlier (`-1`) or later (`1`) among the columns
/// pinned to the same side, or `None` when it cannot move.
pub fn data_table_layout_move(
    keys: &[String],
    state: &DataTableLayoutState,
    key: &str,
    direction: isize,
) -> Option<DataTableLayoutState> {
    let mut order = data_table_layout_column_keys(keys, state);
    let index = order.iter().position(|column| column == key)?;
    let target = index.checked_add_signed(direction)?;
    let neighbor = order.get(target)?;

    if state.pin_of(neighbor) != state.pin_of(key) {
        return None;
    }

    order.swap(index, target);

    Some(DataTableLayoutState {
        order,
        ..state.clone()
    })
}

/// The state after pinning (or unpinning, with `None`) a column.
pub fn data_table_layout_pin(
    keys: &[String],
    state: &DataTableLayoutState,
    key: &str,
    side: Option<DataTablePin>,
) -> Option<DataTableLayoutState> {
    if !keys.iter().any(|known| known == key) {
        return None;
    }

    let mut pinned: Vec<(String, DataTablePin)> = state
        .pinned
        .iter()
        .filter(|(pinned, _)| pinned != key)
        .cloned()
        .collect();

    if let Some(side) = side {
        pinned.push((key.to_string(), side));
    }

    Some(DataTableLayoutState {
        order: data_table_layout_column_keys(keys, state),
        widths: state.widths.clone(),
        pinned,
    })
}

/// Copy for [`DataTableLayoutControls`].
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DataTableLayoutLabels {
    /// Legend of the controls.
    pub region: String,
    /// Width field label suffix.
    pub width: String,
    /// Move earlier button.
    pub earlier: String,
    /// Move later button.
    pub later: String,
    /// Pin to start button.
    pub pin_start: String,
    /// Pin to end button.
    pub pin_end: String,
    /// Unpin button.
    pub unpin: String,
}

impl Default for DataTableLayoutLabels {
    fn default() -> Self {
        Self {
            region: "Column layout".into(),
            width: "Width in pixels".into(),
            earlier: "Move earlier".into(),
            later: "Move later".into(),
            pin_start: "Pin to start".into(),
            pin_end: "Pin to end".into(),
            unpin: "Unpin".into(),
        }
    }
}

/// Props for [`DataTableLayoutControls`].
#[derive(Props, Clone, PartialEq)]
pub struct DataTableLayoutControlsProps {
    /// The columns as `(key, label)` pairs, in their natural order.
    pub columns: Vec<(String, String)>,
    /// The current layout.
    pub layout: DataTableLayoutState,
    /// Called with the next layout.
    pub on_layout_change: EventHandler<DataTableLayoutState>,
    /// Localized copy.
    #[props(default)]
    pub labels: DataTableLayoutLabels,
    /// Disables every control.
    #[props(default)]
    pub disabled: bool,
}

const VERTICAL_STACK: &str = "ui-stack ui-stack--vertical ui-stack--gap-related ui-stack--align-stretch ui-stack--justify-start";
const HORIZONTAL_STACK: &str = "ui-stack ui-stack--horizontal ui-stack--gap-related ui-stack--align-stretch ui-stack--justify-start ui-stack--wrap";

/// Width, order, and pin controls for each column. Apply [`data_table_layout_column_keys`] and
/// [`data_table_layout_style`] to the table's headers and cells.
#[component]
#[allow(clippy::too_many_lines)]
pub fn DataTableLayoutControls(props: DataTableLayoutControlsProps) -> Element {
    let id = use_unique_id();
    let keys: Vec<String> = props.columns.iter().map(|(key, _)| key.clone()).collect();
    let column_keys = data_table_layout_column_keys(&keys, &props.layout);
    let labels = props.labels.clone();
    let on_change = props.on_layout_change;
    let disabled = props.disabled;

    rsx! {
        fieldset { disabled,
            legend { "{labels.region}" }
            div { class: VERTICAL_STACK, "data-direction": "vertical", "data-ui-stack": "true",
                for (index, key) in column_keys.iter().enumerate() {
                    {
                        let label = props
                            .columns
                            .iter()
                            .find(|(column, _)| column == key)
                            .map_or(key.clone(), |(_, label)| label.clone());
                        let side = props.layout.pin_of(key);
                        let neighbor_side = |offset: isize| {
                            index
                                .checked_add_signed(offset)
                                .and_then(|target| column_keys.get(target))
                                .map(|neighbor| props.layout.pin_of(neighbor))
                        };
                        let earlier_disabled = index == 0 || neighbor_side(-1) != Some(side);
                        let later_disabled = index + 1 == column_keys.len() || neighbor_side(1) != Some(side);
                        let width = props.layout.width_of(key);
                        let action = |change: fn(&[String], &DataTableLayoutState, &str) -> Option<DataTableLayoutState>| {
                            let keys = keys.clone();
                            let layout = props.layout.clone();
                            let key = key.clone();

                            move |_: MouseEvent| {
                                if disabled {
                                    return;
                                }

                                if let Some(next) = change(&keys, &layout, &key) {
                                    on_change.call(next);
                                }
                            }
                        };
                        let (resize_keys, resize_layout, resize_key) = (keys.clone(), props.layout.clone(), key.clone());

                        rsx! {
                            div {
                                key: "{key}",
                                aria_label: "{label}",
                                class: HORIZONTAL_STACK,
                                "data-direction": "horizontal",
                                "data-ui-stack": "true",
                                role: "group",
                                Field { control_id: "{id}-{index}",
                                    Label { r#for: "{id}-{index}", "{label}: {labels.width}" }
                                    Input {
                                        id: "{id}-{index}",
                                        max: "1200",
                                        min: "64",
                                        r#type: "number",
                                        value: "{width}",
                                        oninput: move |event: FormEvent| {
                                            if disabled {
                                                return;
                                            }

                                            if let Ok(width) = event.value().trim().parse::<f64>()
                                                && let Some(next) = data_table_layout_resize(&resize_keys, &resize_layout, &resize_key, width)
                                            {
                                                on_change.call(next);
                                            }
                                        },
                                    }
                                }
                                Button {
                                    aria_label: "{label}: {labels.earlier}",
                                    disabled: earlier_disabled,
                                    variant: ButtonVariant::Outline,
                                    onclick: action(|keys, layout, key| data_table_layout_move(keys, layout, key, -1)),
                                    "{labels.earlier}"
                                }
                                Button {
                                    aria_label: "{label}: {labels.later}",
                                    disabled: later_disabled,
                                    variant: ButtonVariant::Outline,
                                    onclick: action(|keys, layout, key| data_table_layout_move(keys, layout, key, 1)),
                                    "{labels.later}"
                                }
                                Button {
                                    aria_pressed: if side == Some(DataTablePin::Start) { "true" } else { "false" },
                                    variant: ButtonVariant::Outline,
                                    onclick: if side == Some(DataTablePin::Start) {
                                        action(|keys, layout, key| data_table_layout_pin(keys, layout, key, None))
                                    } else {
                                        action(|keys, layout, key| data_table_layout_pin(keys, layout, key, Some(DataTablePin::Start)))
                                    },
                                    if side == Some(DataTablePin::Start) { "{labels.unpin}" } else { "{labels.pin_start}" }
                                }
                                Button {
                                    aria_pressed: if side == Some(DataTablePin::End) { "true" } else { "false" },
                                    variant: ButtonVariant::Outline,
                                    onclick: if side == Some(DataTablePin::End) {
                                        action(|keys, layout, key| data_table_layout_pin(keys, layout, key, None))
                                    } else {
                                        action(|keys, layout, key| data_table_layout_pin(keys, layout, key, Some(DataTablePin::End)))
                                    },
                                    if side == Some(DataTablePin::End) { "{labels.unpin}" } else { "{labels.pin_end}" }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{
        DataTableLayoutState, DataTablePin, data_table_layout_column_keys, data_table_layout_move,
        data_table_layout_pin, data_table_layout_resize, data_table_layout_style,
    };

    fn keys() -> Vec<String> {
        ["name", "role", "seats"].map(String::from).to_vec()
    }

    #[test]
    fn pinned_columns_lead_and_trail() {
        let state = DataTableLayoutState {
            order: vec!["seats".into(), "gone".into()],
            widths: vec![("name".into(), 240.0)],
            pinned: vec![
                ("role".into(), DataTablePin::Start),
                ("name".into(), DataTablePin::End),
            ],
        };

        assert_eq!(
            data_table_layout_column_keys(&keys(), &state),
            ["role", "seats", "name"]
        );
        assert_eq!(
            data_table_layout_style(&keys(), &state, "seats"),
            "width:180px;min-width:180px;max-width:180px"
        );
        assert_eq!(
            data_table_layout_style(&keys(), &state, "name"),
            "width:240px;min-width:240px;max-width:240px;position:sticky;z-index:1;background:hsl(var(--surface));inset-inline-end:0px"
        );
    }

    #[test]
    fn moves_stay_within_a_pin_side_and_widths_clamp() {
        let state = DataTableLayoutState {
            pinned: vec![("name".into(), DataTablePin::Start)],
            ..DataTableLayoutState::default()
        };

        assert_eq!(data_table_layout_move(&keys(), &state, "role", -1), None);
        let moved = data_table_layout_move(&keys(), &state, "role", 1).map(|next| next.order);
        assert_eq!(
            moved,
            Some(["name", "seats", "role"].map(String::from).to_vec())
        );
        assert_eq!(
            data_table_layout_resize(&keys(), &state, "role", 10.0),
            None
        );
        assert_eq!(
            data_table_layout_resize(&keys(), &state, "missing", 100.0),
            None
        );
        assert!(data_table_layout_resize(&keys(), &state, "role", 300.0).is_some());
        let unpinned = data_table_layout_pin(&keys(), &state, "name", None).map(|next| next.pinned);
        assert_eq!(unpinned, Some(Vec::new()));
    }
}