livewire-rust 0.1.3

Livewire for Rust: server-rendered reactive components for Laravel for Rust.
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
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
//! The `.livewire` template engine: MiniJinja over the component's compiled source.
//!
//! A component's view is `resources/views/livewire/{name}.livewire`, or a namespace's directory. The
//! engine compiles the component directives into Jinja first, injects the morph markers and derived
//! wire keys, then renders with the framework's helpers and Livewire's own functions, so a component
//! template behaves like an ordinary `.html` view that can also render child components.

use std::fmt::Write as _;
use std::sync::{Arc, PoisonError, RwLock, Weak};

use laravel::view::minijinja::value::merge_maps;
use laravel::view::minijinja::{AutoEscape, Environment, Error, ErrorKind, UndefinedBehavior, Value};
use laravel::view::{DataLayers, Engine, Html, Template, TemplateError, ViewFinder};
use serde_json::Map;

use crate::assets::FrontendAssets;
use crate::compile::{CompileOptions, TemplateIdentity, compile};
use crate::component::Params;
use crate::config::LivewireConfig;
use crate::context::LivewireRequest;
use crate::frontend::Endpoints;
use crate::registry::ComponentRegistry;

/// Renders `.livewire` component views.
pub struct LivewireEngine {
    registry: Arc<ComponentRegistry>,
    environments: RwLock<Vec<Cached>>,
}

struct Cached {
    finder: Weak<ViewFinder>,
    environment: Arc<Environment<'static>>,
}

impl LivewireEngine {
    /// Creates the engine for the application's registered components.
    #[must_use]
    pub fn new(registry: Arc<ComponentRegistry>) -> Self {
        Self {
            registry,
            environments: RwLock::default(),
        }
    }

    /// The registry the engine renders components from.
    #[must_use]
    pub fn registry(&self) -> &Arc<ComponentRegistry> {
        &self.registry
    }

    /// The environment for a finder, built once per finder unless the application debugs its views.
    fn environment(&self, finder: &Arc<ViewFinder>, debug: bool) -> Arc<Environment<'static>> {
        if !debug {
            let cached = self
                .environments
                .read()
                .unwrap_or_else(PoisonError::into_inner)
                .iter()
                .find(|cached| std::ptr::eq(cached.finder.as_ptr(), Arc::as_ptr(finder)))
                .map(|cached| Arc::clone(&cached.environment));

            if let Some(environment) = cached {
                return environment;
            }
        }

        // Build outside the lock: a template configurator may render a view of its own.
        let environment = Arc::new(build_environment(
            Arc::clone(&self.registry),
            Some(Arc::downgrade(finder)),
            debug,
        ));

        if !debug {
            let mut environments = self.environments.write().unwrap_or_else(PoisonError::into_inner);
            environments.retain(|cached| cached.finder.strong_count() > 0);
            environments.push(Cached {
                finder: Arc::downgrade(finder),
                environment: Arc::clone(&environment),
            });
        }

        environment
    }
}

impl Engine for LivewireEngine {
    fn render(&self, template: &Template<'_>) -> Result<Html, laravel::Error> {
        let source = template.source()?;
        let identity = TemplateIdentity {
            name: template.name().to_owned(),
            source: template.extension().to_owned(),
        };

        let compiled = compile(
            &source,
            &identity,
            compile_options(LivewireConfig::of(template.config())),
        );
        let prepared = preprocess_blocks(&compiled);

        let environment = self.environment(template.finder(), template.debug());
        let layers = template.data_layers();

        let context = merge_maps([
            crate::jinja_helpers::session_context(template.session()),
            crate::jinja_helpers::old_input_context(template.old_input()),
            json_map(layers.shared),
            json_map(layers.request),
            json_map(layers.view),
            markup(layers),
        ]);

        let compiled_template = environment
            .template_from_str(&prepared)
            .map_err(|error| template_error(&error, template))?;

        let html = compiled_template
            .render(&context)
            .map_err(|error| template_error(&error, template))?;

        Ok(Html::raw(html))
    }
}

