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 #[must_use]
31 pub const fn default_pattern(self) -> &'static str {
32 match self {
33 Self::Date => "d/m/Y",
34 Self::DateTime => "d/m/Y h:i a",
35 Self::Month => "m/Y",
36 }
37 }
38
39 #[must_use]
42 pub const fn cast_fallback(self) -> &'static str {
43 match self {
44 Self::Date => "d/m/y",
45 Self::DateTime => "d/m/y h:i A",
46 Self::Month => "m/Y",
47 }
48 }
49}
50
51fn pick(patterns: &DatePatterns, kind: Kind) -> Option<&String> {
52 match kind {
53 Kind::Date => patterns.date.as_ref(),
54 Kind::DateTime => patterns.date_time.as_ref(),
55 Kind::Month => patterns.month.as_ref(),
56 }
57}
58
59pub fn format(config: &DateConfig, kind: Kind, purpose: Purpose, fallback: Option<&str>) -> Result<String> {
65 let specific = match purpose {
66 Purpose::Display => None,
67 Purpose::Value => pick(&config.value, kind),
68 Purpose::Filter => pick(&config.filter, kind),
69 };
70 let general = match kind {
71 Kind::Date => config.date.as_ref(),
72 Kind::DateTime => config.date_time.as_ref(),
73 Kind::Month => config.month.as_ref(),
74 };
75 if let Some(pattern) = specific.or(general) {
76 return require(pattern);
77 }
78 let legacy = match kind {
79 Kind::Date => config.date_format_solo.as_deref(),
80 Kind::DateTime => config.date_format.as_deref(),
81 Kind::Month => None,
82 };
83 require(legacy.unwrap_or_else(|| fallback.unwrap_or(kind.default_pattern())))
84}
85
86pub fn frontend_config(config: &DateConfig) -> Result<Value> {
91 let mut result = json!({ "value": {}, "filter": {} });
92 for (key, kind) in [("date", Kind::Date), ("dateTime", Kind::DateTime), ("month", Kind::Month)] {
93 result[key] = to_dayjs(&format(config, kind, Purpose::Display, None)?)?.into();
94 result["value"][key] = to_dayjs(&format(config, kind, Purpose::Value, Some(kind.cast_fallback()))?)?.into();
95 result["filter"][key] = to_dayjs(&format(config, kind, Purpose::Filter, None)?)?.into();
96 }
97 Ok(result)
98}
99
100pub fn to_dayjs(pattern: &str) -> Result<String> {
119 require(pattern)?;
120 let mut result = String::with_capacity(pattern.len() * 2);
121 let mut chars = pattern.chars();
122 let mut previous: Option<&str> = None;
124 while let Some(character) = chars.next() {
125 let token = match character {
126 '\\' => match chars.next() {
127 Some(escaped) if escaped != '[' && escaped != ']' => {
128 result.push('[');
129 result.push(escaped);
130 result.push(']');
131 previous = None;
132 continue;
133 }
134 _ => return Err(Error::argument("Date format contains an unsupported escaped literal.")),
135 },
136 'Y' => "YYYY",
137 'y' => "YY",
138 'm' => "MM",
139 'n' => "M",
140 'd' => "DD",
141 'j' => "D",
142 'H' => "HH",
143 'G' => "H",
144 'h' => "hh",
145 'g' => "h",
146 'i' => "mm",
147 's' => "ss",
148 'a' => "a",
149 'A' => "A",
150 'D' => "ddd",
151 'l' => "dddd",
152 'M' => "MMM",
153 'F' => "MMMM",
154 'w' => "d",
155 'v' => "SSS",
156 'O' => "ZZ",
157 'P' => "Z",
158 'U' => "X",
159 other if other.is_ascii_alphabetic() || other == '[' || other == ']' => {
160 return Err(Error::argument(format!(
161 "PHP date token \"{other}\" cannot be exported to Day.js. Use numeric date/time tokens or escaped literals."
162 )));
163 }
164 other => {
165 result.push(other);
166 previous = None;
167 continue;
168 }
169 };
170 if let Some(before) = previous.filter(|before| runs_into(before, token)) {
171 return Err(Error::argument(format!(
172 "Day.js would read \"{before}{token}\" as other tokens. Put a character between them."
173 )));
174 }
175 result.push_str(token);
176 previous = Some(token);
177 }
178 Ok(result)
179}
180
181fn runs_into(before: &str, next: &str) -> bool {
184 let Some(letter) = before.bytes().next() else { return false };
185 let longest = match letter {
186 b'Y' | b'M' | b'd' => 4,
187 b'S' => 3,
188 b'D' | b'H' | b'h' | b'm' | b's' | b'Z' => 2,
189 _ => 1,
190 };
191 next.bytes().next() == Some(letter) && before.len() < longest
192}
193
194fn require(pattern: &str) -> Result<String> {
195 if pattern.trim().is_empty() {
196 return Err(Error::argument("Date formats must be non-empty PHP pattern strings."));
197 }
198 Ok(pattern.to_owned())
199}