1use std::collections::HashMap;
8use std::rc::Rc;
9
10use dioxus::prelude::*;
11
12use crate::class::{Glass, compose};
13use crate::hooks::{Controllable, use_controllable};
14use crate::overlay::focus_element;
15
16#[derive(Clone, Debug, Default, PartialEq, Eq)]
18pub struct TreeNode {
19 pub id: String,
21 pub label: String,
23 pub children: Vec<TreeNode>,
25 pub disabled: bool,
27}
28
29impl TreeNode {
30 pub fn new(id: impl Into<String>, label: impl Into<String>) -> Self {
32 Self {
33 id: id.into(),
34 label: label.into(),
35 ..Self::default()
36 }
37 }
38
39 #[must_use]
41 pub fn with_children(mut self, children: Vec<TreeNode>) -> Self {
42 self.children = children;
43 self
44 }
45
46 #[must_use]
48 pub fn disabled(mut self) -> Self {
49 self.disabled = true;
50 self
51 }
52}
53
54#[derive(Clone, Debug, Default, PartialEq, Eq)]
56pub struct TreeGridRow {
57 pub id: String,
59 pub cells: Vec<String>,
61 pub children: Vec<TreeGridRow>,
63 pub disabled: bool,
65}
66
67impl TreeGridRow {
68 pub fn new(id: impl Into<String>, cells: impl IntoIterator<Item = impl Into<String>>) -> Self {
70 Self {
71 id: id.into(),
72 cells: cells.into_iter().map(Into::into).collect(),
73 ..Self::default()
74 }
75 }
76
77 #[must_use]
79 pub fn with_children(mut self, children: Vec<TreeGridRow>) -> Self {
80 self.children = children;
81 self
82 }
83
84 #[must_use]
86 pub fn disabled(mut self) -> Self {
87 self.disabled = true;
88 self
89 }
90}
91
92trait OutlineNode: Sized {
93 fn outline_id(&self) -> &str;
94 fn outline_label(&self) -> &str;
95 fn outline_children(&self) -> &[Self];
96 fn outline_disabled(&self) -> bool;
97}
98
99impl OutlineNode for TreeNode {
100 fn outline_id(&self) -> &str {
101 &self.id
102 }
103
104 fn outline_label(&self) -> &str {
105 &self.label
106 }
107
108 fn outline_children(&self) -> &[Self] {
109 &self.children
110 }
111
112 fn outline_disabled(&self) -> bool {
113 self.disabled
114 }
115}
116
117impl OutlineNode for TreeGridRow {
118 fn outline_id(&self) -> &str {
119 &self.id
120 }
121
122 fn outline_label(&self) -> &str {
123 self.cells.first().map_or("", String::as_str)
124 }
125
126 fn outline_children(&self) -> &[Self] {
127 &self.children
128 }
129
130 fn outline_disabled(&self) -> bool {
131 self.disabled
132 }
133}
134
135#[derive(Clone, Debug, PartialEq, Eq)]
137pub(crate) struct OutlineRow {
138 pub id: String,
139 pub label: String,
140 pub level: usize,
141 pub parent: Option<usize>,
142 pub has_children: bool,
143 pub expanded: bool,
144 pub disabled: bool,
145}
146
147fn outline_rows<N: OutlineNode>(roots: &[N], expanded: &[String]) -> Vec<OutlineRow> {
150 let mut rows = Vec::new();
151 let mut stack: Vec<(std::slice::Iter<'_, N>, usize, Option<usize>)> =
152 vec![(roots.iter(), 1, None)];
153
154 while let Some(top) = stack.last_mut() {
155 let (level, parent) = (top.1, top.2);
156
157 let Some(node) = top.0.next() else {
158 stack.pop();
159 continue;
160 };
161
162 let has_children = !node.outline_children().is_empty();
163 let is_expanded = has_children && expanded.iter().any(|id| id == node.outline_id());
164 let index = rows.len();
165
166 rows.push(OutlineRow {
167 id: node.outline_id().to_string(),
168 label: node.outline_label().to_string(),
169 level,
170 parent,
171 has_children,
172 expanded: is_expanded,
173 disabled: node.outline_disabled(),
174 });
175
176 if is_expanded {
177 stack.push((node.outline_children().iter(), level + 1, Some(index)));
178 }
179 }
180
181 rows
182}
183
184#[derive(Clone, Copy, Debug, PartialEq, Eq)]
186pub(crate) enum OutlineAction {
187 Focus(usize),
189 Expand(usize),
191 Collapse(usize),
193 Activate(usize),
195}
196
197fn first_char_lowercase(text: &str) -> Option<char> {
198 text.trim_start()
199 .chars()
200 .next()
201 .map(|c| c.to_lowercase().next().unwrap_or(c))
202}
203
204pub(crate) fn outline_key_action(
209 rows: &[OutlineRow],
210 current: usize,
211 key: &Key,
212) -> Option<OutlineAction> {
213 let len = rows.len();
214 let row = rows.get(current)?;
215
216 match key {
217 Key::ArrowDown => Some(OutlineAction::Focus((current + 1) % len)),
218 Key::ArrowUp => Some(OutlineAction::Focus((current + len - 1) % len)),
219 Key::Home => Some(OutlineAction::Focus(0)),
220 Key::End => Some(OutlineAction::Focus(len - 1)),
221 Key::ArrowRight if row.has_children && !row.expanded && !row.disabled => {
222 Some(OutlineAction::Expand(current))
223 }
224 Key::ArrowRight if row.expanded => rows
225 .get(current + 1)
226 .filter(|child| child.parent == Some(current))
227 .map(|_| OutlineAction::Focus(current + 1)),
228 Key::ArrowLeft if row.expanded && !row.disabled => Some(OutlineAction::Collapse(current)),
229 Key::ArrowLeft => row.parent.map(OutlineAction::Focus),
230 Key::Enter => Some(OutlineAction::Activate(current)),
231 Key::Character(text) if text == " " => Some(OutlineAction::Activate(current)),
232 Key::Character(text) => {
233 let mut chars = text.chars();
234 let wanted = chars.next()?.to_lowercase().next()?;
235
236 if chars.next().is_some() || wanted.is_whitespace() {
237 return None;
238 }
239
240 (1..len)
241 .map(|step| (current + step) % len)
242 .find(|index| first_char_lowercase(&rows[*index].label) == Some(wanted))
243 .map(OutlineAction::Focus)
244 }
245 _ => None,
246 }
247}
248
249#[derive(Clone)]
251struct OutlineView {
252 rows: Rc<[OutlineRow]>,
253 indexes: Rc<HashMap<String, usize>>,
254 expanded: Controllable<Vec<String>>,
255 selected_prop: Option<String>,
256 internal_selected: Signal<Option<String>>,
257 on_select: Option<EventHandler<String>>,
258 focused: Signal<Option<String>>,
259 mounted: Signal<HashMap<String, Rc<MountedData>>>,
260}
261
262impl OutlineView {
263 fn selected(&self) -> Option<String> {
264 self.selected_prop
265 .clone()
266 .or_else(|| self.internal_selected.read().clone())
267 }
268
269 fn tab_stop(&self) -> Option<String> {
271 let visible = |id: &String| self.indexes.contains_key(id);
272
273 self.focused
274 .read()
275 .clone()
276 .filter(visible)
277 .or_else(|| self.selected().filter(visible))
278 .or_else(|| self.rows.first().map(|row| row.id.clone()))
279 }
280
281 fn focus(&self, index: usize) {
282 let Some(row) = self.rows.get(index) else {
283 return;
284 };
285 let mut focused = self.focused;
286
287 focused.set(Some(row.id.clone()));
288 focus_element(self.mounted.peek().get(&row.id).cloned());
289 }
290
291 fn set_expanded(&self, id: &str, open: bool) {
292 let mut next = self.expanded.peek();
293 let present = next.iter().any(|entry| entry == id);
294
295 if open && !present {
296 next.push(id.to_string());
297 } else if !open && present {
298 next.retain(|entry| entry != id);
299 } else {
300 return;
301 }
302
303 self.expanded.set(next);
304 }
305
306 fn activate(&self, index: usize) {
307 let Some(row) = self.rows.get(index) else {
308 return;
309 };
310
311 if row.disabled {
312 return;
313 }
314
315 if self.selected_prop.is_none() {
316 let mut internal = self.internal_selected;
317 internal.set(Some(row.id.clone()));
318 }
319
320 if let Some(handler) = self.on_select {
321 handler.call(row.id.clone());
322 }
323
324 if row.has_children {
325 self.set_expanded(&row.id, !row.expanded);
326 }
327 }
328
329 fn keydown(&self, index: usize, event: &KeyboardEvent) {
330 let modifiers = event.modifiers();
331
332 if modifiers.ctrl() || modifiers.alt() || modifiers.meta() || event.is_composing() {
333 return;
334 }
335
336 let current = self
339 .focused
340 .peek()
341 .as_ref()
342 .and_then(|id| self.indexes.get(id).copied())
343 .unwrap_or(index);
344 let Some(action) = outline_key_action(&self.rows, current, &event.key()) else {
345 return;
346 };
347
348 event.prevent_default();
349
350 match action {
351 OutlineAction::Focus(next) => self.focus(next),
352 OutlineAction::Expand(next) => {
353 if let Some(row) = self.rows.get(next) {
354 self.set_expanded(&row.id, true);
355 }
356 }
357 OutlineAction::Collapse(next) => {
358 if let Some(row) = self.rows.get(next) {
359 self.set_expanded(&row.id, false);
360 }
361 }
362 OutlineAction::Activate(next) => self.activate(next),
363 }
364 }
365
366 fn item(&self, id: &str) -> Option<(usize, &OutlineRow)> {
368 let index = *self.indexes.get(id)?;
369 self.rows.get(index).map(|row| (index, row))
370 }
371}
372
373struct OutlineOptions {
374 expanded: Option<Vec<String>>,
375 default_expanded: Vec<String>,
376 on_expanded_change: Option<EventHandler<Vec<String>>>,
377 selected: Option<String>,
378 default_selected: Option<String>,
379 on_select: Option<EventHandler<String>>,
380}
381
382fn use_outline<N: OutlineNode>(roots: &[N], options: OutlineOptions) -> OutlineView {
383 let OutlineOptions {
384 expanded,
385 default_expanded,
386 on_expanded_change,
387 selected,
388 default_selected,
389 on_select,
390 } = options;
391 let expanded = use_controllable(expanded, || default_expanded, on_expanded_change);
392 let internal_selected = use_signal(|| default_selected);
393 let focused = use_signal(|| None::<String>);
394 let mounted = use_signal(HashMap::<String, Rc<MountedData>>::new);
395 let rows = outline_rows(roots, &expanded.get());
396 let indexes = rows
397 .iter()
398 .enumerate()
399 .map(|(index, row)| (row.id.clone(), index))
400 .collect();
401
402 OutlineView {
403 rows: Rc::from(rows),
404 indexes: Rc::new(indexes),
405 expanded,
406 selected_prop: selected,
407 internal_selected,
408 on_select,
409 focused,
410 mounted,
411 }
412}
413
414#[derive(Props, Clone, PartialEq)]
416pub struct TreeProps {
417 #[props(default)]
419 pub nodes: Vec<TreeNode>,
420 pub expanded: Option<Vec<String>>,
422 #[props(default)]
424 pub default_expanded: Vec<String>,
425 pub on_expanded_change: Option<EventHandler<Vec<String>>>,
427 #[props(into)]
429 pub selected: Option<String>,
430 #[props(into)]
432 pub default_selected: Option<String>,
433 pub on_select: Option<EventHandler<String>>,
435 #[props(default, into)]
437 pub glass: Glass,
438 #[props(default = "tree".to_string(), into)]
440 pub role: String,
441 #[props(into)]
443 pub class: Option<String>,
444 #[props(extends = GlobalAttributes, extends = div)]
446 pub attributes: Vec<Attribute>,
447 pub children: Element,
449}
450
451fn render_tree_nodes(nodes: &[TreeNode], view: &OutlineView, tab_stop: Option<&str>) -> Element {
452 rsx! {
453 for node in nodes {
454 {render_tree_node(node, view, tab_stop)}
455 }
456 }
457}
458
459fn render_tree_node(node: &TreeNode, view: &OutlineView, tab_stop: Option<&str>) -> Element {
460 let Some((index, row)) = view.item(&node.id) else {
461 return rsx! {};
462 };
463 let selected = view.selected().as_deref() == Some(row.id.as_str());
464 let (click_view, key_view, mut mounted) = (view.clone(), view.clone(), view.mounted);
465 let mount_id = row.id.clone();
466
467 rsx! {
468 div {
469 key: "{row.id}",
470 aria_disabled: row.disabled.then_some("true"),
471 aria_expanded: row.has_children.then_some(if row.expanded { "true" } else { "false" }),
472 aria_level: "{row.level}",
473 aria_selected: if selected { "true" } else { "false" },
474 "data-value": "{row.id}",
475 role: "treeitem",
476 tabindex: if tab_stop == Some(row.id.as_str()) { "0" } else { "-1" },
477 onclick: move |_| {
478 click_view.focus(index);
479 click_view.activate(index);
480 },
481 onkeydown: move |event| key_view.keydown(index, &event),
482 onmounted: move |event| {
483 mounted.write().insert(mount_id.clone(), event.data());
484 },
485 "{row.label}"
486 }
487 if row.expanded {
488 div { role: "group", {render_tree_nodes(&node.children, view, tab_stop)} }
489 }
490 }
491}
492
493#[component]
499pub fn Tree(props: TreeProps) -> Element {
500 let view = use_outline(
501 &props.nodes,
502 OutlineOptions {
503 expanded: props.expanded.clone(),
504 default_expanded: props.default_expanded.clone(),
505 on_expanded_change: props.on_expanded_change,
506 selected: props.selected.clone(),
507 default_selected: props.default_selected.clone(),
508 on_select: props.on_select,
509 },
510 );
511 let glass = props.glass.class("ui-tree");
512 let class = compose([Some("ui-tree"), glass.as_deref(), props.class.as_deref()]);
513 let tab_stop = view.tab_stop();
514
515 rsx! {
516 div { class, role: props.role, ..props.attributes,
517 {render_tree_nodes(&props.nodes, &view, tab_stop.as_deref())}
518 {props.children}
519 }
520 }
521}
522
523#[derive(Props, Clone, PartialEq)]
525pub struct TreeGridProps {
526 #[props(default)]
528 pub columns: Vec<String>,
529 #[props(default)]
531 pub rows: Vec<TreeGridRow>,
532 pub expanded: Option<Vec<String>>,
534 #[props(default)]
536 pub default_expanded: Vec<String>,
537 pub on_expanded_change: Option<EventHandler<Vec<String>>>,
539 #[props(into)]
541 pub selected: Option<String>,
542 #[props(into)]
544 pub default_selected: Option<String>,
545 pub on_select: Option<EventHandler<String>>,
547 #[props(default, into)]
549 pub glass: Glass,
550 #[props(default = "treegrid".to_string(), into)]
552 pub role: String,
553 #[props(into)]
555 pub class: Option<String>,
556 #[props(extends = GlobalAttributes, extends = div)]
558 pub attributes: Vec<Attribute>,
559 pub children: Element,
561}
562
563fn render_grid_rows(rows: &[TreeGridRow], view: &OutlineView, tab_stop: Option<&str>) -> Element {
564 rsx! {
565 for row in rows {
566 {render_grid_row(row, view, tab_stop)}
567 }
568 }
569}
570
571fn render_grid_row(node: &TreeGridRow, view: &OutlineView, tab_stop: Option<&str>) -> Element {
572 let Some((index, row)) = view.item(&node.id) else {
573 return rsx! {};
574 };
575 let selected = view.selected().as_deref() == Some(row.id.as_str());
576 let (click_view, key_view, mut mounted) = (view.clone(), view.clone(), view.mounted);
577 let mount_id = row.id.clone();
578
579 rsx! {
580 div {
581 key: "{row.id}",
582 aria_disabled: row.disabled.then_some("true"),
583 aria_expanded: row.has_children.then_some(if row.expanded { "true" } else { "false" }),
584 aria_level: "{row.level}",
585 aria_selected: if selected { "true" } else { "false" },
586 "data-value": "{row.id}",
587 role: "row",
588 tabindex: if tab_stop == Some(row.id.as_str()) { "0" } else { "-1" },
589 onclick: move |_| {
590 click_view.focus(index);
591 click_view.activate(index);
592 },
593 onkeydown: move |event| key_view.keydown(index, &event),
594 onmounted: move |event| {
595 mounted.write().insert(mount_id.clone(), event.data());
596 },
597 for (column, cell) in node.cells.iter().enumerate() {
598 span { key: "{column}", role: "gridcell", "{cell}" }
599 }
600 }
601 if row.expanded {
602 {render_grid_rows(&node.children, view, tab_stop)}
603 }
604 }
605}
606
607#[component]
612pub fn TreeGrid(props: TreeGridProps) -> Element {
613 let view = use_outline(
614 &props.rows,
615 OutlineOptions {
616 expanded: props.expanded.clone(),
617 default_expanded: props.default_expanded.clone(),
618 on_expanded_change: props.on_expanded_change,
619 selected: props.selected.clone(),
620 default_selected: props.default_selected.clone(),
621 on_select: props.on_select,
622 },
623 );
624 let glass = props.glass.class("ui-tree-grid");
625 let class = compose([
626 Some("ui-tree-grid"),
627 glass.as_deref(),
628 props.class.as_deref(),
629 ]);
630 let tab_stop = view.tab_stop();
631
632 rsx! {
633 div { class, role: props.role, ..props.attributes,
634 if !props.columns.is_empty() {
635 div { role: "row",
636 for (column, title) in props.columns.iter().enumerate() {
637 span { key: "{column}", role: "columnheader", "{title}" }
638 }
639 }
640 }
641 {render_grid_rows(&props.rows, &view, tab_stop.as_deref())}
642 {props.children}
643 }
644 }
645}
646
647#[cfg(test)]
648mod tests {
649 use super::{Key, OutlineAction, TreeNode, outline_key_action, outline_rows};
650
651 fn sample() -> Vec<TreeNode> {
652 vec![
653 TreeNode::new("src", "src").with_children(vec![
654 TreeNode::new("components", "components")
655 .with_children(vec![TreeNode::new("button", "button.rs")]),
656 TreeNode::new("index", "index.ts"),
657 ]),
658 TreeNode::new("tests", "tests").with_children(vec![TreeNode::new("unit", "unit.rs")]),
659 TreeNode::new("package", "package.json"),
660 ]
661 }
662
663 #[test]
664 fn collapsed_branches_hide_their_descendants() {
665 let rows = outline_rows(&sample(), &["src".to_string()]);
666 let ids: Vec<&str> = rows.iter().map(|row| row.id.as_str()).collect();
667
668 assert_eq!(ids, ["src", "components", "index", "tests", "package"]);
669 assert_eq!(rows[1].level, 2);
670 assert_eq!(rows[1].parent, Some(0));
671 assert!(rows[1].has_children && !rows[1].expanded);
672 assert!(rows[0].expanded);
673 }
674
675 #[test]
676 fn arrow_keys_follow_the_tree_pattern() {
677 let rows = outline_rows(&sample(), &["src".to_string()]);
678
679 assert_eq!(
680 outline_key_action(&rows, 0, &Key::ArrowDown),
681 Some(OutlineAction::Focus(1))
682 );
683 assert_eq!(
684 outline_key_action(&rows, 4, &Key::ArrowDown),
685 Some(OutlineAction::Focus(0))
686 );
687 assert_eq!(
688 outline_key_action(&rows, 0, &Key::ArrowUp),
689 Some(OutlineAction::Focus(4))
690 );
691 assert_eq!(
692 outline_key_action(&rows, 2, &Key::End),
693 Some(OutlineAction::Focus(4))
694 );
695 assert_eq!(
696 outline_key_action(&rows, 2, &Key::Home),
697 Some(OutlineAction::Focus(0))
698 );
699 assert_eq!(
701 outline_key_action(&rows, 0, &Key::ArrowRight),
702 Some(OutlineAction::Focus(1))
703 );
704 assert_eq!(
705 outline_key_action(&rows, 1, &Key::ArrowRight),
706 Some(OutlineAction::Expand(1))
707 );
708 assert_eq!(outline_key_action(&rows, 2, &Key::ArrowRight), None);
709 assert_eq!(
711 outline_key_action(&rows, 0, &Key::ArrowLeft),
712 Some(OutlineAction::Collapse(0))
713 );
714 assert_eq!(
715 outline_key_action(&rows, 2, &Key::ArrowLeft),
716 Some(OutlineAction::Focus(0))
717 );
718 assert_eq!(outline_key_action(&rows, 4, &Key::ArrowLeft), None);
719 assert_eq!(
720 outline_key_action(&rows, 3, &Key::Enter),
721 Some(OutlineAction::Activate(3))
722 );
723 assert_eq!(
724 outline_key_action(&rows, 3, &Key::Character(" ".into())),
725 Some(OutlineAction::Activate(3))
726 );
727 }
728
729 #[test]
730 fn typing_jumps_to_the_next_matching_label() {
731 let rows = outline_rows(&sample(), &["src".to_string()]);
732
733 assert_eq!(
734 outline_key_action(&rows, 0, &Key::Character("T".into())),
735 Some(OutlineAction::Focus(3))
736 );
737 assert_eq!(
738 outline_key_action(&rows, 0, &Key::Character("i".into())),
739 Some(OutlineAction::Focus(2))
740 );
741 assert_eq!(
742 outline_key_action(&rows, 0, &Key::Character("z".into())),
743 None
744 );
745 assert_eq!(
746 outline_key_action(&rows, 0, &Key::Character("ab".into())),
747 None
748 );
749 }
750
751 #[test]
752 fn disabled_branches_do_not_toggle() {
753 let nodes = vec![
754 TreeNode::new("a", "a")
755 .with_children(vec![TreeNode::new("b", "b")])
756 .disabled(),
757 ];
758 let rows = outline_rows(&nodes, &[]);
759
760 assert_eq!(outline_key_action(&rows, 0, &Key::ArrowRight), None);
761 }
762
763 #[test]
764 fn deep_trees_flatten_without_recursion() {
765 let mut node = TreeNode::new("leaf", "leaf");
766 let mut expanded = Vec::new();
767
768 for depth in 0..20_000 {
769 let id = format!("n{depth}");
770 expanded.push(id.clone());
771 node = TreeNode::new(id, "n").with_children(vec![node]);
772 }
773
774 let rows = outline_rows(
775 std::slice::from_ref(&node),
776 &expanded[expanded.len() - 50..],
777 );
778 assert_eq!(rows.len(), 51);
779 assert_eq!(rows[50].level, 51);
780
781 let mut stack = vec![node];
783 while let Some(mut current) = stack.pop() {
784 stack.append(&mut current.children);
785 }
786 }
787}