oxblade 0.2.0

Laravel Blade templates for Rust: Blade's markup and directives with Rust expressions, rendering the same HTML as Laravel. Community package, not affiliated with Laravel.
Documentation
//! View source loading contract. Implementations resolve names and namespaces.

use crate::error::Result;
use std::{
    fs,
    path::{Path, PathBuf},
    sync::Arc,
};

/// An owned view source, suitable for file-backed and embedded templates.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Source {
    /// Filename or logical name used in diagnostics.
    pub name: String,
    /// Original template text.
    pub text: Arc<str>,
}

impl Source {
    /// Constructs a named template source.
    pub fn new(name: impl Into<String>, text: impl Into<Arc<str>>) -> Self {
        Self {
            name: name.into(),
            text: text.into(),
        }
    }
}

/// Resolves a view name to its source. Implementations own namespace and path lookup.
pub trait Loader {
    /// Loads a view by its logical name.
    fn load(&self, name: &str) -> Result<Source>;

    /// Compiles a prepared source or reuses a program for its exact source and span file ID.
    ///
    /// The callback uses the environment's directives. Cache entries must be scoped to a
    /// configuration whose compilation rules agree.
    fn compile(
        &self,
        _source: &Source,
        _file: crate::span::FileId,
        compile: &mut dyn FnMut() -> Result<crate::compile::Program>,
    ) -> Result<Arc<crate::compile::Program>> {
        compile().map(Arc::new)
    }

    /// Observes a render failure while the render's source map is still available.
    fn diagnose(&self, _error: &crate::error::Error, _sources: &crate::span::SourceMap) {}

    /// Searches the loader's anonymous component views.
    fn find_component(&self, name: &str) -> Result<Option<Source>> {
        for view in component_views(name) {
            if let Some(source) = self.find(&view)? {
                return Ok(Some(source));
            }
        }
        Ok(None)
    }

    /// Searches an optional view. Override to distinguish missing files from load failures.
    fn find(&self, name: &str) -> Result<Option<Source>> {
        match self.load(name) {
            Ok(source) => Ok(Some(source)),
            Err(error) if error.kind == crate::error::ErrorKind::Load => Ok(None),
            Err(error) => Err(error),
        }
    }
}

/// Returns the logical names tried for an anonymous component, in Blade's order.
pub fn component_views(name: &str) -> Vec<String> {
    let (namespace, name) = name
        .split_once("::")
        .map_or((None, name), |(ns, name)| (Some(ns), name));
    let leaf = name.rsplit('.').next().unwrap_or(name);
    let prefix = namespace.map_or_else(
        || format!("components.{name}"),
        |ns| format!("{ns}::{name}"),
    );
    vec![
        prefix.clone(),
        format!("{prefix}.index"),
        format!("{prefix}.{leaf}"),
    ]
}

/// A loader that keeps its views in memory: for tests, examples and templates compiled into the binary.
///
/// ```
/// use oxblade::loader::{Loader, MemoryLoader};
///
/// let views = MemoryLoader::new().view("welcome", "Hello, {{ name }}!");
/// assert_eq!(&*views.load("welcome").unwrap().text, "Hello, {{ name }}!");
/// assert!(views.load("missing").is_err());
/// ```
#[derive(Clone, Debug, Default)]
pub struct MemoryLoader {
    views: indexmap::IndexMap<String, Arc<str>>,
}

impl MemoryLoader {
    /// Creates a loader with no views.
    pub fn new() -> Self {
        Self::default()
    }

    /// Adds a view under its logical name, such as `welcome` or `components.alert`, replacing any view of
    /// the same name.
    pub fn view(mut self, name: impl Into<String>, text: impl Into<Arc<str>>) -> Self {
        self.insert(name, text);
        self
    }

    /// Adds or replaces a view in place.
    pub fn insert(&mut self, name: impl Into<String>, text: impl Into<Arc<str>>) {
        self.views.insert(name.into(), text.into());
    }
}

impl Loader for MemoryLoader {
    fn load(&self, name: &str) -> Result<Source> {
        self.views
            .get(name)
            .map(|text| Source::new(name, Arc::clone(text)))
            .ok_or_else(|| missing_view(name))
    }
}

/// A filesystem loader for .blade.html views and package overrides.
#[derive(Clone, Debug)]
pub struct FilesystemLoader {
    roots: Vec<PathBuf>,
    namespaces: indexmap::IndexMap<String, Vec<PathBuf>>,
    anonymous: Vec<PathBuf>,
}

