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
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
//! `Tree` and `TreeGrid`: hierarchical collections with WAI-ARIA keyboard navigation.
//!
//! Both components accept children for hand-written markup, like lumen-react, and an optional
//! data API (`nodes` or `rows`) that renders the items and handles the keyboard in Rust, because
//! Dioxus has no Lumen web runtime to enhance static markup.

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

use dioxus::prelude::*;

use crate::class::{Glass, compose};
use crate::hooks::{Controllable, use_controllable};
use crate::overlay::focus_element;

/// One item of a data-driven [`Tree`].
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct TreeNode {
    /// Stable, unique id reported by selection and expansion callbacks.
    pub id: String,
    /// Visible text; also used for type-ahead.
    pub label: String,
    /// Child items. A node with children is a branch that expands and collapses.
    pub children: Vec<TreeNode>,
    /// Keeps the item focusable but prevents selecting or expanding it.
    pub disabled: bool,
}

impl TreeNode {
    /// A leaf node.
    pub fn new(id: impl Into<String>, label: impl Into<String>) -> Self {
        Self {
            id: id.into(),
            label: label.into(),
            ..Self::default()
        }
    }

    /// Sets the child nodes.
    #[must_use]
    pub fn with_children(mut self, children: Vec<TreeNode>) -> Self {
        self.children = children;
        self
    }

    /// Marks the node disabled.
    #[must_use]
    pub fn disabled(mut self) -> Self {
        self.disabled = true;
        self
    }
}

/// One row of a data-driven [`TreeGrid`].
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct TreeGridRow {
    /// Stable, unique id reported by selection and expansion callbacks.
    pub id: String,
    /// Cell text, one entry per column. The first cell is used for type-ahead.
    pub cells: Vec<String>,
    /// Child rows. A row with children expands and collapses.
    pub children: Vec<TreeGridRow>,
    /// Keeps the row focusable but prevents selecting or expanding it.
    pub disabled: bool,
}

impl TreeGridRow {
    /// A row with the given cells.
    pub fn new(id: impl Into<String>, cells: impl IntoIterator<Item = impl Into<String>>) -> Self {
        Self {
            id: id.into(),
            cells: cells.into_iter().map(Into::into).collect(),
            ..Self::default()
        }
    }

    /// Sets the child rows.
    #[must_use]
    pub fn with_children(mut self, children: Vec<TreeGridRow>) -> Self {
        self.children = children;
        self
    }

    /// Marks the row disabled.
    #[must_use]
    pub fn disabled(mut self) -> Self {
        self.disabled = true;
        self
    }
}

trait OutlineNode: Sized {
    fn outline_id(&self) -> &str;
    fn outline_label(&self) -> &str;
    fn outline_children(&self) -> &[Self];
    fn outline_disabled(&self) -> bool;
}

impl OutlineNode for TreeNode {
    fn outline_id(&self) -> &str {
        &self.id
    }

    fn outline_label(&self) -> &str {
        &self.label
    }

    fn outline_children(&self) -> &[Self] {
        &self.children
    }

    fn outline_disabled(&self) -> bool {
        self.disabled
    }
}

impl OutlineNode for TreeGridRow {
    fn outline_id(&self) -> &str {
        &self.id
    }

    fn outline_label(&self) -> &str {
        self.cells.first().map_or("", String::as_str)
    }

    fn outline_children(&self) -> &[Self] {
        &self.children
    }

    fn outline_disabled(&self) -> bool {
        self.disabled
    }
}

/// A visible row of a tree, in display order.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct OutlineRow {
    pub id: String,
    pub label: String,
    pub level: usize,
    pub parent: Option<usize>,
    pub has_children: bool,
    pub expanded: bool,
    pub disabled: bool,
}

