Lines
0 %
Functions
Branches
100 %
//! A rendered date is a hidden named RFC3339 input and an unnamed visible
//! `datetime-local` control (`data-date-for`). The hidden value stays the exact
//! loaded instant until the visible text is edited.
use wasm_bindgen::prelude::*;
use web_sys::{Event, HtmlFormElement, HtmlInputElement};
use crate::date_zone::{format_local, format_utc, local_to_utc, parse_local};
use crate::rows::{each_element, listen_form};
const READY: &str = "data-dates-ready";
const SHOWN: &str = "data-local";
const EXACT: &str = "data-exact";
fn offset_at(utc_ms: i64) -> i32 {
let date = js_sys::Date::new(&JsValue::from_f64(utc_ms as f64));
-(date.get_timezone_offset().round() as i32)
}
fn hidden_of(visible: &HtmlInputElement) -> Result<Option<HtmlInputElement>, JsValue> {
let Some(name) = visible.get_attribute("data-date-for") else {
return Ok(None);
};
let Some(form) = visible.closest("form")? else {
let selector = format!("input[type=\"hidden\"][name=\"{name}\"]");
Ok(form
.query_selector(&selector)?
.and_then(|e| e.dyn_into().ok()))
fn visible_inputs(form: &HtmlFormElement) -> Result<Vec<HtmlInputElement>, JsValue> {
Ok(each_element(form, "input[data-date-for]")?
.into_iter()
.filter_map(|e| e.dyn_into().ok())
.collect())
fn show(visible: &HtmlInputElement, hidden: &HtmlInputElement) -> Result<(), JsValue> {
let exact = hidden.value();
let instant = js_sys::Date::new(&JsValue::from_str(&exact)).get_time();
let shown = if instant.is_nan() {
String::new()
} else {
format_local(instant as i64, offset_at(instant as i64))
visible.set_value(&shown);
visible.set_attribute(SHOWN, &visible.value())?;
visible.set_attribute(EXACT, &exact)
/// The value the hidden input must carry for what the visible control shows.
fn instant_for(visible: &HtmlInputElement) -> String {
let text = visible.value();
if visible.get_attribute(SHOWN).as_deref() == Some(text.as_str()) {
return visible.get_attribute(EXACT).unwrap_or_default();
parse_local(&text).map_or_else(String::new, |wall| {
format_utc(local_to_utc(wall, offset_at))
})
fn sync(visible: &HtmlInputElement) -> Result<(), JsValue> {
if let Some(hidden) = hidden_of(visible)? {
hidden.set_value(&instant_for(visible));
Ok(())
fn sync_all(form: &HtmlFormElement, _: &Event) -> Result<(), JsValue> {
visible_inputs(form)?.iter().try_for_each(sync)
/// Fill the visible date controls from their hidden instants and keep the
/// hidden values in step with them.
///
/// # Errors
/// Returns the DOM error if a control cannot be read or written.
pub fn init_dates(form: &HtmlFormElement) -> Result<(), JsValue> {
if form.has_attribute(READY) {
return Ok(());
form.set_attribute(READY, "")?;
for visible in visible_inputs(form)? {
if let Some(hidden) = hidden_of(&visible)? {
show(&visible, &hidden)?;
listen_form(form, "input", sync_all)?;
listen_form(form, "change", sync_all)?;
listen_form(form, "submit", sync_all)