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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
//! Application-defined directives, conditions, source transforms, and view data hooks.

mod data;
mod source;
mod views;

pub(crate) use source::compile;

use std::sync::Arc;

use indexmap::{IndexMap, IndexSet};

use crate::{
    engine::RequestContext,
    error::Result,
    eval::Helper,
    library::{boolean, fault, integer, string},
    shape::TypeDesc,
    value::Value,
};

use crate::render::components::PrefixComponent;
pub use crate::render::components::{ComponentContext, Output, PrefixComponentRender, Slots};
pub use data::ViewData;
pub(crate) use data::{DisplayHandler, ViewEvent, display_data, matching, normalize};

type SourceHook = Arc<dyn Fn(&str) -> String + Send + Sync>;

#[derive(Clone, Default)]
pub(crate) struct Extensions {
    pub(crate) templates: IndexMap<String, String>,
    pub(crate) function_directives: IndexMap<String, FunctionDirective>,
    pub(crate) conditions: IndexMap<String, (Helper, Vec<TypeDesc>)>,
    pub(crate) legacy_conditions: IndexSet<String>,
    pub(crate) prepare: Vec<SourceHook>,
    pub(crate) precompilers: Vec<SourceHook>,
    pub(crate) creators: Vec<ViewEvent>,
    pub(crate) composers: Vec<ViewEvent>,
    pub(crate) display: IndexMap<String, DisplayHandler>,
    pub(crate) component_prefixes: IndexMap<String, PrefixComponent>,
}

pub(crate) type FunctionDirective = Arc<
    dyn for<'r, 'a> Fn(
            DirectiveArgs<'r, 'a>,
            &mut DirectiveOutput<'_>,
            &DirectiveContext<'r, 'a>,
        ) -> Result<()>
        + Send
        + Sync,
>;

/// Evaluated arguments of a registered function directive.
pub struct DirectiveArgs<'r, 'a>(pub(crate) &'r [Value<'a>]);

impl<'r, 'a> DirectiveArgs<'r, 'a> {
    /// Returns all evaluated arguments in source order.
    pub fn values(&self) -> &'r [Value<'a>] {
        self.0
    }

    /// Returns an argument or a render error reporting its position.
    pub fn get(&self, index: usize) -> Result<&'r Value<'a>> {
        self.0
            .get(index)
            .ok_or_else(|| fault(format!("missing directive argument {index}")))
    }

    /// Reads a plain string argument.
    pub fn string(&self, index: usize) -> Result<&'r str> {
        string(self.get(index)?)
    }

    /// Reads an integer argument.
    pub fn integer(&self, index: usize) -> Result<i64> {
        integer(self.get(index)?)
    }

    /// Reads a date accepted by the engine's formatting bridge.
    pub fn date(&self, index: usize) -> Result<&'r Value<'a>> {
        self.get(index)
    }
}

/// Writes a directive's output against the enclosing render's output budget.
pub struct DirectiveOutput<'a> {
    pub(crate) text: &'a mut String,
    pub(crate) budget: &'a crate::engine::RenderBudget,
    pub(crate) double_encode: bool,
}

impl DirectiveOutput<'_> {
    /// Writes text using the same HTML escaping as a regular echo.
    pub fn escaped(&mut self, text: &str) -> Result<()> {
        self.raw(&crate::encode::e_with_double_encode(
            text,
            self.double_encode,
        ))
    }

    /// Writes explicitly trusted markup supplied by the registered application function.
    pub fn raw(&mut self, html: &str) -> Result<()> {
        self.budget.charge_output(html.len())?;
        self.text.push_str(html);
        Ok(())
    }
}

/// Request and helper access made available to a function directive.
pub struct DirectiveContext<'r, 'a> {
    pub(crate) request: &'r RequestContext<'a>,
    pub(crate) evaluator: &'r crate::eval::Evaluator<'a>,
}

impl<'r, 'a> DirectiveContext<'r, 'a> {
    /// Returns the request facts for this render.
    pub fn request(&self) -> &'r RequestContext<'a> {
        self.request
    }

    /// Calls an application helper or built-in function with evaluated values.
    pub fn call(&self, name: &str, values: Vec<Value<'a>>) -> Result<Value<'a>> {
        self.evaluator.function(name, values)
    }

    /// Translates a message through the registered application translator.
    pub fn translate(&self, message: impl Into<String>) -> Result<String> {
        self.call("__", vec![Value::string(message.into())])?
            .display()
    }

    /// Formats a date with the engine's PHP-compatible date formatting helper.
    pub fn format_date(&self, date: &Value<'a>, format: &str) -> Result<String> {
        let date = self.call("date", vec![date.clone()])?;
        crate::formatting::method(
            "format",
            &date,
            vec![crate::value::Arg::Value(Value::string(format.to_owned()))],
        )
        .ok_or_else(|| fault("date formatting is unavailable"))??
        .display()
    }
}

/// A typed argument accepted by a custom condition.
pub trait ConditionArgument {
    /// Whether a trailing argument can be omitted.
    const OPTIONAL: bool = false;

