1
//! What a person does on the pages, and what every page must satisfy.
2

            
3
use std::time::{Duration, Instant};
4

            
5
use anyhow::{Context, Result, anyhow, bail};
6
use serde_json::{Value, json};
7
use uuid::Uuid;
8

            
9
use super::driver::{ARROW_DOWN, BACKSPACE, Driver, ENTER, Element};
10
use super::harness::{Harness, READY_DEADLINE};
11

            
12
pub const DESKTOP: (u32, u32) = (1280, 900);
13
pub const PHONE: (u32, u32) = (390, 844);
14

            
15
#[derive(Clone, Copy)]
16
pub enum Pick {
17
    Mouse,
18
    Keyboard,
19
}
20

            
21
/// Polls `script` (a function body returning a truthy value) until it holds.
22
235
pub async fn wait_for(
23
235
    driver: &Driver,
24
235
    script: &str,
25
235
    args: Vec<Value>,
26
235
    what: &str,
27
235
) -> Result<Value> {
28
235
    let deadline = Instant::now() + READY_DEADLINE;
29
    loop {
30
317
        let value = driver.run(script, args.clone()).await?;
31
317
        if !value.is_null() && value != json!(false) {
32
235
            return Ok(value);
33
82
        }
34
82
        if Instant::now() > deadline {
35
            bail!("timed out waiting for {what}");
36
82
        }
37
82
        tokio::time::sleep(Duration::from_millis(100)).await;
38
    }
39
235
}
40

            
41
57
pub async fn login(h: &Harness) -> Result<()> {
42
57
    h.driver.goto(&h.url("/login")).await?;
43
57
    let email = h.driver.find("input[name=\"email\"]").await?;
44
57
    h.driver.type_into(&email, &h.tenant.email).await?;
45
57
    let password = h.driver.find("input[name=\"password\"]").await?;
46
57
    h.driver.type_into(&password, h.tenant.password).await?;
47
57
    let send = h.driver.find("#loginform button[type=\"submit\"]").await?;
48
57
    h.driver.click(&send).await?;
49
57
    wait_for(
50
57
        &h.driver,
51
57
        "return !location.pathname.startsWith('/login') && document.readyState === 'complete';",
52
57
        vec![],
53
57
        "the login to leave the login page",
54
57
    )
55
57
    .await
56
57
    .map(drop)
57
57
}
58

            
59
/// Opens `path` and waits until the page and its form widgets are ready.
60
80
pub async fn open(h: &Harness, path: &str) -> Result<()> {
61
80
    h.driver.goto(&h.url(path)).await?;
62
80
    wait_for(
63
80
        &h.driver,
64
80
        "return document.readyState === 'complete' && \
65
80
         [...document.querySelectorAll('form.nomi-form')]\
66
80
         .every(f => f.hasAttribute('data-suggest-ready'));",
67
80
        vec![],
68
80
        &format!("{path} to be ready"),
69
80
    )
70
80
    .await
71
80
    .map(drop)
72
80
}
73

            
74
/// The visible control of the select cell at `address`, whichever way the
75
/// page names it.
76
186
pub async fn visible(h: &Harness, address: &str) -> Result<Element> {
77
186
    h.driver
78
186
        .find(&format!(
79
186
            "input[data-source][name=\"{address}\"], input[data-source][name=\"label:{address}\"]"
80
186
        ))
81
186
        .await
82
186
}
83

            
84
/// What the select cell at `address` shows and the id it carries (empty
85
/// when the page has no hidden reference input).
86
35
pub async fn reference(h: &Harness, address: &str) -> Result<(String, String)> {
87
35
    let found = h
88
35
        .driver
89
35
        .run(
90
35
            "const a = arguments[0];\
91
35
             const shown = document.querySelector(\
92
35
               `input[data-source][name=\"${a}\"], input[data-source][name=\"label:${a}\"]`);\
93
35
             const hidden = document.querySelector(`input[type=hidden][name=\"${a}\"]`);\
94
35
             return [shown ? shown.value : null, hidden ? hidden.value : '',\
95
35
               document.body.innerText.slice(0, 400)];",
96
35
            vec![json!(address)],
97
35
        )
98
35
        .await?;
99
35
    let shown = found[0].as_str().ok_or_else(|| {
100
        anyhow!(
101
            "no select control at {address}; the page reads {}",
102
            found[2]
103
        )
104
    })?;
105
35
    Ok((
106
35
        shown.to_string(),
107
35
        found[1].as_str().unwrap_or_default().to_string(),
108
35
    ))
109
35
}
110

            
111
/// The labels of the open suggestion list, without their secondary text.
112
343
async fn suggestions(h: &Harness) -> Result<Vec<String>> {
113
343
    let labels = h
114
343
        .driver
115
343
        .run(
116
343
            "return [...document.querySelectorAll('.autocomplete-results .autocomplete-item')]\
117
343
             .map(i => i.firstChild ? i.firstChild.textContent.trim() : '');",
118
343
            vec![],
119
343
        )
120
343
        .await?;
121
343
    Ok(labels
122
343
        .as_array()
123
343
        .map(|list| {
124
343
            list.iter()
125
359
                .map(|label| label.as_str().unwrap_or_default().to_string())
126
                .collect()
127
343
        })
128
        .unwrap_or_default())
129
343
}
130

            
131
/// Clicks suggestion `position`. The list re-renders when its options
132
/// arrive, which can make a just-found item stale; it is found again.
133
1
pub async fn click_suggestion(h: &Harness, position: usize) -> Result<()> {
134
1
    let mut attempts = 0;
135
    loop {
136
1
        let items = h
137
1
            .driver
138
1
            .find_all(".autocomplete-results .autocomplete-item")
139
1
            .await?;
140
1
        let item = items
141
1
            .get(position)
142
            .ok_or_else(|| anyhow!("suggestion {position} vanished"))?;
143
1
        match h.driver.click(item).await {
144
            Err(error) if attempts < 5 && error.to_string().contains("stale element") => {
145
                attempts += 1;
146
                tokio::time::sleep(Duration::from_millis(100)).await;
147
            }
148
1
            clicked => return clicked,
149
        }
150
    }
151
1
}
152

            
153
/// Clicks the suggestion labelled `label`. The list re-renders as options
154
/// arrive, so the item is looked up by its label again on every attempt,
155
/// never by an index read earlier.
156
167
async fn click_labelled(h: &Harness, label: &str) -> Result<()> {
157
167
    let deadline = Instant::now() + READY_DEADLINE;
158
    loop {
159
169
        let position = suggestions(h).await?.iter().position(|l| l == label);
160
167
        let items = h
161
167
            .driver
162
167
            .find_all(".autocomplete-results .autocomplete-item")
163
167
            .await?;
164
167
        if let Some(item) = position.and_then(|at| items.get(at)) {
165
167
            match h.driver.click(item).await {
166
                Err(error) if error.to_string().contains("stale element") => {}
167
167
                clicked => return clicked,
168
            }
169
        }
170
        if Instant::now() > deadline {
171
            bail!("suggestion {label:?} was not clickable");
172
        }
173
        tokio::time::sleep(Duration::from_millis(100)).await;
174
    }
175
167
}
176

            
177
/// Types `query` into the select cell at `address`, then picks the `nth`
178
/// suggestion `matches` accepts; returns the picked label.
179
176
pub async fn pick(
180
176
    h: &Harness,
181
176
    address: &str,
182
176
    query: &str,
183
176
    matches: impl Fn(&str) -> bool,
184
176
    nth: usize,
185
176
    how: Pick,
186
176
) -> Result<String> {
187
176
    let input = visible(h, address).await?;
188
176
    h.driver.click(&input).await?;
189
176
    h.driver.clear(&input).await?;
190
176
    h.driver.type_into(&input, query).await?;
191
176
    let deadline = Instant::now() + READY_DEADLINE;
192
    let (position, label) = loop {
193
176
        let labels = suggestions(h).await?;
194
176
        let found = labels
195
176
            .iter()
196
176
            .enumerate()
197
178
            .filter(|(_, label)| matches(label))
198
176
            .nth(nth);
199
176
        if let Some((position, label)) = found {
200
176
            break (position, label.clone());
201
        }
202
        if Instant::now() > deadline {
203
            bail!("no suggestion #{nth} for {query:?} at {address}: {labels:?}");
204
        }
205
        tokio::time::sleep(Duration::from_millis(100)).await;
206
    };
207
176
    match how {
208
167
        Pick::Mouse => click_labelled(h, &label).await?,
209
        Pick::Keyboard => {
210
9
            let keys = ARROW_DOWN.repeat(position) + ENTER;
211
9
            h.driver.type_into(&input, &keys).await?;
212
        }
213
    }
214
176
    Ok(label)
215
176
}
216

            
217
/// Replaces the text of the plain input or textarea named `name`.
218
89
pub async fn set_text(h: &Harness, name: &str, text: &str) -> Result<()> {
219
89
    let input = h.driver.find(&format!("[name=\"{name}\"]")).await?;
220
89
    h.driver.clear(&input).await?;
221
89
    h.driver.type_into(&input, text).await
222
89
}
223

            
224
/// Deletes the text of the select cell at `address` key by key, as a person does.
225
1
pub async fn erase(h: &Harness, address: &str) -> Result<()> {
226
1
    let input = visible(h, address).await?;
227
1
    h.driver.click(&input).await?;
228
1
    h.driver.type_into(&input, &BACKSPACE.repeat(16)).await
229
1
}
230

            
231
/// Chooses `value` in the select named `name`.
232
14
pub async fn choose(h: &Harness, name: &str, value: &str) -> Result<()> {
233
14
    let option = h
234
14
        .driver
235
14
        .find(&format!(
236
14
            "select[name=\"{name}\"] option[value=\"{value}\"]"
237
14
        ))
238
14
        .await?;
239
14
    h.driver.click(&option).await
240
14
}
241

            
242
25
pub async fn add_split(h: &Harness) -> Result<()> {
243
25
    let add = h
244
25
        .driver
245
25
        .find("fieldset[data-rows=\"splits\"] > button[data-rows-for$=\"-splits\"]")
246
25
        .await?;
247
25
    h.driver.click(&add).await
248
25
}
249

            
250
/// Adds a split tag to the split row `row` (0-based, in page order).
251
14
pub async fn add_split_tag(h: &Harness, row: usize) -> Result<()> {
252
14
    let groups = h
253
14
        .driver
254
14
        .find_all("fieldset[data-rows=\"splits\"] > .row-group")
255
14
        .await?;
256
14
    let group = groups
257
14
        .get(row)
258
        .ok_or_else(|| anyhow!("no split row {row}"))?;
259
14
    let add = h
260
14
        .driver
261
14
        .find_in(group, ".nested-rows > button[data-action=\"add-row\"]")
262
14
        .await?;
263
14
    h.driver.click(&add).await
264
14
}
265

            
266
/// Submits the page's form and returns the result box text once the reply
267
/// is shown, or the re-rendered form's errors if it came back invalid. The
268
/// form is marked first, so errors of an earlier reply never count.
269
36
pub async fn submit(h: &Harness) -> Result<String> {
270
36
    h.driver
271
36
        .run(
272
36
            "const form = document.querySelector('form.nomi-form');\
273
36
             form.setAttribute('data-e2e-pending', '');\
274
36
             const box = form.querySelector('.result-box'); if (box) box.textContent = '';",
275
36
            vec![],
276
36
        )
277
36
        .await?;
278
36
    let button = h
279
36
        .driver
280
36
        .find("form.nomi-form button[type=\"submit\"]")
281
36
        .await?;
282
36
    h.driver.click(&button).await?;
283
36
    let shown = wait_for(
284
36
        &h.driver,
285
36
        "const form = document.querySelector('form.nomi-form');\
286
36
         const box = form.querySelector('.result-box');\
287
36
         const text = box ? box.textContent.trim() : '';\
288
36
         if (form.hasAttribute('data-e2e-pending')) return text || null;\
289
36
         const errors = [...form.querySelectorAll('.field-error, .row-error, .form-banner')]\
290
36
           .map(e => e.textContent.trim()).filter(Boolean);\
291
36
         return 'INVALID: ' + errors.join(' | ');",
292
36
        vec![],
293
36
        "the submit reply",
294
36
    )
295
36
    .await?;
296
36
    Ok(shown.as_str().unwrap_or_default().to_string())
297
36
}
298

            
299
/// The id a "created with ID" or "updated with ID" reply names.
300
19
pub fn reply_id(reply: &str) -> Result<Uuid> {
301
19
    let id = reply.rsplit(' ').next().unwrap_or_default();
302
19
    Uuid::parse_str(id.trim()).with_context(|| format!("no id in reply {reply:?}"))
303
19
}
304

            
305
/// The exact texts of the buttons of the page's forms, in page order.
306
2
pub async fn button_texts(h: &Harness) -> Result<Vec<String>> {
307
2
    let texts = h
308
2
        .driver
309
2
        .run(
310
2
            "return [...document.querySelectorAll('form.nomi-form button')]\
311
2
             .filter(b => b.offsetParent !== null).map(b => b.textContent.trim());",
312
2
            vec![],
313
2
        )
314
2
        .await?;
315
2
    Ok(texts
316
2
        .as_array()
317
2
        .map(|list| {
318
2
            list.iter()
319
9
                .map(|text| text.as_str().unwrap_or_default().to_string())
320
                .collect()
321
2
        })
322
        .unwrap_or_default())
323
2
}