pub use axum_wire_macros::{Component, html, wire_actions};
pub use futures;
pub use inventory;
pub use serde_json;
pub use subsecond;
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};
#[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),
}
pub trait ComponentMeta {
fn component_name() -> &'static str;
}
pub struct WireResponse {
pub html: String,
pub snapshot: serde_json::Value,
pub effects: ActionEffects,
}
pub type WireResult = Result<WireResponse, WireError>;
#[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());
}
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;
});
}
}
pub fn push_js(code: String) {
ACTION_EFFECTS.with(|e| e.borrow_mut().js.push(code));
}
pub fn set_skip_render() {
ACTION_EFFECTS.with(|e| e.borrow_mut().skip_render = true);
}
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; });
}
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>;
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)
}
#[derive(Deserialize)]
struct WireUpdateRequest {
component: String,
snapshot: serde_json::Value,
action: String,
#[serde(default)]
payload: serde_json::Value,
#[serde(default)]
updates: serde_json::Value,
}
#[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,
}
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();
}
};
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(),
}
}
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('&', "&")
.replace('"', """)
.replace('<', "<")
.replace('>', ">");
format!(
r#"<div data-wire-component="{name}" data-wire-snapshot="{escaped}">{html}</div>"#
)
}
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))
}
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))
}
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))
}
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))
}
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>
"##;
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,
)
}
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 {
connect_devtools();
self.router.route("/_wire/update", post(handle_wire_update))
}
}
impl Default for WireApp {
fn default() -> Self {
Self::new()
}
}
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))
}
}