Skip to main content

livewire/
engine.rs

1//! The `.livewire` template engine: MiniJinja over the component's compiled source.
2//!
3//! A component's view is `resources/views/livewire/{name}.livewire`, or a namespace's directory. The
4//! engine compiles the component directives into Jinja first, injects the morph markers and derived
5//! wire keys, then renders with the framework's helpers and Livewire's own functions, so a component
6//! template behaves like an ordinary `.html` view that can also render child components.
7
8use std::fmt::Write as _;
9use std::sync::{Arc, PoisonError, RwLock, Weak};
10
11use laravel::view::minijinja::value::merge_maps;
12use laravel::view::minijinja::{AutoEscape, Environment, Error, ErrorKind, UndefinedBehavior, Value};
13use laravel::view::{DataLayers, Engine, Html, Template, TemplateError, ViewFinder};
14use serde_json::Map;
15
16use crate::assets::FrontendAssets;
17use crate::compile::{CompileOptions, TemplateIdentity, compile};
18use crate::component::Params;
19use crate::config::LivewireConfig;
20use crate::context::LivewireRequest;
21use crate::frontend::Endpoints;
22use crate::registry::ComponentRegistry;
23
24/// Renders `.livewire` component views.
25pub struct LivewireEngine {
26    registry: Arc<ComponentRegistry>,
27    environments: RwLock<Vec<Cached>>,
28}
29
30struct Cached {
31    finder: Weak<ViewFinder>,
32    environment: Arc<Environment<'static>>,
33}
34
35impl LivewireEngine {
36    /// Creates the engine for the application's registered components.
37    #[must_use]
38    pub fn new(registry: Arc<ComponentRegistry>) -> Self {
39        Self {
40            registry,
41            environments: RwLock::default(),
42        }
43    }
44
45    /// The registry the engine renders components from.
46    #[must_use]
47    pub fn registry(&self) -> &Arc<ComponentRegistry> {
48        &self.registry
49    }
50
51    /// The environment for a finder, built once per finder unless the application debugs its views.
52    fn environment(&self, finder: &Arc<ViewFinder>, debug: bool) -> Arc<Environment<'static>> {
53        if !debug {
54            let cached = self
55                .environments
56                .read()
57                .unwrap_or_else(PoisonError::into_inner)
58                .iter()
59                .find(|cached| std::ptr::eq(cached.finder.as_ptr(), Arc::as_ptr(finder)))
60                .map(|cached| Arc::clone(&cached.environment));
61
62            if let Some(environment) = cached {
63                return environment;
64            }
65        }
66
67        // Build outside the lock: a template configurator may render a view of its own.
68        let environment = Arc::new(build_environment(
69            Arc::clone(&self.registry),
70            Some(Arc::downgrade(finder)),
71            debug,
72        ));
73
74        if !debug {
75            let mut environments = self.environments.write().unwrap_or_else(PoisonError::into_inner);
76            environments.retain(|cached| cached.finder.strong_count() > 0);
77            environments.push(Cached {
78                finder: Arc::downgrade(finder),
79                environment: Arc::clone(&environment),
80            });
81        }
82
83        environment
84    }
85}
86
87impl Engine for LivewireEngine {
88    fn render(&self, template: &Template<'_>) -> Result<Html, laravel::Error> {
89        let source = template.source()?;
90        let identity = TemplateIdentity {
91            name: template.name().to_owned(),
92            source: template.extension().to_owned(),
93        };
94
95        let compiled = compile(
96            &source,
97            &identity,
98            compile_options(LivewireConfig::of(template.config())),
99        );
100        let prepared = preprocess_blocks(&compiled);
101
102        let environment = self.environment(template.finder(), template.debug());
103        let layers = template.data_layers();
104
105        let context = merge_maps([
106            crate::jinja_helpers::session_context(template.session()),
107            crate::jinja_helpers::old_input_context(template.old_input()),
108            json_map(layers.shared),
109            json_map(layers.request),
110            json_map(layers.view),
111            markup(layers),
112        ]);
113
114        let compiled_template = environment
115            .template_from_str(&prepared)
116            .map_err(|error| template_error(&error, template))?;
117
118        let html = compiled_template
119            .render(&context)
120            .map_err(|error| template_error(&error, template))?;
121
122        Ok(Html::raw(html))
123    }
124}
125
126/// Renders a component view written in the component module, which has no finder.
127///
128/// # Errors
129///
130/// Fails when the source does not compile, or fails to render.
131pub fn render_inline(
132    registry: &Arc<ComponentRegistry>,
133    source: &'static str,
134    data: &Map<String, serde_json::Value>,
135) -> Result<String, crate::error::LivewireError> {
136    render_inline_with(registry, source, data, &Map::new())
137}
138
139/// Renders an inline view with `markup` marked safe, so a slot's elements are not escaped.
140pub fn render_inline_with(
141    registry: &Arc<ComponentRegistry>,
142    source: &'static str,
143    data: &Map<String, serde_json::Value>,
144    markup: &Map<String, serde_json::Value>,
145) -> Result<String, crate::error::LivewireError> {
146    let identity = TemplateIdentity {
147        name: "inline".to_owned(),
148        source: "inline".to_owned(),
149    };
150
151    let compiled = compile(source, &identity, compile_options(registry.config()));
152    let prepared = preprocess_blocks(&compiled);
153    let environment = build_environment(Arc::clone(registry), None, false);
154
155    let template =
156        environment
157            .template_from_str(&prepared)
158            .map_err(|error| crate::error::LivewireError::ViewNotFound {
159                view: format!("inline: {error}"),
160            })?;
161
162    let safe: Value = markup
163        .iter()
164        .map(|(name, html)| {
165            (
166                name.as_str(),
167                Value::from_safe_string(html.as_str().unwrap_or_default().to_owned()),
168            )
169        })
170        .collect();
171
172    let context = merge_maps([
173        crate::jinja_helpers::session_context(crate::session::current().as_ref()),
174        crate::jinja_helpers::old_input_context(None),
175        json_map(data),
176        safe,
177    ]);
178
179    template
180        .render(&context)
181        .map_err(|error| crate::error::LivewireError::ViewNotFound {
182            view: format!("inline: {error}"),
183        })
184}
185
186/// The engine's compile options, from the application's configuration.
187fn compile_options(config: &LivewireConfig) -> CompileOptions {
188    CompileOptions {
189        inject_morph_markers: config.inject_morph_markers,
190        smart_wire_keys: config.smart_wire_keys,
191    }
192}
193
194/// Builds the environment a `.livewire` template renders in.
195#[expect(
196    clippy::needless_pass_by_value,
197    reason = "the environment takes ownership of the registry's functions and of one clone of it"
198)]
199fn build_environment(
200    registry: Arc<ComponentRegistry>,
201    finder: Option<Weak<ViewFinder>>,
202    debug: bool,
203) -> Environment<'static> {
204    let mut environment = Environment::new();
205    environment.set_debug(debug);
206    environment.set_auto_escape_callback(|_| AutoEscape::Html);
207    environment.set_formatter(crate::jinja_helpers::format);
208    environment.set_undefined_behavior(UndefinedBehavior::SemiStrict);
209
210    if let Some(finder) = finder {
211        environment.set_loader(move |name| load(&finder, name));
212    }
213
214    crate::jinja_helpers::register(&mut environment);
215
216    for configure in registry.template_configurators() {
217        configure(&mut environment);
218    }
219
220    register_functions(&mut environment, &registry);
221
222    environment
223}
224
225/// Adds Livewire's own template functions, which a component view and an ordinary page both use.
226///
227/// A `.html` page renders components with `{{ livewire("counter", {"count": 1}) }}` and puts the
228/// runtime on the page with `{{ livewire_styles() }}` and `{{ livewire_scripts() }}`.
229pub fn register_functions(environment: &mut Environment<'static>, registry: &Arc<ComponentRegistry>) {
230    let components = Arc::clone(registry);
231    environment.add_function("livewire", move |name: &str, params: Value, key: Option<Value>| {
232        let params = match params.kind() {
233            laravel::view::minijinja::value::ValueKind::Undefined
234            | laravel::view::minijinja::value::ValueKind::None => Params::List(Vec::new()),
235            _ => {
236                let json = serde_json::to_value(&params)
237                    .map_err(|error| Error::new(ErrorKind::InvalidOperation, error.to_string()))?;
238                Params::from_json(json).map_err(|error| Error::new(ErrorKind::InvalidOperation, error.to_string()))?
239            }
240        };
241
242        let key = key.and_then(|key| key.as_str().map(str::to_owned));
243
244        crate::render::mount_child(&components, name, params, key, Map::new())
245            .map(Value::from_safe_string)
246            .map_err(|error| Error::new(ErrorKind::InvalidOperation, error.to_string()))
247    });
248
249    // A `@script` or `@assets` block runs once per request for a given component type and template
250    // position, and the component's snapshot remembers that it ran, which the browser reads back.
251    environment.add_function("livewire_begin_asset", |token: &str| -> bool {
252        let Some(request) = LivewireRequest::current() else {
253            return true;
254        };
255
256        let Some(id) = request.rendering() else {
257            return true;
258        };
259
260        let name = request.read(&id, |state| state.name.clone()).unwrap_or_default();
261        let key = format!("{name}:{token}");
262
263        if !request.first_asset_render(&key) {
264            return false;
265        }
266
267        request.change(&id, |state| {
268            if token.starts_with("script:") {
269                state.scripts.push(key);
270            } else {
271                state.assets.push(key);
272            }
273        });
274
275        true
276    });
277
278    let styles = registry.config().clone();
279    environment.add_function("livewire_styles", move || {
280        if let Some(request) = LivewireRequest::current() {
281            request.mark_styles_rendered();
282        }
283
284        Value::from_safe_string(FrontendAssets::new(&styles, endpoints(&styles)).styles().into_string())
285    });
286
287    let scripts = registry.config().clone();
288    environment.add_function("livewire_scripts", move || {
289        if let Some(request) = LivewireRequest::current() {
290            request.mark_scripts_rendered();
291        }
292
293        let csrf = crate::session::csrf_token().unwrap_or_default();
294        let nonce = laravel::view::csp_nonce();
295
296        Value::from_safe_string(
297            FrontendAssets::new(&scripts, endpoints(&scripts))
298                .scripts(&csrf, nonce.as_deref(), &[])
299                .into_string(),
300        )
301    });
302
303    let config = registry.config().clone();
304    environment.add_function("livewire_script_config", move || {
305        let csrf = crate::session::csrf_token().unwrap_or_default();
306        let nonce = laravel::view::csp_nonce();
307
308        Value::from_safe_string(FrontendAssets::new(&config, endpoints(&config)).script_config(&csrf, nonce.as_deref()))
309    });
310}
311
312/// The endpoint paths of the application being rendered.
313fn endpoints(config: &LivewireConfig) -> Endpoints {
314    let _ = config;
315
316    match app_key() {
317        Some(key) => Endpoints::new(&key),
318        None => Endpoints::new("livewire"),
319    }
320}
321
322/// The application's key as the configuration spells it, which the endpoint prefix hashes.
323///
324/// It must be the same string the provider hashed, so the page's update URI and the registered
325/// route agree.
326pub(crate) fn app_key() -> Option<String> {
327    use laravel_core::context::Internals as _;
328
329    let context = laravel_core::context::Context::current()?;
330
331    context.config().app.key.clone()
332}
333
334/// Loads a view a component template extends or includes, from the application's views.
335fn load(finder: &Weak<ViewFinder>, name: &str) -> Result<Option<String>, Error> {
336    let finder = finder
337        .upgrade()
338        .ok_or_else(|| Error::new(ErrorKind::InvalidOperation, "the application's views are gone"))?;
339
340    let file = finder
341        .find_with(name, &["livewire", "html"])
342        .map_err(|error| Error::new(ErrorKind::TemplateNotFound, error.to_string()))?;
343
344    file.contents()
345        .map(|source| Some(source.into_owned()))
346        .map_err(|error| {
347            Error::new(
348                ErrorKind::InvalidOperation,
349                format!("the view `{name}` can't be read from {}", file.path.display()),
350            )
351            .with_source(error)
352        })
353}
354
355/// Rewrites the asset and script blocks into conditionals that render once per request, which
356/// MiniJinja can express without a compiler extension.
357fn preprocess_blocks(source: &str) -> String {
358    let mut out = String::with_capacity(source.len());
359    let mut rest = source;
360    let mut assets = 0usize;
361    let mut scripts = 0usize;
362
363    while let Some(start) = rest.find("{%") {
364        out.push_str(&rest[..start]);
365        let tail = &rest[start..];
366
367        if let Some(length) = directive(tail, "livewire_assets") {
368            let _ = write!(out, "{{% if livewire_begin_asset(\"assets:{assets}\") %}}");
369            assets += 1;
370            rest = &tail[length..];
371        } else if let Some(length) = directive(tail, "endlivewire_assets") {
372            out.push_str("{% endif %}");
373            rest = &tail[length..];
374        } else if let Some(length) = directive(tail, "livewire_script") {
375            let _ = write!(out, "{{% if livewire_begin_asset(\"script:{scripts}\") %}}");
376            scripts += 1;
377            rest = &tail[length..];
378        } else if let Some(length) = directive(tail, "endlivewire_script") {
379            out.push_str("{% endif %}");
380            rest = &tail[length..];
381        } else {
382            out.push_str("{%");
383            rest = &tail[2..];
384        }
385    }
386
387    out.push_str(rest);
388    out
389}
390
391/// The length of `{% name %}` when `tail` starts with it.
392fn directive(tail: &str, name: &str) -> Option<usize> {
393    let rest = tail.strip_prefix("{%")?;
394    let rest = rest.trim_start().strip_prefix(name)?;
395    let rest = rest.trim_start().strip_prefix("%}")?;
396
397    Some(tail.len() - rest.len())
398}
399
400/// The markup a view was given, which renders unescaped.
401fn markup(layers: DataLayers<'_>) -> Value {
402    layers
403        .markup
404        .iter()
405        .map(|(name, markup)| (name.as_str(), Value::from_safe_string(markup.as_str().to_owned())))
406        .collect()
407}
408
409/// A JSON map as a template value.
410fn json_map(map: &Map<String, serde_json::Value>) -> Value {
411    map.iter()
412        .map(|(name, value)| (name.clone(), laravel_http::view::json_value(value)))
413        .collect()
414}
415
416/// A template error at its file and line, as the framework reports it.
417fn template_error(error: &Error, template: &Template<'_>) -> laravel::Error {
418    let mut located = TemplateError::new(error.kind().to_string(), template.path());
419
420    if let Some(line) = error.line() {
421        located = located.line(line);
422    }
423    if let Ok(contents) = template.source() {
424        located = located.contents(contents);
425    }
426
427    located.into()
428}
429
430impl std::fmt::Debug for LivewireEngine {
431    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
432        formatter
433            .debug_struct("LivewireEngine")
434            .field("components", &self.registry.names().len())
435            .finish_non_exhaustive()
436    }
437}
438
439#[cfg(test)]
440mod tests {
441    use super::{directive, preprocess_blocks};
442
443    #[test]
444    fn a_script_block_becomes_a_guarded_if_numbered_from_zero() {
445        let source = "<div>{% livewire_script %}window.run = 1;{% endlivewire_script %}{% livewire_script %}two{% endlivewire_script %}</div>";
446
447        let out = preprocess_blocks(source);
448
449        assert_eq!(
450            out,
451            "<div>{% if livewire_begin_asset(\"script:0\") %}window.run = 1;{% endif %}\
452             {% if livewire_begin_asset(\"script:1\") %}two{% endif %}</div>"
453        );
454        assert!(!out.contains("livewire_script"), "no block marker is left: {out}");
455    }
456
457    #[test]
458    fn assets_and_scripts_are_numbered_apart() {
459        let source = "{% livewire_assets %}a{% endlivewire_assets %}{% livewire_script %}s{% endlivewire_script %}";
460
461        let out = preprocess_blocks(source);
462
463        assert_eq!(
464            out,
465            "{% if livewire_begin_asset(\"assets:0\") %}a{% endif %}{% if livewire_begin_asset(\"script:0\") %}s{% endif %}"
466        );
467    }
468
469    #[test]
470    fn anything_else_is_left_exactly_as_it_was() {
471        for source in [
472            "",
473            "plain text",
474            "{% if count > 0 %}yes{% endif %}",
475            "{% for item in items %}{{ item }}{% endfor %}",
476            "<p>{ not jinja }</p>",
477        ] {
478            assert_eq!(preprocess_blocks(source), source, "{source:?} is untouched");
479        }
480    }
481
482    #[test]
483    fn a_directive_needs_its_own_word_and_a_close() {
484        // Whitespace inside the tags is allowed, as Jinja allows it.
485        assert!(directive("{%   livewire_script   %}body", "livewire_script").is_some());
486        assert!(directive("{%livewire_script%}", "livewire_script").is_some());
487
488        // A longer word is another directive, and a missing close is not a block at all.
489        assert!(directive("{% livewire_scripture %}", "livewire_script").is_none());
490        assert!(directive("{% livewire_script ", "livewire_script").is_none());
491        assert!(directive("{{ livewire_script }}", "livewire_script").is_none());
492    }
493
494    #[test]
495    fn a_directive_reports_its_whole_length() {
496        let tail = "{% livewire_assets %}rest";
497        let length = directive(tail, "livewire_assets").expect("the directive");
498
499        assert_eq!(&tail[length..], "rest", "the caller continues after the tag");
500    }
501}