Skip to main content

euv_ui/component/tree/view/
fn.rs

1use super::*;
2
3/// A hierarchical tree with selectable rows and collapsible branches.
4///
5/// Renders a `c_euv_tree` column holding one `c_euv_tree_node` per node.
6/// Each node holds a clickable row — `c_euv_tree_node_row`, or
7/// `c_euv_tree_node_row_active` for the selected node — carrying a toggle
8/// marker and a `c_euv_tree_node_label`. The marker is
9/// `c_euv_tree_node_toggle` while collapsed, `c_euv_tree_node_toggle_open`
10/// while expanded, and `c_euv_tree_node_toggle_leaf` for a node without
11/// children, which renders it invisible so the labels stay aligned.
12///
13/// The children of a branch stay mounted: the branch container carries
14/// `c_euv_tree_node_children` plus `c_euv_tree_node_children_open` or
15/// `c_euv_tree_node_children_closed`, so collapsing a branch is a class
16/// swap and never a reactive `if` that would unmount the subtree.
17///
18/// The selection is read once per render and handed down the recursion,
19/// and the expansion set is read once per render as well, so a deep tree
20/// never re-reads a signal per node.
21///
22/// Tree items use the ARIA tree pattern and a single visible roving tab stop;
23/// arrow keys navigate and expand or collapse branches.
24///
25/// # Arguments
26///
27/// - `VirtualNode<EuvTreeProps>` - The props node containing the nodes, the selection and the expansion seed.
28///
29/// # Returns
30///
31/// - `VirtualNode` - The tree virtual DOM tree.
32#[component]
33pub fn euv_tree(node: VirtualNode<EuvTreeProps>) -> VirtualNode {
34    let EuvTreeProps {
35        nodes,
36        selected,
37        on_select,
38        default_expanded,
39    }: EuvTreeProps = node.try_get_props().unwrap_or_default();
40    let expanded: Signal<Vec<String>> = use_euv_tree_expanded(nodes.as_slice(), default_expanded);
41    let selected_value: String = selected.get();
42    let expanded_values: Vec<String> = expanded.get();
43    let visible_values: Vec<String> = visible_tree_node_values(nodes.as_slice(), &expanded_values);
44    let roving_value: String = if visible_values
45        .iter()
46        .any(|value: &String| value == &selected_value)
47    {
48        selected_value.clone()
49    } else {
50        visible_values.first().cloned().unwrap_or_default()
51    };
52    let context: TreeViewContext<'_> = TreeViewContext {
53        selected,
54        selected_value: &selected_value,
55        roving_value: &roving_value,
56        expanded,
57        expanded_values: &expanded_values,
58        on_select,
59    };
60    let tree_nodes: Vec<VirtualNode> = nodes
61        .into_iter()
62        .map(|tree_node: EuvTreeNode| tree_node_view(tree_node, &context, 1, true))
63        .collect();
64    html! {
65        div {
66            class: c_euv_tree()
67            "data-slot": TREE_SLOT
68            role: "tree"
69            "aria-label": TREE_ARIA_LABEL
70            "aria-multiselectable": "false"
71            tree_nodes
72        }
73    }
74}
75
76/// Obtains the expansion state handle registered against the current hook
77/// context slot.
78///
79/// Behaves like [`HookContext::use_hook`] — the same handle is returned on
80/// every render at the same hook index, so the expanded set survives
81/// re-renders. The seed is built once, when the slot is first written:
82/// an empty set when the tree starts collapsed, and the value of every
83/// node in the tree when it starts expanded.
84///
85/// # Arguments
86///
87/// - `&[EuvTreeNode]` - The root nodes used to seed the expanded set.
88/// - `bool` - Whether the tree starts with every node expanded.
89///
90/// # Returns
91///
92/// - `Signal<Vec<String>>` - The signal holding the expanded node values.
93pub fn use_euv_tree_expanded(nodes: &[EuvTreeNode], default_expanded: bool) -> Signal<Vec<String>> {
94    let seed: Vec<String> = if default_expanded {
95        tree_node_values(nodes)
96    } else {
97        Vec::new()
98    };
99    HookContext::use_hook(move || Signal::create(seed))
100}
101
102/// Collects the value of every node in a tree, depth first.
103///
104/// # Arguments
105///
106/// - `&[EuvTreeNode]` - The nodes to walk.
107///
108/// # Returns
109///
110/// - `Vec<String>` - The value of every node, parents before children.
111fn tree_node_values(nodes: &[EuvTreeNode]) -> Vec<String> {
112    let mut values: Vec<String> = Vec::with_capacity(nodes.len());
113    collect_tree_node_values(nodes, &mut values);
114    values
115}
116
117/// Appends the value of every node in a tree to an accumulator.
118///
119/// # Arguments
120///
121/// - `&[EuvTreeNode]` - The nodes to walk.
122/// - `&mut Vec<String>` - The accumulator the node values are appended to.
123fn collect_tree_node_values(nodes: &[EuvTreeNode], values: &mut Vec<String>) {
124    for node in nodes {
125        values.push(node.value.to_string());
126        collect_tree_node_values(&node.children, values);
127    }
128}
129
130/// Collects values of the nodes visible with the current expanded set.
131///
132/// # Arguments
133///
134/// - `&[EuvTreeNode]` - The root nodes to traverse.
135/// - `&[String]` - The values of expanded branches.
136///
137/// # Returns
138///
139/// - `Vec<String>` - The visible node values in depth-first order.
140fn visible_tree_node_values(nodes: &[EuvTreeNode], expanded_values: &[String]) -> Vec<String> {
141    let mut values: Vec<String> = Vec::new();
142    collect_visible_tree_node_values(nodes, expanded_values, &mut values);
143    values
144}
145
146/// Appends visible node values to an accumulator.
147///
148/// # Arguments
149///
150/// - `&[EuvTreeNode]` - The nodes to traverse.
151/// - `&[String]` - The values of expanded branches.
152/// - `&mut Vec<String>` - The accumulator for visible node values.
153fn collect_visible_tree_node_values(
154    nodes: &[EuvTreeNode],
155    expanded_values: &[String],
156    values: &mut Vec<String>,
157) {
158    for node in nodes {
159        values.push(node.value.to_string());
160        let is_expanded: bool = expanded_values
161            .iter()
162            .any(|expanded_value: &String| expanded_value.as_str() == node.value);
163        if is_expanded {
164            collect_visible_tree_node_values(&node.children, expanded_values, values);
165        }
166    }
167}
168
169/// Renders one node: its row, and the container holding its children.
170///
171/// The child list is built with a single `.map(...).collect()` before the
172/// `html!` block: a `for` loop inside `html!` over a local vector fails
173/// the `'static` bound the reactive attribute closure needs.
174///
175/// # Arguments
176///
177/// - `EuvTreeNode` - The node to render, consumed.
178/// - `&TreeViewContext<'_>` - The shared state read once for this render.
179/// - `usize` - The one-based nesting level.
180/// - `bool` - Whether the node is visible through its expanded ancestors.
181///
182/// # Returns
183///
184/// - `VirtualNode` - The tree node virtual DOM tree.
185fn tree_node_view(
186    node: EuvTreeNode,
187    context: &TreeViewContext<'_>,
188    level: usize,
189    is_visible: bool,
190) -> VirtualNode {
191    let value: &'static str = node.value;
192    let label: &'static str = node.label;
193    let has_children: bool = !node.children.is_empty();
194    let is_selected: bool = value == context.selected_value;
195    let is_expanded: bool = has_children
196        && context
197            .expanded_values
198            .iter()
199            .any(|entry: &String| entry == value);
200    let is_roving: bool = value == context.roving_value;
201    let aria_level: String = level.to_string();
202    let tabindex: &str = if is_roving { "0" } else { "-1" };
203    let aria_selected: &str = if is_selected {
204        TREE_ATTR_TRUE
205    } else {
206        TREE_ATTR_FALSE
207    };
208    let aria_expanded: &str = if is_expanded {
209        TREE_ATTR_TRUE
210    } else {
211        TREE_ATTR_FALSE
212    };
213    let on_keydown: Option<Rc<dyn Fn(Event)>> = tree_item_keydown(
214        value,
215        level,
216        has_children,
217        is_expanded,
218        context.selected,
219        context.expanded,
220        context.on_select.clone(),
221    );
222    let child_nodes: Vec<VirtualNode> = node
223        .children
224        .into_iter()
225        .map(|child: EuvTreeNode| {
226            tree_node_view(child, context, level + 1, is_visible && is_expanded)
227        })
228        .collect();
229    html! {
230        div {
231            key: value
232            "data-slot": TREE_ITEM_SLOT
233            "data-value": value
234            "data-visible": if is_visible {
235                TREE_ATTR_TRUE
236            } else {
237                TREE_ATTR_FALSE
238            }
239            role: "treeitem"
240            "aria-label": label
241            "aria-level": aria_level
242            "aria-selected": aria_selected
243            "aria-expanded": aria_expanded
244            tabindex: tabindex
245            class: c_euv_tree_node()
246            onkeydown: on_keydown
247            div {
248                "data-slot": TREE_ROW_SLOT
249                class: if is_selected {
250                    c_euv_tree_node_row_active()
251                } else {
252                    c_euv_tree_node_row()
253                }
254                onclick: on_tree_select(context.selected, context.on_select.clone(), value)
255                span {
256                    "data-slot": TREE_TOGGLE_SLOT
257                    "aria-hidden": "true"
258                    class: if !has_children {
259                        c_euv_tree_node_toggle_leaf()
260                    } else if is_expanded {
261                        c_euv_tree_node_toggle_open()
262                    } else {
263                        c_euv_tree_node_toggle()
264                    }
265                    onclick: on_tree_toggle(context.expanded, value)
266                    "▸"
267                }
268                span {
269                    class: c_euv_tree_node_label()
270                    label
271                }
272            }
273            if has_children {
274                div {
275                    "data-slot": TREE_GROUP_SLOT
276                    role: TREE_GROUP_ROLE
277                    class: c_euv_tree_node_children()
278                    class: if is_expanded {
279                        c_euv_tree_node_children_open()
280                    } else {
281                        c_euv_tree_node_children_closed()
282                    }
283                    child_nodes
284                }
285            }
286        }
287    }
288}
289
290/// Builds the keyboard handler for a focused tree item.
291///
292/// Arrow keys move through visible items and expand or collapse branches;
293/// Home and End move to the visible bounds, while Enter and Space select.
294///
295/// # Arguments
296///
297/// - `&'static str` - The item's stable value.
298/// - `usize` - The item's one-based nesting level.
299/// - `bool` - Whether the item has children.
300/// - `bool` - Whether the item is expanded.
301/// - `Signal<String>` - The selected-value signal.
302/// - `Signal<Vec<String>>` - The expanded-values signal.
303/// - `Option<Rc<dyn Fn(&'static str)>>` - The select callback.
304///
305/// # Returns
306///
307/// - `Option<Rc<dyn Fn(Event)>>` - The keyboard handler.
308fn tree_item_keydown(
309    value: &'static str,
310    level: usize,
311    has_children: bool,
312    is_expanded: bool,
313    selected: Signal<String>,
314    expanded: Signal<Vec<String>>,
315    on_select: Option<Rc<dyn Fn(&'static str)>>,
316) -> Option<Rc<dyn Fn(Event)>> {
317    Some(Rc::new(move |event: Event| {
318        let Ok(keyboard_event) = event.dyn_into::<KeyboardEvent>() else {
319            return;
320        };
321        let key: String = keyboard_event.key();
322        let Some(target) = keyboard_event
323            .target()
324            .and_then(|target: EventTarget| target.dyn_into::<Element>().ok())
325        else {
326            return;
327        };
328        let Some(root) = target.closest(TREE_ROOT_SELECTOR).ok().flatten() else {
329            return;
330        };
331        let Some(current) = target
332            .closest(TREE_ITEM_SELECTOR)
333            .ok()
334            .flatten()
335            .and_then(|item: Element| item.dyn_into::<HtmlElement>().ok())
336        else {
337            return;
338        };
339        let Ok(nodes) = root.query_selector_all(TREE_ITEM_SELECTOR) else {
340            return;
341        };
342        let mut items: Vec<HtmlElement> = Vec::new();
343        for index in 0..nodes.length() {
344            let Some(node) = nodes.item(index) else {
345                continue;
346            };
347            let Ok(item) = node.dyn_into::<HtmlElement>() else {
348                continue;
349            };
350            if item.get_attribute(TREE_VISIBLE_ATTRIBUTE).as_deref() == Some(TREE_VISIBLE_VALUE) {
351                items.push(item);
352            }
353        }
354        let Some(current_index) = items.iter().position(|item: &HtmlElement| item == &current)
355        else {
356            return;
357        };
358        if key == TREE_KEY_ARROW_DOWN
359            || key == TREE_KEY_ARROW_UP
360            || key == TREE_KEY_HOME
361            || key == TREE_KEY_END
362        {
363            let next_index: usize = if key == TREE_KEY_ARROW_DOWN {
364                (current_index + 1).min(items.len() - 1)
365            } else if key == TREE_KEY_ARROW_UP {
366                current_index.saturating_sub(1)
367            } else if key == TREE_KEY_HOME {
368                0
369            } else {
370                items.len() - 1
371            };
372            keyboard_event.prevent_default();
373            if next_index != current_index
374                && let Some(item) = items.get(next_index)
375            {
376                focus_tree_item(item);
377            }
378            return;
379        }
380        if key == TREE_KEY_ENTER || key == TREE_KEY_SPACE {
381            keyboard_event.prevent_default();
382            select_tree_node(selected, on_select.clone(), value);
383            return;
384        }
385        if key == TREE_KEY_ARROW_RIGHT && has_children {
386            keyboard_event.prevent_default();
387            if !is_expanded {
388                let mut values: Vec<String> = expanded.get();
389                toggle_expanded_value(&mut values, value);
390                expanded.set(values);
391                return;
392            }
393            if let Some(item) = items.get(current_index + 1) {
394                let next_level: Option<usize> = item
395                    .get_attribute("aria-level")
396                    .and_then(|value: String| value.parse::<usize>().ok());
397                if next_level == Some(level + 1) {
398                    focus_tree_item(item);
399                }
400            }
401            return;
402        }
403        if key == TREE_KEY_ARROW_LEFT {
404            if has_children && is_expanded {
405                keyboard_event.prevent_default();
406                let mut values: Vec<String> = expanded.get();
407                toggle_expanded_value(&mut values, value);
408                expanded.set(values);
409                return;
410            }
411            let Some(group) = current.closest(TREE_GROUP_SELECTOR).ok().flatten() else {
412                return;
413            };
414            let Some(parent) = group
415                .parent_element()
416                .and_then(|item: Element| item.dyn_into::<HtmlElement>().ok())
417            else {
418                return;
419            };
420            keyboard_event.prevent_default();
421            focus_tree_item(&parent);
422        }
423    }))
424}
425
426/// Moves focus to a tree item and selects it through its rendered row.
427///
428/// # Arguments
429///
430/// - `&HtmlElement` - The tree item to focus and select.
431fn focus_tree_item(item: &HtmlElement) {
432    let _: Result<(), JsValue> = item.focus();
433    if let Ok(Some(row)) = item.query_selector(TREE_ROW_SELECTOR)
434        && let Ok(row) = row.dyn_into::<HtmlElement>()
435    {
436        row.click();
437    }
438}
439
440/// Selects a node and reports the selection to the caller.
441///
442/// The node's value is written into the caller-owned `selected` signal and
443/// the `on_select` callback is called with it, so a caller can react to
444/// the selection without subscribing to the signal itself.
445///
446/// # Arguments
447///
448/// - `Signal<String>` - The selected-value signal.
449/// - `Option<Rc<dyn Fn(&'static str)>>` - The select callback.
450/// - `&'static str` - The selected node's value.
451pub fn select_tree_node(
452    selected: Signal<String>,
453    on_select: Option<Rc<dyn Fn(&'static str)>>,
454    value: &'static str,
455) {
456    selected.set(value.to_string());
457    if let Some(callback) = &on_select {
458        callback(value);
459    }
460}
461
462/// Adds a node's value to the expanded set, or removes it when it is there.
463///
464/// # Arguments
465///
466/// - `&mut Vec<String>` - The expanded values, mutated in place.
467/// - `&str` - The toggled node's value.
468pub fn toggle_expanded_value(values: &mut Vec<String>, value: &str) {
469    if let Some(index) = values.iter().position(|entry: &String| entry == value) {
470        values.remove(index);
471    } else {
472        values.push(value.to_string());
473    }
474}
475
476/// Builds the click handler that selects a node.
477///
478/// # Arguments
479///
480/// - `Signal<String>` - The selected-value signal.
481/// - `Option<Rc<dyn Fn(&'static str)>>` - The select callback.
482/// - `&'static str` - The clicked node's value.
483///
484/// # Returns
485///
486/// - `Option<Rc<dyn Fn(Event)>>` - The click handler.
487fn on_tree_select(
488    selected: Signal<String>,
489    on_select: Option<Rc<dyn Fn(&'static str)>>,
490    value: &'static str,
491) -> Option<Rc<dyn Fn(Event)>> {
492    Some(Rc::new(move |_: Event| {
493        select_tree_node(selected, on_select.clone(), value);
494    }))
495}
496
497/// Builds the click handler that expands or collapses a branch.
498///
499/// The event is stopped so the click does not bubble into the enclosing
500/// row, whose handler would otherwise select the node as well: the toggle
501/// only ever folds a branch, it never changes the selection.
502///
503/// # Arguments
504///
505/// - `Signal<Vec<String>>` - The expanded-values signal.
506/// - `&'static str` - The toggled node's value.
507///
508/// # Returns
509///
510/// - `Option<Rc<dyn Fn(Event)>>` - The click handler.
511fn on_tree_toggle(expanded: Signal<Vec<String>>, value: &'static str) -> Option<Rc<dyn Fn(Event)>> {
512    Some(Rc::new(move |event: Event| {
513        event.stop_propagation();
514        let mut values: Vec<String> = expanded.get();
515        toggle_expanded_value(&mut values, value);
516        expanded.set(values);
517    }))
518}