Skip to main content

larust_live/
mount.rs

1use crate::lock::with_session_lock;
2use crate::registry;
3use crate::state::{evict_oldest_if_over_cap, load_components, save_components, StoredComponent};
4use larust_core::AppError;
5use larust_http::random_hex;
6use larust_http::session::Session;
7use larust_view::escape;
8use std::collections::HashMap;
9
10/// Mounts a fresh instance of the component registered as `name`, storing
11/// its initial state server-side (keyed by `session`) and returning the
12/// rendered `<div data-wire-id="...">` wrapper - what a `@wire(...)`
13/// codegen call site splices directly into the surrounding page's HTML.
14///
15/// Every full-page GET through a `@wire(...)` mount point creates a
16/// brand-new component instance (fresh id, freshly `mount()`-ed state) -
17/// there is no cross-navigation persistence, matching Livewire's own
18/// per-page-load semantics. Stale/orphaned session entries are therefore
19/// expected on every page view, not a bug - see
20/// `crate::state::evict_oldest_if_over_cap`'s own doc comment for how
21/// that's bounded.
22pub async fn mount(
23    session: &Session,
24    name: &str,
25    props: HashMap<String, serde_json::Value>,
26) -> Result<String, AppError> {
27    with_session_lock(session, || async {
28        let entry = registry::lookup(name).ok_or_else(|| {
29            AppError::Internal(Box::new(std::io::Error::other(format!(
30                "@wire('{name}', ...) used but no component is registered under that name - \
31                 call `larust_support::wire::components().register::<YourType>().publish()` \
32                 before serving requests"
33            ))))
34        })?;
35
36        let mut components = load_components(session).await?;
37        let id = random_hex(16);
38        let state = (entry.mount)(session, &props).await?;
39
40        // Captures only what *this* render call pushes to `'head'` (via
41        // `larust_view::push_registry`), leaving any earlier, unrelated
42        // entries already sitting in the registry - from other content on
43        // this same page - untouched. See `larust_view::push_registry`'s
44        // own doc comment for why this is here at all, and
45        // `docs/GOTCHAS.md`'s `@push`/`@stack` entry for the full picture.
46        let head_mark = larust_view::push_registry::mark("head");
47        let html = (entry.render)(&state).await?;
48        let head_content = larust_view::push_registry::drain_since("head", head_mark);
49        // Always wrapped in the marker pair, even when empty, so a
50        // component that pushes nothing at mount time but starts pushing
51        // after a later `wire:model`/`wire:click`/`wire:submit`-triggered
52        // re-render (see `crate::routes::update`) still has an addressable
53        // region in the DOM for that later patch to land in.
54        larust_view::push_registry::record(
55            "head",
56            format!("<!--wire-head:{id}-->{head_content}<!--/wire-head:{id}-->"),
57        );
58
59        components.push((
60            id.clone(),
61            StoredComponent {
62                name: name.to_string(),
63                state,
64            },
65        ));
66        evict_oldest_if_over_cap(&mut components);
67        save_components(session, &components).await?;
68
69        Ok(wrap(&id, &html))
70    })
71    .await
72}
73
74/// Wraps a component's rendered output in the `data-wire-id`-carrying
75/// `<div>` the client runtime addresses `/__larust_wire/{id}` through - the
76/// same wrapper shape both `mount()` and `crate::routes::update` produce,
77/// so the client's DOM patcher has one uniform "patch this node against
78/// that node" code path for both the first paint and every later fragment.
79/// No `data-wire-name` in the markup - the server resolves id → name from
80/// session storage; the client only ever needs the opaque id.
81pub(crate) fn wrap(id: &str, inner_html: &str) -> String {
82    format!(r#"<div data-wire-id="{}">{inner_html}</div>"#, escape(id))
83}