axum-wire 0.0.1

Server-driven reactive UI components for Axum — like Laravel Livewire, but for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
//! # axum-wire
//!
//! Laravel Livewire-like server-driven reactive UI components for Axum.
//!
//! Components are Rust structs whose state lives on the server. User interactions
//! (clicks, input changes, etc.) trigger AJAX requests that update state server-side,
//! re-render HTML, and morph the DOM — no full page reload needed.
//!
//! ## How it works
//!
//! 1. A component struct derives `Component` (+ `Serialize`, `Deserialize`, optionally `Default`)
//! 2. The `#[wire_actions]` macro on the impl block registers `render()`, optional `mount()`, and actions
//! 3. On first load, the component is mounted, rendered to HTML, and its state
//!    serialized as a JSON "snapshot" embedded in a `data-wire-snapshot` attribute
//! 4. A small JS runtime intercepts `wire:click`, `wire:submit`, `wire:model` etc.,
//!    sends the snapshot + action name to the server via fetch()
//! 5. The server deserializes the snapshot, calls the action, re-renders, and
//!    returns the new HTML + snapshot
//! 6. The JS runtime uses morphdom to diff and patch the DOM in-place

pub use axum_wire_macros::{Component, html, wire_actions};
pub use futures;
pub use inventory;
pub use serde_json;

pub use subsecond;

/// Connect to the Dioxus devtools for hot-patching.
///
/// In debug builds, this connects to the `dx serve` devserver so subsecond
/// can receive and apply patches. In release builds this is a no-op.
pub fn connect_devtools() {
    #[cfg(debug_assertions)]
    {
        dioxus_devtools::connect_subsecond();
    }
}

use std::pin::Pin;
use std::sync::Arc;

use axum::{
    Router,
    extract::Json,
    http::StatusCode,
    response::{Html, IntoResponse},
    routing::{get, post},
};
use futures::future::BoxFuture;
use serde::{Deserialize, Serialize};

// ---------------------------------------------------------------------------
// Error types
// ---------------------------------------------------------------------------

#[derive(Debug, thiserror::Error)]
pub enum WireError {
    #[error("Unknown component: {0}")]
    UnknownComponent(String),
    #[error("Unknown action: {0}")]
    UnknownAction(String),
    #[error("Deserialization error: {0}")]
    Deserialization(String),
    #[error("Serialization error: {0}")]
    Serialization(String),
}

// ---------------------------------------------------------------------------
// Core trait
// ---------------------------------------------------------------------------

/// Auto-implemented by the derive macro to provide the component's wire name.
pub trait ComponentMeta {
    fn component_name() -> &'static str;
}

// ---------------------------------------------------------------------------
// Component registry (via `inventory`)
// ---------------------------------------------------------------------------

pub struct WireResponse {
    pub html: String,
    pub snapshot: serde_json::Value,
    pub effects: ActionEffects,
}

pub type WireResult = Result<WireResponse, WireError>;

// ---------------------------------------------------------------------------
// Action effects — scoped per call_action invocation via RAII guard
// ---------------------------------------------------------------------------

/// Side-effects queued during an action (JS commands, redirect, skip render).
#[derive(Default)]
pub struct ActionEffects {
    pub js: Vec<String>,
    pub skip_render: bool,
    pub redirect: Option<String>,
    pub redirect_navigate: bool,
}

std::thread_local! {
    static ACTION_EFFECTS: std::cell::RefCell<ActionEffects> = std::cell::RefCell::new(ActionEffects::default());
}

/// RAII guard that scopes action effects to a single `call_action` invocation.
/// Since actions are synchronous (`&mut self`), no interleaving is possible.
pub struct ActionScope;

impl ActionScope {
    pub fn begin() -> Self {
        ACTION_EFFECTS.with(|e| {
            let mut e = e.borrow_mut();
            e.js.clear();
            e.skip_render = false;
            e.redirect = None;
            e.redirect_navigate = false;
        });
        ActionScope
    }

