1
// -- -*- mode: rust -*-
2
//! Expanding a list row loads its detail once, through real htmx.
3

            
4
use nomisync_frontend::setup_htmx_listener;
5
use wasm_bindgen::{JsCast, JsValue};
6
use wasm_bindgen_futures::JsFuture;
7
use wasm_bindgen_test::*;
8
use web_sys::Element;
9

            
10
wasm_bindgen_test_configure!(run_in_browser);
11

            
12
const ROWS: &str = include_str!("fixtures/transaction_list.html");
13
const HTMX: &str = include_str!("../../static/scripts/htmx.min.js");
14

            
15
// Each send() records its url and answers with the next `window.__replies`.
16
const FAKE_XHR: &str = r#"
17
(() => {
18
  window.__replies = [];
19
  window.__sent = [];
20
  const Real = window.XMLHttpRequest;
21
  window.XMLHttpRequest = class extends Real {
22
    open(method, url) { this.__url = url; }
23
    setRequestHeader() {}
24
    send() {
25
      window.__sent.push(this.__url);
26
      const reply = window.__replies.shift();
27
      const props = { status: 200, response: reply, responseText: reply, responseURL: location.href };
28
      for (const [key, value] of Object.entries(props)) {
29
        Object.defineProperty(this, key, { value });
30
      }
31
      this.getAllResponseHeaders = () => "content-type: text/html\r\n";
32
      this.getResponseHeader = (name) => (name.toLowerCase() === "content-type" ? "text/html" : null);
33
      setTimeout(() => this.onload(), 0);
34
    }
35
  };
36
})()
37
"#;
38

            
39
const DETAIL: &str = "<table class=\"splits-table\"><tr><td>Assets:Cash</td></tr></table>";
40

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

            
46
fn mount(html: &str) -> Result<Element, JsValue> {
47
    global_eval(HTMX)?;
48
    global_eval(FAKE_XHR)?;
49
    setup_htmx_listener();
50
    let document = web_sys::window()
51
        .and_then(|w| w.document())
52
        .ok_or("no document")?;
53
    let host = document.create_element("div")?;
54
    host.set_inner_html(html);
55
    document.body().ok_or("no body")?.append_child(&host)?;
56
    global_eval("htmx.process")?
57
        .dyn_into::<js_sys::Function>()?
58
        .call1(&JsValue::NULL, &host)?;
59
    Ok(host)
60
}
61

            
62
async fn toggle(details: &Element, open: bool) -> Result<(), JsValue> {
63
    let toggled = js_sys::eval(
64
        "new Promise(r => document.addEventListener('toggle', r, { capture: true, once: true }))",
65
    )?;
66
    let toggled = JsFuture::from(toggled.dyn_into::<js_sys::Promise>()?);
67
    js_sys::Reflect::set(details, &"open".into(), &open.into())?;
68
    toggled.await?;
69
    let settled = js_sys::eval("new Promise(r => setTimeout(r, 50))")?;
70
    JsFuture::from(settled.dyn_into::<js_sys::Promise>()?).await?;
71
    Ok(())
72
}
73

            
74
fn sent() -> Result<Vec<String>, JsValue> {
75
    let json = global_eval("JSON.stringify(window.__sent)")?
76
        .as_string()
77
        .ok_or("no log")?;
78
    serde_json::from_str(&json).map_err(|e| e.to_string().into())
79
}
80

            
81
#[wasm_bindgen_test]
82
async fn expanding_a_row_loads_its_detail_once() -> Result<(), JsValue> {
83
    let host = mount(ROWS)?;
84
    assert!(sent()?.is_empty(), "nothing loads before an expand");
85
    global_eval(&format!(
86
        "window.__replies.push({})",
87
        serde_json::to_string(DETAIL).map_err(|e| e.to_string())?
88
    ))?;
89
    let rows = host.query_selector_all("details")?;
90
    let first: Element = rows.item(0).ok_or("no first row")?.dyn_into()?;
91

            
92
    toggle(&first, true).await?;
93
    toggle(&first, false).await?;
94
    toggle(&first, true).await?;
95

            
96
    let log = sent()?;
97
    assert_eq!(log.len(), 1, "{log:?}");
98
    assert!(log[0].starts_with("/api/transaction/detail/"), "{log:?}");
99
    let container = first
100
        .query_selector(".splits-container")?
101
        .ok_or("no container")?;
102
    assert!(container.inner_html().contains("Assets:Cash"));
103
    let second: Element = rows.item(1).ok_or("no second row")?.dyn_into()?;
104
    let other = second
105
        .query_selector(".splits-container")?
106
        .ok_or("no container")?;
107
    assert!(other.inner_html().is_empty());
108
    host.remove();
109
    Ok(())
110
}