Skip to main content

livewire/
hooks.rs

1//! Lifecycle hooks: one place to observe every mount, update, and action.
2//!
3//! An application registers a callback once, and the pipeline calls it at each step. Upstream spells
4//! this `Livewire::hook('mounted', …)`; here one callback matches on [`HookEvent`], so a hook that
5//! only cares about calls needs no registration per event.
6//!
7//! ```
8//! # use livewire::ComponentRegistry;
9//! # use livewire::hooks::HookEvent;
10//! # let mut registry = ComponentRegistry::new(Default::default());
11//! registry.hook(|event| {
12//!     if let HookEvent::Mount { name, id } = event {
13//!         println!("{name} mounted as {id}");
14//!     }
15//! });
16//! ```
17
18use std::sync::Arc;
19
20/// One step of a component's life, borrowed for the length of the call that ran it.
21#[derive(Debug, Clone, Copy)]
22pub enum HookEvent<'a> {
23    /// Before a component's `mount` runs, when its view has not rendered.
24    BeforeMount {
25        /// The component's registered name.
26        name: &'a str,
27    },
28    /// After a component mounted and rendered, with the instance ID the page embeds.
29    Mount {
30        /// The component's registered name.
31        name: &'a str,
32        /// The instance ID.
33        id: &'a str,
34    },
35    /// Before an update applies its field changes.
36    BeforeUpdate {
37        /// The component's registered name.
38        name: &'a str,
39        /// The instance ID.
40        id: &'a str,
41    },
42    /// After an update rendered, before the response is written.
43    Update {
44        /// The component's registered name.
45        name: &'a str,
46        /// The instance ID.
47        id: &'a str,
48    },
49    /// Before one action runs, after the browser's updates were applied.
50    BeforeCall {
51        /// The component's registered name.
52        name: &'a str,
53        /// The instance ID.
54        id: &'a str,
55        /// The method the browser called.
56        method: &'a str,
57    },
58    /// After one action ran, whether it succeeded or reported an error.
59    Call {
60        /// The component's registered name.
61        name: &'a str,
62        /// The instance ID.
63        id: &'a str,
64        /// The method the browser called.
65        method: &'a str,
66    },
67}
68
69impl HookEvent<'_> {
70    /// The component the event is about.
71    #[must_use]
72    pub fn name(&self) -> &str {
73        match self {
74            Self::BeforeMount { name } => name,
75            Self::Mount { name, .. }
76            | Self::BeforeUpdate { name, .. }
77            | Self::Update { name, .. }
78            | Self::BeforeCall { name, .. }
79            | Self::Call { name, .. } => name,
80        }
81    }
82
83    /// The instance ID, when the event knows it.
84    #[must_use]
85    pub fn id(&self) -> Option<&str> {
86        match self {
87            Self::BeforeMount { .. } => None,
88            Self::Mount { id, .. }
89            | Self::BeforeUpdate { id, .. }
90            | Self::Update { id, .. }
91            | Self::BeforeCall { id, .. }
92            | Self::Call { id, .. } => Some(id),
93        }
94    }
95
96    /// The method, for a call event.
97    #[must_use]
98    pub fn method(&self) -> Option<&str> {
99        match self {
100            Self::BeforeCall { method, .. } | Self::Call { method, .. } => Some(method),
101            _ => None,
102        }
103    }
104}
105
106/// A callback an application registers once.
107pub type HookCallback = Arc<dyn for<'a> Fn(&HookEvent<'a>) + Send + Sync>;
108
109/// The hooks an application registered, run in registration order.
110#[derive(Default, Clone)]
111pub struct Hooks {
112    callbacks: Vec<HookCallback>,
113}
114
115impl std::fmt::Debug for Hooks {
116    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
117        formatter
118            .debug_struct("Hooks")
119            .field("callbacks", &self.callbacks.len())
120            .finish()
121    }
122}
123
124impl Hooks {
125    /// Adds `callback` to the end of the list.
126    pub fn push(&mut self, callback: HookCallback) {
127        self.callbacks.push(callback);
128    }
129
130    /// Runs every registered callback with `event`.
131    pub fn run(&self, event: &HookEvent<'_>) {
132        for callback in &self.callbacks {
133            callback(event);
134        }
135    }
136
137    /// How many callbacks are registered.
138    #[must_use]
139    pub fn len(&self) -> usize {
140        self.callbacks.len()
141    }
142
143    /// Whether no callback is registered.
144    #[must_use]
145    pub fn is_empty(&self) -> bool {
146        self.callbacks.is_empty()
147    }
148}
149
150#[cfg(test)]
151mod tests {
152    use super::{HookEvent, Hooks};
153    use std::sync::{Arc, Mutex};
154
155    #[test]
156    fn the_callbacks_run_in_the_order_they_were_added() {
157        let seen: Arc<Mutex<Vec<&'static str>>> = Arc::default();
158        let mut hooks = Hooks::default();
159
160        for label in ["first", "second", "third"] {
161            let seen = Arc::clone(&seen);
162            hooks.push(Arc::new(move |_event| {
163                seen.lock().expect("the recorder is not poisoned").push(label);
164            }));
165        }
166
167        hooks.run(&HookEvent::BeforeMount { name: "counter" });
168
169        assert_eq!(
170            *seen.lock().expect("the recorder is not poisoned"),
171            ["first", "second", "third"]
172        );
173        assert_eq!(hooks.len(), 3);
174        assert!(!hooks.is_empty());
175    }
176
177    #[test]
178    fn no_callback_runs_when_none_is_registered() {
179        let hooks = Hooks::default();
180
181        hooks.run(&HookEvent::Mount {
182            name: "counter",
183            id: "abc",
184        });
185
186        assert!(hooks.is_empty());
187        assert_eq!(hooks.len(), 0);
188    }
189
190    #[test]
191    fn an_event_answers_what_it_knows() {
192        let mounted = HookEvent::BeforeMount { name: "counter" };
193        assert_eq!(mounted.name(), "counter");
194        assert_eq!(mounted.id(), None, "a component has no id before it mounts");
195        assert_eq!(mounted.method(), None);
196
197        let called = HookEvent::Call {
198            name: "counter",
199            id: "abc",
200            method: "increment",
201        };
202        assert_eq!(called.name(), "counter");
203        assert_eq!(called.id(), Some("abc"));
204        assert_eq!(called.method(), Some("increment"));
205
206        let rendered = HookEvent::Update {
207            name: "counter",
208            id: "abc",
209        };
210        assert_eq!(rendered.method(), None, "an update names no method");
211
212        let mounting = HookEvent::Mount {
213            name: "counter",
214            id: "abc",
215        };
216        assert_eq!(mounting.id(), Some("abc"));
217    }
218}