    pub fn finish(self) -> ActionEffects {
        ACTION_EFFECTS.with(|e| {
            let mut e = e.borrow_mut();
            ActionEffects {
                js: e.js.drain(..).collect(),
                skip_render: e.skip_render,
                redirect: e.redirect.take(),
                redirect_navigate: e.redirect_navigate,
            }
        })
    }
}

impl Drop for ActionScope {
    fn drop(&mut self) {
        ACTION_EFFECTS.with(|e| {
            let mut e = e.borrow_mut();
            e.js.clear();
            e.skip_render = false;
            e.redirect = None;
            e.redirect_navigate = false;
        });
    }
}

/// Push a JS command. Called by generated `self.js()`.
pub fn push_js(code: String) {
    ACTION_EFFECTS.with(|e| e.borrow_mut().js.push(code));
}

/// Mark current action to skip rendering. Called by generated `self.skip_render()`.
pub fn set_skip_render() {
    ACTION_EFFECTS.with(|e| e.borrow_mut().skip_render = true);
}

/// Set a redirect URL. Called by generated `self.redirect()`.
pub fn set_redirect(url: String, navigate: bool) {
    ACTION_EFFECTS.with(|e| {
        let mut e = e.borrow_mut();
        e.redirect = Some(url);
        e.redirect_navigate = navigate;
        e.skip_render = true; // redirect implies skip render
    });
}



/// Async-aware function types for the component factory.
///
/// Both sync and async `render`/`mount` are supported — the macro always wraps
/// them into a `BoxFuture` so the runtime is uniformly async.
pub type UpdateFn =
    fn(serde_json::Value, &str, serde_json::Value) -> Pin<Box<dyn std::future::Future<Output = WireResult> + Send + '_>>;
pub type MountFn = fn() -> BoxFuture<'static, WireResult>;
/// Mount with props: receives a JSON object of initial field values.
pub type MountWithPropsFn = fn(serde_json::Value) -> BoxFuture<'static, WireResult>;

pub struct ComponentFactory {
    pub name: &'static str,
    pub update: UpdateFn,
    pub mount: MountFn,
    pub mount_with_props: MountWithPropsFn,
}

impl ComponentFactory {
    pub const fn new(
        name: &'static str,
        update: UpdateFn,
        mount: MountFn,
        mount_with_props: MountWithPropsFn,
    ) -> Self {
        Self { name, update, mount, mount_with_props }
    }
}

inventory::collect!(ComponentFactory);

fn find_factory(name: &str) -> Option<&'static ComponentFactory> {
    inventory::iter::<ComponentFactory>.into_iter().find(|f| f.name == name)
}

// ---------------------------------------------------------------------------
// Axum handlers
// ---------------------------------------------------------------------------

/// Request payload sent from the JS frontend on each interaction.
#[derive(Deserialize)]
struct WireUpdateRequest {
    component: String,
    snapshot: serde_json::Value,
    action: String,
    #[serde(default)]
    payload: serde_json::Value,
    /// Model updates from wire:model — merged into snapshot before action runs.
    #[serde(default)]
    updates: serde_json::Value,
}

/// Response sent back to the JS frontend.
#[derive(Serialize)]
struct WireUpdateResponse {
    html: String,
    snapshot: serde_json::Value,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    js: Vec<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    redirect: Option<String>,
    #[serde(skip_serializing_if = "std::ops::Not::not")]
    redirect_navigate: bool,
}

/// Merge `updates` (from wire:model / $wire property sets) into the snapshot.
fn merge_updates(snapshot: &mut serde_json::Value, updates: &serde_json::Value) {
    if let (Some(snap), Some(upd)) = (snapshot.as_object_mut(), updates.as_object()) {
        for (k, v) in upd {
            snap.insert(k.clone(), v.clone());
        }
    }
}

