Lines
0 %
Functions
Branches
100 %
// -- -*- mode: rust -*-
//! An error redirected into a form's result box must replace the box's
//! contents, not the box, whatever the form's own hx-swap says. A response
//! carrying `HX-Retarget` (the 422 form re-render) is swapped by htmx itself.
use nomisync_frontend::form_init;
use nomisync_frontend::htmx::{retarget_to_box, setup_htmx_validation};
use wasm_bindgen::{JsCast, JsValue};
use wasm_bindgen_futures::JsFuture;
use wasm_bindgen_test::*;
use web_sys::Element;
wasm_bindgen_test_configure!(run_in_browser);
#[wasm_bindgen_test]
fn retarget_swaps_the_box_contents() -> Result<(), JsValue> {
let document = web_sys::window()
.and_then(|w| w.document())
.ok_or("no document")?;
let result_box = document.create_element("div")?;
let detail = js_sys::Object::new();
js_sys::Reflect::set(&detail, &"swapOverride".into(), &"outerHTML".into())?;
retarget_to_box(&detail, &result_box);
let target = js_sys::Reflect::get(&detail, &"target".into())?;
assert!(target.loose_eq(&result_box));
assert_eq!(
js_sys::Reflect::get(&detail, &"swapOverride".into())?.as_string(),
Some("innerHTML".to_string())
);
Ok(())
}
const HTMX: &str = include_str!("../../static/scripts/htmx.min.js");
// Each send() answers with the next `window.__replies` entry.
const FAKE_XHR: &str = r#"
(() => {
window.__replies = [];
const Real = window.XMLHttpRequest;
window.XMLHttpRequest = class extends Real {
open() {}
setRequestHeader() {}
send() {
const { status, headers, body } = window.__replies.shift();
const props = { status, response: body, responseText: body, responseURL: location.href };
for (const [key, value] of Object.entries(props)) {
Object.defineProperty(this, key, { value });
const lower = { "content-type": "text/html", ...headers };
this.getAllResponseHeaders = () =>
Object.entries(lower).map(([k, v]) => `${k}: ${v}\r\n`).join("");
this.getResponseHeader = (name) => lower[name.toLowerCase()] ?? null;
setTimeout(() => this.onload(), 0);
};
})()
"#;
const FORM_ATTRS: &str = r##"id="nf-demo" class="nomi-form" hx-post="/demo" hx-swap="outerHTML""##;
fn global_eval(source: &str) -> Result<JsValue, JsValue> {
js_sys::Function::new_with_args("src", "return (0, eval)(src)")
.call1(&JsValue::NULL, &source.into())
fn setup() -> Result<(), JsValue> {
if !global_eval("typeof htmx !== 'undefined'")?
.as_bool()
.unwrap_or(false)
{
global_eval(HTMX)?;
global_eval(FAKE_XHR)?;
setup_htmx_validation();
fn reply(status: u16, headers: &str, body: &str) -> Result<(), JsValue> {
let body = serde_json::to_string(body).map_err(|e| e.to_string())?;
global_eval(&format!(
"window.__replies.push({{ status: {status}, headers: {headers}, body: {body} }})"
))?;
fn mount(html: &str) -> Result<Element, JsValue> {
let host = document.create_element("div")?;
host.set_inner_html(html);
document.body().ok_or("no body")?.append_child(&host)?;
global_eval("htmx.process")?
.dyn_into::<js_sys::Function>()?
.call1(&JsValue::NULL, &host)?;
Ok(host)
async fn submit(form: &Element) -> Result<(), JsValue> {
let promise = js_sys::eval(
"new Promise(r => document.addEventListener('htmx:afterSettle', r, { once: true }))",
)?;
let done = JsFuture::from(promise.dyn_into::<js_sys::Promise>()?);
let init = web_sys::EventInit::new();
init.set_bubbles(true);
init.set_cancelable(true);
form.dispatch_event(&web_sys::Event::new_with_event_init_dict("submit", &init)?)?;
done.await?;
async fn retargeted_422_swaps_the_form_not_the_result_box() -> Result<(), JsValue> {
setup()?;
let host = mount(&format!(
r#"<form {FORM_ATTRS}><div class="result-box"></div><input name="a"></form>"#
reply(
422,
r##"{"hx-retarget": "#nf-demo", "hx-reswap": "outerHTML"}"##,
r#"<form id="nf-demo" class="nomi-form"><p class="banner">fix it</p><div class="result-box"></div></form>"#,
let form = host.query_selector("form")?.ok_or("form missing")?;
submit(&form).await?;
let fresh = host
.query_selector("form")?
.ok_or("form replaced by nothing")?;
assert!(!fresh.loose_eq(&form));
assert!(fresh.query_selector(".banner")?.is_some());
let result_box = fresh.query_selector(".result-box")?.ok_or("no box")?;
assert_eq!(result_box.inner_html(), "");
assert!(!result_box.class_list().contains("error-message"));
host.remove();
async fn error_without_retarget_still_lands_in_the_result_box() -> Result<(), JsValue> {
r#"<form {FORM_ATTRS}><div class="result-box"></div></form>"#
reply(422, "{}", r#"<div class="error-alert">plain error</div>"#)?;
let same = host.query_selector("form")?.ok_or("form replaced")?;
assert!(same.loose_eq(&form));
let result_box = same.query_selector(".result-box")?.ok_or("no box")?;
assert!(result_box.inner_html().contains("plain error"));
assert!(result_box.class_list().contains("error-message"));
async fn invalid_submit_rerenders_and_corrected_resubmit_succeeds() -> Result<(), JsValue> {
r#"<form {FORM_ATTRS}><div class="result-box"></div><input name="a" value="bad"></form>"#
&format!(
r#"<form {FORM_ATTRS}><p class="banner">fix it</p><div class="result-box"></div>
<input name="a" value="bad"></form>"#
),
let first = host.query_selector("form")?.ok_or("form missing")?;
let href = global_eval("location.href")?.as_string();
submit(&first).await?;
assert_eq!(global_eval("location.href")?.as_string(), href);
let second = host.query_selector("form")?.ok_or("no re-rendered form")?;
assert!(!second.loose_eq(&first));
let markers = [
"data-rows-ready",
"data-dates-ready",
"data-conversion-ready",
];
for marker in markers {
assert!(!second.has_attribute(marker), "{marker}");
form_init::init_all();
assert!(second.has_attribute(marker), "{marker}");
reply(200, "{}", r#"<div class="ok">saved</div>"#)?;
submit(&second).await?;
assert!(host.query_selector("form")?.is_none());
let saved = host.query_selector(".ok")?.ok_or("no success reply")?;
assert_eq!(saved.inner_html(), "saved");
async fn retarget_to_an_absent_form_lands_in_the_result_box() -> Result<(), JsValue> {
r##"{"hx-retarget": "#nf-absent", "hx-reswap": "outerHTML"}"##,
r#"<div class="error-alert">no such form</div>"#,
assert!(result_box.inner_html().contains("no such form"));