/// Renders a component view written in the component module, which has no finder.
///
/// # Errors
///
/// Fails when the source does not compile, or fails to render.
pub fn render_inline(
    registry: &Arc<ComponentRegistry>,
    source: &'static str,
    data: &Map<String, serde_json::Value>,
) -> Result<String, crate::error::LivewireError> {
    render_inline_with(registry, source, data, &Map::new())
}

/// Renders an inline view with `markup` marked safe, so a slot's elements are not escaped.
pub fn render_inline_with(
    registry: &Arc<ComponentRegistry>,
    source: &'static str,
    data: &Map<String, serde_json::Value>,
    markup: &Map<String, serde_json::Value>,
) -> Result<String, crate::error::LivewireError> {
    let identity = TemplateIdentity {
        name: "inline".to_owned(),
        source: "inline".to_owned(),
    };

    let compiled = compile(source, &identity, compile_options(registry.config()));
    let prepared = preprocess_blocks(&compiled);
    let environment = build_environment(Arc::clone(registry), None, false);

    let template =
        environment
            .template_from_str(&prepared)
            .map_err(|error| crate::error::LivewireError::ViewNotFound {
                view: format!("inline: {error}"),
            })?;

    let safe: Value = markup
        .iter()
        .map(|(name, html)| {
            (
                name.as_str(),
                Value::from_safe_string(html.as_str().unwrap_or_default().to_owned()),
            )
        })
        .collect();

    let context = merge_maps([
        crate::jinja_helpers::session_context(crate::session::current().as_ref()),
        crate::jinja_helpers::old_input_context(None),
        json_map(data),
        safe,
    ]);

    template
        .render(&context)
        .map_err(|error| crate::error::LivewireError::ViewNotFound {
            view: format!("inline: {error}"),
        })
}

/// The engine's compile options, from the application's configuration.
fn compile_options(config: &LivewireConfig) -> CompileOptions {
    CompileOptions {
        inject_morph_markers: config.inject_morph_markers,
        smart_wire_keys: config.smart_wire_keys,
    }
}

/// Builds the environment a `.livewire` template renders in.
#[expect(
    clippy::needless_pass_by_value,
    reason = "the environment takes ownership of the registry's functions and of one clone of it"
)]
fn build_environment(
    registry: Arc<ComponentRegistry>,
    finder: Option<Weak<ViewFinder>>,
    debug: bool,
) -> Environment<'static> {
    let mut environment = Environment::new();
    environment.set_debug(debug);
    environment.set_auto_escape_callback(|_| AutoEscape::Html);
    environment.set_formatter(crate::jinja_helpers::format);
    environment.set_undefined_behavior(UndefinedBehavior::SemiStrict);

    if let Some(finder) = finder {
        environment.set_loader(move |name| load(&finder, name));
    }

    crate::jinja_helpers::register(&mut environment);

    for configure in registry.template_configurators() {
        configure(&mut environment);
    }

    register_functions(&mut environment, &registry);

    environment
}