async fn handle_wire_update(
    Json(req): Json<WireUpdateRequest>,
) -> impl IntoResponse {
    let factory = match find_factory(&req.component) {
        Some(f) => f,
        None => {
            return (
                StatusCode::NOT_FOUND,
                Json(serde_json::json!({ "error": format!("Unknown component: {}", req.component) })),
            )
                .into_response();
        }
    };

    // Merge any wire:model / $wire property updates into the snapshot first
    let mut snapshot = req.snapshot;
    merge_updates(&mut snapshot, &req.updates);

    match (factory.update)(snapshot, &req.action, req.payload).await {
        Ok(resp) => Json(WireUpdateResponse {
            html: resp.html,
            snapshot: resp.snapshot,
            js: resp.effects.js,
            redirect: resp.effects.redirect,
            redirect_navigate: resp.effects.redirect_navigate,
        })
        .into_response(),
        Err(e) => (
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(serde_json::json!({ "error": e.to_string() })),
        )
            .into_response(),
    }
}

// ---------------------------------------------------------------------------
// HTML helpers
// ---------------------------------------------------------------------------

/// Wraps a component's rendered HTML with the wire root element and snapshot data.
pub fn render_component_html(name: &str, html: &str, snapshot: &serde_json::Value) -> String {
    let snapshot_json = serde_json::to_string(snapshot).unwrap_or_default();
    let escaped = snapshot_json
        .replace('&', "&amp;")
        .replace('"', "&quot;")
        .replace('<', "&lt;")
        .replace('>', "&gt;");
    format!(
        r#"<div data-wire-component="{name}" data-wire-snapshot="{escaped}">{html}</div>"#
    )
}

/// Mount a component by name and return the full HTML (including wrapper).
pub async fn mount_component(name: &str) -> Result<String, WireError> {
    let factory = find_factory(name).ok_or_else(|| WireError::UnknownComponent(name.to_string()))?;
    let resp = (factory.mount)().await?;
    Ok(render_component_html(name, &resp.html, &resp.snapshot))
}

/// Synchronous mount — used by `html!` macro for sub-components where we're
/// already inside a sync `render()` context. Uses `futures::executor::block_on`.
pub fn mount_component_sync(name: &str) -> Result<String, WireError> {
    let factory = find_factory(name).ok_or_else(|| WireError::UnknownComponent(name.to_string()))?;
    let resp = futures::executor::block_on((factory.mount)())?;
    Ok(render_component_html(name, &resp.html, &resp.snapshot))
}

/// Mount a component with initial prop values (async).
pub async fn mount_component_with_props(
    name: &str,
    props: serde_json::Value,
) -> Result<String, WireError> {
    let factory = find_factory(name).ok_or_else(|| WireError::UnknownComponent(name.to_string()))?;
    let resp = (factory.mount_with_props)(props).await?;
    Ok(render_component_html(name, &resp.html, &resp.snapshot))
}

/// Synchronous mount with props — used by `html!` macro for `<Counter count=42 />`.
pub fn mount_component_with_props_sync(
    name: &str,
    props: serde_json::Value,
) -> Result<String, WireError> {
    let factory = find_factory(name).ok_or_else(|| WireError::UnknownComponent(name.to_string()))?;
    let resp = futures::executor::block_on((factory.mount_with_props)(props))?;
    Ok(render_component_html(name, &resp.html, &resp.snapshot))
}

// ---------------------------------------------------------------------------
// JavaScript runtime (embedded)
// ---------------------------------------------------------------------------

