1
//! What every page must satisfy: no console error, no failed request, the
2
//! stylesheets applied and the form rows laid out as one clean grid, at
3
//! desktop and phone width. Each check also leaves a screenshot of both.
4

            
5
use anyhow::{Result, bail};
6
use serde_json::{Value, json};
7

            
8
use super::harness::Harness;
9
use super::page::{DESKTOP, PHONE};
10

            
11
/// Layout problems of the forms on the page, as text; `wide` adds the
12
/// one-line-per-row rules that only hold at desktop width.
13
const LAYOUT: &str = r#"
14
const wide = arguments[0];
15
const problems = [];
16
const shown = e => e.offsetParent !== null || getComputedStyle(e).position === 'fixed';
17
const near = (a, b) => Math.abs(a - b) <= 2;
18
const root = document.documentElement;
19
if (root.scrollWidth > root.clientWidth + 1) {
20
  problems.push(`page overflows: ${root.scrollWidth} > ${root.clientWidth}`);
21
}
22
for (const form of document.querySelectorAll('form.nomi-form')) {
23
  const field = [...form.querySelectorAll('.field')].find(shown);
24
  if (field && getComputedStyle(field).display !== 'flex') {
25
    problems.push(`${form.id}: form.css not applied`);
26
  }
27
  const columns = new Map();
28
  for (const row of form.querySelectorAll('.form-row')) {
29
    if (!shown(row)) continue;
30
    const kind = row.dataset.row;
31
    if (getComputedStyle(row).display !== 'grid') problems.push(`${kind} row is not a grid`);
32
    const controls = [...row.querySelectorAll(':scope > label input:not([type=hidden]), \
33
      :scope > label select, :scope > label textarea')].filter(shown);
34
    const button = row.querySelector(':scope > button[data-action="remove-row"]');
35
    const rowBox = row.getBoundingClientRect();
36
    for (const control of controls) {
37
      const box = control.getBoundingClientRect();
38
      if (box.right > rowBox.right + 1 || box.left < rowBox.left - 1) {
39
        problems.push(`${kind}: a control leaves its row`);
40
      }
41
    }
42
    if (!wide || controls.length === 0) continue;
43
    const first = controls[0].getBoundingClientRect();
44
    for (const control of controls) {
45
      const box = control.getBoundingClientRect();
46
      if (!near(box.top, first.top) || !near(box.bottom, first.bottom)) {
47
        problems.push(`${kind}: ${control.name} is off the row line (${box.top} vs ${first.top})`);
48
      }
49
    }
50
    if (button) {
51
      const box = button.getBoundingClientRect();
52
      if (!near(box.top, first.top) || !near(box.bottom, first.bottom)) {
53
        problems.push(`${kind}: remove button ${box.top}-${box.bottom} vs inputs ${first.top}-${first.bottom}`);
54
      }
55
    }
56
    const cells = [...row.querySelectorAll(':scope > label')].filter(shown)
57
      .map(l => [l.dataset.cell || (l.querySelector('[name]') || {name: '?'}).name.split('.').pop(),
58
                 l.getBoundingClientRect().left]);
59
    if (button) cells.push(['remove', button.getBoundingClientRect().left]);
60
    for (const [cell, left] of cells) {
61
      const key = `${kind}/${cell}`;
62
      if (!columns.has(key)) columns.set(key, left);
63
      else if (!near(columns.get(key), left)) {
64
        problems.push(`${key} column moves: ${columns.get(key)} vs ${left}`);
65
      }
66
    }
67
  }
68
  if (!wide) continue;
69
  const aligned = [['splits/from', ['split-tags/name', 'tags/name']],
70
                   ['splits/to', ['split-tags/value', 'tags/value']],
71
                   ['splits/from-commodity', ['split-tags/description', 'tags/description']],
72
                   ['splits/to-commodity', ['split-tags/side']],
73
                   ['splits/remove', ['split-tags/remove', 'tags/remove']]];
74
  for (const [anchor, followers] of aligned) {
75
    if (!columns.has(anchor)) continue;
76
    for (const follower of followers) {
77
      if (columns.has(follower) && !near(columns.get(anchor), columns.get(follower))) {
78
        problems.push(`${follower} is not under ${anchor}: ${columns.get(follower)} vs ${columns.get(anchor)}`);
79
      }
80
    }
81
  }
82
}
83
return problems;
84
"#;
85

            
86
/// Requests of this page that answered 4xx or 5xx.
87
const FAILED: &str = r#"
88
return performance.getEntries()
89
  .filter(e => (e.responseStatus || 0) >= 400)
90
  .map(e => `${e.responseStatus} ${e.name}`);
91
"#;
92

            
93
105
fn strings(value: &Value) -> Vec<String> {
94
105
    value
95
105
        .as_array()
96
105
        .map(|list| {
97
105
            list.iter()
98
5
                .map(|item| item.as_str().unwrap_or_default().to_string())
99
                .collect()
100
105
        })
101
        .unwrap_or_default()
102
105
}
103

            
104
/// The console errors since the last check, apart from those naming one of
105
/// `expected` (a status a scenario provokes on purpose).
106
70
async fn console_errors(h: &Harness, expected: &[u16]) -> Result<Vec<String>> {
107
70
    let entries = h.driver.log().await?;
108
70
    Ok(entries
109
70
        .iter()
110
8
        .filter(|entry| entry["level"] == json!("SEVERE"))
111
8
        .map(|entry| entry["message"].as_str().unwrap_or_default().to_string())
112
8
        .filter(|message| {
113
8
            !expected.iter().any(|status| {
114
8
                message.contains(&format!("status of {status}"))
115
3
                    || message.contains(&format!("Error Code {status} "))
116
8
            })
117
8
        })
118
        .collect())
119
70
}
120

            
121
35
async fn failed_requests(h: &Harness, expected: &[u16]) -> Result<Vec<String>> {
122
35
    let failed = strings(&h.driver.run(FAILED, vec![]).await?);
123
35
    Ok(failed
124
35
        .into_iter()
125
5
        .filter(|line| !expected.iter().any(|s| line.starts_with(&format!("{s} "))))
126
        .collect())
127
35
}
128

            
129
70
async fn layout(h: &Harness, wide: bool) -> Result<Vec<String>> {
130
70
    Ok(strings(&h.driver.run(LAYOUT, vec![json!(wide)]).await?))
131
70
}
132

            
133
70
async fn shoot(h: &Harness, name: &str) -> Result<()> {
134
70
    let png = h.driver.screenshot().await?;
135
70
    std::fs::write(h.shots.join(format!("{name}.png")), png)?;
136
70
    Ok(())
137
70
}
138

            
139
/// Checks the page now shown and saves `<name>-desktop.png` and
140
/// `<name>-phone.png`; `expected` statuses are provoked by the scenario.
141
35
pub async fn check_page(h: &Harness, name: &str, expected: &[u16]) -> Result<()> {
142
35
    let mut problems = Vec::new();
143
35
    problems.extend(console_errors(h, expected).await?);
144
35
    problems.extend(failed_requests(h, expected).await?);
145
35
    problems.extend(layout(h, true).await?);
146
35
    shoot(h, &format!("{name}-desktop")).await?;
147
35
    h.driver.set_size(PHONE.0, PHONE.1).await?;
148
35
    problems.extend(
149
35
        layout(h, false)
150
35
            .await?
151
            .into_iter()
152
            .map(|p| format!("phone: {p}")),
153
    );
154
35
    shoot(h, &format!("{name}-phone")).await?;
155
35
    h.driver.set_size(DESKTOP.0, DESKTOP.1).await?;
156
35
    problems.extend(console_errors(h, expected).await?);
157
35
    match problems.is_empty() {
158
35
        true => Ok(()),
159
        false => bail!("{name}: {}", problems.join("\n  ")),
160
    }
161
35
}