Skip to main content

axum_wire/
lib.rs

1//! # axum-wire
2//!
3//! Laravel Livewire-like server-driven reactive UI components for Axum.
4//!
5//! Components are Rust structs whose state lives on the server. User interactions
6//! (clicks, input changes, etc.) trigger AJAX requests that update state server-side,
7//! re-render HTML, and morph the DOM — no full page reload needed.
8//!
9//! ## How it works
10//!
11//! 1. A component struct derives `Component` (+ `Serialize`, `Deserialize`, optionally `Default`)
12//! 2. The `#[wire_actions]` macro on the impl block registers `render()`, optional `mount()`, and actions
13//! 3. On first load, the component is mounted, rendered to HTML, and its state
14//!    serialized as a JSON "snapshot" embedded in a `data-wire-snapshot` attribute
15//! 4. A small JS runtime intercepts `wire:click`, `wire:submit`, `wire:model` etc.,
16//!    sends the snapshot + action name to the server via fetch()
17//! 5. The server deserializes the snapshot, calls the action, re-renders, and
18//!    returns the new HTML + snapshot
19//! 6. The JS runtime uses morphdom to diff and patch the DOM in-place
20
21pub use axum_wire_macros::{html, on, wire_actions, Component};
22pub use futures;
23pub use inventory;
24pub use serde_json;
25pub use tokio;
26
27pub use subsecond;
28
29// Re-export axum extractors and tower for convenience
30pub use axum::extract;
31pub use axum_extra;
32pub use tower;
33
34pub trait HtmlFragment {
35    fn into_html_fragment(self) -> String;
36}
37
38impl<T> HtmlFragment for Vec<T>
39where
40    T: HtmlFragment,
41{
42    fn into_html_fragment(self) -> String {
43        self.into_iter()
44            .map(|item| item.into_html_fragment())
45            .collect()
46    }
47}
48
49impl<T> HtmlFragment for &T
50where
51    T: HtmlFragment + Clone,
52{
53    fn into_html_fragment(self) -> String {
54        self.clone().into_html_fragment()
55    }
56}
57
58impl HtmlFragment for String {
59    fn into_html_fragment(self) -> String {
60        self
61    }
62}
63
64impl HtmlFragment for &str {
65    fn into_html_fragment(self) -> String {
66        self.to_string()
67    }
68}
69
70impl HtmlFragment for char {
71    fn into_html_fragment(self) -> String {
72        self.to_string()
73    }
74}
75
76impl HtmlFragment for bool {
77    fn into_html_fragment(self) -> String {
78        self.to_string()
79    }
80}
81
82impl HtmlFragment for () {
83    fn into_html_fragment(self) -> String {
84        String::new()
85    }
86}
87
88impl<T> HtmlFragment for Option<T>
89where
90    T: HtmlFragment,
91{
92    fn into_html_fragment(self) -> String {
93        self.map(HtmlFragment::into_html_fragment)
94            .unwrap_or_default()
95    }
96}
97
98macro_rules! impl_html_fragment_number {
99    ($($t:ty),* $(,)?) => {
100        $(
101            impl HtmlFragment for $t {
102                fn into_html_fragment(self) -> String {
103                    self.to_string()
104                }
105            }
106        )*
107    };
108}
109
110impl_html_fragment_number!(
111    i8, i16, i32, i64, i128, isize, u8, u16, u32, u64, u128, usize, f32, f64
112);
113
114pub fn render_html_fragment<T>(value: T) -> String
115where
116    T: HtmlFragment,
117{
118    value.into_html_fragment()
119}
120
121// ---------------------------------------------------------------------------
122// Autoref-specialization helper so `html! { {expr} }` blocks accept both
123// `HtmlFragment` values *and* bare iterators whose items are `HtmlFragment`.
124//
125// Uses the autoref specialization pattern:
126// - The macro emits:  `{ let __v = expr; (&__v).__wire_render_tag().__wire_render(__v) }`
127// - For `HtmlFragment` types: `(&T).__wire_render_tag()` returns `WireTagFragment`
128// - For `Iterator` types:     `(&T).__wire_render_tag()` returns `WireTagIter`
129//   (via the trait `WireRenderTagIter` which is behind one autoref level)
130// - Each tag type has a `__wire_render(self, val)` method that does the right thing.
131// ---------------------------------------------------------------------------
132
133pub struct WireTagFragment;
134pub struct WireTagIter;
135
136/// Inherent impl — matches HtmlFragment, chosen first by method resolution.
137impl<T: HtmlFragment> WireRender<T> {
138    #[inline]
139    pub fn __wire_render_tag(&self) -> WireTagFragment {
140        WireTagFragment
141    }
142}
143
144/// Trait fallback — matches Iterator, chosen when inherent doesn't match.
145pub trait WireRenderTagIter {
146    fn __wire_render_tag(&self) -> WireTagIter;
147}
148
149impl<I: Iterator> WireRenderTagIter for WireRender<I> {
150    #[inline]
151    fn __wire_render_tag(&self) -> WireTagIter {
152        WireTagIter
153    }
154}
155
156impl WireTagFragment {
157    #[inline]
158    pub fn __wire_render<T: HtmlFragment>(self, value: T) -> String {
159        value.into_html_fragment()
160    }
161}
162
163impl WireTagIter {
164    #[inline]
165    pub fn __wire_render<I>(self, iter: I) -> String
166    where
167        I: Iterator,
168        I::Item: HtmlFragment,
169    {
170        iter.map(|item| item.into_html_fragment()).collect()
171    }
172}
173
174pub struct WireRender<T>(pub T);
175
176pub trait CollectHtml: Iterator {
177    fn collect_html(self) -> String
178    where
179        Self: Sized,
180        Self::Item: HtmlFragment,
181    {
182        self.map(|item| item.into_html_fragment()).collect()
183    }
184}
185
186impl<I> CollectHtml for I where I: Iterator {}
187
188pub mod html_elements;
189
190/// Connect to the Dioxus devtools for hot-patching.
191///
192/// In debug builds, this connects to the `dx serve` devserver so subsecond
193/// can receive and apply patches. In release builds this is a no-op.
194pub fn connect_devtools() {
195    #[cfg(debug_assertions)]
196    {
197        dioxus_devtools::connect_subsecond();
198    }
199}
200
201use std::pin::Pin;
202use std::sync::Arc;
203
204use axum::{
205    body::Body,
206    extract::{FromRequestParts, Json, Path, Query, Request},
207    http::{header::SET_COOKIE, request::Parts, StatusCode},
208    middleware,
209    response::{Html, IntoResponse, Response},
210    routing::{get, post},
211    Router,
212};
213use futures::future::BoxFuture;
214use serde::{Deserialize, Serialize};
215use tower::ServiceExt;
216
217// ---------------------------------------------------------------------------
218// Error types
219// ---------------------------------------------------------------------------
220
221#[derive(Debug, thiserror::Error)]
222pub enum WireError {
223    #[error("Unknown component: {0}")]
224    UnknownComponent(String),
225    #[error("Unknown action: {0}")]
226    UnknownAction(String),
227    #[error("Deserialization error: {0}")]
228    Deserialization(String),
229    #[error("Serialization error: {0}")]
230    Serialization(String),
231    #[error("Cannot update locked property: {0}")]
232    LockedProperty(String),
233}
234
235// ---------------------------------------------------------------------------
236// Core trait
237// ---------------------------------------------------------------------------
238
239/// Metadata for a field annotated with `#[url]`.
240#[derive(Debug, Clone, Serialize)]
241pub struct UrlFieldMeta {
242    /// The Rust struct field name (e.g. `"search"`).
243    pub field_name: &'static str,
244    /// The query parameter name in the URL (e.g. `"q"` if `#[url(as = "q")]`).
245    pub query_name: &'static str,
246    /// Whether to push browser history entries (`history.pushState` vs `replaceState`).
247    pub history: bool,
248    /// Whether to always keep the parameter in the URL, even when at default value.
249    pub keep: bool,
250}
251
252#[derive(Debug, Clone, Serialize, Deserialize)]
253pub struct EventListenerMeta {
254    pub event: &'static str,
255    pub action: &'static str,
256}
257
258/// Auto-implemented by the derive macro to provide the component's wire name.
259pub trait ComponentMeta {
260    fn component_name() -> &'static str;
261    fn url_fields() -> &'static [UrlFieldMeta] {
262        &[]
263    }
264    /// Field names annotated with `#[locked]` — protected from client-side modification.
265    fn locked_fields() -> &'static [&'static str] {
266        &[]
267    }
268    /// Named layout for this component (from `#[layout("name")]`).
269    /// Returns `None` to use the default layout.
270    fn layout_name() -> Option<&'static str> {
271        None
272    }
273    /// Event listeners registered via `#[on("event")]` on action methods.
274    fn event_listeners() -> &'static [EventListenerMeta] {
275        &[]
276    }
277}
278
279// ---------------------------------------------------------------------------
280// Component registry (via `inventory`)
281// ---------------------------------------------------------------------------
282
283pub struct WireResponse {
284    pub html: String,
285    pub snapshot: serde_json::Value,
286    pub effects: ActionEffects,
287}
288
289pub type WireResult = Result<WireResponse, WireError>;
290
291// ---------------------------------------------------------------------------
292// Action effects — scoped per call_action invocation via RAII guard
293// ---------------------------------------------------------------------------
294
295#[derive(Clone, Serialize)]
296pub struct DispatchEvent {
297    pub name: String,
298    #[serde(skip_serializing_if = "Option::is_none")]
299    pub detail: Option<serde_json::Value>,
300    #[serde(skip_serializing_if = "Option::is_none")]
301    pub target: Option<String>,
302}
303
304/// Side-effects queued during an action (JS commands, redirect, skip render).
305#[derive(Default)]
306pub struct ActionEffects {
307    pub js: Vec<String>,
308    pub dispatches: Vec<DispatchEvent>,
309    pub skip_render: bool,
310    pub redirect: Option<String>,
311    pub redirect_navigate: bool,
312    pub response_extensions: Vec<Arc<dyn Fn(&mut axum::http::Extensions) + Send + Sync>>,
313    pub set_cookie_headers: Vec<axum::http::HeaderValue>,
314}
315
316std::thread_local! {
317    static ACTION_EFFECTS: std::cell::RefCell<ActionEffects> = std::cell::RefCell::new(ActionEffects::default());
318}
319
320/// RAII guard that scopes action effects to a single `call_action` invocation.
321/// Since actions are synchronous (`&mut self`), no interleaving is possible.
322pub struct ActionScope;
323
324impl ActionScope {
325    pub fn begin() -> Self {
326        ACTION_EFFECTS.with(|e| {
327            let mut e = e.borrow_mut();
328            e.js.clear();
329            e.dispatches.clear();
330            e.skip_render = false;
331            e.redirect = None;
332            e.redirect_navigate = false;
333            e.response_extensions.clear();
334            e.set_cookie_headers.clear();
335        });
336        ActionScope
337    }
338
339    pub fn finish(self) -> ActionEffects {
340        ACTION_EFFECTS.with(|e| {
341            let mut e = e.borrow_mut();
342            ActionEffects {
343                js: e.js.drain(..).collect(),
344                dispatches: e.dispatches.drain(..).collect(),
345                skip_render: e.skip_render,
346                redirect: e.redirect.take(),
347                redirect_navigate: e.redirect_navigate,
348                response_extensions: e.response_extensions.drain(..).collect(),
349                set_cookie_headers: e.set_cookie_headers.drain(..).collect(),
350            }
351        })
352    }
353}
354
355impl Drop for ActionScope {
356    fn drop(&mut self) {
357        ACTION_EFFECTS.with(|e| {
358            let mut e = e.borrow_mut();
359            e.js.clear();
360            e.dispatches.clear();
361            e.skip_render = false;
362            e.redirect = None;
363            e.redirect_navigate = false;
364            e.response_extensions.clear();
365            e.set_cookie_headers.clear();
366        });
367    }
368}
369
370/// Push a JS command. Called by generated `self.js()`.
371pub fn push_js(code: String) {
372    ACTION_EFFECTS.with(|e| e.borrow_mut().js.push(code));
373}
374
375/// Dispatch a browser event from the component root.
376pub fn dispatch_event(name: String, detail: Option<serde_json::Value>) {
377    dispatch_event_targeted(name, detail, None);
378}
379
380/// Dispatch a browser event with optional targeting.
381pub fn dispatch_event_targeted(
382    name: String,
383    detail: Option<serde_json::Value>,
384    target: Option<String>,
385) {
386    ACTION_EFFECTS.with(|e| {
387        e.borrow_mut().dispatches.push(DispatchEvent {
388            name,
389            detail,
390            target,
391        });
392    });
393}
394
395/// Mark current action to skip rendering. Called by generated `self.skip_render()`.
396pub fn set_skip_render() {
397    ACTION_EFFECTS.with(|e| e.borrow_mut().skip_render = true);
398}
399
400/// Set a redirect URL. Called by generated `self.redirect()`.
401pub fn set_redirect(url: String, navigate: bool) {
402    ACTION_EFFECTS.with(|e| {
403        let mut e = e.borrow_mut();
404        e.redirect = Some(url);
405        e.redirect_navigate = navigate;
406        e.skip_render = true; // redirect implies skip render
407    });
408}
409
410/// Queue a response extension to be inserted into the HTTP response.
411pub fn push_response_extension<T>(value: T)
412where
413    T: Clone + Send + Sync + 'static,
414{
415    ACTION_EFFECTS.with(|e| {
416        e.borrow_mut()
417            .response_extensions
418            .push(Arc::new(move |extensions| {
419                extensions.insert(value.clone());
420            }));
421    });
422}
423
424fn push_set_cookie_header(value: axum::http::HeaderValue) {
425    ACTION_EFFECTS.with(|e| e.borrow_mut().set_cookie_headers.push(value));
426}
427
428fn collect_set_cookie_headers(response: &Response) -> Vec<axum::http::HeaderValue> {
429    response
430        .headers()
431        .get_all(SET_COOKIE)
432        .iter()
433        .cloned()
434        .collect()
435}
436
437fn cookie_header_value(
438    cookie: &axum_extra::extract::cookie::Cookie<'static>,
439) -> Option<axum::http::HeaderValue> {
440    axum::http::HeaderValue::from_str(&cookie.encoded().to_string()).ok()
441}
442
443fn queue_set_cookie_headers_from_response(response: &Response) {
444    for value in collect_set_cookie_headers(response) {
445        push_set_cookie_header(value);
446    }
447}
448
449fn apply_states_to_request(
450    mut request: Request,
451    states: &Arc<Vec<Arc<dyn StateInjector>>>,
452) -> Request {
453    for state in states.iter() {
454        state.inject(request.extensions_mut());
455    }
456    request
457}
458
459// ---------------------------------------------------------------------------
460// WireContext — gives components access to the Axum request context
461// ---------------------------------------------------------------------------
462
463/// Request context available to wire components.
464///
465/// In `mount(ctx: WireContext)`, the context is passed directly.
466/// In `render()` and actions, use `self.ctx()` to access the task-local context.
467///
468/// Provides convenience shortcuts for common extractors (`path`, `query`,
469/// `state`, `extension`) and a general-purpose `extract::<T>()` for anything
470/// that implements `FromRequestParts<()>`.
471#[derive(Clone)]
472pub struct WireContext {
473    parts: Arc<std::sync::Mutex<Parts>>,
474}
475
476impl WireContext {
477    /// Create a `WireContext` from Axum request parts.
478    pub fn new(parts: Parts) -> Self {
479        Self {
480            parts: Arc::new(std::sync::Mutex::new(parts)),
481        }
482    }
483
484    /// Create an empty `WireContext` (used when no request context is available,
485    /// e.g. sub-component mounts from `html!`).
486    pub fn empty() -> Self {
487        let (parts, _) = axum::http::Request::new(()).into_parts();
488        Self::new(parts)
489    }
490
491    // -----------------------------------------------------------------------
492    // General-purpose extractor
493    // -----------------------------------------------------------------------
494
495    /// Extract any type that implements `FromRequestParts<()>`.
496    ///
497    /// ```ignore
498    /// let headers = ctx.extract::<HeaderMap>().await.unwrap();
499    /// ```
500    pub async fn extract<T>(&self) -> Result<T, T::Rejection>
501    where
502        T: FromRequestParts<()>,
503    {
504        let mut parts = self.parts.lock().unwrap().clone();
505        T::from_request_parts(&mut parts, &()).await
506    }
507
508    // -----------------------------------------------------------------------
509    // Convenience shortcuts — panicking
510    // -----------------------------------------------------------------------
511
512    /// Extract path parameters. Panics on failure.
513    ///
514    /// ```ignore
515    /// let Path(post_id) = ctx.path::<u64>();
516    /// let Path((org, repo)) = ctx.path::<(String, String)>();
517    /// ```
518    pub fn path<T>(&self) -> Path<T>
519    where
520        T: serde::de::DeserializeOwned + Send + 'static,
521    {
522        self.try_path::<T>()
523            .expect("Failed to extract Path from WireContext")
524    }
525
526    /// Extract query parameters. Panics on failure.
527    ///
528    /// ```ignore
529    /// let Query(params) = ctx.query::<Pagination>();
530    /// ```
531    pub fn query<T>(&self) -> Query<T>
532    where
533        T: serde::de::DeserializeOwned + Send + 'static,
534    {
535        self.try_query::<T>()
536            .expect("Failed to extract Query from WireContext")
537    }
538
539    /// Get shared application state by type. Panics if not found.
540    ///
541    /// State is added via `WireApp::state(value)` or `Extension(value)` layer.
542    ///
543    /// ```ignore
544    /// let db = ctx.state::<DatabasePool>();
545    /// ```
546    pub fn state<T: Clone + Send + Sync + 'static>(&self) -> T {
547        self.try_state::<T>()
548            .expect("State not found in WireContext. Did you call WireApp::state()?")
549    }
550
551    /// Get a request extension by type. Panics if not found.
552    ///
553    /// ```ignore
554    /// let flags = ctx.extension::<FeatureFlags>();
555    /// ```
556    pub fn extension<T: Clone + Send + Sync + 'static>(&self) -> T {
557        self.try_extension::<T>()
558            .expect("Extension not found in WireContext")
559    }
560
561    // -----------------------------------------------------------------------
562    // Convenience shortcuts — fallible (try_ variants)
563    // -----------------------------------------------------------------------
564
565    /// Try to extract path parameters.
566    ///
567    /// During the initial page load, this uses Axum's native `Path<T>` extractor.
568    /// During AJAX updates, it falls back to stored path params from the snapshot.
569    pub fn try_path<T>(&self) -> Result<Path<T>, axum::extract::rejection::PathRejection>
570    where
571        T: serde::de::DeserializeOwned + Send + 'static,
572    {
573        // First try native Axum Path extraction (works during initial page load
574        // when the router has injected UrlParams into extensions)
575        let mut parts = self.parts.lock().unwrap().clone();
576        if let Ok(path) =
577            futures::executor::block_on(Path::<T>::from_request_parts(&mut parts, &()))
578        {
579            return Ok(path);
580        }
581
582        // Fall back to StoredPathParams (available during AJAX round-trips)
583        self.extract_path_from_stored::<T>()
584    }
585
586    /// Try to extract query parameters.
587    pub fn try_query<T>(&self) -> Result<Query<T>, axum::extract::rejection::QueryRejection>
588    where
589        T: serde::de::DeserializeOwned + Send + 'static,
590    {
591        let mut parts = self.parts.lock().unwrap().clone();
592        futures::executor::block_on(Query::<T>::from_request_parts(&mut parts, &()))
593    }
594
595    /// Try to get shared application state by type.
596    pub fn try_state<T: Clone + Send + Sync + 'static>(&self) -> Option<T> {
597        let parts = self.parts.lock().unwrap();
598        parts.extensions.get::<T>().cloned()
599    }
600
601    /// Try to get a request extension by type.
602    pub fn try_extension<T: Clone + Send + Sync + 'static>(&self) -> Option<T> {
603        let parts = self.parts.lock().unwrap();
604        parts.extensions.get::<T>().cloned()
605    }
606
607    // -----------------------------------------------------------------------
608    // Request type detection
609    // -----------------------------------------------------------------------
610
611    /// Returns `true` if this request originated from an AJAX wire update
612    /// (`POST /_wire/update`), i.e. a subsequent action/refresh call — not the
613    /// initial page load.
614    pub fn is_wire_request(&self) -> bool {
615        let parts = self.parts.lock().unwrap();
616        parts.extensions.get::<WireRequestMarker>().is_some()
617    }
618
619    // -----------------------------------------------------------------------
620    // Internal helpers
621    // -----------------------------------------------------------------------
622
623    /// Insert a value into the request extensions. Useful for adding custom
624    /// data accessible via `ctx.extension::<T>()`.
625    pub fn insert_extension<T: Clone + Send + Sync + 'static>(&self, val: T) {
626        self.parts.lock().unwrap().extensions.insert(val);
627    }
628
629    /// Build a plain cookie jar from request headers.
630    pub fn cookie_jar(&self) -> axum_extra::extract::CookieJar {
631        let parts = self.parts.lock().unwrap();
632        axum_extra::extract::CookieJar::from_headers(&parts.headers)
633    }
634
635    /// Build a signed cookie jar from request headers using the provided key.
636    pub fn signed_cookie_jar(
637        &self,
638        key: axum_extra::extract::cookie::Key,
639    ) -> axum_extra::extract::SignedCookieJar {
640        let parts = self.parts.lock().unwrap();
641        axum_extra::extract::SignedCookieJar::from_headers(&parts.headers, key)
642    }
643
644    /// Queue a response extension to be inserted into the HTTP response.
645    pub fn set_response_extension<T>(&self, value: T)
646    where
647        T: Clone + Send + Sync + 'static,
648    {
649        push_response_extension(value);
650    }
651
652    /// Dispatch a browser event from the component root.
653    pub fn dispatch(&self, name: &str) {
654        dispatch_event(name.to_string(), None);
655    }
656
657    /// Dispatch a browser event with a JSON detail payload.
658    pub fn dispatch_with<T: serde::Serialize>(&self, name: &str, detail: T) {
659        if let Ok(value) = serde_json::to_value(detail) {
660            dispatch_event(name.to_string(), Some(value));
661        }
662    }
663
664    /// Dispatch a browser event to this component root only.
665    pub fn dispatch_self(&self, name: &str) {
666        dispatch_event_targeted(name.to_string(), None, Some(String::from("self")));
667    }
668
669    /// Dispatch a browser event with detail to this component root only.
670    pub fn dispatch_self_with<T: serde::Serialize>(&self, name: &str, detail: T) {
671        if let Ok(value) = serde_json::to_value(detail) {
672            dispatch_event_targeted(name.to_string(), Some(value), Some(String::from("self")));
673        }
674    }
675
676    /// Dispatch a browser event to all mounted components with the given wire name.
677    pub fn dispatch_to(&self, component: &str, name: &str) {
678        dispatch_event_targeted(name.to_string(), None, Some(format!("to:{component}")));
679    }
680
681    /// Dispatch a browser event with detail to all mounted components with the given wire name.
682    pub fn dispatch_to_with<T: serde::Serialize>(&self, component: &str, name: &str, detail: T) {
683        if let Ok(value) = serde_json::to_value(detail) {
684            dispatch_event_targeted(
685                name.to_string(),
686                Some(value),
687                Some(format!("to:{component}")),
688            );
689        }
690    }
691
692    /// Queue a plain cookie to be set on the HTTP response.
693    pub fn set_cookie(&self, cookie: axum_extra::extract::cookie::Cookie<'static>) {
694        if let Some(v) = cookie_header_value(&cookie) {
695            push_set_cookie_header(v);
696        }
697    }
698
699    /// Queue a plain cookie removal on the HTTP response.
700    pub fn remove_cookie(&self, cookie: axum_extra::extract::cookie::Cookie<'static>) {
701        let removal = self.cookie_jar().remove(cookie).into_response();
702        queue_set_cookie_headers_from_response(&removal);
703    }
704
705    /// Queue a signed cookie set on the HTTP response.
706    pub fn set_signed_cookie(
707        &self,
708        key: axum_extra::extract::cookie::Key,
709        cookie: axum_extra::extract::cookie::Cookie<'static>,
710    ) {
711        let signed = axum_extra::extract::SignedCookieJar::new(key)
712            .add(cookie)
713            .into_response();
714        queue_set_cookie_headers_from_response(&signed);
715    }
716
717    /// Queue a signed cookie removal on the HTTP response.
718    pub fn remove_signed_cookie(
719        &self,
720        key: axum_extra::extract::cookie::Key,
721        cookie: axum_extra::extract::cookie::Cookie<'static>,
722    ) {
723        let signed = self.signed_cookie_jar(key).remove(cookie).into_response();
724        queue_set_cookie_headers_from_response(&signed);
725    }
726}
727
728/// Marker extension inserted into request parts during `/_wire/update` handling.
729#[derive(Clone)]
730struct WireRequestMarker;
731
732// ---------------------------------------------------------------------------
733// Task-local WireContext
734// ---------------------------------------------------------------------------
735
736tokio::task_local! {
737    static WIRE_CTX: WireContext;
738}
739
740/// Get the current `WireContext` from the task-local storage.
741///
742/// Available in `render()` and action methods via `self.ctx()`.
743/// Panics if called outside a wire component lifecycle.
744pub fn get_wire_ctx() -> WireContext {
745    WIRE_CTX.try_with(|ctx| ctx.clone())
746        .expect("WireContext not available — this function must be called inside a wire component lifecycle (mount/render/action)")
747}
748
749/// Run an async block with the given `WireContext` set in task-local storage.
750pub async fn with_wire_ctx<F, R>(ctx: WireContext, f: F) -> R
751where
752    F: std::future::Future<Output = R>,
753{
754    WIRE_CTX.scope(ctx, f).await
755}
756
757// ---------------------------------------------------------------------------
758// Stored context — serialized into the snapshot for AJAX round-trips
759// ---------------------------------------------------------------------------
760
761/// Serializable context embedded in the component snapshot so that path params
762/// and other route information survive AJAX round-trips.
763#[derive(Debug, Clone, Serialize, Deserialize)]
764pub struct WireStoredContext {
765    /// Original path parameters extracted during mount (e.g. `{"postId": "42"}`).
766    #[serde(default)]
767    pub path_params: std::collections::HashMap<String, String>,
768    /// The matched route pattern (e.g. `/posts/{postId}`).
769    #[serde(default)]
770    pub matched_path: Option<String>,
771    /// Layer indices captured from the original mounted route.
772    #[serde(default)]
773    pub layer_indices: Vec<usize>,
774}
775
776/// Extension marker carrying the layer indices for the current page route.
777#[derive(Clone, Debug)]
778struct RouteLayerIndices(Vec<usize>);
779
780/// Key used in the snapshot JSON for the stored context.
781const WIRE_CTX_KEY: &str = "__wire_ctx";
782
783/// Extract stored context from a snapshot, removing it from the snapshot object.
784fn extract_stored_ctx(snapshot: &mut serde_json::Value) -> Option<WireStoredContext> {
785    snapshot
786        .as_object_mut()
787        .and_then(|obj| obj.remove(WIRE_CTX_KEY))
788        .and_then(|v| serde_json::from_value(v).ok())
789}
790
791/// Inject stored context into a snapshot.
792fn inject_stored_ctx(snapshot: &mut serde_json::Value, stored: &WireStoredContext) {
793    if let Some(obj) = snapshot.as_object_mut() {
794        if let Ok(val) = serde_json::to_value(stored) {
795            obj.insert(WIRE_CTX_KEY.to_string(), val);
796        }
797    }
798}
799
800/// Build a `WireStoredContext` from the current request parts.
801fn build_stored_ctx(parts: &Parts) -> WireStoredContext {
802    // Extract path params using the RawPathParams extractor
803    let mut path_params = std::collections::HashMap::new();
804
805    // Try to extract raw path params from a cloned parts
806    let mut parts_clone = parts.clone();
807    if let Ok(raw) = futures::executor::block_on(axum::extract::RawPathParams::from_request_parts(
808        &mut parts_clone,
809        &(),
810    )) {
811        for (key, value) in raw.iter() {
812            path_params.insert(key.to_string(), value.to_string());
813        }
814    }
815
816    let matched_path = parts
817        .extensions
818        .get::<axum::extract::MatchedPath>()
819        .map(|m| m.as_str().to_string());
820
821    let layer_indices = parts
822        .extensions
823        .get::<RouteLayerIndices>()
824        .map(|v| v.0.clone())
825        .unwrap_or_default();
826
827    WireStoredContext {
828        path_params,
829        matched_path,
830        layer_indices,
831    }
832}
833
834/// Reconstruct path-related extensions in a `Parts` from stored context,
835/// so that `Path<T>` extraction works during AJAX updates.
836fn restore_path_context(parts: &mut Parts, stored: &WireStoredContext) {
837    // We need to reconstruct the URI with path params filled in and set up
838    // the extensions that Axum's Path<T> extractor reads from.
839    // Axum's Path extractor uses `RawPathParams` from extensions.
840
841    if let Some(ref matched) = stored.matched_path {
842        // Reconstruct a URI that the path extractor can work with.
843        // Build a synthetic path by replacing {param} with actual values.
844        let mut synthetic_path = matched.clone();
845        for (key, value) in &stored.path_params {
846            synthetic_path = synthetic_path.replace(&format!("{{{key}}}"), value);
847        }
848
849        // Update the URI in parts so extractors see the correct path
850        let mut uri_parts = parts.uri.clone().into_parts();
851        if let Ok(pq) =
852            axum::http::uri::PathAndQuery::from_maybe_shared(synthetic_path.into_bytes())
853        {
854            uri_parts.path_and_query = Some(pq);
855        }
856        if let Ok(uri) = axum::http::Uri::from_parts(uri_parts) {
857            parts.uri = uri;
858        }
859
860        // Insert MatchedPath extension
861        // We use a workaround: construct a temporary router to get MatchedPath,
862        // or insert the raw path params directly.
863        // Actually, Axum's Path<T> extractor can deserialize from the URI
864        // if we set up the matched path pattern. The simplest approach is
865        // to insert the raw path params as a custom extension and have
866        // our try_path method handle both cases.
867    }
868
869    // Store path params as a custom extension for our own extractors
870    if !stored.path_params.is_empty() {
871        parts
872            .extensions
873            .insert(StoredPathParams(stored.path_params.clone()));
874    }
875}
876
877/// Custom extension type for storing path params during AJAX round-trips.
878#[derive(Clone, Debug)]
879pub struct StoredPathParams(pub std::collections::HashMap<String, String>);
880
881impl WireContext {
882    /// Extract path parameters using stored path params (works during AJAX updates).
883    /// This handles both direct Axum Path extraction and our stored params fallback.
884    fn extract_path_from_stored<T>(
885        &self,
886    ) -> Result<Path<T>, axum::extract::rejection::PathRejection>
887    where
888        T: serde::de::DeserializeOwned + Send + 'static,
889    {
890        let parts = self.parts.lock().unwrap();
891        // First try to get StoredPathParams (available during AJAX updates)
892        if let Some(StoredPathParams(params)) = parts.extensions.get::<StoredPathParams>() {
893            // Serialize the HashMap to a JSON value and deserialize as T
894            let json = serde_json::to_value(params).unwrap_or_default();
895
896            // For single-value paths (e.g., Path<u64>), try the first value
897            if let Ok(val) = serde_json::from_value::<T>(json.clone()) {
898                return Ok(Path(val));
899            }
900            // Try extracting from an array of values (for tuple paths)
901            let values: Vec<&str> = params.values().map(|s| s.as_str()).collect();
902            if values.len() == 1 {
903                if let Ok(val) = serde_json::from_str::<T>(values[0]) {
904                    return Ok(Path(val));
905                }
906                // Try wrapping in quotes for string deserialization
907                if let Ok(val) =
908                    serde_json::from_value::<T>(serde_json::Value::String(values[0].to_string()))
909                {
910                    return Ok(Path(val));
911                }
912            }
913        }
914        drop(parts);
915
916        // Fall back to normal Axum Path extraction (works during initial page load)
917        // NOTE: do not call `self.try_path()` here, that would recurse.
918        let mut parts = self.parts.lock().unwrap().clone();
919        futures::executor::block_on(Path::<T>::from_request_parts(&mut parts, &()))
920    }
921}
922
923/// Async-aware function types for the component factory.
924///
925/// Both sync and async `render`/`mount` are supported — the macro always wraps
926/// them into a `BoxFuture` so the runtime is uniformly async.
927pub type UpdateFn = fn(
928    serde_json::Value,
929    &str,
930    serde_json::Value,
931    WireContext,
932) -> Pin<Box<dyn std::future::Future<Output = WireResult> + Send + '_>>;
933pub type MountFn = fn(WireContext) -> BoxFuture<'static, WireResult>;
934/// Mount with props: receives a JSON object of initial field values.
935pub type MountWithPropsFn = fn(serde_json::Value, WireContext) -> BoxFuture<'static, WireResult>;
936
937pub struct ComponentFactory {
938    pub name: &'static str,
939    pub update: UpdateFn,
940    pub mount: MountFn,
941    pub mount_with_props: MountWithPropsFn,
942    pub url_fields: &'static [UrlFieldMeta],
943    /// Event listeners registered via `#[on("event")]` on action methods.
944    pub event_listeners: &'static [EventListenerMeta],
945    /// Event listeners registered via `#[on("event")]` on the component type.
946    pub component_event_listeners: &'static [EventListenerMeta],
947    /// Field names protected by `#[locked]` — client-side updates to these are rejected.
948    pub locked_fields: &'static [&'static str],
949    /// Named layout for this component (from `#[layout("name")]`).
950    pub layout: Option<&'static str>,
951}
952
953impl ComponentFactory {
954    pub const fn new(
955        name: &'static str,
956        update: UpdateFn,
957        mount: MountFn,
958        mount_with_props: MountWithPropsFn,
959        url_fields: &'static [UrlFieldMeta],
960        event_listeners: &'static [EventListenerMeta],
961        component_event_listeners: &'static [EventListenerMeta],
962        locked_fields: &'static [&'static str],
963        layout: Option<&'static str>,
964    ) -> Self {
965        Self {
966            name,
967            update,
968            mount,
969            mount_with_props,
970            url_fields,
971            event_listeners,
972            component_event_listeners,
973            locked_fields,
974            layout,
975        }
976    }
977}
978
979inventory::collect!(ComponentFactory);
980
981fn find_factory(name: &str) -> Option<&'static ComponentFactory> {
982    inventory::iter::<ComponentFactory>
983        .into_iter()
984        .find(|f| f.name == name)
985}
986
987/// Resolve which layout to use for a component.
988///
989/// Priority: explicit per-route override > component `#[layout("name")]` > `"default"`.
990fn resolve_layout(
991    component_name: &str,
992    explicit: Option<&LayoutFn>,
993    registry: &std::collections::HashMap<String, LayoutFn>,
994) -> LayoutFn {
995    // 1. Explicit per-route override (from .wire_with())
996    if let Some(layout) = explicit {
997        return layout.clone();
998    }
999
1000    // 2. Component's #[layout("name")] attribute
1001    if let Some(factory) = find_factory(component_name) {
1002        if let Some(layout_name) = factory.layout {
1003            if let Some(layout) = registry.get(layout_name) {
1004                return layout.clone();
1005            }
1006        }
1007    }
1008
1009    // 3. Fall back to "default"
1010    registry
1011        .get("default")
1012        .cloned()
1013        .unwrap_or_else(|| Arc::new(default_layout))
1014}
1015
1016// ---------------------------------------------------------------------------
1017// Axum handlers
1018// ---------------------------------------------------------------------------
1019
1020/// Request payload sent from the JS frontend on each interaction.
1021#[derive(Deserialize)]
1022struct WireUpdateRequest {
1023    component: String,
1024    snapshot: serde_json::Value,
1025    action: String,
1026    #[serde(default)]
1027    payload: serde_json::Value,
1028    /// Model updates from wire:model — merged into snapshot before action runs.
1029    #[serde(default)]
1030    updates: serde_json::Value,
1031}
1032
1033/// Response sent back to the JS frontend.
1034#[derive(Serialize)]
1035struct WireUpdateResponse {
1036    html: String,
1037    snapshot: serde_json::Value,
1038    #[serde(skip_serializing_if = "Vec::is_empty")]
1039    js: Vec<String>,
1040    #[serde(skip_serializing_if = "Vec::is_empty")]
1041    dispatches: Vec<DispatchEvent>,
1042    #[serde(skip_serializing_if = "Option::is_none")]
1043    redirect: Option<String>,
1044    #[serde(skip_serializing_if = "std::ops::Not::not")]
1045    redirect_navigate: bool,
1046    /// Current values of `#[url]` fields for JS to sync to the browser URL.
1047    #[serde(skip_serializing_if = "Option::is_none")]
1048    url_params: Option<serde_json::Value>,
1049}
1050
1051/// Merge `updates` (from wire:model / $wire property sets) into the snapshot.
1052fn merge_updates(snapshot: &mut serde_json::Value, updates: &serde_json::Value) {
1053    if let (Some(snap), Some(upd)) = (snapshot.as_object_mut(), updates.as_object()) {
1054        for (k, v) in upd {
1055            snap.insert(k.clone(), v.clone());
1056        }
1057    }
1058}
1059
1060fn resolve_update_layer_indices(
1061    req: &WireUpdateRequest,
1062    route_layer_map: &std::collections::HashMap<String, Vec<usize>>,
1063) -> Vec<usize> {
1064    let stored = req.snapshot.get(WIRE_CTX_KEY);
1065
1066    if let Some(indices) = stored
1067        .and_then(|ctx| ctx.get("layer_indices"))
1068        .and_then(|v| serde_json::from_value::<Vec<usize>>(v.clone()).ok())
1069    {
1070        if !indices.is_empty() {
1071            return indices;
1072        }
1073    }
1074
1075    if let Some(matched_path) = stored
1076        .and_then(|ctx| ctx.get("matched_path"))
1077        .and_then(|v| v.as_str())
1078    {
1079        return route_layer_map
1080            .get(matched_path)
1081            .cloned()
1082            .unwrap_or_default();
1083    }
1084
1085    Vec::new()
1086}
1087
1088fn resolve_event_action(component_name: &str, event_name: &str) -> Option<&'static str> {
1089    find_factory(component_name).and_then(|factory| {
1090        factory
1091            .event_listeners
1092            .iter()
1093            .find(|m| m.event == event_name)
1094            .or_else(|| {
1095                factory
1096                    .component_event_listeners
1097                    .iter()
1098                    .find(|m| m.event == event_name)
1099            })
1100            .map(|m| m.action)
1101    })
1102}
1103
1104fn wire_event_listener_attr(name: &str) -> String {
1105    find_factory(name)
1106        .filter(|f| !f.event_listeners.is_empty() || !f.component_event_listeners.is_empty())
1107        .map(|f| {
1108            let mut map = serde_json::Map::new();
1109            for meta in f.component_event_listeners {
1110                map.insert(
1111                    meta.event.to_string(),
1112                    serde_json::Value::String(meta.action.to_string()),
1113                );
1114            }
1115            for meta in f.event_listeners {
1116                map.insert(
1117                    meta.event.to_string(),
1118                    serde_json::Value::String(meta.action.to_string()),
1119                );
1120            }
1121            let json = serde_json::to_string(&serde_json::Value::Object(map)).unwrap_or_default();
1122            format!(r#" data-wire-on="{}""#, escape_attr(&json))
1123        })
1124        .unwrap_or_default()
1125}
1126
1127fn try_map_event_to_action(req: &mut WireUpdateRequest) {
1128    if req.action != "$event" {
1129        return;
1130    }
1131
1132    let event_name = req
1133        .payload
1134        .get("event")
1135        .and_then(|v| v.as_str())
1136        .map(String::from)
1137        .or_else(|| {
1138            req.payload
1139                .get("detail")
1140                .and_then(|d| d.get("event"))
1141                .and_then(|v| v.as_str())
1142                .map(String::from)
1143        });
1144
1145    let Some(event_name) = event_name else {
1146        return;
1147    };
1148
1149    if let Some(mapped) = resolve_event_action(&req.component, &event_name) {
1150        req.action = String::from(mapped);
1151    }
1152}
1153
1154async fn dispatch_wire_update(
1155    request: Request,
1156    states: Arc<Vec<Arc<dyn StateInjector>>>,
1157    layers: Vec<RouterLayer>,
1158    route_layer_map: Arc<std::collections::HashMap<String, Vec<usize>>>,
1159) -> Response {
1160    let (parts, body) = request.into_parts();
1161    let body_bytes = match axum::body::to_bytes(body, usize::MAX).await {
1162        Ok(b) => b,
1163        Err(e) => {
1164            return (
1165                StatusCode::BAD_REQUEST,
1166                Json(serde_json::json!({ "error": format!("Failed to read body: {e}") })),
1167            )
1168                .into_response();
1169        }
1170    };
1171
1172    let layer_indices = serde_json::from_slice::<WireUpdateRequest>(&body_bytes)
1173        .map(|req| resolve_update_layer_indices(&req, &route_layer_map))
1174        .unwrap_or_default();
1175
1176    let update_handler = move |request: Request| async move { handle_wire_update(request).await };
1177
1178    let mut router = Router::new().route("/_wire/update", post(update_handler));
1179
1180    for idx in layer_indices {
1181        if let Some(apply_layer) = layers.get(idx) {
1182            router = apply_layer(router);
1183        }
1184    }
1185
1186    // Ensure app state is available to route-specific middleware before it runs.
1187    let states_for_layer = states.clone();
1188    let state_layer = move |request: Request, next: middleware::Next| {
1189        let states = states_for_layer.clone();
1190        async move {
1191            let request = apply_states_to_request(request, &states);
1192            next.run(request).await
1193        }
1194    };
1195    router = router.layer(middleware::from_fn(state_layer));
1196
1197    let request = Request::<Body>::from_parts(parts, Body::from(body_bytes));
1198    match router.oneshot(request).await {
1199        Ok(response) => response,
1200        Err(never) => match never {},
1201    }
1202}
1203
1204async fn handle_wire_update(request: Request) -> impl IntoResponse {
1205    // Split the request to get parts (headers, extensions, uri) and body
1206    let (mut parts, body) = request.into_parts();
1207
1208    // Mark this as a wire AJAX request (not an initial page load)
1209    parts.extensions.insert(WireRequestMarker);
1210
1211    // Read body and deserialize
1212    let body_bytes = match axum::body::to_bytes(body, usize::MAX).await {
1213        Ok(b) => b,
1214        Err(e) => {
1215            return (
1216                StatusCode::BAD_REQUEST,
1217                Json(serde_json::json!({ "error": format!("Failed to read body: {e}") })),
1218            )
1219                .into_response();
1220        }
1221    };
1222    let mut req: WireUpdateRequest = match serde_json::from_slice(&body_bytes) {
1223        Ok(r) => r,
1224        Err(e) => {
1225            return (
1226                StatusCode::BAD_REQUEST,
1227                Json(serde_json::json!({ "error": format!("Invalid JSON: {e}") })),
1228            )
1229                .into_response();
1230        }
1231    };
1232
1233    try_map_event_to_action(&mut req);
1234
1235    let factory = match find_factory(&req.component) {
1236        Some(f) => f,
1237        None => {
1238            return (
1239                StatusCode::NOT_FOUND,
1240                Json(
1241                    serde_json::json!({ "error": format!("Unknown component: {}", req.component) }),
1242                ),
1243            )
1244                .into_response();
1245        }
1246    };
1247
1248    // Reject client-side updates to #[locked] fields
1249    if !factory.locked_fields.is_empty() {
1250        if let Some(upd) = req.updates.as_object() {
1251            for key in upd.keys() {
1252                if factory.locked_fields.contains(&key.as_str()) {
1253                    return (
1254                        StatusCode::FORBIDDEN,
1255                        Json(serde_json::json!({ "error": format!("Cannot update locked property: {}", key) })),
1256                    )
1257                        .into_response();
1258                }
1259            }
1260        }
1261    }
1262
1263    // Merge any wire:model / $wire property updates into the snapshot first
1264    let mut snapshot = req.snapshot;
1265    merge_updates(&mut snapshot, &req.updates);
1266
1267    // Extract stored context from snapshot (path params, matched path)
1268    // and restore it into the request parts so extractors work
1269    let stored_ctx = extract_stored_ctx(&mut snapshot);
1270    if let Some(ref stored) = stored_ctx {
1271        restore_path_context(&mut parts, stored);
1272    }
1273
1274    // Build WireContext from the AJAX request parts
1275    let ctx = WireContext::new(parts);
1276
1277    // Inject any app-level state from extensions (already present from middleware)
1278
1279    match (factory.update)(snapshot, &req.action, req.payload, ctx).await {
1280        Ok(mut resp) => {
1281            let response_extensions = std::mem::take(&mut resp.effects.response_extensions);
1282            let set_cookie_headers = std::mem::take(&mut resp.effects.set_cookie_headers);
1283
1284            // Re-inject stored context into the response snapshot
1285            if let Some(stored) = stored_ctx {
1286                inject_stored_ctx(&mut resp.snapshot, &stored);
1287            }
1288
1289            // Extract current values of #[url] fields from snapshot
1290            let url_params = if factory.url_fields.is_empty() {
1291                None
1292            } else {
1293                let mut params = serde_json::Map::new();
1294                if let Some(snap_obj) = resp.snapshot.as_object() {
1295                    for uf in factory.url_fields {
1296                        if let Some(val) = snap_obj.get(uf.field_name) {
1297                            params.insert(uf.query_name.to_string(), val.clone());
1298                        }
1299                    }
1300                }
1301                Some(serde_json::Value::Object(params))
1302            };
1303
1304            let mut response = Json(WireUpdateResponse {
1305                html: resp.html,
1306                snapshot: resp.snapshot,
1307                js: resp.effects.js,
1308                dispatches: resp.effects.dispatches,
1309                redirect: resp.effects.redirect,
1310                redirect_navigate: resp.effects.redirect_navigate,
1311                url_params,
1312            })
1313            .into_response();
1314
1315            for apply in response_extensions {
1316                apply(response.extensions_mut());
1317            }
1318
1319            for value in set_cookie_headers {
1320                response.headers_mut().append(SET_COOKIE, value);
1321            }
1322
1323            response
1324        }
1325        Err(e) => (
1326            StatusCode::INTERNAL_SERVER_ERROR,
1327            Json(serde_json::json!({ "error": e.to_string() })),
1328        )
1329            .into_response(),
1330    }
1331}
1332
1333// ---------------------------------------------------------------------------
1334// HTML helpers
1335// ---------------------------------------------------------------------------
1336
1337/// Parse a query string into a HashMap (simple key=value pairs, no arrays).
1338fn parse_query_string(query: Option<&str>) -> std::collections::HashMap<String, String> {
1339    query
1340        .map(|q| {
1341            q.split('&')
1342                .filter(|s| !s.is_empty())
1343                .filter_map(|pair| {
1344                    let mut parts = pair.splitn(2, '=');
1345                    let key = parts.next()?;
1346                    let value = parts.next().unwrap_or("");
1347                    Some((percent_decode(key), percent_decode(value)))
1348                })
1349                .collect()
1350        })
1351        .unwrap_or_default()
1352}
1353
1354/// Basic percent-decoding for query string values.
1355fn percent_decode(s: &str) -> String {
1356    let mut result = Vec::new();
1357    let mut chars = s.bytes();
1358    while let Some(b) = chars.next() {
1359        if b == b'%' {
1360            let hi = chars.next().and_then(hex_val);
1361            let lo = chars.next().and_then(hex_val);
1362            if let (Some(h), Some(l)) = (hi, lo) {
1363                result.push(h << 4 | l);
1364            }
1365        } else if b == b'+' {
1366            result.push(b' ');
1367        } else {
1368            result.push(b);
1369        }
1370    }
1371    String::from_utf8(result).unwrap_or_else(|_| s.to_string())
1372}
1373
1374fn hex_val(b: u8) -> Option<u8> {
1375    match b {
1376        b'0'..=b'9' => Some(b - b'0'),
1377        b'a'..=b'f' => Some(b - b'a' + 10),
1378        b'A'..=b'F' => Some(b - b'A' + 10),
1379        _ => None,
1380    }
1381}
1382
1383fn escape_attr(s: &str) -> String {
1384    s.replace('&', "&amp;")
1385        .replace('"', "&quot;")
1386        .replace('<', "&lt;")
1387        .replace('>', "&gt;")
1388}
1389
1390/// Wraps a component's rendered HTML with the wire root element and snapshot data.
1391pub fn render_component_html(name: &str, html: &str, snapshot: &serde_json::Value) -> String {
1392    let snapshot_json = serde_json::to_string(snapshot).unwrap_or_default();
1393    let escaped = escape_attr(&snapshot_json);
1394
1395    // Look up URL field metadata for this component
1396    let url_attr = find_factory(name)
1397        .filter(|f| !f.url_fields.is_empty())
1398        .map(|f| {
1399            let json = serde_json::to_string(f.url_fields).unwrap_or_default();
1400            format!(r#" data-wire-url="{}""#, escape_attr(&json))
1401        })
1402        .unwrap_or_default();
1403
1404    let event_attr = wire_event_listener_attr(name);
1405
1406    format!(
1407        r#"<div data-wire-component="{name}" data-wire-snapshot="{escaped}"{url_attr}{event_attr}>{html}</div>"#
1408    )
1409}
1410
1411/// Same as `render_component_html`, but attaches event listeners that map
1412/// browser events to wire actions for component tags using `@event={Self::action}`.
1413pub fn render_component_html_with_listeners(
1414    name: &str,
1415    html: &str,
1416    snapshot: &serde_json::Value,
1417    listeners: &[(String, String)],
1418) -> String {
1419    let mut out = render_component_html(name, html, snapshot);
1420    if listeners.is_empty() {
1421        return out;
1422    }
1423
1424    if let Some(insert_pos) = out.find('>') {
1425        let attrs = listeners
1426            .iter()
1427            .map(|(event, action)| {
1428                format!(" x-on:{}=\"{}\"", escape_attr(event), escape_attr(action))
1429            })
1430            .collect::<String>();
1431        out.insert_str(insert_pos, &attrs);
1432    }
1433
1434    out
1435}
1436
1437/// Mount a component by name and return the full HTML (including wrapper).
1438pub async fn mount_component(name: &str) -> Result<String, WireError> {
1439    let factory =
1440        find_factory(name).ok_or_else(|| WireError::UnknownComponent(name.to_string()))?;
1441    let ctx = WIRE_CTX
1442        .try_with(|c| c.clone())
1443        .unwrap_or_else(|_| WireContext::empty());
1444    let resp = (factory.mount)(ctx).await?;
1445    Ok(render_component_html(name, &resp.html, &resp.snapshot))
1446}
1447
1448fn block_on_component_future<F>(fut: F) -> F::Output
1449where
1450    F: std::future::Future + Send + 'static,
1451    F::Output: Send + 'static,
1452{
1453    if let Ok(handle) = tokio::runtime::Handle::try_current() {
1454        if matches!(
1455            handle.runtime_flavor(),
1456            tokio::runtime::RuntimeFlavor::MultiThread
1457        ) {
1458            return tokio::task::block_in_place(|| handle.block_on(fut));
1459        }
1460    }
1461
1462    let join = std::thread::spawn(move || {
1463        let rt = tokio::runtime::Builder::new_current_thread()
1464            .enable_all()
1465            .build()
1466            .expect("failed to build temporary tokio runtime");
1467        rt.block_on(fut)
1468    });
1469
1470    match join.join() {
1471        Ok(output) => output,
1472        Err(panic) => std::panic::resume_unwind(panic),
1473    }
1474}
1475
1476/// Synchronous mount — used by `html!` macro for sub-components where we're
1477/// already inside a sync `render()` context.
1478pub fn mount_component_sync(name: &str) -> Result<String, WireError> {
1479    let factory =
1480        find_factory(name).ok_or_else(|| WireError::UnknownComponent(name.to_string()))?;
1481    let ctx = WIRE_CTX
1482        .try_with(|c| c.clone())
1483        .unwrap_or_else(|_| WireContext::empty());
1484    let resp = block_on_component_future((factory.mount)(ctx))?;
1485    Ok(render_component_html(name, &resp.html, &resp.snapshot))
1486}
1487
1488/// Mount a component with initial prop values (async).
1489pub async fn mount_component_with_props(
1490    name: &str,
1491    props: serde_json::Value,
1492) -> Result<String, WireError> {
1493    let factory =
1494        find_factory(name).ok_or_else(|| WireError::UnknownComponent(name.to_string()))?;
1495    let ctx = WIRE_CTX
1496        .try_with(|c| c.clone())
1497        .unwrap_or_else(|_| WireContext::empty());
1498    let resp = (factory.mount_with_props)(props, ctx).await?;
1499    Ok(render_component_html(name, &resp.html, &resp.snapshot))
1500}
1501
1502/// Synchronous mount with props — used by `html!` macro for `<Counter count=42 />`.
1503pub fn mount_component_with_props_sync(
1504    name: &str,
1505    props: serde_json::Value,
1506) -> Result<String, WireError> {
1507    let factory =
1508        find_factory(name).ok_or_else(|| WireError::UnknownComponent(name.to_string()))?;
1509    let ctx = WIRE_CTX
1510        .try_with(|c| c.clone())
1511        .unwrap_or_else(|_| WireContext::empty());
1512    let resp = block_on_component_future((factory.mount_with_props)(props, ctx))?;
1513    Ok(render_component_html(name, &resp.html, &resp.snapshot))
1514}
1515
1516/// Synchronous mount with props + event listeners for sub-components.
1517pub fn mount_component_with_options_sync(
1518    name: &str,
1519    props: serde_json::Value,
1520    listeners: Option<serde_json::Value>,
1521) -> Result<String, WireError> {
1522    let factory =
1523        find_factory(name).ok_or_else(|| WireError::UnknownComponent(name.to_string()))?;
1524    let ctx = WIRE_CTX
1525        .try_with(|c| c.clone())
1526        .unwrap_or_else(|_| WireContext::empty());
1527    let resp = block_on_component_future((factory.mount_with_props)(props, ctx))?;
1528
1529    let listeners_vec = listeners
1530        .and_then(|v| v.as_object().cloned())
1531        .map(|obj| {
1532            obj.into_iter()
1533                .filter_map(|(event, action)| action.as_str().map(|a| (event, String::from(a))))
1534                .collect::<Vec<_>>()
1535        })
1536        .unwrap_or_default();
1537
1538    Ok(render_component_html_with_listeners(
1539        name,
1540        &resp.html,
1541        &resp.snapshot,
1542        &listeners_vec,
1543    ))
1544}
1545
1546/// Mount a component, merging URL query parameters into `#[url]` fields.
1547///
1548/// For each `#[url]` field on the component, if a matching query parameter is
1549/// present, its value is merged into the initial props before mounting.
1550/// The default (pre-query) values of URL fields are embedded as
1551/// `data-wire-url-defaults` so JS can determine when to exclude params.
1552pub async fn mount_component_with_query(
1553    name: &str,
1554    query_params: &std::collections::HashMap<String, String>,
1555    ctx: &WireContext,
1556) -> Result<String, WireError> {
1557    let factory =
1558        find_factory(name).ok_or_else(|| WireError::UnknownComponent(name.to_string()))?;
1559
1560    // Build stored context from the request parts (path params, matched path)
1561    let stored_ctx = {
1562        let parts = ctx.parts.lock().unwrap();
1563        build_stored_ctx(&parts)
1564    };
1565
1566    if factory.url_fields.is_empty() {
1567        // No URL fields — normal mount, ignore query params
1568        let mut resp = (factory.mount)(ctx.clone()).await?;
1569        // Inject stored context into snapshot
1570        inject_stored_ctx(&mut resp.snapshot, &stored_ctx);
1571        return Ok(render_component_html(name, &resp.html, &resp.snapshot));
1572    }
1573
1574    // First, mount with defaults to capture the default values of URL fields
1575    let default_resp = (factory.mount)(ctx.clone()).await?;
1576    let mut url_defaults = serde_json::Map::new();
1577    if let Some(snap_obj) = default_resp.snapshot.as_object() {
1578        for uf in factory.url_fields {
1579            if let Some(val) = snap_obj.get(uf.field_name) {
1580                url_defaults.insert(uf.field_name.to_string(), val.clone());
1581            }
1582        }
1583    }
1584
1585    // Build props from query parameters that match #[url] fields
1586    let mut props = serde_json::Map::new();
1587    for uf in factory.url_fields {
1588        if let Some(value) = query_params.get(uf.query_name) {
1589            // Try to parse as JSON first (numbers, booleans, etc.), fall back to string
1590            let json_value = serde_json::from_str(value)
1591                .unwrap_or_else(|_| serde_json::Value::String(value.clone()));
1592            props.insert(uf.field_name.to_string(), json_value);
1593        }
1594    }
1595
1596    let mut resp = if props.is_empty() {
1597        default_resp
1598    } else {
1599        (factory.mount_with_props)(serde_json::Value::Object(props), ctx.clone()).await?
1600    };
1601
1602    // Inject stored context into snapshot
1603    inject_stored_ctx(&mut resp.snapshot, &stored_ctx);
1604
1605    Ok(render_component_html_with_url_defaults(
1606        name,
1607        &resp.html,
1608        &resp.snapshot,
1609        &serde_json::Value::Object(url_defaults),
1610    ))
1611}
1612
1613/// Like `render_component_html` but also embeds `data-wire-url-defaults`.
1614fn render_component_html_with_url_defaults(
1615    name: &str,
1616    html: &str,
1617    snapshot: &serde_json::Value,
1618    url_defaults: &serde_json::Value,
1619) -> String {
1620    let snapshot_json = serde_json::to_string(snapshot).unwrap_or_default();
1621    let escaped = escape_attr(&snapshot_json);
1622
1623    let url_attr = find_factory(name)
1624        .filter(|f| !f.url_fields.is_empty())
1625        .map(|f| {
1626            let json = serde_json::to_string(f.url_fields).unwrap_or_default();
1627            format!(r#" data-wire-url="{}""#, escape_attr(&json))
1628        })
1629        .unwrap_or_default();
1630
1631    let event_attr = wire_event_listener_attr(name);
1632
1633    let defaults_json = serde_json::to_string(url_defaults).unwrap_or_default();
1634    let defaults_attr = format!(
1635        r#" data-wire-url-defaults="{}""#,
1636        escape_attr(&defaults_json)
1637    );
1638
1639    format!(
1640        r#"<div data-wire-component="{name}" data-wire-snapshot="{escaped}"{url_attr}{defaults_attr}{event_attr}>{html}</div>"#
1641    )
1642}
1643
1644// ---------------------------------------------------------------------------
1645// JavaScript runtime (embedded)
1646// ---------------------------------------------------------------------------
1647
1648/// The JS runtime that powers wire: directives on the client.
1649/// Ships Alpine.js + morphdom + the $wire proxy.
1650pub const WIRE_JS: &str = r##"
1651<script src="https://unpkg.com/morphdom@2.7.4/dist/morphdom-umd.min.js"></script>
1652<script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3/dist/cdn.min.js"></script>
1653<script>
1654(function() {
1655    "use strict";
1656
1657    const WIRE_ENDPOINT = "/_wire/update";
1658
1659    // -----------------------------------------------------------------------
1660    // Helpers
1661    // -----------------------------------------------------------------------
1662
1663    function findRoot(el) {
1664        return el.closest("[data-wire-component]");
1665    }
1666
1667    function getSnapshot(root) {
1668        return JSON.parse(root.dataset.wireSnapshot);
1669    }
1670
1671    function setSnapshot(root, snap) {
1672        root.dataset.wireSnapshot = JSON.stringify(snap);
1673    }
1674
1675    // Track request ordering per component root to avoid out-of-order morphs.
1676    // Only the latest response is allowed to patch the DOM.
1677    const pending = new WeakMap();
1678    let navVersion = 0;
1679
1680    // -----------------------------------------------------------------------
1681    // Core: send an action to the server and morph the result
1682    // -----------------------------------------------------------------------
1683
1684    async function sendAction(root, action, payload, updates) {
1685        const requestNavVersion = navVersion;
1686        const requestId = (pending.get(root) || 0) + 1;
1687        pending.set(root, requestId);
1688
1689        const component = root.dataset.wireComponent;
1690        const snapshot = getSnapshot(root);
1691
1692        // Loading state
1693        root.setAttribute("data-wire-loading", "");
1694
1695        try {
1696            const res = await fetch(WIRE_ENDPOINT, {
1697                method: "POST",
1698                credentials: "same-origin",
1699                headers: { "Content-Type": "application/json" },
1700                body: JSON.stringify({
1701                    component,
1702                    snapshot,
1703                    action: action || "$refresh",
1704                    payload: payload || {},
1705                    updates: updates || {},
1706                }),
1707            });
1708
1709            if (!res.ok) {
1710                console.error("[wire] Update failed:", res.status);
1711                return;
1712            }
1713
1714            const data = await res.json();
1715
1716            // Ignore stale responses; a newer request already started.
1717            if (pending.get(root) !== requestId) {
1718                return;
1719            }
1720
1721            // Ignore responses from a previous page navigation cycle.
1722            if (requestNavVersion !== navVersion) {
1723                return;
1724            }
1725
1726            // Root may have been removed/replaced during navigation.
1727            if (!document.contains(root)) {
1728                return;
1729            }
1730
1731            // Handle redirect
1732            if (data.redirect) {
1733                if (data.redirect_navigate && typeof navigateTo === "function") {
1734                    navigateTo(data.redirect);
1735                } else {
1736                    window.location.href = data.redirect;
1737                }
1738                return;
1739            }
1740
1741            // Update snapshot on the root
1742            setSnapshot(root, data.snapshot);
1743
1744            // Sync #[url] fields to browser URL
1745            if (data.url_params) {
1746                syncUrlParams(root, data.url_params);
1747            }
1748
1749            // Skip render — only snapshot was updated, no HTML to morph
1750            if (!data.html) {
1751                updateWireData(root, data.snapshot);
1752                // Still execute JS commands
1753                if (data.js && data.js.length) {
1754                    const $wire = root.__wire_proxy || {};
1755                    for (const code of data.js) {
1756                        try { new Function("$wire", code).call(root, $wire); } catch(e) { console.error("[wire] js() error:", e); }
1757                    }
1758                }
1759
1760                if (data.dispatches && data.dispatches.length) {
1761                    for (const evt of data.dispatches) {
1762                        if (!evt || !evt.name) continue;
1763                        dispatchWireEvent(root, evt);
1764                    }
1765                }
1766                return;
1767            }
1768
1769            // Build a temporary wrapper to morph from
1770            const fresh = root.cloneNode(false);
1771            fresh.innerHTML = data.html;
1772
1773            // Remember which element has focus + cursor position
1774            const focused = document.activeElement;
1775            const focusedWireModel = focused && (
1776                focused.getAttribute("wire:model") ||
1777                focused.getAttribute("wire:model.live") ||
1778                focused.getAttribute("wire:model.defer")
1779            );
1780            const selStart = focused && focused.selectionStart;
1781            const selEnd = focused && focused.selectionEnd;
1782
1783            // Morph children only — preserves the root element (and its snapshot attrs)
1784            morphdom(root, fresh, {
1785                childrenOnly: true,
1786                getNodeKey(node) {
1787                    if (node.getAttribute) {
1788                        const key = node.getAttribute("wire:key");
1789                        return key && key.length ? key : null;
1790                    }
1791                    return null;
1792                },
1793                onBeforeElUpdated(fromEl, toEl) {
1794                    // wire:ignore — skip this entire subtree
1795                    if (fromEl.hasAttribute && fromEl.hasAttribute("wire:ignore")) {
1796                        return false;
1797                    }
1798                    // Preserve focused input value to prevent caret jump
1799                    if (fromEl === focused && focusedWireModel) {
1800                        toEl.value = fromEl.value;
1801                    }
1802                    // Preserve Alpine state
1803                    if (fromEl._x_dataStack) {
1804                        window.Alpine && Alpine.clone(fromEl, toEl);
1805                    }
1806                    return true;
1807                },
1808            });
1809
1810            // Restore focus if it was on a wire:model input
1811            if (focusedWireModel) {
1812                const restored = root.querySelector(
1813                    "[wire\\:model='" + focusedWireModel + "']," +
1814                    "[wire\\:model\\.live='" + focusedWireModel + "']," +
1815                    "[wire\\:model\\.defer='" + focusedWireModel + "']"
1816                );
1817                if (restored && restored !== document.activeElement) {
1818                    restored.focus();
1819                    if (selStart !== null && restored.setSelectionRange) {
1820                        try { restored.setSelectionRange(selStart, selEnd); } catch(e) {}
1821                    }
1822                }
1823            }
1824
1825            // Update $wire reactive data for Alpine
1826            updateWireData(root, data.snapshot);
1827
1828            // Execute server-dispatched JS commands with $wire in scope
1829            if (data.js && data.js.length) {
1830                const $wire = root.__wire_proxy || {};
1831                for (const code of data.js) {
1832                    try {
1833                        new Function("$wire", code).call(root, $wire);
1834                    } catch(e) {
1835                        console.error("[wire] js() error:", e);
1836                    }
1837                }
1838            }
1839
1840            // Dispatch server-emitted browser events from this component root
1841            if (data.dispatches && data.dispatches.length) {
1842                for (const evt of data.dispatches) {
1843                    if (!evt || !evt.name) continue;
1844                    dispatchWireEvent(root, evt);
1845                }
1846            }
1847
1848            // Re-setup polling for any new wire:poll elements
1849            setupPolling(root);
1850
1851        } finally {
1852            if (pending.get(root) === requestId) {
1853                root.removeAttribute("data-wire-loading");
1854            }
1855        }
1856    }
1857
1858    // -----------------------------------------------------------------------
1859    // $wire proxy — available in Alpine expressions via x-data
1860    // -----------------------------------------------------------------------
1861
1862    function createWireProxy(root) {
1863        const snapshot = getSnapshot(root);
1864        const reactiveData = Alpine.reactive ? Alpine.reactive({ ...snapshot }) : { ...snapshot };
1865
1866        const proxy = new Proxy(reactiveData, {
1867            get(target, prop) {
1868                if (prop === "$refresh") return () => sendAction(root, "$refresh", {}, {});
1869                if (prop === "$dispatch") return (name, detail = {}) => dispatchClientEvent(root, name, detail, true);
1870                if (prop === "$dispatchSelf") return (name, detail = {}) => dispatchClientEvent(root, name, detail, false);
1871                if (prop === "$dispatchTo") return (component, name, detail = {}) => dispatchClientEventTo(component, name, detail);
1872                if (prop === "$parent") {
1873                    const parentRoot = root.parentElement && root.parentElement.closest("[data-wire-component]");
1874                    if (!parentRoot) return {};
1875                    if (!parentRoot.__wire_proxy && !parentRoot.__wire_initialized) {
1876                        try { initComponent(parentRoot); } catch(_) {}
1877                    }
1878                    return parentRoot.__wire_proxy || {};
1879                }
1880                if (prop === "$set") return (key, value) => {
1881                    target[key] = value;
1882                    const updates = {};
1883                    updates[key] = value;
1884                    sendAction(root, "$refresh", {}, updates);
1885                };
1886                if (prop === "$snapshot") return getSnapshot(root);
1887                if (prop === "$root") return root;
1888                if (prop in target) return target[prop];
1889
1890                // Assume it's a method call
1891                return (...args) => {
1892                    const updates = collectDirtyFields(target, getSnapshot(root));
1893                    sendAction(root, prop, args.length ? { args } : {}, updates);
1894                };
1895            },
1896            set(target, prop, value) {
1897                target[prop] = value;
1898                const snap = getSnapshot(root);
1899                snap[prop] = value;
1900                setSnapshot(root, snap);
1901                return true;
1902            }
1903        });
1904
1905        return { proxy, reactiveData };
1906    }
1907
1908    function collectDirtyFields(current, original) {
1909        const updates = {};
1910        for (const key of Object.keys(current)) {
1911            if (JSON.stringify(current[key]) !== JSON.stringify(original[key])) {
1912                updates[key] = current[key];
1913            }
1914        }
1915        return updates;
1916    }
1917
1918    function dispatchClientEvent(root, name, detail, bubbles) {
1919        if (!name) return;
1920        root.dispatchEvent(new CustomEvent(name, {
1921            detail: detail ?? null,
1922            bubbles,
1923            composed: true,
1924        }));
1925    }
1926
1927    function dispatchClientEventTo(componentName, name, detail) {
1928        if (!componentName || !name) return;
1929        document.querySelectorAll(`[data-wire-component="${componentName}"]`).forEach((el) => {
1930            el.dispatchEvent(new CustomEvent(name, {
1931                detail: detail ?? null,
1932                bubbles: true,
1933                composed: true,
1934            }));
1935        });
1936    }
1937
1938    function evaluateWireExpression(root, expr, event) {
1939        const $wire = root.__wire_proxy || {};
1940        const $dispatch = (name, detail = {}) => dispatchClientEvent(root, name, detail, true);
1941        const $dispatchSelf = (name, detail = {}) => dispatchClientEvent(root, name, detail, false);
1942        const $dispatchTo = (component, name, detail = {}) => dispatchClientEventTo(component, name, detail);
1943
1944        const scope = Object.create($wire || null);
1945        scope.$wire = $wire;
1946        scope.$dispatch = $dispatch;
1947        scope.$dispatchSelf = $dispatchSelf;
1948        scope.$dispatchTo = $dispatchTo;
1949
1950        return new Function("$event", "$scope", `with($scope){ ${expr} }`).call(root, event, scope);
1951    }
1952
1953    function updateWireData(root, snapshot) {
1954        if (root.__wire_data) {
1955            for (const [k, v] of Object.entries(snapshot)) {
1956                root.__wire_data[k] = v;
1957            }
1958        }
1959    }
1960
1961    function dispatchWireEvent(root, evt) {
1962        const target = evt.target || null;
1963        const detail = evt.detail ?? null;
1964
1965        if (target === "self") {
1966            root.dispatchEvent(new CustomEvent(evt.name, {
1967                detail,
1968                bubbles: false,
1969                composed: true,
1970            }));
1971            return;
1972        }
1973
1974                if (target && target.startsWith("to:")) {
1975                    const componentName = target.slice(3);
1976                    if (!componentName) return;
1977                    document.querySelectorAll(`[data-wire-component="${componentName}"]`).forEach((el) => {
1978                        el.dispatchEvent(new CustomEvent(evt.name, {
1979                            detail,
1980                            bubbles: true,
1981                            composed: true,
1982                        }));
1983                    });
1984                    return;
1985                }
1986
1987        root.dispatchEvent(new CustomEvent(evt.name, {
1988            detail,
1989            bubbles: true,
1990            composed: true,
1991        }));
1992    }
1993
1994    // -----------------------------------------------------------------------
1995    // #[url] — URL query parameter sync
1996    // -----------------------------------------------------------------------
1997
1998    function getUrlFields(root) {
1999        if (root.__wire_url_fields) return root.__wire_url_fields;
2000        const attr = root.getAttribute("data-wire-url");
2001        if (!attr) return null;
2002        try {
2003            const fields = JSON.parse(attr);
2004            root.__wire_url_fields = fields;
2005            return fields;
2006        } catch { return null; }
2007    }
2008
2009    /**
2010     * Update the browser URL with current #[url] field values.
2011     * Called after server responses and client-side wire:model changes.
2012     *
2013     * @param {Element} root - component root element
2014     * @param {Object} urlParams - { queryName: value } from server response
2015     * @param {boolean} [forceHistory] - if any field has history:true, use pushState
2016     */
2017    function syncUrlParams(root, urlParams, forceHistory) {
2018        const fields = getUrlFields(root);
2019        if (!fields || !urlParams) return;
2020
2021        const url = new URL(window.location.href);
2022        let useHistory = !!forceHistory;
2023        const defaults = root.__wire_url_defaults || {};
2024
2025        for (const field of fields) {
2026            const queryKey = field.query_name;
2027            const fieldName = field.field_name;
2028            const value = urlParams[queryKey];
2029
2030            if (field.history) useHistory = true;
2031
2032            // Determine the default value for this field
2033            const defaultVal = defaults[fieldName];
2034
2035            // Decide whether to include in URL
2036            const isDefault = JSON.stringify(value) === JSON.stringify(defaultVal);
2037
2038            if (field.keep || !isDefault) {
2039                // Include in URL
2040                if (value === null || value === undefined) {
2041                    url.searchParams.delete(queryKey);
2042                } else if (typeof value === "object") {
2043                    url.searchParams.set(queryKey, JSON.stringify(value));
2044                } else {
2045                    url.searchParams.set(queryKey, String(value));
2046                }
2047            } else {
2048                // Remove from URL (at default value)
2049                url.searchParams.delete(queryKey);
2050            }
2051        }
2052
2053        const newUrl = url.toString();
2054        if (newUrl !== window.location.href) {
2055            if (useHistory) {
2056                history.pushState({}, "", newUrl);
2057            } else {
2058                history.replaceState({}, "", newUrl);
2059            }
2060        }
2061    }
2062
2063    // -----------------------------------------------------------------------
2064    // Initialize wire components with Alpine x-data
2065    // -----------------------------------------------------------------------
2066
2067    function initComponent(root) {
2068        if (root.__wire_initialized) return;
2069        root.__wire_initialized = true;
2070
2071        // Read default values for #[url] fields (set by server before query param merge)
2072        const fields = getUrlFields(root);
2073        if (fields) {
2074            const defaultsAttr = root.getAttribute("data-wire-url-defaults");
2075            if (defaultsAttr) {
2076                try { root.__wire_url_defaults = JSON.parse(defaultsAttr); } catch {}
2077            }
2078            if (!root.__wire_url_defaults) {
2079                // Fallback: use current snapshot as defaults
2080                const snapshot = getSnapshot(root);
2081                const defaults = {};
2082                for (const field of fields) {
2083                    defaults[field.field_name] = snapshot[field.field_name];
2084                }
2085                root.__wire_url_defaults = defaults;
2086            }
2087        }
2088
2089        const { proxy, reactiveData } = createWireProxy(root);
2090        root.__wire_data = reactiveData;
2091        root.__wire_proxy = proxy;
2092
2093        if (!root.hasAttribute("x-data")) {
2094            root.setAttribute("x-data", "");
2095        }
2096
2097        if (window.Alpine && !root._x_dataStack) {
2098            Alpine.initTree(root);
2099        }
2100
2101        setupEventListeners(root);
2102        setupOnActionListeners(root);
2103    }
2104
2105    function setupEventListeners(root) {
2106        if (root.__wire_listener_cleanup) return;
2107
2108        const listeners = {};
2109        for (const attr of root.attributes) {
2110            if (!attr.name || !attr.name.startsWith("x-on:")) continue;
2111            listeners[attr.name.slice(5)] = attr.value;
2112        }
2113        if (Object.keys(listeners).length === 0) return;
2114
2115        const handlers = [];
2116        for (const [eventName, expr] of Object.entries(listeners)) {
2117            if (!eventName || !expr) continue;
2118            const binding = parseEventBinding(eventName);
2119            if (!binding) continue;
2120            const fn = function(event) {
2121                if (!matchesEventModifiers(binding.modifiers, event)) return;
2122                if (binding.modifiers.has("prevent")) event.preventDefault();
2123                if (binding.modifiers.has("stop")) event.stopPropagation();
2124                try {
2125                    evaluateWireExpression(root, expr, event);
2126                } catch (e) {
2127                    console.error("[wire] @event handler error:", e);
2128                }
2129            };
2130
2131            const target = binding.modifiers.has("window")
2132                ? window
2133                : binding.modifiers.has("document")
2134                    ? document
2135                    : root;
2136
2137            target.addEventListener(binding.name, fn);
2138            handlers.push([target, binding.name, fn]);
2139        }
2140
2141        root.__wire_listener_cleanup = () => {
2142            for (const [target, eventName, fn] of handlers) {
2143                target.removeEventListener(eventName, fn);
2144            }
2145        };
2146    }
2147
2148    function parseEventBinding(name) {
2149        if (!name) return null;
2150        const parts = name.split('.');
2151        let eventName = parts[0];
2152        if (!eventName) return null;
2153        const modifiers = new Set(parts.slice(1));
2154        if (modifiers.has("camel")) {
2155            eventName = eventName.replace(/-([a-z])/g, (_, c) => c.toUpperCase());
2156        }
2157        return {
2158            name: eventName,
2159            modifiers,
2160        };
2161    }
2162
2163    function matchesEventModifiers(modifiers, event) {
2164        if (modifiers.has("escape") && event.key !== "Escape") return false;
2165        if (modifiers.has("enter") && event.key !== "Enter") return false;
2166        return true;
2167    }
2168
2169    function setupOnActionListeners(root) {
2170        if (root.__wire_on_cleanup) return;
2171
2172        const attr = root.getAttribute("data-wire-on");
2173        if (!attr) return;
2174
2175        let listeners = null;
2176        try {
2177            listeners = JSON.parse(attr);
2178        } catch {
2179            return;
2180        }
2181        if (!listeners || typeof listeners !== "object") return;
2182
2183        const handlers = [];
2184        for (const [eventName, actionName] of Object.entries(listeners)) {
2185            if (!eventName || !actionName) continue;
2186            const fn = function(event) {
2187                const updates = root.__wire_data ? collectDirtyFields(root.__wire_data, getSnapshot(root)) : {};
2188                sendAction(root, "$event", {
2189                    event: eventName,
2190                    detail: event && event.detail !== undefined ? event.detail : null
2191                }, updates);
2192            };
2193            root.addEventListener(eventName, fn);
2194            handlers.push([eventName, fn]);
2195        }
2196
2197        root.__wire_on_cleanup = () => {
2198            for (const [eventName, fn] of handlers) {
2199                root.removeEventListener(eventName, fn);
2200            }
2201        };
2202    }
2203
2204    // Alpine magic: $wire
2205    document.addEventListener("alpine:init", () => {
2206        Alpine.magic("wire", (el) => {
2207            const root = findRoot(el);
2208            if (!root || !root.__wire_proxy) return {};
2209            return root.__wire_proxy;
2210        });
2211    });
2212
2213    // -----------------------------------------------------------------------
2214    // Event delegation for wire: directives
2215    // -----------------------------------------------------------------------
2216
2217    function parseActionCall(action) {
2218        if (!action) return null;
2219        const match = action.match(/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*\((.*)\)\s*$/s);
2220        if (!match) return null;
2221
2222        const name = match[1];
2223        const argsSource = match[2].trim();
2224        if (!argsSource) return { name, args: [] };
2225
2226        try {
2227            const args = new Function(`return [${argsSource}]`)();
2228            return Array.isArray(args) ? { name, args } : null;
2229        } catch (_) {
2230            return null;
2231        }
2232    }
2233
2234    // wire:click
2235    document.addEventListener("click", function(e) {
2236        const el = e.target.closest("[wire\\:click]");
2237        if (!el) return;
2238        e.preventDefault();
2239        const action = el.getAttribute("wire:click");
2240        const root = findRoot(el);
2241        if (!root) return;
2242
2243        const updates = root.__wire_data ? collectDirtyFields(root.__wire_data, getSnapshot(root)) : {};
2244
2245        if (action === "$refresh") {
2246            sendAction(root, "$refresh", {}, updates);
2247            return;
2248        }
2249
2250        if (action && action.trim().startsWith("$")) {
2251            try {
2252                evaluateWireExpression(root, action, e);
2253            } catch (err) {
2254                console.error("[wire] wire:click expression error:", err);
2255            }
2256            return;
2257        }
2258
2259        const parsedCall = parseActionCall(action);
2260        if (parsedCall) {
2261            sendAction(root, parsedCall.name, parsedCall.args.length ? { args: parsedCall.args } : {}, updates);
2262            return;
2263        }
2264
2265        sendAction(root, action, {}, updates);
2266    });
2267
2268    // wire:submit / wire:submit.prevent
2269    document.addEventListener("submit", function(e) {
2270        const form = e.target.closest("[wire\\:submit\\.prevent]") || e.target.closest("[wire\\:submit]");
2271        if (!form) return;
2272        e.preventDefault();
2273        const action = form.getAttribute("wire:submit.prevent") || form.getAttribute("wire:submit");
2274        const root = findRoot(form);
2275        if (!root) return;
2276
2277        const formData = new FormData(form);
2278        const payload = {};
2279        for (const [key, value] of formData.entries()) {
2280            payload[key] = value;
2281        }
2282        const updates = root.__wire_data ? collectDirtyFields(root.__wire_data, getSnapshot(root)) : {};
2283        sendAction(root, action, payload, updates);
2284    });
2285
2286    // wire:model — two-way binding on input/change
2287    function handleModel(e) {
2288        const el = e.target;
2289        const prop = el.getAttribute("wire:model") ||
2290                     el.getAttribute("wire:model.live") ||
2291                     el.getAttribute("wire:model.defer");
2292        if (!prop) return;
2293        const root = findRoot(el);
2294        if (!root) return;
2295
2296        const value = el.type === "checkbox" ? el.checked :
2297                      el.type === "select-multiple" ? [...el.selectedOptions].map(o => o.value) :
2298                      el.value;
2299
2300        // Update local state
2301        if (root.__wire_data) root.__wire_data[prop] = value;
2302        const snap = getSnapshot(root);
2303        snap[prop] = value;
2304        setSnapshot(root, snap);
2305
2306        // If this field is a #[url] field, update URL immediately on client side
2307        const urlFields = getUrlFields(root);
2308        if (urlFields) {
2309            const matchingField = urlFields.find(f => f.field_name === prop);
2310            if (matchingField) {
2311                const urlParams = {};
2312                urlParams[matchingField.query_name] = value;
2313                // Also include other url fields from current snapshot
2314                const currentSnap = getSnapshot(root);
2315                for (const f of urlFields) {
2316                    if (f.field_name !== prop) {
2317                        urlParams[f.query_name] = currentSnap[f.field_name];
2318                    }
2319                }
2320                syncUrlParams(root, urlParams);
2321            }
2322        }
2323
2324        // wire:model.live — sync to server immediately (debounced)
2325        if (el.hasAttribute("wire:model.live")) {
2326            clearTimeout(root.__wire_debounce);
2327            root.__wire_debounce = setTimeout(() => {
2328                const updates = {};
2329                updates[prop] = value;
2330                sendAction(root, "$refresh", {}, updates);
2331            }, 150);
2332        }
2333    }
2334    document.addEventListener("input", handleModel);
2335    document.addEventListener("change", handleModel);
2336
2337    // wire:init — call action when component first appears
2338    function processInit(el) {
2339        if (el.__wire_init_done) return;
2340        el.__wire_init_done = true;
2341        const action = el.getAttribute("wire:init");
2342        const root = findRoot(el);
2343        if (root && action) sendAction(root, action, {}, {});
2344    }
2345
2346    // -----------------------------------------------------------------------
2347    // wire:poll — periodic refresh (stored on root, not on elements)
2348    // -----------------------------------------------------------------------
2349
2350    function setupPolling(scope) {
2351        const container = scope || document;
2352
2353        // Match wire:poll, wire:poll.2s, wire:poll.500ms etc.
2354        container.querySelectorAll("[wire\\:poll], [wire\\:poll\\.2s], [wire\\:poll\\.1s], [wire\\:poll\\.3s], [wire\\:poll\\.5s], [wire\\:poll\\.10s]").forEach(el => {
2355            const root = findRoot(el);
2356            if (!root) return;
2357
2358            let interval = 2000;
2359            let action = "$refresh";
2360
2361            // Check for wire:poll.Xs / wire:poll.Xms modifiers
2362            for (const attr of el.attributes) {
2363                const m = attr.name.match(/^wire:poll\.(\d+)(ms|s)?$/);
2364                if (m) {
2365                    interval = parseInt(m[1]) * (m[2] === "s" || !m[2] ? 1000 : 1);
2366                    action = attr.value || "$refresh";
2367                    break;
2368                }
2369            }
2370
2371            // Fallback: wire:poll="value"
2372            if (el.hasAttribute("wire:poll")) {
2373                const attr = el.getAttribute("wire:poll");
2374                if (attr) {
2375                    const msMatch = attr.match(/^(\d+)(ms|s)?$/);
2376                    if (msMatch) {
2377                        interval = parseInt(msMatch[1]) * (msMatch[2] === "s" ? 1000 : 1);
2378                    } else {
2379                        action = attr;
2380                    }
2381                }
2382            }
2383
2384            // Store on root so it survives morphs
2385            const key = "poll_" + interval + "_" + action;
2386            if (!root.__wire_polls) root.__wire_polls = {};
2387            if (root.__wire_polls[key]) return;
2388
2389            root.__wire_polls[key] = setInterval(() => {
2390                if (!document.contains(root)) {
2391                    clearInterval(root.__wire_polls[key]);
2392                    delete root.__wire_polls[key];
2393                    return;
2394                }
2395                sendAction(root, action, {}, {});
2396            }, interval);
2397        });
2398    }
2399
2400    // -----------------------------------------------------------------------
2401    // wire:navigate — SPA-like page transitions
2402    // -----------------------------------------------------------------------
2403
2404    // Clear all active polls (called before wire:navigate page transitions)
2405    function clearAllPolls() {
2406        document.querySelectorAll("[data-wire-component]").forEach(root => {
2407            if (root.__wire_polls) {
2408                for (const key of Object.keys(root.__wire_polls)) {
2409                    clearInterval(root.__wire_polls[key]);
2410                }
2411                root.__wire_polls = {};
2412            }
2413            if (root.__wire_listener_cleanup) {
2414                try { root.__wire_listener_cleanup(); } catch {}
2415                root.__wire_listener_cleanup = null;
2416            }
2417            if (root.__wire_on_cleanup) {
2418                try { root.__wire_on_cleanup(); } catch {}
2419                root.__wire_on_cleanup = null;
2420            }
2421        });
2422    }
2423
2424    const pageCache = new Map();
2425
2426    async function navigateTo(url, pushState) {
2427        navVersion += 1;
2428
2429        // Stop all polling before navigating
2430        clearAllPolls();
2431
2432        // Show a subtle loading indicator
2433        document.body.setAttribute("data-wire-navigating", "");
2434
2435        try {
2436            let html = pageCache.get(url);
2437            if (!html) {
2438                const res = await fetch(url, {
2439                    credentials: "same-origin",
2440                    headers: { "X-Wire-Navigate": "true" }
2441                });
2442                if (!res.ok) { window.location.href = url; return; }
2443                html = await res.text();
2444            }
2445            pageCache.delete(url);
2446
2447            // Parse the new page
2448            const parser = new DOMParser();
2449            const doc = parser.parseFromString(html, "text/html");
2450
2451            // Update title
2452            const newTitle = doc.querySelector("title");
2453            if (newTitle) document.title = newTitle.textContent;
2454
2455            // Replace body content for navigation to avoid cross-page morph artifacts.
2456            // Keep the currently loaded runtime script; drop scripts from fetched HTML.
2457            doc.body.querySelectorAll("script").forEach((node) => node.remove());
2458            document.body.replaceWith(doc.body);
2459
2460            // Push URL
2461            if (pushState !== false) {
2462                history.pushState({}, "", url);
2463            }
2464
2465            // Reset and re-bootstrap wire components on the new page.
2466            // morphdom may reuse existing DOM nodes, so we must clear the
2467            // initialized flag so initComponent re-reads the new snapshot,
2468            // URL field metadata, and defaults from the morphed attributes.
2469            document.querySelectorAll("[data-wire-component]").forEach(root => {
2470                root.__wire_initialized = false;
2471                root.__wire_url_fields = null;
2472                root.__wire_url_defaults = null;
2473            });
2474            bootstrap();
2475
2476            // Update wire:navigate current indicators
2477            updateCurrentLinks();
2478
2479        } finally {
2480            document.body.removeAttribute("data-wire-navigating");
2481        }
2482    }
2483
2484    // Prefetch cache for wire:navigate.hover
2485    function prefetch(url) {
2486        if (pageCache.has(url)) return;
2487        fetch(url, {
2488            credentials: "same-origin",
2489            headers: { "X-Wire-Navigate": "true" }
2490        })
2491            .then(res => res.ok ? res.text() : null)
2492            .then(html => { if (html) pageCache.set(url, html); })
2493            .catch(() => {});
2494    }
2495
2496    // Click handler for wire:navigate links
2497    document.addEventListener("click", function(e) {
2498        const link = e.target.closest("a[wire\\:navigate], a[wire\\:navigate\\.hover]");
2499        if (!link) return;
2500        const href = link.getAttribute("href");
2501        if (!href || href.startsWith("#") || href.startsWith("javascript:")) return;
2502        // Only handle same-origin
2503        try {
2504            const url = new URL(href, window.location.origin);
2505            if (url.origin !== window.location.origin) return;
2506        } catch { return; }
2507        e.preventDefault();
2508        navigateTo(href);
2509    });
2510
2511    // Hover prefetch for wire:navigate.hover
2512    document.addEventListener("mouseover", function(e) {
2513        const link = e.target.closest("a[wire\\:navigate\\.hover]");
2514        if (!link) return;
2515        const href = link.getAttribute("href");
2516        if (href) {
2517            try {
2518                const url = new URL(href, window.location.origin);
2519                if (url.origin === window.location.origin) prefetch(href);
2520            } catch {}
2521        }
2522    });
2523
2524    // Handle browser back/forward
2525    window.addEventListener("popstate", function() {
2526        navigateTo(window.location.href, false);
2527    });
2528
2529    // Mark current page links with data-current
2530    function updateCurrentLinks() {
2531        const path = window.location.pathname;
2532        document.querySelectorAll("a[wire\\:navigate], a[wire\\:navigate\\.hover]").forEach(a => {
2533            const href = a.getAttribute("href");
2534            if (href === path || (href === "/" && path === "/")) {
2535                a.setAttribute("data-current", "");
2536            } else {
2537                a.removeAttribute("data-current");
2538            }
2539        });
2540    }
2541
2542    // -----------------------------------------------------------------------
2543    // Bootstrap
2544    // -----------------------------------------------------------------------
2545
2546    function bootstrap() {
2547        document.querySelectorAll("[data-wire-component]").forEach(initComponent);
2548        document.querySelectorAll("[wire\\:init]").forEach(processInit);
2549        setupPolling();
2550        updateCurrentLinks();
2551    }
2552
2553    if (document.readyState === "loading") {
2554        document.addEventListener("DOMContentLoaded", bootstrap);
2555    } else {
2556        bootstrap();
2557    }
2558
2559    // Watch for dynamically added components
2560    new MutationObserver((mutations) => {
2561        for (const m of mutations) {
2562            for (const node of m.addedNodes) {
2563                if (node.nodeType !== 1) continue;
2564                if (node.hasAttribute && node.hasAttribute("data-wire-component")) initComponent(node);
2565                if (node.querySelectorAll) {
2566                    node.querySelectorAll("[data-wire-component]").forEach(initComponent);
2567                    node.querySelectorAll("[wire\\:init]").forEach(processInit);
2568                }
2569            }
2570        }
2571    }).observe(document.body, { childNodes: true, subtree: true });
2572
2573    console.log("[axum-wire] Runtime loaded.");
2574})();
2575</script>
2576"##;
2577
2578// ---------------------------------------------------------------------------
2579// Layouts
2580// ---------------------------------------------------------------------------
2581
2582/// The JavaScript runtime (`<script>` tags) that powers wire: directives.
2583/// Place in `<body>` just before `</body>`, or use `@wireScripts` in file layouts.
2584pub const WIRE_SCRIPTS: &str = WIRE_JS;
2585
2586/// CSS styles for wire components (loading states, etc.).
2587/// Place in `<head>`, or use `@wireStyles` in file layouts.
2588pub const WIRE_STYLES: &str = r#"<style>
2589[wire\:loading] { display: none; }
2590[data-wire-loading] [wire\:loading] { display: inline; }
2591</style>"#;
2592
2593type RouterLayer = Arc<dyn Fn(Router) -> Router + Send + Sync>;
2594
2595/// Context passed to layout functions when rendering a page.
2596pub struct LayoutContext {
2597    /// The component's wire name (e.g. `"counter"`).
2598    pub component: String,
2599    /// The rendered component HTML (wrapped in the wire root div).
2600    pub body: String,
2601    /// **Deprecated**: use `wire_scripts()` instead. The raw JS runtime string.
2602    pub wire_js: &'static str,
2603}
2604
2605impl LayoutContext {
2606    /// Returns the `<script>` tags for the wire JS runtime (morphdom + Alpine + $wire proxy).
2607    /// Place at the end of `<body>`.
2608    pub fn wire_scripts(&self) -> &'static str {
2609        WIRE_SCRIPTS
2610    }
2611
2612    /// Returns the `<style>` tag for wire CSS (loading states, etc.).
2613    /// Place in `<head>`.
2614    pub fn wire_styles(&self) -> &'static str {
2615        WIRE_STYLES
2616    }
2617}
2618
2619pub type LayoutFn = Arc<dyn Fn(LayoutContext) -> String + Send + Sync>;
2620
2621/// Built-in default layout — a minimal HTML page.
2622pub fn default_layout(ctx: LayoutContext) -> String {
2623    format!(
2624        r#"<!DOCTYPE html>
2625<html lang="en">
2626<head>
2627    <meta charset="UTF-8">
2628    <meta name="viewport" content="width=device-width, initial-scale=1.0">
2629    <title>{title}</title>
2630    {styles}
2631    <style>
2632        * {{ margin: 0; padding: 0; box-sizing: border-box; }}
2633        body {{ font-family: system-ui, -apple-system, sans-serif; background: #f5f5f5; color: #333; }}
2634    </style>
2635</head>
2636<body>
2637    {body}
2638    {scripts}
2639</body>
2640</html>"#,
2641        title = ctx.component,
2642        body = ctx.body,
2643        styles = ctx.wire_styles(),
2644        scripts = ctx.wire_scripts(),
2645    )
2646}
2647
2648/// Create a layout function from an HTML template string.
2649///
2650/// The template supports these placeholders:
2651/// - `@wireBody` — replaced with the rendered component HTML
2652/// - `@wireScripts` — replaced with the wire JS runtime `<script>` tags
2653/// - `@wireStyles` — replaced with the wire CSS `<style>` tag
2654/// - `@wireTitle` — replaced with the component's wire name
2655///
2656/// ```ignore
2657/// let tpl = std::fs::read_to_string("layouts/auth.html").unwrap();
2658/// WireApp::new()
2659///     .layout("auth", layout_from_str(&tpl))
2660/// ```
2661pub fn layout_from_str(template: &str) -> impl Fn(LayoutContext) -> String + Send + Sync + 'static {
2662    let tpl = template.to_string();
2663    move |ctx: LayoutContext| {
2664        tpl.replace("@wireBody", &ctx.body)
2665            .replace("@wireScripts", ctx.wire_scripts())
2666            .replace("@wireStyles", ctx.wire_styles())
2667            .replace("@wireTitle", &ctx.component)
2668    }
2669}
2670
2671// ---------------------------------------------------------------------------
2672// WireApp builder
2673// ---------------------------------------------------------------------------
2674
2675// ---------------------------------------------------------------------------
2676// Type-erased state storage
2677// ---------------------------------------------------------------------------
2678
2679/// Trait object for injecting type-erased state into request extensions.
2680trait StateInjector: Send + Sync {
2681    fn inject(&self, extensions: &mut axum::http::Extensions);
2682}
2683
2684/// Concrete implementation for a specific state type.
2685struct TypedStateInjector<T: Clone + Send + Sync + 'static> {
2686    value: T,
2687}
2688
2689impl<T: Clone + Send + Sync + 'static> StateInjector for TypedStateInjector<T> {
2690    fn inject(&self, extensions: &mut axum::http::Extensions) {
2691        extensions.insert(self.value.clone());
2692    }
2693}
2694
2695pub struct WireApp {
2696    router: Router,
2697    layouts: Arc<std::collections::HashMap<String, LayoutFn>>,
2698    states: Arc<Vec<Arc<dyn StateInjector>>>,
2699    layers: Vec<RouterLayer>,
2700    route_layer_map: Arc<std::collections::HashMap<String, Vec<usize>>>,
2701}
2702
2703impl WireApp {
2704    pub fn new() -> Self {
2705        let mut layouts = std::collections::HashMap::new();
2706        layouts.insert("default".to_string(), Arc::new(default_layout) as LayoutFn);
2707        Self {
2708            router: Router::new(),
2709            layouts: Arc::new(layouts),
2710            states: Arc::new(Vec::new()),
2711            layers: Vec::new(),
2712            route_layer_map: Arc::new(std::collections::HashMap::new()),
2713        }
2714    }
2715
2716    /// Register a named layout function.
2717    ///
2718    /// The name `"default"` is special — it's used when no `#[layout]` attribute
2719    /// is set on the component and no per-route override is given.
2720    ///
2721    /// ```ignore
2722    /// WireApp::new()
2723    ///     .layout("default", |ctx| { ... })
2724    ///     .layout("auth", auth_layout)
2725    ///     .layout("admin", admin_layout)
2726    /// ```
2727    pub fn layout<F>(mut self, name: &str, f: F) -> Self
2728    where
2729        F: Fn(LayoutContext) -> String + Send + Sync + 'static,
2730    {
2731        Arc::make_mut(&mut self.layouts).insert(name.to_string(), Arc::new(f));
2732        self
2733    }
2734
2735    /// Register a layout from an HTML template string.
2736    ///
2737    /// The template supports these placeholders:
2738    /// - `@wireBody` — the rendered component HTML
2739    /// - `@wireScripts` — the wire JS runtime `<script>` tags
2740    /// - `@wireStyles` — the wire CSS `<style>` tag
2741    /// - `@wireTitle` — the component's wire name
2742    ///
2743    /// ```ignore
2744    /// WireApp::new()
2745    ///     .layout_str("auth", include_str!("layouts/auth.html"))
2746    /// ```
2747    pub fn layout_str(self, name: &str, template: &str) -> Self {
2748        self.layout(name, layout_from_str(template))
2749    }
2750
2751    /// Register a layout from an HTML file path (read at startup).
2752    ///
2753    /// The file supports the same placeholders as `layout_str`.
2754    ///
2755    /// ```ignore
2756    /// WireApp::new()
2757    ///     .layout_file("auth", "layouts/auth.html")
2758    /// ```
2759    ///
2760    /// # Panics
2761    /// Panics if the file cannot be read.
2762    pub fn layout_file(self, name: &str, path: &str) -> Self {
2763        let template = std::fs::read_to_string(path)
2764            .unwrap_or_else(|e| panic!("Failed to read layout file {path:?}: {e}"));
2765        self.layout_str(name, &template)
2766    }
2767
2768    /// Add shared application state accessible via `ctx.state::<T>()` in components.
2769    ///
2770    /// ```ignore
2771    /// let app = WireApp::new()
2772    ///     .state(db_pool)
2773    ///     .state(redis_client)
2774    ///     .wire("/posts/{postId}", "post-view")
2775    ///     .into_router();
2776    /// ```
2777    pub fn state<T: Clone + Send + Sync + 'static>(mut self, value: T) -> Self {
2778        let states =
2779            Arc::get_mut(&mut self.states).expect("Cannot add state after cloning WireApp");
2780        states.push(Arc::new(TypedStateInjector { value }));
2781        self
2782    }
2783
2784    /// Register a wire component route. Layout is resolved from the component's
2785    /// `#[layout("name")]` attribute, falling back to `"default"`.
2786    pub fn wire(self, path: &str, component_name: &str) -> Self {
2787        self.wire_with_layout(path, component_name, None)
2788    }
2789
2790    /// Register a wire component route with an explicit per-route layout function.
2791    /// This overrides any `#[layout]` attribute on the component.
2792    pub fn wire_with<F>(self, path: &str, component_name: &str, layout_fn: F) -> Self
2793    where
2794        F: Fn(LayoutContext) -> String + Send + Sync + 'static,
2795    {
2796        self.wire_with_layout(path, component_name, Some(Arc::new(layout_fn)))
2797    }
2798
2799    fn wire_with_layout(
2800        mut self,
2801        path: &str,
2802        component_name: &str,
2803        explicit_layout: Option<LayoutFn>,
2804    ) -> Self {
2805        let name = component_name.to_string();
2806        let layouts = self.layouts.clone();
2807
2808        Arc::make_mut(&mut self.route_layer_map)
2809            .entry(path.to_string())
2810            .or_default();
2811        let route_layers = self.route_layer_map.get(path).cloned().unwrap_or_default();
2812
2813        let handler = move |request: Request| {
2814            let name = name.clone();
2815            let explicit_layout = explicit_layout.clone();
2816            let layouts = layouts.clone();
2817            async move {
2818                let (mut parts, _body) = request.into_parts();
2819
2820                parts
2821                    .extensions
2822                    .insert(RouteLayerIndices(route_layers.clone()));
2823
2824                // Extract query params for #[url] field support
2825                let query_params = parse_query_string(parts.uri.query());
2826
2827                let wire_ctx = WireContext::new(parts);
2828
2829                match with_wire_ctx(
2830                    wire_ctx.clone(),
2831                    mount_component_with_query(&name, &query_params, &wire_ctx),
2832                )
2833                .await
2834                {
2835                    Ok(component_html) => {
2836                        // Resolve layout: explicit override > component #[layout] > "default"
2837                        let layout = resolve_layout(&name, explicit_layout.as_ref(), &layouts);
2838
2839                        let layout_ctx = LayoutContext {
2840                            component: name,
2841                            body: component_html,
2842                            wire_js: WIRE_JS,
2843                        };
2844
2845                        // Render layout with the same request context so nested
2846                        // components inside the layout (e.g. <Navbar />) can
2847                        // access ctx.state()/ctx.extension().
2848                        let html =
2849                            with_wire_ctx(wire_ctx.clone(), async { layout(layout_ctx) }).await;
2850                        Html(html).into_response()
2851                    }
2852                    Err(e) => (
2853                        StatusCode::INTERNAL_SERVER_ERROR,
2854                        format!("Failed to mount component: {e}"),
2855                    )
2856                        .into_response(),
2857                }
2858            }
2859        };
2860
2861        let route_router = Router::new().route(path, get(handler));
2862
2863        self.router = self.router.merge(route_router);
2864        self
2865    }
2866
2867    /// Apply a Tower layer/middleware to wire page routes.
2868    ///
2869    /// Like `axum::Router::layer`, this applies to the routes that currently
2870    /// exist in the builder. Routes registered later are unaffected.
2871    ///
2872    /// `/_wire/update` is intentionally not layered by Axum. Instead, during
2873    /// an AJAX update, axum-wire replays the layers associated with the
2874    /// original mounted route (tracked via `__wire_ctx` in the snapshot).
2875    ///
2876    /// To scope middleware to a subset of routes, use `group(...)`.
2877    ///
2878    /// ```ignore
2879    /// use tower_http::cors::CorsLayer;
2880    /// use tower_http::compression::CompressionLayer;
2881    ///
2882    /// WireApp::new()
2883    ///     .wire("/", "counter")
2884    ///     .layer(CorsLayer::permissive())
2885    ///     .layer(CompressionLayer::new())
2886    ///     .into_router();
2887    /// ```
2888    pub fn layer<L>(mut self, layer: L) -> Self
2889    where
2890        L: tower::Layer<axum::routing::Route> + Clone + Send + Sync + 'static,
2891        L::Service: tower::Service<Request, Error = std::convert::Infallible>
2892            + Clone
2893            + Send
2894            + Sync
2895            + 'static,
2896        <L::Service as tower::Service<Request>>::Response: IntoResponse + 'static,
2897        <L::Service as tower::Service<Request>>::Future: Send + 'static,
2898    {
2899        let idx = self.layers.len();
2900        let apply_layer: RouterLayer = Arc::new(move |router: Router| router.layer(layer.clone()));
2901        self.router = apply_layer(self.router);
2902        self.layers.push(apply_layer);
2903
2904        for indices in Arc::make_mut(&mut self.route_layer_map).values_mut() {
2905            indices.push(idx);
2906        }
2907
2908        self
2909    }
2910
2911    /// Build a scoped set of wire routes and layers, then merge them back.
2912    ///
2913    /// This is useful when you want Axum-like layering on just a subset of
2914    /// routes without affecting the rest of the app.
2915    ///
2916    /// ```ignore
2917    /// WireApp::new()
2918    ///     .wire("/", "home")
2919    ///     .group(|app| {
2920    ///         app.wire("/admin", "admin-dashboard")
2921    ///             .wire("/admin/posts", "admin-posts")
2922    ///             .layer(auth_layer)
2923    ///     })
2924    ///     .wire("/about", "about")
2925    /// ```
2926    pub fn group<F>(mut self, f: F) -> Self
2927    where
2928        F: FnOnce(Self) -> Self,
2929    {
2930        let group_app = Self {
2931            router: Router::new(),
2932            layouts: Arc::new(self.layouts.as_ref().clone()),
2933            states: Arc::new(self.states.as_ref().clone()),
2934            layers: self.layers.clone(),
2935            route_layer_map: Arc::new(std::collections::HashMap::new()),
2936        };
2937
2938        let group_app = f(group_app);
2939
2940        self.router = self.router.merge(group_app.router);
2941        self.layouts = group_app.layouts;
2942        self.states = group_app.states;
2943        self.layers = group_app.layers;
2944        Arc::make_mut(&mut self.route_layer_map).extend(group_app.route_layer_map.as_ref().clone());
2945        self
2946    }
2947
2948    pub fn merge(mut self, router: Router) -> Self {
2949        self.router = self.router.merge(router);
2950        self
2951    }
2952
2953    pub fn into_router<S>(self) -> Router<S>
2954    where
2955        S: Clone + Send + Sync + 'static,
2956    {
2957        // Auto-connect to dioxus devtools when running under `dx serve --hotpatch`
2958        connect_devtools();
2959
2960        let states_for_pages = self.states.clone();
2961        let page_state_layer = move |request: Request, next: middleware::Next| {
2962            let states = states_for_pages.clone();
2963            async move {
2964                let request = apply_states_to_request(request, &states);
2965                next.run(request).await
2966            }
2967        };
2968
2969        let page_router = self.router.layer(middleware::from_fn(page_state_layer));
2970
2971        let states = self.states.clone();
2972        let layers = self.layers.clone();
2973        let route_layer_map = self.route_layer_map.clone();
2974        let update_handler = move |request: Request| {
2975            let states = states.clone();
2976            let layers = layers.clone();
2977            let route_layer_map = route_layer_map.clone();
2978            async move { dispatch_wire_update(request, states, layers, route_layer_map).await }
2979        };
2980
2981        page_router
2982            .route("/_wire/update", post(update_handler))
2983            .with_state::<S>(())
2984    }
2985}
2986
2987impl Default for WireApp {
2988    fn default() -> Self {
2989        Self::new()
2990    }
2991}
2992
2993// ---------------------------------------------------------------------------
2994// Router extension (convenience)
2995// ---------------------------------------------------------------------------
2996
2997pub trait WireRouter {
2998    fn wire(self, path: &str, component_name: &str) -> Self;
2999    fn wire_routes(self) -> Self;
3000}
3001
3002impl WireRouter for Router {
3003    fn wire(self, path: &str, component_name: &str) -> Self {
3004        let name = component_name.to_string();
3005
3006        let handler = move |request: Request| {
3007            let name = name.clone();
3008            async move {
3009                let (parts, _body) = request.into_parts();
3010
3011                // Extract query params for #[url] field support
3012                let query_params = parse_query_string(parts.uri.query());
3013
3014                let wire_ctx = WireContext::new(parts);
3015
3016                match with_wire_ctx(
3017                    wire_ctx.clone(),
3018                    mount_component_with_query(&name, &query_params, &wire_ctx),
3019                )
3020                .await
3021                {
3022                    Ok(component_html) => {
3023                        let empty_registry = std::collections::HashMap::new();
3024                        let layout = resolve_layout(&name, None, &empty_registry);
3025                        let layout_ctx = LayoutContext {
3026                            component: name,
3027                            body: component_html,
3028                            wire_js: WIRE_JS,
3029                        };
3030                        Html(layout(layout_ctx)).into_response()
3031                    }
3032                    Err(e) => (
3033                        StatusCode::INTERNAL_SERVER_ERROR,
3034                        format!("Failed to mount component: {e}"),
3035                    )
3036                        .into_response(),
3037                }
3038            }
3039        };
3040
3041        self.route(path, get(handler))
3042    }
3043
3044    fn wire_routes(self) -> Self {
3045        connect_devtools();
3046        self.route("/_wire/update", post(handle_wire_update))
3047    }
3048}