Skip to main content

livewire/
component.rs

1//! The authoring contract: what a component is, what it renders, and how the browser's calls reach
2//! it.
3//!
4//! A component is a Rust struct whose fields are the wire-public state, plus an inherent
5//! implementation annotated with [`#[livewire::component]`](macro@livewire::component) that
6//! publishes its actions. The derive macro writes [`LivewireState`], so the server never reflects
7//! over a type at runtime.
8
9use std::sync::Arc;
10
11use laravel::http::Request;
12use serde::de::DeserializeOwned;
13use serde_json::{Map, Value};
14
15use crate::error::LivewireError;
16
17/// The result of an operation in this crate.
18pub type Result<T, E = LivewireError> = std::result::Result<T, E>;
19
20/// What a component's `render` asks the engine to render.
21#[derive(Debug, Clone, PartialEq)]
22pub enum ComponentView {
23    /// A template found through the view finder, such as `livewire.counter`.
24    Named(String),
25    /// Markup written in the component module, rendered with `data` on top of the component's
26    /// fields.
27    Inline {
28        /// The template source.
29        source: &'static str,
30        /// Extra data the source renders with.
31        data: Map<String, Value>,
32    },
33}
34
35impl ComponentView {
36    /// The view name, or `inline` for a component that carries its own source.
37    #[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/// One action call's parameters, as the browser sent them.
47#[derive(Debug, Clone, PartialEq)]
48pub enum Params {
49    /// Positional parameters, in the order the action declared them.
50    List(Vec<Value>),
51    /// Named parameters, as `{param: 'value'}` sent them.
52    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    /// Reads the parameters the browser sent, rejecting anything that is neither a list nor an
63    /// object.
64    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    /// The parameter at `index`, or under `name`.
76    ///
77    /// The macro-generated dispatch reads each declared parameter this way, so a browser that
78    /// sends named parameters and one that sends positional ones both reach the same action.
79    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    /// The parameter at `index`, or under `name`, or `None` when the browser sent neither, for an
94    /// optional parameter.
95    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    /// Whether the browser sent no parameters at all.
105    #[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    /// Decodes the whole parameter list into `T`, for actions that take one struct.
114    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
124/// Decodes one wire value into the parameter's Rust type.
125fn 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/// One action call, as the browser sent it.
131#[derive(Debug, Clone, PartialEq)]
132pub struct Call {
133    /// The method the browser called.
134    pub method: String,
135    /// The call's parameters.
136    pub params: Params,
137    /// Per-call metadata, such as the island the call came from.
138    pub metadata: Map<String, Value>,
139}
140
141impl Call {
142    /// Whether the call is one of the refresh-only signals the client sends, which do not name a
143    /// method of the component.
144    #[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/// The context one lifecycle hook or action receives.
154#[derive(Debug, Clone)]
155pub struct ComponentContext {
156    /// The component's instance ID.
157    pub id: String,
158    /// The component's registered name, such as `counter`.
159    pub name: String,
160    /// Whether this render is the component's first.
161    pub mounting: bool,
162    /// Metadata the browser sent with the call, such as `island` or `async`.
163    pub request_metadata: Map<String, Value>,
164    /// Effects the component adds during this request.
165    pub effects: Map<String, Value>,
166    /// Memo entries the component adds during this request.
167    pub memo: Map<String, Value>,
168    /// The browser's request, so an action can read the signed-in user, run a policy, or use a
169    /// service without the framework cloning the request per component.
170    pub request: Option<Arc<Request>>,
171    /// The frames an action streamed, in the order it wrote them.
172    pub streamed: Vec<Value>,
173}
174
175/// Reads a browser-sent value into a field's type, accepting the strings form inputs send.
176///
177/// `wire:model` sends `"4"` for a number field and `""` for an emptied one; a snapshot this crate
178/// wrote carries real JSON types. Both reach here, so a value that is already the field's type is
179/// read as it is, and a string is read as JSON text, with the empty string as `null`.
180///
181/// # Errors
182///
183/// Returns the decoder's error when neither reading fits the type.
184pub 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    /// A context for a component that is mounting, in a request that has `request`.
203    #[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    /// A context for a component that is updating.
218    #[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    /// Runs the component's declared rules against its current state.
227    ///
228    /// Every failing field's first message is recorded in the snapshot's `memo.errors`, which the
229    /// browser's `$errors` reads, and the whole set comes back in [`LivewireError::ValidationFailed`]
230    /// so the caller can answer without an HTTP failure.
231    ///
232    /// # Errors
233    ///
234    /// Returns [`LivewireError::ValidationFailed`] when a rule rejects a field, and the framework's
235    /// own error when a rule could not run at all, such as a check that needs the database.
236    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    /// Records a validation error for `field`, which the browser reads from the snapshot's
269    /// `memo.errors` and shows through `$errors`.
270    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        // The client's `$errors.first(field)` reads `messages[0]`, so each field maps to a list of
275        // messages, as upstream sends it.
276        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    /// Sends `content` to the element marked `wire:stream="name"`, as the action runs.
284    ///
285    /// The browser appends it as the frame arrives, so a long action can show progress; the
286    /// ordinary response follows the frames.
287    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    /// Adds `value` under `name`, replacing any value already there.
304    pub fn add_effect(&mut self, name: &str, value: Value) {
305        self.effects.insert(name.to_owned(), value);
306    }
307
308    /// Queues a JavaScript expression the browser evaluates once the answer morphed.
309    ///
310    /// The client reads `effects.xjs` as a list of `{expression, params}` entries, so a second
311    /// call appends instead of replacing what the first one asked for.
312    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    /// Adds `value` to the list under `name`, keeping a list that is already there.
320    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    /// Adds a memo entry.
337    pub fn add_memo(&mut self, key: &str, value: Value) {
338        self.memo.insert(key.to_owned(), value);
339    }
340
341    /// Sends `content` to the browser as a file, instead of replacing the component's markup.
342    ///
343    /// The response carries the file base64-encoded in the `download` effect, which the runtime
344    /// turns into a save dialog; the component renders nothing.
345    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    /// The browser's request, or `None` when the component rendered outside a request.
360    #[must_use]
361    pub fn request(&self) -> Option<&Request> {
362        self.request.as_deref()
363    }
364
365    /// The signed-in user of the browser's request.
366    ///
367    /// # Errors
368    ///
369    /// Fails when the component rendered outside a request.
370    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/// One wire-public field's rules, generated by the derive in declaration order.
385#[derive(Debug, Clone, Copy, PartialEq, Eq)]
386pub struct WireField {
387    /// The field's name on the wire.
388    pub name: &'static str,
389    /// Whether the browser may change the field at all.
390    pub locked: bool,
391    /// Whether a parent component may bind the field with `wire:model`.
392    pub modelable: bool,
393    /// Whether the field resets the component when its parent changes it.
394    pub reactive: bool,
395    /// The query string binding of a `#[livewire(url)]` field.
396    pub url: Option<UrlBinding>,
397    /// The session binding of a `#[livewire(session)]` field.
398    pub session: Option<SessionBinding>,
399    /// The synthesizer that reads and writes the field, when it needs one.
400    pub synth: Option<&'static str>,
401    /// The validation rules the field declares, in the framework's rule syntax.
402    pub rules: &'static [&'static str],
403    /// The Rust type the field declares, for diagnostics and the testing helpers.
404    pub type_name: &'static str,
405}
406
407/// How a field follows the page's query string.
408#[derive(Debug, Clone, Copy, PartialEq, Eq)]
409pub struct UrlBinding {
410    /// The query string key, which defaults to the field name.
411    pub as_name: Option<&'static str>,
412    /// Whether a change pushes a history entry or replaces the current one.
413    pub push: bool,
414    /// Whether the key stays in the query string when the field is at its default.
415    pub always_show: bool,
416    /// Keys to leave out of the generated query string.
417    pub except: &'static str,
418}
419
420/// How a field persists in the session.
421#[derive(Debug, Clone, Copy, PartialEq, Eq)]
422pub struct SessionBinding {
423    /// The session key, or `None` for the key derived from the component and field names.
424    pub key: Option<&'static str>,
425}
426
427/// The wire-public state of a component, generated by `#[derive(LivewireComponent)]`.
428///
429/// The derive writes one arm per field in declaration order, so the server never reflects over a
430/// type at runtime and skipped fields never touch the wire.
431pub trait LivewireState: Send + Sync + 'static {
432    /// The wire-public fields, in declaration order.
433    fn wire_fields() -> &'static [WireField]
434    where
435        Self: Sized;
436
437    /// The component's name, which the registry replaces with the name the application registered
438    /// and which diagnostics use until then.
439    fn component_name() -> &'static str
440    where
441        Self: Sized,
442    {
443        std::any::type_name::<Self>()
444    }
445
446    /// Writes the wire-public fields into `data`, in declaration order.
447    fn dehydrate_fields(&self, data: &mut Map<String, Value>);
448
449    /// Reads the fields present in `data`. A field that is absent keeps its default.
450    ///
451    /// # Errors
452    ///
453    /// Fails when a present value cannot be hydrated into its field.
454    fn hydrate_fields(&mut self, data: &Map<String, Value>) -> Result<()>;
455
456    /// Sets one wire-public field, without interpreting dots in its name.
457    ///
458    /// # Errors
459    ///
460    /// Fails when the field is not wire-public, or when the value cannot be assigned.
461    fn set_field(&mut self, field: &str, value: Value) -> Result<()>;
462
463    /// The values a template reads, which are the fields as they cross the wire unless the
464    /// component shows more.
465    ///
466    /// The derive overrides this for `#[livewire(model)]` fields: the view reads the fetched row,
467    /// while the snapshot keeps only the reference.
468    fn render_values(&self, data: &mut Map<String, Value>) {
469        self.dehydrate_fields(data);
470    }
471
472    /// The view the component renders by default.
473    fn default_view(&self) -> ComponentView;
474
475    /// The rules the component's fields declare, ready to run against its own state.
476    ///
477    /// The derive generates this from `#[livewire(validate(..))]`; a component without those
478    /// returns an empty set.
479    fn validation_rules(&self) -> laravel::validation::Rules {
480        laravel::validation::Rules::new()
481    }
482}
483
484/// The options a class-level `#[component(..)]` attribute declares.
485#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
486pub struct ClassOptions {
487    /// The layout a page component renders inside, or `None` for the configured default.
488    pub layout: Option<&'static str>,
489    /// The page title a page component sets.
490    pub title: Option<&'static str>,
491    /// The Alpine transition the component's updates use.
492    pub transition: Option<&'static str>,
493    /// Whether the component renders a placeholder first and loads itself afterwards.
494    pub lazy: bool,
495    /// Whether the component loads itself after the page has loaded.
496    pub defer: bool,
497    /// Whether the component's requests skip the components around it.
498    pub isolate: bool,
499}
500
501/// A listener or dispatch a component declares statically.
502#[derive(Debug, Clone, Copy, PartialEq, Eq)]
503pub struct Listener {
504    /// The event name. A `{placeholder}` is filled from the component's state.
505    pub event: &'static str,
506    /// The method that runs, when the listener does not run the method of the same name.
507    pub method: Option<&'static str>,
508}
509
510/// What an action's return value means to the response.
511#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
512pub enum ActionResultKind {
513    /// The action's return value is ignored.
514    #[default]
515    Ignored,
516    /// The action's return value is a `returns` effect, which the browser's promise resolves with.
517    Returned,
518    /// The action answers with JSON instead of new HTML, and its return value is the body.
519    Json,
520}
521
522/// A component: wire-public state plus the lifecycle the server runs around it.
523///
524/// Every method has a default, so a component implements only the hooks it needs. The derive and
525/// [`#[livewire::component]`](macro@livewire::component) generate the state methods and the action
526/// dispatch; an inherent method is reachable from the browser only when it appears in the annotated
527/// implementation.
528#[async_trait::async_trait]
529pub trait Component: LivewireState {
530    /// Runs before the component mounts or hydrates, on every request.
531    fn boot(&mut self) -> Result<()> {
532        Ok(())
533    }
534
535    /// Runs after `boot`, before the component mounts or hydrates.
536    fn initialize(&mut self, context: &mut ComponentContext) -> Result<()> {
537        let _ = context;
538        Ok(())
539    }
540
541    /// Runs when the component first appears on the page.
542    ///
543    /// # Errors
544    ///
545    /// Fails when the props cannot be read into the component's fields.
546    fn mount(&mut self, params: Params, context: &mut ComponentContext) -> Result<()> {
547        let _ = (params, context);
548        Ok(())
549    }
550
551    /// Runs after the component mounted, on its first request.
552    fn booted(&mut self) -> Result<()> {
553        Ok(())
554    }
555
556    /// Runs when a later request rebuilds the component from its snapshot.
557    fn hydrate(&mut self, context: &mut ComponentContext) -> Result<()> {
558        let _ = context;
559        Ok(())
560    }
561
562    /// Produces the component's markup.
563    ///
564    /// # Errors
565    ///
566    /// Fails when the component cannot name its view or its data.
567    fn render(&self) -> Result<ComponentView> {
568        Ok(self.default_view())
569    }
570
571    /// Runs before the snapshot is written.
572    fn dehydrate(&mut self, context: &mut ComponentContext) -> Result<()> {
573        let _ = context;
574        Ok(())
575    }
576
577    /// Runs after the response is built, when the component instance is dropped.
578    fn destroy(&mut self) {}
579
580    /// Runs before an update assigns `property`.
581    fn updating(&mut self, property: &str, value: &Value, context: &mut ComponentContext) -> Result<()> {
582        let _ = (property, value, context);
583        Ok(())
584    }
585
586    /// Runs after every update of a batch is assigned.
587    fn updated(&mut self, property: &str, context: &mut ComponentContext) -> Result<()> {
588        let _ = (property, context);
589        Ok(())
590    }
591
592    /// Runs one action the browser called.
593    ///
594    /// # Errors
595    ///
596    /// Fails when the method is unknown, its parameters do not decode, or the action fails.
597    async fn call(&mut self, call: Call, context: &mut ComponentContext) -> Result<Option<Value>>;
598
599    /// Whether the browser may run `method`, which an action's `authorize` path decides.
600    ///
601    /// # Errors
602    ///
603    /// Fails when the policy itself cannot run.
604    async fn authorize(&mut self, method: &str, context: &ComponentContext) -> Result<bool> {
605        let _ = (method, context);
606        Ok(true)
607    }
608
609    /// Fetches the model references this component holds, before the hooks, the actions, and the
610    /// render read them.
611    ///
612    /// The derive generates this for `#[livewire(model)]` fields; a component without one keeps the
613    /// default, which resolves nothing.
614    async fn hydrate_models(&mut self, context: &mut ComponentContext) -> Result<()> {
615        let _ = context;
616
617        Ok(())
618    }
619
620    /// The token a redeployment changes, so a stale browser page is asked to reload.
621    fn release_token(&self) -> &'static str {
622        "a"
623    }
624
625    /// The events the component listens to.
626    fn listeners(&self) -> &'static [Listener] {
627        &[]
628    }
629
630    /// The events the component dispatches when it mounts.
631    fn dispatches(&self) -> &'static [Listener] {
632        &[]
633    }
634
635    /// Runs when an action failed, before the failure becomes a response.
636    fn exception(&mut self, error: &LivewireError, context: &mut ComponentContext) {
637        let _ = (error, context);
638    }
639
640    /// Whether an action's return value becomes a `returns` effect or JSON.
641    fn action_result_kind(&self, method: &str) -> ActionResultKind {
642        let _ = method;
643        ActionResultKind::Ignored
644    }
645
646    /// The options the component's class-level attribute declared.
647    fn class_options(&self) -> ClassOptions {
648        ClassOptions::default()
649    }
650
651    /// The actions the browser sends ahead of the others.
652    fn async_methods(&self) -> &'static [&'static str] {
653        &[]
654    }
655
656    /// The actions that answer with JSON instead of new markup.
657    fn json_methods(&self) -> &'static [&'static str] {
658        &[]
659    }
660
661    /// The component's computed properties, which its template reads like fields.
662    ///
663    /// A computed property is memoized for the rest of the request, so a template that prints it
664    /// twice computes it once.
665    fn computed_values(&self, id: &str) -> Map<String, Value> {
666        let _ = id;
667        Map::new()
668    }
669}
670
671/// Turns `postEditor` into `postEditor`, which is how a browser-written prop name reaches a field.
672///
673/// The macro-generated mount matches a kebab-case prop such as `post-id` to the field `post_id` and
674/// to the camel-case name, as upstream's `separateParamsAndAttributes` does.
675#[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/// Serializes a field for the wire, normalizing negative zero so that snapshots stay stable.
697#[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
704/// Replaces `-0.0` with `0.0` wherever it appears in a wire value.
705fn 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/// Reads a scalar out of a wire map by dot path, as a session key's `{placeholder}` needs it.
722#[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        // The hook saw the prop and overrode it, and set the locked field.
843        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        // A skipped field never crosses the wire, so the restored instance keeps its own value.
892        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        // A computed property is read by the template, never dispatched by the browser.
1088        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}