Skip to main content

yew_e2e/test_driver/
style.rs

1//! What the browser settled on for a style, and forcing one.
2
3use anyhow::{Context, Result};
4
5use super::finite;
6use crate::{TestDriver, TestElement};
7
8impl TestDriver {
9    /// **Force one inline CSS property on an element**, the same lever a
10    /// hand-typed `style=""` pulls, for a size no real window is narrow
11    /// enough to produce on its own, such as a popover's own row.
12    pub async fn set_style(
13        &self,
14        element: &TestElement,
15        property: &str,
16        value: &str,
17    ) -> Result<()> {
18        tracing::trace!(property, value, "Setting an inline style property");
19
20        self.inner
21            .execute(
22                "arguments[0].style.setProperty(arguments[1], arguments[2]);",
23                vec![
24                    element.inner.to_json()?,
25                    serde_json::json!(property),
26                    serde_json::json!(value),
27                ],
28            )
29            .await?;
30
31        Ok(())
32    }
33
34    /// **Force one class on or off an element**, for a state the app has no
35    /// way to put that element in yet but a stylesheet rule already answers
36    /// for, such as a record button that is capturing and unavailable at once.
37    pub async fn set_class(&self, element: &TestElement, class: &str, on: bool) -> Result<()> {
38        tracing::trace!(class, on, "Forcing a class");
39
40        self.inner
41            .execute(
42                "arguments[0].classList.toggle(arguments[1], arguments[2]);",
43                vec![
44                    element.inner.to_json()?,
45                    serde_json::json!(class),
46                    serde_json::json!(on),
47                ],
48            )
49            .await?;
50
51        Ok(())
52    }
53
54    /// **Every box inside an element that has more to show than it has room
55    /// for**, one line each: a scroller with something to scroll, or a box
56    /// that clips what it holds. Empty when everything in it fits. A box a
57    /// pixel or less across is passed over, since that is how a control is
58    /// hidden from sight while staying reachable, and it clips by design.
59    pub async fn overflowing(&self, element: &TestElement) -> Result<Vec<String>> {
60        tracing::trace!("Finding what overflows inside an element");
61
62        let script = "const out = []; \
63             for (const el of [arguments[0], ...arguments[0].querySelectorAll('*')]) { \
64                 if (el.clientHeight <= 1 || el.clientWidth <= 1) continue; \
65                 const cs = getComputedStyle(el); \
66                 const y = el.scrollHeight - el.clientHeight; \
67                 const x = el.scrollWidth - el.clientWidth; \
68                 const shows = v => v === 'auto' || v === 'scroll' || v === 'hidden' || v === 'clip'; \
69                 if ((y > 1 && shows(cs.overflowY)) || (x > 1 && shows(cs.overflowX))) { \
70                     const test = el.getAttribute('data-test'); \
71                     out.push(el.localName + (el.className ? '.' + String(el.className).trim().split(/\\s+/).join('.') : '') \
72                         + (test ? `[data-test=${test}]` : '') \
73                         + ` ${cs.overflowX}/${cs.overflowY} over by ${x}x${y}`); \
74                 } \
75             } \
76             return out;";
77
78        let found = self
79            .inner
80            .execute(script, vec![element.inner.to_json()?])
81            .await?;
82
83        Ok(found
84            .json()
85            .as_array()
86            .into_iter()
87            .flatten()
88            .filter_map(|line| line.as_str().map(str::to_owned))
89            .collect())
90    }
91
92    /// **Every piece of text inside an element set smaller than `floor`
93    /// pixels**, one line each, passing over whatever sits inside `marks`: the
94    /// numbers of a scale or a badge's count, which are read at a glance rather
95    /// than as words. Text nobody can see is passed over too.
96    pub async fn small_text(
97        &self,
98        element: &TestElement,
99        floor: f64,
100        marks: &str,
101    ) -> Result<Vec<String>> {
102        tracing::trace!(floor, marks, "Finding text set below a size");
103
104        let floor = finite("a text size floor", floor)?;
105
106        let script = "const out = []; \
107             for (const el of [arguments[0], ...arguments[0].querySelectorAll('*')]) { \
108                 if (el.closest(arguments[1])) continue; \
109                 const words = Array.from(el.childNodes) \
110                     .filter(n => n.nodeType === Node.TEXT_NODE) \
111                     .map(n => n.textContent.trim()).join(' ').trim(); \
112                 if (!words) continue; \
113                 const rect = el.getBoundingClientRect(); \
114                 if (rect.width <= 1 || rect.height <= 1) continue; \
115                 const cs = getComputedStyle(el); \
116                 if (cs.visibility !== 'visible') continue; \
117                 const size = parseFloat(cs.fontSize); \
118                 if (size < arguments[2]) { \
119                     const test = el.getAttribute('data-test'); \
120                     out.push(el.localName + (el.className ? '.' + String(el.className).trim().split(/\\s+/).join('.') : '') \
121                         + (test ? `[data-test=${test}]` : '') \
122                         + ` at ${cs.fontSize}: ${JSON.stringify(words.slice(0, 32))}`); \
123                 } \
124             } \
125             return out;";
126
127        let found = self
128            .inner
129            .execute(
130                script,
131                vec![element.inner.to_json()?, serde_json::json!(marks), floor],
132            )
133            .await?;
134
135        Ok(found
136            .json()
137            .as_array()
138            .into_iter()
139            .flatten()
140            .filter_map(|line| line.as_str().map(str::to_owned))
141            .collect())
142    }
143
144    /// **What the browser settled on, rather than what a rule says.**
145    pub async fn computed(
146        &self,
147        element: &TestElement,
148        pseudo: &str,
149        property: &str,
150    ) -> Result<String> {
151        tracing::trace!(pseudo, property, "Asking what a property computed to");
152
153        let script = "return getComputedStyle(arguments[0], arguments[1] || null) \
154             .getPropertyValue(arguments[2]);";
155
156        let value = self
157            .inner
158            .execute(
159                script,
160                vec![
161                    element.inner.to_json()?,
162                    serde_json::json!(pseudo),
163                    serde_json::json!(property),
164                ],
165            )
166            .await?;
167
168        Ok(value.json().as_str().unwrap_or_default().trim().to_string())
169    }
170
171    /// Whether the page matches `prefers-reduced-motion: reduce`.
172    ///
173    /// Where `E2E_MOTION` is set this is an error when the browser disagrees
174    /// with it, so a run meant to exercise one preference cannot quietly get
175    /// the other. Set it (Firefox only) to test the browser's own media
176    /// preference rather than a replacement stylesheet.
177    pub async fn reduced_motion(&self) -> Result<bool> {
178        let value = self
179            .inner
180            .execute(
181                "return matchMedia('(prefers-reduced-motion: reduce)').matches;",
182                Vec::new(),
183            )
184            .await?;
185        let reduced = value
186            .json()
187            .as_bool()
188            .context("reduced-motion media query")?;
189        if let Ok(requested) = std::env::var("E2E_MOTION") {
190            anyhow::ensure!(
191                reduced == (requested == "reduce"),
192                "browser did not honor E2E_MOTION={requested}"
193            );
194        }
195        Ok(reduced)
196    }
197
198    /// Pause an actual CSS animation at a deterministic phase before reading its
199    /// computed presentation. Missing animations are failures, not idle samples.
200    pub async fn animation_time(
201        &self,
202        element: &TestElement,
203        name: &str,
204        millis: f64,
205    ) -> Result<()> {
206        self.inner.execute(
207            "const animation = arguments[0].getAnimations().find(a => a.animationName === arguments[1]); \
208             if (!animation) throw new Error('Missing animation: ' + arguments[1]); \
209             animation.pause(); animation.currentTime = arguments[2];",
210            vec![element.inner.to_json()?, serde_json::json!(name), serde_json::json!(millis)],
211        ).await?;
212        Ok(())
213    }
214
215    /// Read a computed color's alpha through the browser's color parser so both
216    /// legacy rgba() and CSS Color 4 serialization describe the same measurement.
217    pub async fn color_alpha(&self, element: &TestElement, property: &str) -> Result<f64> {
218        let value = self.inner.execute(
219            "const canvas = document.createElement('canvas'); canvas.width = canvas.height = 1; \
220             const context = canvas.getContext('2d'); context.fillStyle = 'transparent'; \
221             context.fillStyle = getComputedStyle(arguments[0]).getPropertyValue(arguments[1]); \
222             context.fillRect(0, 0, 1, 1); return context.getImageData(0, 0, 1, 1).data[3] / 255;",
223            vec![element.inner.to_json()?, serde_json::json!(property)],
224        ).await?;
225        value.json().as_f64().context("computed color alpha")
226    }
227
228    /// **Which way a computed colour moves what is painted under it.** The
229    /// property is filled over mid grey by the browser itself and the result
230    /// compared with it, so a band's direction is measured rather than read off
231    /// a serialization: negative darkens, positive lightens, zero paints
232    /// nothing. `color-mix()` and a legacy `rgba()` are the same measurement.
233    pub async fn color_shift(&self, element: &TestElement, property: &str) -> Result<f64> {
234        let [red, green, blue] = self.painted(element, property).await?;
235        Ok((red + green + blue) / 3.0 - 128.0)
236    }
237
238    /// **What a computed colour actually paints**, as red, green and blue.
239    ///
240    /// The browser fills the property over mid grey and the pixel is read back,
241    /// so a `color-mix()`, a legacy `rgba()` and a translucent wash all answer
242    /// as the colour that is seen rather than as whatever the property happens
243    /// to serialize to.
244    pub async fn painted(&self, element: &TestElement, property: &str) -> Result<[f64; 3]> {
245        let value = self.inner.execute(
246            "const canvas = document.createElement('canvas'); canvas.width = canvas.height = 1; \
247             const context = canvas.getContext('2d'); \
248             context.fillStyle = '#808080'; context.fillRect(0, 0, 1, 1); \
249             context.fillStyle = 'transparent'; \
250             context.fillStyle = getComputedStyle(arguments[0]).getPropertyValue(arguments[1]); \
251             context.fillRect(0, 0, 1, 1); \
252             const painted = context.getImageData(0, 0, 1, 1).data; \
253             return [painted[0], painted[1], painted[2]];",
254            vec![element.inner.to_json()?, serde_json::json!(property)],
255        ).await?;
256
257        let read = value.json();
258        let read = read.as_array().context("what a computed colour paints")?;
259
260        let mut rgb = [0.0; 3];
261
262        for (channel, value) in rgb.iter_mut().zip(read) {
263            *channel = value.as_f64().context("a painted channel")?;
264        }
265
266        Ok(rgb)
267    }
268}