use std::sync::LazyLock;
use laravel::str::Str;
use laravel::time::{Timestamp, civil, tz::TimeZone};
use regex::Regex;
use serde_json::Value;
pub fn slug(text: &str) -> String {
text.ascii().slug()
}
pub fn headline(text: &str) -> String {
text.headline()
}
pub fn localized(value: Option<&Value>, locale: &str, fallback: &str) -> Option<String> {
let value = value?;
let picked = match value {
Value::Object(map) => map
.get(locale)
.or_else(|| map.get(fallback))
.or_else(|| map.values().next())?,
other => other,
};
scalar_text(picked).filter(|text| !text.is_empty())
}
pub fn scalar_text(value: &Value) -> Option<String> {
match value {
Value::String(text) => Some(text.clone()),
Value::Number(number) => Some(number.to_string()),
Value::Bool(true) => Some("1".to_owned()),
Value::Bool(false) => Some(String::new()),
_ => None,
}
}
pub fn truthy(value: Option<&Value>) -> bool {
match value {
None | Some(Value::Null) => false,
Some(Value::Bool(value)) => *value,
Some(Value::Number(number)) => number.as_f64().is_some_and(|number| number != 0.0),
Some(Value::String(text)) => !text.is_empty() && text != "0",
Some(Value::Array(items)) => !items.is_empty(),
Some(Value::Object(map)) => !map.is_empty(),
}
}
pub fn data_get<'a>(value: &'a Value, path: &str) -> Option<&'a Value> {
path.split('.').try_fold(value, |current, segment| match current {
Value::Object(map) => map.get(segment),
Value::Array(items) => segment.parse::<usize>().ok().and_then(|index| items.get(index)),
_ => None,
})
}
static TAGS: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?s)<[^>]*>").expect("a valid pattern"));
static DATE_ONLY: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^\d{4}-\d{2}-\d{2}$").expect("a valid pattern"));
static WORDS: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"[A-Za-z][A-Za-z'-]*").expect("a valid pattern"));
pub fn word_count(html: &str) -> usize {
WORDS.find_iter(&TAGS.replace_all(html, "")).count()
}
pub fn parse_date(text: &str) -> Option<Timestamp> {
let text = text.trim();
if text.is_empty() {
return None;
}
if let Ok(timestamp) = text.parse::<Timestamp>() {
return Some(timestamp);
}
let utc = TimeZone::UTC;
if DATE_ONLY.is_match(text) {
let date = text.parse::<civil::Date>().ok()?;
return date.to_zoned_datetime(utc).ok().map(|zoned| zoned.timestamp());
}
let normalized = text.replacen(' ', "T", 1);
if let Ok(date_time) = normalized.parse::<civil::DateTime>() {
return date_time.to_zoned_datetime(utc).ok().map(|zoned| zoned.timestamp());
}
None
}
pub fn atom(timestamp: Timestamp) -> String {
timestamp.strftime("%Y-%m-%dT%H:%M:%S+00:00").to_string()
}
pub fn rss(timestamp: Timestamp) -> String {
timestamp.strftime("%a, %d %b %Y %H:%M:%S +0000").to_string()
}
pub fn date_string(timestamp: Timestamp) -> String {
timestamp.strftime("%Y-%m-%d").to_string()
}
pub fn long_date(timestamp: Timestamp, locale: &str) -> String {
let date = timestamp.to_zoned_datetime(TimeZone::UTC).date();
let (year, month, day) = (date.year(), usize::try_from(date.month()).unwrap_or(1), date.day());
let language = locale.split(['-', '_']).next().unwrap_or(locale).to_ascii_lowercase();
let month_name = |names: &[&'static str; 12]| names[month - 1];
match language.as_str() {
"en" => format!("{} {day}, {year}", month_name(&EN)),
"es" => format!("{day} de {} de {year}", month_name(&ES)),
"ca" => {
let name = month_name(&CA);
let article = if name.starts_with(['a', 'o']) { "d'" } else { "de " };
format!("{day} {article}{name} de {year}")
}
"gl" => format!("{day} de {} de {year}", month_name(&GL)),
"pt" => format!("{day} de {} de {year}", month_name(&PT)),
"fr" => format!("{day} {} {year}", month_name(&FR)),
"it" => format!("{day} {} {year}", month_name(&IT)),
"de" => format!("{day}. {} {year}", month_name(&DE)),
_ => date_string(timestamp),
}
}
const EN: [&str; 12] = [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December",
];
const ES: [&str; 12] = [
"enero",
"febrero",
"marzo",
"abril",
"mayo",
"junio",
"julio",
"agosto",
"septiembre",
"octubre",
"noviembre",
"diciembre",
];
const CA: [&str; 12] = [
"gener", "febrer", "març", "abril", "maig", "juny", "juliol", "agost", "setembre", "octubre", "novembre",
"desembre",
];
const GL: [&str; 12] = [
"xaneiro", "febreiro", "marzo", "abril", "maio", "xuño", "xullo", "agosto", "setembro", "outubro", "novembro",
"decembro",
];
const PT: [&str; 12] = [
"janeiro",
"fevereiro",
"março",
"abril",
"maio",
"junho",
"julho",
"agosto",
"setembro",
"outubro",
"novembro",
"dezembro",
];
const FR: [&str; 12] = [
"janvier",
"février",
"mars",
"avril",
"mai",
"juin",
"juillet",
"août",
"septembre",
"octobre",
"novembre",
"décembre",
];
const IT: [&str; 12] = [
"gennaio",
"febbraio",
"marzo",
"aprile",
"maggio",
"giugno",
"luglio",
"agosto",
"settembre",
"ottobre",
"novembre",
"dicembre",
];
const DE: [&str; 12] = [
"Januar",
"Februar",
"März",
"April",
"Mai",
"Juni",
"Juli",
"August",
"September",
"Oktober",
"November",
"Dezember",
];
pub fn resolve_locales(configured: Option<&[String]>, supported: &[String], default: &str) -> Vec<String> {
let source: Vec<String> = match configured {
Some(locales) => locales.to_vec(),
None if supported.is_empty() => vec![default.to_owned()],
None => supported.to_vec(),
};
let mut locales: Vec<String> = Vec::new();
for locale in source {
if !locales.contains(&locale) {
locales.push(locale);
}
}
if let Some(position) = locales.iter().position(|locale| locale == default) {
let first = locales.remove(position);
locales.insert(0, first);
}
locales
}