1
//! A rendered date is a hidden named RFC3339 input and an unnamed visible
2
//! `datetime-local` control (`data-date-for`). The hidden value stays the exact
3
//! loaded instant until the visible text is edited.
4

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

            
8
use crate::date_zone::{format_local, format_utc, local_to_utc, parse_local};
9
use crate::rows::{each_element, listen_form};
10

            
11
const READY: &str = "data-dates-ready";
12
const SHOWN: &str = "data-local";
13
const EXACT: &str = "data-exact";
14

            
15
fn offset_at(utc_ms: i64) -> i32 {
16
    let date = js_sys::Date::new(&JsValue::from_f64(utc_ms as f64));
17
    -(date.get_timezone_offset().round() as i32)
18
}
19

            
20
fn hidden_of(visible: &HtmlInputElement) -> Result<Option<HtmlInputElement>, JsValue> {
21
    let Some(name) = visible.get_attribute("data-date-for") else {
22
        return Ok(None);
23
    };
24
    let Some(form) = visible.closest("form")? else {
25
        return Ok(None);
26
    };
27
    let selector = format!("input[type=\"hidden\"][name=\"{name}\"]");
28
    Ok(form
29
        .query_selector(&selector)?
30
        .and_then(|e| e.dyn_into().ok()))
31
}
32

            
33
fn visible_inputs(form: &HtmlFormElement) -> Result<Vec<HtmlInputElement>, JsValue> {
34
    Ok(each_element(form, "input[data-date-for]")?
35
        .into_iter()
36
        .filter_map(|e| e.dyn_into().ok())
37
        .collect())
38
}
39

            
40
fn show(visible: &HtmlInputElement, hidden: &HtmlInputElement) -> Result<(), JsValue> {
41
    let exact = hidden.value();
42
    let instant = js_sys::Date::new(&JsValue::from_str(&exact)).get_time();
43
    let shown = if instant.is_nan() {
44
        String::new()
45
    } else {
46
        format_local(instant as i64, offset_at(instant as i64))
47
    };
48
    visible.set_value(&shown);
49
    visible.set_attribute(SHOWN, &visible.value())?;
50
    visible.set_attribute(EXACT, &exact)
51
}
52

            
53
/// The value the hidden input must carry for what the visible control shows.
54
fn instant_for(visible: &HtmlInputElement) -> String {
55
    let text = visible.value();
56
    if visible.get_attribute(SHOWN).as_deref() == Some(text.as_str()) {
57
        return visible.get_attribute(EXACT).unwrap_or_default();
58
    }
59
    parse_local(&text).map_or_else(String::new, |wall| {
60
        format_utc(local_to_utc(wall, offset_at))
61
    })
62
}
63

            
64
fn sync(visible: &HtmlInputElement) -> Result<(), JsValue> {
65
    if let Some(hidden) = hidden_of(visible)? {
66
        hidden.set_value(&instant_for(visible));
67
    }
68
    Ok(())
69
}
70

            
71
fn sync_all(form: &HtmlFormElement, _: &Event) -> Result<(), JsValue> {
72
    visible_inputs(form)?.iter().try_for_each(sync)
73
}
74

            
75
/// Fill the visible date controls from their hidden instants and keep the
76
/// hidden values in step with them.
77
///
78
/// # Errors
79
/// Returns the DOM error if a control cannot be read or written.
80
pub fn init_dates(form: &HtmlFormElement) -> Result<(), JsValue> {
81
    if form.has_attribute(READY) {
82
        return Ok(());
83
    }
84
    form.set_attribute(READY, "")?;
85
    for visible in visible_inputs(form)? {
86
        if let Some(hidden) = hidden_of(&visible)? {
87
            show(&visible, &hidden)?;
88
        }
89
    }
90
    listen_form(form, "input", sync_all)?;
91
    listen_form(form, "change", sync_all)?;
92
    listen_form(form, "submit", sync_all)
93
}