/// Flattens the visible part of a tree (collapsed branches hide their descendants) without
/// recursion, so very deep trees cannot overflow the stack.
fn outline_rows<N: OutlineNode>(roots: &[N], expanded: &[String]) -> Vec<OutlineRow> {
    let mut rows = Vec::new();
    let mut stack: Vec<(std::slice::Iter<'_, N>, usize, Option<usize>)> =
        vec![(roots.iter(), 1, None)];

    while let Some(top) = stack.last_mut() {
        let (level, parent) = (top.1, top.2);

        let Some(node) = top.0.next() else {
            stack.pop();
            continue;
        };

        let has_children = !node.outline_children().is_empty();
        let is_expanded = has_children && expanded.iter().any(|id| id == node.outline_id());
        let index = rows.len();

        rows.push(OutlineRow {
            id: node.outline_id().to_string(),
            label: node.outline_label().to_string(),
            level,
            parent,
            has_children,
            expanded: is_expanded,
            disabled: node.outline_disabled(),
        });

        if is_expanded {
            stack.push((node.outline_children().iter(), level + 1, Some(index)));
        }
    }

    rows
}

/// What a key press does to a tree.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum OutlineAction {
    /// Move focus to the row.
    Focus(usize),
    /// Open the branch.
    Expand(usize),
    /// Close the branch.
    Collapse(usize),
    /// Select the row and toggle it when it is a branch.
    Activate(usize),
}

fn first_char_lowercase(text: &str) -> Option<char> {
    text.trim_start()
        .chars()
        .next()
        .map(|c| c.to_lowercase().next().unwrap_or(c))
}

/// Maps a key press on the row at `current` to an action, following the WAI-ARIA tree pattern:
/// Up and Down move (looping like the Lumen web runtime), Home and End jump, Right opens a branch
/// or enters it, Left closes a branch or moves to the parent, Enter and Space activate, and a
/// printable character moves to the next row whose label starts with it.
pub(crate) fn outline_key_action(
    rows: &[OutlineRow],
    current: usize,
    key: &Key,
) -> Option<OutlineAction> {
    let len = rows.len();
    let row = rows.get(current)?;

    match key {
        Key::ArrowDown => Some(OutlineAction::Focus((current + 1) % len)),
        Key::ArrowUp => Some(OutlineAction::Focus((current + len - 1) % len)),
        Key::Home => Some(OutlineAction::Focus(0)),
        Key::End => Some(OutlineAction::Focus(len - 1)),
        Key::ArrowRight if row.has_children && !row.expanded && !row.disabled => {
            Some(OutlineAction::Expand(current))
        }
        Key::ArrowRight if row.expanded => rows
            .get(current + 1)
            .filter(|child| child.parent == Some(current))
            .map(|_| OutlineAction::Focus(current + 1)),
        Key::ArrowLeft if row.expanded && !row.disabled => Some(OutlineAction::Collapse(current)),
        Key::ArrowLeft => row.parent.map(OutlineAction::Focus),
        Key::Enter => Some(OutlineAction::Activate(current)),
        Key::Character(text) if text == " " => Some(OutlineAction::Activate(current)),
        Key::Character(text) => {
            let mut chars = text.chars();
            let wanted = chars.next()?.to_lowercase().next()?;

            if chars.next().is_some() || wanted.is_whitespace() {
                return None;
            }

            (1..len)
                .map(|step| (current + step) % len)
                .find(|index| first_char_lowercase(&rows[*index].label) == Some(wanted))
                .map(OutlineAction::Focus)
        }
        _ => None,
    }
}

/// Shared state of a data-driven tree or tree grid.
#[derive(Clone)]
struct OutlineView {
    rows: Rc<[OutlineRow]>,
    indexes: Rc<HashMap<String, usize>>,
    expanded: Controllable<Vec<String>>,
    selected_prop: Option<String>,
    internal_selected: Signal<Option<String>>,
    on_select: Option<EventHandler<String>>,
    focused: Signal<Option<String>>,
    mounted: Signal<HashMap<String, Rc<MountedData>>>,
}

impl OutlineView {
    fn selected(&self) -> Option<String> {
        self.selected_prop
            .clone()
            .or_else(|| self.internal_selected.read().clone())
    }

    /// The row that holds `tabindex="0"`: the focused row, else the selected one, else the first.
    fn tab_stop(&self) -> Option<String> {
        let visible = |id: &String| self.indexes.contains_key(id);

        self.focused
            .read()
            .clone()
            .filter(visible)
            .or_else(|| self.selected().filter(visible))
            .or_else(|| self.rows.first().map(|row| row.id.clone()))
    }

