1use std::sync::Arc;
19
20#[derive(Debug, Clone, Copy)]
22pub enum HookEvent<'a> {
23 BeforeMount {
25 name: &'a str,
27 },
28 Mount {
30 name: &'a str,
32 id: &'a str,
34 },
35 BeforeUpdate {
37 name: &'a str,
39 id: &'a str,
41 },
42 Update {
44 name: &'a str,
46 id: &'a str,
48 },
49 BeforeCall {
51 name: &'a str,
53 id: &'a str,
55 method: &'a str,
57 },
58 Call {
60 name: &'a str,
62 id: &'a str,
64 method: &'a str,
66 },
67}
68
69impl HookEvent<'_> {
70 #[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 #[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 #[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
106pub type HookCallback = Arc<dyn for<'a> Fn(&HookEvent<'a>) + Send + Sync>;
108
109#[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 pub fn push(&mut self, callback: HookCallback) {
127 self.callbacks.push(callback);
128 }
129
130 pub fn run(&self, event: &HookEvent<'_>) {
132 for callback in &self.callbacks {
133 callback(event);
134 }
135 }
136
137 #[must_use]
139 pub fn len(&self) -> usize {
140 self.callbacks.len()
141 }
142
143 #[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}