Skip to main content

WIRE_JS

Constant WIRE_JS 

Source
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 request ordering per component root to avoid out-of-order morphs.
    // Only the latest response is allowed to patch the DOM.
    const pending = new WeakMap();
    let navVersion = 0;

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

    async function sendAction(root, action, payload, updates) {
        const requestNavVersion = navVersion;
        const requestId = (pending.get(root) || 0) + 1;
        pending.set(root, requestId);

        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",
                credentials: "same-origin",
                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();

            // Ignore stale responses; a newer request already started.
            if (pending.get(root) !== requestId) {
                return;
            }

            // Ignore responses from a previous page navigation cycle.
            if (requestNavVersion !== navVersion) {
                return;
            }

            // Root may have been removed/replaced during navigation.
            if (!document.contains(root)) {
                return;
            }

            // 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);

            // Sync #[url] fields to browser URL
            if (data.url_params) {
                syncUrlParams(root, data.url_params);
            }

            // 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); }
                    }
                }

                if (data.dispatches && data.dispatches.length) {
                    for (const evt of data.dispatches) {
                        if (!evt || !evt.name) continue;
                        dispatchWireEvent(root, evt);
                    }
                }
                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) {
                        const key = node.getAttribute("wire:key");
                        return key && key.length ? key : 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);
                    }
                }
            }

            // Dispatch server-emitted browser events from this component root
            if (data.dispatches && data.dispatches.length) {
                for (const evt of data.dispatches) {
                    if (!evt || !evt.name) continue;
                    dispatchWireEvent(root, evt);
                }
            }

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

        } finally {
            if (pending.get(root) === requestId) {
                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 === "$dispatch") return (name, detail = {}) => dispatchClientEvent(root, name, detail, true);
                if (prop === "$dispatchSelf") return (name, detail = {}) => dispatchClientEvent(root, name, detail, false);
                if (prop === "$dispatchTo") return (component, name, detail = {}) => dispatchClientEventTo(component, name, detail);
                if (prop === "$parent") {
                    const parentRoot = root.parentElement && root.parentElement.closest("[data-wire-component]");
                    if (!parentRoot) return {};
                    if (!parentRoot.__wire_proxy && !parentRoot.__wire_initialized) {
                        try { initComponent(parentRoot); } catch(_) {}
                    }
                    return parentRoot.__wire_proxy || {};
                }
                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 dispatchClientEvent(root, name, detail, bubbles) {
        if (!name) return;
        root.dispatchEvent(new CustomEvent(name, {
            detail: detail ?? null,
            bubbles,
            composed: true,
        }));
    }

    function dispatchClientEventTo(componentName, name, detail) {
        if (!componentName || !name) return;
        document.querySelectorAll(`[data-wire-component="${componentName}"]`).forEach((el) => {
            el.dispatchEvent(new CustomEvent(name, {
                detail: detail ?? null,
                bubbles: true,
                composed: true,
            }));
        });
    }

    function evaluateWireExpression(root, expr, event) {
        const $wire = root.__wire_proxy || {};
        const $dispatch = (name, detail = {}) => dispatchClientEvent(root, name, detail, true);
        const $dispatchSelf = (name, detail = {}) => dispatchClientEvent(root, name, detail, false);
        const $dispatchTo = (component, name, detail = {}) => dispatchClientEventTo(component, name, detail);

        const scope = Object.create($wire || null);
        scope.$wire = $wire;
        scope.$dispatch = $dispatch;
        scope.$dispatchSelf = $dispatchSelf;
        scope.$dispatchTo = $dispatchTo;

        return new Function("$event", "$scope", `with($scope){ ${expr} }`).call(root, event, scope);
    }

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

    function dispatchWireEvent(root, evt) {
        const target = evt.target || null;
        const detail = evt.detail ?? null;

        if (target === "self") {
            root.dispatchEvent(new CustomEvent(evt.name, {
                detail,
                bubbles: false,
                composed: true,
            }));
            return;
        }

                if (target && target.startsWith("to:")) {
                    const componentName = target.slice(3);
                    if (!componentName) return;
                    document.querySelectorAll(`[data-wire-component="${componentName}"]`).forEach((el) => {
                        el.dispatchEvent(new CustomEvent(evt.name, {
                            detail,
                            bubbles: true,
                            composed: true,
                        }));
                    });
                    return;
                }

        root.dispatchEvent(new CustomEvent(evt.name, {
            detail,
            bubbles: true,
            composed: true,
        }));
    }

    // -----------------------------------------------------------------------
    // #[url] — URL query parameter sync
    // -----------------------------------------------------------------------

    function getUrlFields(root) {
        if (root.__wire_url_fields) return root.__wire_url_fields;
        const attr = root.getAttribute("data-wire-url");
        if (!attr) return null;
        try {
            const fields = JSON.parse(attr);
            root.__wire_url_fields = fields;
            return fields;
        } catch { return null; }
    }

    /**
     * Update the browser URL with current #[url] field values.
     * Called after server responses and client-side wire:model changes.
     *
     * @param {Element} root - component root element
     * @param {Object} urlParams - { queryName: value } from server response
     * @param {boolean} [forceHistory] - if any field has history:true, use pushState
     */
    function syncUrlParams(root, urlParams, forceHistory) {
        const fields = getUrlFields(root);
        if (!fields || !urlParams) return;

        const url = new URL(window.location.href);
        let useHistory = !!forceHistory;
        const defaults = root.__wire_url_defaults || {};

        for (const field of fields) {
            const queryKey = field.query_name;
            const fieldName = field.field_name;
            const value = urlParams[queryKey];

            if (field.history) useHistory = true;

            // Determine the default value for this field
            const defaultVal = defaults[fieldName];

            // Decide whether to include in URL
            const isDefault = JSON.stringify(value) === JSON.stringify(defaultVal);

            if (field.keep || !isDefault) {
                // Include in URL
                if (value === null || value === undefined) {
                    url.searchParams.delete(queryKey);
                } else if (typeof value === "object") {
                    url.searchParams.set(queryKey, JSON.stringify(value));
                } else {
                    url.searchParams.set(queryKey, String(value));
                }
            } else {
                // Remove from URL (at default value)
                url.searchParams.delete(queryKey);
            }
        }

        const newUrl = url.toString();
        if (newUrl !== window.location.href) {
            if (useHistory) {
                history.pushState({}, "", newUrl);
            } else {
                history.replaceState({}, "", newUrl);
            }
        }
    }

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

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

        // Read default values for #[url] fields (set by server before query param merge)
        const fields = getUrlFields(root);
        if (fields) {
            const defaultsAttr = root.getAttribute("data-wire-url-defaults");
            if (defaultsAttr) {
                try { root.__wire_url_defaults = JSON.parse(defaultsAttr); } catch {}
            }
            if (!root.__wire_url_defaults) {
                // Fallback: use current snapshot as defaults
                const snapshot = getSnapshot(root);
                const defaults = {};
                for (const field of fields) {
                    defaults[field.field_name] = snapshot[field.field_name];
                }
                root.__wire_url_defaults = defaults;
            }
        }

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

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

        if (window.Alpine && !root._x_dataStack) {
            Alpine.initTree(root);
        }

        setupEventListeners(root);
        setupOnActionListeners(root);
    }

    function setupEventListeners(root) {
        if (root.__wire_listener_cleanup) return;

        const listeners = {};
        for (const attr of root.attributes) {
            if (!attr.name || !attr.name.startsWith("x-on:")) continue;
            listeners[attr.name.slice(5)] = attr.value;
        }
        if (Object.keys(listeners).length === 0) return;

        const handlers = [];
        for (const [eventName, expr] of Object.entries(listeners)) {
            if (!eventName || !expr) continue;
            const binding = parseEventBinding(eventName);
            if (!binding) continue;
            const fn = function(event) {
                if (!matchesEventModifiers(binding.modifiers, event)) return;
                if (binding.modifiers.has("prevent")) event.preventDefault();
                if (binding.modifiers.has("stop")) event.stopPropagation();
                try {
                    evaluateWireExpression(root, expr, event);
                } catch (e) {
                    console.error("[wire] @event handler error:", e);
                }
            };

            const target = binding.modifiers.has("window")
                ? window
                : binding.modifiers.has("document")
                    ? document
                    : root;

            target.addEventListener(binding.name, fn);
            handlers.push([target, binding.name, fn]);
        }

        root.__wire_listener_cleanup = () => {
            for (const [target, eventName, fn] of handlers) {
                target.removeEventListener(eventName, fn);
            }
        };
    }

    function parseEventBinding(name) {
        if (!name) return null;
        const parts = name.split('.');
        let eventName = parts[0];
        if (!eventName) return null;
        const modifiers = new Set(parts.slice(1));
        if (modifiers.has("camel")) {
            eventName = eventName.replace(/-([a-z])/g, (_, c) => c.toUpperCase());
        }
        return {
            name: eventName,
            modifiers,
        };
    }

    function matchesEventModifiers(modifiers, event) {
        if (modifiers.has("escape") && event.key !== "Escape") return false;
        if (modifiers.has("enter") && event.key !== "Enter") return false;
        return true;
    }

    function setupOnActionListeners(root) {
        if (root.__wire_on_cleanup) return;

        const attr = root.getAttribute("data-wire-on");
        if (!attr) return;

        let listeners = null;
        try {
            listeners = JSON.parse(attr);
        } catch {
            return;
        }
        if (!listeners || typeof listeners !== "object") return;

        const handlers = [];
        for (const [eventName, actionName] of Object.entries(listeners)) {
            if (!eventName || !actionName) continue;
            const fn = function(event) {
                const updates = root.__wire_data ? collectDirtyFields(root.__wire_data, getSnapshot(root)) : {};
                sendAction(root, "$event", {
                    event: eventName,
                    detail: event && event.detail !== undefined ? event.detail : null
                }, updates);
            };
            root.addEventListener(eventName, fn);
            handlers.push([eventName, fn]);
        }

        root.__wire_on_cleanup = () => {
            for (const [eventName, fn] of handlers) {
                root.removeEventListener(eventName, fn);
            }
        };
    }

    // 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
    // -----------------------------------------------------------------------

    function parseActionCall(action) {
        if (!action) return null;
        const match = action.match(/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*\((.*)\)\s*$/s);
        if (!match) return null;

        const name = match[1];
        const argsSource = match[2].trim();
        if (!argsSource) return { name, args: [] };

        try {
            const args = new Function(`return [${argsSource}]`)();
            return Array.isArray(args) ? { name, args } : null;
        } catch (_) {
            return null;
        }
    }

    // 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)) : {};

        if (action === "$refresh") {
            sendAction(root, "$refresh", {}, updates);
            return;
        }

        if (action && action.trim().startsWith("$")) {
            try {
                evaluateWireExpression(root, action, e);
            } catch (err) {
                console.error("[wire] wire:click expression error:", err);
            }
            return;
        }

        const parsedCall = parseActionCall(action);
        if (parsedCall) {
            sendAction(root, parsedCall.name, parsedCall.args.length ? { args: parsedCall.args } : {}, updates);
            return;
        }

        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);

        // If this field is a #[url] field, update URL immediately on client side
        const urlFields = getUrlFields(root);
        if (urlFields) {
            const matchingField = urlFields.find(f => f.field_name === prop);
            if (matchingField) {
                const urlParams = {};
                urlParams[matchingField.query_name] = value;
                // Also include other url fields from current snapshot
                const currentSnap = getSnapshot(root);
                for (const f of urlFields) {
                    if (f.field_name !== prop) {
                        urlParams[f.query_name] = currentSnap[f.field_name];
                    }
                }
                syncUrlParams(root, urlParams);
            }
        }

        // 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 = {};
            }
            if (root.__wire_listener_cleanup) {
                try { root.__wire_listener_cleanup(); } catch {}
                root.__wire_listener_cleanup = null;
            }
            if (root.__wire_on_cleanup) {
                try { root.__wire_on_cleanup(); } catch {}
                root.__wire_on_cleanup = null;
            }
        });
    }

    const pageCache = new Map();

    async function navigateTo(url, pushState) {
        navVersion += 1;

        // 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, {
                    credentials: "same-origin",
                    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;

            // Replace body content for navigation to avoid cross-page morph artifacts.
            // Keep the currently loaded runtime script; drop scripts from fetched HTML.
            doc.body.querySelectorAll("script").forEach((node) => node.remove());
            document.body.replaceWith(doc.body);

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

            // Reset and re-bootstrap wire components on the new page.
            // morphdom may reuse existing DOM nodes, so we must clear the
            // initialized flag so initComponent re-reads the new snapshot,
            // URL field metadata, and defaults from the morphed attributes.
            document.querySelectorAll("[data-wire-component]").forEach(root => {
                root.__wire_initialized = false;
                root.__wire_url_fields = null;
                root.__wire_url_defaults = null;
            });
            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, {
            credentials: "same-origin",
            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>
"##;
Expand description

The JS runtime that powers wire: directives on the client. Ships Alpine.js + morphdom + the $wire proxy.