1use std::sync::Arc;
10
11use laravel::http::Request;
12use serde::de::DeserializeOwned;
13use serde_json::{Map, Value};
14
15use crate::error::LivewireError;
16
17pub type Result<T, E = LivewireError> = std::result::Result<T, E>;
19
20#[derive(Debug, Clone, PartialEq)]
22pub enum ComponentView {
23 Named(String),
25 Inline {
28 source: &'static str,
30 data: Map<String, Value>,
32 },
33}
34
35impl ComponentView {
36 #[must_use]
38 pub fn name(&self) -> &str {
39 match self {
40 Self::Named(name) => name,
41 Self::Inline { .. } => "inline",
42 }
43 }
44}
45
46#[derive(Debug, Clone, PartialEq)]
48pub enum Params {
49 List(Vec<Value>),
51 Named(Map<String, Value>),
53}
54
55impl Default for Params {
56 fn default() -> Self {
57 Self::List(Vec::new())
58 }
59}
60
61impl Params {
62 pub fn from_json(value: Value) -> Result<Self> {
65 match value {
66 Value::Array(list) => Ok(Self::List(list)),
67 Value::Object(map) => Ok(Self::Named(map)),
68 Value::Null => Ok(Self::List(Vec::new())),
69 _ => Err(LivewireError::MalformedPayload(
70 "a call's params must be a list or an object".to_owned(),
71 )),
72 }
73 }
74
75 pub fn arg<T: DeserializeOwned>(&self, name: &str, index: usize) -> Result<T> {
80 let value = match self {
81 Self::List(list) => list.get(index).cloned(),
82 Self::Named(map) => map.get(name).cloned().or_else(|| map.get(&index.to_string()).cloned()),
83 };
84
85 match value {
86 Some(value) => decode(value, name),
87 None => Err(LivewireError::MalformedPayload(format!(
88 "the call is missing its parameter [{name}]"
89 ))),
90 }
91 }
92
93 pub fn optional<T: DeserializeOwned>(&self, name: &str, index: usize) -> Result<Option<T>> {
96 let value = match self {
97 Self::List(list) => list.get(index).cloned(),
98 Self::Named(map) => map.get(name).cloned().or_else(|| map.get(&index.to_string()).cloned()),
99 };
100
101 value.map(|value| decode(value, name)).transpose()
102 }
103
104 #[must_use]
106 pub fn is_empty(&self) -> bool {
107 match self {
108 Self::List(list) => list.is_empty(),
109 Self::Named(map) => map.is_empty(),
110 }
111 }
112
113 pub fn decode<T: DeserializeOwned>(self) -> Result<T> {
115 let value = match self {
116 Self::List(list) => Value::Array(list),
117 Self::Named(map) => Value::Object(map),
118 };
119
120 decode(value, "params")
121 }
122}
123
124fn decode<T: DeserializeOwned>(value: Value, name: &str) -> Result<T> {
126 serde_json::from_value(value)
127 .map_err(|error| LivewireError::MalformedPayload(format!("the parameter [{name}] can't be decoded: {error}")))
128}
129
130#[derive(Debug, Clone, PartialEq)]
132pub struct Call {
133 pub method: String,
135 pub params: Params,
137 pub metadata: Map<String, Value>,
139}
140
141impl Call {
142 #[must_use]
145 pub fn is_signal(&self) -> bool {
146 matches!(
147 self.method.as_str(),
148 "$refresh" | "$commit" | "$set" | "$sync" | "__dispatch" | "__lazyLoad" | "__lazyLoadIsland"
149 )
150 }
151}
152
153#[derive(Debug, Clone)]
155pub struct ComponentContext {
156 pub id: String,
158 pub name: String,
160 pub mounting: bool,
162 pub request_metadata: Map<String, Value>,
164 pub effects: Map<String, Value>,
166 pub memo: Map<String, Value>,
168 pub request: Option<Arc<Request>>,
171 pub streamed: Vec<Value>,
173}
174
175pub fn coerce<T: DeserializeOwned>(value: &Value) -> std::result::Result<T, serde_json::Error> {
185 match serde_json::from_value::<T>(value.clone()) {
186 Ok(value) => Ok(value),
187 Err(error) => {
188 let Some(text) = value.as_str() else {
189 return Err(error);
190 };
191
192 if text.is_empty() {
193 return serde_json::from_value(Value::Null);
194 }
195
196 serde_json::from_str::<T>(text.trim())
197 }
198 }
199}
200
201impl ComponentContext {
202 #[must_use]
204 pub fn mounting(id: impl Into<String>, name: impl Into<String>, request: Option<Arc<Request>>) -> Self {
205 Self {
206 id: id.into(),
207 name: name.into(),
208 mounting: true,
209 request_metadata: Map::new(),
210 effects: Map::new(),
211 memo: Map::new(),
212 request,
213 streamed: Vec::new(),
214 }
215 }
216
217 #[must_use]
219 pub fn updating(id: impl Into<String>, name: impl Into<String>, request: Option<Arc<Request>>) -> Self {
220 Self {
221 mounting: false,
222 ..Self::mounting(id, name, request)
223 }
224 }
225
226 pub async fn validate(&mut self, component: &dyn Component) -> Result<()> {
237 let mut data = Map::new();
238 component.dehydrate_fields(&mut data);
239
240 let rules = component.validation_rules();
241
242 match rules.validate(&data).await {
243 Ok(()) => Ok(()),
244 Err(laravel::validation::ValidationError::Invalid(invalid)) => {
245 let errors = serde_json::to_value(&invalid)
246 .ok()
247 .and_then(|value| value.as_object().cloned())
248 .unwrap_or_default();
249
250 for (field, messages) in &errors {
251 let message = messages
252 .as_array()
253 .and_then(|messages| messages.first())
254 .and_then(Value::as_str)
255 .unwrap_or_default();
256
257 self.add_error(field.clone(), message);
258 }
259
260 Err(LivewireError::ValidationFailed { errors })
261 }
262 Err(laravel::validation::ValidationError::Failed(error)) => Err(LivewireError::MalformedPayload(format!(
263 "a validation rule could not run: {error}"
264 ))),
265 }
266 }
267
268 pub fn add_error(&mut self, field: impl Into<String>, message: impl Into<String>) {
271 let request = crate::context::LivewireRequest::current().unwrap_or_default();
272 let id = self.id.clone();
273 let field = field.into();
274 let messages = Value::Array(vec![Value::from(message.into())]);
277
278 request.change(&id, |state| {
279 state.errors.insert(field, messages);
280 });
281 }
282
283 pub fn stream(&mut self, name: impl Into<String>, content: impl Into<String>) {
288 self.streamed.push(Value::Object(Map::from_iter([
289 ("stream".to_owned(), Value::Bool(true)),
290 (
291 "body".to_owned(),
292 Value::Object(Map::from_iter([
293 ("id".to_owned(), Value::from(self.id.clone())),
294 ("type".to_owned(), Value::from("directive")),
295 ("name".to_owned(), Value::from(name.into())),
296 ("content".to_owned(), Value::from(content.into())),
297 ])),
298 ),
299 ("endStream".to_owned(), Value::Bool(true)),
300 ])));
301 }
302
303 pub fn add_effect(&mut self, name: &str, value: Value) {
305 self.effects.insert(name.to_owned(), value);
306 }
307
308 pub fn xjs(&mut self, expression: impl Into<String>) {
313 self.push_effect(
314 "xjs",
315 serde_json::json!({"expression": expression.into(), "params": {}}),
316 );
317 }
318
319 pub fn push_effect(&mut self, name: &str, value: Value) {
321 match self.effects.get_mut(name) {
322 Some(Value::Array(values)) => values.push(value),
323 Some(existing) => {
324 let first = std::mem::replace(existing, Value::Array(Vec::new()));
325 if let Some(Value::Array(values)) = self.effects.get_mut(name) {
326 values.push(first);
327 values.push(value);
328 }
329 }
330 None => {
331 self.effects.insert(name.to_owned(), Value::Array(vec![value]));
332 }
333 }
334 }
335
336 pub fn add_memo(&mut self, key: &str, value: Value) {
338 self.memo.insert(key.to_owned(), value);
339 }
340
341 pub fn download(&mut self, name: impl Into<String>, content: impl AsRef<[u8]>, content_type: impl Into<String>) {
346 use base64::Engine as _;
347
348 self.add_effect(
349 "download",
350 serde_json::json!({
351 "name": name.into(),
352 "content": base64::engine::general_purpose::STANDARD.encode(content.as_ref()),
353 "contentType": content_type.into(),
354 }),
355 );
356 self.add_effect("skipRender", Value::Bool(true));
357 }
358
359 #[must_use]
361 pub fn request(&self) -> Option<&Request> {
362 self.request.as_deref()
363 }
364
365 pub async fn user<U: laravel::auth::Authenticatable>(&self) -> Result<Option<U>> {
371 let Some(request) = self.request() else {
372 return Err(LivewireError::MalformedPayload(
373 "the component has no request, so it has no user".to_owned(),
374 ));
375 };
376
377 request
378 .user()
379 .await
380 .map_err(|error| LivewireError::MalformedPayload(format!("the request's user can't be read: {error}")))
381 }
382}
383
384#[derive(Debug, Clone, Copy, PartialEq, Eq)]
386pub struct WireField {
387 pub name: &'static str,
389 pub locked: bool,
391 pub modelable: bool,
393 pub reactive: bool,
395 pub url: Option<UrlBinding>,
397 pub session: Option<SessionBinding>,
399 pub synth: Option<&'static str>,
401 pub rules: &'static [&'static str],
403 pub type_name: &'static str,
405}
406
407#[derive(Debug, Clone, Copy, PartialEq, Eq)]
409pub struct UrlBinding {
410 pub as_name: Option<&'static str>,
412 pub push: bool,
414 pub always_show: bool,
416 pub except: &'static str,
418}
419
420#[derive(Debug, Clone, Copy, PartialEq, Eq)]
422pub struct SessionBinding {
423 pub key: Option<&'static str>,
425}
426
427pub trait LivewireState: Send + Sync + 'static {
432 fn wire_fields() -> &'static [WireField]
434 where
435 Self: Sized;
436
437 fn component_name() -> &'static str
440 where
441 Self: Sized,
442 {
443 std::any::type_name::<Self>()
444 }
445
446 fn dehydrate_fields(&self, data: &mut Map<String, Value>);
448
449 fn hydrate_fields(&mut self, data: &Map<String, Value>) -> Result<()>;
455
456 fn set_field(&mut self, field: &str, value: Value) -> Result<()>;
462
463 fn render_values(&self, data: &mut Map<String, Value>) {
469 self.dehydrate_fields(data);
470 }
471
472 fn default_view(&self) -> ComponentView;
474
475 fn validation_rules(&self) -> laravel::validation::Rules {
480 laravel::validation::Rules::new()
481 }
482}
483
484#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
486pub struct ClassOptions {
487 pub layout: Option<&'static str>,
489 pub title: Option<&'static str>,
491 pub transition: Option<&'static str>,
493 pub lazy: bool,
495 pub defer: bool,
497 pub isolate: bool,
499}
500
501#[derive(Debug, Clone, Copy, PartialEq, Eq)]
503pub struct Listener {
504 pub event: &'static str,
506 pub method: Option<&'static str>,
508}
509
510#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
512pub enum ActionResultKind {
513 #[default]
515 Ignored,
516 Returned,
518 Json,
520}
521
522#[async_trait::async_trait]
529pub trait Component: LivewireState {
530 fn boot(&mut self) -> Result<()> {
532 Ok(())
533 }
534
535 fn initialize(&mut self, context: &mut ComponentContext) -> Result<()> {
537 let _ = context;
538 Ok(())
539 }
540
541 fn mount(&mut self, params: Params, context: &mut ComponentContext) -> Result<()> {
547 let _ = (params, context);
548 Ok(())
549 }
550
551 fn booted(&mut self) -> Result<()> {
553 Ok(())
554 }
555
556 fn hydrate(&mut self, context: &mut ComponentContext) -> Result<()> {
558 let _ = context;
559 Ok(())
560 }
561
562 fn render(&self) -> Result<ComponentView> {
568 Ok(self.default_view())
569 }
570
571 fn dehydrate(&mut self, context: &mut ComponentContext) -> Result<()> {
573 let _ = context;
574 Ok(())
575 }
576
577 fn destroy(&mut self) {}
579
580 fn updating(&mut self, property: &str, value: &Value, context: &mut ComponentContext) -> Result<()> {
582 let _ = (property, value, context);
583 Ok(())
584 }
585
586 fn updated(&mut self, property: &str, context: &mut ComponentContext) -> Result<()> {
588 let _ = (property, context);
589 Ok(())
590 }
591
592 async fn call(&mut self, call: Call, context: &mut ComponentContext) -> Result<Option<Value>>;
598
599 async fn authorize(&mut self, method: &str, context: &ComponentContext) -> Result<bool> {
605 let _ = (method, context);
606 Ok(true)
607 }
608
609 async fn hydrate_models(&mut self, context: &mut ComponentContext) -> Result<()> {
615 let _ = context;
616
617 Ok(())
618 }
619
620 fn release_token(&self) -> &'static str {
622 "a"
623 }
624
625 fn listeners(&self) -> &'static [Listener] {
627 &[]
628 }
629
630 fn dispatches(&self) -> &'static [Listener] {
632 &[]
633 }
634
635 fn exception(&mut self, error: &LivewireError, context: &mut ComponentContext) {
637 let _ = (error, context);
638 }
639
640 fn action_result_kind(&self, method: &str) -> ActionResultKind {
642 let _ = method;
643 ActionResultKind::Ignored
644 }
645
646 fn class_options(&self) -> ClassOptions {
648 ClassOptions::default()
649 }
650
651 fn async_methods(&self) -> &'static [&'static str] {
653 &[]
654 }
655
656 fn json_methods(&self) -> &'static [&'static str] {
658 &[]
659 }
660
661 fn computed_values(&self, id: &str) -> Map<String, Value> {
666 let _ = id;
667 Map::new()
668 }
669}
670
671#[must_use]
676pub fn camel_case(name: &str) -> String {
677 if !name.contains('-') {
678 return name.to_owned();
679 }
680
681 let mut out = String::with_capacity(name.len());
682 let mut upper = false;
683 for character in name.chars() {
684 if character == '-' {
685 upper = true;
686 } else if upper {
687 out.extend(character.to_uppercase());
688 upper = false;
689 } else {
690 out.push(character);
691 }
692 }
693 out
694}
695
696#[must_use]
698pub fn to_wire<T: serde::Serialize>(value: &T) -> Value {
699 let mut value = serde_json::to_value(value).unwrap_or(Value::Null);
700 normalize(&mut value);
701 value
702}
703
704fn normalize(value: &mut Value) {
706 match value {
707 Value::Number(number) => {
708 if number
709 .as_f64()
710 .is_some_and(|float| float == 0.0 && float.is_sign_negative())
711 {
712 *number = serde_json::Number::from(0);
713 }
714 }
715 Value::Array(values) => values.iter_mut().for_each(normalize),
716 Value::Object(map) => map.values_mut().for_each(normalize),
717 _ => {}
718 }
719}
720
721#[must_use]
723pub fn lookup_scalar(data: &Map<String, Value>, path: &str) -> Option<String> {
724 let mut current = data;
725 let mut segments = path.split('.').peekable();
726
727 while let Some(segment) = segments.next() {
728 let value = current.get(segment)?;
729
730 if segments.peek().is_none() {
731 return match value {
732 Value::String(text) => Some(text.clone()),
733 Value::Number(number) => Some(number.to_string()),
734 Value::Bool(flag) => Some(flag.to_string()),
735 _ => None,
736 };
737 }
738
739 current = value.as_object()?;
740 }
741
742 None
743}
744
745#[cfg(test)]
746mod derive_tests {
747 use super::*;
748 use crate::{LivewireComponent, component};
749
750 #[derive(Default, LivewireComponent)]
751 #[livewire(view = "livewire.counter")]
752 struct Counter {
753 count: i32,
754 #[livewire(locked)]
755 id: String,
756 #[livewire(session(key = "counter-step"))]
757 step: i32,
758 #[livewire(validate(required, max_length(255)))]
759 label: Option<String>,
760 #[livewire(skip)]
761 cache: Vec<String>,
762 }
763
764 #[component]
765 impl Counter {
766 pub fn mount(&mut self, count: Option<i32>) {
767 self.count = count.unwrap_or(7);
768 self.id = "fixed".to_owned();
769 }
770
771 pub fn increment(&mut self, by: i32) {
772 self.count += by;
773 }
774
775 pub fn describe(&mut self) -> String {
776 format!("count={}", self.count)
777 }
778
779 pub fn fail(&mut self) -> Result<(), LivewireError> {
780 Err(LivewireError::MalformedPayload("the action failed".to_owned()))
781 }
782
783 #[livewire(renderless)]
784 pub fn quietly(&mut self) {}
785
786 #[livewire(json)]
787 pub fn as_json(&mut self) -> serde_json::Value {
788 serde_json::json!({"ok": true})
789 }
790
791 #[livewire(on = "refresh-counter")]
792 pub fn refreshed(&mut self) {}
793 }
794
795 fn context() -> ComponentContext {
796 ComponentContext::mounting("abc", "counter", None)
797 }
798
799 #[test]
800 fn the_derive_lists_the_wire_public_fields_in_declaration_order() {
801 let fields = Counter::wire_fields();
802
803 assert_eq!(
804 fields.iter().map(|field| field.name).collect::<Vec<_>>(),
805 ["count", "id", "step", "label"]
806 );
807 assert!(
808 fields
809 .iter()
810 .find(|field| field.name == "id")
811 .is_some_and(|field| field.locked)
812 );
813 assert_eq!(
814 fields
815 .iter()
816 .find(|field| field.name == "step")
817 .and_then(|field| field.session)
818 .and_then(|session| session.key),
819 Some("counter-step")
820 );
821 assert_eq!(
822 fields
823 .iter()
824 .find(|field| field.name == "label")
825 .map(|field| field.rules),
826 Some(&["required", "max_length(255)"][..])
827 );
828 }
829
830 #[test]
831 fn a_mount_prop_reaches_its_field_and_the_hook_runs() {
832 let mut counter = Counter::default();
833 let mut context = context();
834
835 Component::mount(
836 &mut counter,
837 Params::Named(Map::from_iter([("count".to_owned(), Value::from(3))])),
838 &mut context,
839 )
840 .expect("mounts");
841
842 assert_eq!(counter.count, 3);
844 assert_eq!(counter.id, "fixed");
845 }
846
847 #[test]
848 fn a_missing_optional_mount_prop_uses_the_default() {
849 let mut counter = Counter::default();
850
851 Component::mount(&mut counter, Params::default(), &mut context()).expect("mounts");
852
853 assert_eq!(counter.count, 7);
854 }
855
856 #[test]
857 fn a_form_string_reads_into_a_typed_field() {
858 use super::coerce;
859
860 assert_eq!(coerce::<i32>(&Value::from("4")).expect("a numeral"), 4);
861 assert_eq!(coerce::<i32>(&Value::from(4)).expect("real JSON"), 4);
862 assert!(coerce::<bool>(&Value::from("true")).expect("a boolean"));
863 assert_eq!(coerce::<Option<i32>>(&Value::from("")).expect("an emptied field"), None);
864 assert_eq!(coerce::<String>(&Value::from("plain")).expect("text"), "plain");
865 assert!(coerce::<i32>(&Value::from("not a number")).is_err());
866 }
867
868 #[test]
869 fn the_state_round_trips_without_the_skipped_field() {
870 let mut counter = Counter {
871 count: 4,
872 id: "fixed".to_owned(),
873 step: 2,
874 label: Some("hi".to_owned()),
875 cache: vec!["not on the wire".to_owned()],
876 };
877 counter.cache.push("still not".to_owned());
878
879 let mut data = Map::new();
880 counter.dehydrate_fields(&mut data);
881
882 assert!(!data.contains_key("cache"));
883 assert_eq!(data["count"], serde_json::json!(4));
884
885 let mut restored = Counter::default();
886 restored.cache.push("kept".to_owned());
887 restored.hydrate_fields(&data).expect("hydrates");
888
889 assert_eq!(restored.count, 4);
890 assert_eq!(restored.label.as_deref(), Some("hi"));
891 assert_eq!(restored.cache, ["kept".to_owned()]);
893 }
894
895 #[test]
896 fn a_locked_field_rejects_updates_but_hydrates() {
897 let mut counter = Counter::default();
898 counter
899 .hydrate_fields(&Map::from_iter([("id".to_owned(), Value::from("from-snapshot"))]))
900 .expect("hydrates");
901 assert_eq!(counter.id, "from-snapshot");
902
903 let error = counter.set_field("id", Value::from("hacked")).expect_err("locked");
904 assert!(matches!(error, LivewireError::LockedProperty { .. }));
905 }
906
907 #[test]
908 fn an_unknown_field_is_reported() {
909 let mut counter = Counter::default();
910
911 let error = counter.set_field("nope", Value::from(1)).expect_err("unknown");
912
913 assert!(matches!(error, LivewireError::UnknownProperty { .. }));
914 assert!(error.to_string().contains("[$nope]"));
915 }
916
917 #[test]
918 fn an_action_decodes_its_typed_parameters() {
919 let mut counter = Counter::default();
920
921 let value = futures_util::FutureExt::now_or_never(Component::call(
922 &mut counter,
923 Call {
924 method: "increment".to_owned(),
925 params: Params::List(vec![Value::from(5)]),
926 metadata: Map::new(),
927 },
928 &mut context(),
929 ))
930 .expect("the action future is ready")
931 .expect("the action runs");
932
933 assert_eq!(value, None);
934 assert_eq!(counter.count, 5);
935 }
936
937 #[test]
938 fn a_returning_action_becomes_a_returns_value() {
939 let mut counter = Counter {
940 count: 2,
941 ..Counter::default()
942 };
943
944 let value = futures_util::FutureExt::now_or_never(Component::call(
945 &mut counter,
946 Call {
947 method: "describe".to_owned(),
948 params: Params::default(),
949 metadata: Map::new(),
950 },
951 &mut context(),
952 ))
953 .expect("ready")
954 .expect("runs");
955
956 assert_eq!(value, Some(serde_json::json!("count=2")));
957 }
958
959 #[test]
960 fn a_failing_action_propagates_its_error() {
961 let mut counter = Counter::default();
962
963 let error = futures_util::FutureExt::now_or_never(Component::call(
964 &mut counter,
965 Call {
966 method: "fail".to_owned(),
967 params: Params::default(),
968 metadata: Map::new(),
969 },
970 &mut context(),
971 ))
972 .expect("ready")
973 .expect_err("fails");
974
975 assert!(error.to_string().contains("the action failed"));
976 }
977
978 #[test]
979 fn an_unknown_action_is_a_419_error() {
980 let mut counter = Counter::default();
981
982 let error = futures_util::FutureExt::now_or_never(Component::call(
983 &mut counter,
984 Call {
985 method: "deleteEverything".to_owned(),
986 params: Params::default(),
987 metadata: Map::new(),
988 },
989 &mut context(),
990 ))
991 .expect("ready")
992 .expect_err("unknown method");
993
994 assert!(matches!(error, LivewireError::MethodNotFound { .. }));
995 assert_eq!(error.status().as_u16(), 419);
996 }
997
998 #[test]
999 fn the_refresh_signals_do_nothing() {
1000 let mut counter = Counter::default();
1001
1002 for method in ["$refresh", "$commit", "$sync"] {
1003 let value = futures_util::FutureExt::now_or_never(Component::call(
1004 &mut counter,
1005 Call {
1006 method: method.to_owned(),
1007 params: Params::default(),
1008 metadata: Map::new(),
1009 },
1010 &mut context(),
1011 ))
1012 .expect("ready")
1013 .expect("runs");
1014 assert_eq!(value, None, "{method}");
1015 }
1016 }
1017
1018 #[test]
1019 fn action_options_reach_the_response() {
1020 let counter = Counter::default();
1021
1022 assert_eq!(counter.action_result_kind("as_json"), ActionResultKind::Json);
1023 assert_eq!(counter.action_result_kind("increment"), ActionResultKind::Ignored);
1024
1025 let listeners = Component::listeners(&counter);
1026 assert_eq!(listeners.len(), 1);
1027 assert_eq!(listeners[0].event, "refresh-counter");
1028 assert_eq!(listeners[0].method, Some("refreshed"));
1029 }
1030
1031 #[test]
1032 fn a_renderless_action_asks_for_no_html() {
1033 let mut counter = Counter::default();
1034 let mut context = context();
1035
1036 futures_util::FutureExt::now_or_never(Component::call(
1037 &mut counter,
1038 Call {
1039 method: "quietly".to_owned(),
1040 params: Params::default(),
1041 metadata: Map::new(),
1042 },
1043 &mut context,
1044 ))
1045 .expect("ready")
1046 .expect("runs");
1047
1048 assert_eq!(context.effects["skipRender"], serde_json::json!(true));
1049 }
1050
1051 #[test]
1052 fn the_default_view_comes_from_the_struct_attribute() {
1053 assert_eq!(
1054 Counter::default().default_view(),
1055 ComponentView::Named("livewire.counter".to_owned())
1056 );
1057 }
1058
1059 #[test]
1060 fn a_computed_property_reaches_the_template_and_is_not_an_action() {
1061 use std::sync::atomic::{AtomicUsize, Ordering};
1062
1063 static CALLS: AtomicUsize = AtomicUsize::new(0);
1064
1065 #[derive(Default, LivewireComponent)]
1066 #[livewire(inline = "<div>{{ doubled }}</div>")]
1067 struct Totals {
1068 count: i32,
1069 }
1070
1071 #[component]
1072 impl Totals {
1073 #[livewire(computed)]
1074 pub fn doubled(&self) -> i32 {
1075 CALLS.fetch_add(1, Ordering::SeqCst);
1076 self.count * 2
1077 }
1078 }
1079
1080 let totals = Totals { count: 4 };
1081
1082 assert_eq!(
1083 Component::computed_values(&totals, "id")["doubled"],
1084 serde_json::json!(8)
1085 );
1086
1087 let error = futures_util::FutureExt::now_or_never(Component::call(
1089 &mut Totals::default(),
1090 Call {
1091 method: "doubled".to_owned(),
1092 params: Params::default(),
1093 metadata: Map::new(),
1094 },
1095 &mut context(),
1096 ))
1097 .expect("ready")
1098 .expect_err("not an action");
1099
1100 assert!(matches!(error, LivewireError::MethodNotFound { .. }));
1101 }
1102
1103 #[test]
1104 fn a_negative_zero_is_normalized_on_the_wire() {
1105 assert_eq!(to_wire(&-0.0f64), serde_json::json!(0));
1106 assert_eq!(to_wire(&vec![-0.0f64, 1.5]), serde_json::json!([0, 1.5]));
1107 }
1108}
1109
1110#[cfg(test)]
1111mod tests {
1112 use super::*;
1113
1114 #[test]
1115 fn positional_and_named_parameters_reach_the_same_argument() {
1116 let positional = Params::from_json(serde_json::json!([2])).expect("a list");
1117 let named = Params::from_json(serde_json::json!({"by": 2})).expect("an object");
1118
1119 assert_eq!(positional.arg::<i32>("by", 0).expect("decodes"), 2);
1120 assert_eq!(named.arg::<i32>("by", 0).expect("decodes"), 2);
1121 }
1122
1123 #[test]
1124 fn a_missing_argument_is_reported_not_panicked() {
1125 let params = Params::from_json(serde_json::json!([])).expect("a list");
1126
1127 let error = params.arg::<i32>("by", 0).expect_err("missing");
1128
1129 assert!(matches!(error, LivewireError::MalformedPayload(_)));
1130 assert!(error.to_string().contains("[by]"));
1131 }
1132
1133 #[test]
1134 fn an_optional_argument_may_be_absent() {
1135 let params = Params::from_json(serde_json::json!([])).expect("a list");
1136
1137 assert_eq!(params.optional::<i32>("by", 0).expect("absent is fine"), None);
1138 }
1139
1140 #[test]
1141 fn a_wrongly_typed_argument_is_reported() {
1142 let params = Params::from_json(serde_json::json!(["two"])).expect("a list");
1143
1144 let error = params.arg::<i32>("by", 0).expect_err("wrong type");
1145
1146 assert!(error.to_string().contains("can't be decoded"));
1147 }
1148
1149 #[test]
1150 fn mixed_parameters_are_rejected() {
1151 let error = Params::from_json(serde_json::json!("by=2")).expect_err("neither list nor object");
1152
1153 assert!(matches!(error, LivewireError::MalformedPayload(_)));
1154 }
1155
1156 #[test]
1157 fn the_refresh_signals_are_not_component_methods() {
1158 for method in ["$refresh", "$commit", "$set", "$sync", "__dispatch", "__lazyLoad"] {
1159 let call = Call {
1160 method: method.to_owned(),
1161 params: Params::default(),
1162 metadata: Map::new(),
1163 };
1164 assert!(call.is_signal(), "{method}");
1165 }
1166
1167 let call = Call {
1168 method: "increment".to_owned(),
1169 params: Params::default(),
1170 metadata: Map::new(),
1171 };
1172 assert!(!call.is_signal());
1173 }
1174
1175 #[test]
1176 fn effects_collect_into_lists() {
1177 let mut context = ComponentContext::mounting("id", "counter", None);
1178
1179 context.push_effect("dispatches", Value::from("first"));
1180 context.push_effect("dispatches", Value::from("second"));
1181 context.add_effect("xjs", Value::from("console.log(1)"));
1182
1183 assert_eq!(context.effects["dispatches"], serde_json::json!(["first", "second"]));
1184 assert_eq!(context.effects["xjs"], serde_json::json!("console.log(1)"));
1185 }
1186}