1
//! The cells a fill wrote ride along with a submit as `filled:<address>`, a
2
//! copied one with the value `copied`, so a form the server re-renders still
3
//! lets a later pick move them.
4

            
5
use forms::labels::{COPIED_MARK, FILLED_PREFIX, LABEL_PREFIX};
6
use wasm_bindgen::prelude::*;
7
use web_sys::{CustomEvent, Event, HtmlFormElement};
8

            
9
use crate::rows::{each_element, listen_form};
10

            
11
/// Marks a cell a fill wrote: a later fill may move or clear it until the user picks or types it.
12
pub(crate) const FILLED: &str = "data-filled";
13

            
14
/// A filled cell that came from the split above: a fill may move it, never clear it.
15
pub(crate) const COPIED: &str = "data-copied";
16

            
17
fn on_request(form: &HtmlFormElement, event: &Event) -> Result<(), JsValue> {
18
    let Some(request) = event.dyn_ref::<CustomEvent>() else {
19
        return Ok(());
20
    };
21
    let parameters = js_sys::Reflect::get(&request.detail(), &"parameters".into())?;
22
    for input in each_element(form, &format!("input[{FILLED}]"))? {
23
        let name = input.get_attribute("name").unwrap_or_default();
24
        let mark = match input.has_attribute(COPIED) {
25
            true => COPIED_MARK,
26
            false => "",
27
        };
28
        if let Some(address) = name.strip_prefix(LABEL_PREFIX) {
29
            js_sys::Reflect::set(
30
                &parameters,
31
                &format!("{FILLED_PREFIX}{address}").into(),
32
                &mark.into(),
33
            )?;
34
        }
35
    }
36
    Ok(())
37
}
38

            
39
/// Send the filled marks of `form` with every request it makes.
40
///
41
/// # Errors
42
/// Returns the DOM error if the listener cannot be set up.
43
pub fn init_filled_marks(form: &HtmlFormElement) -> Result<(), JsValue> {
44
    listen_form(form, "htmx:configRequest", on_request)
45
}