oxblade 0.1.0

Blade templates for Laravel for Rust: Blade's markup and directives, Laravel's helpers, Rust's expressions. Community package, not affiliated with Laravel.
Documentation
use std::sync::Arc;

use indexmap::IndexMap;
use serde::Serialize;

use crate::{
    compile::Program,
    engine::{Environment, RequestContext},
    error::{Error, Frame, Result},
    library::{boolean, fault},
    loader::{Loader, Source, missing_view},
    render::Renderer,
    span::SourceMap,
    value::{Value, ValueMap, check_owned_layer},
};

impl<L: Loader> Environment<L> {
    /// Evaluates a registered condition, as Laravel's `Blade::check` does.
    pub fn check_condition(&self, name: &str, values: &[Value<'_>]) -> Result<bool> {
        let callback = self
            .extensions
            .conditions
            .get(name)
            .map(|(callback, _)| callback)
            .or_else(|| {
                self.extensions
                    .legacy_conditions
                    .contains(name)
                    .then(|| self.helpers.get(name))
                    .flatten()
            })
            .ok_or_else(|| fault(format!("unknown condition `{name}`")))?;
        boolean(&callback(values)?)
    }

    /// Compiles a source with this environment's extensions and registers its diagnostic spans.
    pub fn compile_source(&self, source: &Source, sources: &mut SourceMap) -> Result<Arc<Program>> {
        super::compile(
            &self.loader,
            source,
            sources,
            &self.directives,
            &self.extensions,
        )
    }

    /// Parses a view for static checking using the configured directive and source hooks.
    ///
    /// Plain input keeps all parser diagnostics. Source transformation failures surface as
    /// compilation diagnostics because the original text may no longer correspond to the spans.
    pub fn parse_source(
        &self,
        source: &Source,
        sources: &mut SourceMap,
    ) -> Result<crate::parser::Parsed> {
        if self.has_source_transforms() {
            return self
                .compile_source(source, sources)
                .map(|program| crate::parser::Parsed {
                    template: program.template().clone(),
                    errors: Vec::new(),
                });
        }
        let file = sources
            .add(&source.name, source.text.as_ref())
            .ok_or_else(|| {
                Error::new(
                    crate::error::ErrorKind::Limit,
                    "view source exceeds span limits",
                    None,
                )
            })?;
        Ok(crate::parser::parse(file, &source.text, &self.directives))
    }

    /// Compiles each supplied view and collects all load and compile failures for a cache check.
    ///
    /// The caller enumerates views through its application's loader or finder.
    pub fn compile_views<'n>(&self, names: impl IntoIterator<Item = &'n str>) -> Vec<Error> {
        names
            .into_iter()
            .filter_map(|name| {
                let mut sources = SourceMap::new();
                self.loader
                    .load(name)
                    .and_then(|source| self.compile_source(&source, &mut sources))
                    .err()
                    .map(|error| {
                        let mut error = error.with_frame(Frame {
                            name: name.into(),
                            span: None,
                        });
                        if let Some(location) = error.span.and_then(|span| sources.location(span)) {
                            error.message.push_str(&format!(
                                " at {}:{}:{}",
                                location.name, location.line, location.column
                            ));
                        }
                        self.loader.diagnose(&error, &sources);
                        error
                    })
            })
            .collect()
    }

    /// Tests whether a named view can be found.
    pub fn exists(&self, name: &str) -> Result<bool> {
        Ok(self.loader.find(name)?.is_some())
    }