    fn focus(&self, index: usize) {
        let Some(row) = self.rows.get(index) else {
            return;
        };
        let mut focused = self.focused;

        focused.set(Some(row.id.clone()));
        focus_element(self.mounted.peek().get(&row.id).cloned());
    }

    fn set_expanded(&self, id: &str, open: bool) {
        let mut next = self.expanded.peek();
        let present = next.iter().any(|entry| entry == id);

        if open && !present {
            next.push(id.to_string());
        } else if !open && present {
            next.retain(|entry| entry != id);
        } else {
            return;
        }

        self.expanded.set(next);
    }

    fn activate(&self, index: usize) {
        let Some(row) = self.rows.get(index) else {
            return;
        };

        if row.disabled {
            return;
        }

        if self.selected_prop.is_none() {
            let mut internal = self.internal_selected;
            internal.set(Some(row.id.clone()));
        }

        if let Some(handler) = self.on_select {
            handler.call(row.id.clone());
        }

        if row.has_children {
            self.set_expanded(&row.id, !row.expanded);
        }
    }

    fn keydown(&self, index: usize, event: &KeyboardEvent) {
        let modifiers = event.modifiers();

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

        // Dioxus Native cannot move DOM focus, so keys keep acting on the row that holds the
        // roving tab stop even while the first focused row still receives the events.
        let current = self
            .focused
            .peek()
            .as_ref()
            .and_then(|id| self.indexes.get(id).copied())
            .unwrap_or(index);
        let Some(action) = outline_key_action(&self.rows, current, &event.key()) else {
            return;
        };

        event.prevent_default();

        match action {
            OutlineAction::Focus(next) => self.focus(next),
            OutlineAction::Expand(next) => {
                if let Some(row) = self.rows.get(next) {
                    self.set_expanded(&row.id, true);
                }
            }
            OutlineAction::Collapse(next) => {
                if let Some(row) = self.rows.get(next) {
                    self.set_expanded(&row.id, false);
                }
            }
            OutlineAction::Activate(next) => self.activate(next),
        }
    }

    /// Attributes shared by tree items and tree grid rows.
    fn item(&self, id: &str) -> Option<(usize, &OutlineRow)> {
        let index = *self.indexes.get(id)?;
        self.rows.get(index).map(|row| (index, row))
    }
}

struct OutlineOptions {
    expanded: Option<Vec<String>>,
    default_expanded: Vec<String>,
    on_expanded_change: Option<EventHandler<Vec<String>>>,
    selected: Option<String>,
    default_selected: Option<String>,
    on_select: Option<EventHandler<String>>,
}

fn use_outline<N: OutlineNode>(roots: &[N], options: OutlineOptions) -> OutlineView {
    let OutlineOptions {
        expanded,
        default_expanded,
        on_expanded_change,
        selected,
        default_selected,
        on_select,
    } = options;
    let expanded = use_controllable(expanded, || default_expanded, on_expanded_change);
    let internal_selected = use_signal(|| default_selected);
    let focused = use_signal(|| None::<String>);
    let mounted = use_signal(HashMap::<String, Rc<MountedData>>::new);
    let rows = outline_rows(roots, &expanded.get());
    let indexes = rows
        .iter()
        .enumerate()
        .map(|(index, row)| (row.id.clone(), index))
        .collect();

    OutlineView {
        rows: Rc::from(rows),
        indexes: Rc::new(indexes),
        expanded,
        selected_prop: selected,
        internal_selected,
        on_select,
        focused,
        mounted,
    }
}

/// Props for [`Tree`].
#[derive(Props, Clone, PartialEq)]
pub struct TreeProps {
    /// Items to render with keyboard support. Leave empty to write the markup yourself.
    #[props(default)]
    pub nodes: Vec<TreeNode>,
    /// Controlled ids of the open branches.
    pub expanded: Option<Vec<String>>,
    /// Initially open branches when uncontrolled.
    #[props(default)]
    pub default_expanded: Vec<String>,
    /// Called with the open branch ids after a branch opens or closes.
    pub on_expanded_change: Option<EventHandler<Vec<String>>>,
    /// Controlled selected id.
    #[props(into)]
    pub selected: Option<String>,
    /// Initially selected id when uncontrolled.
    #[props(into)]
    pub default_selected: Option<String>,
    /// Called with the id of the item the user selects.
    pub on_select: Option<EventHandler<String>>,
    /// Glass intensity.
    #[props(default, into)]
    pub glass: Glass,
    /// ARIA role of the root. Defaults to `tree`.
    #[props(default = "tree".to_string(), into)]
    pub role: String,
    /// Extra classes appended after the Lumen classes.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<div>` or global attribute. Name the tree with `aria_label`.
    #[props(extends = GlobalAttributes, extends = div)]
    pub attributes: Vec<Attribute>,
    /// Hand-written `treeitem` and `group` markup, rendered after the data items.
    pub children: Element,
}

