laratext 0.1.0

Laratext for Laravel Rust: translation keys with their source text, and auto-translation with OpenAI, Claude, Google Translate or Translatorio.
Documentation
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;

/// The translations of the keys under some prefixes, for JavaScript: what `Text::frontend()`
/// returns, `{locale, lines}`.
///
/// It serialises as that, so it can be shared as an Inertia prop as it is.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Frontend {
    /// The locale of the lines.
    pub locale: String,
    /// The lines, `[key => translation]`.
    pub lines: IndexMap<String, String>,
}

/// One or several key prefixes, as `Text::frontend()` takes them: `'header'` takes `header` and
/// `header.*`, and `'*'` takes every key.
pub trait Prefixes {
    /// The prefixes as a list.
    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()
    }
}

/// The translator of texts, PHP's `EduLazaro\Laratext\Text`.
///
/// ```ignore
/// Text::get("welcome.user", Some("Welcome, :name!"), &replace! { name => "John" }, None);
/// ```
///
/// [`text()`](crate::text()) and the [`text!`](crate::text!) macro are the shorter ways to call
/// [`Text::get`].
pub struct Text;

impl Text {
    /// The translation of a key in the current locale, or the source text when there is none yet.
    ///
    /// `default` is the source text. Without one, the text is made from the key: the last part
    /// after a dot, with the underscores read as spaces and each word capitalised, so
    /// `user.first_name` is `First Name`. That is the text `laratext:scan` gives the key, so the
    /// application reads the same before and after the next scan.
    ///
    /// The locale is laralocale's current one unless `locale` is given. A key missing from that
    /// locale's file is looked up in the fallback locale's before the source text is used.
    ///
    /// Placeholders (`:name`, `:Name`, `:NAME`) are replaced from `replace`. A text with forms
    /// separated by `|` and a numeric `count` in `replace` is pluralised with Laravel's rules.
    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 {
            // The key exists in the language file. When its text carries plural forms, the
            // placeholders are replaced but no form is chosen yet, so the choice is made here.
            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),
        };

        // The key is not in the language file yet, so the source text is used. Plural forms are
        // honoured here too, otherwise a brand new key would render every form at once until the
        // next scan.
        if is_pluralized(&translation, replace)
            && let Some(count) = replace.count()
        {
            translation = choose(&translation, count.trunc(), &locale);
        }

        make_replacements(&translation, replace)
    }

    /// The translations of the keys under the given prefixes, for JavaScript.
    ///
    /// Read from the language's JSON file, so a key not translated yet is left out and `text()` in
    /// the browser falls back to its source text, as it does here. `"*"` takes every key.
    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 }
    }

    /// The same translations in a JSON script tag, read by `text()` in the browser.
    pub fn script(prefixes: impl Prefixes, locale: Option<&str>) -> Html {
        Html::raw(Self::script_tag(&Self::frontend(prefixes, locale)))
    }

    /// The script tag of a payload. `<` and `>` are written as `<` and `>`, so a
    /// `</script>` inside a translation cannot close the tag.
    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('.'))
    })
}

/// Whether a text is written with plural forms and was given a quantity.
///
/// Both signals are required. Laravel only treats a pipe as a separator inside `trans_choice`, so a
/// text that merely contains one, such as `Ctrl|Alt`, must keep being returned untouched.
fn is_pluralized(text: &str, replace: &Replace) -> bool {
    text.contains('|') && replace.count().is_some()
}

/// Whether the stored translation of a key has plural forms. The raw line is read, without
/// replacements, so a replaced value that happens to contain a pipe is not mistaken for a form.
fn has_plural_forms(key: &str, locale: &str) -> bool {
    match lookup(key, locale) {
        Some((raw, _)) => raw.contains('|'),
        None => key.contains('|'),
    }
}

/// The line of a key and the locale it was found in: the locale's own file, then its language's
/// (`pt` for `pt_BR`), then the fallback locale's, as `laralocale::candidates` orders them.
/// Laravel's translator does not fall back for JSON strings, this does.
///
/// An empty line, or `0`, counts as missing, as `__()` treats them.
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
}

/// `None` when the file has no such key, `Some(None)` when it has one that counts as missing.
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,
    })
}