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
427    let _rendering = request.push_rendering(id);
428
429    let html = render_view_of(registry, &view, data, slots, id)?;
430
431    let roots = html::count_root_elements(&html);
432    if roots == 0 {
433        return Err(LivewireError::RootTagMissing);
434    }
435    if roots > 1 {
436        return Err(LivewireError::MultipleRootElements { name: name.to_owned() });
437    }
438
439    Ok(html)
440}
441
442/// Renders a component's view, whether it names a template or carries its own source.
443///
444/// # Errors
445///
446/// Fails when the view cannot be found or rendered.
447pub fn render_view(
448    registry: &Arc<ComponentRegistry>,
449    view: &ComponentView,
450    data: Map<String, Value>,
451) -> Result<String, LivewireError> {
452    render_view_with(registry, view, data, &Map::new())
453}
454
455/// Renders a component's view with `markup` marked safe, which is how a slot renders as elements
456/// rather than as text.
457fn render_view_with(
458    registry: &Arc<ComponentRegistry>,
459    view: &ComponentView,
460    data: Map<String, Value>,
461    markup: &Map<String, Value>,
462) -> Result<String, LivewireError> {
463    render_view_of(registry, view, data, markup, "")
464}
465
466/// Renders `view` for the component `id`, whose slots are marked as fragments of its element.
467fn render_view_of(
468    registry: &Arc<ComponentRegistry>,
469    view: &ComponentView,
470    data: Map<String, Value>,
471    markup: &Map<String, Value>,
472    id: &str,
473) -> Result<String, LivewireError> {
474    // Every slot is wrapped once, so a named and an inline view both carry the markers the browser
475    // needs to morph it in place.
476    let wrapped: Map<String, Value> = markup
477        .iter()
478        .map(|(slot, html)| {
479            (
480                slot.clone(),
481                Value::from(slot_fragment(id, slot, html.as_str().unwrap_or_default())),
482            )
483        })
484        .collect();
485
486    match view {
487        ComponentView::Named(name) => {
488            let mut page = laravel::view::view(name.clone(), Value::Object(data));
489            for (slot, html) in &wrapped {
490                page = page.with_html(
491                    slot.clone(),
492                    laravel::view::Html::raw(html.as_str().unwrap_or_default()),
493                );
494            }
495
496            page.render()
497                .map(|html| html.into_string())
498                .map_err(|error| LivewireError::ViewNotFound {
499                    view: format!("{name}: {error}"),
500                })
501        }
502        ComponentView::Inline { source, data: extra } => {
503            let mut data = data;
504            data.extend(extra.clone());
505            crate::engine::render_inline_with(registry, source, &data, &wrapped)
506        }
507    }
508}
509
510/// Reads the page's query string into the fields that follow it, and remembers what it held.
511///
512/// Upstream's `SupportQueryString` binds these fields on mount, so `?q=abc` is the component's
513/// starting value rather than something the browser has to send.
514fn hydrate_query(component: &mut dyn Component, fields: &[WireField]) {
515    let Some(query) = page_query() else {
516        return;
517    };
518
519    for field in fields {
520        let Some(binding) = field.url else {
521            continue;
522        };
523        let key = binding.as_name.unwrap_or(field.name);
524
525        let Some(raw) = query
526            .iter()
527            .find(|(name, _)| name == key)
528            .map(|(_, value)| value.clone())
529        else {
530            continue;
531        };
532
533        // A bare query value is a string, but the field may be a number or a boolean, so the value
534        // is read as JSON first and kept as a string only when it is not JSON.
535        let value = serde_json::from_str::<Value>(&raw).unwrap_or(Value::from(raw));
536        let _ = component.set_field(field.name, value);
537    }
538}
539
540/// The page's query string, decoded, or `None` outside a request.
541///
542/// An update request has no query of its own, so the page's query comes from the `Referer` header
543/// the browser sent with it, which is what upstream reads.
544fn page_query() -> Option<Vec<(String, String)>> {
545    use laravel_core::context::Internals as _;
546
547    let context = laravel_core::context::Context::current()?;
548    let request = context.request()?;
549
550    let query = match request.referer().and_then(|referer| referer.split_once('?')) {
551        Some((_, query)) => query.to_owned(),
552        None => request.query().to_owned(),
553    };
554
555    serde_urlencoded::from_str(&query).ok()
556}
557
558/// The `url` effect: one descriptor per field that follows the query string.
559///
560/// The browser owns the URL. It reads each property's value from the component and writes the query
561/// string itself, so the server sends only the descriptor: the key to write, whether a change
562/// pushes a history entry or replaces it, whether the key stays in the URL at its default, and
563/// which keys to leave out. Upstream sends it once, when the component mounts.
564fn query_effect(fields: &[WireField]) -> Option<Map<String, Value>> {
565    let mut effect = Map::new();
566
567    for field in fields.iter().filter(|field| field.url.is_some()) {
568        let Some(binding) = field.url else {
569            continue;
570        };
571
572        effect.insert(
573            field.name.to_owned(),
574            serde_json::json!({
575                "as": binding.as_name,
576                "use": if binding.push { "push" } else { "replace" },
577                "alwaysShow": binding.always_show,
578                "except": if binding.except.is_empty() { Value::Null } else { Value::from(binding.except) },
579            }),
580        );
581    }
582
583    (!effect.is_empty()).then_some(effect)
584}
585
586/// Resolves a `__dispatch` call to the listener method that handles its event.
587///
588/// The browser may only dispatch an event the component listens for, and the resolved method still
589/// goes through the action allowlist, so a dispatch can never reach a method an ordinary call
590/// could not.
591fn resolve_event_call(component: &dyn Component, call: Call) -> Result<Call, LivewireError> {
592    if call.method != "__dispatch" {
593        return Ok(call);
594    }
595
596    let event: String = call.params.arg("name", 0)?;
597    let params = call
598        .params
599        .optional::<Value>("params", 1)?
600        .unwrap_or(Value::Array(Vec::new()));
601
602    let listener = component
603        .listeners()
604        .iter()
605        .find(|listener| listener.event == event)
606        .ok_or_else(|| LivewireError::EventListenerMissing { event: event.clone() })?;
607
608    Ok(Call {
609        method: listener.method.unwrap_or(listener.event).to_owned(),
610        params: Params::from_json(params)?,
611        metadata: call.metadata,
612    })
613}
614
615/// The effects a component's class options add on every render.
616fn class_effects(component: &dyn Component, context: &mut ComponentContext) {
617    if let Some(transition) = component.class_options().transition {
618        context.add_effect("transition", serde_json::json!({"type": transition}));
619    }
620}
621
622/// Builds the snapshot the browser round-trips.
623fn snapshot_for(
624    registry: &Arc<ComponentRegistry>,
625    component: &dyn Component,
626    id: &str,
627    name: &str,
628    request: &Arc<LivewireRequest>,
629    context: &ComponentContext,
630    _attributes: &Map<String, Value>,
631) -> Result<Snapshot, LivewireError> {
632    let mut data = Map::new();
633    component.dehydrate_fields(&mut data);
634
635    // A session-backed field renders on the page but never crosses the wire: it is read back from
636    // the session, so the snapshot would only duplicate it.
637    if let Some(fields) = registry.wire_fields(name) {
638        for field in fields.iter().filter(|field| field.session.is_some()) {
639            data.remove(field.name);
640        }
641    }
642
643    let mut memo = Map::new();
644    memo.insert("id".to_owned(), Value::from(id));
645    memo.insert("name".to_owned(), Value::from(name));
646
647    let children = request.children(id);
648    let mut child_map = Map::new();
649    for child in children {
650        child_map.insert(
651            child.key.clone(),
652            Value::Array(vec![Value::from(child.tag), Value::from(child.id)]),
653        );
654    }
655    memo.insert("children".to_owned(), Value::Object(child_map));
656
657    memo.insert("release".to_owned(), Value::from(release_token(registry, component)));
658
659    // The browser reads these three from the snapshot: which actions answer with JSON, which it may
660    // send ahead of the others, and whether this component's requests skip the components around it.
661    let json = component.json_methods();
662    if !json.is_empty() {
663        memo.insert(
664            "json".to_owned(),
665            Value::Array(json.iter().map(|name| Value::from(*name)).collect()),
666        );
667    }
668
669    let mut asynchronous: Vec<&'static str> = component.async_methods().to_vec();
670    asynchronous.extend(json.iter().copied());
671    if !asynchronous.is_empty() {
672        memo.insert(
673            "async".to_owned(),
674            Value::Array(asynchronous.iter().map(|name| Value::from(*name)).collect()),
675        );
676    }
677
678    if component.class_options().isolate {
679        memo.insert("isolate".to_owned(), Value::Bool(true));
680    }
681
682    // The parent drives these: an update compares them before it decides to render the child at all.
683    if let Some(fields) = registry.wire_fields(name) {
684        let reactive: Vec<Value> = fields
685            .iter()
686            .filter(|field| field.reactive)
687            .map(|field| Value::from(field.name))
688            .collect();
689
690        if !reactive.is_empty() {
691            memo.insert("props".to_owned(), Value::Array(reactive));
692        }
693    }
694
695    // The browser's `$errors` bag reads these, so a field the server rejected keeps its message
696    // until the next accepted update.
697    if let Some(errors) = request
698        .read(id, |state| state.errors.clone())
699        .filter(|errors| !errors.is_empty())
700    {
701        memo.insert("errors".to_owned(), Value::Object(errors));
702    }
703
704    // Which `@script` and `@assets` blocks this render ran, so the browser does not run them twice.
705    let (scripts, assets) = request
706        .read(id, |state| (state.scripts.clone(), state.assets.clone()))
707        .unwrap_or_default();
708
709    if !scripts.is_empty() {
710        memo.insert(
711            "scripts".to_owned(),
712            Value::Array(scripts.iter().map(|key| Value::from(key.as_str())).collect()),
713        );
714    }
715    if !assets.is_empty() {
716        memo.insert(
717            "assets".to_owned(),
718            Value::Array(assets.iter().map(|key| Value::from(key.as_str())).collect()),
719        );
720    }
721
722    for (key, value) in &context.memo {
723        memo.insert(key.clone(), value.clone());
724    }
725
726    let mut snapshot = Snapshot {
727        data,
728        memo,
729        checksum: String::new(),
730    };
731
732    let key = app_key()?;
733    snapshot.checksum = checksum::sign(&snapshot, &key);
734
735    Ok(snapshot)
736}
737
738/// The token a redeployment changes: the protocol version, the application's token, and the
739/// component's own.
740fn release_token(registry: &ComponentRegistry, component: &dyn Component) -> String {
741    format!("a-{}-{}", registry.config().release_token, component.release_token())
742}
743
744/// The application's encryption key, which signs snapshots.
745pub(crate) fn app_key() -> Result<Vec<u8>, LivewireError> {
746    let context = laravel_core::context::Context::current().ok_or_else(|| {
747        LivewireError::MalformedPayload("Livewire needs the application to sign a snapshot".to_owned())
748    })?;
749
750    use laravel_core::context::Internals as _;
751
752    let encrypter = context.encrypter().map_err(|error| {
753        LivewireError::MalformedPayload(format!(
754            "the application's encryption key is missing or invalid: {error}"
755        ))
756    })?;
757
758    Ok(encrypter.key().to_vec())
759}
760
761/// Serializes the effects the browser reads off the element.
762fn encode_effects(effects: &Map<String, Value>) -> Result<String, LivewireError> {
763    serde_json::to_string(effects)
764        .map_err(|error| LivewireError::MalformedPayload(format!("the effects can't be serialized: {error}")))
765}
766
767/// Splits a mount's parameters into the component's props and the HTML attributes it forwards.
768fn separate(params: Params, fields: &[WireField], mut attributes: Map<String, Value>) -> (Params, Map<String, Value>) {
769    let Params::Named(named) = params else {
770        return (params, attributes);
771    };
772
773    let mut props = Map::new();
774    for (key, value) in named {
775        let camel = crate::component::camel_case(&key);
776
777        if is_reserved(&key) || fields.iter().any(|field| field.name == camel) {
778            props.insert(camel, value);
779        } else {
780            attributes.insert(key, value);
781        }
782    }
783
784    (Params::Named(props), attributes)
785}
786
787/// Whether a mount parameter is reserved by the protocol rather than forwarded as an attribute.
788fn is_reserved(key: &str) -> bool {
789    matches!(key, "lazy" | "defer" | "lazy.bundle" | "defer.bundle" | "wire:ref") || key.starts_with('@')
790}
791
792/// Whether the first element already declares `attribute`.
793fn first_tag_declares(html: &str, attribute: &str) -> bool {
794    let end = html.find('>').unwrap_or(html.len());
795    html[..end].contains(&format!("{attribute}="))
796}
797
798/// The first element's tag name, which a child's parent records.
799fn first_tag_name(html: &str) -> Option<String> {
800    let start = html.find('<')?;
801    let rest = &html[start + 1..];
802    let name: String = rest
803        .chars()
804        .take_while(|character| character.is_ascii_alphanumeric() || *character == '-')
805        .collect();
806
807    (!name.is_empty()).then_some(name)
808}
809
810/// Applies one property update, walking a dot path and rejecting one that is too deep.
811///
812/// # Errors
813///
814/// Fails when the path names no wire-public field, is deeper than the configured limit, or cannot
815/// be assigned.
816pub fn apply_update(
817    component: &mut dyn Component,
818    fields: &[WireField],
819    max_depth: Option<usize>,
820    path: &str,
821    value: Value,
822) -> Result<String, LivewireError> {
823    let segments: Vec<&str> = path.split('.').collect();
824    let root = segments[0];
825
826    let field = fields
827        .iter()
828        .find(|field| field.name == root)
829        .ok_or_else(|| LivewireError::UnknownProperty {
830            property: root.to_owned(),
831            component: String::new(),
832        })?;
833
834    if field.locked {
835        return Err(LivewireError::LockedProperty {
836            property: root.to_owned(),
837            component: String::new(),
838        });
839    }
840
841    if let Some(max) = max_depth
842        && segments.len() > max
843    {
844        return Err(LivewireError::NestingDepthExceeded {
845            path: path.to_owned(),
846            max,
847        });
848    }
849
850    if segments.len() == 1 {
851        component.set_field(root, value)?;
852        return Ok(root.to_owned());
853    }
854
855    // A nested update reads the field, changes the path inside it, and writes the field back: the
856    // component's fields are typed, so the change goes through the same setter a root update uses.
857    let mut current = Map::new();
858    component.dehydrate_fields(&mut current);
859    let mut document = current.remove(root).unwrap_or(Value::Null);
860
861    set_in_place(&mut document, &segments[1..], value)?;
862    component.set_field(root, document)?;
863
864    Ok(root.to_owned())
865}
866
867/// Sets `path` inside a JSON document the browser sent, treating `__rm__` as a removal.
868fn set_in_place(document: &mut Value, path: &[&str], value: Value) -> Result<(), LivewireError> {
869    let Some((first, rest)) = path.split_first() else {
870        *document = value;
871        return Ok(());
872    };
873
874    if rest.is_empty() {
875        return assign(document, first, value);
876    }
877
878    match document {
879        Value::Object(map) => {
880            let entry = map
881                .entry((*first).to_owned())
882                .or_insert_with(|| Value::Object(Map::new()));
883            set_in_place(entry, rest, value)
884        }
885        Value::Array(values) => {
886            let index = array_index(first)
887                .ok_or_else(|| LivewireError::MalformedPayload(format!("[{first}] is not an array index")))?;
888            let entry = values
889                .get_mut(index)
890                .ok_or_else(|| LivewireError::MalformedPayload(format!("the array has no index {index}")))?;
891            set_in_place(entry, rest, value)
892        }
893        _ => {
894            *document = Value::Object(Map::new());
895            set_in_place(document, path, value)
896        }
897    }
898}
899
900/// Assigns or removes one level of a JSON document.
901fn assign(document: &mut Value, key: &str, value: Value) -> Result<(), LivewireError> {
902    let removal = value.as_str() == Some("__rm__");
903
904    match document {
905        Value::Object(map) => {
906            if removal {
907                map.remove(key);
908            } else {
909                map.insert(key.to_owned(), value);
910            }
911            Ok(())
912        }
913        Value::Array(values) => {
914            let index = array_index(key)
915                .ok_or_else(|| LivewireError::MalformedPayload(format!("[{key}] is not an array index")))?;
916            if removal {
917                if index < values.len() {
918                    values.remove(index);
919                }
920            } else if index < values.len() {
921                values[index] = value;
922            } else {
923                values.push(value);
924            }
925            Ok(())
926        }
927        _ => {
928            *document = Value::Object(Map::new());
929            assign(document, key, value)
930        }
931    }
932}
933
934fn array_index(key: &str) -> Option<usize> {
935    key.parse::<usize>().ok()
936}
937
938/// Reads the download an action asked for, which the response sends instead of markup.
939#[must_use]
940pub fn download_of(request: &LivewireRequest, id: &str) -> Option<Download> {
941    request.read(id, |state| state.download.clone()).flatten()
942}
943
944/// Updates a component from its verified snapshot: properties first, then the calls, then a render
945/// unless an action or a redirect said to skip it.
946///
947/// The caller verifies the checksum, because the batch checks the client's failure allowance once
948/// however many components it updates.
949///
950/// # Errors
951///
952/// Fails on a release-token mismatch, a property the component does not publish or has locked, an
953/// unknown action, a denied action, or a failed render.
954pub async fn update(
955    registry: &Arc<ComponentRegistry>,
956    snapshot: &Snapshot,
957    updates: Map<String, Value>,
958    calls: Vec<Call>,
959    http: Option<Arc<Request>>,
960) -> Result<Updated, LivewireError> {
961    let request = state();
962    if let Some(http) = &http {
963        request.set_http_request(Arc::clone(http));
964    }
965
966    let name = snapshot.name()?.to_owned();
967    let id = snapshot.id()?.to_owned();
968
969    let fields = registry
970        .wire_fields(&name)
971        .ok_or_else(|| LivewireError::ComponentNotFound { name: name.clone() })?;
972
973    let mut component = registry
974        .instantiate(&name)
975        .ok_or_else(|| LivewireError::ComponentNotFound { name: name.clone() })?;
976
977    let expected = release_token(registry, &*component);
978    match snapshot.memo_value("release").and_then(Value::as_str) {
979        Some(release) if release == expected => {}
980        _ => return Err(LivewireError::ReleaseTokenMismatch),
981    }
982
983    let parent = snapshot
984        .memo_value("parent")
985        .and_then(|parent| parent.get(0))
986        .and_then(Value::as_str)
987        .map(str::to_owned);
988
989    // The parent may already have handed this child the props it passed in this request; the
990    // component's own state is replaced below, so its params are carried across by hand.
991    let provided_props = request.read(&id, |state| state.provided_props.clone()).flatten();
992
993    request.register(
994        &id,
995        ComponentState {
996            name: name.clone(),
997            parent,
998            provided_props,
999            ..ComponentState::default()
1000        },
1001    );
1002
1003    // A snapshot rendered on one origin may not be driven from another, even with a valid
1004    // checksum: the page it belongs to is where its route context is meaningful.
1005    if let (Some(snapshot_origin), Some(http)) = (snapshot.memo_value("origin").and_then(Value::as_str), http.as_ref())
1006        && snapshot_origin != origin_of(http)
1007    {
1008        return Err(LivewireError::InvalidRouteContext(format!(
1009            "the component was mounted on [{snapshot_origin}]"
1010        )));
1011    }
1012
1013    let mut context = ComponentContext::updating(id.clone(), name.clone(), http);
1014
1015    // A slot is the parent's content: only mount sees it, so the child keeps it in its memo from
1016    // one snapshot to the next. The update context carries it, and the snapshot builder signs it.
1017    if let Some(slots) = snapshot.memo_value("slots") {
1018        context.memo.insert("slots".to_owned(), slots.clone());
1019    }
1020
1021    // The children this component rendered last time are the ones its view will meet again: each
1022    // becomes a stub in the new markup, keeping its own ID rather than mounting afresh.
1023    for (key, child) in snapshot.children() {
1024        let Some(parts) = child.as_array() else { continue };
1025        let (Some(tag), Some(child_id)) = (
1026            parts.first().and_then(Value::as_str),
1027            parts.get(1).and_then(Value::as_str),
1028        ) else {
1029            continue;
1030        };
1031
1032        request.add_child(
1033            &id,
1034            Child {
1035                key,
1036                tag: tag.to_owned(),
1037                id: child_id.to_owned(),
1038            },
1039        );
1040    }
1041
1042    component.hydrate_fields(&snapshot.data)?;
1043    {
1044        let _guard = request.push_mounting(&id);
1045        component.boot()?;
1046        component.initialize(&mut context)?;
1047        component.hydrate(&mut context)?;
1048    }
1049
1050    // A model reference fetches its row before the hooks, the actions, and the render read it.
1051    component.hydrate_models(&mut context).await?;
1052
1053    // A reactive prop takes the value its parent passed in this request, so a changed parent
1054    // resets the child before it renders.
1055    if let Some(provided) = request.read(&id, |state| state.provided_props.clone()).flatten() {
1056        for field in fields.iter().filter(|field| field.reactive) {
1057            if let Some(value) = provided.get(field.name) {
1058                component.set_field(field.name, value.clone())?;
1059            }
1060        }
1061    }
1062
1063    registry.run_hooks(&HookEvent::BeforeUpdate { name: &name, id: &id });
1064
1065    let max_depth = registry.config().payload.max_nesting_depth;
1066    let mut touched: Vec<String> = Vec::new();
1067
1068    for (path, value) in &updates {
1069        let root = path.split('.').next().unwrap_or(path).to_owned();
1070        component.updating(&root, value, &mut context)?;
1071        apply_update(&mut *component, fields, max_depth, path, value.clone())?;
1072        if !touched.contains(&root) {
1073            touched.push(root);
1074        }
1075    }
1076
1077    for property in &touched {
1078        component.updated(property, &mut context)?;
1079    }
1080
1081    // An action that originates inside an island asks for that island's fragment back, not the
1082    // whole component's markup.
1083    let islands: Vec<(String, String)> = calls
1084        .iter()
1085        .filter_map(|call| {
1086            let island = call.metadata.get("island")?.as_object()?;
1087            let name = island.get("name")?.as_str()?.to_owned();
1088            let mode = island.get("mode").and_then(Value::as_str).unwrap_or("morph").to_owned();
1089
1090            Some((name, mode))
1091        })
1092        .collect();
1093
1094    let call_count = calls.len();
1095    let mut returns: Vec<Value> = Vec::with_capacity(call_count);
1096    let mut returns_meta = Map::new();
1097    let mut all_calls_are_json = call_count > 0;
1098
1099    let mut vetoed = false;
1100
1101    for (index, call) in calls.into_iter().enumerate() {
1102        let call = resolve_event_call(&*component, call)?;
1103
1104        // A rejected field stops the rest of the batch for this component, but the response still
1105        // carries every call's slot and renders the component, so the browser can show the error.
1106        if vetoed {
1107            returns.push(Value::Null);
1108            continue;
1109        }
1110
1111        // The upload calls are the runtime's own, not the component's: they answer with effects and
1112        // never reach an action of the same name.
1113        if crate::uploads::is_upload_call(&call.method) {
1114            let outcome = match call.method.as_str() {
1115                "_startUpload" => crate::uploads::start_upload(&mut context, registry.config(), &call)?,
1116                "_finishUpload" => crate::uploads::finish_upload(&mut *component, &mut context, &call)?,
1117                "_uploadErrored" => crate::uploads::upload_errored(&mut context, &call)?,
1118                _ => crate::uploads::remove_upload(&mut context, registry.config(), &call).await?,
1119            };
1120
1121            // An upload call never skips the render: the response carries the new field.
1122            all_calls_are_json = false;
1123            returns.push(outcome.unwrap_or(Value::Null));
1124            continue;
1125        }
1126        let method = call.method.clone();
1127        let json = component.action_result_kind(&method) == ActionResultKind::Json;
1128        all_calls_are_json &= json;
1129
1130        registry.run_hooks(&HookEvent::BeforeCall {
1131            name: &name,
1132            id: &id,
1133            method: &method,
1134        });
1135
1136        if !component.authorize(&method, &context).await? {
1137            if !json {
1138                return Err(LivewireError::Unauthorized { method: call.method });
1139            }
1140
1141            // A denied JSON action answers the caller with a status instead of failing the batch.
1142            returns_meta.insert(index.to_string(), serde_json::json!({"status": 403}));
1143            returns.push(Value::Null);
1144            continue;
1145        }
1146
1147        let outcome = component.call(call, &mut context).await;
1148        registry.run_hooks(&HookEvent::Call {
1149            name: &name,
1150            id: &id,
1151            method: &method,
1152        });
1153
1154        match outcome {
1155            Ok(value) => returns.push(value.unwrap_or(Value::Null)),
1156            Err(LivewireError::ValidationFailed { .. }) => {
1157                // The messages are already in the snapshot's memo; nothing else to answer.
1158                returns.push(Value::Null);
1159                vetoed = true;
1160            }
1161            Err(error) => {
1162                if !json {
1163                    component.exception(&error, &mut context);
1164                    return Err(error);
1165                }
1166
1167                let status = u16::from(error.status());
1168                returns_meta.insert(index.to_string(), serde_json::json!({"status": status}));
1169                returns.push(Value::Null);
1170            }
1171        }
1172    }
1173
1174    // A call may have written a new key; the reference fetches it before this same response
1175    // renders, so an element bound to the model shows its row.
1176    component.hydrate_models(&mut context).await?;
1177
1178    registry.run_hooks(&HookEvent::Update { name: &name, id: &id });
1179
1180    // The browser aligns these with the calls it sent, so one entry per call, always.
1181    context.add_effect("returns", Value::Array(returns));
1182    if !returns_meta.is_empty() {
1183        context.add_effect("returnsMeta", Value::Object(returns_meta));
1184    }
1185
1186    let config = registry.config();
1187    let redirecting = context.effects.contains_key("redirect") || context.effects.contains_key("redirectUsingNavigate");
1188    let skipping = all_calls_are_json
1189        || context
1190            .effects
1191            .get("skipRender")
1192            .is_some_and(|value| value.as_bool().unwrap_or(false));
1193
1194    if skipping || (redirecting && !config.render_on_redirect) {
1195        // The state changed even when the markup does not, so the browser still receives a signed
1196        // snapshot to keep. Only the render is skipped; a missing snapshot would leave the client
1197        // parsing `undefined`.
1198        let next = snapshot_for(registry, &*component, &id, &name, &request, &context, &Map::new())?;
1199        let effects = std::mem::take(&mut context.effects);
1200        component.destroy();
1201
1202        return Ok(Updated {
1203            snapshot: Some(next),
1204            effects,
1205            skip: false,
1206            frames: context.streamed,
1207        });
1208    }
1209
1210    // The slots the parent passed at mount stay available to every later render of the child.
1211    let slots = snapshot
1212        .memo_value("slots")
1213        .and_then(Value::as_object)
1214        .cloned()
1215        .unwrap_or_default();
1216
1217    let html = {
1218        let _rendering = request.push_rendering(&id);
1219        render_component(registry, &*component, &id, &name, &request, &slots)?
1220    };
1221
1222    // The browser morphs an island's fragment in place, so the whole component's markup would only
1223    // duplicate that work and disturb the islands around it.
1224    let island_fragments: Vec<Value> = islands
1225        .iter()
1226        .filter_map(|(name, mode)| fragment_of(&html, "island", name).map(|fragment| fragment_in_mode(fragment, mode)))
1227        .map(Value::from)
1228        .collect();
1229
1230    component.dehydrate(&mut context)?;
1231    class_effects(&*component, &mut context);
1232
1233    // The first update renders what the mount left out; from then on the component is loaded.
1234    if snapshot.memo_value("lazyLoaded").is_some() {
1235        context.memo.insert("lazyLoaded".to_owned(), Value::Bool(true));
1236    }
1237
1238    emit_slot_fragments(&request, &id, &mut context);
1239
1240    let next = snapshot_for(registry, &*component, &id, &name, &request, &context, &Map::new())?;
1241
1242    // The client morphs this markup over the element it already has, and keeps the component only
1243    // while the root still names it. The snapshot and effects it reads back are the ones it just
1244    // received, so the attributes must carry them too.
1245    if island_fragments.is_empty() {
1246        let mut attributes = vec![
1247            ("wire:id".to_owned(), id.clone()),
1248            ("wire:name".to_owned(), name.clone()),
1249            ("wire:snapshot".to_owned(), next.encode()),
1250            ("wire:effects".to_owned(), encode_effects(&context.effects)?),
1251        ];
1252        attributes.retain(|(attribute, _)| !first_tag_declares(&html, attribute));
1253
1254        let html = html::insert_attributes(&html, &attributes)?;
1255        context.add_effect("html", Value::from(html));
1256    } else {
1257        context.add_effect("islandFragments", Value::Array(island_fragments));
1258    }
1259
1260    let effects = std::mem::take(&mut context.effects);
1261    component.destroy();
1262
1263    Ok(Updated {
1264        snapshot: Some(next),
1265        effects,
1266        skip: false,
1267        frames: std::mem::take(&mut context.streamed),
1268    })
1269}
1270
1271/// The fragment `html` holds for `kind` named `name`, markers included, as the browser's
1272/// `renderIsland`/`renderSlot` read it.
1273///
1274/// A fragment runs from its `<!--[if FRAGMENT:…]>` opener to the `<!--[if ENDFRAGMENT:…]>` closer
1275/// with the same metadata, so a nested island ends at its own closer rather than its parent's.
1276pub(crate) fn fragment_of(html: &str, kind: &str, name: &str) -> Option<String> {
1277    let mut rest = html;
1278
1279    while let Some(start) = rest.find("<!--[if FRAGMENT:") {
1280        let after = &rest[start..];
1281        let metadata_end = after.find("]>")?;
1282        let metadata = &after["<!--[if FRAGMENT:".len()..metadata_end];
1283
1284        let matches = metadata
1285            .split('|')
1286            .any(|field| field.strip_prefix("type=") == Some(kind))
1287            && metadata
1288                .split('|')
1289                .any(|field| field.strip_prefix("name=") == Some(name));
1290
1291        if matches {
1292            let closer = format!("<!--[if ENDFRAGMENT:{metadata}]>");
1293            let close_at = rest[start..].find(&closer)? + start;
1294            let end = close_at + closer.len() + "<![endif]-->".len();
1295
1296            return Some(rest[start..end].to_owned());
1297        }
1298
1299        rest = &rest[start + metadata_end + 2..];
1300    }
1301
1302    None
1303}
1304
1305/// The same fragment with its markers naming `mode`, which is how `wire:island.append` and
1306/// `.prepend` reach the browser: the client reads the mode from the fragment it receives.
1307fn fragment_in_mode(fragment: String, mode: &str) -> String {
1308    if mode == "morph" {
1309        return fragment;
1310    }
1311
1312    let mut out = String::with_capacity(fragment.len());
1313    let mut rest = fragment.as_str();
1314
1315    for marker in ["<!--[if FRAGMENT:", "<!--[if ENDFRAGMENT:"] {
1316        while let Some(at) = rest.find(marker) {
1317            let (head, tail) = rest.split_at(at + marker.len());
1318            out.push_str(head);
1319
1320            let close = tail.find(']').unwrap_or(tail.len());
1321            let metadata = &tail[..close];
1322            out.push_str(
1323                &metadata
1324                    .split('|')
1325                    .map(|field| match field.strip_prefix("mode=") {
1326                        Some(_) => format!("mode={mode}"),
1327                        None => field.to_owned(),
1328                    })
1329                    .collect::<Vec<_>>()
1330                    .join("|"),
1331            );
1332            rest = &tail[close..];
1333        }
1334    }
1335
1336    out.push_str(rest);
1337    out
1338}
1339
1340#[cfg(test)]
1341mod tests {
1342    use super::*;
1343    use crate::component::LivewireState as _;
1344    use crate::{LivewireComponent, component};
1345
1346    #[derive(Default, LivewireComponent)]
1347    #[livewire(inline = "<div></div>")]
1348    struct Nested {
1349        list: Vec<i32>,
1350        config: Map<String, Value>,
1351        title: String,
1352        #[livewire(locked)]
1353        id: String,
1354    }
1355
1356    #[component]
1357    impl Nested {}
1358
1359    fn fields() -> &'static [WireField] {
1360        Nested::wire_fields()
1361    }
1362
1363    #[test]
1364    fn a_root_update_reaches_its_field() {
1365        let mut component = Nested::default();
1366
1367        apply_update(&mut component, fields(), None, "title", Value::from("hi")).expect("updates");
1368
1369        assert_eq!(component.title, "hi");
1370    }
1371
1372    #[test]
1373    fn a_dotted_update_reaches_inside_an_array() {
1374        let mut component = Nested {
1375            list: vec![1, 2],
1376            ..Nested::default()
1377        };
1378
1379        apply_update(&mut component, fields(), None, "list.0", Value::from(9)).expect("updates");
1380
1381        assert_eq!(component.list, [9, 2]);
1382    }
1383
1384    #[test]
1385    fn a_removal_deletes_the_entry() {
1386        let mut component = Nested {
1387            list: vec![1, 2, 3],
1388            ..Nested::default()
1389        };
1390
1391        apply_update(&mut component, fields(), None, "list.1", Value::from("__rm__")).expect("updates");
1392
1393        assert_eq!(component.list, [1, 3]);
1394    }
1395
1396    #[test]
1397    fn a_dotted_update_creates_missing_objects() {
1398        let mut component = Nested::default();
1399
1400        apply_update(
1401            &mut component,
1402            fields(),
1403            None,
1404            "config.theme.color",
1405            Value::from("dark"),
1406        )
1407        .expect("updates");
1408
1409        assert_eq!(component.config["theme"]["color"], serde_json::json!("dark"));
1410    }
1411
1412    #[test]
1413    fn an_unknown_root_is_reported() {
1414        let mut component = Nested::default();
1415
1416        let error = apply_update(&mut component, fields(), None, "nope.deeper", Value::from(1)).expect_err("unknown");
1417
1418        assert!(matches!(error, LivewireError::UnknownProperty { .. }));
1419    }
1420
1421    #[test]
1422    fn a_locked_root_is_rejected_even_through_a_path() {
1423        let mut component = Nested::default();
1424
1425        let error = apply_update(&mut component, fields(), None, "id.inner", Value::from(1)).expect_err("locked");
1426
1427        assert!(matches!(error, LivewireError::LockedProperty { .. }));
1428    }
1429
1430    #[test]
1431    fn a_path_deeper_than_the_limit_is_rejected() {
1432        let mut component = Nested::default();
1433
1434        let error =
1435            apply_update(&mut component, fields(), Some(2), "config.a.b.c", Value::from(1)).expect_err("too deep");
1436
1437        assert!(matches!(error, LivewireError::NestingDepthExceeded { max: 2, .. }));
1438    }
1439
1440    #[test]
1441    fn a_slot_fragment_names_the_component_that_holds_it() {
1442        let fragment = slot_fragment("abc", "header", "<h1>hi</h1>");
1443
1444        assert_eq!(
1445            fragment,
1446            "<!--[if FRAGMENT:type=slot|name=header|token=header|id=abc]><![endif]--><h1>hi</h1>\
1447             <!--[if ENDFRAGMENT:type=slot|name=header|token=header|id=abc]><![endif]-->"
1448        );
1449        assert!(
1450            fragment_of(&fragment, "slot", "header").is_some(),
1451            "the parser reads it back"
1452        );
1453    }
1454
1455    #[test]
1456    fn slots_leave_the_mount_params() {
1457        let params = Params::Named(Map::from_iter([
1458            ("step".to_owned(), Value::from(1)),
1459            ("slot".to_owned(), Value::from("<em>x</em>")),
1460            ("slots".to_owned(), Value::from("named")),
1461        ]));
1462
1463        let (params, slots) = take_slots(params);
1464
1465        let Params::Named(params) = params else {
1466            panic!("named params")
1467        };
1468        assert_eq!(params.get("step"), Some(&Value::from(1)), "a real param stays");
1469        assert!(params.get("slot").is_none(), "the slot is not a mount param");
1470        assert!(params.get("slots").is_none());
1471        assert_eq!(slots.get("slot"), Some(&Value::from("<em>x</em>")));
1472        assert_eq!(slots.get("slots"), Some(&Value::from("named")));
1473    }
1474
1475    #[test]
1476    fn positional_params_carry_no_slots() {
1477        let (params, slots) = take_slots(Params::List(vec![Value::from(1)]));
1478
1479        assert!(matches!(params, Params::List(_)));
1480        assert!(slots.is_empty());
1481    }
1482
1483    #[test]
1484    fn a_fragment_is_cut_out_by_its_own_markers() {
1485        let open = |name: &str, token: &str| {
1486            format!("<!--[if FRAGMENT:type=island|name={name}|token={token}|mode=morph]><![endif]-->")
1487        };
1488        let close = |name: &str, token: &str| {
1489            format!("<!--[if ENDFRAGMENT:type=island|name={name}|token={token}|mode=morph]><![endif]-->")
1490        };
1491        let html = [
1492            "a",
1493            &open("outer", "t1"),
1494            &open("inner", "t2"),
1495            "i",
1496            &close("inner", "t2"),
1497            "x",
1498            &close("outer", "t1"),
1499            "b",
1500        ]
1501        .concat();
1502
1503        let inner = fragment_of(&html, "island", "inner").expect("the inner island");
1504        assert!(inner.starts_with("<!--[if FRAGMENT:type=island|name=inner"));
1505        assert!(
1506            !inner.contains("name=outer"),
1507            "the inner island ends at its own closer: {inner}"
1508        );
1509
1510        let outer = fragment_of(&html, "island", "outer").expect("the outer island");
1511        assert!(
1512            outer.contains("name=inner"),
1513            "the outer island spans the inner one: {outer}"
1514        );
1515        assert!(outer.ends_with("mode=morph]><![endif]-->"));
1516
1517        assert!(fragment_of(&html, "island", "missing").is_none());
1518        assert!(fragment_of(&html, "slot", "outer").is_none(), "the kind must match too");
1519    }
1520
1521    #[test]
1522    fn a_fragment_reaches_append_and_prepend_with_their_mode() {
1523        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]-->";
1524
1525        let appended = fragment_in_mode(fragment_of(html, "island", "log").expect("the island"), "append");
1526
1527        assert_eq!(
1528            appended.matches("mode=append").count(),
1529            2,
1530            "both markers name the mode: {appended}"
1531        );
1532        assert!(
1533            !appended.contains("mode=morph"),
1534            "no marker keeps the old mode: {appended}"
1535        );
1536        assert!(appended.contains(">row<"), "the content is untouched: {appended}");
1537
1538        assert_eq!(
1539            fragment_in_mode(html.to_owned(), "morph"),
1540            html,
1541            "morph leaves the fragment alone"
1542        );
1543    }
1544
1545    #[test]
1546    fn the_depth_limit_counts_the_root() {
1547        let mut component = Nested::default();
1548
1549        apply_update(&mut component, fields(), Some(2), "config.a", Value::from(1)).expect("within the limit");
1550    }
1551
1552    #[test]
1553    fn a_mount_separates_props_from_forwarded_attributes() {
1554        let attributes = Map::from_iter([("class".to_owned(), Value::from("p-4"))]);
1555        let params = Params::Named(Map::from_iter([
1556            ("title".to_owned(), Value::from("hello")),
1557            ("name".to_owned(), Value::from("sergio")),
1558            ("lazy".to_owned(), Value::from(true)),
1559            ("@click".to_owned(), Value::from("open()")),
1560        ]));
1561
1562        let (props, forwarded) = separate(params, fields(), attributes);
1563
1564        let Params::Named(props) = props else {
1565            panic!("named props")
1566        };
1567        assert_eq!(props["title"], serde_json::json!("hello"));
1568        assert_eq!(props["lazy"], serde_json::json!(true));
1569        assert!(!props.contains_key("name"));
1570        assert_eq!(forwarded["class"], serde_json::json!("p-4"));
1571        assert_eq!(forwarded["name"], serde_json::json!("sergio"));
1572        // A reserved param stays with the component instead of becoming an attribute, as upstream's
1573        // `isReservedParam` does.
1574        assert!(!forwarded.contains_key("@click"));
1575    }
1576
1577    #[test]
1578    fn a_positional_mount_keeps_its_parameters() {
1579        let (props, forwarded) = separate(Params::List(vec![Value::from(1)]), fields(), Map::new());
1580
1581        assert!(matches!(props, Params::List(_)));
1582        assert!(forwarded.is_empty());
1583    }
1584
1585    #[test]
1586    fn the_first_tag_name_is_read_from_the_markup() {
1587        assert_eq!(first_tag_name("<div class=\"a\">").as_deref(), Some("div"));
1588        assert_eq!(first_tag_name("  <my-widget>").as_deref(), Some("my-widget"));
1589        assert_eq!(first_tag_name("no markup"), None);
1590    }
1591}