pub use axum_wire_macros::{html, on, wire_actions, Component};
pub use futures;
pub use inventory;
pub use serde_json;
pub use tokio;
pub use subsecond;
pub use axum::extract;
pub use axum_extra;
pub use tower;
pub mod html_elements;
pub fn connect_devtools() {
#[cfg(debug_assertions)]
{
dioxus_devtools::connect_subsecond();
}
}
use std::pin::Pin;
use std::sync::Arc;
use axum::{
body::Body,
extract::{FromRequestParts, Json, Path, Query, Request},
http::{header::SET_COOKIE, request::Parts, StatusCode},
middleware,
response::{Html, IntoResponse, Response},
routing::{get, post},
Router,
};
use futures::future::BoxFuture;
use serde::{Deserialize, Serialize};
use tower::ServiceExt;
#[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),
#[error("Cannot update locked property: {0}")]
LockedProperty(String),
}
#[derive(Debug, Clone, Serialize)]
pub struct UrlFieldMeta {
pub field_name: &'static str,
pub query_name: &'static str,
pub history: bool,
pub keep: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EventListenerMeta {
pub event: &'static str,
pub action: &'static str,
}
pub trait ComponentMeta {
fn component_name() -> &'static str;
fn url_fields() -> &'static [UrlFieldMeta] {
&[]
}
fn locked_fields() -> &'static [&'static str] {
&[]
}
fn layout_name() -> Option<&'static str> {
None
}
fn event_listeners() -> &'static [EventListenerMeta] {
&[]
}
}
pub struct WireResponse {
pub html: String,
pub snapshot: serde_json::Value,
pub effects: ActionEffects,
}
pub type WireResult = Result<WireResponse, WireError>;
#[derive(Clone, Serialize)]
pub struct DispatchEvent {
pub name: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub detail: Option<serde_json::Value>,
#[serde(skip_serializing_if = "Option::is_none")]
pub target: Option<String>,
}
#[derive(Default)]
pub struct ActionEffects {
pub js: Vec<String>,
pub dispatches: Vec<DispatchEvent>,
pub skip_render: bool,
pub redirect: Option<String>,
pub redirect_navigate: bool,
pub response_extensions: Vec<Arc<dyn Fn(&mut axum::http::Extensions) + Send + Sync>>,
pub set_cookie_headers: Vec<axum::http::HeaderValue>,
}
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.dispatches.clear();
e.skip_render = false;
e.redirect = None;
e.redirect_navigate = false;
e.response_extensions.clear();
e.set_cookie_headers.clear();
});
ActionScope
}
pub fn finish(self) -> ActionEffects {
ACTION_EFFECTS.with(|e| {
let mut e = e.borrow_mut();
ActionEffects {
js: e.js.drain(..).collect(),
dispatches: e.dispatches.drain(..).collect(),
skip_render: e.skip_render,
redirect: e.redirect.take(),
redirect_navigate: e.redirect_navigate,
response_extensions: e.response_extensions.drain(..).collect(),
set_cookie_headers: e.set_cookie_headers.drain(..).collect(),
}
})
}
}
impl Drop for ActionScope {
fn drop(&mut self) {
ACTION_EFFECTS.with(|e| {
let mut e = e.borrow_mut();
e.js.clear();
e.dispatches.clear();
e.skip_render = false;
e.redirect = None;
e.redirect_navigate = false;
e.response_extensions.clear();
e.set_cookie_headers.clear();
});
}
}
pub fn push_js(code: String) {
ACTION_EFFECTS.with(|e| e.borrow_mut().js.push(code));
}
pub fn dispatch_event(name: String, detail: Option<serde_json::Value>) {
dispatch_event_targeted(name, detail, None);
}
pub fn dispatch_event_targeted(
name: String,
detail: Option<serde_json::Value>,
target: Option<String>,
) {
ACTION_EFFECTS.with(|e| {
e.borrow_mut().dispatches.push(DispatchEvent {
name,
detail,
target,
});
});
}
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 fn push_response_extension<T>(value: T)
where
T: Clone + Send + Sync + 'static,
{
ACTION_EFFECTS.with(|e| {
e.borrow_mut()
.response_extensions
.push(Arc::new(move |extensions| {
extensions.insert(value.clone());
}));
});
}
fn push_set_cookie_header(value: axum::http::HeaderValue) {
ACTION_EFFECTS.with(|e| e.borrow_mut().set_cookie_headers.push(value));
}
fn collect_set_cookie_headers(response: &Response) -> Vec<axum::http::HeaderValue> {
response
.headers()
.get_all(SET_COOKIE)
.iter()
.cloned()
.collect()
}
fn cookie_header_value(
cookie: &axum_extra::extract::cookie::Cookie<'static>,
) -> Option<axum::http::HeaderValue> {
axum::http::HeaderValue::from_str(&cookie.encoded().to_string()).ok()
}
fn queue_set_cookie_headers_from_response(response: &Response) {
for value in collect_set_cookie_headers(response) {
push_set_cookie_header(value);
}
}
fn apply_states_to_request(
mut request: Request,
states: &Arc<Vec<Arc<dyn StateInjector>>>,
) -> Request {
for state in states.iter() {
state.inject(request.extensions_mut());
}
request
}
#[derive(Clone)]
pub struct WireContext {
parts: Arc<std::sync::Mutex<Parts>>,
}
impl WireContext {
pub fn new(parts: Parts) -> Self {
Self {
parts: Arc::new(std::sync::Mutex::new(parts)),
}
}
pub fn empty() -> Self {
let (parts, _) = axum::http::Request::new(()).into_parts();
Self::new(parts)
}
pub async fn extract<T>(&self) -> Result<T, T::Rejection>
where
T: FromRequestParts<()>,
{
let mut parts = self.parts.lock().unwrap().clone();
T::from_request_parts(&mut parts, &()).await
}
pub fn path<T>(&self) -> Path<T>
where
T: serde::de::DeserializeOwned + Send + 'static,
{
self.try_path::<T>()
.expect("Failed to extract Path from WireContext")
}
pub fn query<T>(&self) -> Query<T>
where
T: serde::de::DeserializeOwned + Send + 'static,
{
self.try_query::<T>()
.expect("Failed to extract Query from WireContext")
}
pub fn state<T: Clone + Send + Sync + 'static>(&self) -> T {
self.try_state::<T>()
.expect("State not found in WireContext. Did you call WireApp::state()?")
}
pub fn extension<T: Clone + Send + Sync + 'static>(&self) -> T {
self.try_extension::<T>()
.expect("Extension not found in WireContext")
}
pub fn try_path<T>(&self) -> Result<Path<T>, axum::extract::rejection::PathRejection>
where
T: serde::de::DeserializeOwned + Send + 'static,
{
let mut parts = self.parts.lock().unwrap().clone();
if let Ok(path) =
futures::executor::block_on(Path::<T>::from_request_parts(&mut parts, &()))
{
return Ok(path);
}
self.extract_path_from_stored::<T>()
}
pub fn try_query<T>(&self) -> Result<Query<T>, axum::extract::rejection::QueryRejection>
where
T: serde::de::DeserializeOwned + Send + 'static,
{
let mut parts = self.parts.lock().unwrap().clone();
futures::executor::block_on(Query::<T>::from_request_parts(&mut parts, &()))
}
pub fn try_state<T: Clone + Send + Sync + 'static>(&self) -> Option<T> {
let parts = self.parts.lock().unwrap();
parts.extensions.get::<T>().cloned()
}
pub fn try_extension<T: Clone + Send + Sync + 'static>(&self) -> Option<T> {
let parts = self.parts.lock().unwrap();
parts.extensions.get::<T>().cloned()
}
pub fn is_wire_request(&self) -> bool {
let parts = self.parts.lock().unwrap();
parts.extensions.get::<WireRequestMarker>().is_some()
}
pub fn insert_extension<T: Clone + Send + Sync + 'static>(&self, val: T) {
self.parts.lock().unwrap().extensions.insert(val);
}
pub fn cookie_jar(&self) -> axum_extra::extract::CookieJar {
let parts = self.parts.lock().unwrap();
axum_extra::extract::CookieJar::from_headers(&parts.headers)
}
pub fn signed_cookie_jar(
&self,
key: axum_extra::extract::cookie::Key,
) -> axum_extra::extract::SignedCookieJar {
let parts = self.parts.lock().unwrap();
axum_extra::extract::SignedCookieJar::from_headers(&parts.headers, key)
}
pub fn set_response_extension<T>(&self, value: T)
where
T: Clone + Send + Sync + 'static,
{
push_response_extension(value);
}
pub fn dispatch(&self, name: &str) {
dispatch_event(name.to_string(), None);
}
pub fn dispatch_with<T: serde::Serialize>(&self, name: &str, detail: T) {
if let Ok(value) = serde_json::to_value(detail) {
dispatch_event(name.to_string(), Some(value));
}
}
pub fn dispatch_self(&self, name: &str) {
dispatch_event_targeted(name.to_string(), None, Some(String::from("self")));
}
pub fn dispatch_self_with<T: serde::Serialize>(&self, name: &str, detail: T) {
if let Ok(value) = serde_json::to_value(detail) {
dispatch_event_targeted(name.to_string(), Some(value), Some(String::from("self")));
}
}
pub fn dispatch_to(&self, component: &str, name: &str) {
dispatch_event_targeted(name.to_string(), None, Some(format!("to:{component}")));
}
pub fn dispatch_to_with<T: serde::Serialize>(&self, component: &str, name: &str, detail: T) {
if let Ok(value) = serde_json::to_value(detail) {
dispatch_event_targeted(
name.to_string(),
Some(value),
Some(format!("to:{component}")),
);
}
}
pub fn set_cookie(&self, cookie: axum_extra::extract::cookie::Cookie<'static>) {
if let Some(v) = cookie_header_value(&cookie) {
push_set_cookie_header(v);
}
}
pub fn remove_cookie(&self, cookie: axum_extra::extract::cookie::Cookie<'static>) {
let removal = self.cookie_jar().remove(cookie).into_response();
queue_set_cookie_headers_from_response(&removal);
}
pub fn set_signed_cookie(
&self,
key: axum_extra::extract::cookie::Key,
cookie: axum_extra::extract::cookie::Cookie<'static>,
) {
let signed = axum_extra::extract::SignedCookieJar::new(key)
.add(cookie)
.into_response();
queue_set_cookie_headers_from_response(&signed);
}
pub fn remove_signed_cookie(
&self,
key: axum_extra::extract::cookie::Key,
cookie: axum_extra::extract::cookie::Cookie<'static>,
) {
let signed = self.signed_cookie_jar(key).remove(cookie).into_response();
queue_set_cookie_headers_from_response(&signed);
}
}
#[derive(Clone)]
struct WireRequestMarker;
tokio::task_local! {
static WIRE_CTX: WireContext;
}
pub fn get_wire_ctx() -> WireContext {
WIRE_CTX.try_with(|ctx| ctx.clone())
.expect("WireContext not available — this function must be called inside a wire component lifecycle (mount/render/action)")
}
pub async fn with_wire_ctx<F, R>(ctx: WireContext, f: F) -> R
where
F: std::future::Future<Output = R>,
{
WIRE_CTX.scope(ctx, f).await
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WireStoredContext {
#[serde(default)]
pub path_params: std::collections::HashMap<String, String>,
#[serde(default)]
pub matched_path: Option<String>,
#[serde(default)]
pub layer_indices: Vec<usize>,
}
#[derive(Clone, Debug)]
struct RouteLayerIndices(Vec<usize>);
const WIRE_CTX_KEY: &str = "__wire_ctx";
fn extract_stored_ctx(snapshot: &mut serde_json::Value) -> Option<WireStoredContext> {
snapshot
.as_object_mut()
.and_then(|obj| obj.remove(WIRE_CTX_KEY))
.and_then(|v| serde_json::from_value(v).ok())
}
fn inject_stored_ctx(snapshot: &mut serde_json::Value, stored: &WireStoredContext) {
if let Some(obj) = snapshot.as_object_mut() {
if let Ok(val) = serde_json::to_value(stored) {
obj.insert(WIRE_CTX_KEY.to_string(), val);
}
}
}
fn build_stored_ctx(parts: &Parts) -> WireStoredContext {
let mut path_params = std::collections::HashMap::new();
let mut parts_clone = parts.clone();
if let Ok(raw) = futures::executor::block_on(axum::extract::RawPathParams::from_request_parts(
&mut parts_clone,
&(),
)) {
for (key, value) in raw.iter() {
path_params.insert(key.to_string(), value.to_string());
}
}
let matched_path = parts
.extensions
.get::<axum::extract::MatchedPath>()
.map(|m| m.as_str().to_string());
let layer_indices = parts
.extensions
.get::<RouteLayerIndices>()
.map(|v| v.0.clone())
.unwrap_or_default();
WireStoredContext {
path_params,
matched_path,
layer_indices,
}
}
fn restore_path_context(parts: &mut Parts, stored: &WireStoredContext) {
if let Some(ref matched) = stored.matched_path {
let mut synthetic_path = matched.clone();
for (key, value) in &stored.path_params {
synthetic_path = synthetic_path.replace(&format!("{{{key}}}"), value);
}
let mut uri_parts = parts.uri.clone().into_parts();
if let Ok(pq) =
axum::http::uri::PathAndQuery::from_maybe_shared(synthetic_path.into_bytes())
{
uri_parts.path_and_query = Some(pq);
}
if let Ok(uri) = axum::http::Uri::from_parts(uri_parts) {
parts.uri = uri;
}
}
if !stored.path_params.is_empty() {
parts
.extensions
.insert(StoredPathParams(stored.path_params.clone()));
}
}
#[derive(Clone, Debug)]
pub struct StoredPathParams(pub std::collections::HashMap<String, String>);
impl WireContext {
fn extract_path_from_stored<T>(
&self,
) -> Result<Path<T>, axum::extract::rejection::PathRejection>
where
T: serde::de::DeserializeOwned + Send + 'static,
{
let parts = self.parts.lock().unwrap();
if let Some(StoredPathParams(params)) = parts.extensions.get::<StoredPathParams>() {
let json = serde_json::to_value(params).unwrap_or_default();
if let Ok(val) = serde_json::from_value::<T>(json.clone()) {
return Ok(Path(val));
}
let values: Vec<&str> = params.values().map(|s| s.as_str()).collect();
if values.len() == 1 {
if let Ok(val) = serde_json::from_str::<T>(values[0]) {
return Ok(Path(val));
}
if let Ok(val) =
serde_json::from_value::<T>(serde_json::Value::String(values[0].to_string()))
{
return Ok(Path(val));
}
}
}
drop(parts);
let mut parts = self.parts.lock().unwrap().clone();
futures::executor::block_on(Path::<T>::from_request_parts(&mut parts, &()))
}
}
pub type UpdateFn = fn(
serde_json::Value,
&str,
serde_json::Value,
WireContext,
) -> Pin<Box<dyn std::future::Future<Output = WireResult> + Send + '_>>;
pub type MountFn = fn(WireContext) -> BoxFuture<'static, WireResult>;
pub type MountWithPropsFn = fn(serde_json::Value, WireContext) -> BoxFuture<'static, WireResult>;
pub struct ComponentFactory {
pub name: &'static str,
pub update: UpdateFn,
pub mount: MountFn,
pub mount_with_props: MountWithPropsFn,
pub url_fields: &'static [UrlFieldMeta],
pub event_listeners: &'static [EventListenerMeta],
pub component_event_listeners: &'static [EventListenerMeta],
pub locked_fields: &'static [&'static str],
pub layout: Option<&'static str>,
}
impl ComponentFactory {
pub const fn new(
name: &'static str,
update: UpdateFn,
mount: MountFn,
mount_with_props: MountWithPropsFn,
url_fields: &'static [UrlFieldMeta],
event_listeners: &'static [EventListenerMeta],
component_event_listeners: &'static [EventListenerMeta],
locked_fields: &'static [&'static str],
layout: Option<&'static str>,
) -> Self {
Self {
name,
update,
mount,
mount_with_props,
url_fields,
event_listeners,
component_event_listeners,
locked_fields,
layout,
}
}
}
inventory::collect!(ComponentFactory);
fn find_factory(name: &str) -> Option<&'static ComponentFactory> {
inventory::iter::<ComponentFactory>
.into_iter()
.find(|f| f.name == name)
}
fn resolve_layout(
component_name: &str,
explicit: Option<&LayoutFn>,
registry: &std::collections::HashMap<String, LayoutFn>,
) -> LayoutFn {
if let Some(layout) = explicit {
return layout.clone();
}
if let Some(factory) = find_factory(component_name) {
if let Some(layout_name) = factory.layout {
if let Some(layout) = registry.get(layout_name) {
return layout.clone();
}
}
}
registry
.get("default")
.cloned()
.unwrap_or_else(|| Arc::new(default_layout))
}
#[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 = "Vec::is_empty")]
dispatches: Vec<DispatchEvent>,
#[serde(skip_serializing_if = "Option::is_none")]
redirect: Option<String>,
#[serde(skip_serializing_if = "std::ops::Not::not")]
redirect_navigate: bool,
#[serde(skip_serializing_if = "Option::is_none")]
url_params: Option<serde_json::Value>,
}
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());
}
}
}
fn resolve_update_layer_indices(
req: &WireUpdateRequest,
route_layer_map: &std::collections::HashMap<String, Vec<usize>>,
) -> Vec<usize> {
let stored = req.snapshot.get(WIRE_CTX_KEY);
if let Some(indices) = stored
.and_then(|ctx| ctx.get("layer_indices"))
.and_then(|v| serde_json::from_value::<Vec<usize>>(v.clone()).ok())
{
if !indices.is_empty() {
return indices;
}
}
if let Some(matched_path) = stored
.and_then(|ctx| ctx.get("matched_path"))
.and_then(|v| v.as_str())
{
return route_layer_map
.get(matched_path)
.cloned()
.unwrap_or_default();
}
Vec::new()
}
fn resolve_event_action(component_name: &str, event_name: &str) -> Option<&'static str> {
find_factory(component_name).and_then(|factory| {
factory
.event_listeners
.iter()
.find(|m| m.event == event_name)
.or_else(|| {
factory
.component_event_listeners
.iter()
.find(|m| m.event == event_name)
})
.map(|m| m.action)
})
}
fn wire_event_listener_attr(name: &str) -> String {
find_factory(name)
.filter(|f| !f.event_listeners.is_empty() || !f.component_event_listeners.is_empty())
.map(|f| {
let mut map = serde_json::Map::new();
for meta in f.component_event_listeners {
map.insert(
meta.event.to_string(),
serde_json::Value::String(meta.action.to_string()),
);
}
for meta in f.event_listeners {
map.insert(
meta.event.to_string(),
serde_json::Value::String(meta.action.to_string()),
);
}
let json = serde_json::to_string(&serde_json::Value::Object(map)).unwrap_or_default();
format!(r#" data-wire-on="{}""#, escape_attr(&json))
})
.unwrap_or_default()
}
fn try_map_event_to_action(req: &mut WireUpdateRequest) {
if req.action != "$event" {
return;
}
let event_name = req
.payload
.get("event")
.and_then(|v| v.as_str())
.map(String::from)
.or_else(|| {
req.payload
.get("detail")
.and_then(|d| d.get("event"))
.and_then(|v| v.as_str())
.map(String::from)
});
let Some(event_name) = event_name else {
return;
};
if let Some(mapped) = resolve_event_action(&req.component, &event_name) {
req.action = String::from(mapped);
}
}
async fn dispatch_wire_update(
request: Request,
states: Arc<Vec<Arc<dyn StateInjector>>>,
layers: Vec<RouterLayer>,
route_layer_map: Arc<std::collections::HashMap<String, Vec<usize>>>,
) -> Response {
let (parts, body) = request.into_parts();
let body_bytes = match axum::body::to_bytes(body, usize::MAX).await {
Ok(b) => b,
Err(e) => {
return (
StatusCode::BAD_REQUEST,
Json(serde_json::json!({ "error": format!("Failed to read body: {e}") })),
)
.into_response();
}
};
let layer_indices = serde_json::from_slice::<WireUpdateRequest>(&body_bytes)
.map(|req| resolve_update_layer_indices(&req, &route_layer_map))
.unwrap_or_default();
let update_handler = move |request: Request| async move { handle_wire_update(request).await };
let mut router = Router::new().route("/_wire/update", post(update_handler));
for idx in layer_indices {
if let Some(apply_layer) = layers.get(idx) {
router = apply_layer(router);
}
}
let states_for_layer = states.clone();
let state_layer = move |request: Request, next: middleware::Next| {
let states = states_for_layer.clone();
async move {
let request = apply_states_to_request(request, &states);
next.run(request).await
}
};
router = router.layer(middleware::from_fn(state_layer));
let request = Request::<Body>::from_parts(parts, Body::from(body_bytes));
match router.oneshot(request).await {
Ok(response) => response,
Err(never) => match never {},
}
}
async fn handle_wire_update(request: Request) -> impl IntoResponse {
let (mut parts, body) = request.into_parts();
parts.extensions.insert(WireRequestMarker);
let body_bytes = match axum::body::to_bytes(body, usize::MAX).await {
Ok(b) => b,
Err(e) => {
return (
StatusCode::BAD_REQUEST,
Json(serde_json::json!({ "error": format!("Failed to read body: {e}") })),
)
.into_response();
}
};
let mut req: WireUpdateRequest = match serde_json::from_slice(&body_bytes) {
Ok(r) => r,
Err(e) => {
return (
StatusCode::BAD_REQUEST,
Json(serde_json::json!({ "error": format!("Invalid JSON: {e}") })),
)
.into_response();
}
};
try_map_event_to_action(&mut req);
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();
}
};
if !factory.locked_fields.is_empty() {
if let Some(upd) = req.updates.as_object() {
for key in upd.keys() {
if factory.locked_fields.contains(&key.as_str()) {
return (
StatusCode::FORBIDDEN,
Json(serde_json::json!({ "error": format!("Cannot update locked property: {}", key) })),
)
.into_response();
}
}
}
}
let mut snapshot = req.snapshot;
merge_updates(&mut snapshot, &req.updates);
let stored_ctx = extract_stored_ctx(&mut snapshot);
if let Some(ref stored) = stored_ctx {
restore_path_context(&mut parts, stored);
}
let ctx = WireContext::new(parts);
match (factory.update)(snapshot, &req.action, req.payload, ctx).await {
Ok(mut resp) => {
let response_extensions = std::mem::take(&mut resp.effects.response_extensions);
let set_cookie_headers = std::mem::take(&mut resp.effects.set_cookie_headers);
if let Some(stored) = stored_ctx {
inject_stored_ctx(&mut resp.snapshot, &stored);
}
let url_params = if factory.url_fields.is_empty() {
None
} else {
let mut params = serde_json::Map::new();
if let Some(snap_obj) = resp.snapshot.as_object() {
for uf in factory.url_fields {
if let Some(val) = snap_obj.get(uf.field_name) {
params.insert(uf.query_name.to_string(), val.clone());
}
}
}
Some(serde_json::Value::Object(params))
};
let mut response = Json(WireUpdateResponse {
html: resp.html,
snapshot: resp.snapshot,
js: resp.effects.js,
dispatches: resp.effects.dispatches,
redirect: resp.effects.redirect,
redirect_navigate: resp.effects.redirect_navigate,
url_params,
})
.into_response();
for apply in response_extensions {
apply(response.extensions_mut());
}
for value in set_cookie_headers {
response.headers_mut().append(SET_COOKIE, value);
}
response
}
Err(e) => (
StatusCode::INTERNAL_SERVER_ERROR,
Json(serde_json::json!({ "error": e.to_string() })),
)
.into_response(),
}
}
fn parse_query_string(query: Option<&str>) -> std::collections::HashMap<String, String> {
query
.map(|q| {
q.split('&')
.filter(|s| !s.is_empty())
.filter_map(|pair| {
let mut parts = pair.splitn(2, '=');
let key = parts.next()?;
let value = parts.next().unwrap_or("");
Some((percent_decode(key), percent_decode(value)))
})
.collect()
})
.unwrap_or_default()
}
fn percent_decode(s: &str) -> String {
let mut result = Vec::new();
let mut chars = s.bytes();
while let Some(b) = chars.next() {
if b == b'%' {
let hi = chars.next().and_then(hex_val);
let lo = chars.next().and_then(hex_val);
if let (Some(h), Some(l)) = (hi, lo) {
result.push(h << 4 | l);
}
} else if b == b'+' {
result.push(b' ');
} else {
result.push(b);
}
}
String::from_utf8(result).unwrap_or_else(|_| s.to_string())
}
fn hex_val(b: u8) -> Option<u8> {
match b {
b'0'..=b'9' => Some(b - b'0'),
b'a'..=b'f' => Some(b - b'a' + 10),
b'A'..=b'F' => Some(b - b'A' + 10),
_ => None,
}
}
fn escape_attr(s: &str) -> String {
s.replace('&', "&")
.replace('"', """)
.replace('<', "<")
.replace('>', ">")
}
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 = escape_attr(&snapshot_json);
let url_attr = find_factory(name)
.filter(|f| !f.url_fields.is_empty())
.map(|f| {
let json = serde_json::to_string(f.url_fields).unwrap_or_default();
format!(r#" data-wire-url="{}""#, escape_attr(&json))
})
.unwrap_or_default();
let event_attr = wire_event_listener_attr(name);
format!(
r#"<div data-wire-component="{name}" data-wire-snapshot="{escaped}"{url_attr}{event_attr}>{html}</div>"#
)
}
pub fn render_component_html_with_listeners(
name: &str,
html: &str,
snapshot: &serde_json::Value,
listeners: &[(String, String)],
) -> String {
let mut out = render_component_html(name, html, snapshot);
if listeners.is_empty() {
return out;
}
if let Some(insert_pos) = out.find('>') {
let attrs = listeners
.iter()
.map(|(event, action)| {
format!(" x-on:{}=\"{}\"", escape_attr(event), escape_attr(action))
})
.collect::<String>();
out.insert_str(insert_pos, &attrs);
}
out
}
pub async fn mount_component(name: &str) -> Result<String, WireError> {
let factory =
find_factory(name).ok_or_else(|| WireError::UnknownComponent(name.to_string()))?;
let ctx = WIRE_CTX
.try_with(|c| c.clone())
.unwrap_or_else(|_| WireContext::empty());
let resp = (factory.mount)(ctx).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 ctx = WIRE_CTX
.try_with(|c| c.clone())
.unwrap_or_else(|_| WireContext::empty());
let resp = futures::executor::block_on((factory.mount)(ctx))?;
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 ctx = WIRE_CTX
.try_with(|c| c.clone())
.unwrap_or_else(|_| WireContext::empty());
let resp = (factory.mount_with_props)(props, ctx).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 ctx = WIRE_CTX
.try_with(|c| c.clone())
.unwrap_or_else(|_| WireContext::empty());
let resp = futures::executor::block_on((factory.mount_with_props)(props, ctx))?;
Ok(render_component_html(name, &resp.html, &resp.snapshot))
}
pub fn mount_component_with_options_sync(
name: &str,
props: serde_json::Value,
listeners: Option<serde_json::Value>,
) -> Result<String, WireError> {
let factory =
find_factory(name).ok_or_else(|| WireError::UnknownComponent(name.to_string()))?;
let ctx = WIRE_CTX
.try_with(|c| c.clone())
.unwrap_or_else(|_| WireContext::empty());
let resp = futures::executor::block_on((factory.mount_with_props)(props, ctx))?;
let listeners_vec = listeners
.and_then(|v| v.as_object().cloned())
.map(|obj| {
obj.into_iter()
.filter_map(|(event, action)| action.as_str().map(|a| (event, String::from(a))))
.collect::<Vec<_>>()
})
.unwrap_or_default();
Ok(render_component_html_with_listeners(
name,
&resp.html,
&resp.snapshot,
&listeners_vec,
))
}
pub async fn mount_component_with_query(
name: &str,
query_params: &std::collections::HashMap<String, String>,
ctx: &WireContext,
) -> Result<String, WireError> {
let factory =
find_factory(name).ok_or_else(|| WireError::UnknownComponent(name.to_string()))?;
let stored_ctx = {
let parts = ctx.parts.lock().unwrap();
build_stored_ctx(&parts)
};
if factory.url_fields.is_empty() {
let mut resp = (factory.mount)(ctx.clone()).await?;
inject_stored_ctx(&mut resp.snapshot, &stored_ctx);
return Ok(render_component_html(name, &resp.html, &resp.snapshot));
}
let default_resp = (factory.mount)(ctx.clone()).await?;
let mut url_defaults = serde_json::Map::new();
if let Some(snap_obj) = default_resp.snapshot.as_object() {
for uf in factory.url_fields {
if let Some(val) = snap_obj.get(uf.field_name) {
url_defaults.insert(uf.field_name.to_string(), val.clone());
}
}
}
let mut props = serde_json::Map::new();
for uf in factory.url_fields {
if let Some(value) = query_params.get(uf.query_name) {
let json_value = serde_json::from_str(value)
.unwrap_or_else(|_| serde_json::Value::String(value.clone()));
props.insert(uf.field_name.to_string(), json_value);
}
}
let mut resp = if props.is_empty() {
default_resp
} else {
(factory.mount_with_props)(serde_json::Value::Object(props), ctx.clone()).await?
};
inject_stored_ctx(&mut resp.snapshot, &stored_ctx);
Ok(render_component_html_with_url_defaults(
name,
&resp.html,
&resp.snapshot,
&serde_json::Value::Object(url_defaults),
))
}
fn render_component_html_with_url_defaults(
name: &str,
html: &str,
snapshot: &serde_json::Value,
url_defaults: &serde_json::Value,
) -> String {
let snapshot_json = serde_json::to_string(snapshot).unwrap_or_default();
let escaped = escape_attr(&snapshot_json);
let url_attr = find_factory(name)
.filter(|f| !f.url_fields.is_empty())
.map(|f| {
let json = serde_json::to_string(f.url_fields).unwrap_or_default();
format!(r#" data-wire-url="{}""#, escape_attr(&json))
})
.unwrap_or_default();
let event_attr = wire_event_listener_attr(name);
let defaults_json = serde_json::to_string(url_defaults).unwrap_or_default();
let defaults_attr = format!(
r#" data-wire-url-defaults="{}""#,
escape_attr(&defaults_json)
);
format!(
r#"<div data-wire-component="{name}" data-wire-snapshot="{escaped}"{url_attr}{defaults_attr}{event_attr}>{html}</div>"#
)
}
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
// -----------------------------------------------------------------------
// 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;
}
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>
"##;
pub const WIRE_SCRIPTS: &str = WIRE_JS;
pub const WIRE_STYLES: &str = r#"<style>
[wire\:loading] { display: none; }
[data-wire-loading] [wire\:loading] { display: inline; }
</style>"#;
type RouterLayer = Arc<dyn Fn(Router) -> Router + Send + Sync>;
pub struct LayoutContext {
pub component: String,
pub body: String,
pub wire_js: &'static str,
}
impl LayoutContext {
pub fn wire_scripts(&self) -> &'static str {
WIRE_SCRIPTS
}
pub fn wire_styles(&self) -> &'static str {
WIRE_STYLES
}
}
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>
{styles}
<style>
* {{ margin: 0; padding: 0; box-sizing: border-box; }}
body {{ font-family: system-ui, -apple-system, sans-serif; background: #f5f5f5; color: #333; }}
</style>
</head>
<body>
{body}
{scripts}
</body>
</html>"#,
title = ctx.component,
body = ctx.body,
styles = ctx.wire_styles(),
scripts = ctx.wire_scripts(),
)
}
pub fn layout_from_str(template: &str) -> impl Fn(LayoutContext) -> String + Send + Sync + 'static {
let tpl = template.to_string();
move |ctx: LayoutContext| {
tpl.replace("@wireBody", &ctx.body)
.replace("@wireScripts", ctx.wire_scripts())
.replace("@wireStyles", ctx.wire_styles())
.replace("@wireTitle", &ctx.component)
}
}
trait StateInjector: Send + Sync {
fn inject(&self, extensions: &mut axum::http::Extensions);
}
struct TypedStateInjector<T: Clone + Send + Sync + 'static> {
value: T,
}
impl<T: Clone + Send + Sync + 'static> StateInjector for TypedStateInjector<T> {
fn inject(&self, extensions: &mut axum::http::Extensions) {
extensions.insert(self.value.clone());
}
}
pub struct WireApp {
router: Router,
layouts: Arc<std::collections::HashMap<String, LayoutFn>>,
states: Arc<Vec<Arc<dyn StateInjector>>>,
layers: Vec<RouterLayer>,
route_layer_map: Arc<std::collections::HashMap<String, Vec<usize>>>,
}
impl WireApp {
pub fn new() -> Self {
let mut layouts = std::collections::HashMap::new();
layouts.insert("default".to_string(), Arc::new(default_layout) as LayoutFn);
Self {
router: Router::new(),
layouts: Arc::new(layouts),
states: Arc::new(Vec::new()),
layers: Vec::new(),
route_layer_map: Arc::new(std::collections::HashMap::new()),
}
}
pub fn layout<F>(mut self, name: &str, f: F) -> Self
where
F: Fn(LayoutContext) -> String + Send + Sync + 'static,
{
Arc::make_mut(&mut self.layouts).insert(name.to_string(), Arc::new(f));
self
}
pub fn layout_str(self, name: &str, template: &str) -> Self {
self.layout(name, layout_from_str(template))
}
pub fn layout_file(self, name: &str, path: &str) -> Self {
let template = std::fs::read_to_string(path)
.unwrap_or_else(|e| panic!("Failed to read layout file {path:?}: {e}"));
self.layout_str(name, &template)
}
pub fn state<T: Clone + Send + Sync + 'static>(mut self, value: T) -> Self {
let states =
Arc::get_mut(&mut self.states).expect("Cannot add state after cloning WireApp");
states.push(Arc::new(TypedStateInjector { value }));
self
}
pub fn wire(self, path: &str, component_name: &str) -> Self {
self.wire_with_layout(path, component_name, None)
}
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, Some(Arc::new(layout_fn)))
}
fn wire_with_layout(
mut self,
path: &str,
component_name: &str,
explicit_layout: Option<LayoutFn>,
) -> Self {
let name = component_name.to_string();
let layouts = self.layouts.clone();
Arc::make_mut(&mut self.route_layer_map)
.entry(path.to_string())
.or_default();
let route_layers = self.route_layer_map.get(path).cloned().unwrap_or_default();
let handler = move |request: Request| {
let name = name.clone();
let explicit_layout = explicit_layout.clone();
let layouts = layouts.clone();
async move {
let (mut parts, _body) = request.into_parts();
parts
.extensions
.insert(RouteLayerIndices(route_layers.clone()));
let query_params = parse_query_string(parts.uri.query());
let wire_ctx = WireContext::new(parts);
match with_wire_ctx(
wire_ctx.clone(),
mount_component_with_query(&name, &query_params, &wire_ctx),
)
.await
{
Ok(component_html) => {
let layout = resolve_layout(&name, explicit_layout.as_ref(), &layouts);
let layout_ctx = LayoutContext {
component: name,
body: component_html,
wire_js: WIRE_JS,
};
let html =
with_wire_ctx(wire_ctx.clone(), async { layout(layout_ctx) }).await;
Html(html).into_response()
}
Err(e) => (
StatusCode::INTERNAL_SERVER_ERROR,
format!("Failed to mount component: {e}"),
)
.into_response(),
}
}
};
let route_router = Router::new().route(path, get(handler));
self.router = self.router.merge(route_router);
self
}
pub fn layer<L>(mut self, layer: L) -> Self
where
L: tower::Layer<axum::routing::Route> + Clone + Send + Sync + 'static,
L::Service: tower::Service<Request, Error = std::convert::Infallible>
+ Clone
+ Send
+ Sync
+ 'static,
<L::Service as tower::Service<Request>>::Response: IntoResponse + 'static,
<L::Service as tower::Service<Request>>::Future: Send + 'static,
{
let idx = self.layers.len();
let apply_layer: RouterLayer = Arc::new(move |router: Router| router.layer(layer.clone()));
self.router = apply_layer(self.router);
self.layers.push(apply_layer);
for indices in Arc::make_mut(&mut self.route_layer_map).values_mut() {
indices.push(idx);
}
self
}
pub fn group<F>(mut self, f: F) -> Self
where
F: FnOnce(Self) -> Self,
{
let group_app = Self {
router: Router::new(),
layouts: Arc::new(self.layouts.as_ref().clone()),
states: Arc::new(self.states.as_ref().clone()),
layers: self.layers.clone(),
route_layer_map: Arc::new(std::collections::HashMap::new()),
};
let group_app = f(group_app);
self.router = self.router.merge(group_app.router);
self.layouts = group_app.layouts;
self.states = group_app.states;
self.layers = group_app.layers;
Arc::make_mut(&mut self.route_layer_map).extend(group_app.route_layer_map.as_ref().clone());
self
}
pub fn merge(mut self, router: Router) -> Self {
self.router = self.router.merge(router);
self
}
pub fn into_router<S>(self) -> Router<S>
where
S: Clone + Send + Sync + 'static,
{
connect_devtools();
let states_for_pages = self.states.clone();
let page_state_layer = move |request: Request, next: middleware::Next| {
let states = states_for_pages.clone();
async move {
let request = apply_states_to_request(request, &states);
next.run(request).await
}
};
let page_router = self.router.layer(middleware::from_fn(page_state_layer));
let states = self.states.clone();
let layers = self.layers.clone();
let route_layer_map = self.route_layer_map.clone();
let update_handler = move |request: Request| {
let states = states.clone();
let layers = layers.clone();
let route_layer_map = route_layer_map.clone();
async move { dispatch_wire_update(request, states, layers, route_layer_map).await }
};
page_router
.route("/_wire/update", post(update_handler))
.with_state::<S>(())
}
}
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 |request: Request| {
let name = name.clone();
async move {
let (parts, _body) = request.into_parts();
let query_params = parse_query_string(parts.uri.query());
let wire_ctx = WireContext::new(parts);
match with_wire_ctx(
wire_ctx.clone(),
mount_component_with_query(&name, &query_params, &wire_ctx),
)
.await
{
Ok(component_html) => {
let empty_registry = std::collections::HashMap::new();
let layout = resolve_layout(&name, None, &empty_registry);
let layout_ctx = LayoutContext {
component: name,
body: component_html,
wire_js: WIRE_JS,
};
Html(layout(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))
}
}