use super::refs::Refs;
use rho_browser::cdp::accessibility::AxNode;
use rho_browser::cdp::dom_snapshot::DocumentSnapshot;
use rho_browser::cdp::{AxNodeId, BackendNodeId};
use std::collections::HashMap;
use std::fmt::Write as _;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum Filter {
Visible,
Interactive,
All,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) struct Read {
pub(super) filter: Filter,
pub(super) depth: usize,
pub(super) start: Option<BackendNodeId>,
}
#[derive(Debug, Clone, PartialEq)]
pub(super) struct View {
boxes: HashMap<BackendNodeId, Rect>,
viewport: Rect,
}
#[derive(Debug, Clone, Copy, PartialEq)]
struct Rect {
x: f64,
y: f64,
width: f64,
height: f64,
}
impl Rect {
fn overlaps(&self, other: &Rect) -> bool {
self.width > 0.0
&& self.height > 0.0
&& self.x < other.x + other.width
&& other.x < self.x + self.width
&& self.y < other.y + other.height
&& other.y < self.y + self.height
}
}
impl View {
pub(super) fn of(document: &DocumentSnapshot, width: u32, height: u32) -> Self {
let nodes = &document.nodes.backend_node_id;
let boxes = document
.layout
.node_index
.iter()
.zip(&document.layout.bounds)
.filter_map(|(&index, &[x, y, width, height])| {
Some((
*nodes.get(index)?,
Rect {
x,
y,
width,
height,
},
))
})
.collect();
Self {
boxes,
viewport: Rect {
x: document.scroll_offset_x,
y: document.scroll_offset_y,
width: f64::from(width),
height: f64::from(height),
},
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) struct Rendered {
pub(super) text: String,
pub(super) cut_at_depth: bool,
}
pub(super) fn render(
tree: &[AxNode],
view: Option<&View>,
read: &Read,
refs: &mut Refs,
) -> Option<Rendered> {
let page = Page::new(tree);
let start = match read.start {
Some(node) => *page.by_dom.get(&node)?,
None => 0,
};
let in_view = match (read.filter, view) {
(Filter::All, _) | (_, None) => None,
(Filter::Visible | Filter::Interactive, Some(view)) => Some(page.in_view(view)),
};
let mut out = Out::default();
let mut stack = vec![Visit {
index: start,
depth: 0,
element_above: None,
}];
while let Some(visit) = stack.pop() {
let Visit {
index,
depth,
element_above,
} = visit;
if in_view.as_ref().is_some_and(|in_view| !in_view[index]) {
continue;
}
let node = &tree[index];
let mut below = Visit {
index,
depth,
element_above,
};
match Kind::of(node, index == start && read.start.is_some()) {
Kind::Skipped => continue,
Kind::Transparent => {}
Kind::Text(_) if depth >= read.depth => {
out.cut_at_depth = true;
continue;
}
Kind::Text(run) => {
let repeated = element_above.is_some_and(|above| {
let above = &tree[above];
VALUED.contains(&role(above)) || name(above).contains(run.trim())
});
if read.filter != Filter::Interactive && !repeated {
out.text(depth, node.parent_id.as_ref(), &run);
}
continue;
}
Kind::Element if depth >= read.depth => {
out.cut_at_depth = true;
continue;
}
Kind::Element => {
match read.filter {
Filter::Interactive if !is_interactive(node) => {}
Filter::Interactive => {
out.element(node, 0, refs);
below.depth += 1;
}
Filter::Visible | Filter::All => {
out.element(node, depth, refs);
below.depth += 1;
}
}
below.element_above = Some(index);
}
}
for &child in page.children[index].iter().rev() {
stack.push(Visit {
index: child,
..below
});
}
}
Some(out.finish())
}
#[derive(Clone, Copy)]
struct Visit {
index: usize,
depth: usize,
element_above: Option<usize>,
}
#[derive(Default)]
struct Out {
text: String,
run: Option<Run>,
cut_at_depth: bool,
}
struct Run {
depth: usize,
parent: Option<AxNodeId>,
text: String,
}
impl Out {
fn text(&mut self, depth: usize, parent: Option<&AxNodeId>, run: &str) {
match &mut self.run {
Some(line) if line.depth == depth => {
if line.parent.as_ref() != parent
&& !line.text.ends_with(' ')
&& !run.starts_with(' ')
{
line.text.push(' ');
}
line.text.push_str(run);
line.parent = parent.cloned();
}
_ => {
self.end_run();
self.run = Some(Run {
depth,
parent: parent.cloned(),
text: run.to_owned(),
});
}
}
}
fn element(&mut self, node: &AxNode, indent: usize, refs: &mut Refs) {
self.end_run();
write_element(&mut self.text, node, indent, refs);
}
fn end_run(&mut self) {
if let Some(Run { depth, text, .. }) = self.run.take() {
let run = text.trim();
if !run.is_empty() {
let _ = writeln!(
self.text,
"{:indent$}text {}",
"",
quoted(run),
indent = depth * 2
);
}
}
}
fn finish(mut self) -> Rendered {
self.end_run();
Rendered {
text: self.text,
cut_at_depth: self.cut_at_depth,
}
}
}
pub(super) fn find(tree: &[AxNode], query: &str, limit: usize, refs: &mut Refs) -> Vec<String> {
let words: Vec<String> = query
.split(|c: char| !c.is_alphanumeric())
.filter(|word| !word.is_empty() && !STOP_WORDS.contains(word))
.map(str::to_lowercase)
.collect();
if words.is_empty() {
return Vec::new();
}
let page = Page::new(tree);
let mut matches: Vec<(usize, bool, usize, &AxNode)> = page
.document_order()
.into_iter()
.enumerate()
.filter_map(|(order, index)| {
let node = &tree[index];
if !matches!(Kind::of(node, false), Kind::Element) {
return None;
}
let haystack = haystack(node);
let score = words
.iter()
.filter(|word| haystack.contains(word.as_str()))
.count();
(score > 0).then_some((score, is_interactive(node), order, node))
})
.collect();
matches.sort_by(|a, b| b.0.cmp(&a.0).then(b.1.cmp(&a.1)).then(a.2.cmp(&b.2)));
matches
.into_iter()
.take(limit)
.map(|(_, _, _, node)| {
let mut line = String::new();
write_element(&mut line, node, 0, refs);
line.pop();
line
})
.collect()
}
const STOP_WORDS: [&str; 11] = [
"a", "an", "the", "to", "for", "of", "on", "in", "with", "and", "or",
];
fn haystack(node: &AxNode) -> String {
let role = role(node);
let mut haystack = format!("{role} {} ", role_aliases(role));
for value in [&node.name, &node.value, &node.description]
.into_iter()
.flatten()
{
if let Some(text) = value.as_str() {
haystack.push_str(text);
haystack.push(' ');
}
}
haystack.to_lowercase()
}
fn role_aliases(role: &str) -> &'static str {
match role {
"textbox" | "searchbox" | "combobox" => "field input box text search",
"checkbox" | "switch" => "check box toggle",
"radio" => "option choice",
"img" | "image" => "image picture",
"heading" => "title header",
"navigation" => "nav menu",
"listbox" => "list select dropdown",
_ => "",
}
}
struct Page<'a> {
tree: &'a [AxNode],
children: Vec<Vec<usize>>,
by_dom: HashMap<BackendNodeId, usize>,
}
impl<'a> Page<'a> {
fn new(tree: &'a [AxNode]) -> Self {
let by_id: HashMap<&AxNodeId, usize> = tree
.iter()
.enumerate()
.map(|(index, node)| (&node.node_id, index))
.collect();
let children = tree
.iter()
.map(|node| {
node.child_ids
.iter()
.filter_map(|child| by_id.get(child).copied())
.collect()
})
.collect();
let by_dom = tree
.iter()
.enumerate()
.filter_map(|(index, node)| Some((node.backend_dom_node_id?, index)))
.collect();
Self {
tree,
children,
by_dom,
}
}
fn document_order(&self) -> Vec<usize> {
let mut order = Vec::with_capacity(self.tree.len());
let mut seen = vec![false; self.tree.len()];
let mut stack = if self.tree.is_empty() {
Vec::new()
} else {
vec![0]
};
while let Some(index) = stack.pop() {
if std::mem::replace(&mut seen[index], true) {
continue;
}
order.push(index);
stack.extend(self.children[index].iter().rev());
}
order
}
fn in_view(&self, view: &View) -> Vec<bool> {
let mut in_view: Vec<bool> = self
.tree
.iter()
.map(|node| {
node.backend_dom_node_id
.and_then(|dom| view.boxes.get(&dom))
.is_some_and(|rect| rect.overlaps(&view.viewport))
})
.collect();
for &index in self.document_order().iter().rev() {
if self.children[index].iter().any(|&child| in_view[child]) {
in_view[index] = true;
}
}
in_view
}
}
enum Kind {
Skipped,
Transparent,
Text(String),
Element,
}
impl Kind {
fn of(node: &AxNode, start: bool) -> Self {
let role = role(node);
match role {
"InlineTextBox" => Self::Skipped,
"StaticText" if node.ignored => Self::Skipped,
"StaticText" => Self::Text(clean(
node.name
.as_ref()
.and_then(|name| name.as_str())
.unwrap_or(""),
)),
_ if start => Self::Element,
_ if node.ignored => Self::Transparent,
"RootWebArea" | "WebArea" => Self::Transparent,
"generic" | "none" | "" if !has_name(node) => Self::Transparent,
_ => Self::Element,
}
}
}
fn role(node: &AxNode) -> &str {
node.role
.as_ref()
.and_then(|role| role.as_str())
.unwrap_or("")
}
fn name(node: &AxNode) -> String {
clean(
node.name
.as_ref()
.and_then(|name| name.as_str())
.unwrap_or(""),
)
}
fn has_name(node: &AxNode) -> bool {
!name(node).trim().is_empty()
}
const INTERACTIVE: [&str; 17] = [
"button",
"checkbox",
"combobox",
"link",
"listbox",
"menuitem",
"menuitemcheckbox",
"menuitemradio",
"option",
"radio",
"searchbox",
"slider",
"spinbutton",
"switch",
"tab",
"textbox",
"treeitem",
];
fn is_interactive(node: &AxNode) -> bool {
INTERACTIVE.contains(&role(node))
|| (has_name(node) && property(node, "focusable") == Some(&serde_json::Value::Bool(true)))
}
fn property<'a>(node: &'a AxNode, name: &str) -> Option<&'a serde_json::Value> {
node.properties
.iter()
.find(|property| property.name == name)
.and_then(|property| property.value.value.as_ref())
}
const VALUED: [&str; 5] = ["textbox", "searchbox", "combobox", "spinbutton", "slider"];
fn write_element(text: &mut String, node: &AxNode, indent: usize, refs: &mut Refs) {
use serde_json::Value;
let role = role(node);
let _ = write!(text, "{:indent$}{role}", "", indent = indent * 2);
let name = name(node);
if !name.trim().is_empty() {
let _ = write!(text, " {}", quoted(name.trim()));
}
if VALUED.contains(&role) {
if let Some(value) = node.value.as_ref().and_then(|value| value.value.as_ref()) {
let value = match value {
Value::String(value) => clean(value),
other => other.to_string(),
};
let _ = write!(text, " value={}", quoted(&value));
}
}
if let Some(Value::Number(level)) = property(node, "level") {
let _ = write!(text, " level={level}");
}
match property(node, "checked") {
Some(Value::String(checked)) if checked == "true" => text.push_str(" checked"),
Some(Value::String(checked)) if checked == "mixed" => text.push_str(" mixed"),
Some(Value::Bool(true)) => text.push_str(" checked"),
_ => {}
}
match property(node, "expanded") {
Some(Value::Bool(true)) => text.push_str(" expanded"),
Some(Value::Bool(false)) => text.push_str(" collapsed"),
_ => {}
}
for state in ["selected", "disabled"] {
if property(node, state) == Some(&Value::Bool(true)) {
let _ = write!(text, " {state}");
}
}
if let Some(dom) = node.backend_dom_node_id {
let _ = write!(text, " [{}]", refs.name(dom));
}
text.push('\n');
}
fn clean(text: &str) -> String {
let mut cleaned = String::with_capacity(text.len());
let mut space = false;
for c in text.chars() {
if c.is_whitespace() {
space = true;
} else if !c.is_control() {
if std::mem::take(&mut space) {
cleaned.push(' ');
}
cleaned.push(c);
}
}
if space {
cleaned.push(' ');
}
cleaned
}
fn quoted(text: &str) -> String {
format!("\"{}\"", text.replace('\\', "\\\\").replace('"', "\\\""))
}
#[cfg(test)]
#[path = "snapshot_tests.rs"]
mod tests;