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;
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct TreeNode {
pub id: String,
pub label: String,
pub children: Vec<TreeNode>,
pub disabled: bool,
}
impl TreeNode {
pub fn new(id: impl Into<String>, label: impl Into<String>) -> Self {
Self {
id: id.into(),
label: label.into(),
..Self::default()
}
}
#[must_use]
pub fn with_children(mut self, children: Vec<TreeNode>) -> Self {
self.children = children;
self
}
#[must_use]
pub fn disabled(mut self) -> Self {
self.disabled = true;
self
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct TreeGridRow {
pub id: String,
pub cells: Vec<String>,
pub children: Vec<TreeGridRow>,
pub disabled: bool,
}
impl TreeGridRow {
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()
}
}
#[must_use]
pub fn with_children(mut self, children: Vec<TreeGridRow>) -> Self {
self.children = children;
self
}
#[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
}
}
#[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,
}
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
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum OutlineAction {
Focus(usize),
Expand(usize),
Collapse(usize),
Activate(usize),
}
fn first_char_lowercase(text: &str) -> Option<char> {
text.trim_start()
.chars()
.next()
.map(|c| c.to_lowercase().next().unwrap_or(c))
}
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,
}
}
#[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())
}
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;
}
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),
}
}
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,
}
}
#[derive(Props, Clone, PartialEq)]
pub struct TreeProps {
#[props(default)]
pub nodes: Vec<TreeNode>,
pub expanded: Option<Vec<String>>,
#[props(default)]
pub default_expanded: Vec<String>,
pub on_expanded_change: Option<EventHandler<Vec<String>>>,
#[props(into)]
pub selected: Option<String>,
#[props(into)]
pub default_selected: Option<String>,
pub on_select: Option<EventHandler<String>>,
#[props(default, into)]
pub glass: Glass,
#[props(default = "tree".to_string(), into)]
pub role: String,
#[props(into)]
pub class: Option<String>,
#[props(extends = GlobalAttributes, extends = div)]
pub attributes: Vec<Attribute>,
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)} }
}
}
}
#[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}
}
}
}
#[derive(Props, Clone, PartialEq)]
pub struct TreeGridProps {
#[props(default)]
pub columns: Vec<String>,
#[props(default)]
pub rows: Vec<TreeGridRow>,
pub expanded: Option<Vec<String>>,
#[props(default)]
pub default_expanded: Vec<String>,
pub on_expanded_change: Option<EventHandler<Vec<String>>>,
#[props(into)]
pub selected: Option<String>,
#[props(into)]
pub default_selected: Option<String>,
pub on_select: Option<EventHandler<String>>,
#[props(default, into)]
pub glass: Glass,
#[props(default = "treegrid".to_string(), into)]
pub role: String,
#[props(into)]
pub class: Option<String>,
#[props(extends = GlobalAttributes, extends = div)]
pub attributes: Vec<Attribute>,
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)}
}
}
}
#[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))
);
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);
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);
let mut stack = vec![node];
while let Some(mut current) = stack.pop() {
stack.append(&mut current.children);
}
}
}