Skip to main content

strata/runtime/
test_support.rs

1//! Headless test helpers: locate elements by visible text or `title`/`alt`, and click them.
2//!
3//! These replace hand-rolled depth-first searches over `NodeBlueprint` / `LayoutNode` that match
4//! on `Debug` output. Matching walks the blueprint and layout trees in lockstep (so it honours
5//! fragment flattening and skips `display: none` subtrees) and returns hierarchical index paths
6//! compatible with [`AppRuntime::find_node_by_path`].
7//!
8//! Matches are returned in document (pre-order) order. Later elements, such as modals and
9//! `<Portal>` content, are painted above earlier ones, so use the `*_last` variants to target the
10//! top-most match.
11
12use super::*;
13
14/// How a [`NodeQuery`] compares its needle against an element's text or title.
15#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
16pub enum MatchMode {
17    /// Whitespace-normalized equality (default).
18    #[default]
19    Exact,
20    /// Whitespace-normalized substring containment.
21    Contains,
22}
23
24/// Declarative element query for [`AppRuntime::find_all`], [`AppRuntime::click`] and friends.
25///
26/// When both `text` and `title` are set, an element must satisfy both. Only the *deepest*
27/// matching elements are reported: an ancestor whose text merely aggregates a matching
28/// descendant is not itself a match.
29#[derive(Debug, Clone, Default)]
30pub struct NodeQuery {
31    text: Option<String>,
32    title: Option<String>,
33    mode: MatchMode,
34}
35
36impl NodeQuery {
37    /// Matches elements whose rendered text content equals `text` (see [`NodeQuery::contains`]).
38    pub fn text(text: impl Into<String>) -> Self {
39        Self {
40            text: Some(text.into()),
41            ..Self::default()
42        }
43    }
44
45    /// Matches elements whose `title` attribute (or `alt` on `<button>` / `<img>`) equals `title`.
46    ///
47    /// `title` and `alt` are not prioritised here, unlike the hover tooltip (which prefers
48    /// `title`): the element matches if **either** attribute matches the needle. A button with
49    /// `title="Save"` and `alt="Store"` is found by both `"Save"` and `"Store"`. `alt` is only
50    /// considered on `<button>` and `<img>`; other elements match on `title` alone.
51    pub fn title(title: impl Into<String>) -> Self {
52        Self {
53            title: Some(title.into()),
54            ..Self::default()
55        }
56    }
57
58    /// Additionally requires the element's rendered text content to match.
59    pub fn with_text(mut self, text: impl Into<String>) -> Self {
60        self.text = Some(text.into());
61        self
62    }
63
64    /// Additionally requires the element's `title` / `alt` to match.
65    pub fn with_title(mut self, title: impl Into<String>) -> Self {
66        self.title = Some(title.into());
67        self
68    }
69
70    /// Switches from whitespace-normalized equality to substring containment.
71    pub fn contains(mut self) -> Self {
72        self.mode = MatchMode::Contains;
73        self
74    }
75
76    fn matches_str(&self, needle: &str, haystack: &str) -> bool {
77        let needle = normalize_ws(needle);
78        let haystack = normalize_ws(haystack);
79        match self.mode {
80            MatchMode::Exact => haystack == needle,
81            MatchMode::Contains => haystack.contains(&needle),
82        }
83    }
84}
85
86fn normalize_ws(s: &str) -> String {
87    s.split_whitespace().collect::<Vec<_>>().join(" ")
88}
89
90fn collect_text(bp: &NodeBlueprint, out: &mut String) {
91    match bp {
92        NodeBlueprint::Text(t) => {
93            if !out.is_empty() && !out.ends_with(' ') {
94                out.push(' ');
95            }
96            out.push_str(t);
97        }
98        NodeBlueprint::DynamicText(f) => {
99            if !out.is_empty() && !out.ends_with(' ') {
100                out.push(' ');
101            }
102            out.push_str(&f());
103        }
104        NodeBlueprint::Element { children, .. } | NodeBlueprint::Fragment(children) => {
105            for c in children {
106                collect_text(c, out);
107            }
108        }
109        NodeBlueprint::Empty => {}
110    }
111}
112
113fn own_tooltip_attrs(bp: &NodeBlueprint) -> Vec<&str> {
114    let mut found = Vec::new();
115    if let NodeBlueprint::Element {
116        tag, attributes, ..
117    } = bp
118    {
119        let supports_alt = match tag {
120            strata_dom::Tag::Img | strata_dom::Tag::Button => true,
121            strata_dom::Tag::Custom(name) => {
122                name.eq_ignore_ascii_case("img") || name.eq_ignore_ascii_case("button")
123            }
124            _ => false,
125        };
126        for attr in attributes {
127            if let strata_dom::Attribute::Property { key, value } = attr {
128                if key.eq_ignore_ascii_case("title")
129                    || (supports_alt && key.eq_ignore_ascii_case("alt"))
130                {
131                    found.push(value.as_str());
132                }
133            }
134        }
135    }
136    found
137}
138
139impl AppRuntime {
140    fn query_matches_node(query: &NodeQuery, bp: &NodeBlueprint) -> bool {
141        if !matches!(bp, NodeBlueprint::Element { .. }) {
142            return false;
143        }
144        if query.text.is_none() && query.title.is_none() {
145            return false;
146        }
147        if let Some(ref needle) = query.text {
148            let mut content = String::new();
149            collect_text(bp, &mut content);
150            if !query.matches_str(needle, &content) {
151                return false;
152            }
153        }
154        if let Some(ref needle) = query.title {
155            if !own_tooltip_attrs(bp)
156                .into_iter()
157                .any(|v| query.matches_str(needle, v))
158            {
159                return false;
160            }
161        }
162        true
163    }
164
165    /// Walks the paired trees; returns whether `bp` or any descendant matched. A node is reported
166    /// only if none of its descendants matched, so results are the deepest matches in
167    /// document order.
168    fn collect_query_matches(
169        query: &NodeQuery,
170        bp: &NodeBlueprint,
171        layout: &LayoutNode,
172        path: &mut Vec<usize>,
173        out: &mut Vec<Vec<usize>>,
174    ) -> bool {
175        if path.len() >= 256 {
176            return false;
177        }
178        let mut any_child = false;
179        for (idx, child_bp, child_layout) in Self::paired_blueprint_children(bp, layout) {
180            if matches!(
181                child_layout.style.display,
182                strata_style::types::Display::None
183            ) {
184                continue;
185            }
186            path.push(idx);
187            if Self::collect_query_matches(query, child_bp, child_layout, path, out) {
188                any_child = true;
189            }
190            path.pop();
191        }
192        if !any_child && Self::query_matches_node(query, bp) {
193            out.push(path.clone());
194            return true;
195        }
196        any_child
197    }
198
199    /// Returns the tree paths of every element matching `query`, in document order.
200    pub fn find_all(&self, query: &NodeQuery) -> Vec<Vec<usize>> {
201        let mut out = Vec::new();
202        let mut path = Vec::new();
203        Self::collect_query_matches(
204            query,
205            &self.root_blueprint,
206            &self.layout_root,
207            &mut path,
208            &mut out,
209        );
210        out
211    }
212
213    /// First (bottom-most in paint order) element matching `query`.
214    pub fn find(&self, query: &NodeQuery) -> Option<Vec<usize>> {
215        self.find_all(query).into_iter().next()
216    }
217
218    /// Last (top-most in paint order) element matching `query`, e.g. a modal's button when the
219    /// same label also exists on the page behind it.
220    pub fn find_last(&self, query: &NodeQuery) -> Option<Vec<usize>> {
221        self.find_all(query).into_iter().next_back()
222    }
223
224    /// Shorthand for `find(&NodeQuery::text(text))`.
225    pub fn find_by_text(&self, text: &str) -> Option<Vec<usize>> {
226        self.find(&NodeQuery::text(text))
227    }
228
229    /// Shorthand for `find_last(&NodeQuery::text(text))`.
230    pub fn find_last_by_text(&self, text: &str) -> Option<Vec<usize>> {
231        self.find_last(&NodeQuery::text(text))
232    }
233
234    /// Shorthand for `find(&NodeQuery::title(title))`.
235    pub fn find_by_title(&self, title: &str) -> Option<Vec<usize>> {
236        self.find(&NodeQuery::title(title))
237    }
238
239    /// Shorthand for `find_last(&NodeQuery::title(title))`.
240    pub fn find_last_by_title(&self, title: &str) -> Option<Vec<usize>> {
241        self.find_last(&NodeQuery::title(title))
242    }
243
244    /// Rendered text content of the element at `path`, whitespace-normalized.
245    pub fn node_text(&self, path: &[usize]) -> Option<String> {
246        let (bp, _) = Self::find_node_by_path(&self.root_blueprint, &self.layout_root, path)?;
247        let mut content = String::new();
248        collect_text(bp, &mut content);
249        Some(normalize_ws(&content))
250    }
251
252    /// Border-box center of the element at `path` in window coordinates.
253    pub fn node_center(&self, path: &[usize]) -> Option<(f32, f32)> {
254        let (_, layout) = Self::find_node_by_path(&self.root_blueprint, &self.layout_root, path)?;
255        let b = layout.geometry.border_box;
256        Some((b.x + b.width * 0.5, b.y + b.height * 0.5))
257    }
258
259    /// Clicks the center of the element at `path` through the normal hit-test path (so an
260    /// occluding element receives the click, as for a real pointer). Returns `true` if a
261    /// click listener ran.
262    pub fn click_node(&self, path: &[usize]) -> bool {
263        match self.node_center(path) {
264            Some((x, y)) => self.dispatch_click(x, y),
265            None => false,
266        }
267    }
268
269    /// Clicks the first element matching `query`. Returns `false` if none matched or no listener ran.
270    pub fn click(&self, query: &NodeQuery) -> bool {
271        self.find(query).is_some_and(|p| self.click_node(&p))
272    }
273
274    /// Clicks the last (top-most) element matching `query`.
275    pub fn click_last(&self, query: &NodeQuery) -> bool {
276        self.find_last(query).is_some_and(|p| self.click_node(&p))
277    }
278
279    /// Clicks the first element whose text equals `text`.
280    pub fn click_text(&self, text: &str) -> bool {
281        self.click(&NodeQuery::text(text))
282    }
283
284    /// Clicks the last (top-most) element whose text equals `text`.
285    pub fn click_last_text(&self, text: &str) -> bool {
286        self.click_last(&NodeQuery::text(text))
287    }
288
289    /// Clicks the first element whose `title` or (on button/img) `alt` equals `title`; either
290    /// attribute may match. See [`NodeQuery::title`].
291    pub fn click_title(&self, title: &str) -> bool {
292        self.click(&NodeQuery::title(title))
293    }
294
295    /// Clicks the last (top-most) element whose `title` or (on button/img) `alt` equals `title`;
296    /// either attribute may match. See [`NodeQuery::title`].
297    pub fn click_last_title(&self, title: &str) -> bool {
298        self.click_last(&NodeQuery::title(title))
299    }
300}