    /// Argument representation borrowed for one invocation.
    type Borrowed<'a>;

    /// Reads the runtime argument without implicit type coercion.
    fn read<'a>(value: &'a Value<'_>) -> Result<Self::Borrowed<'a>>;

    /// Describes the argument to the static checker.
    fn shape() -> TypeDesc;
}

macro_rules! condition_arg {
    ($ty:ty, $borrowed:ty, $read:ident, $shape:ident) => {
        impl ConditionArgument for $ty {
            type Borrowed<'a> = $borrowed;
            fn read<'a>(value: &'a Value<'_>) -> Result<Self::Borrowed<'a>> {
                $read(value)
            }
            fn shape() -> TypeDesc {
                TypeDesc::$shape
            }
        }
    };
}

condition_arg!(&'static str, &'a str, string, String);
condition_arg!(String, String, owned_string, String);

fn owned_string(value: &Value<'_>) -> Result<String> {
    string(value).map(str::to_owned)
}
condition_arg!(i64, i64, integer, Int);
condition_arg!(bool, bool, boolean, Bool);

fn float(value: &Value<'_>) -> Result<f64> {
    match value.scalar() {
        Value::Float(value) => Ok(value),
        _ => Err(fault(format!("expected float, got {}", value.type_name()))),
    }
}

condition_arg!(f64, f64, float, Float);

impl<T: ConditionArgument> ConditionArgument for Option<T> {
    const OPTIONAL: bool = true;

    type Borrowed<'a> = Option<T::Borrowed<'a>>;

    fn read<'a>(value: &'a Value<'_>) -> Result<Self::Borrowed<'a>> {
        (!value.is_null()).then(|| T::read(value)).transpose()
    }

    fn shape() -> TypeDesc {
        TypeDesc::Option(Box::new(T::shape()))
    }
}

/// Converts a typed Rust closure to a condition usable from Blade.
pub trait Condition<Args> {
    /// Returns the runtime handler and the types expected by its parameters.
    fn into_condition(self) -> (Helper, Vec<TypeDesc>);
}

impl<F> Condition<()> for F
where
    F: Fn() -> bool + Send + Sync + 'static,
{
    fn into_condition(self) -> (Helper, Vec<TypeDesc>) {
        (
            Arc::new(move |args| {
                if !args.is_empty() {
                    return Err(fault("condition expects no arguments"));
                }
                Ok(Value::Bool(self()))
            }),
            Vec::new(),
        )
    }
}

macro_rules! condition {
    ($($arg:ident : $value:ident),+) => {
        impl<F, $($arg),+> Condition<($($arg,)+)> for F
        where
            $($arg: ConditionArgument + 'static,)+
            F: Fn($($arg),+) -> bool + for<'v> Fn($($arg::Borrowed<'v>),+) -> bool
                + Send + Sync + 'static,
        {
            fn into_condition(self) -> (Helper, Vec<TypeDesc>) {
                (Arc::new(move |args| {
                    let optional = [$($arg::OPTIONAL),+];
                    let max = optional.len();
                    let min = optional.iter().rposition(|optional| !optional).map_or(0, |index| index + 1);
                    if !(min..=max).contains(&args.len()) {
                        return Err(fault(format!("condition expects {min} to {max} arguments, got {}", args.len())));
                    }
                    let mut args = args.iter();
                    $(let $value = $arg::read(args.next().unwrap_or(&Value::Null))?;)+
                    Ok(Value::Bool(self($($value),+)))
                }), vec![$($arg::shape()),+])
            }
        }
    };
}

condition!(A: a);
condition!(A: a, B: b);
condition!(A: a, B: b, C: c);
condition!(A: a, B: b, C: c, D: d);
condition!(A: a, B: b, C: c, D: d, E: e);
condition!(A: a, B: b, C: c, D: d, E: e, G: g);

impl<L: crate::loader::Loader> crate::engine::EnvironmentBuilder<L> {
    /// Registers a template expansion with positional placeholders and an optional `{args}`.
    pub fn directive(mut self, name: &str, template: impl Into<String>) -> Self {
        self.clear_inline(name);
        self.0.directives.register_exact_directive(name, true);
        Arc::make_mut(&mut self.0.extensions)
            .templates
            .insert(name.to_owned(), template.into());
        self
    }

