| 1 | use std::fmt::Display; |
| 2 | use std::sync::LazyLock; |
| 3 | |
| 4 | use chrono::{DateTime, Local, TimeZone}; |
| 5 | use regex::{Captures, Regex}; |
| 6 | |
| 7 | const COMPACT_FORMAT: &str = "%Y-%m-%d"; |
| 8 | const SHORT_FORMAT: &str = "%a, %b %-d, %Y"; |
| 9 | const LONG_FORMAT: &str = "%A, %B %-d, %Y"; |
| 10 | const TIME_FORMAT: &str = "%H:%M"; |
| 11 | |
| 12 | static DATE_TIME_FUNCTION: LazyLock<Regex> = LazyLock::new(|| { |
| 13 | Regex::new(r"(?:\{\{\s*)?\b(DATE|TIME)\(\s*([^,()\s]+)\s*(?:,\s*(SHORT|LONG|COMPACT)\s*)?\)(?:\s*\}\})?") |
| 14 | .unwrap() |
| 15 | }); |
| 16 | |
| 17 | pub fn format_card_dates(text: &str) -> String { |
| 18 | format_card_dates_in(text, &Local) |
| 19 | } |
| 20 | |
| 21 | pub fn format_card_dates_in<Zone>(text: &str, zone: &Zone) -> String |
| 22 | where |
| 23 | Zone: TimeZone, |
| 24 | Zone::Offset: Display, |
| 25 | { |
| 26 | DATE_TIME_FUNCTION |
| 27 | .replace_all(text, |captures: &Captures| { |
| 28 | format_function(captures, zone).unwrap_or_else(|| captures[0].to_owned()) |
| 29 | }) |
| 30 | .into_owned() |
| 31 | } |
| 32 | |
| 33 | fn format_function<Zone>(captures: &Captures, zone: &Zone) -> Option<String> |
| 34 | where |
| 35 | Zone: TimeZone, |
| 36 | Zone::Offset: Display, |
| 37 | { |
| 38 | let moment = DateTime::parse_from_rfc3339(&captures[2]) |
| 39 | .ok()? |
| 40 | .with_timezone(zone); |
| 41 | let pattern = match (&captures[1], captures.get(3).map(|style| style.as_str())) { |
| 42 | ("TIME", _) => TIME_FORMAT, |
| 43 | (_, Some("SHORT")) => SHORT_FORMAT, |
| 44 | (_, Some("LONG")) => LONG_FORMAT, |
| 45 | _ => COMPACT_FORMAT, |
| 46 | }; |
| 47 | Some(moment.format(pattern).to_string()) |
| 48 | } |