use crate::{DateConfig, DatePatterns, Error, Result};
use serde_json::{Value, json};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Kind {
Date,
DateTime,
Month,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Purpose {
Display,
Value,
Filter,
}
impl Kind {
const fn default_pattern(self) -> &'static str {
match self {
Self::Date => "d/m/Y",
Self::DateTime => "d/m/Y h:i a",
Self::Month => "m/Y",
}
}
const fn cast_fallback(self) -> &'static str {
match self {
Self::Date => "d/m/y",
Self::DateTime => "d/m/y h:i A",
Self::Month => "m/Y",
}
}
}
fn pick(patterns: &DatePatterns, kind: Kind) -> Option<&String> {
match kind {
Kind::Date => patterns.date.as_ref(),
Kind::DateTime => patterns.date_time.as_ref(),
Kind::Month => patterns.month.as_ref(),
}
}
pub fn format(config: &DateConfig, kind: Kind, purpose: Purpose, fallback: Option<&str>) -> Result<String> {
let specific = match purpose {
Purpose::Display => None,
Purpose::Value => pick(&config.value, kind),
Purpose::Filter => pick(&config.filter, kind),
};
let general = match kind {
Kind::Date => config.date.as_ref(),
Kind::DateTime => config.date_time.as_ref(),
Kind::Month => config.month.as_ref(),
};
if let Some(pattern) = specific.or(general) {
return require(pattern);
}
let legacy = match kind {
Kind::Date => config.date_format_solo.as_deref(),
Kind::DateTime => config.date_format.as_deref(),
Kind::Month => None,
};
require(legacy.unwrap_or_else(|| fallback.unwrap_or(kind.default_pattern())))
}
pub fn frontend_config(config: &DateConfig) -> Result<Value> {
let mut result = json!({ "value": {}, "filter": {} });
for (key, kind) in [("date", Kind::Date), ("dateTime", Kind::DateTime), ("month", Kind::Month)] {
result[key] = to_dayjs(&format(config, kind, Purpose::Display, None)?)?.into();
result["value"][key] =
to_dayjs(&format(config, kind, Purpose::Value, Some(kind.cast_fallback()))?)?.into();
result["filter"][key] = to_dayjs(&format(config, kind, Purpose::Filter, None)?)?.into();
}
Ok(result)
}
pub fn to_dayjs(pattern: &str) -> Result<String> {
require(pattern)?;
let mut result = String::new();
let mut chars = pattern.chars();
while let Some(character) = chars.next() {
match character {
'\\' => match chars.next() {
Some(escaped) if escaped != '[' && escaped != ']' => {
result.push('[');
result.push(escaped);
result.push(']');
}
_ => return Err(Error::argument("Date format contains an unsupported escaped literal.")),
},
'Y' => result.push_str("YYYY"),
'y' => result.push_str("YY"),
'm' => result.push_str("MM"),
'n' => result.push('M'),
'd' => result.push_str("DD"),
'j' => result.push('D'),
'H' => result.push_str("HH"),
'G' => result.push('H'),
'h' => result.push_str("hh"),
'g' => result.push('h'),
'i' => result.push_str("mm"),
's' => result.push_str("ss"),
'a' => result.push('a'),
'A' => result.push('A'),
other if other.is_ascii_alphabetic() || other == '[' || other == ']' => {
return Err(Error::argument(format!(
"PHP date token \"{other}\" cannot be exported to Day.js. Use numeric date/time tokens or escaped literals."
)));
}
other => result.push(other),
}
}
Ok(result)
}
fn require(pattern: &str) -> Result<String> {
if pattern.trim().is_empty() {
return Err(Error::argument("Date formats must be non-empty PHP pattern strings."));
}
Ok(pattern.to_owned())
}