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 {
#[must_use]
pub 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",
}
}
#[must_use]
pub 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::with_capacity(pattern.len() * 2);
let mut chars = pattern.chars();
let mut previous: Option<&str> = None;
while let Some(character) = chars.next() {
let token = match character {
'\\' => match chars.next() {
Some(escaped) if escaped != '[' && escaped != ']' => {
result.push('[');
result.push(escaped);
result.push(']');
previous = None;
continue;
}
_ => return Err(Error::argument("Date format contains an unsupported escaped literal.")),
},
'Y' => "YYYY",
'y' => "YY",
'm' => "MM",
'n' => "M",
'd' => "DD",
'j' => "D",
'H' => "HH",
'G' => "H",
'h' => "hh",
'g' => "h",
'i' => "mm",
's' => "ss",
'a' => "a",
'A' => "A",
'D' => "ddd",
'l' => "dddd",
'M' => "MMM",
'F' => "MMMM",
'w' => "d",
'v' => "SSS",
'O' => "ZZ",
'P' => "Z",
'U' => "X",
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);
previous = None;
continue;
}
};
if let Some(before) = previous.filter(|before| runs_into(before, token)) {
return Err(Error::argument(format!(
"Day.js would read \"{before}{token}\" as other tokens. Put a character between them."
)));
}
result.push_str(token);
previous = Some(token);
}
Ok(result)
}
fn runs_into(before: &str, next: &str) -> bool {
let Some(letter) = before.bytes().next() else { return false };
let longest = match letter {
b'Y' | b'M' | b'd' => 4,
b'S' => 3,
b'D' | b'H' | b'h' | b'm' | b's' | b'Z' => 2,
_ => 1,
};
next.bytes().next() == Some(letter) && before.len() < longest
}
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())
}