1
// -- -*- mode: rust -*-
2
//! The edit page through htmx and the production afterSwap listener: an
3
//! untouched submit posts the exact loaded date and every hidden value, a
4
//! removed split takes its tags along, and a 422 re-render brings its
5
//! widgets up exactly once.
6

            
7
use forms::{FormValues, TRANSACTION_EDIT};
8
use nomisync_frontend::htmx::setup_htmx_validation;
9
use nomisync_frontend::{form_init, setup_htmx_listener};
10
use wasm_bindgen::{JsCast, JsValue};
11
use wasm_bindgen_futures::JsFuture;
12
use wasm_bindgen_test::*;
13
use web_sys::{Element, HtmlElement};
14

            
15
wasm_bindgen_test_configure!(run_in_browser);
16

            
17
const FIXTURE: &str = include_str!("fixtures/transaction_update.html");
18
const HTMX: &str = include_str!("../../static/scripts/htmx.min.js");
19
const DATE: &str = "2026-10-27T09:15:42.123456Z";
20
const HIDDEN: [&str; 2] = [
21
    "(:from-id \"a\" :to-id \"b\" :value \"10\" :to-amount \"9\" :price-date \"2026-10-20T08:30:15.654321Z\")",
22
    "(:from-id \"a\" :to-id \"b\" :value \"1/3\")",
23
];
24

            
25
// Each send() records its body and answers with the next `window.__replies`.
26
const FAKE_XHR: &str = r#"
27
(() => {
28
  window.__replies = [];
29
  window.__sent = [];
30
  const Real = window.XMLHttpRequest;
31
  window.XMLHttpRequest = class extends Real {
32
    open() {}
33
    setRequestHeader() {}
34
    send(body) {
35
      window.__sent.push(body instanceof FormData ? new URLSearchParams(body).toString() : String(body));
36
      const { status, headers, body: reply } = window.__replies.shift();
37
      const props = { status, response: reply, responseText: reply, responseURL: location.href };
38
      for (const [key, value] of Object.entries(props)) {
39
        Object.defineProperty(this, key, { value });
40
      }
41
      const lower = { "content-type": "text/html", ...headers };
42
      this.getAllResponseHeaders = () =>
43
        Object.entries(lower).map(([k, v]) => `${k}: ${v}\r\n`).join("");
44
      this.getResponseHeader = (name) => lower[name.toLowerCase()] ?? null;
45
      setTimeout(() => this.onload(), 0);
46
    }
47
  };
48
})()
49
"#;
50

            
51
fn global_eval(source: &str) -> Result<JsValue, JsValue> {
52
    js_sys::Function::new_with_args("src", "return (0, eval)(src)")
53
        .call1(&JsValue::NULL, &source.into())
54
}
55

            
56
thread_local! {
57
    static READY: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
58
}
59

            
60
/// The page's listeners go up once, as in production, whichever test runs first.
61
fn setup() -> Result<(), JsValue> {
62
    if READY.with(|ready| ready.replace(true)) {
63
        return Ok(());
64
    }
65
    global_eval(HTMX)?;
66
    global_eval(FAKE_XHR)?;
67
    setup_htmx_validation();
68
    setup_htmx_listener();
69
    Ok(())
70
}
71

            
72
fn mount() -> Result<Element, JsValue> {
73
    let document = web_sys::window()
74
        .and_then(|w| w.document())
75
        .ok_or("no document")?;
76
    let host = document.create_element("div")?;
77
    host.set_inner_html(FIXTURE);
78
    document.body().ok_or("no body")?.append_child(&host)?;
79
    form_init::init_all();
80
    global_eval("htmx.process")?
81
        .dyn_into::<js_sys::Function>()?
82
        .call1(&JsValue::NULL, &host)?;
83
    Ok(host)
84
}
85

            
86
fn reply(status: u16, headers: &str, body: &str) -> Result<(), JsValue> {
87
    let body = serde_json::to_string(body).map_err(|e| e.to_string())?;
88
    global_eval(&format!(
89
        "window.__replies.push({{ status: {status}, headers: {headers}, body: {body} }})"
90
    ))?;
91
    Ok(())
92
}
93

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

            
107
/// The last posted body, decoded as the server decodes it.
108
fn sent() -> Result<FormValues, JsValue> {
109
    let body = global_eval("window.__sent[window.__sent.length - 1]")?
110
        .as_string()
111
        .ok_or("nothing posted")?;
112
    assert!(!body.trim_start().starts_with('{'), "{body}");
113
    let json = global_eval(&format!(
114
        "JSON.stringify([...new URLSearchParams({})])",
115
        serde_json::to_string(&body).map_err(|e| e.to_string())?
116
    ))?
117
    .as_string()
118
    .ok_or("no pairs")?;
119
    let pairs: Vec<(String, String)> = serde_json::from_str(&json).map_err(|e| e.to_string())?;
120
    assert!(pairs.iter().all(|(name, _)| !name.is_empty()), "{pairs:?}");
121
    FormValues::from_pairs(&TRANSACTION_EDIT, pairs).map_err(|e| format!("{e:?}").into())
122
}
123

            
124
fn cells<'a>(values: &'a FormValues, rows: &str, cell: &str) -> Vec<&'a str> {
125
    values
