use crate::{app::events::KeyboardEvent, node::Node};
#[derive(Clone, Copy)]
pub(super) enum KeyPhase {
Down,
Up,
}
pub(super) fn fire_key(root: &Node, evt: &mut KeyboardEvent, focus: Option<&[usize]>, phase: KeyPhase) {
let first = focus.and_then(|focus| first_on(root, focus).map(|depth| focus.split_at(depth)));
if let Some((to, rest)) = first {
let node = to
.iter()
.try_fold(root, |node, index| node.children().get(*index))
.expect("the path was found in the tree");
if fire(node, evt, Some(rest), None, phase) {
return;
}
}
fire(root, evt, focus, first.map(|(to, _)| to), phase);
}
fn first_on(root: &Node, focus: &[usize]) -> Option<usize> {
if root.keys_first() {
return Some(0);
}
let mut node = root;
for (depth, index) in focus.iter().enumerate() {
node = node.children().get(*index)?;
if node.keys_first() {
return Some(depth + 1);
}
}
None
}
fn through(path: Option<&[usize]>, index: usize) -> Option<&[usize]> {
let (first, rest) = path?.split_first()?;
(*first == index).then_some(rest)
}
fn fire(
node: &Node,
evt: &mut KeyboardEvent,
focus: Option<&[usize]>,
skip: Option<&[usize]>,
phase: KeyPhase,
) -> bool {
if skip.is_some_and(<[usize]>::is_empty) {
return false;
}
evt.target_id = node.node_id();
evt.focus_within = focus.is_some();
let handlers = match phase {
KeyPhase::Down => &node.events.on_key_down,
KeyPhase::Up => &node.events.on_key_up,
};
for handler in handlers {
handler.call(evt);
if evt.immediate_propagation_stopped() {
return true;
}
}
if evt.propagation_stopped() {
return true;
}
for (index, child) in node.children().iter().enumerate() {
if fire(child, evt, through(focus, index), through(skip, index), phase) {
return true;
}
}
false
}