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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
//! `Cascader`: a select whose options open further columns of sub-options.

use std::collections::HashMap;
use std::rc::Rc;

use dioxus::prelude::*;

use crate::class::compose;
use crate::hooks::use_unique_id;
use crate::icons::{Icon, IconSize, lucide};
use crate::overlay::{DismissLayer, focus_element, is_escape, wrap_index};

/// One option, with optional sub-options shown in the next column.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CascaderOption {
    /// Submitted value when this option is the final pick.
    pub value: String,
    /// Visible label.
    pub label: String,
    /// Sub-options. An option without children completes the selection.
    pub children: Vec<CascaderOption>,
}

impl CascaderOption {
    /// A final option.
    pub fn new(value: impl Into<String>, label: impl Into<String>) -> Self {
        Self {
            value: value.into(),
            label: label.into(),
            children: Vec::new(),
        }
    }

    /// The same option with sub-options.
    #[must_use]
    pub fn with_children(mut self, children: Vec<CascaderOption>) -> Self {
        self.children = children;
        self
    }
}

/// A rendered column option.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct CascaderCell {
    pub(crate) value: String,
    pub(crate) label: String,
    /// Index of the column this option opens.
    pub(crate) next: Option<usize>,
}

/// A rendered column: the root column first, then sub-columns in depth-first order.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct CascaderColumn {
    pub(crate) id: String,
    pub(crate) root: bool,
    pub(crate) options: Vec<CascaderCell>,
}

/// Flattens the option tree into columns with ids `{prefix}-column-{n}`, like lumen-react's
/// `buildCascaderColumns` (iterative, so deep trees cannot overflow the stack).
pub(crate) fn cascader_columns(options: &[CascaderOption], prefix: &str) -> Vec<CascaderColumn> {
    let mut columns = Vec::new();

    if options.is_empty() {
        return columns;
    }

    // Each frame is a column being built: (column index, its options, next child to visit).
    let mut stack: Vec<(usize, &[CascaderOption], usize)> = Vec::new();
    let open_column = |items: &[CascaderOption], root: bool, columns: &mut Vec<CascaderColumn>| {
        let index = columns.len();
        columns.push(CascaderColumn {
            id: format!("{prefix}-column-{}", index + 1),
            root,
            options: items
                .iter()
                .map(|item| CascaderCell {
                    value: item.value.clone(),
                    label: item.label.clone(),
                    next: None,
                })
                .collect(),
        });
        index
    };

    let root = open_column(options, true, &mut columns);
    stack.push((root, options, 0));

    while let Some((column, items, position)) = stack.pop() {
        let Some(item) = items.get(position) else {
            continue;
        };

        stack.push((column, items, position + 1));

        if !item.children.is_empty() {
            let child = open_column(&item.children, false, &mut columns);
            columns[column].options[position].next = Some(child);
            stack.push((child, &item.children, 0));
        }
    }

    columns
}

/// The columns on screen for an active path of `(column, option)` picks.
pub(crate) fn cascader_visible_columns(
    columns: &[CascaderColumn],
    path: &[(usize, usize)],
) -> Vec<bool> {
    let mut visible: Vec<bool> = columns.iter().map(|column| column.root).collect();

    for (column, option) in path {
        if let Some(next) = columns
            .get(*column)
            .and_then(|entry| entry.options.get(*option))
            .and_then(|cell| cell.next)
            && let Some(slot) = visible.get_mut(next)
        {
            *slot = true;
        }
    }

    visible
}

/// Props for [`Cascader`].
#[derive(Props, Clone, PartialEq)]
pub struct CascaderProps {
    /// The option tree.
    #[props(default)]
    pub options: Vec<CascaderOption>,
    /// Form field name of the hidden input that submits the final value.
    #[props(into)]
    pub name: Option<String>,
    /// Trigger text before a value is picked.
    #[props(default = "Select…".to_string(), into)]
    pub placeholder: String,
    /// Id of the root; column and panel ids derive from it.
    #[props(into)]
    pub id: Option<String>,
    /// Called with the value of the final option the user picks.
    pub on_value_change: Option<EventHandler<String>>,
    /// Extra classes appended after the Lumen class.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<div>` or global attribute.
    #[props(extends = GlobalAttributes, extends = div)]
    pub attributes: Vec<Attribute>,
    /// Extra content at the end of the panel.
    pub children: Element,
}

