1
//! Add, remove and renumber the rows of a server-rendered form so the posted
2
//! addresses stay contiguous (`FormValues::from_pairs` refuses gaps).
3

            
4
use std::collections::HashMap;
5

            
6
use forms::labels::LABEL_PREFIX;
7

            
8
use crate::suggest::copy_pick;
9

            
10
use wasm_bindgen::prelude::*;
11
use web_sys::{
12
    Element, Event, EventTarget, HtmlFormElement, HtmlInputElement, HtmlTemplateElement,
13
};
14

            
15
const GROUP: &str = ".row-group";
16
const READY: &str = "data-rows-ready";
17
const COPIED: [&str; 3] = ["from", "from-commodity", "to-commodity"];
18

            
19
pub(crate) fn each_element(root: &Element, selector: &str) -> Result<Vec<Element>, JsValue> {
20
    let list = root.query_selector_all(selector)?;
21
    Ok((0..list.length())
22
        .filter_map(|i| list.item(i)?.dyn_into().ok())
23
        .collect())
24
}
25

            
26
fn cell_in(root: &Element, rows: &str, cell: &str) -> Result<Option<HtmlInputElement>, JsValue> {
27
    let selector = format!("[data-row=\"{rows}\"] input[name$=\".{cell}\"]");
28
    Ok(root
29
        .query_selector(&selector)?
30
        .and_then(|e| e.dyn_into().ok()))
31
}
32

            
33
/// The key input of a group, with the name of the cell the server marked.
34
fn key_input(group: &Element) -> Result<Option<HtmlInputElement>, JsValue> {
35
    let Some(cell) = group.get_attribute("data-key-cell") else {
36
        return Ok(None);
37
    };
38
    let row = group.query_selector("[data-row]")?;
39
    let kind = row.and_then(|r| r.get_attribute("data-row"));
40
    kind.map_or(Ok(None), |kind| cell_in(group, &kind, &cell))
41
}
42

            
43
fn key_inputs(form: &Element) -> Result<Vec<HtmlInputElement>, JsValue> {
44
    let mut inputs = Vec::new();
45
    for group in each_element(form, GROUP)? {
46
        inputs.extend(key_input(&group)?);
47
    }
48
    Ok(inputs)
49
}
50

            
51
fn next_key_number(form: &Element) -> Result<usize, JsValue> {
52
    let used = key_inputs(form)?
53
        .into_iter()
54
        .filter_map(|i| i.value().strip_prefix('n')?.parse::<usize>().ok());
55
    Ok(used.max().map_or(1, |n| n + 1))
56
}
57

            
58
/// Give every keyed row without a key the next free `n…` key.
59
fn assign_keys(form: &Element) -> Result<(), JsValue> {
60
    let mut next = next_key_number(form)?;
61
    for key in key_inputs(form)? {
62
        if key.value().is_empty() {
63
            key.set_value(&format!("n{next}"));
64
            next += 1;
65
        }
66
    }
67
    Ok(())
68
}
69

            
70
/// Point every nested row's link cell at the key of the row it sits in.
71
fn sync_links(form: &Element) -> Result<(), JsValue> {
72
    for group in each_element(form, GROUP)? {
73
        let Some(key) = key_input(&group)? else {
74
            continue;
75
        };
76
        for nested in each_element(&group, "[data-link-cell]")? {
77
            let link = nested.get_attribute("data-link-cell").unwrap_or_default();
78
            for input in each_element(&nested, &format!("input[name$=\".{link}\"]"))? {
79
                if let Ok(input) = input.dyn_into::<HtmlInputElement>() {
80
                    input.set_value(&key.value());
81
                }
82
            }
83
        }
84
    }
85
    Ok(())
86
}
87

            
88
fn rename(row: &Element, kind: &str, index: usize) -> Result<(), JsValue> {
89
    for control in each_element(row, "[name]")? {
90
        let name = control.get_attribute("name").unwrap_or_default();
91
        let (prefix, address) = name
92
            .strip_prefix(LABEL_PREFIX)
93
            .map_or(("", name.as_str()), |address| (LABEL_PREFIX, address));
94
        let mut parts = address.splitn(3, '.');
95
        if let (Some(_), Some(_), Some(rest)) = (parts.next(), parts.next(), parts.next()) {
96
            control.set_attribute("name", &format!("{prefix}{kind}.{index}.{rest}"))?;
97
        }
98
    }
99
    Ok(())
100
}
101

            
102
/// Number every row of every kind contiguously in document order.
103
///
104
/// # Errors
105
/// Returns the DOM error if a selector or attribute write fails.
106
pub fn renumber_rows(form: &HtmlFormElement) -> Result<(), JsValue> {
107
    assign_keys(form)?;
108
    sync_links(form)?;
109
    let mut counters: HashMap<String, usize> = HashMap::new();
110
    for row in each_element(form, "[data-row]")? {
111
        let kind = row.get_attribute("data-row").unwrap_or_default();
112
        let index = counters.entry(kind.clone()).or_default();
113
        rename(&row, &kind, *index)?;
114
        *index += 1;
115
    }
116
    Ok(())
117
}
118

            
119
fn add_row(container: &Element) -> Result<Option<Element>, JsValue> {
120
    let Some(template) = container.query_selector(":scope > template")? else {
121
        return Ok(None);
122
    };
123
    let template: HtmlTemplateElement = template.dyn_into()?;
124
    let clone = template.content().clone_node_with_deep(true)?;
125
    container.insert_before(&clone, Some(&template))?;
126
    Ok(template.previous_element_sibling())
127
}
128

            
129
/// The rows container a button adds to: the one it names, else the one around it.
130
fn rows_container(form: &HtmlFormElement, button: &Element) -> Result<Option<Element>, JsValue> {
131
    match button.get_attribute("data-rows-for") {
132
        Some(id) => form.query_selector(&format!("[id=\"{id}\"]")),
133
        None => button.closest("[data-rows]"),
134
    }
135
}
136

            
137
fn split_row(group: &Element) -> Result<Option<Element>, JsValue> {
138
    group.query_selector(":scope > [data-row=\"splits\"]")
139
}
140

            
141
/// A new split starts as a copy of the split above it in the accounts and
142
/// commodities, and the cursor goes to the first cell still to fill.
143
fn start_split(group: &Element) -> Result<(), JsValue> {
144
    let Some(row) = split_row(group)? else {
145
        return Ok(());
146
    };
147
    let above = group.previous_element_sibling().map(|p| split_row(&p));
148
    if let Some(source) = above.transpose()?.flatten() {
149
        for cell in COPIED {
150
            copy_pick(&source, &row, cell)?;
151
        }
152
    }
153
    let inputs = each_element(&row, "input:not([type=\"hidden\"]):not(:disabled)")?;
154
    let empty = inputs
155
        .into_iter()
156
        .filter_map(|e| e.dyn_into::<HtmlInputElement>().ok())
157
        .find(|input| input.value().is_empty());
158
    empty.map_or(Ok(()), |input| input.focus())
159
}
160

            
161
fn remove_row(button: &Element) -> Result<(), JsValue> {
162
    let Some(row) = button.closest("[data-row]")? else {
163
        return Ok(());
164
    };
165
    let owner = row
166
        .parent_element()
167
        .filter(|p| p.matches(GROUP).unwrap_or(false));
168
    owner.unwrap_or(row).remove();
169
    Ok(())
170
}
171

            
172
fn on_click(form: &HtmlFormElement, event: &Event) -> Result<(), JsValue> {
173
    let Some(button) = event
174
        .target()
175
        .and_then(|t| t.dyn_into::<Element>().ok())
176
        .and_then(|e| e.closest("[data-action]").ok().flatten())
177
    else {
178
        return Ok(());
179
    };
180
    let mut added = None;
181
    match button.get_attribute("data-action").as_deref() {
182
        Some("add-row") => {
183
            if let Some(container) = rows_container(form, &button)? {
184
                added = add_row(&container)?;
185
            }
186
        }
187
        Some("remove-row") => remove_row(&button)?,
188
        _ => return Ok(()),
189
    }
190
    renumber_rows(form)?;
191
    added.map_or(Ok(()), |group| start_split(&group))
192
}
193

            
194
pub(crate) fn listen(
195
    target: &EventTarget,
196
    event: &str,
197
    handler: impl FnMut(Event) + 'static,
198
) -> Result<(), JsValue> {
199
    let callback = Closure::<dyn FnMut(Event)>::new(handler);
200
    target.add_event_listener_with_callback(event, callback.as_ref().unchecked_ref())?;
201
    callback.forget();
202
    Ok(())
203
}
204

            
205
pub(crate) fn listen_form(
206
    form: &HtmlFormElement,
207
    event: &str,
208
    action: fn(&HtmlFormElement, &Event) -> Result<(), JsValue>,
209
) -> Result<(), JsValue> {
210
    let target = form.clone();
211
    listen(form, event, move |event| {
212
        if let Err(error) = action(&target, &event) {
213
            web_sys::console::error_1(&error);
214
        }
215
    })
216
}
217

            
218
/// Make the rows of a rendered form editable: the add and remove buttons
219
/// work and the names stay contiguous, also right before a submit.
220
///
221
/// # Errors
222
/// Returns the DOM error if the form cannot be numbered or listened to.
223
pub fn init_rows(form: &HtmlFormElement) -> Result<(), JsValue> {
224
    if form.has_attribute(READY) {
225
        return Ok(());
226
    }
227
    form.set_attribute(READY, "")?;
228
    renumber_rows(form)?;
229
    listen_form(form, "click", on_click)?;
230
    listen_form(form, "submit", |form, _| renumber_rows(form))
231
}