use indexmap::IndexMap;
use laravel::view::Html;
use serde::Serialize;
use serde_json::Value;
use crate::catalog::Catalog;
use crate::json;
use crate::replace::{Replace, make_replacements};
use crate::selector::choose;
use crate::support::key_to_text;
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Frontend {
pub locale: String,
pub lines: IndexMap<String, String>,
}
pub trait Prefixes {
fn prefixes(&self) -> Vec<String>;
}
impl Prefixes for &str {
fn prefixes(&self) -> Vec<String> {
vec![(*self).to_owned()]
}
}
impl Prefixes for String {
fn prefixes(&self) -> Vec<String> {
vec![self.clone()]
}
}
impl<T: AsRef<str>> Prefixes for &[T] {
fn prefixes(&self) -> Vec<String> {
self.iter().map(|prefix| prefix.as_ref().to_owned()).collect()
}
}
impl<T: AsRef<str>, const N: usize> Prefixes for [T; N] {
fn prefixes(&self) -> Vec<String> {
self.iter().map(|prefix| prefix.as_ref().to_owned()).collect()
}
}
impl<T: AsRef<str>> Prefixes for Vec<T> {
fn prefixes(&self) -> Vec<String> {
self.iter().map(|prefix| prefix.as_ref().to_owned()).collect()
}
}
pub struct Text;
impl Text {
pub fn get(key: &str, default: Option<&str>, replace: &Replace, locale: Option<&str>) -> String {
let locale = match locale.filter(|locale| !locale.is_empty()) {
Some(locale) => locale.to_owned(),
None => laralocale::locale(),
};
let found = lookup(key, &locale);
let line = found.as_ref().map_or(key, |(line, _)| line.as_str());
let translation = make_replacements(line, replace);
if translation != key {
if let Some(count) = replace.count()
&& has_plural_forms(key, &locale)
{
let (raw, line_locale) = found.unwrap_or_else(|| (key.to_owned(), locale.clone()));
return make_replacements(&choose(&raw, count, &line_locale), replace);
}
return translation;
}
let mut translation = match default {
Some(default) => default.to_owned(),
None => key_to_text(key),
};
if is_pluralized(&translation, replace)
&& let Some(count) = replace.count()
{
translation = choose(&translation, count.trunc(), &locale);
}
make_replacements(&translation, replace)
}
pub fn frontend(prefixes: impl Prefixes, locale: Option<&str>) -> Frontend {
let locale = match locale.filter(|locale| !locale.is_empty()) {
Some(locale) => locale.to_owned(),
None => laralocale::locale(),
};
let prefixes = prefixes.prefixes();
let lines = Catalog::lines(&locale)
.iter()
.filter_map(|(key, line)| match line {
Value::String(line) if matches_prefix(key, &prefixes) => Some((key.clone(), line.clone())),
_ => None,
})
.collect();
Frontend { locale, lines }
}
pub fn script(prefixes: impl Prefixes, locale: Option<&str>) -> Html {
Html::raw(Self::script_tag(&Self::frontend(prefixes, locale)))
}
pub fn script_tag(payload: &Frontend) -> String {
format!(
"<script type=\"application/json\" data-laratext>{}</script>",
json::for_script(payload)
)
}
}
fn matches_prefix(key: &str, prefixes: &[String]) -> bool {
prefixes.iter().any(|prefix| {
prefix == "*"
|| key == prefix
|| key
.strip_prefix(prefix.as_str())
.is_some_and(|rest| rest.starts_with('.'))
})
}
fn is_pluralized(text: &str, replace: &Replace) -> bool {
text.contains('|') && replace.count().is_some()
}
fn has_plural_forms(key: &str, locale: &str) -> bool {
match lookup(key, locale) {
Some((raw, _)) => raw.contains('|'),
None => key.contains('|'),
}
}
fn lookup(key: &str, locale: &str) -> Option<(String, String)> {
for candidate in laralocale::candidates(locale) {
if candidate.is_empty() {
continue;
}
if let Some(line) = line_in(&candidate, key) {
return line.map(|line| (line, candidate));
}
}
None
}
fn line_in(locale: &str, key: &str) -> Option<Option<String>> {
let lines = Catalog::lines(locale);
Some(match lines.get(key)? {
Value::String(line) if !line.is_empty() && line != "0" => Some(line.clone()),
_ => None,
})
}