1
//! Helpers of the browser tests that drive the suggestion widget over the
2
//! rendered fixture with a stubbed `fetch`.
3

            
4
use nomisync_frontend::form_init::init_form;
5
use wasm_bindgen::{JsCast, JsValue};
6
use wasm_bindgen_futures::JsFuture;
7
use web_sys::{
8
    Element, Event, EventInit, HtmlFormElement, HtmlInputElement, KeyboardEvent, KeyboardEventInit,
9
};
10

            
11
pub const FIXTURE: &str = include_str!("../fixtures/transaction_edit.html");
12

            
13
const STUB: &str = r#"
14
(() => {
15
  if (window.__stubbed) return;
16
  window.__stubbed = true;
17
  window.__consumed = {};
18
  const accounts = [
19
    { id: "acc-a", label: "Assets:A", key: "Assets:A", alias: "A" },
20
    { id: "acc-w", label: "Assets:Wallet", key: "Assets:Wallet", alias: "Wallet", commodity: "com-eur" },
21
    { id: "acc-f", label: "Expenses:Food", key: "Expenses:Food" },
22
    { id: "acc-u", label: "Cash:Usd", key: "Cash:Usd", commodity: "com-usd" },
23
    { id: "acc-d1", label: "Dup", key: "Dup" },
24
    { id: "acc-d2", label: "Dup", key: "Dup" },
25
    { id: "acc-jr", label: "JR", key: "Transportation:JR", alias: "JR", path: "Transportation:JR" },
26
  ];
27
  const commodities = [
28
    { id: "com-usd", label: "USD", key: "USD", alias: "USD" },
29
    { id: "com-eur", label: "EUR", key: "EUR", alias: "EUR" },
30
  ];
31
  const data = {
32
    "/api/forms/options/accounts": accounts,
33
    "/api/forms/options/commodities": commodities,
34
    "/api/forms/suggestions/transaction-tag-names": [{ name: "category" }, { name: "mood" }],
35
    "/api/forms/suggestions/transaction-tag-values?name=category": [{ name: "food", value: "food" }],
36
    "/api/forms/suggestions/transaction-tag-values?name=mood": [{ name: "happy", value: "happy" }],
37
    "/api/forms/suggestions/transaction-tag-values?name=slow": [{ name: "slowval", value: "slowval" }],
38
    "/api/forms/suggestions/transaction-tag-values?name=stagger": [{ name: "staggered", value: "staggered" }],
39
    "/api/forms/suggestions/transaction-tag-values?name=fast": [{ name: "fastval", value: "fastval" }],
40
    "/api/forms/suggestions/transaction-tag-values?name=a%26b%23c%2B%25": [{ name: "special", value: "special" }],
41
    "/api/forms/suggestions/split-tag-names": [{ name: "memo" }],
42
    "/api/forms/suggestions/split-tag-values?name=memo": [{ name: "lunch", value: "lunch" }],
43
  };
44
  window.fetch = (request) => {
45
    const url = new URL(request.url);
46
    const key = url.pathname + url.search;
47
    const body = data[key];
48
    const stagger = key.endsWith("name=stagger") ? (window.__staggered = (window.__staggered ?? -1) + 1) : 0;
49
    const delay = key.endsWith("name=slow") ? 300 : stagger * 200;
50
    const reply = body === undefined
51
      ? new Response("missing", { status: 404 })
52
      : new Response(JSON.stringify(body), { status: 200 });
53
    const text = reply.text.bind(reply);
54
    reply.text = async () => {
55
      const read = await text();
56
      setTimeout(() => { window.__consumed[key] = (window.__consumed[key] ?? 0) + 1; }, 0);
57
      return read;
58
    };
59
    return new Promise((resolve) => setTimeout(() => resolve(reply), delay));
60
  };
61
})()
62
"#;
63

            
64
pub fn stub_fetch() -> Result<(), JsValue> {
65
    js_sys::eval(STUB).map(drop)
66
}
67

            
68
pub fn mount(html: &str) -> Result<(Element, HtmlFormElement), JsValue> {
69
    stub_fetch()?;
70
    let document = web_sys::window()
71
        .and_then(|w| w.document())
72
        .ok_or("no document")?;
73
    let host = document.create_element("div")?;
74
    host.set_inner_html(html);
75
    document.body().ok_or("no body")?.append_child(&host)?;
76
    let form: HtmlFormElement = find(&host, "form")?.dyn_into()?;
77
    init_form(&form)?;
78
    Ok((host, form))
79
}
80

            
81
pub fn find(root: &Element, selector: &str) -> Result<Element, JsValue> {
82
    root.query_selector(selector)?
83
        .ok_or_else(|| JsValue::from_str(selector))
84
}
85

            
86
/// The control a person types into at `name`: a select cell's visible
87
/// `label:` control, else the input named `name`.
88
pub fn cell(form: &HtmlFormElement, name: &str) -> Result<HtmlInputElement, JsValue> {
89
    let visible = form.query_selector(&format!("input[name=\"label:{name}\"]"))?;
90
    match visible {
91
        Some(visible) => Ok(visible.dyn_into()?),
92
        None => Ok(find(form, &format!("input[name=\"{name}\"]"))?.dyn_into()?),
93
    }
94
}
95

            
96
/// The hidden input carrying the reference of the select cell `name`.
97
pub fn reference(form: &HtmlFormElement, name: &str) -> Result<HtmlInputElement, JsValue> {
98
    Ok(find(form, &format!("input[type=\"hidden\"][name=\"{name}\"]"))?.dyn_into()?)
99
}
100

            
101
/// Point the select cell `name` at `id`, shown as `label`.
102
pub fn set_reference(
103
    form: &HtmlFormElement,
104
    name: &str,
105
    label: &str,
106
    id: &str,
107
) -> Result<(), JsValue> {
108
    reference(form, name)?.set_value(id);
109
    cell(form, name)?.set_value(label);
110
    Ok(())
111
}
112

            
113
pub fn fire(target: &Element, name: &str) -> Result<(), JsValue> {
114
    let init = EventInit::new();
115
    init.set_bubbles(true);
116
    target.dispatch_event(&Event::new_with_event_init_dict(name, &init)?)?;
117
    Ok(())
118
}
119

            
120
pub fn focus(input: &HtmlInputElement) -> Result<(), JsValue> {
121
    fire(input, "focusin")
122
}
123

            
124
pub fn type_text(input: &HtmlInputElement, text: &str) -> Result<(), JsValue> {
125
    input.set_value(text);
126
    fire(input, "input")
127
}
128

            
129
pub fn press(input: &HtmlInputElement, key: &str) -> Result<(), JsValue> {
130
    let init = KeyboardEventInit::new();
131
    init.set_bubbles(true);
132
    init.set_cancelable(true);
133
    init.set_key(key);
134
    let event = KeyboardEvent::new_with_keyboard_event_init_dict("keydown", &init)?;
135
    input.dispatch_event(&event)?;
136
    Ok(())
137
}
138

            
139
pub async fn tick() -> Result<(), JsValue> {
140
    sleep(20).await
141
}
142

            
143
pub async fn sleep(ms: u32) -> Result<(), JsValue> {
144
    let promise = js_sys::eval(&format!("new Promise(r => setTimeout(r, {ms}))"))?;
145
    JsFuture::from(promise.dyn_into::<js_sys::Promise>()?).await?;
146
    Ok(())
147
}
148

            
149
const WAIT_MS: f64 = 10_000.0;
150

            
151
/// Wait until `check` holds, up to ten seconds.
152
pub async fn until(mut check: impl FnMut() -> bool) -> Result<(), JsValue> {
153
    let deadline = js_sys::Date::now() + WAIT_MS;
154
    while !check() {
155
        if js_sys::Date::now() > deadline {
156
            return Err(JsValue::from_str("condition not reached"));
157
        }
158
        tick().await?;
159
    }
160
    Ok(())
161
}
162

            
163
/// The suggestions listed under `input`.
164
pub fn shown(input: &HtmlInputElement) -> Vec<String> {
165
    let Some(label) = input.parent_element() else {
166
        return Vec::new();
167
    };
168
    let items = label
169
        .query_selector_all(".autocomplete-results .autocomplete-item")
170
        .ok();
171
    items.map_or_else(Vec::new, |list| {
172
        (0..list.length())
173
            .filter_map(|i| list.item(i)?.text_content())
174
            .collect()
175
    })
176
}
177

            
178
/// Open the list of `input` and wait for its suggestions.
179
pub async fn open(input: &HtmlInputElement, text: &str) -> Result<(), JsValue> {
180
    input.set_value(text);
181
    focus(input)?;
182
    until(|| !shown(input).is_empty()).await
183
}