    /// Renders the first existing view from a list of candidates.
    pub fn first<'a>(&self, names: &[&str], data: ValueMap<'a>) -> Result<String> {
        let data = check_owned_layer(data)?;
        for &name in names {
            if let Some(source) = self.loader.find(name)? {
                let request = RequestContext::default();
                let renderer = Renderer::new(self, &request);
                let eval = self.evaluator([data], &request, renderer.budget.clone());
                return renderer.render_source(name, source, eval, None);
            }
        }
        Err(missing_view(""))
    }

    /// Renders a child view and binds its HTML under the supplied key.
    pub fn nest<'a>(
        &self,
        data: &mut ValueMap<'a>,
        key: impl Into<String>,
        child: &str,
        child_data: ValueMap<'a>,
    ) -> Result<()> {
        if let Some(mut previous) =
            data.insert(key.into(), Value::html(self.render(child, child_data)?))
        {
            previous.reject_if_too_deep();
        }
        Ok(())
    }

    /// Renders a view when the condition is true, or returns an empty string.
    pub fn render_when<'a>(
        &self,
        condition: bool,
        name: &str,
        data: ValueMap<'a>,
    ) -> Result<String> {
        if condition {
            self.render(name, data)
        } else {
            drop(check_owned_layer(data)?);
            Ok(String::new())
        }
    }

    /// Renders a view when the condition is false, or returns an empty string.
    pub fn render_unless<'a>(
        &self,
        condition: bool,
        name: &str,
        data: ValueMap<'a>,
    ) -> Result<String> {
        self.render_when(!condition, name, data)
    }

    /// Renders a partial for each item with local `key` and item bindings.
    ///
    /// Empty collections can use a fallback view or explicitly trusted `raw|` text.
    pub fn render_each<'a>(
        &self,
        name: &str,
        items: Value<'a>,
        binding: &str,
        empty: Option<&str>,
    ) -> Result<String> {
        self.render_each_layers(name, items, binding, empty, [], &RequestContext::default())
    }

    /// Renders repeated isolated views using the supplied shared layers and request facts.
    pub fn render_each_layers<'a>(
        &self,
        name: &str,
        mut items: Value<'a>,
        binding: &str,
        empty: Option<&str>,
        layers: impl IntoIterator<Item = ValueMap<'a>>,
        request: &RequestContext<'a>,
    ) -> Result<String> {
        items.reject_if_too_deep();
        self.with_view_layers(name, layers, request, |renderer, layers| {
            renderer.render_each(name, &items, binding, empty, layers)
        })
    }

    /// Renders a view and returns the completed section contents.
    pub fn render_sections<'a>(
        &self,
        name: &str,
        data: ValueMap<'a>,
    ) -> Result<IndexMap<String, String>> {
        self.render_section_layers(name, [data], &RequestContext::default())
    }

    /// Captures every section using the supplied layers and request facts.
    pub fn render_section_layers<'a>(
        &self,
        name: &str,
        layers: impl IntoIterator<Item = ValueMap<'a>>,
        request: &RequestContext<'a>,
    ) -> Result<IndexMap<String, String>> {
        self.with_view_layers(name, layers, request, |renderer, layers| {
            renderer.render_sections(name, layers)
        })
    }

    /// Renders a Blade string using the environment's full extension configuration.
    pub fn render_str<'a>(&self, template: &str, data: ValueMap<'a>) -> Result<String> {
        let request = RequestContext::default();
        let renderer = Renderer::new(self, &request);
        let eval = self.evaluator([data], &request, renderer.budget.clone());
        renderer.render_source("<inline>", Source::new("<inline>", template), eval, None)
    }

    /// Renders a registered or anonymous component with the given props and an empty slot.
    pub fn render_component<'a>(&self, name: &str, props: ValueMap<'a>) -> Result<String> {
        let props = check_owned_layer(props)?;
        let request = RequestContext::default();
        let renderer = Renderer::new(self, &request);
        let mut eval = self.evaluator([], &request, renderer.budget.clone());
        renderer.render_component(name, props, &mut eval)
    }

    /// Converts typed, serializable view data, applying named display handlers by shape.
    ///
    /// The serializer bounds nesting at 128 levels. Custom serializers must use
    /// bounded stack space for work they do before calling oxblade's serializer
    /// methods, including when delegating to serde_json's map-key serializer.
    pub fn shape_data<'a>(&self, data: &(impl crate::Shape + Serialize)) -> Result<ValueMap<'a>> {
        super::display_data(data, &self.extensions.display)
    }

    /// Renders a typed view with its named display handlers.
    ///
    /// Models must meet the serialization requirements in [`Self::shape_data`].
    pub fn render_model<T: crate::View>(&self, model: &T) -> Result<String> {
        self.render(T::NAME, self.shape_data(model)?)
    }

    /// Adds the environment's custom condition signatures to a checker.
    pub fn configure_checker(&self, checker: &mut crate::check::Checker<'_>) {
        use crate::{check::Signature, shape::TypeDesc};

        checker
            .conditions
            .extend(
                self.extensions
                    .conditions
                    .iter()
                    .map(|(name, (_, parameters))| {
                        (
                            name.clone(),
                            Signature::new(parameters.clone(), TypeDesc::Bool),
                        )
                    }),
            );
        if !self.extensions.conditions.is_empty() || !self.extensions.legacy_conditions.is_empty() {
            checker.helpers.insert(
                "Blade::check".into(),
                Signature {
                    parameters: vec![TypeDesc::String],
                    variadic: Some(TypeDesc::Any),
                    returns: TypeDesc::Bool,
                },
            );
        }
    }

    /// Returns shapes added by view callbacks in the order they are applied.
    pub fn view_shapes(
        &self,
        view: &str,
        types: &mut crate::shape::TypeRegistry,
    ) -> Vec<crate::shape::TypeDesc> {
        let name = super::normalize(view);
        super::matching(&self.extensions.creators, &name)
            .chain(super::matching(&self.extensions.composers, &name))
            .map(|event| (event.describe)(types))
            .collect()
    }
}