1
//! Account and commodity fills over the rendered fixture; each fill must
2
//! reach the form's listeners so the converted amount re-evaluates.
3

            
4
mod common;
5

            
6
use common::{FIXTURE, cell, find, mount, open, press, set_reference, until};
7
use nomisync_frontend::form_init;
8
use nomisync_frontend::htmx::setup_htmx_validation;
9
use wasm_bindgen::prelude::*;
10
use wasm_bindgen_futures::JsFuture;
11
use wasm_bindgen_test::*;
12
use web_sys::{CustomEvent, Element, HtmlFormElement};
13

            
14
wasm_bindgen_test_configure!(run_in_browser);
15

            
16
fn clear(form: &HtmlFormElement, names: &[&str]) -> Result<(), JsValue> {
17
    names
18
        .iter()
19
        .try_for_each(|name| set_reference(form, name, "", ""))
20
}
21

            
22
fn to_amount_hidden(form: &HtmlFormElement, row: usize) -> Result<bool, JsValue> {
23
    let input = cell(form, &format!("splits.{row}.to-amount"))?;
24
    Ok(input.disabled())
25
}
26

            
27
#[wasm_bindgen_test]
28
async fn an_account_fills_an_empty_from_commodity_and_to_amount_reappears() -> Result<(), JsValue> {
29
    let (host, form) = mount(FIXTURE)?;
30
    clear(&form, &["splits.1.from", "splits.1.from-commodity"])?;
31
    set_reference(&form, "splits.1.to-commodity", "USD", "com-usd")?;
32
    form.dispatch_event(&web_sys::Event::new("change")?)?;
33
    let from = cell(&form, "splits.1.from")?;
34
    let commodity = cell(&form, "splits.1.from-commodity")?;
35

            
36
    open(&from, "wallet").await?;
37
    press(&from, "Enter")?;
38
    until(|| commodity.value() == "EUR").await?;
39

            
40
    assert!(!to_amount_hidden(&form, 1)?);
41
    host.remove();
42
    Ok(())
43
}
44

            
45
#[wasm_bindgen_test]
46
async fn an_account_never_overwrites_a_filled_commodity() -> Result<(), JsValue> {
47
    let (host, form) = mount(FIXTURE)?;
48
    let from = cell(&form, "splits.1.from")?;
49
    let commodity = cell(&form, "splits.1.from-commodity")?;
50
    assert_eq!(commodity.value(), "USD");
51

            
52
    open(&from, "wallet").await?;
53
    press(&from, "Enter")?;
54
    common::tick().await?;
55
    common::tick().await?;
56

            
57
    assert_eq!(from.value(), "Assets:Wallet");
58
    assert_eq!(commodity.value(), "USD");
59
    host.remove();
60
    Ok(())
61
}
62

            
63
#[wasm_bindgen_test]
64
async fn a_typed_account_does_not_fill() -> Result<(), JsValue> {
65
    let (host, form) = mount(FIXTURE)?;
66
    clear(&form, &["splits.1.from", "splits.1.from-commodity"])?;
67
    let from = cell(&form, "splits.1.from")?;
68

            
69
    common::type_text(&from, "wallet")?;
70
    common::fire(&from, "change")?;
71
    common::tick().await?;
72

            
73
    assert_eq!(cell(&form, "splits.1.from-commodity")?.value(), "");
74
    host.remove();
75
    Ok(())
76
}
77

            
78
#[wasm_bindgen_test]
79
async fn a_commodity_fills_an_empty_to_commodity() -> Result<(), JsValue> {
80
    let (host, form) = mount(FIXTURE)?;
81
    clear(&form, &["splits.1.from-commodity", "splits.1.to-commodity"])?;
82
    let from = cell(&form, "splits.1.from-commodity")?;
83
    let to = cell(&form, "splits.1.to-commodity")?;
84

            
85
    open(&from, "EUR").await?;
86
    press(&from, "Enter")?;
87
    until(|| to.value() == "EUR").await?;
88

            
89
    host.remove();
90
    Ok(())
91
}
92

            
93
#[wasm_bindgen_test]
94
async fn a_commodity_never_overwrites_a_filled_to_commodity() -> Result<(), JsValue> {
95
    let (host, form) = mount(FIXTURE)?;
96
    clear(&form, &["splits.1.from-commodity"])?;
97
    set_reference(&form, "splits.1.to-commodity", "USD", "com-usd")?;
98
    let from = cell(&form, "splits.1.from-commodity")?;
99

            
100
    open(&from, "EUR").await?;
101
    press(&from, "Enter")?;
102
    common::tick().await?;
103
    common::tick().await?;
104

            
105
    assert_eq!(from.value(), "EUR");
106
    assert_eq!(cell(&form, "splits.1.to-commodity")?.value(), "USD");
107
    host.remove();
108
    Ok(())
109
}
110

            
111
#[wasm_bindgen_test]
112
async fn an_account_fills_the_to_commodity_through_the_from_commodity() -> Result<(), JsValue> {
113
    let (host, form) = mount(FIXTURE)?;
114
    clear(
115
        &form,
116
        &[
117
            "splits.1.from",
118
            "splits.1.from-commodity",
119
            "splits.1.to-commodity",
120
        ],
121
    )?;
122
    let from = cell(&form, "splits.1.from")?;
123
    let to = cell(&form, "splits.1.to-commodity")?;
124

            
125
    open(&from, "wallet").await?;
126
    press(&from, "Enter")?;
127
    until(|| to.value() == "EUR").await?;
128

            
129
    host.remove();
130
    Ok(())
131
}
132

            
133
#[wasm_bindgen_test]
134
async fn a_repick_moves_a_filled_to_commodity() -> Result<(), JsValue> {
135
    let (host, form) = mount(FIXTURE)?;
136
    clear(&form, &["splits.1.from-commodity", "splits.1.to-commodity"])?;
137
    let from = cell(&form, "splits.1.from-commodity")?;
138
    let to = cell(&form, "splits.1.to-commodity")?;
139

            
140
    open(&from, "EUR").await?;
141
    press(&from, "Enter")?;
142
    until(|| to.value() == "EUR").await?;
143
    open(&from, "USD").await?;
144
    press(&from, "Enter")?;
145
    until(|| to.value() == "USD").await?;
146

            
147
    host.remove();
148
    Ok(())
149
}
150

            
151
#[wasm_bindgen_test]
152
async fn a_picked_to_commodity_stays_after_a_repick() -> Result<(), JsValue> {
153
    let (host, form) = mount(FIXTURE)?;
154
    clear(&form, &["splits.1.from-commodity", "splits.1.to-commodity"])?;
155
    let from = cell(&form, "splits.1.from-commodity")?;
156
    let to = cell(&form, "splits.1.to-commodity")?;
157

            
158
    open(&to, "USD").await?;
159
    press(&to, "Enter")?;
160
    open(&from, "EUR").await?;
161
    press(&from, "Enter")?;
162
    common::tick().await?;
163
    common::tick().await?;
164

            
165
    assert_eq!(from.value(), "EUR");
166
    assert_eq!(to.value(), "USD");
167
    host.remove();
168
    Ok(())
169
}
170

            
171
#[wasm_bindgen_test]
172
async fn a_repicked_multi_commodity_account_clears_the_fills() -> Result<(), JsValue> {
173
    let (host, form) = mount(FIXTURE)?;
174
    clear(
175
        &form,
176
        &[
177
            "splits.1.from",
178
            "splits.1.from-commodity",
179
            "splits.1.to-commodity",
180
        ],
181
    )?;
182
    let from = cell(&form, "splits.1.from")?;
183
    let commodity = cell(&form, "splits.1.from-commodity")?;
184
    let to = cell(&form, "splits.1.to-commodity")?;
185

            
186
    open(&from, "wallet").await?;
187
    press(&from, "Enter")?;
188
    until(|| to.value() == "EUR").await?;
189
    open(&from, "Food").await?;
190
    press(&from, "Enter")?;
191
    until(|| commodity.value().is_empty() && to.value().is_empty()).await?;
192

            
193
    host.remove();
194
    Ok(())
195
}
196

            
197
const HTMX: &str = include_str!("../../static/scripts/htmx.min.js");
198

            
199
const FAKE_XHR: &str = r##"
200
(() => {
201
  const Real = window.XMLHttpRequest;
202
  window.XMLHttpRequest = class extends Real {
203
    open() {}
204
    setRequestHeader() {}
205
    send() {
206
      const body = window.__reply;
207
      const props = { status: 422, response: body, responseText: body, responseURL: location.href };
208
      for (const [key, value] of Object.entries(props)) {
209
        Object.defineProperty(this, key, { value });
210
      }
211
      const headers = { "content-type": "text/html", "hx-retarget": "#nf-demo", "hx-reswap": "outerHTML" };
212
      this.getAllResponseHeaders = () =>
213
        Object.entries(headers).map(([k, v]) => `${k}: ${v}\r\n`).join("");
214
      this.getResponseHeader = (name) => headers[name.toLowerCase()] ?? null;
215
      setTimeout(() => this.onload(), 0);
216
    }
217
  };
218
})()
219
"##;
220

            
221
const DEMO: &str = r#"<form id="nf-demo" class="nomi-form" hx-post="/demo" hx-swap="outerHTML"><div data-row="splits"><label class="field"><input type="text" name="splits.0.from" value="" data-source="accounts" autocomplete="off" /></label></div></form>"#;
222

            
223
fn global_eval(source: &str) -> Result<JsValue, JsValue> {
224
    js_sys::Function::new_with_args("src", "return (0, eval)(src)")
225
        .call1(&JsValue::NULL, &source.into())
226
}
227

            
228
fn demo_form(host: &Element) -> Result<HtmlFormElement, JsValue> {
229
    Ok(find(host, "form")?.dyn_into()?)
230
}
231

            
232
/// Wires its own `htmx:afterSwap` listener around `form_init::init_all`, as the
233
/// production one does; it does not exercise `setup_htmx_listener` itself.
234
/// W5/W6 must pin the production listener, per the plan.
235
#[wasm_bindgen_test]
236
async fn a_422_swap_initialises_the_new_form_once() -> Result<(), JsValue> {
237
    global_eval(HTMX)?;
238
    global_eval(FAKE_XHR)?;
239
    setup_htmx_validation();
240
    common::stub_fetch()?;
241
    let document = web_sys::window()
242
        .and_then(|w| w.document())
243
        .ok_or("no document")?;
244
    let after_swap = Closure::<dyn FnMut()>::new(form_init::init_all);
245
    document
246
        .add_event_listener_with_callback("htmx:afterSwap", after_swap.as_ref().unchecked_ref())?;
247
    let host = document.create_element("div")?;
248
    host.set_inner_html(DEMO);
249
    document.body().ok_or("no body")?.append_child(&host)?;
250
    global_eval("htmx.process")?
251
        .dyn_into::<js_sys::Function>()?
252
        .call1(&JsValue::NULL, &host)?;
253
    form_init::init_all();
254
    global_eval(&format!(
255
        "window.__reply = {}",
256
        serde_json::to_string(DEMO).map_err(|e| e.to_string())?
257
    ))?;
258

            
259
    let promise = js_sys::eval(
260
        "new Promise(r => document.addEventListener('htmx:afterSwap', r, { once: true }))",
261
    )?;
262
    let done = JsFuture::from(promise.dyn_into::<js_sys::Promise>()?);
263
    let old = demo_form(&host)?;
264
    common::fire(&old, "submit")?;
265
    done.await?;
266
    let fresh = demo_form(&host)?;
267
    assert!(!JsValue::from(&fresh).loose_eq(&JsValue::from(&old)));
268
    form_init::init_all();
269
    form_init::init_all();
270

            
271
    let from = cell(&fresh, "splits.0.from")?;
272
    open(&from, "wallet").await?;
273
    press(&from, "Enter")?;
274
    assert_eq!(from.value(), "Assets:Wallet");
275
    let popups = fresh.query_selector_all(".autocomplete-results")?;
276
    assert_eq!(popups.length(), 1);
277
    document.remove_event_listener_with_callback(
278
        "htmx:afterSwap",
279
        after_swap.as_ref().unchecked_ref(),
280
    )?;
281
    host.remove();
282
    Ok(())
283
}
284

            
285
fn request_parameters(form: &web_sys::HtmlFormElement) -> Result<js_sys::Object, JsValue> {
286
    let parameters = js_sys::Object::new();
287
    let detail = js_sys::Object::new();
288
    js_sys::Reflect::set(&detail, &"parameters".into(), &parameters)?;
289
    let event = CustomEvent::new("htmx:configRequest")?;
290
    event.init_custom_event_with_can_bubble_and_cancelable_and_detail(
291
        "htmx:configRequest",
292
        true,
293
        true,
294
        &detail,
295
    );
296
    form.dispatch_event(&event)?;
297
    Ok(parameters)
298
}
299

            
300
#[wasm_bindgen_test]
301
fn a_request_carries_the_marks_of_the_filled_cells_only() -> Result<(), JsValue> {
302
    let (host, form) = mount(FIXTURE)?;
303
    cell(&form, "splits.1.to-commodity")?.set_attribute("data-filled", "")?;
304
    let copied = cell(&form, "splits.0.to-commodity")?;
305
    copied.set_attribute("data-filled", "")?;
306
    copied.set_attribute("data-copied", "")?;
307

            
308
    let parameters = request_parameters(&form)?;
309

            
310
    let marks: Vec<(String, String)> = js_sys::Object::entries(&parameters)
311
        .iter()
312
        .filter_map(|entry| {
313
            let pair = js_sys::Array::from(&entry);
314
            Some((pair.get(0).as_string()?, pair.get(1).as_string()?))
315
        })
316
        .collect();
317
    let expected = [
318
        ("filled:splits.0.to-commodity", "copied"),
319
        ("filled:splits.1.to-commodity", ""),
320
    ];
321
    assert_eq!(marks, expected.map(|(n, v)| (n.to_string(), v.to_string())));
322
    host.remove();
323
    Ok(())
324
}