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 rendered text content contains `substring` (whitespace-normalized).
46    pub fn text_contains(substring: impl Into<String>) -> Self {
47        Self::text(substring).contains()
48    }
49
50    /// Matches elements whose `title` attribute (or `alt` on `<button>` / `<img>`) equals `title`.
51    ///
52    /// `title` and `alt` are not prioritised here, unlike the hover tooltip (which prefers
53    /// `title`): the element matches if **either** attribute matches the needle. A button with
54    /// `title="Save"` and `alt="Store"` is found by both `"Save"` and `"Store"`. `alt` is only
55    /// considered on `<button>` and `<img>`; other elements match on `title` alone.
56    pub fn title(title: impl Into<String>) -> Self {
57        Self {
58            title: Some(title.into()),
59            ..Self::default()
60        }
61    }
62
63    /// Matches elements whose `title` (or `alt` on `<button>` / `<img>`) contains `substring`.
64    pub fn title_contains(substring: impl Into<String>) -> Self {
65        Self::title(substring).contains()
66    }
67
68    /// Additionally requires the element's rendered text content to match.
69    pub fn with_text(mut self, text: impl Into<String>) -> Self {
70        self.text = Some(text.into());
71        self
72    }
73
74    /// Additionally requires the element's `title` / `alt` to match.
75    pub fn with_title(mut self, title: impl Into<String>) -> Self {
76        self.title = Some(title.into());
77        self
78    }
79
80    /// Switches from whitespace-normalized equality to substring containment.
81    pub fn contains(mut self) -> Self {
82        self.mode = MatchMode::Contains;
83        self
84    }
85
86    fn matches_str(&self, needle: &str, haystack: &str) -> bool {
87        let needle = normalize_ws(needle);
88        let haystack = normalize_ws(haystack);
89        match self.mode {
90            MatchMode::Exact => haystack == needle,
91            MatchMode::Contains => haystack.contains(&needle),
92        }
93    }
94}
95
96fn normalize_ws(s: &str) -> String {
97    s.split_whitespace().collect::<Vec<_>>().join(" ")
98}
99
100fn collect_text(bp: &NodeBlueprint, out: &mut String) {
101    match bp {
102        NodeBlueprint::Text(t) => {
103            if !out.is_empty() && !out.ends_with(' ') {
104                out.push(' ');
105            }
106            out.push_str(t);
107        }
108        NodeBlueprint::DynamicText(f) => {
109            if !out.is_empty() && !out.ends_with(' ') {
110                out.push(' ');
111            }
112            out.push_str(&f());
113        }
114        NodeBlueprint::Element { children, .. } | NodeBlueprint::Fragment(children) => {
115            for c in children {
116                collect_text(c, out);
117            }
118        }
119        NodeBlueprint::Empty => {}
120    }
121}
122
123fn own_tooltip_attrs(bp: &NodeBlueprint) -> Vec<&str> {
124    let mut found = Vec::new();
125    if let NodeBlueprint::Element {
126        tag, attributes, ..
127    } = bp
128    {
129        let supports_alt = match tag {
130            strata_dom::Tag::Img | strata_dom::Tag::Button => true,
131            strata_dom::Tag::Custom(name) => {
132                name.eq_ignore_ascii_case("img") || name.eq_ignore_ascii_case("button")
133            }
134            _ => false,
135        };
136        for attr in attributes {
137            if let strata_dom::Attribute::Property { key, value } = attr {
138                if key.eq_ignore_ascii_case("title")
139                    || (supports_alt && key.eq_ignore_ascii_case("alt"))
140                {
141                    found.push(value.as_str());
142                }
143            }
144        }
145    }
146    found
147}
148
149impl AppRuntime {
150    fn query_matches_node(query: &NodeQuery, bp: &NodeBlueprint) -> bool {
151        if !matches!(bp, NodeBlueprint::Element { .. }) {
152            return false;
153        }
154        if query.text.is_none() && query.title.is_none() {
155            return false;
156        }
157        if let Some(ref needle) = query.text {
158            let mut content = String::new();
159            collect_text(bp, &mut content);
160            if !query.matches_str(needle, &content) {
161                return false;
162            }
163        }
164        if let Some(ref needle) = query.title {
165            if !own_tooltip_attrs(bp)
166                .into_iter()
167                .any(|v| query.matches_str(needle, v))
168            {
169                return false;
170            }
171        }
172        true
173    }
174
175    /// Walks the paired trees; returns whether `bp` or any descendant matched. A node is reported
176    /// only if none of its descendants matched, so results are the deepest matches in
177    /// document order.
178    fn collect_query_matches(
179        query: &NodeQuery,
180        bp: &NodeBlueprint,
181        layout: &LayoutNode,
182        path: &mut Vec<usize>,
183        out: &mut Vec<Vec<usize>>,
184    ) -> bool {
185        if path.len() >= 256 {
186            return false;
187        }
188        let mut any_child = false;
189        for (idx, child_bp, child_layout) in Self::paired_blueprint_children(bp, layout) {
190            if matches!(
191                child_layout.style.display,
192                strata_style::types::Display::None
193            ) {
194                continue;
195            }
196            path.push(idx);
197            if Self::collect_query_matches(query, child_bp, child_layout, path, out) {
198                any_child = true;
199            }
200            path.pop();
201        }
202        if !any_child && Self::query_matches_node(query, bp) {
203            out.push(path.clone());
204            return true;
205        }
206        any_child
207    }
208
209    /// Returns the tree paths of every element matching `query`, in document order.
210    pub fn find_all(&self, query: &NodeQuery) -> Vec<Vec<usize>> {
211        let mut out = Vec::new();
212        let mut path = Vec::new();
213        Self::collect_query_matches(
214            query,
215            &self.root_blueprint,
216            &self.layout_root,
217            &mut path,
218            &mut out,
219        );
220        out
221    }
222
223    /// First (bottom-most in paint order) element matching `query`.
224    pub fn find(&self, query: &NodeQuery) -> Option<Vec<usize>> {
225        self.find_all(query).into_iter().next()
226    }
227
228    /// Last (top-most in paint order) element matching `query`, e.g. a modal's button when the
229    /// same label also exists on the page behind it.
230    pub fn find_last(&self, query: &NodeQuery) -> Option<Vec<usize>> {
231        self.find_all(query).into_iter().next_back()
232    }
233
234    /// Shorthand for `find(&NodeQuery::text(text))`.
235    pub fn find_by_text(&self, text: &str) -> Option<Vec<usize>> {
236        self.find(&NodeQuery::text(text))
237    }
238
239    /// Shorthand for `find(&NodeQuery::text_contains(substring))`.
240    pub fn find_by_text_contains(&self, substring: &str) -> Option<Vec<usize>> {
241        self.find(&NodeQuery::text_contains(substring))
242    }
243
244    /// Shorthand for `find_last(&NodeQuery::text(text))`.
245    pub fn find_last_by_text(&self, text: &str) -> Option<Vec<usize>> {
246        self.find_last(&NodeQuery::text(text))
247    }
248
249    /// Shorthand for `find_last(&NodeQuery::text_contains(substring))`.
250    pub fn find_last_by_text_contains(&self, substring: &str) -> Option<Vec<usize>> {
251        self.find_last(&NodeQuery::text_contains(substring))
252    }
253
254    /// Shorthand for `find(&NodeQuery::title(title))`.
255    pub fn find_by_title(&self, title: &str) -> Option<Vec<usize>> {
256        self.find(&NodeQuery::title(title))
257    }
258
259    /// Shorthand for `find(&NodeQuery::title_contains(substring))`.
260    pub fn find_by_title_contains(&self, substring: &str) -> Option<Vec<usize>> {
261        self.find(&NodeQuery::title_contains(substring))
262    }
263
264    /// Shorthand for `find_last(&NodeQuery::title(title))`.
265    pub fn find_last_by_title(&self, title: &str) -> Option<Vec<usize>> {
266        self.find_last(&NodeQuery::title(title))
267    }
268
269    /// Shorthand for `find_last(&NodeQuery::title_contains(substring))`.
270    pub fn find_last_by_title_contains(&self, substring: &str) -> Option<Vec<usize>> {
271        self.find_last(&NodeQuery::title_contains(substring))
272    }
273
274    /// Rendered text content of the element at `path`, whitespace-normalized.
275    pub fn node_text(&self, path: &[usize]) -> Option<String> {
276        let (bp, _) = Self::find_node_by_path(&self.root_blueprint, &self.layout_root, path)?;
277        let mut content = String::new();
278        collect_text(bp, &mut content);
279        Some(normalize_ws(&content))
280    }
281
282    /// Border-box center of the element at `path` in window coordinates.
283    pub fn node_center(&self, path: &[usize]) -> Option<(f32, f32)> {
284        let (_, layout) = Self::find_node_by_path(&self.root_blueprint, &self.layout_root, path)?;
285        let b = layout.geometry.border_box;
286        Some((b.x + b.width * 0.5, b.y + b.height * 0.5))
287    }
288
289    /// Clicks the center of the element at `path` through the normal hit-test path (so an
290    /// occluding element receives the click, as for a real pointer). Returns `true` if a
291    /// click listener ran.
292    pub fn click_node(&self, path: &[usize]) -> bool {
293        match self.node_center(path) {
294            Some((x, y)) => self.dispatch_click(x, y),
295            None => false,
296        }
297    }
298
299    /// Clicks the first element matching `query`. Returns `false` if none matched or no listener ran.
300    pub fn click(&self, query: &NodeQuery) -> bool {
301        self.find(query).is_some_and(|p| self.click_node(&p))
302    }
303
304    /// Clicks the last (top-most) element matching `query`.
305    pub fn click_last(&self, query: &NodeQuery) -> bool {
306        self.find_last(query).is_some_and(|p| self.click_node(&p))
307    }
308
309    /// Clicks the first element whose text equals `text`.
310    pub fn click_text(&self, text: &str) -> bool {
311        self.click(&NodeQuery::text(text))
312    }
313
314    /// Clicks the first element whose text contains `substring`.
315    pub fn click_text_contains(&self, substring: &str) -> bool {
316        self.click(&NodeQuery::text_contains(substring))
317    }
318
319    /// Clicks the last (top-most) element whose text equals `text`.
320    pub fn click_last_text(&self, text: &str) -> bool {
321        self.click_last(&NodeQuery::text(text))
322    }
323
324    /// Clicks the last (top-most) element whose text contains `substring`.
325    pub fn click_last_text_contains(&self, substring: &str) -> bool {
326        self.click_last(&NodeQuery::text_contains(substring))
327    }
328
329    /// Clicks the first element whose `title` or (on button/img) `alt` equals `title`; either
330    /// attribute may match. See [`NodeQuery::title`].
331    pub fn click_title(&self, title: &str) -> bool {
332        self.click(&NodeQuery::title(title))
333    }
334
335    /// Clicks the first element whose `title` or (on button/img) `alt` contains `substring`.
336    pub fn click_title_contains(&self, substring: &str) -> bool {
337        self.click(&NodeQuery::title_contains(substring))
338    }
339
340    /// Clicks the last (top-most) element whose `title` or (on button/img) `alt` equals `title`;
341    /// either attribute may match. See [`NodeQuery::title`].
342    pub fn click_last_title(&self, title: &str) -> bool {
343        self.click_last(&NodeQuery::title(title))
344    }
345
346    /// Clicks the last (top-most) element whose `title` or (on button/img) `alt` contains `substring`.
347    pub fn click_last_title_contains(&self, substring: &str) -> bool {
348        self.click_last(&NodeQuery::title_contains(substring))
349    }
350}