/// The JS runtime that powers wire: directives on the client.
/// Ships Alpine.js + morphdom + the $wire proxy.
pub const WIRE_JS: &str = r##"
<script src="https://unpkg.com/morphdom@2.7.4/dist/morphdom-umd.min.js"></script>
<script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3/dist/cdn.min.js"></script>
<script>
(function() {
    "use strict";

    const WIRE_ENDPOINT = "/_wire/update";

    // -----------------------------------------------------------------------
    // Helpers
    // -----------------------------------------------------------------------

    function findRoot(el) {
        return el.closest("[data-wire-component]");
    }

    function getSnapshot(root) {
        return JSON.parse(root.dataset.wireSnapshot);
    }

    function setSnapshot(root, snap) {
        root.dataset.wireSnapshot = JSON.stringify(snap);
    }

    // Track in-flight requests per component to avoid races
    const pending = new WeakMap();

    // -----------------------------------------------------------------------
    // Core: send an action to the server and morph the result
    // -----------------------------------------------------------------------

    async function sendAction(root, action, payload, updates) {
        const component = root.dataset.wireComponent;
        const snapshot = getSnapshot(root);

        // Loading state
        root.setAttribute("data-wire-loading", "");

        try {
            const res = await fetch(WIRE_ENDPOINT, {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({
                    component,
                    snapshot,
                    action: action || "$refresh",
                    payload: payload || {},
                    updates: updates || {},
                }),
            });

            if (!res.ok) {
                console.error("[wire] Update failed:", res.status);
                return;
            }

            const data = await res.json();

            // Handle redirect
            if (data.redirect) {
                if (data.redirect_navigate && typeof navigateTo === "function") {
                    navigateTo(data.redirect);
                } else {
                    window.location.href = data.redirect;
                }
                return;
            }

            // Update snapshot on the root
            setSnapshot(root, data.snapshot);

            // Skip render — only snapshot was updated, no HTML to morph
            if (!data.html) {
                updateWireData(root, data.snapshot);
                // Still execute JS commands
                if (data.js && data.js.length) {
                    const $wire = root.__wire_proxy || {};
                    for (const code of data.js) {
                        try { new Function("$wire", code).call(root, $wire); } catch(e) { console.error("[wire] js() error:", e); }
                    }
                }
                return;
            }

            // Build a temporary wrapper to morph from
            const fresh = root.cloneNode(false);
            fresh.innerHTML = data.html;

            // Remember which element has focus + cursor position
            const focused = document.activeElement;
            const focusedWireModel = focused && (
                focused.getAttribute("wire:model") ||
                focused.getAttribute("wire:model.live") ||
                focused.getAttribute("wire:model.defer")
            );
            const selStart = focused && focused.selectionStart;
            const selEnd = focused && focused.selectionEnd;

            // Morph children only — preserves the root element (and its snapshot attrs)
            morphdom(root, fresh, {
                childrenOnly: true,
                getNodeKey(node) {
                    if (node.getAttribute) {
                        return node.getAttribute("wire:key") || node.getAttribute("wire:id") || node.id || null;
                    }
                    return null;
                },
                onBeforeElUpdated(fromEl, toEl) {
                    // wire:ignore — skip this entire subtree
                    if (fromEl.hasAttribute && fromEl.hasAttribute("wire:ignore")) {
                        return false;
                    }
                    // Preserve focused input value to prevent caret jump
                    if (fromEl === focused && focusedWireModel) {
                        toEl.value = fromEl.value;
                    }
                    // Preserve Alpine state
                    if (fromEl._x_dataStack) {
                        window.Alpine && Alpine.clone(fromEl, toEl);
                    }
                    return true;
                },
            });

            // Restore focus if it was on a wire:model input
            if (focusedWireModel) {
                const restored = root.querySelector(
                    "[wire\\:model='" + focusedWireModel + "']," +
                    "[wire\\:model\\.live='" + focusedWireModel + "']," +
                    "[wire\\:model\\.defer='" + focusedWireModel + "']"
                );
                if (restored && restored !== document.activeElement) {
                    restored.focus();
                    if (selStart !== null && restored.setSelectionRange) {
                        try { restored.setSelectionRange(selStart, selEnd); } catch(e) {}
                    }
                }
            }

            // Update $wire reactive data for Alpine
            updateWireData(root, data.snapshot);

            // Execute server-dispatched JS commands with $wire in scope
            if (data.js && data.js.length) {
                const $wire = root.__wire_proxy || {};
                for (const code of data.js) {
                    try {
                        new Function("$wire", code).call(root, $wire);
                    } catch(e) {
                        console.error("[wire] js() error:", e);
                    }
                }
            }

            // Re-setup polling for any new wire:poll elements
            setupPolling(root);

        } finally {
            root.removeAttribute("data-wire-loading");
        }
    }

    // -----------------------------------------------------------------------
    // $wire proxy — available in Alpine expressions via x-data
    // -----------------------------------------------------------------------

    function createWireProxy(root) {
        const snapshot = getSnapshot(root);
        const reactiveData = Alpine.reactive ? Alpine.reactive({ ...snapshot }) : { ...snapshot };

        const proxy = new Proxy(reactiveData, {
            get(target, prop) {
                if (prop === "$refresh") return () => sendAction(root, "$refresh", {}, {});
                if (prop === "$set") return (key, value) => {
                    target[key] = value;
                    const updates = {};
                    updates[key] = value;
                    sendAction(root, "$refresh", {}, updates);
                };
                if (prop === "$snapshot") return getSnapshot(root);
                if (prop === "$root") return root;
                if (prop in target) return target[prop];

                // Assume it's a method call
                return (...args) => {
                    const updates = collectDirtyFields(target, getSnapshot(root));
                    sendAction(root, prop, args.length ? { args } : {}, updates);
                };
            },
            set(target, prop, value) {
                target[prop] = value;
                const snap = getSnapshot(root);
                snap[prop] = value;
                setSnapshot(root, snap);
                return true;
            }
        });

        return { proxy, reactiveData };
    }

    function collectDirtyFields(current, original) {
        const updates = {};
        for (const key of Object.keys(current)) {
            if (JSON.stringify(current[key]) !== JSON.stringify(original[key])) {
                updates[key] = current[key];
            }
        }
        return updates;
    }

    function updateWireData(root, snapshot) {
        if (root.__wire_data) {
            for (const [k, v] of Object.entries(snapshot)) {
                root.__wire_data[k] = v;
            }
        }
    }

    // -----------------------------------------------------------------------
    // Initialize wire components with Alpine x-data
    // -----------------------------------------------------------------------

    function initComponent(root) {
        if (root.__wire_initialized) return;
        root.__wire_initialized = true;

        const { proxy, reactiveData } = createWireProxy(root);
        root.__wire_data = reactiveData;
        root.__wire_proxy = proxy;

        if (!root.hasAttribute("x-data")) {
            root.setAttribute("x-data", "");
        }
    }

    // Alpine magic: $wire
    document.addEventListener("alpine:init", () => {
        Alpine.magic("wire", (el) => {
            const root = findRoot(el);
            if (!root || !root.__wire_proxy) return {};
            return root.__wire_proxy;
        });
    });

    // -----------------------------------------------------------------------
    // Event delegation for wire: directives
    // -----------------------------------------------------------------------

    // wire:click
    document.addEventListener("click", function(e) {
        const el = e.target.closest("[wire\\:click]");
        if (!el) return;
        e.preventDefault();
        const action = el.getAttribute("wire:click");
        const root = findRoot(el);
        if (!root) return;
        const updates = root.__wire_data ? collectDirtyFields(root.__wire_data, getSnapshot(root)) : {};
        sendAction(root, action, {}, updates);
    });

    // wire:submit / wire:submit.prevent
    document.addEventListener("submit", function(e) {
        const form = e.target.closest("[wire\\:submit\\.prevent]") || e.target.closest("[wire\\:submit]");
        if (!form) return;
        e.preventDefault();
        const action = form.getAttribute("wire:submit.prevent") || form.getAttribute("wire:submit");
        const root = findRoot(form);
        if (!root) return;

        const formData = new FormData(form);
        const payload = {};
        for (const [key, value] of formData.entries()) {
            payload[key] = value;
        }
        const updates = root.__wire_data ? collectDirtyFields(root.__wire_data, getSnapshot(root)) : {};
        sendAction(root, action, payload, updates);
    });

    // wire:model — two-way binding on input/change
    function handleModel(e) {
        const el = e.target;
        const prop = el.getAttribute("wire:model") ||
                     el.getAttribute("wire:model.live") ||
                     el.getAttribute("wire:model.defer");
        if (!prop) return;
        const root = findRoot(el);
        if (!root) return;

        const value = el.type === "checkbox" ? el.checked :
                      el.type === "select-multiple" ? [...el.selectedOptions].map(o => o.value) :
                      el.value;

        // Update local state
        if (root.__wire_data) root.__wire_data[prop] = value;
        const snap = getSnapshot(root);
        snap[prop] = value;
        setSnapshot(root, snap);

        // wire:model.live — sync to server immediately (debounced)
        if (el.hasAttribute("wire:model.live")) {
            clearTimeout(root.__wire_debounce);
            root.__wire_debounce = setTimeout(() => {
                const updates = {};
                updates[prop] = value;
                sendAction(root, "$refresh", {}, updates);
            }, 150);
        }
    }
    document.addEventListener("input", handleModel);
    document.addEventListener("change", handleModel);

    // wire:init — call action when component first appears
    function processInit(el) {
        if (el.__wire_init_done) return;
        el.__wire_init_done = true;
        const action = el.getAttribute("wire:init");
        const root = findRoot(el);
        if (root && action) sendAction(root, action, {}, {});
    }

    // -----------------------------------------------------------------------
    // wire:poll — periodic refresh (stored on root, not on elements)
    // -----------------------------------------------------------------------

    function setupPolling(scope) {
        const container = scope || document;

        // Match wire:poll, wire:poll.2s, wire:poll.500ms etc.
        container.querySelectorAll("[wire\\:poll], [wire\\:poll\\.2s], [wire\\:poll\\.1s], [wire\\:poll\\.3s], [wire\\:poll\\.5s], [wire\\:poll\\.10s]").forEach(el => {
            const root = findRoot(el);
            if (!root) return;

            let interval = 2000;
            let action = "$refresh";

            // Check for wire:poll.Xs / wire:poll.Xms modifiers
            for (const attr of el.attributes) {
                const m = attr.name.match(/^wire:poll\.(\d+)(ms|s)?$/);
                if (m) {
                    interval = parseInt(m[1]) * (m[2] === "s" || !m[2] ? 1000 : 1);
                    action = attr.value || "$refresh";
                    break;
                }
            }

            // Fallback: wire:poll="value"
            if (el.hasAttribute("wire:poll")) {
                const attr = el.getAttribute("wire:poll");
                if (attr) {
                    const msMatch = attr.match(/^(\d+)(ms|s)?$/);
                    if (msMatch) {
                        interval = parseInt(msMatch[1]) * (msMatch[2] === "s" ? 1000 : 1);
                    } else {
                        action = attr;
                    }
                }
            }

            // Store on root so it survives morphs
            const key = "poll_" + interval + "_" + action;
            if (!root.__wire_polls) root.__wire_polls = {};
            if (root.__wire_polls[key]) return;

            root.__wire_polls[key] = setInterval(() => {
                if (!document.contains(root)) {
                    clearInterval(root.__wire_polls[key]);
                    delete root.__wire_polls[key];
                    return;
                }
                sendAction(root, action, {}, {});
            }, interval);
        });
    }

    // -----------------------------------------------------------------------
    // wire:navigate — SPA-like page transitions
    // -----------------------------------------------------------------------

    // Clear all active polls (called before wire:navigate page transitions)
    function clearAllPolls() {
        document.querySelectorAll("[data-wire-component]").forEach(root => {
            if (root.__wire_polls) {
                for (const key of Object.keys(root.__wire_polls)) {
                    clearInterval(root.__wire_polls[key]);
                }
                root.__wire_polls = {};
            }
        });
    }

    const pageCache = new Map();

    async function navigateTo(url, pushState) {
        // Stop all polling before navigating
        clearAllPolls();

        // Show a subtle loading indicator
        document.body.setAttribute("data-wire-navigating", "");

        try {
            let html = pageCache.get(url);
            if (!html) {
                const res = await fetch(url, { headers: { "X-Wire-Navigate": "true" } });
                if (!res.ok) { window.location.href = url; return; }
                html = await res.text();
            }
            pageCache.delete(url);

            // Parse the new page
            const parser = new DOMParser();
            const doc = parser.parseFromString(html, "text/html");

            // Update title
            const newTitle = doc.querySelector("title");
            if (newTitle) document.title = newTitle.textContent;

            // Morph body
            morphdom(document.body, doc.body, {
                childrenOnly: false,
                getNodeKey(node) {
                    return node.id || null;
                },
                onBeforeElUpdated(fromEl, toEl) {
                    // Preserve scripts (don't re-execute)
                    if (fromEl.tagName === "SCRIPT") return false;
                    // Preserve Alpine state
                    if (fromEl._x_dataStack) {
                        window.Alpine && Alpine.clone(fromEl, toEl);
                    }
                    return true;
                },
                onNodeAdded(node) {
                    // Skip script re-injection from morph
                    if (node.tagName === "SCRIPT") {
                        node.remove();
                    }
                    return node;
                }
            });

            // Push URL
            if (pushState !== false) {
                history.pushState({}, "", url);
            }

            // Re-bootstrap wire components on the new page
            bootstrap();

            // Update wire:navigate current indicators
            updateCurrentLinks();

        } finally {
            document.body.removeAttribute("data-wire-navigating");
        }
    }

    // Prefetch cache for wire:navigate.hover
    function prefetch(url) {
        if (pageCache.has(url)) return;
        fetch(url, { headers: { "X-Wire-Navigate": "true" } })
            .then(res => res.ok ? res.text() : null)
            .then(html => { if (html) pageCache.set(url, html); })
            .catch(() => {});
    }

    // Click handler for wire:navigate links
    document.addEventListener("click", function(e) {
        const link = e.target.closest("a[wire\\:navigate], a[wire\\:navigate\\.hover]");
        if (!link) return;
        const href = link.getAttribute("href");
        if (!href || href.startsWith("#") || href.startsWith("javascript:")) return;
        // Only handle same-origin
        try {
            const url = new URL(href, window.location.origin);
            if (url.origin !== window.location.origin) return;
        } catch { return; }
        e.preventDefault();
        navigateTo(href);
    });

    // Hover prefetch for wire:navigate.hover
    document.addEventListener("mouseover", function(e) {
        const link = e.target.closest("a[wire\\:navigate\\.hover]");
        if (!link) return;
        const href = link.getAttribute("href");
        if (href) {
            try {
                const url = new URL(href, window.location.origin);
                if (url.origin === window.location.origin) prefetch(href);
            } catch {}
        }
    });

    // Handle browser back/forward
    window.addEventListener("popstate", function() {
        navigateTo(window.location.href, false);
    });

    // Mark current page links with data-current
    function updateCurrentLinks() {
        const path = window.location.pathname;
        document.querySelectorAll("a[wire\\:navigate], a[wire\\:navigate\\.hover]").forEach(a => {
            const href = a.getAttribute("href");
            if (href === path || (href === "/" && path === "/")) {
                a.setAttribute("data-current", "");
            } else {
                a.removeAttribute("data-current");
            }
        });
    }

    // -----------------------------------------------------------------------
    // Bootstrap
    // -----------------------------------------------------------------------

    function bootstrap() {
        document.querySelectorAll("[data-wire-component]").forEach(initComponent);
        document.querySelectorAll("[wire\\:init]").forEach(processInit);
        setupPolling();
        updateCurrentLinks();
    }

    if (document.readyState === "loading") {
        document.addEventListener("DOMContentLoaded", bootstrap);
    } else {
        bootstrap();
    }

    // Watch for dynamically added components
    new MutationObserver((mutations) => {
        for (const m of mutations) {
            for (const node of m.addedNodes) {
                if (node.nodeType !== 1) continue;
                if (node.hasAttribute && node.hasAttribute("data-wire-component")) initComponent(node);
                if (node.querySelectorAll) {
                    node.querySelectorAll("[data-wire-component]").forEach(initComponent);
                    node.querySelectorAll("[wire\\:init]").forEach(processInit);
                }
            }
        }
    }).observe(document.body, { childNodes: true, subtree: true });

    console.log("[axum-wire] Runtime loaded.");
})();
</script>
"##;

