use wasm_bindgen::prelude::*;
#[wasm_bindgen]
pub struct WasmTimestampFormatter {
inner: crate::timestamp::TimestampFormatter,
}
impl Default for WasmTimestampFormatter {
fn default() -> Self {
Self::new()
}
}
#[wasm_bindgen]
impl WasmTimestampFormatter {
#[wasm_bindgen(constructor)]
pub fn new() -> Self {
Self {
inner: crate::timestamp::TimestampFormatter::new(
crate::timestamp::TimestampFormat::Iso8601,
),
}
}
#[wasm_bindgen(js_name = withFormat)]
pub fn with_format(format: &str) -> Result<WasmTimestampFormatter, JsValue> {
let fmt = match format {
"iso8601" => crate::timestamp::TimestampFormat::Iso8601,
"iso8601-date" => crate::timestamp::TimestampFormat::Iso8601Date,
"iso8601-datetime" => crate::timestamp::TimestampFormat::Iso8601DateTime,
"unix-ms" => crate::timestamp::TimestampFormat::UnixMs,
"unix-sec" => crate::timestamp::TimestampFormat::UnixSec,
"relative" => crate::timestamp::TimestampFormat::Relative,
"rfc2822" => crate::timestamp::TimestampFormat::Rfc2822,
"rfc3339" => crate::timestamp::TimestampFormat::Rfc3339,
_ => return Err(JsValue::from_str(&format!("Unknown format: {}", format))),
};
Ok(Self {
inner: crate::timestamp::TimestampFormatter::new(fmt),
})
}
pub fn format(&self, milliseconds: Option<f64>) -> String {
let ms = milliseconds.map(|f| f as i64);
self.inner.format(ms)
}
#[wasm_bindgen(js_name = formatRelative)]
pub fn format_relative(&self, milliseconds: f64) -> String {
self.inner.format_relative(milliseconds as i64)
}
}
#[wasm_bindgen(js_name = parseIso8601)]
pub fn parse_iso8601(iso_string: &str) -> Result<f64, JsValue> {
crate::timestamp::parse_iso8601(iso_string)
.map(|ms| ms as f64)
.map_err(|e| JsValue::from_str(&e.to_string()))
}
#[wasm_bindgen(js_name = timestampNow)]
pub fn timestamp_now() -> f64 {
crate::timestamp::now() as f64
}