/// Adds Livewire's own template functions, which a component view and an ordinary page both use.
///
/// A `.html` page renders components with `{{ livewire("counter", {"count": 1}) }}` and puts the
/// runtime on the page with `{{ livewire_styles() }}` and `{{ livewire_scripts() }}`.
pub fn register_functions(environment: &mut Environment<'static>, registry: &Arc<ComponentRegistry>) {
    let components = Arc::clone(registry);
    environment.add_function("livewire", move |name: &str, params: Value, key: Option<Value>| {
        let params = match params.kind() {
            laravel::view::minijinja::value::ValueKind::Undefined
            | laravel::view::minijinja::value::ValueKind::None => Params::List(Vec::new()),
            _ => {
                let json = serde_json::to_value(&params)
                    .map_err(|error| Error::new(ErrorKind::InvalidOperation, error.to_string()))?;
                Params::from_json(json).map_err(|error| Error::new(ErrorKind::InvalidOperation, error.to_string()))?
            }
        };

        let key = key.and_then(|key| key.as_str().map(str::to_owned));

        crate::render::mount_child(&components, name, params, key, Map::new())
            .map(Value::from_safe_string)
            .map_err(|error| Error::new(ErrorKind::InvalidOperation, error.to_string()))
    });

    // A `@script` or `@assets` block runs once per request for a given component type and template
    // position, and the component's snapshot remembers that it ran, which the browser reads back.
    environment.add_function("livewire_begin_asset", |token: &str| -> bool {
        let Some(request) = LivewireRequest::current() else {
            return true;
        };

        let Some(id) = request.rendering() else {
            return true;
        };

        let name = request.read(&id, |state| state.name.clone()).unwrap_or_default();
        let key = format!("{name}:{token}");

        if !request.first_asset_render(&key) {
            return false;
        }

        request.change(&id, |state| {
            if token.starts_with("script:") {
                state.scripts.push(key);
            } else {
                state.assets.push(key);
            }
        });

        true
    });

    let styles = registry.config().clone();
    environment.add_function("livewire_styles", move || {
        if let Some(request) = LivewireRequest::current() {
            request.mark_styles_rendered();
        }

        Value::from_safe_string(FrontendAssets::new(&styles, endpoints(&styles)).styles().into_string())
    });

    let scripts = registry.config().clone();
    environment.add_function("livewire_scripts", move || {
        if let Some(request) = LivewireRequest::current() {
            request.mark_scripts_rendered();
        }

        let csrf = crate::session::csrf_token().unwrap_or_default();
        let nonce = laravel::view::csp_nonce();

        Value::from_safe_string(
            FrontendAssets::new(&scripts, endpoints(&scripts))
                .scripts(&csrf, nonce.as_deref(), &[])
                .into_string(),
        )
    });

    let config = registry.config().clone();
    environment.add_function("livewire_script_config", move || {
        let csrf = crate::session::csrf_token().unwrap_or_default();
        let nonce = laravel::view::csp_nonce();

        Value::from_safe_string(FrontendAssets::new(&config, endpoints(&config)).script_config(&csrf, nonce.as_deref()))
    });
}

/// The endpoint paths of the application being rendered.
fn endpoints(config: &LivewireConfig) -> Endpoints {
    let _ = config;

    match app_key() {
        Some(key) => Endpoints::new(&key),
        None => Endpoints::new("livewire"),
    }
}

/// The application's key as the configuration spells it, which the endpoint prefix hashes.
///
/// It must be the same string the provider hashed, so the page's update URI and the registered
/// route agree.
pub(crate) fn app_key() -> Option<String> {
    use laravel_core::context::Internals as _;

    let context = laravel_core::context::Context::current()?;

    context.config().app.key.clone()
}

/// Loads a view a component template extends or includes, from the application's views.
fn load(finder: &Weak<ViewFinder>, name: &str) -> Result<Option<String>, Error> {
    let finder = finder
        .upgrade()
        .ok_or_else(|| Error::new(ErrorKind::InvalidOperation, "the application's views are gone"))?;

    let file = finder
        .find_with(name, &["livewire", "html"])
        .map_err(|error| Error::new(ErrorKind::TemplateNotFound, error.to_string()))?;

    file.contents()
        .map(|source| Some(source.into_owned()))
        .map_err(|error| {
            Error::new(
                ErrorKind::InvalidOperation,
                format!("the view `{name}` can't be read from {}", file.path.display()),
            )
            .with_source(error)
        })
}

/// Rewrites the asset and script blocks into conditionals that render once per request, which
/// MiniJinja can express without a compiler extension.
fn preprocess_blocks(source: &str) -> String {
    let mut out = String::with_capacity(source.len());
    let mut rest = source;
    let mut assets = 0usize;
    let mut scripts = 0usize;

    while let Some(start) = rest.find("{%") {
        out.push_str(&rest[..start]);
        let tail = &rest[start..];

        if let Some(length) = directive(tail, "livewire_assets") {
            let _ = write!(out, "{{% if livewire_begin_asset(\"assets:{assets}\") %}}");
            assets += 1;
            rest = &tail[length..];
        } else if let Some(length) = directive(tail, "endlivewire_assets") {
            out.push_str("{% endif %}");
            rest = &tail[length..];
        } else if let Some(length) = directive(tail, "livewire_script") {
            let _ = write!(out, "{{% if livewire_begin_asset(\"script:{scripts}\") %}}");
            scripts += 1;
            rest = &tail[length..];
        } else if let Some(length) = directive(tail, "endlivewire_script") {
            out.push_str("{% endif %}");
            rest = &tail[length..];
        } else {
            out.push_str("{%");
            rest = &tail[2..];
        }
    }

    out.push_str(rest);
    out
}

