1
// -- -*- mode: rust -*-
2
//! An error redirected into a form's result box must replace the box's
3
//! contents, not the box, whatever the form's own hx-swap says. A response
4
//! carrying `HX-Retarget` (the 422 form re-render) is swapped by htmx itself.
5

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

            
13
wasm_bindgen_test_configure!(run_in_browser);
14

            
15
#[wasm_bindgen_test]
16
fn retarget_swaps_the_box_contents() -> Result<(), JsValue> {
17
    let document = web_sys::window()
18
        .and_then(|w| w.document())
19
        .ok_or("no document")?;
20
    let result_box = document.create_element("div")?;
21
    let detail = js_sys::Object::new();
22
    js_sys::Reflect::set(&detail, &"swapOverride".into(), &"outerHTML".into())?;
23

            
24
    retarget_to_box(&detail, &result_box);
25

            
26
    let target = js_sys::Reflect::get(&detail, &"target".into())?;
27
    assert!(target.loose_eq(&result_box));
28
    assert_eq!(
29
        js_sys::Reflect::get(&detail, &"swapOverride".into())?.as_string(),
30
        Some("innerHTML".to_string())
31
    );
32
    Ok(())
33
}
34

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

            
37
// Each send() answers with the next `window.__replies` entry.
38
const FAKE_XHR: &str = r#"
39
(() => {
40
  window.__replies = [];
41
  const Real = window.XMLHttpRequest;
42
  window.XMLHttpRequest = class extends Real {
43
    open() {}
44
    setRequestHeader() {}
45
    send() {
46
      const { status, headers, body } = window.__replies.shift();
47
      const props = { status, response: body, responseText: body, responseURL: location.href };
48
      for (const [key, value] of Object.entries(props)) {
49
        Object.defineProperty(this, key, { value });
50
      }
51
      const lower = { "content-type": "text/html", ...headers };
52
      this.getAllResponseHeaders = () =>
53
        Object.entries(lower).map(([k, v]) => `${k}: ${v}\r\n`).join("");
54
      this.getResponseHeader = (name) => lower[name.toLowerCase()] ?? null;
55
      setTimeout(() => this.onload(), 0);
56
    }
57
  };
58
})()
59
"#;
60

            
61
const FORM_ATTRS: &str = r##"id="nf-demo" class="nomi-form" hx-post="/demo" hx-swap="outerHTML""##;
62

            
63
fn global_eval(source: &str) -> Result<JsValue, JsValue> {
64
    js_sys::Function::new_with_args("src", "return (0, eval)(src)")
65
        .call1(&JsValue::NULL, &source.into())
66
}
67

            
68
fn setup() -> Result<(), JsValue> {
69
    if !global_eval("typeof htmx !== 'undefined'")?
70
        .as_bool()
71
        .unwrap_or(false)
72
    {
73
        global_eval(HTMX)?;
74
        global_eval(FAKE_XHR)?;
75
        setup_htmx_validation();
76
    }
77
    Ok(())
78
}
79

            
80
fn reply(status: u16, headers: &str, body: &str) -> Result<(), JsValue> {
81
    let body = serde_json::to_string(body).map_err(|e| e.to_string())?;
82
    global_eval(&format!(
83
        "window.__replies.push({{ status: {status}, headers: {headers}, body: {body} }})"
84
    ))?;
85
    Ok(())
86
}
87

            
88
fn mount(html: &str) -> Result<Element, JsValue> {
89
    let document = web_sys::window()
90
        .and_then(|w| w.document())
91
        .ok_or("no document")?;
92
    let host = document.create_element("div")?;
93
    host.set_inner_html(html);
94
    document.body().ok_or("no body")?.append_child(&host)?;
95
    global_eval("htmx.process")?
96
        .dyn_into::<js_sys::Function>()?
97
        .call1(&JsValue::NULL, &host)?;
98
    Ok(host)
99
}
100

            
101
async fn submit(form: &Element) -> Result<(), JsValue> {
102
    let promise = js_sys::eval(
103
        "new Promise(r => document.addEventListener('htmx:afterSettle', r, { once: true }))",
104
    )?;
105
    let done = JsFuture::from(promise.dyn_into::<js_sys::Promise>()?);
106
    let init = web_sys::EventInit::new();
107
    init.set_bubbles(true);
108
    init.set_cancelable(true);
109
    form.dispatch_event(&web_sys::Event::new_with_event_init_dict("submit", &init)?)?;
110
    done.await?;
111
    Ok(())
112
}
113

            
114
#[wasm_bindgen_test]
115
async fn retargeted_422_swaps_the_form_not_the_result_box() -> Result<(), JsValue> {
116
    setup()?;
117
    let host = mount(&format!(
118
        r#"<form {FORM_ATTRS}><div class="result-box"></div><input name="a"></form>"#
119
    ))?;
120
    reply(
121
        422,
122
        r##"{"hx-retarget": "#nf-demo", "hx-reswap": "outerHTML"}"##,
123
        r#"<form id="nf-demo" class="nomi-form"><p class="banner">fix it</p><div class="result-box"></div></form>"#,
124
    )?;
125

            
126
    let form = host.query_selector("form")?.ok_or("form missing")?;
127
    submit(&form).await?;
128

            
129
    let fresh = host
130
        .query_selector("form")?
131
        .ok_or("form replaced by nothing")?;
132
    assert!(!fresh.loose_eq(&form));
133
    assert!(fresh.query_selector(".banner")?.is_some());
134
    let result_box = fresh.query_selector(".result-box")?.ok_or("no box")?;
135
    assert_eq!(result_box.inner_html(), "");
136
    assert!(!result_box.class_list().contains("error-message"));
137
    host.remove();
138
    Ok(())
139
}
140

            
141
#[wasm_bindgen_test]
142
async fn error_without_retarget_still_lands_in_the_result_box() -> Result<(), JsValue> {
143
    setup()?;
144
    let host = mount(&format!(
145
        r#"<form {FORM_ATTRS}><div class="result-box"></div></form>"#
146
    ))?;
147
    reply(422, "{}", r#"<div class="error-alert">plain error</div>"#)?;
148

            
149
    let form = host.query_selector("form")?.ok_or("form missing")?;
150
    submit(&form).await?;
151

            
152
    let same = host.query_selector("form")?.ok_or("form replaced")?;
153
    assert!(same.loose_eq(&form));
154
    let result_box = same.query_selector(".result-box")?.ok_or("no box")?;
155
    assert!(result_box.inner_html().contains("plain error"));
156
    assert!(result_box.class_list().contains("error-message"));
157
    host.remove();
158
    Ok(())
159
}
160

            
161
#[wasm_bindgen_test]
162
async fn invalid_submit_rerenders_and_corrected_resubmit_succeeds() -> Result<(), JsValue> {
163
    setup()?;
164
    let host = mount(&format!(
165
        r#"<form {FORM_ATTRS}><div class="result-box"></div><input name="a" value="bad"></form>"#
166
    ))?;
167
    reply(
168
        422,
169
        r##"{"hx-retarget": "#nf-demo", "hx-reswap": "outerHTML"}"##,
170
        &format!(
171
            r#"<form {FORM_ATTRS}><p class="banner">fix it</p><div class="result-box"></div>
172
            <input name="a" value="bad"></form>"#
173
        ),
174
    )?;
175

            
176
    let first = host.query_selector("form")?.ok_or("form missing")?;
177
    let href = global_eval("location.href")?.as_string();
178
    submit(&first).await?;
179
    assert_eq!(global_eval("location.href")?.as_string(), href);
180

            
181
    let second = host.query_selector("form")?.ok_or("no re-rendered form")?;
182
    assert!(!second.loose_eq(&first));
183
    let markers = [
184
        "data-rows-ready",
185
        "data-dates-ready",
186
        "data-conversion-ready",
187
    ];
188
    for marker in markers {
189
        assert!(!second.has_attribute(marker), "{marker}");
190
    }
191
    form_init::init_all();
192
    for marker in markers {
193
        assert!(second.has_attribute(marker), "{marker}");
194
    }
195

            
196
    reply(200, "{}", r#"<div class="ok">saved</div>"#)?;
197
    submit(&second).await?;
198

            
199
    assert!(host.query_selector("form")?.is_none());
200
    let saved = host.query_selector(".ok")?.ok_or("no success reply")?;
201
    assert_eq!(saved.inner_html(), "saved");
202
    host.remove();
203
    Ok(())
204
}
205

            
206
#[wasm_bindgen_test]
207
async fn retarget_to_an_absent_form_lands_in_the_result_box() -> Result<(), JsValue> {
208
    setup()?;
209
    let host = mount(&format!(
210
        r#"<form {FORM_ATTRS}><div class="result-box"></div></form>"#
211
    ))?;
212
    reply(
213
        422,
214
        r##"{"hx-retarget": "#nf-absent", "hx-reswap": "outerHTML"}"##,
215
        r#"<div class="error-alert">no such form</div>"#,
216
    )?;
217

            
218
    let form = host.query_selector("form")?.ok_or("form missing")?;
219
    submit(&form).await?;
220

            
221
    let same = host.query_selector("form")?.ok_or("form replaced")?;
222
    assert!(same.loose_eq(&form));
223
    let result_box = same.query_selector(".result-box")?.ok_or("no box")?;
224
    assert!(result_box.inner_html().contains("no such form"));
225
    host.remove();
226
    Ok(())
227
}