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 laravel::config::{Config, Env};
use laravel::container::Registrar;
use laravel::foundation::ServiceProvider;

use crate::translator::Translator;
use crate::translators::Translators;

/// Wires Laratext into the application: the configuration, the commands, the translators, the
/// `text()` and `texts()` functions in the views and the JavaScript module.
///
/// ```ignore
/// Application::configure().with_providers(|providers| {
///     providers.add(LaralocaleServiceProvider::new());
///     providers.add(LaratextServiceProvider::new());
/// })
/// ```
///
/// Laratext reads the current locale from laralocale, so register its provider too: it holds the
/// locale of each request. Set it with a middleware, or add `.with_detection()` to detect it.
#[derive(Clone)]
pub struct LaratextServiceProvider {
    translators: Translators,
}

impl LaratextServiceProvider {
    /// A provider with the four translators that ship with the package.
    pub fn new() -> Self {
        Self {
            translators: Translators::bundled(),
        }
    }

    /// Use these translators instead of the bundled ones, such as [`Translators::empty`] to
    /// register only your own.
    #[must_use]
    pub fn with_translators(mut self, translators: Translators) -> Self {
        self.translators = translators;

        self
    }

    /// Register a translator of your own under a name, which `--translator=` and
    /// `default_translator` take. It replaces a translator with the same name.
    ///
    /// ```ignore
    /// LaratextServiceProvider::new().translator("beautiful", || BeautifulTranslator)
    /// ```
    #[must_use]
    pub fn translator<T: Translator + 'static>(
        mut self,
        name: impl Into<String>,
        factory: impl Fn() -> T + Send + Sync + 'static,
    ) -> Self {
        self.translators.register(name, factory);

        self
    }
}

impl Default for LaratextServiceProvider {
    fn default() -> Self {
        Self::new()
    }
}

impl ServiceProvider for LaratextServiceProvider {
    fn config(&self, config: &mut Config, env: &Env) {
        config.discover(env!("CARGO_CRATE_NAME"), env);
    }

    fn register(&self, app: &mut Registrar) {
        app.instance(self.translators.clone());

        app.discover(env!("CARGO_CRATE_NAME"));

        app.routing().assets("laratext", laravel::embed!("resources/js"));

        #[cfg(feature = "minijinja")]
        app.views().minijinja(crate::views::register);
    }
}