/// A cascading select. Picking an option with children opens its column; picking a final option
/// sets the value, closes the panel, and returns focus to the trigger.
///
/// In the panel, Arrow Up and Down, Home, and End move within a column, Arrow Right opens the
/// next column, Arrow Left returns to the previous one, and Escape closes.
#[component]
pub fn Cascader(props: CascaderProps) -> Element {
    let generated = use_unique_id();
    let base_id = props
        .id
        .clone()
        .filter(|id| !id.trim().is_empty())
        .unwrap_or_else(|| format!("ui-cascader-{generated}"));
    let panel_id = format!("{base_id}-panel");
    let columns = cascader_columns(&props.options, &base_id);
    let mut open = use_signal(|| false);
    let mut interacted = use_signal(|| false);
    let mut path = use_signal(Vec::<(usize, usize)>::new);
    let mut picked = use_signal(|| None::<(String, String)>);
    let mut trigger = use_signal(|| None::<Rc<MountedData>>);
    let mut nodes = use_signal(HashMap::<(usize, usize), Rc<MountedData>>::new);
    let mut pending_focus = use_signal(|| None::<(usize, usize)>);
    let visible = cascader_visible_columns(&columns, &path.read());
    let is_open = open();
    let on_value_change = props.on_value_change;

    let mut set_open = move |next: bool| {
        open.set(next);
        interacted.set(true);
    };

    let mut focus_option = move |target: (usize, usize)| {
        if let Some(node) = nodes.peek().get(&target).cloned() {
            focus_element(Some(node));
        } else {
            pending_focus.set(Some(target));
        }
    };

    let columns_for_pick = columns.clone();
    let pick = use_callback(move |(column, option): (usize, usize)| {
        let Some(cell) = columns_for_pick
            .get(column)
            .and_then(|entry| entry.options.get(option))
        else {
            return;
        };

        {
            let mut active = path.write();
            if let Some(position) = active.iter().position(|(entry, _)| *entry == column) {
                active.truncate(position);
            } else {
                // A pick in a newly shown column extends the path.
                active.retain(|(entry, _)| *entry < column);
            }
            active.push((column, option));
        }

        if cell.next.is_none() {
            picked.set(Some((cell.value.clone(), cell.label.clone())));
            set_open(false);
            focus_element(trigger.peek().clone());

            if let Some(handler) = on_value_change {
                handler.call(cell.value.clone());
            }
        }
    });

    let columns_for_keys = columns.clone();
    let on_option_key = use_callback(
        move |(event, column, option): (KeyboardEvent, usize, usize)| {
            if event.is_composing()
                || event.modifiers().alt()
                || event.modifiers().ctrl()
                || event.modifiers().meta()
            {
                return;
            }

            let Some(entry) = columns_for_keys.get(column) else {
                return;
            };
            let count = entry.options.len();
            let key = event.key();
            let next_index = match key {
                Key::ArrowDown => wrap_index(Some(option), 1, count),
                Key::ArrowUp => wrap_index(Some(option), -1, count),
                Key::Home => (count > 0).then_some(0),
                Key::End => count.checked_sub(1),
                _ => None,
            };

            if let Some(index) = next_index {
                event.prevent_default();
                focus_option((column, index));
                return;
            }

            if key == Key::ArrowRight
                && let Some(next) = entry.options.get(option).and_then(|cell| cell.next)
            {
                event.prevent_default();
                pick((column, option));
                focus_option((next, 0));
            } else if key == Key::ArrowLeft && column > 0 {
                event.prevent_default();
                let position = path.peek().iter().position(|(entry_column, entry_option)| {
                    columns_for_keys
                        .get(*entry_column)
                        .and_then(|entry| entry.options.get(*entry_option))
                        .and_then(|cell| cell.next)
                        == Some(column)
                });

                if let Some(position) = position {
                    // Closing this column (and every deeper one) returns to the option that opened it.
                    let parent = path.peek()[position];
                    path.write().truncate(position);
                    focus_option(parent);
                }
            }
        },
    );

    let trigger_label = picked
        .read()
        .as_ref()
        .map_or_else(|| props.placeholder.clone(), |(_, label)| label.clone());
    let picked_value = picked.read().as_ref().map(|(value, _)| value.clone());
    let class = compose([Some("ui-cascader"), props.class.as_deref()]);
    let active_path = path.read().clone();

    rsx! {
        div {
            class,
            "data-surface": "default",
            "data-ui-cascader": "true",
            "data-ui-cascader-bound": "true",
            "data-ui-owner": "dioxus",
            "data-ui-popover": "true",
            id: props.id.clone(),
            onkeydown: move |event: KeyboardEvent| {
                if is_open && is_escape(&event) {
                    event.prevent_default();
                    set_open(false);
                    focus_element(trigger.peek().clone());
                }
            },
            ..props.attributes,
            button {
                aria_controls: panel_id.clone(),
                aria_expanded: if is_open { "true" } else { "false" },
                aria_haspopup: "listbox",
                class: "ui-select ui-select__trigger ui-cascader__trigger",
                "data-ui-trigger": "true",
                role: "combobox",
                r#type: "button",
                onclick: move |_| set_open(!is_open),
                onkeydown: move |event: KeyboardEvent| {
                    let key = event.key();

                    if !is_open
                        && (key == Key::ArrowDown || key == Key::Enter || key == Key::Character(" ".to_string()))
                    {
                        event.prevent_default();
                        set_open(true);
                        focus_option((0, 0));
                    }
                },
                onmounted: move |event: MountedEvent| trigger.set(Some(event.data())),
                span {
                    "data-ui-cascader-placeholder": props.placeholder.clone(),
                    "data-ui-cascader-value": "true",
                    "{trigger_label}"
                }
            }
            if is_open {
                DismissLayer { on_dismiss: move |()| set_open(false) }
            }
            div {
                class: "ui-cascader__panel",
                "data-state": if is_open { "open" } else { "closed" },
                "data-ui-panel": "true",
                hidden: !is_open,
                id: panel_id,
                for (column_index, column) in columns.into_iter().enumerate() {
                    ol {
                        key: "{column.id}",
                        aria_label: if column.root { "Options" } else { "Sub-options" },
                        class: "ui-cascader__column",
                        hidden: !visible.get(column_index).copied().unwrap_or(false),
                        id: column.id.clone(),
                        role: "listbox",
                        for (option_index, cell) in column.options.into_iter().enumerate() {
                            li { key: "{cell.value}", role: "presentation",
                                button {
                                    aria_selected: if active_path.contains(&(column_index, option_index)) { "true" } else { "false" },
                                    class: "ui-cascader__option",
                                    "data-active": if active_path.contains(&(column_index, option_index)) { "true" } else { "false" },
                                    "data-label": cell.label.clone(),
                                    "data-ui-cascader-next": cell.next.map(|next| format!("#{base_id}-column-{}", next + 1)),
                                    "data-ui-cascader-option": "true",
                                    "data-value": cell.value.clone(),
                                    role: "option",
                                    r#type: "button",
                                    onclick: move |_| pick((column_index, option_index)),
                                    onkeydown: move |event: KeyboardEvent| on_option_key((event, column_index, option_index)),
                                    onmounted: move |event: MountedEvent| {
                                        let node = event.data();
                                        nodes.write().insert((column_index, option_index), node.clone());

                                        if *pending_focus.peek() == Some((column_index, option_index)) {
                                            pending_focus.set(None);
                                            focus_element(Some(node));
                                        }
                                    },
                                    span { "{cell.label}" }
                                    if cell.next.is_some() {
                                        Icon { icon: &lucide::CHEVRON_RIGHT, size: IconSize::Sm }
                                    }
                                }
                            }
                        }
                    }
                }
                {props.children}
            }
            if let Some(name) = props.name {
                input {
                    "data-ui-cascader-input": "true",
                    name,
                    r#type: "hidden",
                    // lumen-react always writes the attribute, empty until a leaf is picked.
                    "value": picked_value.clone().unwrap_or_default(),
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{CascaderOption, cascader_columns, cascader_visible_columns};

    fn tree() -> Vec<CascaderOption> {
        vec![
            CascaderOption::new("co", "Colombia").with_children(vec![
                CascaderOption::new("bog", "Bogotá"),
                CascaderOption::new("and", "Andes")
                    .with_children(vec![CascaderOption::new("med", "MedellĂ­n")]),
            ]),
            CascaderOption::new("pt", "Portugal")
                .with_children(vec![CascaderOption::new("lis", "Lisbon")]),
            CascaderOption::new("other", "Other"),
        ]
    }

    #[test]
    fn columns_follow_depth_first_order() {
        let columns = cascader_columns(&tree(), "c");
        let ids: Vec<&str> = columns.iter().map(|column| column.id.as_str()).collect();
        assert_eq!(
            ids,
            ["c-column-1", "c-column-2", "c-column-3", "c-column-4"]
        );
        assert_eq!(columns[0].options[0].next, Some(1));
        assert_eq!(columns[1].options[1].next, Some(2));
        assert_eq!(columns[0].options[1].next, Some(3));
        assert_eq!(columns[0].options[2].next, None);
        assert!(columns[0].root && !columns[1].root);
        assert_eq!(cascader_columns(&[], "c"), Vec::new());
    }

    #[test]
    fn the_active_path_shows_its_columns() {
        let columns = cascader_columns(&tree(), "c");
        assert_eq!(
            cascader_visible_columns(&columns, &[]),
            [true, false, false, false]
        );
        assert_eq!(
            cascader_visible_columns(&columns, &[(0, 0), (1, 1)]),
            [true, true, true, false]
        );
    }

    #[test]
    fn deep_trees_do_not_overflow() {
        let mut node = CascaderOption::new("leaf", "Leaf");

        for depth in 0..5_000 {
            node = CascaderOption::new(format!("n{depth}"), "Node").with_children(vec![node]);
        }

        let columns = cascader_columns(&[node], "deep");
        assert_eq!(columns.len(), 5_001);
        // Dropping a deep tree recurses; leak it so the test checks only the column builder.
        std::mem::forget(columns);
    }
}