1use anyhow::{Context, Result};
4
5use super::finite;
6use crate::{TestDriver, TestElement};
7
8impl TestDriver {
9 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 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 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 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 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 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 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 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 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 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}