    /// Registers a function directive that writes output with access to the request and helpers.
    pub fn directive_fn<F>(mut self, name: &str, callback: F) -> Self
    where
        F: for<'r, 'a> Fn(
                DirectiveArgs<'r, 'a>,
                &mut DirectiveOutput<'_>,
                &DirectiveContext<'r, 'a>,
            ) -> Result<()>
            + Send
            + Sync
            + 'static,
    {
        self.clear_inline(name);
        self.0.directives.register_exact_directive(name, true);
        Arc::make_mut(&mut self.0.extensions)
            .function_directives
            .insert(name.to_owned(), Arc::new(callback));
        self
    }

    pub(crate) fn clear_inline(&mut self, name: &str) {
        let extensions = Arc::make_mut(&mut self.0.extensions);
        extensions.templates.shift_remove(name);
        extensions.function_directives.shift_remove(name);
        self.0.aliases.shift_remove(name);
    }

    /// Registers a typed Blade condition and its unless, else, and end directives.
    pub fn condition<Args>(mut self, name: &str, callback: impl Condition<Args>) -> Self {
        self.0.directives.register_exact_condition(name);
        Arc::make_mut(&mut self.0.extensions)
            .conditions
            .insert(name.to_owned(), callback.into_condition());
        self
    }

    pub(crate) fn install_condition_check(&mut self) {
        let extensions = &self.0.extensions;
        let mut conditions: IndexMap<_, _> = extensions
            .legacy_conditions
            .iter()
            .filter_map(|name| Some((name.clone(), self.0.helpers.get(name)?.clone())))
            .collect();
        conditions.extend(
            extensions
                .conditions
                .iter()
                .map(|(name, (callback, _))| (name.clone(), callback.clone())),
        );
        if conditions.is_empty() {
            return;
        }
        Arc::make_mut(&mut self.0.helpers).insert(
            "Blade::check".into(),
            Arc::new(move |args| {
                let [name, args @ ..] = args else {
                    return Err(fault("Blade::check requires a condition name"));
                };
                let name = string(name)?;
                let condition = conditions
                    .get(name)
                    .ok_or_else(|| fault(format!("unknown condition `{name}`")))?;
                condition(args)
            }),
        );
    }

    /// Registers a source transform that runs before Blade protects raw regions.
    pub fn prepare_source(
        mut self,
        callback: impl Fn(&str) -> String + Send + Sync + 'static,
    ) -> Self {
        Arc::make_mut(&mut self.0.extensions)
            .prepare
            .push(Arc::new(callback));
        self
    }

    /// Registers a source transform that sees opaque markers for raw regions and comments.
    pub fn precompiler(
        mut self,
        callback: impl Fn(&str) -> String + Send + Sync + 'static,
    ) -> Self {
        Arc::make_mut(&mut self.0.extensions)
            .precompilers
            .push(Arc::new(callback));
        self
    }

    /// Formats fields marked with the same `#[shape(display = "...")]` in typed view data.
    pub fn stringable(
        mut self,
        name: impl Into<String>,
        callback: impl Fn(&Value<'_>) -> String + Send + Sync + 'static,
    ) -> Self {
        Arc::make_mut(&mut self.0.extensions)
            .display
            .insert(name.into(), Arc::new(callback));
        self
    }

    /// Registers a typed data callback that runs when a matching view is created.
    ///
    /// Returned data must be safe to drop after bounded serialization. See
    /// [`crate::engine::Environment::shape_data`] for the serialization requirements.
    pub fn creator<I, P, F, T>(mut self, patterns: I, callback: F) -> Self
    where
        I: IntoIterator<Item = P>,
        P: AsRef<str>,
        T: crate::Shape + serde::Serialize,
        F: for<'a> Fn(ViewData<'_, 'a>) -> T + Send + Sync + 'static,
    {
        Arc::make_mut(&mut self.0.extensions)
            .creators
            .extend(ViewEvent::register(patterns, callback));
        self
    }

    /// Registers a typed data callback that runs after creators, before a matching view renders.
    ///
    /// Returned data must be safe to drop after bounded serialization. See
    /// [`crate::engine::Environment::shape_data`] for the serialization requirements.
    pub fn composer<I, P, F, T>(mut self, patterns: I, callback: F) -> Self
    where
        I: IntoIterator<Item = P>,
        P: AsRef<str>,
        T: crate::Shape + serde::Serialize,
        F: for<'a> Fn(ViewData<'_, 'a>) -> T + Send + Sync + 'static,
    {
        Arc::make_mut(&mut self.0.extensions)
            .composers
            .extend(ViewEvent::register(patterns, callback));
        self
    }
}