fn render_tree_nodes(nodes: &[TreeNode], view: &OutlineView, tab_stop: Option<&str>) -> Element {
    rsx! {
        for node in nodes {
            {render_tree_node(node, view, tab_stop)}
        }
    }
}

fn render_tree_node(node: &TreeNode, view: &OutlineView, tab_stop: Option<&str>) -> Element {
    let Some((index, row)) = view.item(&node.id) else {
        return rsx! {};
    };
    let selected = view.selected().as_deref() == Some(row.id.as_str());
    let (click_view, key_view, mut mounted) = (view.clone(), view.clone(), view.mounted);
    let mount_id = row.id.clone();

    rsx! {
        div {
            key: "{row.id}",
            aria_disabled: row.disabled.then_some("true"),
            aria_expanded: row.has_children.then_some(if row.expanded { "true" } else { "false" }),
            aria_level: "{row.level}",
            aria_selected: if selected { "true" } else { "false" },
            "data-value": "{row.id}",
            role: "treeitem",
            tabindex: if tab_stop == Some(row.id.as_str()) { "0" } else { "-1" },
            onclick: move |_| {
                click_view.focus(index);
                click_view.activate(index);
            },
            onkeydown: move |event| key_view.keydown(index, &event),
            onmounted: move |event| {
                mounted.write().insert(mount_id.clone(), event.data());
            },
            "{row.label}"
        }
        if row.expanded {
            div { role: "group", {render_tree_nodes(&node.children, view, tab_stop)} }
        }
    }
}

/// A hierarchical list of items, such as files or navigation.
///
/// With `nodes`, items get roving focus and the WAI-ARIA tree keyboard: Up and Down move,
/// Home and End jump, Right opens or enters a branch, Left closes it or moves to the parent,
/// Enter, Space, and click select and toggle, and typing a letter jumps to the next match.
#[component]
pub fn Tree(props: TreeProps) -> Element {
    let view = use_outline(
        &props.nodes,
        OutlineOptions {
            expanded: props.expanded.clone(),
            default_expanded: props.default_expanded.clone(),
            on_expanded_change: props.on_expanded_change,
            selected: props.selected.clone(),
            default_selected: props.default_selected.clone(),
            on_select: props.on_select,
        },
    );
    let glass = props.glass.class("ui-tree");
    let class = compose([Some("ui-tree"), glass.as_deref(), props.class.as_deref()]);
    let tab_stop = view.tab_stop();

    rsx! {
        div { class, role: props.role, ..props.attributes,
            {render_tree_nodes(&props.nodes, &view, tab_stop.as_deref())}
            {props.children}
        }
    }
}

/// Props for [`TreeGrid`].
#[derive(Props, Clone, PartialEq)]
pub struct TreeGridProps {
    /// Column headers for the data rows.
    #[props(default)]
    pub columns: Vec<String>,
    /// Rows to render with keyboard support. Leave empty to write the markup yourself.
    #[props(default)]
    pub rows: Vec<TreeGridRow>,
    /// Controlled ids of the open rows.
    pub expanded: Option<Vec<String>>,
    /// Initially open rows when uncontrolled.
    #[props(default)]
    pub default_expanded: Vec<String>,
    /// Called with the open row ids after a row opens or closes.
    pub on_expanded_change: Option<EventHandler<Vec<String>>>,
    /// Controlled selected row id.
    #[props(into)]
    pub selected: Option<String>,
    /// Initially selected row id when uncontrolled.
    #[props(into)]
    pub default_selected: Option<String>,
    /// Called with the id of the row the user selects.
    pub on_select: Option<EventHandler<String>>,
    /// Glass intensity.
    #[props(default, into)]
    pub glass: Glass,
    /// ARIA role of the root. Defaults to `treegrid`.
    #[props(default = "treegrid".to_string(), into)]
    pub role: String,
    /// Extra classes appended after the Lumen classes.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<div>` or global attribute. Name the grid with `aria_label`.
    #[props(extends = GlobalAttributes, extends = div)]
    pub attributes: Vec<Attribute>,
    /// Hand-written `row` markup, rendered after the data rows.
    pub children: Element,
}

