Lines
0 %
Functions
Branches
100 %
//! The converted amount of a split is posted only while its two commodities
//! differ; otherwise it is hidden and disabled so the browser leaves it out.
use wasm_bindgen::prelude::*;
use web_sys::{Element, Event, HtmlFormElement, HtmlInputElement};
use crate::rows::{each_element, listen_form};
use crate::suggest::{commodity_id, load_commodities};
const READY: &str = "data-conversion-ready";
const HIDDEN: &str = "hidden-field";
/// The reference a commodity cell carries: its hidden input.
fn commodity_in(row: &Element, cell: &str) -> Result<String, JsValue> {
let selector = format!("input[type=\"hidden\"][name$=\".{cell}\"]");
Ok(row
.query_selector(&selector)?
.and_then(|e| e.dyn_into::<HtmlInputElement>().ok())
.map(|input| input.value())
.unwrap_or_default())
}
/// Whether two commodity texts name different commodities; a text the cached
/// options cannot resolve is compared as written.
fn differ(from: &str, to: &str) -> bool {
let (from, to) = (from.trim(), to.trim());
if from.is_empty() || to.is_empty() {
return false;
commodity_id(from)
.zip(commodity_id(to))
.map_or(from != to, |(a, b)| a != b)
fn sync_label(label: &Element) -> Result<(), JsValue> {
if label.query_selector(".field-error")?.is_some() {
return Ok(());
let (Some(from), Some(to), Some(row)) = (
label.get_attribute("data-from-cell"),
label.get_attribute("data-to-cell"),
label.closest("[data-row]")?,
) else {
};
let shown = differ(&commodity_in(&row, &from)?, &commodity_in(&row, &to)?);
label.class_list().toggle_with_force(HIDDEN, !shown)?;
if let Some(input) = label.query_selector("input")? {
input.dyn_into::<HtmlInputElement>()?.set_disabled(!shown);
Ok(())
fn resync(form: &HtmlFormElement) -> Result<(), JsValue> {
each_element(form, "label[data-to-cell]")?
.iter()
.try_for_each(sync_label)
fn sync_all(form: &HtmlFormElement, _: &Event) -> Result<(), JsValue> {
resync(form)
/// Show or hide each converted amount as its commodities change.
///
/// # Errors
/// Returns the DOM error if a control cannot be read or written.
pub fn init_conversion(form: &HtmlFormElement) -> Result<(), JsValue> {
if form.has_attribute(READY) {
form.set_attribute(READY, "")?;
for event in ["input", "change", "click", "submit"] {
listen_form(form, event, sync_all)?;
let target = form.clone();
wasm_bindgen_futures::spawn_local(async move {
load_commodities().await;
if let Err(error) = resync(&target) {
web_sys::console::error_1(&error);
});