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
//! The MiniJinja functions `text()` and `texts()`, the equivalents of the `@text` and `@texts`
//! Blade directives.

use laravel::view::minijinja::value::{Kwargs, Rest};
use laravel::view::minijinja::{Environment, Error, ErrorKind, Value, value::ValueKind};

use crate::replace::{Replace, ReplaceValue};
use crate::text::Text;

/// Register `text()` and `texts()` in a MiniJinja environment.
pub fn register(environment: &mut Environment<'static>) {
    environment.add_function("text", text);
    environment.add_function("texts", texts);
}

/// `{{ text('key', 'Default', {'name': name}, 'es') }}`: the arguments of PHP's `text()`, by
/// position or by name (`key`, `default`, `replace`, `locale`).
fn text(args: Rest<Value>, kwargs: Kwargs) -> Result<String, Error> {
    let key = string(argument(&args, 0, &kwargs, "key")?, "key")?;
    let default = string(argument(&args, 1, &kwargs, "default")?, "default")?;
    let replace = argument(&args, 2, &kwargs, "replace")?;
    let locale = string(argument(&args, 3, &kwargs, "locale")?, "locale")?;

    kwargs.assert_all_used()?;

    let Some(key) = key else {
        return Err(Error::new(ErrorKind::MissingArgument, "text() needs a key"));
    };

    let replace = replace.as_ref().map(replacements).transpose()?.unwrap_or_default();

    Ok(Text::get(&key, default.as_deref(), &replace, locale.as_deref()))
}

/// `{{ texts(['header', 'cart']) }}`: the translations the page needs, in a `<script>` tag.
fn texts(args: Rest<Value>, kwargs: Kwargs) -> Result<Value, Error> {
    let prefixes = argument(&args, 0, &kwargs, "prefixes")?;
    let locale = string(argument(&args, 1, &kwargs, "locale")?, "locale")?;

    kwargs.assert_all_used()?;

    let prefixes = match prefixes {
        Some(value) if value.kind() == ValueKind::Seq => value
            .try_iter()?
            .map(|item| string(Some(item), "prefixes")?.ok_or_else(not_text))
            .collect::<Result<Vec<_>, _>>()?,
        Some(value) => vec![string(Some(value), "prefixes")?.ok_or_else(not_text)?],
        None => return Err(Error::new(ErrorKind::MissingArgument, "texts() needs the prefixes")),
    };

    let html = Text::script(prefixes, locale.as_deref());

    Ok(Value::from_safe_string(html.into_string()))
}

fn not_text() -> Error {
    Error::new(ErrorKind::InvalidOperation, "a prefix must be a string")
}

/// An argument by position, or by name when it was not given by position. `none` is no argument.
fn argument(args: &[Value], position: usize, kwargs: &Kwargs, name: &str) -> Result<Option<Value>, Error> {
    let by_name: Option<Value> = kwargs.get(name)?;

    Ok(args
        .get(position)
        .cloned()
        .or(by_name)
        .filter(|value| !value.is_none() && !value.is_undefined()))
}

fn string(value: Option<Value>, name: &str) -> Result<Option<String>, Error> {
    match value {
        None => Ok(None),
        Some(value) => match value.as_str() {
            Some(text) => Ok(Some(text.to_owned())),
            None => Err(Error::new(
                ErrorKind::InvalidOperation,
                format!("`{name}` must be a string"),
            )),
        },
    }
}

/// The values of a template's `{'name': value}` map as the replacements of a text.
fn replacements(value: &Value) -> Result<Replace, Error> {
    let mut replace = Replace::new();

    if value.kind() != ValueKind::Map {
        return Err(Error::new(
            ErrorKind::InvalidOperation,
            "the replacements of a text must be a map, such as {'name': name}",
        ));
    }

    for key in value.try_iter()? {
        let Some(name) = key.as_str().map(str::to_owned) else {
            continue;
        };

        let item = value.get_item(&key)?;

        replace.insert(name, replace_value(&item));
    }

    Ok(replace)
}

fn replace_value(value: &Value) -> ReplaceValue {
    match value.kind() {
        ValueKind::Undefined | ValueKind::None => ReplaceValue::Null,
        ValueKind::Bool => ReplaceValue::Bool(value.is_true()),
        ValueKind::Number => match value.as_i64() {
            Some(number) => ReplaceValue::Int(number),
            None => {
                f64::try_from(value.clone()).map_or_else(|_| ReplaceValue::Text(value.to_string()), ReplaceValue::Float)
            }
        },
        _ => ReplaceValue::Text(value.to_string()),
    }
}