use super::Entry;
use crate::accessibility::{ids, AccessNode};
use crate::{context::HitRegion, Id};
use std::collections::{HashMap, HashSet};
pub(super) struct Hits<'a> {
focusable: HashMap<Id, bool>,
clickable: &'a HashSet<Id>,
}
impl<'a> Hits<'a> {
pub(super) fn new(published: &[HitRegion], clickable: &'a HashSet<Id>) -> Self {
let focusable = published
.iter()
.map(|hit| (hit.id, hit.action.focusable()))
.collect();
Self {
focusable,
clickable,
}
}
}
pub(super) struct Identity {
pub runs: Vec<u64>,
pub by_id: HashMap<Id, u64>,
pub focus_owner: HashMap<Id, u64>,
}
pub(super) fn assign(nodes: &[AccessNode], entries: &mut [Entry], hits: &Hits) -> Identity {
let mut used: HashSet<u64> = HashSet::with_capacity(nodes.len() + 4);
used.extend([ids::ROOT, ids::ANNOUNCE_POLITE, ids::ANNOUNCE_ASSERTIVE]);
let mut out = Identity {
runs: Vec::new(),
by_id: HashMap::with_capacity(nodes.len()),
focus_owner: HashMap::new(),
};
for (node, entry) in nodes.iter().zip(entries.iter_mut()) {
if !entry.alive {
continue;
}
let nid = ids::unique(ids::node(node.id), &mut used);
entry.nid = nid;
out.by_id.entry(node.id).or_insert(nid);
let focus = node.focus.unwrap_or(node.id);
let focusable = hits.focusable.get(&focus).copied().unwrap_or_default();
if focusable && !out.focus_owner.contains_key(&focus) {
entry.focusable = true;
out.focus_owner.insert(focus, nid);
}
entry.clickable = node.click.is_some_and(|id| hits.clickable.contains(&id));
let start = out.runs.len() as u32;
let runs = node.more.as_ref().and_then(|more| more.text.as_ref());
for run in 0..runs.map_or(0, |text| text.0.runs.len()) {
out.runs.push(ids::unique(ids::run(nid, run), &mut used));
}
entry.runs = (start, out.runs.len() as u32);
}
out
}
pub(super) fn relate(nodes: &[AccessNode], entries: &mut [Entry], by_id: &HashMap<Id, u64>) {
for (node, entry) in nodes.iter().zip(entries.iter_mut()) {
let Some(more) = node.more.as_ref().filter(|_| entry.alive) else {
continue;
};
let targets = more
.labelled_by
.iter()
.chain(&more.described_by)
.chain(&more.controls)
.chain(&more.error_message)
.chain(&more.active_descendant);
entry.links = targets.fold(0, |hash, id| {
fold(hash, by_id.get(id).copied().unwrap_or(0))
});
}
}
fn fold(hash: u64, value: u64) -> u64 {
(hash ^ value)
.wrapping_mul(0x0000_0100_0000_01b3)
.rotate_left(17)
}