126
        .rows(rows)
127
        .unwrap_or_default()
128
        .iter()
129
        .map(|row| row.get(cell).map_or("", String::as_str))
130
        .collect()
131
}
132

            
133
fn form_of(host: &Element) -> Result<Element, JsValue> {
134
    host.query_selector("#nf-transaction-edit")?
135
        .ok_or_else(|| "no edit form".into())
136
}
137

            
138
fn split_groups(form: &Element) -> Result<u32, JsValue> {
139
    Ok(form
140
        .query_selector_all("#nf-transaction-edit-splits > .row-group")?
141
        .length())
142
}
143

            
144
fn click(root: &Element, selector: &str) -> Result<(), JsValue> {
145
    root.query_selector(selector)?
146
        .ok_or_else(|| JsValue::from_str(selector))?
147
        .dyn_into::<HtmlElement>()?
148
        .click();
149
    Ok(())
150
}
151

            
152
#[wasm_bindgen_test]
153
async fn an_untouched_edit_posts_the_exact_date_and_every_hidden_value() -> Result<(), JsValue> {
154
    setup()?;
155
    let host = mount()?;
156
    reply(200, "{}", "Transaction updated")?;
157

            
158
    submit(&form_of(&host)?).await?;
159

            
160
    let values = sent()?;
161
    assert_eq!(values.text("date"), Some(DATE));
162
    assert_eq!(
163
        values.text("id"),
164
        Some("00000000-0000-0000-0000-0000000000e1")
165
    );
166
    assert_eq!(values.text("revision"), Some("rev-1"));
167
    assert_eq!(values.text("note"), Some("first line\nsecond"));
168
    assert_eq!(cells(&values, "splits", "key"), ["r1", "r2"]);
169
    assert_eq!(cells(&values, "splits", "hidden"), HIDDEN);
170
    assert_eq!(cells(&values, "split-tags", "row"), ["r1", "r2"]);
171
    assert_eq!(cells(&values, "tags", "description"), ["a\nb"]);
172
    host.remove();
173
    Ok(())
174
}
175

            
176
#[wasm_bindgen_test]
177
async fn a_removed_split_takes_its_tags_along() -> Result<(), JsValue> {
178
    setup()?;
179
    let host = mount()?;
180
    let form = form_of(&host)?;
181
    let groups = form.query_selector_all("#nf-transaction-edit-splits > .row-group")?;
182
    let first = groups
183
        .item(0)
184
        .ok_or("no first split")?
185
        .dyn_into::<Element>()?;
186
    click(
187
        &first,
188
        "[data-row=\"splits\"] > button[data-action=\"remove-row\"]",
189
    )?;
190
    reply(200, "{}", "Transaction updated")?;
191

            
192
    submit(&form).await?;
193

            
194
    let values = sent()?;
195
    assert_eq!(cells(&values, "splits", "key"), ["r2"]);
196
    assert_eq!(cells(&values, "splits", "hidden"), [HIDDEN[1]]);
197
    assert_eq!(cells(&values, "split-tags", "row"), ["r2"]);
198
    assert_eq!(cells(&values, "split-tags", "name"), ["category"]);
199
    host.remove();
200
    Ok(())
201
}
202

            
203
#[wasm_bindgen_test]
204
async fn an_invalid_edit_rerenders_its_widgets_once() -> Result<(), JsValue> {
205
    setup()?;
206
    let host = mount()?;
207
    let first = form_of(&host)?;
208
    let banner = r#"<p class="form-banner">fix it</p><div class="result-box"></div>"#;
209
    reply(
210
        422,
211
        r##"{ "hx-retarget": "#nf-transaction-edit", "hx-reswap": "outerHTML" }"##,
212
        &FIXTURE.replace("<div class=\"result-box\"></div>", banner),
213
    )?;
214

            
215
    submit(&first).await?;
216

            
217
    let second = form_of(&host)?;
218
    assert!(!second.loose_eq(&first));
219
    assert!(second.query_selector(".form-banner")?.is_some());
220
    for marker in [
221
        "data-rows-ready",
222
        "data-dates-ready",
223
        "data-conversion-ready",
224
    ] {
225
        assert!(second.has_attribute(marker), "{marker}");
226
    }
227
    let before = split_groups(&second)?;
228
    click(&second, "[data-rows-for=\"nf-transaction-edit-splits\"]")?;
229
    assert_eq!(split_groups(&second)?, before + 1);
230
    host.remove();
231
    Ok(())
232
}