// ---------------------------------------------------------------------------
// Layouts
// ---------------------------------------------------------------------------

pub struct LayoutContext {
    pub component: String,
    pub body: String,
    pub wire_js: &'static str,
}

pub type LayoutFn = Arc<dyn Fn(LayoutContext) -> String + Send + Sync>;

pub fn default_layout(ctx: LayoutContext) -> String {
    format!(
        r#"<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{title}</title>
    <style>
        * {{ margin: 0; padding: 0; box-sizing: border-box; }}
        body {{ font-family: system-ui, -apple-system, sans-serif; background: #f5f5f5; color: #333; }}
        [data-wire-loading] {{ opacity: 0.6; pointer-events: none; transition: opacity 0.15s; }}
    </style>
</head>
<body>
    {body}
    {wire_js}
</body>
</html>"#,
        title = ctx.component,
        body = ctx.body,
        wire_js = ctx.wire_js,
    )
}

// ---------------------------------------------------------------------------
// WireApp builder
// ---------------------------------------------------------------------------

pub struct WireApp {
    router: Router,
    layout: LayoutFn,
}

impl WireApp {
    pub fn new() -> Self {
        Self {
            router: Router::new(),
            layout: Arc::new(default_layout),
        }
    }

    pub fn layout<F>(mut self, f: F) -> Self
    where
        F: Fn(LayoutContext) -> String + Send + Sync + 'static,
    {
        self.layout = Arc::new(f);
        self
    }

    pub fn wire(self, path: &str, component_name: &str) -> Self {
        let layout = self.layout.clone();
        self.wire_with_layout(path, component_name, layout)
    }

    pub fn wire_with<F>(self, path: &str, component_name: &str, layout_fn: F) -> Self
    where
        F: Fn(LayoutContext) -> String + Send + Sync + 'static,
    {
        self.wire_with_layout(path, component_name, Arc::new(layout_fn))
    }

    fn wire_with_layout(mut self, path: &str, component_name: &str, layout: LayoutFn) -> Self {
        let name = component_name.to_string();

        let handler = move || {
            let name = name.clone();
            let layout = layout.clone();
            async move {
                match mount_component(&name).await {
                    Ok(component_html) => {
                        let ctx = LayoutContext {
                            component: name,
                            body: component_html,
                            wire_js: WIRE_JS,
                        };
                        Html(layout(ctx)).into_response()
                    }
                    Err(e) => (
                        StatusCode::INTERNAL_SERVER_ERROR,
                        format!("Failed to mount component: {e}"),
                    )
                        .into_response(),
                }
            }
        };

        self.router = self.router.route(path, get(handler));
        self
    }

    pub fn merge(mut self, router: Router) -> Self {
        self.router = self.router.merge(router);
        self
    }

    pub fn into_router(self) -> Router {
        // Auto-connect to dioxus devtools when running under `dx serve --hotpatch`
        connect_devtools();

        self.router.route("/_wire/update", post(handle_wire_update))
    }
}

impl Default for WireApp {
    fn default() -> Self {
        Self::new()
    }
}

// ---------------------------------------------------------------------------
// Router extension (convenience)
// ---------------------------------------------------------------------------

pub trait WireRouter {
    fn wire(self, path: &str, component_name: &str) -> Self;
    fn wire_routes(self) -> Self;
}

impl WireRouter for Router {
    fn wire(self, path: &str, component_name: &str) -> Self {
        let name = component_name.to_string();

        let handler = move || {
            let name = name.clone();
            async move {
                match mount_component(&name).await {
                    Ok(component_html) => {
                        let ctx = LayoutContext {
                            component: name,
                            body: component_html,
                            wire_js: WIRE_JS,
                        };
                        Html(default_layout(ctx)).into_response()
                    }
                    Err(e) => (
                        StatusCode::INTERNAL_SERVER_ERROR,
                        format!("Failed to mount component: {e}"),
                    )
                        .into_response(),
                }
            }
        };

        self.route(path, get(handler))
    }

    fn wire_routes(self) -> Self {
        connect_devtools();
        self.route("/_wire/update", post(handle_wire_update))
    }
}