laralang 0.1.0

Localized routes for Laravel Rust: one route per language, translated paths, resources and hreflang alternates.
Documentation
use laravel::head::Head;

use crate::current;
use crate::params::{IntoParams, Params};
use crate::registry::Registry;
use crate::url::url_of;

/// The current page in every locale that has it: locale to URL, in the order of the configured
/// locales.
///
/// For language switchers, `hreflang` tags and multi-locale sitemaps.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Alternates(Vec<(String, String)>);

impl Alternates {
    /// The URL in a locale.
    pub fn get(&self, locale: &str) -> Option<&str> {
        self.0
            .iter()
            .find(|(candidate, _)| candidate == locale)
            .map(|(_, url)| url.as_str())
    }

    /// The locales that have the page, in order.
    pub fn locales(&self) -> impl Iterator<Item = &str> {
        self.0.iter().map(|(locale, _)| locale.as_str())
    }

    /// The `(locale, url)` pairs, in order.
    pub fn iter(&self) -> impl Iterator<Item = (&str, &str)> {
        self.0.iter().map(|(locale, url)| (locale.as_str(), url.as_str()))
    }

    /// How many locales have the page.
    pub fn len(&self) -> usize {
        self.0.len()
    }

    /// Whether no locale has the page, as outside a localized route.
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    /// The `hreflang` links of these alternates, as `Head::alternate` writes them, to merge into
    /// the page's head.
    pub fn head(&self) -> Head {
        self.0
            .iter()
            .fold(Head::new(), |head, (locale, url)| head.alternate(locale, url))
    }
}

impl IntoIterator for Alternates {
    type Item = (String, String);
    type IntoIter = std::vec::IntoIter<(String, String)>;

    fn into_iter(self) -> Self::IntoIter {
        self.0.into_iter()
    }
}

/// The current route's URL in every configured locale.
///
/// The parameters of the current route are carried into every URL, so `{slug}` stays the same.
/// A locale that does not have the route is left out, so there are no dead links. Outside a
/// localized route, or on one without a name, it is empty.
///
/// ```ignore
/// let alternates = laralang::alternates()?;
/// // [("en", "https://example.com/services"), ("es", "https://example.com/es/servicios")]
/// ```
///
/// # Errors
///
/// Fails when a URL cannot be built, such as when the parameters you give miss one a locale needs.
pub fn alternates() -> laravel::Result<Alternates> {
    build(None, true)
}

/// [`alternates()`] with its two parameters: the route parameters to use instead of the current
/// route's, and whether the URLs are absolute. Relative URLs suit sitemaps that build the host
/// themselves.
///
/// ```ignore
/// laralang::alternates_with([("slug", "custom")], false)?;
/// ```
///
/// # Errors
///
/// As [`alternates()`].
pub fn alternates_with(params: impl IntoParams, absolute: bool) -> laravel::Result<Alternates> {
    build(Some(params.into_params()), absolute)
}

/// The global helper of the PHP package, which does what [`alternates()`] does.
///
/// # Errors
///
/// As [`alternates()`].
pub fn laralang_alternates() -> laravel::Result<Alternates> {
    alternates()
}

/// The `hreflang` links of the current page, as a `Head` to merge with `laravel::head::merge`.
///
/// ```ignore
/// laravel::head::merge(laralang::alternates_head()?);
/// ```
///
/// # Errors
///
/// As [`alternates()`].
pub fn alternates_head() -> laravel::Result<Head> {
    Ok(alternates()?.head())
}

fn build(params: Option<Params>, absolute: bool) -> laravel::Result<Alternates> {
    let (Some(registry), Some(matched)) = (
        Registry::try_current(),
        current::get().and_then(|current| current.route),
    ) else {
        return Ok(Alternates::default());
    };
    let Some(base) = matched.base else {
        return Ok(Alternates::default());
    };
    let params = match params {
        Some(params) if !params.is_empty() => params,
        _ => Params::from_pairs(matched.params),
    };
    let mut urls = Vec::new();

    for locale in &registry.settings().locales {
        if let Some(entry) = registry.get(&format!("{locale}.{base}")) {
            urls.push((locale.clone(), url_of(&entry, params.clone(), absolute)?));
        }
    }

    Ok(Alternates(urls))
}