Skip to main content

rosetta_date/
wasm.rs

1//! WASM bindings – exposes core functionality to JavaScript via `wasm-bindgen`.
2//!
3//! Gated behind the `wasm` feature flag.
4
5#[cfg(feature = "wasm")]
6pub mod inner {
7    use wasm_bindgen::prelude::*;
8
9    /// Parse a date string and return an ISO 8601 representation.
10    #[wasm_bindgen(js_name = "parseDate")]
11    pub fn parse_date(input: &str) -> Result<String, JsValue> {
12        let dt = crate::parser::parse(input).map_err(|e| JsValue::from_str(&e.to_string()))?;
13        Ok(format!("{}", dt))
14    }
15
16    /// Parse a date string and return a Unix timestamp (seconds).
17    #[wasm_bindgen(js_name = "parseDateTimestamp")]
18    pub fn parse_date_timestamp(input: &str) -> Result<f64, JsValue> {
19        let dt = crate::parser::parse(input).map_err(|e| JsValue::from_str(&e.to_string()))?;
20        Ok(dt.timestamp() as f64)
21    }
22
23    /// Format a Unix timestamp with the given strftime format string.
24    #[wasm_bindgen(js_name = "formatTimestamp")]
25    pub fn format_timestamp(timestamp: f64, format: &str) -> Result<String, JsValue> {
26        let dt = crate::datetime::RosettaDateTime::from_components(
27            1970,
28            1,
29            1,
30            0,
31            0,
32            0,
33            crate::timezone::TzOffset::UTC,
34        )
35        .map_err(|e| JsValue::from_str(&e.to_string()))?
36        .add_seconds(timestamp as i64);
37
38        Ok(crate::formatter::format_datetime(&dt, format, None))
39    }
40
41    /// Return a relative time string (e.g. "5 minutes ago") for the given
42    /// ISO date string compared to the current time.
43    #[wasm_bindgen(js_name = "timeAgo")]
44    pub fn time_ago(input: &str) -> Result<String, JsValue> {
45        let dt = crate::parser::parse(input).map_err(|e| JsValue::from_str(&e.to_string()))?;
46        let now = crate::datetime::RosettaDateTime::now_utc();
47        Ok(crate::formatter::time_ago(&dt, &now, None))
48    }
49}