1
// -- -*- mode: rust -*-
2
//! Real htmx events against a faked XHR: a failed request from a form whose
3
//! `hx-target` is an outer panel with `hx-swap="outerHTML"` must put the error
4
//! inside the form's result box and leave the panel intact, repeatedly.
5

            
6
use nomisync_frontend::htmx::setup_htmx_validation;
7
use wasm_bindgen::{JsCast, JsValue};
8
use wasm_bindgen_futures::JsFuture;
9
use wasm_bindgen_test::*;
10
use web_sys::Element;
11

            
12
wasm_bindgen_test_configure!(run_in_browser);
13

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

            
16
const FAKE_XHR: &str = r#"
17
(() => {
18
  const Real = window.XMLHttpRequest;
19
  window.XMLHttpRequest = class extends Real {
20
    open() {}
21
    setRequestHeader() {}
22
    send() {
23
      const body = '<div class="error-alert">bad input</div>';
24
      const props = {
25
        status: 422,
26
        response: body,
27
        responseText: body,
28
        responseURL: location.href,
29
      };
30
      for (const [key, value] of Object.entries(props)) {
31
        Object.defineProperty(this, key, { value });
32
      }
33
      this.getAllResponseHeaders = () => "content-type: text/html\r\n";
34
      this.getResponseHeader = (name) =>
35
        name.toLowerCase() === "content-type" ? "text/html" : null;
36
      setTimeout(() => this.onload(), 0);
37
    }
38
  };
39
})()
40
"#;
41

            
42
fn global_eval(source: &str) -> Result<JsValue, JsValue> {
43
    js_sys::Function::new_with_args("src", "return (0, eval)(src)")
44
        .call1(&JsValue::NULL, &source.into())
45
}
46

            
47
fn swapped() -> Result<JsFuture, JsValue> {
48
    let promise = js_sys::eval(
49
        "new Promise(r => document.addEventListener('htmx:afterSwap', r, { once: true }))",
50
    )?;
51
    Ok(JsFuture::from(promise.dyn_into::<js_sys::Promise>()?))
52
}
53

            
54
async fn fail_once(form: &Element) -> Result<(), JsValue> {
55
    let done = swapped()?;
56
    let init = web_sys::EventInit::new();
57
    init.set_bubbles(true);
58
    init.set_cancelable(true);
59
    form.dispatch_event(&web_sys::Event::new_with_event_init_dict("submit", &init)?)?;
60
    done.await?;
61
    Ok(())
62
}
63

            
64
#[wasm_bindgen_test]
65
async fn failed_form_request_lands_in_its_result_box() -> Result<(), JsValue> {
66
    global_eval(HTMX)?;
67
    global_eval(FAKE_XHR)?;
68
    setup_htmx_validation();
69

            
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(
75
        r##"<div id="panel"><form hx-post="/fail" hx-target="#panel" hx-swap="outerHTML">
76
        <div class="result-box"></div></form></div>"##,
77
    );
78
    document.body().ok_or("no body")?.append_child(&host)?;
79
    global_eval("htmx.process")?
80
        .dyn_into::<js_sys::Function>()?
81
        .call1(&JsValue::NULL, &host)?;
82

            
83
    let form = host.query_selector("form")?.ok_or("form missing")?;
84
    for _ in 0..2 {
85
        fail_once(&form).await?;
86
        let panel = host.query_selector("#panel")?.ok_or("panel replaced")?;
87
        let result_box = panel
88
            .query_selector("form .result-box")?
89
            .ok_or("result box replaced")?;
90
        assert!(result_box.inner_html().contains("bad input"));
91
        assert!(result_box.class_list().contains("error-message"));
92
    }
93
    host.remove();
94
    Ok(())
95
}