laralang 0.1.0

Localized routes for Laravel Rust: one route per language, translated paths, resources and hreflang alternates.
Documentation
use serde_json::{Map, Value, json};

use crate::pattern;
use crate::registry::Registry;

/// The localized routes in the shape Ziggy 2's JavaScript `route()` reads, so the same names work in
/// the browser as in Rust.
///
/// Laravel Rust has no Ziggy. Share this payload with your Inertia pages, and hand it to Ziggy's
/// `route(name, params, absolute, config)`, or to a `route()` of your own:
///
/// ```ignore
/// impl inertia::Middleware for HandleInertiaRequests {
///     async fn share(&self, _request: &Request) -> laravel::Result<Props> {
///         Ok(props! { ziggy => laralang::ziggy() })
///     }
/// }
/// ```
///
/// Like the PHP package's Ziggy integration, the routes of the current locale are also published
/// under their unprefixed name, so `route('dashboard')` in JavaScript resolves to the current
/// language while `route('es.dashboard')` still works. A name that already exists is never
/// replaced by an alias.
///
/// # Panics
///
/// Panics outside the application.
pub fn ziggy() -> Value {
    let registry = Registry::current();
    let locale = laralocale::locale();
    let prefix = format!("{locale}.");
    let mut routes = Map::new();
    let mut aliases = Vec::new();

    for entry in registry.entries() {
        let Some(name) = &entry.name else {
            continue;
        };
        let mut methods: Vec<String> = Vec::new();

        for method in &entry.methods {
            methods.push(method.clone());

            if method == "GET" {
                methods.push("HEAD".to_owned());
            }
        }

        let parameters = pattern::names(&entry.uri);
        let mut route = json!({ "uri": entry.uri.trim_start_matches('/'), "methods": methods });

        if !parameters.is_empty() {
            route["parameters"] = json!(parameters);
        }

        if let Some(alias) = name.strip_prefix(&prefix) {
            aliases.push((alias.to_owned(), route.clone()));
        }

        routes.insert(name.clone(), route);
    }

    for (alias, route) in aliases {
        routes.entry(alias).or_insert(route);
    }

    json!({
        "url": laravel::url::to("/"),
        "port": null,
        "defaults": {},
        "routes": routes,
        "locale": locale,
    })
}