Skip to main content

livewire/
render.rs

1//! Mounting, rendering, and updating a component.
2//!
3//! The order is upstream's, and it is what the browser depends on: a component boots, initializes,
4//! mounts, boots again, renders, dehydrates, and is destroyed; an update verifies the snapshot,
5//! rebuilds the component, applies the properties, runs the calls, then renders again unless an
6//! action or a redirect said not to.
7
8use std::sync::Arc;
9
10use laravel::http::Request;
11use serde_json::{Map, Value};
12
13use crate::checksum;
14use crate::component::{ActionResultKind, Call, Component, ComponentContext, ComponentView, Params, WireField};
15use crate::context::{Child, ComponentState, Download, LivewireRequest};
16use crate::error::LivewireError;
17use crate::hooks::HookEvent;
18use crate::html;
19use crate::registry::ComponentRegistry;
20use crate::snapshot::Snapshot;
21
22/// What a mount or an update produced.
23#[derive(Debug, Clone)]
24pub struct Rendered {
25    /// The component's instance ID.
26    pub id: String,
27    /// The component's registered name.
28    pub name: String,
29    /// The component's markup, with its wire attributes injected.
30    pub html: String,
31    /// The signed snapshot the browser sends back next time.
32    pub snapshot: Snapshot,
33    /// What the browser should do besides replacing the markup.
34    pub effects: Map<String, Value>,
35}
36
37/// What one component's update produced.
38#[derive(Debug, Clone)]
39pub struct Updated {
40    /// The new signed snapshot, or `None` when the component asked to skip its render.
41    pub snapshot: Option<Snapshot>,
42    /// What the browser should do with the response.
43    pub effects: Map<String, Value>,
44    /// Whether the browser should leave the component alone, as an unchanged reactive child asks.
45    pub skip: bool,
46    /// The frames the component streamed while it ran, which the response sends before its payload.
47    pub frames: Vec<Value>,
48}
49
50/// The request's Livewire state, created here when the caller has none, as a unit test does.
51fn state() -> Arc<LivewireRequest> {
52    LivewireRequest::current().unwrap_or_default()
53}
54
55/// The request being handled, for an action that reads the signed-in user or a service.
56fn current_request(request: &Arc<LivewireRequest>) -> Option<Arc<Request>> {
57    request.http_request()
58}
59
60/// Mounts the component `name`, and renders it to the markup the page embeds.
61///
62/// # Errors
63///
64/// Fails when the component is not registered, when a hook fails, or when the view renders no
65/// single root element.
66pub fn mount(
67    registry: &Arc<ComponentRegistry>,
68    name: &str,
69    params: Params,
70    key: Option<String>,
71    attributes: Map<String, Value>,
72) -> Result<Rendered, LivewireError> {
73    let request = state();
74    let http = current_request(&request);
75
76    mount_with(registry, name, params, key, attributes, &request, http)
77}
78
79/// Mounts a component within the caller's request state, which a nested render shares.
80#[expect(
81    clippy::needless_pass_by_value,
82    reason = "the key is forwarded into the snapshot the caller keeps"
83)]
84fn mount_with(
85    registry: &Arc<ComponentRegistry>,
86    name: &str,
87    params: Params,
88    key: Option<String>,
89    attributes: Map<String, Value>,
90    request: &Arc<LivewireRequest>,
91    http_request: Option<Arc<Request>>,
92) -> Result<Rendered, LivewireError> {
93    let fields = registry
94        .wire_fields(name)
95        .ok_or_else(|| LivewireError::ComponentNotFound { name: name.to_owned() })?;
96
97    let mut component = registry
98        .instantiate(name)
99        .ok_or_else(|| LivewireError::ComponentNotFound { name: name.to_owned() })?;
100
101    let id = laravel::str::random(20);
102    let (params, slots) = take_slots(params);
103    let (component_params, forwarded) = separate(params, fields, attributes);
104
105    request.register(
106        &id,
107        ComponentState {
108            name: name.to_owned(),
109            ..ComponentState::default()
110        },
111    );
112
113    hydrate_query(&mut *component, fields);
114
115    let mut context = ComponentContext::mounting(id.clone(), name.to_owned(), http_request);
116    context.request_metadata = forwarded.clone();
117
118    // The page this component renders on is part of the snapshot, so an update can replay the
119    // route it was mounted from.
120    if let Some(page) = request.page() {
121        context.memo.insert("path".to_owned(), Value::from(page.path));
122        context.memo.insert("method".to_owned(), Value::from(page.method));
123        context.memo.insert("origin".to_owned(), Value::from(page.origin));
124    }
125
126    // A slot is content the parent renders, not component state: it is kept out of `data` so the
127    // snapshot does not carry it, and out of the mount params so no field can claim it.
128    if !slots.is_empty() {
129        context.memo.insert("slots".to_owned(), Value::Object(slots.clone()));
130    }
131
132    registry.run_hooks(&HookEvent::BeforeMount { name });
133
134    // A lazy (or deferred) component renders its placeholder first: the browser fires
135    // `wire:init="__lazyLoad"` and the update that follows renders the real view.
136    let lazy = {
137        let options = component.class_options();
138        options.lazy || options.defer
139    };
140    if lazy {
141        context.memo.insert("lazyLoaded".to_owned(), Value::Bool(false));
142    }
143
144    let html = {
145        let _mounting = request.push_mounting(&id);
146
147        component.boot()?;
148        component.initialize(&mut context)?;
149        component.mount(component_params, &mut context)?;
150        component.booted()?;
151
152        let listeners: Vec<Value> = component
153            .listeners()
154            .iter()
155            .map(|listener| Value::from(listener.event))
156            .collect();
157        if !listeners.is_empty() {
158            context.add_effect("listeners", Value::Array(listeners));
159        }
160
161        let dispatches: Vec<Value> = component
162            .dispatches()
163            .iter()
164            .map(|listener| Value::from(listener.event))
165            .collect();
166        if !dispatches.is_empty() {
167            context.add_effect("dispatches", Value::Array(dispatches));
168        }
169
170        if lazy {
171            // The placeholder must be one root element, because the wire attributes are injected
172            // into it; the browser replaces its contents when the component loads.
173            String::from("<div></div>")
174        } else {
175            render_component(registry, &*component, &context.id, name, request, &slots)?
176        }
177    };
178
179    component.dehydrate(&mut context)?;
180
181    if let Some(url) = query_effect(fields) {
182        context.add_effect("url", Value::Object(url));
183    }
184    class_effects(&*component, &mut context);
185
186    emit_slot_fragments(request, &id, &mut context);
187
188    let snapshot = snapshot_for(registry, &*component, &id, name, request, &context, &forwarded)?;
189
190    component.destroy();
191
192    let mut attributes = vec![
193        ("wire:id".to_owned(), id.clone()),
194        ("wire:name".to_owned(), name.to_owned()),
195    ];
196    if let Some(key) = &key {
197        attributes.push(("wire:key".to_owned(), key.clone()));
198    }
199    if lazy {
200        attributes.push(("wire:init".to_owned(), "__lazyLoad".to_owned()));
201    }
202    attributes.push(("wire:snapshot".to_owned(), snapshot.encode()));
203    attributes.push(("wire:effects".to_owned(), encode_effects(&context.effects)?));
204
205    // A component that writes its own `wire:key` keeps it: injecting a second one would make the
206    // element's attributes invalid.
207    attributes.retain(|(name, _)| !first_tag_declares(&html, name));
208
209    let html = html::insert_attributes(&html, &attributes)?;
210
211    registry.run_hooks(&HookEvent::Mount { name, id: &id });
212
213    Ok(Rendered {
214        id,
215        name: name.to_owned(),
216        html,
217        snapshot,
218        effects: context.effects,
219    })
220}
221
222/// The slot content a `Params` carries, by name.
223fn slots_of(params: &Params) -> Map<String, Value> {
224    let Params::Named(names) = params else {
225        return Map::new();
226    };
227
228    ["slot", "slots"]
229        .into_iter()
230        .filter_map(|slot| names.get(slot).map(|content| (slot.to_owned(), content.clone())))
231        .collect()
232}
233
234/// A slot's content wrapped in the markers the browser's `renderSlot` reads, naming the component
235/// whose element holds it.
236fn slot_fragment(id: &str, name: &str, content: &str) -> String {
237    let metadata = format!("type=slot|name={name}|token={name}|id={id}");
238
239    format!("<!--[if FRAGMENT:{metadata}]><![endif]-->{content}<!--[if ENDFRAGMENT:{metadata}]><![endif]-->")
240}
241
242/// Splits the slot content a parent passed out of the mount params.
243///
244/// `slot` is the paired tag's content and `slots` holds named ones; neither is a component field,
245/// so neither reaches `mount` or the snapshot's `data`.
246fn take_slots(params: Params) -> (Params, Map<String, Value>) {
247    let Params::Named(mut names) = params else {
248        return (params, Map::new());
249    };
250
251    let mut slots = Map::new();
252    for name in ["slot", "slots"] {
253        if let Some(content) = names.remove(name) {
254            slots.insert(name.to_owned(), content);
255        }
256    }
257
258    (Params::Named(names), slots)
259}
260
261/// Hands the slots this component stubbed a child with to the browser, which morphs them inside the
262/// child's element instead of re-rendering the child.
263fn emit_slot_fragments(request: &Arc<LivewireRequest>, id: &str, context: &mut ComponentContext) {
264    let fragments = request
265        .read(id, |state| state.slot_fragments.clone())
266        .unwrap_or_default();
267
268    if !fragments.is_empty() {
269        context.add_effect(
270            "slotFragments",
271            Value::Array(fragments.into_iter().map(Value::from).collect()),
272        );
273    }
274}
275
276/// The origin an update came from: the page it was sent by, when it names one, or the host it was
277/// addressed to.
278fn origin_of(request: &Request) -> String {
279    request.header("origin").map_or_else(|| request.origin(), str::to_owned)
280}
281
282/// Whether an update can be answered with `skip` instead of a render.
283///
284/// Upstream's rule: a child whose parent rendered it this request, whose props are all unchanged,
285/// whose calls are only `$commit`, and which holds no bindings needs no render at all.
286#[must_use]
287pub fn should_skip(
288    registry: &Arc<ComponentRegistry>,
289    snapshot: &Snapshot,
290    updates: &Map<String, Value>,
291    calls: &[Call],
292) -> bool {
293    if !updates.is_empty() || calls.is_empty() {
294        return false;
295    }
296
297    if !calls.iter().all(|call| call.method == "$commit") {
298        return false;
299    }
300
301    let Ok(id) = snapshot.id() else { return false };
302
303    let props: Vec<&str> = snapshot
304        .memo_value("props")
305        .and_then(Value::as_array)
306        .map(|names| names.iter().filter_map(Value::as_str).collect())
307        .unwrap_or_default();
308    if props.is_empty() {
309        return false;
310    }
311
312    if snapshot
313        .memo_value("bindings")
314        .and_then(Value::as_object)
315        .is_some_and(|bindings| !bindings.is_empty())
316    {
317        return false;
318    }
319
320    let _ = registry;
321    let request = state();
322    let Some(provided) = request.read(id, |state| state.provided_props.clone()).flatten() else {
323        return false;
324    };
325
326    props.iter().all(|name| snapshot.data.get(*name) == provided.get(*name))
327}
328
329/// Mounts a component that another component's template renders, and records it on its parent.
330///
331/// # Errors
332///
333/// Fails as [`mount`] does.
334pub fn mount_child(
335    registry: &Arc<ComponentRegistry>,
336    name: &str,
337    params: Params,
338    key: Option<String>,
339    attributes: Map<String, Value>,
340) -> Result<String, LivewireError> {
341    let request = state();
342    let parent = request.rendering();
343
344    let key = match (parent.as_deref(), key) {
345        (Some(parent), None) => Some(next_child_key(&request, parent, name)),
346        (_, key) => key,
347    };
348
349    // A parent that renders the same child twice in one request embeds the first render's element
350    // again instead of mounting the child a second time.
351    if let (Some(parent), Some(key)) = (parent.as_deref(), key.as_deref())
352        && let Some(existing) = request.children(parent).into_iter().find(|child| child.key == key)
353    {
354        // The child re-renders only if these differ from what it already holds, so the params the
355        // parent passes now are kept for its own payload in this batch.
356        if let Params::Named(names) = &params {
357            let names = names.clone();
358            request.change(&existing.id, |state| state.provided_props = Some(names));
359        }
360
361        // The child is not rendered here, so its slot content comes back as a fragment the browser
362        // morphs inside the child's element.
363        for (slot, content) in slots_of(&params) {
364            let fragment = slot_fragment(&existing.id, &slot, content.as_str().unwrap_or_default());
365            request.change(parent, |state| state.slot_fragments.push(fragment));
366        }
367
368        return Ok(format!(
369            "<{tag} wire:id=\"{id}\" wire:name=\"{name}\"{key}></{tag}>",
370            tag = existing.tag,
371            id = existing.id,
372            key = if key.is_empty() {
373                String::new()
374            } else {
375                format!(" wire:key=\"{}\"", html::escape_attribute(key))
376            },
377        ));
378    }
379
380    let http = current_request(&request);
381    let rendered = mount_with(registry, name, params, key.clone(), attributes, &request, http)?;
382
383    if let Some(parent) = parent {
384        let tag = first_tag_name(&rendered.html).unwrap_or_else(|| "div".to_owned());
385        request.add_child(
386            &parent,
387            Child {
388                key: key.unwrap_or_default(),
389                tag,
390                id: rendered.id.clone(),
391            },
392        );
393    }
394
395    Ok(rendered.html)
396}
397
398/// A key for a child the template did not give one, stable for the child's position.
399fn next_child_key(request: &LivewireRequest, parent: &str, name: &str) -> String {
400    let children = request.children(parent);
401    let count = children
402        .iter()
403        .filter(|child| !child.id.is_empty() && !child.tag.is_empty())
404        .count();
405    let existing = children.iter().filter(|child| child.key.starts_with(name)).count();
406    let _ = count;
407
408    format!("{name}-{existing}")
409}
410
411/// Renders one component's view to markup.
412fn render_component(
413    registry: &Arc<ComponentRegistry>,
414    component: &dyn Component,
415    id: &str,
416    name: &str,
417    request: &Arc<LivewireRequest>,
418    slots: &Map<String, Value>,
419) -> Result<String, LivewireError> {
420    let view = component.render()?;
421
422    let mut data = Map::new();
423    component.render_values(&mut data);
424    data.remove("__meta__");
425    data.extend(component.computed_values(id));
426    // The template's `error(field)` helper reads this, so a failed validation is visible in the
427    // server-rendered markup as it is in `$errors`.
428    if let Some(errors) = request
429        .read(id, |state| state.errors.clone())
430        .filter(|errors| !errors.is_empty())
431    {
432        data.insert("livewire_errors".to_owned(), Value::Object(errors));
433    }
434
435    let _rendering = request.push_rendering(id);
436
437    let html = render_view_of(registry, &view, data, slots, id)?;
438
439    let roots = html::count_root_elements(&html);
440    if roots == 0 {
441        return Err(LivewireError::RootTagMissing);
442    }
443    if roots > 1 {
444        return Err(LivewireError::MultipleRootElements { name: name.to_owned() });
445    }
446
447    Ok(html)
448}
449
450/// Renders a component's view, whether it names a template or carries its own source.
451///
452/// # Errors
453///
454/// Fails when the view cannot be found or rendered.
455pub fn render_view(
456    registry: &Arc<ComponentRegistry>,
457    view: &ComponentView,
458    data: Map<String, Value>,
459) -> Result<String, LivewireError> {
460    render_view_with(registry, view, data, &Map::new())
461}
462
463/// Renders a component's view with `markup` marked safe, which is how a slot renders as elements
464/// rather than as text.
465fn render_view_with(
466    registry: &Arc<ComponentRegistry>,
467    view: &ComponentView,
468    data: Map<String, Value>,
469    markup: &Map<String, Value>,
470) -> Result<String, LivewireError> {
471    render_view_of(registry, view, data, markup, "")
472}
473
474/// Renders `view` for the component `id`, whose slots are marked as fragments of its element.
475fn render_view_of(
476    registry: &Arc<ComponentRegistry>,
477    view: &ComponentView,
478    data: Map<String, Value>,
479    markup: &Map<String, Value>,
480    id: &str,
481) -> Result<String, LivewireError> {
482    // Every slot is wrapped once, so a named and an inline view both carry the markers the browser
483    // needs to morph it in place.
484    let wrapped: Map<String, Value> = markup
485        .iter()
486        .map(|(slot, html)| {
487            (
488                slot.clone(),
489                Value::from(slot_fragment(id, slot, html.as_str().unwrap_or_default())),
490            )
491        })
492        .collect();
493
494    match view {
495        ComponentView::Named(name) => {
496            let mut page = laravel::view::view(name.clone(), Value::Object(data));
497            for (slot, html) in &wrapped {
498                page = page.with_html(
499                    slot.clone(),
500                    laravel::view::Html::raw(html.as_str().unwrap_or_default()),
501                );
502            }
503
504            page.render()
505                .map(|html| html.into_string())
506                .map_err(|error| LivewireError::ViewNotFound {
507                    view: format!("{name}: {error}"),
508                })
509        }
510        ComponentView::Inline { source, data: extra } => {
511            let mut data = data;
512            data.extend(extra.clone());
513            crate::engine::render_inline_with(registry, source, &data, &wrapped)
514        }
515    }
516}
517
518/// Reads the page's query string into the fields that follow it, and remembers what it held.
519///
520/// Upstream's `SupportQueryString` binds these fields on mount, so `?q=abc` is the component's
521/// starting value rather than something the browser has to send.
522fn hydrate_query(component: &mut dyn Component, fields: &[WireField]) {
523    let Some(query) = page_query() else {
524        return;
525    };
526
527    for field in fields {
528        let Some(binding) = field.url else {
529            continue;
530        };
531        let key = binding.as_name.unwrap_or(field.name);
532
533        let Some(raw) = query
534            .iter()
535            .find(|(name, _)| name == key)
536            .map(|(_, value)| value.clone())
537        else {
538            continue;
539        };
540
541        // A bare query value is a string, but the field may be a number or a boolean, so the value
542        // is read as JSON first and kept as a string only when it is not JSON.
543        let value = serde_json::from_str::<Value>(&raw).unwrap_or(Value::from(raw));
544        let _ = component.set_field(field.name, value);
545    }
546}
547
548/// The page's query string, decoded, or `None` outside a request.
549///
550/// An update request has no query of its own, so the page's query comes from the `Referer` header
551/// the browser sent with it, which is what upstream reads.
552fn page_query() -> Option<Vec<(String, String)>> {
553    use laravel_core::context::Internals as _;
554
555    let context = laravel_core::context::Context::current()?;
556    let request = context.request()?;
557
558    let query = match request.referer().and_then(|referer| referer.split_once('?')) {
559        Some((_, query)) => query.to_owned(),
560        None => request.query().to_owned(),
561    };
562
563    serde_urlencoded::from_str(&query).ok()
564}
565
566/// The `url` effect: one descriptor per field that follows the query string.
567///
568/// The browser owns the URL. It reads each property's value from the component and writes the query
569/// string itself, so the server sends only the descriptor: the key to write, whether a change
570/// pushes a history entry or replaces it, whether the key stays in the URL at its default, and
571/// which keys to leave out. Upstream sends it once, when the component mounts.
572fn query_effect(fields: &[WireField]) -> Option<Map<String, Value>> {
573    let mut effect = Map::new();
574
575    for field in fields.iter().filter(|field| field.url.is_some()) {
576        let Some(binding) = field.url else {
577            continue;
578        };
579
580        effect.insert(
581            field.name.to_owned(),
582            serde_json::json!({
583                "as": binding.as_name,
584                "use": if binding.push { "push" } else { "replace" },
585                "alwaysShow": binding.always_show,
586                "except": if binding.except.is_empty() { Value::Null } else { Value::from(binding.except) },
587            }),
588        );
589    }
590
591    (!effect.is_empty()).then_some(effect)
592}
593
594/// Resolves a `__dispatch` call to the listener method that handles its event.
595///
596/// The browser may only dispatch an event the component listens for, and the resolved method still
597/// goes through the action allowlist, so a dispatch can never reach a method an ordinary call
598/// could not.
599fn resolve_event_call(component: &dyn Component, call: Call) -> Result<Call, LivewireError> {
600    if call.method != "__dispatch" {
601        return Ok(call);
602    }
603
604    let event: String = call.params.arg("name", 0)?;
605    let params = call
606        .params
607        .optional::<Value>("params", 1)?
608        .unwrap_or(Value::Array(Vec::new()));
609
610    let listener = component
611        .listeners()
612        .iter()
613        .find(|listener| listener.event == event)
614        .ok_or_else(|| LivewireError::EventListenerMissing { event: event.clone() })?;
615
616    Ok(Call {
617        method: listener.method.unwrap_or(listener.event).to_owned(),
618        params: Params::from_json(params)?,
619        metadata: call.metadata,
620    })
621}
622
623/// The effects a component's class options add on every render.
624fn class_effects(component: &dyn Component, context: &mut ComponentContext) {
625    if let Some(transition) = component.class_options().transition {
626        context.add_effect("transition", serde_json::json!({"type": transition}));
627    }
628}
629
630/// Builds the snapshot the browser round-trips.
631fn snapshot_for(
632    registry: &Arc<ComponentRegistry>,
633    component: &dyn Component,
634    id: &str,
635    name: &str,
636    request: &Arc<LivewireRequest>,
637    context: &ComponentContext,
638    _attributes: &Map<String, Value>,
639) -> Result<Snapshot, LivewireError> {
640    let mut data = Map::new();
641    component.dehydrate_fields(&mut data);
642
643    // A session-backed field renders on the page but never crosses the wire: it is read back from
644    // the session, so the snapshot would only duplicate it.
645    if let Some(fields) = registry.wire_fields(name) {
646        for field in fields.iter().filter(|field| field.session.is_some()) {
647            data.remove(field.name);
648        }
649    }
650
651    let mut memo = Map::new();
652    memo.insert("id".to_owned(), Value::from(id));
653    memo.insert("name".to_owned(), Value::from(name));
654
655    let children = request.children(id);
656    let mut child_map = Map::new();
657    for child in children {
658        child_map.insert(
659            child.key.clone(),
660            Value::Array(vec![Value::from(child.tag), Value::from(child.id)]),
661        );
662    }
663    memo.insert("children".to_owned(), Value::Object(child_map));
664
665    memo.insert("release".to_owned(), Value::from(release_token(registry, component)));
666
667    // The browser reads these three from the snapshot: which actions answer with JSON, which it may
668    // send ahead of the others, and whether this component's requests skip the components around it.
669    let json = component.json_methods();
670    if !json.is_empty() {
671        memo.insert(
672            "json".to_owned(),
673            Value::Array(json.iter().map(|name| Value::from(*name)).collect()),
674        );
675    }
676
677    let mut asynchronous: Vec<&'static str> = component.async_methods().to_vec();
678    asynchronous.extend(json.iter().copied());
679    if !asynchronous.is_empty() {
680        memo.insert(
681            "async".to_owned(),
682            Value::Array(asynchronous.iter().map(|name| Value::from(*name)).collect()),
683        );
684    }
685
686    if component.class_options().isolate {
687        memo.insert("isolate".to_owned(), Value::Bool(true));
688    }
689
690    // The parent drives these: an update compares them before it decides to render the child at all.
691    if let Some(fields) = registry.wire_fields(name) {
692        let reactive: Vec<Value> = fields
693            .iter()
694            .filter(|field| field.reactive)
695            .map(|field| Value::from(field.name))
696            .collect();
697
698        if !reactive.is_empty() {
699            memo.insert("props".to_owned(), Value::Array(reactive));
700        }
701    }
702
703    // The browser's `$errors` bag reads these, so a field the server rejected keeps its message
704    // until the next accepted update.
705    if let Some(errors) = request
706        .read(id, |state| state.errors.clone())
707        .filter(|errors| !errors.is_empty())
708    {
709        memo.insert("errors".to_owned(), Value::Object(errors));
710    }
711
712    // Which `@script` and `@assets` blocks this render ran, so the browser does not run them twice.
713    let (scripts, assets) = request
714        .read(id, |state| (state.scripts.clone(), state.assets.clone()))
715        .unwrap_or_default();
716
717    if !scripts.is_empty() {
718        memo.insert(
719            "scripts".to_owned(),
720            Value::Array(scripts.iter().map(|key| Value::from(key.as_str())).collect()),
721        );
722    }
723    if !assets.is_empty() {
724        memo.insert(
725            "assets".to_owned(),
726            Value::Array(assets.iter().map(|key| Value::from(key.as_str())).collect()),
727        );
728    }
729
730    for (key, value) in &context.memo {
731        memo.insert(key.clone(), value.clone());
732    }
733
734    let mut snapshot = Snapshot {
735        data,
736        memo,
737        checksum: String::new(),
738    };
739
740    let key = app_key()?;
741    snapshot.checksum = checksum::sign(&snapshot, &key);
742
743    Ok(snapshot)
744}
745
746/// The token a redeployment changes: the protocol version, the application's token, and the
747/// component's own.
748fn release_token(registry: &ComponentRegistry, component: &dyn Component) -> String {
749    format!("a-{}-{}", registry.config().release_token, component.release_token())
750}
751
752/// The application's encryption key, which signs snapshots.
753pub(crate) fn app_key() -> Result<Vec<u8>, LivewireError> {
754    let context = laravel_core::context::Context::current().ok_or_else(|| {
755        LivewireError::MalformedPayload("Livewire needs the application to sign a snapshot".to_owned())
756    })?;
757
758    use laravel_core::context::Internals as _;
759
760    let encrypter = context.encrypter().map_err(|error| {
761        LivewireError::MalformedPayload(format!(
762            "the application's encryption key is missing or invalid: {error}"
763        ))
764    })?;
765
766    Ok(encrypter.key().to_vec())
767}
768
769/// Serializes the effects the browser reads off the element.
770fn encode_effects(effects: &Map<String, Value>) -> Result<String, LivewireError> {
771    serde_json::to_string(effects)
772        .map_err(|error| LivewireError::MalformedPayload(format!("the effects can't be serialized: {error}")))
773}
774
775/// Splits a mount's parameters into the component's props and the HTML attributes it forwards.
776fn separate(params: Params, fields: &[WireField], mut attributes: Map<String, Value>) -> (Params, Map<String, Value>) {
777    let Params::Named(named) = params else {
778        return (params, attributes);
779    };
780
781    let mut props = Map::new();
782    for (key, value) in named {
783        let camel = crate::component::camel_case(&key);
784
785        if is_reserved(&key) || fields.iter().any(|field| field.name == camel) {
786            props.insert(camel, value);
787        } else {
788            attributes.insert(key, value);
789        }
790    }
791
792    (Params::Named(props), attributes)
793}
794
795/// Whether a mount parameter is reserved by the protocol rather than forwarded as an attribute.
796fn is_reserved(key: &str) -> bool {
797    matches!(key, "lazy" | "defer" | "lazy.bundle" | "defer.bundle" | "wire:ref") || key.starts_with('@')
798}
799
800/// Whether the first element already declares `attribute`.
801fn first_tag_declares(html: &str, attribute: &str) -> bool {
802    let end = html.find('>').unwrap_or(html.len());
803    html[..end].contains(&format!("{attribute}="))
804}
805
806/// The first element's tag name, which a child's parent records.
807fn first_tag_name(html: &str) -> Option<String> {
808    let start = html.find('<')?;
809    let rest = &html[start + 1..];
810    let name: String = rest
811        .chars()
812        .take_while(|character| character.is_ascii_alphanumeric() || *character == '-')
813        .collect();
814
815    (!name.is_empty()).then_some(name)
816}
817
818/// Applies one property update, walking a dot path and rejecting one that is too deep.
819///
820/// # Errors
821///
822/// Fails when the path names no wire-public field, is deeper than the configured limit, or cannot
823/// be assigned.
824pub fn apply_update(
825    component: &mut dyn Component,
826    fields: &[WireField],
827    max_depth: Option<usize>,
828    path: &str,
829    value: Value,
830) -> Result<String, LivewireError> {
831    let segments: Vec<&str> = path.split('.').collect();
832    let root = segments[0];
833
834    let field = fields
835        .iter()
836        .find(|field| field.name == root)
837        .ok_or_else(|| LivewireError::UnknownProperty {
838            property: root.to_owned(),
839            component: String::new(),
840        })?;
841
842    if field.locked {
843        return Err(LivewireError::LockedProperty {
844            property: root.to_owned(),
845            component: String::new(),
846        });
847    }
848
849    if let Some(max) = max_depth
850        && segments.len() > max
851    {
852        return Err(LivewireError::NestingDepthExceeded {
853            path: path.to_owned(),
854            max,
855        });
856    }
857
858    if segments.len() == 1 {
859        component.set_field(root, value)?;
860        return Ok(root.to_owned());
861    }
862
863    // A nested update reads the field, changes the path inside it, and writes the field back: the
864    // component's fields are typed, so the change goes through the same setter a root update uses.
865    let mut current = Map::new();
866    component.dehydrate_fields(&mut current);
867    let mut document = current.remove(root).unwrap_or(Value::Null);
868
869    set_in_place(&mut document, &segments[1..], value)?;
870    component.set_field(root, document)?;
871
872    Ok(root.to_owned())
873}
874
875/// Sets `path` inside a JSON document the browser sent, treating `__rm__` as a removal.
876fn set_in_place(document: &mut Value, path: &[&str], value: Value) -> Result<(), LivewireError> {
877    let Some((first, rest)) = path.split_first() else {
878        *document = value;
879        return Ok(());
880    };
881
882    if rest.is_empty() {
883        return assign(document, first, value);
884    }
885
886    match document {
887        Value::Object(map) => {
888            let entry = map
889                .entry((*first).to_owned())
890                .or_insert_with(|| Value::Object(Map::new()));
891            set_in_place(entry, rest, value)
892        }
893        Value::Array(values) => {
894            let index = array_index(first)
895                .ok_or_else(|| LivewireError::MalformedPayload(format!("[{first}] is not an array index")))?;
896            let entry = values
897                .get_mut(index)
898                .ok_or_else(|| LivewireError::MalformedPayload(format!("the array has no index {index}")))?;
899            set_in_place(entry, rest, value)
900        }
901        _ => {
902            *document = Value::Object(Map::new());
903            set_in_place(document, path, value)
904        }
905    }
906}
907
908/// Assigns or removes one level of a JSON document.
909fn assign(document: &mut Value, key: &str, value: Value) -> Result<(), LivewireError> {
910    let removal = value.as_str() == Some("__rm__");
911
912    match document {
913        Value::Object(map) => {
914            if removal {
915                map.remove(key);
916            } else {
917                map.insert(key.to_owned(), value);
918            }
919            Ok(())
920        }
921        Value::Array(values) => {
922            let index = array_index(key)
923                .ok_or_else(|| LivewireError::MalformedPayload(format!("[{key}] is not an array index")))?;
924            if removal {
925                if index < values.len() {
926                    values.remove(index);
927                }
928            } else if index < values.len() {
929                values[index] = value;
930            } else {
931                values.push(value);
932            }
933            Ok(())
934        }
935        _ => {
936            *document = Value::Object(Map::new());
937            assign(document, key, value)
938        }
939    }
940}
941
942fn array_index(key: &str) -> Option<usize> {
943    key.parse::<usize>().ok()
944}
945
946/// Reads the download an action asked for, which the response sends instead of markup.
947#[must_use]
948pub fn download_of(request: &LivewireRequest, id: &str) -> Option<Download> {
949    request.read(id, |state| state.download.clone()).flatten()
950}
951
952/// Updates a component from its verified snapshot: properties first, then the calls, then a render
953/// unless an action or a redirect said to skip it.
954///
955/// The caller verifies the checksum, because the batch checks the client's failure allowance once
956/// however many components it updates.
957///
958/// # Errors
959///
960/// Fails on a release-token mismatch, a property the component does not publish or has locked, an
961/// unknown action, a denied action, or a failed render.
962pub async fn update(
963    registry: &Arc<ComponentRegistry>,
964    snapshot: &Snapshot,
965    updates: Map<String, Value>,
966    calls: Vec<Call>,
967    http: Option<Arc<Request>>,
968) -> Result<Updated, LivewireError> {
969    let request = state();
970    if let Some(http) = &http {
971        request.set_http_request(Arc::clone(http));
972    }
973
974    let name = snapshot.name()?.to_owned();
975    let id = snapshot.id()?.to_owned();
976
977    let fields = registry
978        .wire_fields(&name)
979        .ok_or_else(|| LivewireError::ComponentNotFound { name: name.clone() })?;
980
981    let mut component = registry
982        .instantiate(&name)
983        .ok_or_else(|| LivewireError::ComponentNotFound { name: name.clone() })?;
984
985    let expected = release_token(registry, &*component);
986    match snapshot.memo_value("release").and_then(Value::as_str) {
987        Some(release) if release == expected => {}
988        _ => return Err(LivewireError::ReleaseTokenMismatch),
989    }
990
991    let parent = snapshot
992        .memo_value("parent")
993        .and_then(|parent| parent.get(0))
994        .and_then(Value::as_str)
995        .map(str::to_owned);
996
997    // The parent may already have handed this child the props it passed in this request; the
998    // component's own state is replaced below, so its params are carried across by hand.
999    let provided_props = request.read(&id, |state| state.provided_props.clone()).flatten();
1000
1001    request.register(
1002        &id,
1003        ComponentState {
1004            name: name.clone(),
1005            parent,
1006            provided_props,
1007            ..ComponentState::default()
1008        },
1009    );
1010
1011    // A snapshot rendered on one origin may not be driven from another, even with a valid
1012    // checksum: the page it belongs to is where its route context is meaningful.
1013    if let (Some(snapshot_origin), Some(http)) = (snapshot.memo_value("origin").and_then(Value::as_str), http.as_ref())
1014        && snapshot_origin != origin_of(http)
1015    {
1016        return Err(LivewireError::InvalidRouteContext(format!(
1017            "the component was mounted on [{snapshot_origin}]"
1018        )));
1019    }
1020
1021    let mut context = ComponentContext::updating(id.clone(), name.clone(), http);
1022
1023    // A slot is the parent's content: only mount sees it, so the child keeps it in its memo from
1024    // one snapshot to the next. The update context carries it, and the snapshot builder signs it.
1025    if let Some(slots) = snapshot.memo_value("slots") {
1026        context.memo.insert("slots".to_owned(), slots.clone());
1027    }
1028
1029    // The children this component rendered last time are the ones its view will meet again: each
1030    // becomes a stub in the new markup, keeping its own ID rather than mounting afresh.
1031    for (key, child) in snapshot.children() {
1032        let Some(parts) = child.as_array() else { continue };
1033        let (Some(tag), Some(child_id)) = (
1034            parts.first().and_then(Value::as_str),
1035            parts.get(1).and_then(Value::as_str),
1036        ) else {
1037            continue;
1038        };
1039
1040        request.add_child(
1041            &id,
1042            Child {
1043                key,
1044                tag: tag.to_owned(),
1045                id: child_id.to_owned(),
1046            },
1047        );
1048    }
1049
1050    component.hydrate_fields(&snapshot.data)?;
1051    {
1052        let _guard = request.push_mounting(&id);
1053        component.boot()?;
1054        component.initialize(&mut context)?;
1055        component.hydrate(&mut context)?;
1056    }
1057
1058    // A model reference fetches its row before the hooks, the actions, and the render read it.
1059    component.hydrate_models(&mut context).await?;
1060
1061    // A reactive prop takes the value its parent passed in this request, so a changed parent
1062    // resets the child before it renders.
1063    if let Some(provided) = request.read(&id, |state| state.provided_props.clone()).flatten() {
1064        for field in fields.iter().filter(|field| field.reactive) {
1065            if let Some(value) = provided.get(field.name) {
1066                component.set_field(field.name, value.clone())?;
1067            }
1068        }
1069    }
1070
1071    registry.run_hooks(&HookEvent::BeforeUpdate { name: &name, id: &id });
1072
1073    let max_depth = registry.config().payload.max_nesting_depth;
1074    let mut touched: Vec<String> = Vec::new();
1075
1076    for (path, value) in &updates {
1077        let root = path.split('.').next().unwrap_or(path).to_owned();
1078        component.updating(&root, value, &mut context)?;
1079        apply_update(&mut *component, fields, max_depth, path, value.clone())?;
1080        if !touched.contains(&root) {
1081            touched.push(root);
1082        }
1083    }
1084
1085    for property in &touched {
1086        component.updated(property, &mut context)?;
1087    }
1088
1089    // An action that originates inside an island asks for that island's fragment back, not the
1090    // whole component's markup.
1091    let islands: Vec<(String, String)> = calls
1092        .iter()
1093        .filter_map(|call| {
1094            let island = call.metadata.get("island")?.as_object()?;
1095            let name = island.get("name")?.as_str()?.to_owned();
1096            let mode = island.get("mode").and_then(Value::as_str).unwrap_or("morph").to_owned();
1097
1098            Some((name, mode))
1099        })
1100        .collect();
1101
1102    let call_count = calls.len();
1103    let mut returns: Vec<Value> = Vec::with_capacity(call_count);
1104    let mut returns_meta = Map::new();
1105    let mut all_calls_are_json = call_count > 0;
1106
1107    let mut vetoed = false;
1108
1109    for (index, call) in calls.into_iter().enumerate() {
1110        let call = resolve_event_call(&*component, call)?;
1111
1112        // A rejected field stops the rest of the batch for this component, but the response still
1113        // carries every call's slot and renders the component, so the browser can show the error.
1114        if vetoed {
1115            returns.push(Value::Null);
1116            continue;
1117        }
1118
1119        // The upload calls are the runtime's own, not the component's: they answer with effects and
1120        // never reach an action of the same name.
1121        if crate::uploads::is_upload_call(&call.method) {
1122            let outcome = match call.method.as_str() {
1123                "_startUpload" => crate::uploads::start_upload(&mut context, registry.config(), &call)?,
1124                "_finishUpload" => crate::uploads::finish_upload(&mut *component, &mut context, &call)?,
1125                "_uploadErrored" => crate::uploads::upload_errored(&mut context, &call)?,
1126                _ => crate::uploads::remove_upload(&mut context, registry.config(), &call).await?,
1127            };
1128
1129            // An upload call never skips the render: the response carries the new field.
1130            all_calls_are_json = false;
1131            returns.push(outcome.unwrap_or(Value::Null));
1132            continue;
1133        }
1134        let method = call.method.clone();
1135        let json = component.action_result_kind(&method) == ActionResultKind::Json;
1136        all_calls_are_json &= json;
1137
1138        registry.run_hooks(&HookEvent::BeforeCall {
1139            name: &name,
1140            id: &id,
1141            method: &method,
1142        });
1143
1144        if !component.authorize(&method, &context).await? {
1145            if !json {
1146                return Err(LivewireError::Unauthorized { method: call.method });
1147            }
1148
1149            // A denied JSON action answers the caller with a status instead of failing the batch.
1150            returns_meta.insert(index.to_string(), serde_json::json!({"status": 403}));
1151            returns.push(Value::Null);
1152            continue;
1153        }
1154
1155        let outcome = component.call(call, &mut context).await;
1156        registry.run_hooks(&HookEvent::Call {
1157            name: &name,
1158            id: &id,
1159            method: &method,
1160        });
1161
1162        match outcome {
1163            Ok(value) => {
1164                // A JSON action that validated records its errors in the batch state; they ride
1165                // in the call's own slot, as upstream answers them.
1166                if json
1167                    && let Some(errors) = request
1168                        .read(&id, |state| state.errors.clone())
1169                        .filter(|errors| !errors.is_empty())
1170                {
1171                    returns_meta.insert(index.to_string(), serde_json::json!({ "errors": errors }));
1172                }
1173                returns.push(value.unwrap_or(Value::Null));
1174            }
1175            Err(LivewireError::ValidationFailed { errors }) => {
1176                // The messages are in the snapshot's memo; a JSON call also answers them in its
1177                // slot, as upstream does.
1178                if json {
1179                    returns_meta.insert(index.to_string(), serde_json::json!({ "errors": errors }));
1180                }
1181                returns.push(Value::Null);
1182                vetoed = true;
1183            }
1184            Err(error) => {
1185                if !json {
1186                    component.exception(&error, &mut context);
1187                    return Err(error);
1188                }
1189
1190                let status = u16::from(error.status());
1191                returns_meta.insert(index.to_string(), serde_json::json!({"status": status}));
1192                returns.push(Value::Null);
1193            }
1194        }
1195    }
1196
1197    // A call may have written a new key; the reference fetches it before this same response
1198    // renders, so an element bound to the model shows its row.
1199    component.hydrate_models(&mut context).await?;
1200
1201    registry.run_hooks(&HookEvent::Update { name: &name, id: &id });
1202
1203    // The browser aligns these with the calls it sent, so one entry per call, always.
1204    context.add_effect("returns", Value::Array(returns));
1205    if !returns_meta.is_empty() {
1206        context.add_effect("returnsMeta", Value::Object(returns_meta));
1207    }
1208
1209    let config = registry.config();
1210    let redirecting = context.effects.contains_key("redirect") || context.effects.contains_key("redirectUsingNavigate");
1211    let skipping = all_calls_are_json
1212        || context
1213            .effects
1214            .get("skipRender")
1215            .is_some_and(|value| value.as_bool().unwrap_or(false));
1216
1217    if skipping || (redirecting && !config.render_on_redirect) {
1218        // The state changed even when the markup does not, so the browser still receives a signed
1219        // snapshot to keep. Only the render is skipped; a missing snapshot would leave the client
1220        // parsing `undefined`.
1221        let next = snapshot_for(registry, &*component, &id, &name, &request, &context, &Map::new())?;
1222        let effects = std::mem::take(&mut context.effects);
1223        component.destroy();
1224
1225        return Ok(Updated {
1226            snapshot: Some(next),
1227            effects,
1228            skip: false,
1229            frames: context.streamed,
1230        });
1231    }
1232
1233    // The slots the parent passed at mount stay available to every later render of the child.
1234    let slots = snapshot
1235        .memo_value("slots")
1236        .and_then(Value::as_object)
1237        .cloned()
1238        .unwrap_or_default();
1239
1240    let html = {
1241        let _rendering = request.push_rendering(&id);
1242        render_component(registry, &*component, &id, &name, &request, &slots)?
1243    };
1244
1245    // The browser morphs an island's fragment in place, so the whole component's markup would only
1246    // duplicate that work and disturb the islands around it.
1247    let island_fragments: Vec<Value> = islands
1248        .iter()
1249        .filter_map(|(name, mode)| fragment_of(&html, "island", name).map(|fragment| fragment_in_mode(fragment, mode)))
1250        .map(Value::from)
1251        .collect();
1252
1253    component.dehydrate(&mut context)?;
1254    class_effects(&*component, &mut context);
1255
1256    // The first update renders what the mount left out; from then on the component is loaded.
1257    if snapshot.memo_value("lazyLoaded").is_some() {
1258        context.memo.insert("lazyLoaded".to_owned(), Value::Bool(true));
1259    }
1260
1261    emit_slot_fragments(&request, &id, &mut context);
1262
1263    let next = snapshot_for(registry, &*component, &id, &name, &request, &context, &Map::new())?;
1264
1265    // The client morphs this markup over the element it already has, and keeps the component only
1266    // while the root still names it. The snapshot and effects it reads back are the ones it just
1267    // received, so the attributes must carry them too.
1268    if island_fragments.is_empty() {
1269        let mut attributes = vec![
1270            ("wire:id".to_owned(), id.clone()),
1271            ("wire:name".to_owned(), name.clone()),
1272            ("wire:snapshot".to_owned(), next.encode()),
1273            ("wire:effects".to_owned(), encode_effects(&context.effects)?),
1274        ];
1275        attributes.retain(|(attribute, _)| !first_tag_declares(&html, attribute));
1276
1277        let html = html::insert_attributes(&html, &attributes)?;
1278        context.add_effect("html", Value::from(html));
1279    } else {
1280        context.add_effect("islandFragments", Value::Array(island_fragments));
1281    }
1282
1283    let effects = std::mem::take(&mut context.effects);
1284    component.destroy();
1285
1286    Ok(Updated {
1287        snapshot: Some(next),
1288        effects,
1289        skip: false,
1290        frames: std::mem::take(&mut context.streamed),
1291    })
1292}
1293
1294/// The fragment `html` holds for `kind` named `name`, markers included, as the browser's
1295/// `renderIsland`/`renderSlot` read it.
1296///
1297/// A fragment runs from its `<!--[if FRAGMENT:…]>` opener to the `<!--[if ENDFRAGMENT:…]>` closer
1298/// with the same metadata, so a nested island ends at its own closer rather than its parent's.
1299pub(crate) fn fragment_of(html: &str, kind: &str, name: &str) -> Option<String> {
1300    let mut rest = html;
1301
1302    while let Some(start) = rest.find("<!--[if FRAGMENT:") {
1303        let after = &rest[start..];
1304        let metadata_end = after.find("]>")?;
1305        let metadata = &after["<!--[if FRAGMENT:".len()..metadata_end];
1306
1307        let matches = metadata
1308            .split('|')
1309            .any(|field| field.strip_prefix("type=") == Some(kind))
1310            && metadata
1311                .split('|')
1312                .any(|field| field.strip_prefix("name=") == Some(name));
1313
1314        if matches {
1315            let closer = format!("<!--[if ENDFRAGMENT:{metadata}]>");
1316            let close_at = rest[start..].find(&closer)? + start;
1317            let end = close_at + closer.len() + "<![endif]-->".len();
1318
1319            return Some(rest[start..end].to_owned());
1320        }
1321
1322        rest = &rest[start + metadata_end + 2..];
1323    }
1324
1325    None
1326}
1327
1328/// The same fragment with its markers naming `mode`, which is how `wire:island.append` and
1329/// `.prepend` reach the browser: the client reads the mode from the fragment it receives.
1330fn fragment_in_mode(fragment: String, mode: &str) -> String {
1331    if mode == "morph" {
1332        return fragment;
1333    }
1334
1335    let mut out = String::with_capacity(fragment.len());
1336    let mut rest = fragment.as_str();
1337
1338    for marker in ["<!--[if FRAGMENT:", "<!--[if ENDFRAGMENT:"] {
1339        while let Some(at) = rest.find(marker) {
1340            let (head, tail) = rest.split_at(at + marker.len());
1341            out.push_str(head);
1342
1343            let close = tail.find(']').unwrap_or(tail.len());
1344            let metadata = &tail[..close];
1345            out.push_str(
1346                &metadata
1347                    .split('|')
1348                    .map(|field| match field.strip_prefix("mode=") {
1349                        Some(_) => format!("mode={mode}"),
1350                        None => field.to_owned(),
1351                    })
1352                    .collect::<Vec<_>>()
1353                    .join("|"),
1354            );
1355            rest = &tail[close..];
1356        }
1357    }
1358
1359    out.push_str(rest);
1360    out
1361}
1362
1363#[cfg(test)]
1364mod tests {
1365    use super::*;
1366    use crate::component::LivewireState as _;
1367    use crate::{LivewireComponent, component};
1368
1369    #[derive(Default, LivewireComponent)]
1370    #[livewire(inline = "<div></div>")]
1371    struct Nested {
1372        list: Vec<i32>,
1373        config: Map<String, Value>,
1374        title: String,
1375        #[livewire(locked)]
1376        id: String,
1377    }
1378
1379    #[component]
1380    impl Nested {}
1381
1382    fn fields() -> &'static [WireField] {
1383        Nested::wire_fields()
1384    }
1385
1386    #[test]
1387    fn a_root_update_reaches_its_field() {
1388        let mut component = Nested::default();
1389
1390        apply_update(&mut component, fields(), None, "title", Value::from("hi")).expect("updates");
1391
1392        assert_eq!(component.title, "hi");
1393    }
1394
1395    #[test]
1396    fn a_dotted_update_reaches_inside_an_array() {
1397        let mut component = Nested {
1398            list: vec![1, 2],
1399            ..Nested::default()
1400        };
1401
1402        apply_update(&mut component, fields(), None, "list.0", Value::from(9)).expect("updates");
1403
1404        assert_eq!(component.list, [9, 2]);
1405    }
1406
1407    #[test]
1408    fn a_removal_deletes_the_entry() {
1409        let mut component = Nested {
1410            list: vec![1, 2, 3],
1411            ..Nested::default()
1412        };
1413
1414        apply_update(&mut component, fields(), None, "list.1", Value::from("__rm__")).expect("updates");
1415
1416        assert_eq!(component.list, [1, 3]);
1417    }
1418
1419    #[test]
1420    fn a_dotted_update_creates_missing_objects() {
1421        let mut component = Nested::default();
1422
1423        apply_update(
1424            &mut component,
1425            fields(),
1426            None,
1427            "config.theme.color",
1428            Value::from("dark"),
1429        )
1430        .expect("updates");
1431
1432        assert_eq!(component.config["theme"]["color"], serde_json::json!("dark"));
1433    }
1434
1435    #[test]
1436    fn an_unknown_root_is_reported() {
1437        let mut component = Nested::default();
1438
1439        let error = apply_update(&mut component, fields(), None, "nope.deeper", Value::from(1)).expect_err("unknown");
1440
1441        assert!(matches!(error, LivewireError::UnknownProperty { .. }));
1442    }
1443
1444    #[test]
1445    fn a_locked_root_is_rejected_even_through_a_path() {
1446        let mut component = Nested::default();
1447
1448        let error = apply_update(&mut component, fields(), None, "id.inner", Value::from(1)).expect_err("locked");
1449
1450        assert!(matches!(error, LivewireError::LockedProperty { .. }));
1451    }
1452
1453    #[test]
1454    fn a_path_deeper_than_the_limit_is_rejected() {
1455        let mut component = Nested::default();
1456
1457        let error =
1458            apply_update(&mut component, fields(), Some(2), "config.a.b.c", Value::from(1)).expect_err("too deep");
1459
1460        assert!(matches!(error, LivewireError::NestingDepthExceeded { max: 2, .. }));
1461    }
1462
1463    #[test]
1464    fn a_slot_fragment_names_the_component_that_holds_it() {
1465        let fragment = slot_fragment("abc", "header", "<h1>hi</h1>");
1466
1467        assert_eq!(
1468            fragment,
1469            "<!--[if FRAGMENT:type=slot|name=header|token=header|id=abc]><![endif]--><h1>hi</h1>\
1470             <!--[if ENDFRAGMENT:type=slot|name=header|token=header|id=abc]><![endif]-->"
1471        );
1472        assert!(
1473            fragment_of(&fragment, "slot", "header").is_some(),
1474            "the parser reads it back"
1475        );
1476    }
1477
1478    #[test]
1479    fn slots_leave_the_mount_params() {
1480        let params = Params::Named(Map::from_iter([
1481            ("step".to_owned(), Value::from(1)),
1482            ("slot".to_owned(), Value::from("<em>x</em>")),
1483            ("slots".to_owned(), Value::from("named")),
1484        ]));
1485
1486        let (params, slots) = take_slots(params);
1487
1488        let Params::Named(params) = params else {
1489            panic!("named params")
1490        };
1491        assert_eq!(params.get("step"), Some(&Value::from(1)), "a real param stays");
1492        assert!(params.get("slot").is_none(), "the slot is not a mount param");
1493        assert!(params.get("slots").is_none());
1494        assert_eq!(slots.get("slot"), Some(&Value::from("<em>x</em>")));
1495        assert_eq!(slots.get("slots"), Some(&Value::from("named")));
1496    }
1497
1498    #[test]
1499    fn positional_params_carry_no_slots() {
1500        let (params, slots) = take_slots(Params::List(vec![Value::from(1)]));
1501
1502        assert!(matches!(params, Params::List(_)));
1503        assert!(slots.is_empty());
1504    }
1505
1506    #[test]
1507    fn a_fragment_is_cut_out_by_its_own_markers() {
1508        let open = |name: &str, token: &str| {
1509            format!("<!--[if FRAGMENT:type=island|name={name}|token={token}|mode=morph]><![endif]-->")
1510        };
1511        let close = |name: &str, token: &str| {
1512            format!("<!--[if ENDFRAGMENT:type=island|name={name}|token={token}|mode=morph]><![endif]-->")
1513        };
1514        let html = [
1515            "a",
1516            &open("outer", "t1"),
1517            &open("inner", "t2"),
1518            "i",
1519            &close("inner", "t2"),
1520            "x",
1521            &close("outer", "t1"),
1522            "b",
1523        ]
1524        .concat();
1525
1526        let inner = fragment_of(&html, "island", "inner").expect("the inner island");
1527        assert!(inner.starts_with("<!--[if FRAGMENT:type=island|name=inner"));
1528        assert!(
1529            !inner.contains("name=outer"),
1530            "the inner island ends at its own closer: {inner}"
1531        );
1532
1533        let outer = fragment_of(&html, "island", "outer").expect("the outer island");
1534        assert!(
1535            outer.contains("name=inner"),
1536            "the outer island spans the inner one: {outer}"
1537        );
1538        assert!(outer.ends_with("mode=morph]><![endif]-->"));
1539
1540        assert!(fragment_of(&html, "island", "missing").is_none());
1541        assert!(fragment_of(&html, "slot", "outer").is_none(), "the kind must match too");
1542    }
1543
1544    #[test]
1545    fn a_fragment_reaches_append_and_prepend_with_their_mode() {
1546        let html = "<!--[if FRAGMENT:type=island|name=log|token=t1|mode=morph]><![endif]-->row<!--[if ENDFRAGMENT:type=island|name=log|token=t1|mode=morph]><![endif]-->";
1547
1548        let appended = fragment_in_mode(fragment_of(html, "island", "log").expect("the island"), "append");
1549
1550        assert_eq!(
1551            appended.matches("mode=append").count(),
1552            2,
1553            "both markers name the mode: {appended}"
1554        );
1555        assert!(
1556            !appended.contains("mode=morph"),
1557            "no marker keeps the old mode: {appended}"
1558        );
1559        assert!(appended.contains(">row<"), "the content is untouched: {appended}");
1560
1561        assert_eq!(
1562            fragment_in_mode(html.to_owned(), "morph"),
1563            html,
1564            "morph leaves the fragment alone"
1565        );
1566    }
1567
1568    #[test]
1569    fn the_depth_limit_counts_the_root() {
1570        let mut component = Nested::default();
1571
1572        apply_update(&mut component, fields(), Some(2), "config.a", Value::from(1)).expect("within the limit");
1573    }
1574
1575    #[test]
1576    fn a_mount_separates_props_from_forwarded_attributes() {
1577        let attributes = Map::from_iter([("class".to_owned(), Value::from("p-4"))]);
1578        let params = Params::Named(Map::from_iter([
1579            ("title".to_owned(), Value::from("hello")),
1580            ("name".to_owned(), Value::from("sergio")),
1581            ("lazy".to_owned(), Value::from(true)),
1582            ("@click".to_owned(), Value::from("open()")),
1583        ]));
1584
1585        let (props, forwarded) = separate(params, fields(), attributes);
1586
1587        let Params::Named(props) = props else {
1588            panic!("named props")
1589        };
1590        assert_eq!(props["title"], serde_json::json!("hello"));
1591        assert_eq!(props["lazy"], serde_json::json!(true));
1592        assert!(!props.contains_key("name"));
1593        assert_eq!(forwarded["class"], serde_json::json!("p-4"));
1594        assert_eq!(forwarded["name"], serde_json::json!("sergio"));
1595        // A reserved param stays with the component instead of becoming an attribute, as upstream's
1596        // `isReservedParam` does.
1597        assert!(!forwarded.contains_key("@click"));
1598    }
1599
1600    #[test]
1601    fn a_positional_mount_keeps_its_parameters() {
1602        let (props, forwarded) = separate(Params::List(vec![Value::from(1)]), fields(), Map::new());
1603
1604        assert!(matches!(props, Params::List(_)));
1605        assert!(forwarded.is_empty());
1606    }
1607
1608    #[test]
1609    fn the_first_tag_name_is_read_from_the_markup() {
1610        assert_eq!(first_tag_name("<div class=\"a\">").as_deref(), Some("div"));
1611        assert_eq!(first_tag_name("  <my-widget>").as_deref(), Some("my-widget"));
1612        assert_eq!(first_tag_name("no markup"), None);
1613    }
1614}