/// The length of `{% name %}` when `tail` starts with it.
fn directive(tail: &str, name: &str) -> Option<usize> {
    let rest = tail.strip_prefix("{%")?;
    let rest = rest.trim_start().strip_prefix(name)?;
    let rest = rest.trim_start().strip_prefix("%}")?;

    Some(tail.len() - rest.len())
}

/// The markup a view was given, which renders unescaped.
fn markup(layers: DataLayers<'_>) -> Value {
    layers
        .markup
        .iter()
        .map(|(name, markup)| (name.as_str(), Value::from_safe_string(markup.as_str().to_owned())))
        .collect()
}

/// A JSON map as a template value.
fn json_map(map: &Map<String, serde_json::Value>) -> Value {
    map.iter()
        .map(|(name, value)| (name.clone(), laravel_http::view::json_value(value)))
        .collect()
}

/// A template error at its file and line, as the framework reports it.
fn template_error(error: &Error, template: &Template<'_>) -> laravel::Error {
    let mut located = TemplateError::new(error.kind().to_string(), template.path());

    if let Some(line) = error.line() {
        located = located.line(line);
    }
    if let Ok(contents) = template.source() {
        located = located.contents(contents);
    }

    located.into()
}

impl std::fmt::Debug for LivewireEngine {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("LivewireEngine")
            .field("components", &self.registry.names().len())
            .finish_non_exhaustive()
    }
}

#[cfg(test)]
mod tests {
    use super::{directive, preprocess_blocks};

    #[test]
    fn a_script_block_becomes_a_guarded_if_numbered_from_zero() {
        let source = "<div>{% livewire_script %}window.run = 1;{% endlivewire_script %}{% livewire_script %}two{% endlivewire_script %}</div>";

        let out = preprocess_blocks(source);

        assert_eq!(
            out,
            "<div>{% if livewire_begin_asset(\"script:0\") %}window.run = 1;{% endif %}\
             {% if livewire_begin_asset(\"script:1\") %}two{% endif %}</div>"
        );
        assert!(!out.contains("livewire_script"), "no block marker is left: {out}");
    }

    #[test]
    fn assets_and_scripts_are_numbered_apart() {
        let source = "{% livewire_assets %}a{% endlivewire_assets %}{% livewire_script %}s{% endlivewire_script %}";

        let out = preprocess_blocks(source);

        assert_eq!(
            out,
            "{% if livewire_begin_asset(\"assets:0\") %}a{% endif %}{% if livewire_begin_asset(\"script:0\") %}s{% endif %}"
        );
    }

    #[test]
    fn anything_else_is_left_exactly_as_it_was() {
        for source in [
            "",
            "plain text",
            "{% if count > 0 %}yes{% endif %}",
            "{% for item in items %}{{ item }}{% endfor %}",
            "<p>{ not jinja }</p>",
        ] {
            assert_eq!(preprocess_blocks(source), source, "{source:?} is untouched");
        }
    }

    #[test]
    fn a_directive_needs_its_own_word_and_a_close() {
        // Whitespace inside the tags is allowed, as Jinja allows it.
        assert!(directive("{%   livewire_script   %}body", "livewire_script").is_some());
        assert!(directive("{%livewire_script%}", "livewire_script").is_some());

        // A longer word is another directive, and a missing close is not a block at all.
        assert!(directive("{% livewire_scripture %}", "livewire_script").is_none());
        assert!(directive("{% livewire_script ", "livewire_script").is_none());
        assert!(directive("{{ livewire_script }}", "livewire_script").is_none());
    }

    #[test]
    fn a_directive_reports_its_whole_length() {
        let tail = "{% livewire_assets %}rest";
        let length = directive(tail, "livewire_assets").expect("the directive");

        assert_eq!(&tail[length..], "rest", "the caller continues after the tag");
    }
}