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
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
//! `TreeSelect`: a select whose options form a collapsible tree.

use std::collections::{HashMap, HashSet};
use std::rc::Rc;

use dioxus::prelude::*;

use crate::class::compose;
use crate::hooks::{use_controllable, use_unique_id};
use crate::overlay::{DismissLayer, focus_element, is_escape};

/// One tree node.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TreeSelectNode {
    /// Submitted value.
    pub value: String,
    /// Visible label.
    pub label: String,
    /// Blocks selecting this node and its descendants.
    pub disabled: bool,
    /// Child nodes.
    pub children: Vec<TreeSelectNode>,
}

impl TreeSelectNode {
    /// An enabled leaf.
    pub fn new(value: impl Into<String>, label: impl Into<String>) -> Self {
        Self {
            value: value.into(),
            label: label.into(),
            disabled: false,
            children: Vec::new(),
        }
    }

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

    /// The same node, disabled along with its descendants.
    #[must_use]
    pub fn disabled(mut self) -> Self {
        self.disabled = true;
        self
    }
}

/// A flattened node.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct TreeSelectRow {
    pub(crate) depth: usize,
    pub(crate) parent: Option<String>,
    pub(crate) disabled: bool,
    pub(crate) label: String,
    pub(crate) value: String,
}

/// Depth-first rows with inherited `disabled` and duplicate values skipped, like
/// `flattenTreeSelect` (iterative, so deep trees cannot overflow the stack).
pub(crate) fn flatten_tree_select(nodes: &[TreeSelectNode]) -> Vec<TreeSelectRow> {
    let mut rows = Vec::new();
    let mut seen = HashSet::new();
    let mut branches: Vec<(bool, std::slice::Iter<'_, TreeSelectNode>, Option<String>)> =
        vec![(false, nodes.iter(), None)];

    while let Some((disabled_branch, iter, parent)) = branches.last_mut() {
        let Some(node) = iter.next() else {
            branches.pop();
            continue;
        };

        if !seen.insert(node.value.clone()) {
            continue;
        }

        let disabled = *disabled_branch || node.disabled;
        let parent = parent.clone();
        let depth = branches.len();

        rows.push(TreeSelectRow {
            depth,
            parent,
            disabled,
            label: node.label.clone(),
            value: node.value.clone(),
        });

        if !node.children.is_empty() {
            branches.push((disabled, node.children.iter(), Some(node.value.clone())));
        }
    }

    rows
}

/// Rows not hidden under a collapsed ancestor, with `Some(expanded)` for rows that have children.
pub(crate) fn visible_tree_select_rows(
    rows: &[TreeSelectRow],
    collapsed: &HashSet<String>,
) -> Vec<(Option<bool>, TreeSelectRow)> {
    let mut hidden_below = usize::MAX;
    let mut visible = Vec::new();

    for (index, row) in rows.iter().enumerate() {
        if row.depth > hidden_below {
            continue;
        }

        let has_children = rows
            .get(index + 1)
            .is_some_and(|next| next.depth > row.depth);
        let expanded = has_children.then(|| !collapsed.contains(&row.value));
        hidden_below = if expanded == Some(false) {
            row.depth
        } else {
            usize::MAX
        };
        visible.push((expanded, row.clone()));
    }

    visible
}

/// The row a navigation key focuses among the enabled visible rows, like `focusTreeSelectItem`.
pub(crate) fn tree_select_focus_target(
    key: &Key,
    current: &str,
    items: &[(String, Option<String>)],
) -> Option<usize> {
    if items.is_empty() {
        return None;
    }

    let index = items.iter().position(|(value, _)| value == current);

    match key {
        Key::End => Some(items.len() - 1),
        Key::Home => Some(0),
        Key::ArrowDown => Some(index.map_or(0, |index| (index + 1).min(items.len() - 1))),
        Key::ArrowUp => Some(index.map_or(0, |index| index.saturating_sub(1))),
        Key::ArrowRight => items
            .iter()
            .position(|(_, parent)| parent.as_deref() == Some(current)),
        Key::ArrowLeft => {
            let parent = items.get(index?)?.1.clone()?;
            items.iter().position(|(value, _)| *value == parent)
        }
        _ => None,
    }
}

/// Props for [`TreeSelect`].
#[derive(Props, Clone, PartialEq)]
pub struct TreeSelectProps {
    /// The tree.
    #[props(default)]
    pub tree_data: Vec<TreeSelectNode>,
    /// Controlled selected value.
    #[props(into)]
    pub value: Option<String>,
    /// Initial value when uncontrolled.
    #[props(into)]
    pub default_value: Option<String>,
    /// Called with the picked value.
    pub on_value_change: Option<EventHandler<String>>,
    /// Disables the trigger and every node.
    #[props(default)]
    pub disabled: bool,
    /// Form field name of the hidden input.
    #[props(into)]
    pub name: Option<String>,
    /// Trigger text and tree name while nothing is selected.
    #[props(default = "Select…".to_string(), into)]
    pub placeholder: String,
    /// Extra classes appended after the Lumen class.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<div>` or global attribute. `aria_label` and `aria_labelledby` also name the
    /// trigger and the tree, like lumen-react.
    #[props(extends = GlobalAttributes, extends = div)]
    pub attributes: Vec<Attribute>,
    /// Extra content at the end of the panel.
    pub children: Element,
}

fn attribute_text(attributes: &[Attribute], name: &str) -> Option<String> {
    attributes
        .iter()
        .rev()
        .find(|attribute| attribute.name == name)
        .and_then(|attribute| match &attribute.value {
            dioxus::core::AttributeValue::Text(text) => Some(text.clone()),
            _ => None,
        })
}

/// A select backed by a tree. Opening expands every branch and focuses the selected node.
///
/// In the tree, Arrow Up and Down move, Home and End jump, Arrow Right expands or moves to the
/// first child, Arrow Left collapses or moves to the parent, Enter picks, and Escape closes.
#[component]
pub fn TreeSelect(props: TreeSelectProps) -> Element {
    let rows = flatten_tree_select(&props.tree_data);
    let value = use_controllable(
        props.value.clone(),
        || props.default_value.clone().unwrap_or_default(),
        props.on_value_change,
    );
    let current = value.get();
    let selected = rows.iter().find(|row| row.value == current).cloned();
    let disabled = props.disabled;
    let mut requested_open = use_signal(|| false);
    let open = requested_open() && !disabled;
    let mut collapsed = use_signal(HashSet::<String>::new);
    let tree_id = use_unique_id();
    let panel_uid = use_unique_id();
    let panel_id = format!("ui-menu-{panel_uid}");
    let mut trigger = use_signal(|| None::<Rc<MountedData>>);
    let mut nodes = use_signal(HashMap::<String, Rc<MountedData>>::new);
    let mut pending_focus = use_signal(|| None::<String>);
    let visible = visible_tree_select_rows(&rows, &collapsed.read());
    let focusable: Vec<(String, Option<String>)> = visible
        .iter()
        .filter(|(_, row)| !(disabled || row.disabled))
        .map(|(_, row)| (row.value.clone(), row.parent.clone()))
        .collect();
    let selected_value = selected.as_ref().map(|row| row.value.clone());

    let aria_label = attribute_text(&props.attributes, "aria-label");
    let aria_labelledby = attribute_text(&props.attributes, "aria-labelledby");
    let tree_label = aria_label
        .clone()
        .unwrap_or_else(|| props.placeholder.clone());

    let focusable_for_open = focusable.clone();
    let selected_for_open = selected_value.clone();
    let focus_row = use_callback(move |target: String| {
        if let Some(node) = nodes.peek().get(&target).cloned() {
            focus_element(Some(node));
        }

        pending_focus.set(Some(target));
    });
    let set_open = use_callback(move |next: bool| {
        if next && disabled {
            return;
        }

        if next && !requested_open() {
            collapsed.set(HashSet::new());
            let target = selected_for_open
                .clone()
                .filter(|value| focusable_for_open.iter().any(|(entry, _)| entry == value))
                .or_else(|| focusable_for_open.first().map(|(entry, _)| entry.clone()));

            if let Some(target) = target {
                focus_row(target);
            }
        }

        requested_open.set(next);
    });

    let mut close_to_trigger = move || {
        requested_open.set(false);
        focus_element(trigger.peek().clone());
    };

    let class = compose([Some("ui-tree-select"), props.class.as_deref()]);
    let trigger_text = selected
        .as_ref()
        .map_or_else(|| props.placeholder.clone(), |row| row.label.clone());
    let focusable_for_keys = focusable.clone();
    let focusable_for_trigger = focusable.clone();
    let selected_for_trigger = selected_value.clone();

    rsx! {
        div {
            class,
            "data-surface": "default",
            "data-ui-owner": "dioxus",
            "data-ui-popover": "true",
            "data-ui-tree-select": "true",
            "data-ui-tree-select-bound": "true",
            ..props.attributes,
            button {
                aria_controls: tree_id.clone(),
                aria_expanded: if open { "true" } else { "false" },
                aria_haspopup: "tree",
                aria_label: aria_label.clone(),
                aria_labelledby: aria_labelledby.clone(),
                class: "ui-select ui-select__trigger ui-tree-select__trigger",
                "data-ui-trigger": "true",
                disabled,
                r#type: "button",
                onclick: move |_| set_open(!open),
                onkeydown: move |event: KeyboardEvent| {
                    let modifiers = event.modifiers();

                    if disabled || event.is_composing() || modifiers.alt() || modifiers.ctrl()
                        || modifiers.meta() || modifiers.shift()
                    {
                        return;
                    }

                    let key = event.key();

                    if matches!(key, Key::ArrowUp | Key::ArrowDown | Key::Enter)
                        || key == Key::Character(" ".to_string())
                    {
                        event.prevent_default();

                        if open {
                            let target = selected_for_trigger
                                .clone()
                                .filter(|value| focusable_for_trigger.iter().any(|(entry, _)| entry == value))
                                .or_else(|| focusable_for_trigger.first().map(|(entry, _)| entry.clone()));

                            if let Some(target) = target {
                                focus_row(target);
                            }
                        } else {
                            set_open(true);
                        }
                    } else if key == Key::Escape && open {
                        event.prevent_default();
                        requested_open.set(false);
                    }
                },
                onmounted: move |event: MountedEvent| trigger.set(Some(event.data())),
                span {
                    "data-ui-tree-select-placeholder": props.placeholder.clone(),
                    "data-ui-tree-select-value": "true",
                    "{trigger_text}"
                }
            }
            if open {
                DismissLayer { on_dismiss: move |()| requested_open.set(false) }
            }
            div {
                class: "ui-tree-select__panel",
                "data-state": if open { "open" } else { "closed" },
                "data-ui-panel": "true",
                hidden: !open,
                id: panel_id,
                onkeydown: move |event: KeyboardEvent| {
                    if is_escape(&event) && !event.is_composing() {
                        event.prevent_default();
                        close_to_trigger();
                    }
                },
                div {
                    aria_label: tree_label,
                    aria_labelledby,
                    class: "ui-tree-select__tree",
                    id: tree_id,
                    role: "tree",
                    for (expanded, row) in visible {
                        button {
                            key: "{row.value}",
                            aria_expanded: expanded.map(|expanded| if expanded { "true" } else { "false" }),
                            aria_level: "{row.depth}",
                            aria_selected: if selected_value.as_deref() == Some(row.value.as_str()) { "true" } else { "false" },
                            class: "ui-tree-select__option",
                            "data-active": if selected_value.as_deref() == Some(row.value.as_str()) { "true" } else { "false" },
                            "data-parent-value": row.parent.clone(),
                            "data-value": row.value.clone(),
                            disabled: disabled || row.disabled,
                            role: "treeitem",
                            style: "--ui-tree-depth:{row.depth - 1}",
                            tabindex: "-1",
                            r#type: "button",
                            onclick: {
                                let picked = row.value.clone();
                                let blocked = disabled || row.disabled;
                                move |_| {
                                    if blocked {
                                        return;
                                    }

                                    close_to_trigger();
                                    value.set(picked.clone());
                                }
                            },
                            onkeydown: {
                                let row_value = row.value.clone();
                                let items = focusable_for_keys.clone();
                                move |event: KeyboardEvent| {
                                    let modifiers = event.modifiers();

                                    if event.is_composing() || modifiers.alt() || modifiers.ctrl()
                                        || modifiers.meta() || modifiers.shift()
                                    {
                                        return;
                                    }

                                    let key = event.key();

                                    if !matches!(
                                        key,
                                        Key::ArrowDown | Key::ArrowUp | Key::Home | Key::End | Key::ArrowLeft | Key::ArrowRight
                                    ) {
                                        return;
                                    }

                                    event.prevent_default();

                                    if key == Key::ArrowLeft && expanded == Some(true) {
                                        collapsed.write().insert(row_value.clone());
                                    } else if key == Key::ArrowRight && expanded == Some(false) {
                                        collapsed.write().remove(&row_value);
                                    } else if let Some(index) = tree_select_focus_target(&key, &row_value, &items)
                                        && let Some((target, _)) = items.get(index)
                                    {
                                        focus_row(target.clone());
                                    }
                                }
                            },
                            onmounted: {
                                let row_value = row.value.clone();
                                move |event: MountedEvent| {
                                    let node = event.data();
                                    nodes.write().insert(row_value.clone(), node.clone());

                                    if pending_focus.peek().as_deref() == Some(row_value.as_str()) {
                                        pending_focus.set(None);
                                        focus_element(Some(node));
                                    }
                                }
                            },
                            "{row.label}"
                        }
                    }
                }
                {props.children}
            }
            if let Some(name) = props.name {
                input {
                    "data-ui-tree-select-input": "true",
                    disabled,
                    name,
                    r#type: "hidden",
                    value: selected_value.clone().unwrap_or_default(),
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use std::collections::HashSet;

    use super::{
        TreeSelectNode, flatten_tree_select, tree_select_focus_target, visible_tree_select_rows,
    };
    use dioxus::prelude::Key;

    fn tree() -> Vec<TreeSelectNode> {
        vec![
            TreeSelectNode::new("design", "Design").with_children(vec![
                TreeSelectNode::new("tokens", "Tokens"),
                TreeSelectNode::new("icons", "Icons").disabled(),
            ]),
            TreeSelectNode::new("eng", "Engineering")
                .disabled()
                .with_children(vec![TreeSelectNode::new("web", "Web")]),
            TreeSelectNode::new("tokens", "Duplicate"),
        ]
    }

    #[test]
    fn rows_flatten_depth_first_with_inherited_disabled() {
        let rows = flatten_tree_select(&tree());
        let values: Vec<&str> = rows.iter().map(|row| row.value.as_str()).collect();
        assert_eq!(values, ["design", "tokens", "icons", "eng", "web"]);
        assert_eq!(rows[1].depth, 2);
        assert_eq!(rows[1].parent.as_deref(), Some("design"));
        assert!(rows[2].disabled && rows[4].disabled && !rows[1].disabled);
    }

    #[test]
    fn collapsed_rows_hide_their_descendants() {
        let rows = flatten_tree_select(&tree());
        let all = visible_tree_select_rows(&rows, &HashSet::new());
        assert_eq!(all.len(), 5);
        assert_eq!(all[0].0, Some(true));
        assert_eq!(all[1].0, None);

        let collapsed = HashSet::from(["design".to_string()]);
        let visible = visible_tree_select_rows(&rows, &collapsed);
        let values: Vec<&str> = visible.iter().map(|(_, row)| row.value.as_str()).collect();
        assert_eq!(values, ["design", "eng", "web"]);
        assert_eq!(visible[0].0, Some(false));
    }

    #[test]
    fn keys_move_through_enabled_rows() {
        let items = vec![
            ("a".to_string(), None),
            ("a1".to_string(), Some("a".to_string())),
            ("b".to_string(), None),
        ];
        assert_eq!(
            tree_select_focus_target(&Key::ArrowDown, "a", &items),
            Some(1)
        );
        assert_eq!(
            tree_select_focus_target(&Key::ArrowDown, "b", &items),
            Some(2)
        );
        assert_eq!(
            tree_select_focus_target(&Key::ArrowUp, "a", &items),
            Some(0)
        );
        assert_eq!(tree_select_focus_target(&Key::End, "a", &items), Some(2));
        assert_eq!(tree_select_focus_target(&Key::Home, "b", &items), Some(0));
        assert_eq!(
            tree_select_focus_target(&Key::ArrowRight, "a", &items),
            Some(1)
        );
        assert_eq!(
            tree_select_focus_target(&Key::ArrowRight, "b", &items),
            None
        );
        assert_eq!(
            tree_select_focus_target(&Key::ArrowLeft, "a1", &items),
            Some(0)
        );
        assert_eq!(tree_select_focus_target(&Key::ArrowLeft, "a", &items), None);
    }

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

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

        let tree = vec![node];
        let rows = flatten_tree_select(&tree);
        assert_eq!(rows.len(), 5_001);
        // Dropping a deep tree recurses; leak it so the test checks only the flattening.
        std::mem::forget(tree);
    }
}