impl FilesystemLoader {
    /// Creates a loader with the primary application view root.
    pub fn new(root: impl Into<PathBuf>) -> Self {
        Self {
            roots: vec![root.into()],
            namespaces: Default::default(),
            anonymous: Vec::new(),
        }
    }

    /// Adds another application view root in lookup order.
    pub fn root(mut self, root: impl Into<PathBuf>) -> Self {
        self.roots.push(root.into());
        self
    }

    /// Registers another unprefixed anonymous component search path.
    pub fn anonymous_path(mut self, root: impl Into<PathBuf>) -> Self {
        self.anonymous.push(root.into());
        self
    }

    /// Registers a package or anonymous-component namespace.
    pub fn namespace(mut self, name: impl Into<String>, root: impl Into<PathBuf>) -> Self {
        self.namespaces
            .entry(name.into())
            .or_default()
            .push(root.into());
        self
    }
}

impl Loader for FilesystemLoader {
    fn load(&self, name: &str) -> Result<Source> {
        self.find(name)?.ok_or_else(|| missing_view(name))
    }

    fn find_component(&self, name: &str) -> Result<Option<Source>> {
        let views = component_views(name);
        for view in &views {
            if let Some(source) = self.find(view)? {
                return Ok(Some(source));
            }
        }
        if !name.contains("::") {
            for root in &self.anonymous {
                for view in &views {
                    let logical = view.strip_prefix("components.").unwrap_or(view);
                    if let Some(source) = read_source(&root.join(relative_view(logical)?))? {
                        return Ok(Some(source));
                    }
                }
            }
        }
        Ok(None)
    }

    fn find(&self, name: &str) -> Result<Option<Source>> {
        let (namespace, logical) = name
            .split_once("::")
            .map_or((None, name), |(ns, view)| (Some(ns), view));
        if namespace.is_some_and(|ns| !valid_segment(ns)) {
            return Err(invalid_view());
        }
        let relative = relative_view(logical)?;
        let mut candidates = Vec::new();
        if let Some(namespace) = namespace {
            candidates.extend(
                self.roots
                    .iter()
                    .map(|root| root.join("vendor").join(namespace).join(&relative)),
            );
            if let Some(roots) = self.namespaces.get(namespace) {
                candidates.extend(roots.iter().map(|root| root.join(&relative)));
            }
        } else {
            candidates.extend(self.roots.iter().map(|root| root.join(&relative)));
        }
        for path in candidates {
            if let Some(source) = read_source(&path)? {
                return Ok(Some(source));
            }
        }
        Ok(None)
    }
}

fn valid_segment(segment: &str) -> bool {
    !segment.is_empty()
        && segment
            .chars()
            .all(|ch| ch.is_alphanumeric() || matches!(ch, '-' | '_'))
}

fn relative_view(name: &str) -> Result<PathBuf> {
    if !name.split('.').all(valid_segment) {
        return Err(invalid_view());
    }
    let mut relative = name.split('.').collect::<PathBuf>();
    if let Some(file) = relative.file_name() {
        relative.set_file_name(format!("{}.blade.html", file.to_string_lossy()));
    }
    Ok(relative)
}

fn invalid_view() -> crate::error::Error {
    crate::error::Error::new(crate::error::ErrorKind::Load, "invalid view name", None)
}

fn read_source(path: &Path) -> Result<Option<Source>> {
    let report = |error: std::io::Error| {
        crate::error::Error::new(
            crate::error::ErrorKind::Load,
            format!("cannot read view source: {}", error.kind()),
            None,
        )
    };
    match fs::metadata(path) {
        Ok(metadata) if metadata.is_file() => {
            let source = fs::read_to_string(path).map_err(report)?;
            Ok(Some(Source::new(path.to_string_lossy(), source)))
        }
        Ok(_) => Ok(None),
        Err(error)
            if matches!(
                error.kind(),
                std::io::ErrorKind::NotFound | std::io::ErrorKind::NotADirectory
            ) =>
        {
            Ok(None)
        }
        Err(error) => Err(report(error)),
    }
}

/// Constructs a missing-view diagnostic without including the requested name.
pub fn missing_view(_name: &str) -> crate::error::Error {
    crate::error::Error::new(crate::error::ErrorKind::Load, "view not found", None)
}