use std::sync::Arc;
use laravel::http::Request;
use serde::de::DeserializeOwned;
use serde_json::{Map, Value};
use crate::error::LivewireError;
pub type Result<T, E = LivewireError> = std::result::Result<T, E>;
#[derive(Debug, Clone, PartialEq)]
pub enum ComponentView {
Named(String),
Inline {
source: &'static str,
data: Map<String, Value>,
},
}
impl ComponentView {
#[must_use]
pub fn name(&self) -> &str {
match self {
Self::Named(name) => name,
Self::Inline { .. } => "inline",
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum Params {
List(Vec<Value>),
Named(Map<String, Value>),
}
impl Default for Params {
fn default() -> Self {
Self::List(Vec::new())
}
}
impl Params {
pub fn from_json(value: Value) -> Result<Self> {
match value {
Value::Array(list) => Ok(Self::List(list)),
Value::Object(map) => Ok(Self::Named(map)),
Value::Null => Ok(Self::List(Vec::new())),
_ => Err(LivewireError::MalformedPayload(
"a call's params must be a list or an object".to_owned(),
)),
}
}
pub fn arg<T: DeserializeOwned>(&self, name: &str, index: usize) -> Result<T> {
let value = match self {
Self::List(list) => list.get(index).cloned(),
Self::Named(map) => map.get(name).cloned().or_else(|| map.get(&index.to_string()).cloned()),
};
match value {
Some(value) => decode(value, name),
None => Err(LivewireError::MalformedPayload(format!(
"the call is missing its parameter [{name}]"
))),
}
}
pub fn optional<T: DeserializeOwned>(&self, name: &str, index: usize) -> Result<Option<T>> {
let value = match self {
Self::List(list) => list.get(index).cloned(),
Self::Named(map) => map.get(name).cloned().or_else(|| map.get(&index.to_string()).cloned()),
};
value.map(|value| decode(value, name)).transpose()
}
#[must_use]
pub fn is_empty(&self) -> bool {
match self {
Self::List(list) => list.is_empty(),
Self::Named(map) => map.is_empty(),
}
}
pub fn decode<T: DeserializeOwned>(self) -> Result<T> {
let value = match self {
Self::List(list) => Value::Array(list),
Self::Named(map) => Value::Object(map),
};
decode(value, "params")
}
}
fn decode<T: DeserializeOwned>(value: Value, name: &str) -> Result<T> {
serde_json::from_value(value)
.map_err(|error| LivewireError::MalformedPayload(format!("the parameter [{name}] can't be decoded: {error}")))
}
#[derive(Debug, Clone, PartialEq)]
pub struct Call {
pub method: String,
pub params: Params,
pub metadata: Map<String, Value>,
}
impl Call {
#[must_use]
pub fn is_signal(&self) -> bool {
matches!(
self.method.as_str(),
"$refresh" | "$commit" | "$set" | "$sync" | "__dispatch" | "__lazyLoad" | "__lazyLoadIsland"
)
}
}
#[derive(Debug, Clone)]
pub struct ComponentContext {
pub id: String,
pub name: String,
pub mounting: bool,
pub request_metadata: Map<String, Value>,
pub effects: Map<String, Value>,
pub memo: Map<String, Value>,
pub request: Option<Arc<Request>>,
pub streamed: Vec<Value>,
}
pub fn coerce<T: DeserializeOwned>(value: &Value) -> std::result::Result<T, serde_json::Error> {
match serde_json::from_value::<T>(value.clone()) {
Ok(value) => Ok(value),
Err(error) => {
let Some(text) = value.as_str() else {
return Err(error);
};
if text.is_empty() {
return serde_json::from_value(Value::Null);
}
serde_json::from_str::<T>(text.trim())
}
}
}
impl ComponentContext {
#[must_use]
pub fn mounting(id: impl Into<String>, name: impl Into<String>, request: Option<Arc<Request>>) -> Self {
Self {
id: id.into(),
name: name.into(),
mounting: true,
request_metadata: Map::new(),
effects: Map::new(),
memo: Map::new(),
request,
streamed: Vec::new(),
}
}
#[must_use]
pub fn updating(id: impl Into<String>, name: impl Into<String>, request: Option<Arc<Request>>) -> Self {
Self {
mounting: false,
..Self::mounting(id, name, request)
}
}
pub async fn validate(&mut self, component: &dyn Component) -> Result<()> {
let mut data = Map::new();
component.dehydrate_fields(&mut data);
let rules = component.validation_rules();
match rules.validate(&data).await {
Ok(()) => Ok(()),
Err(laravel::validation::ValidationError::Invalid(invalid)) => {
let errors = serde_json::to_value(&invalid)
.ok()
.and_then(|value| value.as_object().cloned())
.unwrap_or_default();
for (field, messages) in &errors {
let message = messages
.as_array()
.and_then(|messages| messages.first())
.and_then(Value::as_str)
.unwrap_or_default();
self.add_error(field.clone(), message);
}
Err(LivewireError::ValidationFailed { errors })
}
Err(laravel::validation::ValidationError::Failed(error)) => Err(LivewireError::MalformedPayload(format!(
"a validation rule could not run: {error}"
))),
}
}
pub fn add_error(&mut self, field: impl Into<String>, message: impl Into<String>) {
let request = crate::context::LivewireRequest::current().unwrap_or_default();
let id = self.id.clone();
let field = field.into();
let messages = Value::Array(vec![Value::from(message.into())]);
request.change(&id, |state| {
state.errors.insert(field, messages);
});
}
pub fn stream(&mut self, name: impl Into<String>, content: impl Into<String>) {
self.streamed.push(Value::Object(Map::from_iter([
("stream".to_owned(), Value::Bool(true)),
(
"body".to_owned(),
Value::Object(Map::from_iter([
("id".to_owned(), Value::from(self.id.clone())),
("type".to_owned(), Value::from("directive")),
("name".to_owned(), Value::from(name.into())),
("content".to_owned(), Value::from(content.into())),
])),
),
("endStream".to_owned(), Value::Bool(true)),
])));
}
pub fn add_effect(&mut self, name: &str, value: Value) {
self.effects.insert(name.to_owned(), value);
}
pub fn xjs(&mut self, expression: impl Into<String>) {
self.push_effect(
"xjs",
serde_json::json!({"expression": expression.into(), "params": {}}),
);
}
pub fn push_effect(&mut self, name: &str, value: Value) {
match self.effects.get_mut(name) {
Some(Value::Array(values)) => values.push(value),
Some(existing) => {
let first = std::mem::replace(existing, Value::Array(Vec::new()));
if let Some(Value::Array(values)) = self.effects.get_mut(name) {
values.push(first);
values.push(value);
}
}
None => {
self.effects.insert(name.to_owned(), Value::Array(vec![value]));
}
}
}
pub fn add_memo(&mut self, key: &str, value: Value) {
self.memo.insert(key.to_owned(), value);
}
pub fn download(&mut self, name: impl Into<String>, content: impl AsRef<[u8]>, content_type: impl Into<String>) {
use base64::Engine as _;
self.add_effect(
"download",
serde_json::json!({
"name": name.into(),
"content": base64::engine::general_purpose::STANDARD.encode(content.as_ref()),
"contentType": content_type.into(),
}),
);
self.add_effect("skipRender", Value::Bool(true));
}
#[must_use]
pub fn request(&self) -> Option<&Request> {
self.request.as_deref()
}
pub async fn user<U: laravel::auth::Authenticatable>(&self) -> Result<Option<U>> {
let Some(request) = self.request() else {
return Err(LivewireError::MalformedPayload(
"the component has no request, so it has no user".to_owned(),
));
};
request
.user()
.await
.map_err(|error| LivewireError::MalformedPayload(format!("the request's user can't be read: {error}")))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct WireField {
pub name: &'static str,
pub locked: bool,
pub modelable: bool,
pub reactive: bool,
pub url: Option<UrlBinding>,
pub session: Option<SessionBinding>,
pub synth: Option<&'static str>,
pub rules: &'static [&'static str],
pub type_name: &'static str,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct UrlBinding {
pub as_name: Option<&'static str>,
pub push: bool,
pub always_show: bool,
pub except: &'static str,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SessionBinding {
pub key: Option<&'static str>,
}
pub trait LivewireState: Send + Sync + 'static {
fn wire_fields() -> &'static [WireField]
where
Self: Sized;
fn component_name() -> &'static str
where
Self: Sized,
{
std::any::type_name::<Self>()
}
fn dehydrate_fields(&self, data: &mut Map<String, Value>);
fn hydrate_fields(&mut self, data: &Map<String, Value>) -> Result<()>;
fn set_field(&mut self, field: &str, value: Value) -> Result<()>;
fn render_values(&self, data: &mut Map<String, Value>) {
self.dehydrate_fields(data);
}
fn default_view(&self) -> ComponentView;
fn validation_rules(&self) -> laravel::validation::Rules {
laravel::validation::Rules::new()
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct ClassOptions {
pub layout: Option<&'static str>,
pub title: Option<&'static str>,
pub transition: Option<&'static str>,
pub lazy: bool,
pub defer: bool,
pub isolate: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Listener {
pub event: &'static str,
pub method: Option<&'static str>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ActionResultKind {
#[default]
Ignored,
Returned,
Json,
}
#[async_trait::async_trait]
pub trait Component: LivewireState {
fn boot(&mut self) -> Result<()> {
Ok(())
}
fn initialize(&mut self, context: &mut ComponentContext) -> Result<()> {
let _ = context;
Ok(())
}
fn mount(&mut self, params: Params, context: &mut ComponentContext) -> Result<()> {
let _ = (params, context);
Ok(())
}
fn booted(&mut self) -> Result<()> {
Ok(())
}
fn hydrate(&mut self, context: &mut ComponentContext) -> Result<()> {
let _ = context;
Ok(())
}
fn render(&self) -> Result<ComponentView> {
Ok(self.default_view())
}
fn dehydrate(&mut self, context: &mut ComponentContext) -> Result<()> {
let _ = context;
Ok(())
}
fn destroy(&mut self) {}
fn updating(&mut self, property: &str, value: &Value, context: &mut ComponentContext) -> Result<()> {
let _ = (property, value, context);
Ok(())
}
fn updated(&mut self, property: &str, context: &mut ComponentContext) -> Result<()> {
let _ = (property, context);
Ok(())
}
async fn call(&mut self, call: Call, context: &mut ComponentContext) -> Result<Option<Value>>;
async fn authorize(&mut self, method: &str, context: &ComponentContext) -> Result<bool> {
let _ = (method, context);
Ok(true)
}
async fn hydrate_models(&mut self, context: &mut ComponentContext) -> Result<()> {
let _ = context;
Ok(())
}
fn release_token(&self) -> &'static str {
"a"
}
fn listeners(&self) -> &'static [Listener] {
&[]
}
fn dispatches(&self) -> &'static [Listener] {
&[]
}
fn exception(&mut self, error: &LivewireError, context: &mut ComponentContext) {
let _ = (error, context);
}
fn action_result_kind(&self, method: &str) -> ActionResultKind {
let _ = method;
ActionResultKind::Ignored
}
fn class_options(&self) -> ClassOptions {
ClassOptions::default()
}
fn async_methods(&self) -> &'static [&'static str] {
&[]
}
fn json_methods(&self) -> &'static [&'static str] {
&[]
}
fn computed_values(&self, id: &str) -> Map<String, Value> {
let _ = id;
Map::new()
}
}
#[must_use]
pub fn camel_case(name: &str) -> String {
if !name.contains('-') {
return name.to_owned();
}
let mut out = String::with_capacity(name.len());
let mut upper = false;
for character in name.chars() {
if character == '-' {
upper = true;
} else if upper {
out.extend(character.to_uppercase());
upper = false;
} else {
out.push(character);
}
}
out
}
#[must_use]
pub fn to_wire<T: serde::Serialize>(value: &T) -> Value {
let mut value = serde_json::to_value(value).unwrap_or(Value::Null);
normalize(&mut value);
value
}
fn normalize(value: &mut Value) {
match value {
Value::Number(number) => {
if number
.as_f64()
.is_some_and(|float| float == 0.0 && float.is_sign_negative())
{
*number = serde_json::Number::from(0);
}
}
Value::Array(values) => values.iter_mut().for_each(normalize),
Value::Object(map) => map.values_mut().for_each(normalize),
_ => {}
}
}
#[must_use]
pub fn lookup_scalar(data: &Map<String, Value>, path: &str) -> Option<String> {
let mut current = data;
let mut segments = path.split('.').peekable();
while let Some(segment) = segments.next() {
let value = current.get(segment)?;
if segments.peek().is_none() {
return match value {
Value::String(text) => Some(text.clone()),
Value::Number(number) => Some(number.to_string()),
Value::Bool(flag) => Some(flag.to_string()),
_ => None,
};
}
current = value.as_object()?;
}
None
}
#[cfg(test)]
mod derive_tests {
use super::*;
use crate::{LivewireComponent, component};
#[derive(Default, LivewireComponent)]
#[livewire(view = "livewire.counter")]
struct Counter {
count: i32,
#[livewire(locked)]
id: String,
#[livewire(session(key = "counter-step"))]
step: i32,
#[livewire(validate(required, max_length(255)))]
label: Option<String>,
#[livewire(skip)]
cache: Vec<String>,
}
#[component]
impl Counter {
pub fn mount(&mut self, count: Option<i32>) {
self.count = count.unwrap_or(7);
self.id = "fixed".to_owned();
}
pub fn increment(&mut self, by: i32) {
self.count += by;
}
pub fn describe(&mut self) -> String {
format!("count={}", self.count)
}
pub fn fail(&mut self) -> Result<(), LivewireError> {
Err(LivewireError::MalformedPayload("the action failed".to_owned()))
}
#[livewire(renderless)]
pub fn quietly(&mut self) {}
#[livewire(json)]
pub fn as_json(&mut self) -> serde_json::Value {
serde_json::json!({"ok": true})
}
#[livewire(on = "refresh-counter")]
pub fn refreshed(&mut self) {}
}
fn context() -> ComponentContext {
ComponentContext::mounting("abc", "counter", None)
}
#[test]
fn the_derive_lists_the_wire_public_fields_in_declaration_order() {
let fields = Counter::wire_fields();
assert_eq!(
fields.iter().map(|field| field.name).collect::<Vec<_>>(),
["count", "id", "step", "label"]
);
assert!(
fields
.iter()
.find(|field| field.name == "id")
.is_some_and(|field| field.locked)
);
assert_eq!(
fields
.iter()
.find(|field| field.name == "step")
.and_then(|field| field.session)
.and_then(|session| session.key),
Some("counter-step")
);
assert_eq!(
fields
.iter()
.find(|field| field.name == "label")
.map(|field| field.rules),
Some(&["required", "max_length(255)"][..])
);
}
#[test]
fn a_mount_prop_reaches_its_field_and_the_hook_runs() {
let mut counter = Counter::default();
let mut context = context();
Component::mount(
&mut counter,
Params::Named(Map::from_iter([("count".to_owned(), Value::from(3))])),
&mut context,
)
.expect("mounts");
assert_eq!(counter.count, 3);
assert_eq!(counter.id, "fixed");
}
#[test]
fn a_missing_optional_mount_prop_uses_the_default() {
let mut counter = Counter::default();
Component::mount(&mut counter, Params::default(), &mut context()).expect("mounts");
assert_eq!(counter.count, 7);
}
#[test]
fn a_form_string_reads_into_a_typed_field() {
use super::coerce;
assert_eq!(coerce::<i32>(&Value::from("4")).expect("a numeral"), 4);
assert_eq!(coerce::<i32>(&Value::from(4)).expect("real JSON"), 4);
assert!(coerce::<bool>(&Value::from("true")).expect("a boolean"));
assert_eq!(coerce::<Option<i32>>(&Value::from("")).expect("an emptied field"), None);
assert_eq!(coerce::<String>(&Value::from("plain")).expect("text"), "plain");
assert!(coerce::<i32>(&Value::from("not a number")).is_err());
}
#[test]
fn the_state_round_trips_without_the_skipped_field() {
let mut counter = Counter {
count: 4,
id: "fixed".to_owned(),
step: 2,
label: Some("hi".to_owned()),
cache: vec!["not on the wire".to_owned()],
};
counter.cache.push("still not".to_owned());
let mut data = Map::new();
counter.dehydrate_fields(&mut data);
assert!(!data.contains_key("cache"));
assert_eq!(data["count"], serde_json::json!(4));
let mut restored = Counter::default();
restored.cache.push("kept".to_owned());
restored.hydrate_fields(&data).expect("hydrates");
assert_eq!(restored.count, 4);
assert_eq!(restored.label.as_deref(), Some("hi"));
assert_eq!(restored.cache, ["kept".to_owned()]);
}
#[test]
fn a_locked_field_rejects_updates_but_hydrates() {
let mut counter = Counter::default();
counter
.hydrate_fields(&Map::from_iter([("id".to_owned(), Value::from("from-snapshot"))]))
.expect("hydrates");
assert_eq!(counter.id, "from-snapshot");
let error = counter.set_field("id", Value::from("hacked")).expect_err("locked");
assert!(matches!(error, LivewireError::LockedProperty { .. }));
}
#[test]
fn an_unknown_field_is_reported() {
let mut counter = Counter::default();
let error = counter.set_field("nope", Value::from(1)).expect_err("unknown");
assert!(matches!(error, LivewireError::UnknownProperty { .. }));
assert!(error.to_string().contains("[$nope]"));
}
#[test]
fn an_action_decodes_its_typed_parameters() {
let mut counter = Counter::default();
let value = futures_util::FutureExt::now_or_never(Component::call(
&mut counter,
Call {
method: "increment".to_owned(),
params: Params::List(vec![Value::from(5)]),
metadata: Map::new(),
},
&mut context(),
))
.expect("the action future is ready")
.expect("the action runs");
assert_eq!(value, None);
assert_eq!(counter.count, 5);
}
#[test]
fn a_returning_action_becomes_a_returns_value() {
let mut counter = Counter {
count: 2,
..Counter::default()
};
let value = futures_util::FutureExt::now_or_never(Component::call(
&mut counter,
Call {
method: "describe".to_owned(),
params: Params::default(),
metadata: Map::new(),
},
&mut context(),
))
.expect("ready")
.expect("runs");
assert_eq!(value, Some(serde_json::json!("count=2")));
}
#[test]
fn a_failing_action_propagates_its_error() {
let mut counter = Counter::default();
let error = futures_util::FutureExt::now_or_never(Component::call(
&mut counter,
Call {
method: "fail".to_owned(),
params: Params::default(),
metadata: Map::new(),
},
&mut context(),
))
.expect("ready")
.expect_err("fails");
assert!(error.to_string().contains("the action failed"));
}
#[test]
fn an_unknown_action_is_a_419_error() {
let mut counter = Counter::default();
let error = futures_util::FutureExt::now_or_never(Component::call(
&mut counter,
Call {
method: "deleteEverything".to_owned(),
params: Params::default(),
metadata: Map::new(),
},
&mut context(),
))
.expect("ready")
.expect_err("unknown method");
assert!(matches!(error, LivewireError::MethodNotFound { .. }));
assert_eq!(error.status().as_u16(), 419);
}
#[test]
fn the_refresh_signals_do_nothing() {
let mut counter = Counter::default();
for method in ["$refresh", "$commit", "$sync"] {
let value = futures_util::FutureExt::now_or_never(Component::call(
&mut counter,
Call {
method: method.to_owned(),
params: Params::default(),
metadata: Map::new(),
},
&mut context(),
))
.expect("ready")
.expect("runs");
assert_eq!(value, None, "{method}");
}
}
#[test]
fn action_options_reach_the_response() {
let counter = Counter::default();
assert_eq!(counter.action_result_kind("as_json"), ActionResultKind::Json);
assert_eq!(counter.action_result_kind("increment"), ActionResultKind::Ignored);
let listeners = Component::listeners(&counter);
assert_eq!(listeners.len(), 1);
assert_eq!(listeners[0].event, "refresh-counter");
assert_eq!(listeners[0].method, Some("refreshed"));
}
#[test]
fn a_renderless_action_asks_for_no_html() {
let mut counter = Counter::default();
let mut context = context();
futures_util::FutureExt::now_or_never(Component::call(
&mut counter,
Call {
method: "quietly".to_owned(),
params: Params::default(),
metadata: Map::new(),
},
&mut context,
))
.expect("ready")
.expect("runs");
assert_eq!(context.effects["skipRender"], serde_json::json!(true));
}
#[test]
fn the_default_view_comes_from_the_struct_attribute() {
assert_eq!(
Counter::default().default_view(),
ComponentView::Named("livewire.counter".to_owned())
);
}
#[test]
fn a_computed_property_reaches_the_template_and_is_not_an_action() {
use std::sync::atomic::{AtomicUsize, Ordering};
static CALLS: AtomicUsize = AtomicUsize::new(0);
#[derive(Default, LivewireComponent)]
#[livewire(inline = "<div>{{ doubled }}</div>")]
struct Totals {
count: i32,
}
#[component]
impl Totals {
#[livewire(computed)]
pub fn doubled(&self) -> i32 {
CALLS.fetch_add(1, Ordering::SeqCst);
self.count * 2
}
}
let totals = Totals { count: 4 };
assert_eq!(
Component::computed_values(&totals, "id")["doubled"],
serde_json::json!(8)
);
let error = futures_util::FutureExt::now_or_never(Component::call(
&mut Totals::default(),
Call {
method: "doubled".to_owned(),
params: Params::default(),
metadata: Map::new(),
},
&mut context(),
))
.expect("ready")
.expect_err("not an action");
assert!(matches!(error, LivewireError::MethodNotFound { .. }));
}
#[test]
fn a_negative_zero_is_normalized_on_the_wire() {
assert_eq!(to_wire(&-0.0f64), serde_json::json!(0));
assert_eq!(to_wire(&vec![-0.0f64, 1.5]), serde_json::json!([0, 1.5]));
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn positional_and_named_parameters_reach_the_same_argument() {
let positional = Params::from_json(serde_json::json!([2])).expect("a list");
let named = Params::from_json(serde_json::json!({"by": 2})).expect("an object");
assert_eq!(positional.arg::<i32>("by", 0).expect("decodes"), 2);
assert_eq!(named.arg::<i32>("by", 0).expect("decodes"), 2);
}
#[test]
fn a_missing_argument_is_reported_not_panicked() {
let params = Params::from_json(serde_json::json!([])).expect("a list");
let error = params.arg::<i32>("by", 0).expect_err("missing");
assert!(matches!(error, LivewireError::MalformedPayload(_)));
assert!(error.to_string().contains("[by]"));
}
#[test]
fn an_optional_argument_may_be_absent() {
let params = Params::from_json(serde_json::json!([])).expect("a list");
assert_eq!(params.optional::<i32>("by", 0).expect("absent is fine"), None);
}
#[test]
fn a_wrongly_typed_argument_is_reported() {
let params = Params::from_json(serde_json::json!(["two"])).expect("a list");
let error = params.arg::<i32>("by", 0).expect_err("wrong type");
assert!(error.to_string().contains("can't be decoded"));
}
#[test]
fn mixed_parameters_are_rejected() {
let error = Params::from_json(serde_json::json!("by=2")).expect_err("neither list nor object");
assert!(matches!(error, LivewireError::MalformedPayload(_)));
}
#[test]
fn the_refresh_signals_are_not_component_methods() {
for method in ["$refresh", "$commit", "$set", "$sync", "__dispatch", "__lazyLoad"] {
let call = Call {
method: method.to_owned(),
params: Params::default(),
metadata: Map::new(),
};
assert!(call.is_signal(), "{method}");
}
let call = Call {
method: "increment".to_owned(),
params: Params::default(),
metadata: Map::new(),
};
assert!(!call.is_signal());
}
#[test]
fn effects_collect_into_lists() {
let mut context = ComponentContext::mounting("id", "counter", None);
context.push_effect("dispatches", Value::from("first"));
context.push_effect("dispatches", Value::from("second"));
context.add_effect("xjs", Value::from("console.log(1)"));
assert_eq!(context.effects["dispatches"], serde_json::json!(["first", "second"]));
assert_eq!(context.effects["xjs"], serde_json::json!("console.log(1)"));
}
}