1use crate::{DateConfig, DatePatterns, Error, Result};
4use serde_json::{Value, json};
5
6#[derive(Debug, Clone, Copy, PartialEq, Eq)]
8pub enum Kind {
9 Date,
11 DateTime,
13 Month,
15}
16
17#[derive(Debug, Clone, Copy, PartialEq, Eq)]
19pub enum Purpose {
20 Display,
22 Value,
24 Filter,
26}
27
28impl Kind {
29 const fn default_pattern(self) -> &'static str {
30 match self {
31 Self::Date => "d/m/Y",
32 Self::DateTime => "d/m/Y h:i a",
33 Self::Month => "m/Y",
34 }
35 }
36
37 const fn cast_fallback(self) -> &'static str {
39 match self {
40 Self::Date => "d/m/y",
41 Self::DateTime => "d/m/y h:i A",
42 Self::Month => "m/Y",
43 }
44 }
45}
46
47fn pick(patterns: &DatePatterns, kind: Kind) -> Option<&String> {
48 match kind {
49 Kind::Date => patterns.date.as_ref(),
50 Kind::DateTime => patterns.date_time.as_ref(),
51 Kind::Month => patterns.month.as_ref(),
52 }
53}
54
55pub fn format(config: &DateConfig, kind: Kind, purpose: Purpose, fallback: Option<&str>) -> Result<String> {
61 let specific = match purpose {
62 Purpose::Display => None,
63 Purpose::Value => pick(&config.value, kind),
64 Purpose::Filter => pick(&config.filter, kind),
65 };
66 let general = match kind {
67 Kind::Date => config.date.as_ref(),
68 Kind::DateTime => config.date_time.as_ref(),
69 Kind::Month => config.month.as_ref(),
70 };
71 if let Some(pattern) = specific.or(general) {
72 return require(pattern);
73 }
74 let legacy = match kind {
75 Kind::Date => config.date_format_solo.as_deref(),
76 Kind::DateTime => config.date_format.as_deref(),
77 Kind::Month => None,
78 };
79 require(legacy.unwrap_or_else(|| fallback.unwrap_or(kind.default_pattern())))
80}
81
82pub fn frontend_config(config: &DateConfig) -> Result<Value> {
87 let mut result = json!({ "value": {}, "filter": {} });
88 for (key, kind) in [("date", Kind::Date), ("dateTime", Kind::DateTime), ("month", Kind::Month)] {
89 result[key] = to_dayjs(&format(config, kind, Purpose::Display, None)?)?.into();
90 result["value"][key] =
91 to_dayjs(&format(config, kind, Purpose::Value, Some(kind.cast_fallback()))?)?.into();
92 result["filter"][key] = to_dayjs(&format(config, kind, Purpose::Filter, None)?)?.into();
93 }
94 Ok(result)
95}
96
97pub fn to_dayjs(pattern: &str) -> Result<String> {
103 require(pattern)?;
104 let mut result = String::new();
105 let mut chars = pattern.chars();
106 while let Some(character) = chars.next() {
107 match character {
108 '\\' => match chars.next() {
109 Some(escaped) if escaped != '[' && escaped != ']' => {
110 result.push('[');
111 result.push(escaped);
112 result.push(']');
113 }
114 _ => return Err(Error::argument("Date format contains an unsupported escaped literal.")),
115 },
116 'Y' => result.push_str("YYYY"),
117 'y' => result.push_str("YY"),
118 'm' => result.push_str("MM"),
119 'n' => result.push('M'),
120 'd' => result.push_str("DD"),
121 'j' => result.push('D'),
122 'H' => result.push_str("HH"),
123 'G' => result.push('H'),
124 'h' => result.push_str("hh"),
125 'g' => result.push('h'),
126 'i' => result.push_str("mm"),
127 's' => result.push_str("ss"),
128 'a' => result.push('a'),
129 'A' => result.push('A'),
130 'D' => result.push_str("ddd"),
131 'l' => result.push_str("dddd"),
132 'M' => result.push_str("MMM"),
133 'F' => result.push_str("MMMM"),
134 'w' => result.push('d'),
135 'v' => result.push_str("SSS"),
136 'O' => result.push_str("ZZ"),
137 'P' => result.push('Z'),
138 'U' => result.push('X'),
139 other if other.is_ascii_alphabetic() || other == '[' || other == ']' => {
140 return Err(Error::argument(format!(
141 "PHP date token \"{other}\" cannot be exported to Day.js. Use numeric date/time tokens or escaped literals."
142 )));
143 }
144 other => result.push(other),
145 }
146 }
147 Ok(result)
148}
149
150fn require(pattern: &str) -> Result<String> {
151 if pattern.trim().is_empty() {
152 return Err(Error::argument("Date formats must be non-empty PHP pattern strings."));
153 }
154 Ok(pattern.to_owned())
155}