fn render_grid_rows(rows: &[TreeGridRow], view: &OutlineView, tab_stop: Option<&str>) -> Element {
    rsx! {
        for row in rows {
            {render_grid_row(row, view, tab_stop)}
        }
    }
}

fn render_grid_row(node: &TreeGridRow, view: &OutlineView, tab_stop: Option<&str>) -> Element {
    let Some((index, row)) = view.item(&node.id) else {
        return rsx! {};
    };
    let selected = view.selected().as_deref() == Some(row.id.as_str());
    let (click_view, key_view, mut mounted) = (view.clone(), view.clone(), view.mounted);
    let mount_id = row.id.clone();

    rsx! {
        div {
            key: "{row.id}",
            aria_disabled: row.disabled.then_some("true"),
            aria_expanded: row.has_children.then_some(if row.expanded { "true" } else { "false" }),
            aria_level: "{row.level}",
            aria_selected: if selected { "true" } else { "false" },
            "data-value": "{row.id}",
            role: "row",
            tabindex: if tab_stop == Some(row.id.as_str()) { "0" } else { "-1" },
            onclick: move |_| {
                click_view.focus(index);
                click_view.activate(index);
            },
            onkeydown: move |event| key_view.keydown(index, &event),
            onmounted: move |event| {
                mounted.write().insert(mount_id.clone(), event.data());
            },
            for (column, cell) in node.cells.iter().enumerate() {
                span { key: "{column}", role: "gridcell", "{cell}" }
            }
        }
        if row.expanded {
            {render_grid_rows(&node.children, view, tab_stop)}
        }
    }
}

