1
//! The converted amount of a split is posted only while its two commodities
2
//! differ; otherwise it is hidden and disabled so the browser leaves it out.
3

            
4
use wasm_bindgen::prelude::*;
5
use web_sys::{Element, Event, HtmlFormElement, HtmlInputElement};
6

            
7
use crate::rows::{each_element, listen_form};
8
use crate::suggest::{commodity_id, load_commodities};
9

            
10
const READY: &str = "data-conversion-ready";
11
const HIDDEN: &str = "hidden-field";
12

            
13
/// The reference a commodity cell carries: its hidden input.
14
fn commodity_in(row: &Element, cell: &str) -> Result<String, JsValue> {
15
    let selector = format!("input[type=\"hidden\"][name$=\".{cell}\"]");
16
    Ok(row
17
        .query_selector(&selector)?
18
        .and_then(|e| e.dyn_into::<HtmlInputElement>().ok())
19
        .map(|input| input.value())
20
        .unwrap_or_default())
21
}
22

            
23
/// Whether two commodity texts name different commodities; a text the cached
24
/// options cannot resolve is compared as written.
25
fn differ(from: &str, to: &str) -> bool {
26
    let (from, to) = (from.trim(), to.trim());
27
    if from.is_empty() || to.is_empty() {
28
        return false;
29
    }
30
    commodity_id(from)
31
        .zip(commodity_id(to))
32
        .map_or(from != to, |(a, b)| a != b)
33
}
34

            
35
fn sync_label(label: &Element) -> Result<(), JsValue> {
36
    if label.query_selector(".field-error")?.is_some() {
37
        return Ok(());
38
    }
39
    let (Some(from), Some(to), Some(row)) = (
40
        label.get_attribute("data-from-cell"),
41
        label.get_attribute("data-to-cell"),
42
        label.closest("[data-row]")?,
43
    ) else {
44
        return Ok(());
45
    };
46
    let shown = differ(&commodity_in(&row, &from)?, &commodity_in(&row, &to)?);
47
    label.class_list().toggle_with_force(HIDDEN, !shown)?;
48
    if let Some(input) = label.query_selector("input")? {
49
        input.dyn_into::<HtmlInputElement>()?.set_disabled(!shown);
50
    }
51
    Ok(())
52
}
53

            
54
fn resync(form: &HtmlFormElement) -> Result<(), JsValue> {
55
    each_element(form, "label[data-to-cell]")?
56
        .iter()
57
        .try_for_each(sync_label)
58
}
59

            
60
fn sync_all(form: &HtmlFormElement, _: &Event) -> Result<(), JsValue> {
61
    resync(form)
62
}
63

            
64
/// Show or hide each converted amount as its commodities change.
65
///
66
/// # Errors
67
/// Returns the DOM error if a control cannot be read or written.
68
pub fn init_conversion(form: &HtmlFormElement) -> Result<(), JsValue> {
69
    if form.has_attribute(READY) {
70
        return Ok(());
71
    }
72
    form.set_attribute(READY, "")?;
73
    for event in ["input", "change", "click", "submit"] {
74
        listen_form(form, event, sync_all)?;
75
    }
76
    let target = form.clone();
77
    wasm_bindgen_futures::spawn_local(async move {
78
        load_commodities().await;
79
        if let Err(error) = resync(&target) {
80
            web_sys::console::error_1(&error);
81
        }
82
    });
83
    Ok(())
84
}