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> {
102 require(pattern)?;
103 let mut result = String::new();
104 let mut chars = pattern.chars();
105 while let Some(character) = chars.next() {
106 match character {
107 '\\' => match chars.next() {
108 Some(escaped) if escaped != '[' && escaped != ']' => {
109 result.push('[');
110 result.push(escaped);
111 result.push(']');
112 }
113 _ => return Err(Error::argument("Date format contains an unsupported escaped literal.")),
114 },
115 'Y' => result.push_str("YYYY"),
116 'y' => result.push_str("YY"),
117 'm' => result.push_str("MM"),
118 'n' => result.push('M'),
119 'd' => result.push_str("DD"),
120 'j' => result.push('D'),
121 'H' => result.push_str("HH"),
122 'G' => result.push('H'),
123 'h' => result.push_str("hh"),
124 'g' => result.push('h'),
125 'i' => result.push_str("mm"),
126 's' => result.push_str("ss"),
127 'a' => result.push('a'),
128 'A' => result.push('A'),
129 other if other.is_ascii_alphabetic() || other == '[' || other == ']' => {
130 return Err(Error::argument(format!(
131 "PHP date token \"{other}\" cannot be exported to Day.js. Use numeric date/time tokens or escaped literals."
132 )));
133 }
134 other => result.push(other),
135 }
136 }
137 Ok(result)
138}
139
140fn require(pattern: &str) -> Result<String> {
141 if pattern.trim().is_empty() {
142 return Err(Error::argument("Date formats must be non-empty PHP pattern strings."));
143 }
144 Ok(pattern.to_owned())
145}