/// Hierarchical rows with grid columns, such as a project status table.
///
/// With `rows`, the header row comes from `columns`, rows get roving focus, and the keyboard
/// follows [`Tree`]: rows are the focus targets (row-focus mode of the WAI-ARIA treegrid).
#[component]
pub fn TreeGrid(props: TreeGridProps) -> Element {
    let view = use_outline(
        &props.rows,
        OutlineOptions {
            expanded: props.expanded.clone(),
            default_expanded: props.default_expanded.clone(),
            on_expanded_change: props.on_expanded_change,
            selected: props.selected.clone(),
            default_selected: props.default_selected.clone(),
            on_select: props.on_select,
        },
    );
    let glass = props.glass.class("ui-tree-grid");
    let class = compose([
        Some("ui-tree-grid"),
        glass.as_deref(),
        props.class.as_deref(),
    ]);
    let tab_stop = view.tab_stop();

    rsx! {
        div { class, role: props.role, ..props.attributes,
            if !props.columns.is_empty() {
                div { role: "row",
                    for (column, title) in props.columns.iter().enumerate() {
                        span { key: "{column}", role: "columnheader", "{title}" }
                    }
                }
            }
            {render_grid_rows(&props.rows, &view, tab_stop.as_deref())}
            {props.children}
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{Key, OutlineAction, TreeNode, outline_key_action, outline_rows};

    fn sample() -> Vec<TreeNode> {
        vec![
            TreeNode::new("src", "src").with_children(vec![
                TreeNode::new("components", "components")
                    .with_children(vec![TreeNode::new("button", "button.rs")]),
                TreeNode::new("index", "index.ts"),
            ]),
            TreeNode::new("tests", "tests").with_children(vec![TreeNode::new("unit", "unit.rs")]),
            TreeNode::new("package", "package.json"),
        ]
    }

    #[test]
    fn collapsed_branches_hide_their_descendants() {
        let rows = outline_rows(&sample(), &["src".to_string()]);
        let ids: Vec<&str> = rows.iter().map(|row| row.id.as_str()).collect();

        assert_eq!(ids, ["src", "components", "index", "tests", "package"]);
        assert_eq!(rows[1].level, 2);
        assert_eq!(rows[1].parent, Some(0));
        assert!(rows[1].has_children && !rows[1].expanded);
        assert!(rows[0].expanded);
    }

    #[test]
    fn arrow_keys_follow_the_tree_pattern() {
        let rows = outline_rows(&sample(), &["src".to_string()]);

        assert_eq!(
            outline_key_action(&rows, 0, &Key::ArrowDown),
            Some(OutlineAction::Focus(1))
        );
        assert_eq!(
            outline_key_action(&rows, 4, &Key::ArrowDown),
            Some(OutlineAction::Focus(0))
        );
        assert_eq!(
            outline_key_action(&rows, 0, &Key::ArrowUp),
            Some(OutlineAction::Focus(4))
        );
        assert_eq!(
            outline_key_action(&rows, 2, &Key::End),
            Some(OutlineAction::Focus(4))
        );
        assert_eq!(
            outline_key_action(&rows, 2, &Key::Home),
            Some(OutlineAction::Focus(0))
        );
        // Right enters an open branch and opens a closed one; leaves do nothing.
        assert_eq!(
            outline_key_action(&rows, 0, &Key::ArrowRight),
            Some(OutlineAction::Focus(1))
        );
        assert_eq!(
            outline_key_action(&rows, 1, &Key::ArrowRight),
            Some(OutlineAction::Expand(1))
        );
        assert_eq!(outline_key_action(&rows, 2, &Key::ArrowRight), None);
        // Left closes an open branch and otherwise moves to the parent.
        assert_eq!(
            outline_key_action(&rows, 0, &Key::ArrowLeft),
            Some(OutlineAction::Collapse(0))
        );
        assert_eq!(
            outline_key_action(&rows, 2, &Key::ArrowLeft),
            Some(OutlineAction::Focus(0))
        );
        assert_eq!(outline_key_action(&rows, 4, &Key::ArrowLeft), None);
        assert_eq!(
            outline_key_action(&rows, 3, &Key::Enter),
            Some(OutlineAction::Activate(3))
        );
        assert_eq!(
            outline_key_action(&rows, 3, &Key::Character(" ".into())),
            Some(OutlineAction::Activate(3))
        );
    }

    #[test]
    fn typing_jumps_to_the_next_matching_label() {
        let rows = outline_rows(&sample(), &["src".to_string()]);

        assert_eq!(
            outline_key_action(&rows, 0, &Key::Character("T".into())),
            Some(OutlineAction::Focus(3))
        );
        assert_eq!(
            outline_key_action(&rows, 0, &Key::Character("i".into())),
            Some(OutlineAction::Focus(2))
        );
        assert_eq!(
            outline_key_action(&rows, 0, &Key::Character("z".into())),
            None
        );
        assert_eq!(
            outline_key_action(&rows, 0, &Key::Character("ab".into())),
            None
        );
    }

    #[test]
    fn disabled_branches_do_not_toggle() {
        let nodes = vec![
            TreeNode::new("a", "a")
                .with_children(vec![TreeNode::new("b", "b")])
                .disabled(),
        ];
        let rows = outline_rows(&nodes, &[]);

        assert_eq!(outline_key_action(&rows, 0, &Key::ArrowRight), None);
    }

    #[test]
    fn deep_trees_flatten_without_recursion() {
        let mut node = TreeNode::new("leaf", "leaf");
        let mut expanded = Vec::new();

        for depth in 0..20_000 {
            let id = format!("n{depth}");
            expanded.push(id.clone());
            node = TreeNode::new(id, "n").with_children(vec![node]);
        }

        let rows = outline_rows(
            std::slice::from_ref(&node),
            &expanded[expanded.len() - 50..],
        );
        assert_eq!(rows.len(), 51);
        assert_eq!(rows[50].level, 51);

        // Dropping a deeply nested value recursively could overflow; leak-free iterative drop.
        let mut stack = vec![node];
        while let Some(mut current) = stack.pop() {
            stack.append(&mut current.children);
        }
    }
}