1use std::collections::{BTreeMap, BTreeSet};
9use std::fmt;
10use std::sync::Arc;
11
12use laravel::view::minijinja::Environment;
13
14use crate::component::{Component, WireField};
15use crate::config::LivewireConfig;
16use crate::synthesizers::Synth;
17
18#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
20pub enum RegistryError {
21 #[error("two components are registered as [{name}]: a component name must be unique")]
23 DuplicateComponent {
24 name: String,
26 },
27 #[error("two synthesizers are registered with the key [{key}]: a synthesizer key must be unique")]
29 DuplicateSynth {
30 key: String,
32 },
33 #[error("the component name [{name}] is not valid: use letters, digits, dashes, dots, slashes, or `::`")]
35 InvalidName {
36 name: String,
38 },
39}
40
41struct Registration {
43 factory: Box<dyn Fn() -> Box<dyn Component> + Send + Sync>,
45 fields: fn() -> &'static [WireField],
47 type_name: &'static str,
49}
50
51impl fmt::Debug for Registration {
52 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
53 formatter
54 .debug_struct("Registration")
55 .field("type_name", &self.type_name)
56 .finish_non_exhaustive()
57 }
58}
59
60pub type TemplateConfigurator = Arc<dyn Fn(&mut Environment<'static>) + Send + Sync>;
62
63pub struct ComponentRegistry {
65 components: BTreeMap<String, Registration>,
66 synthesizers: BTreeSet<&'static str>,
67 templates: Vec<TemplateConfigurator>,
68 config: LivewireConfig,
69 synthesize_placeholder: bool,
70 hooks: crate::hooks::Hooks,
71 persistent: Vec<std::sync::Arc<dyn crate::persistent::PersistentMiddleware>>,
72}
73
74impl fmt::Debug for ComponentRegistry {
75 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
76 formatter
77 .debug_struct("ComponentRegistry")
78 .field("components", &self.components)
79 .field("synthesizers", &self.synthesizers)
80 .field("templates", &self.templates.len())
81 .field("config", &self.config)
82 .field("hooks", &self.hooks)
83 .field("persistent", &self.persistent.len())
84 .finish_non_exhaustive()
85 }
86}
87
88impl ComponentRegistry {
89 #[must_use]
91 pub fn new(config: LivewireConfig) -> Self {
92 let mut registry = Self {
93 components: BTreeMap::new(),
94 synthesizers: BTreeSet::new(),
95 templates: Vec::new(),
96 config,
97 synthesize_placeholder: true,
98 hooks: crate::hooks::Hooks::default(),
99 persistent: Vec::new(),
100 };
101
102 registry.synthesizers.insert(crate::synthesizers::Arr::KEY);
104 registry.synthesizers.insert(crate::synthesizers::Std::KEY);
105 registry.synthesizers.insert(crate::synthesizers::Str::KEY);
106 registry.synthesizers.insert(crate::synthesizers::Int::KEY);
107 registry.synthesizers.insert(crate::synthesizers::Float::KEY);
108
109 registry
110 }
111
112 pub fn persistent(&mut self, guard: impl crate::persistent::PersistentMiddleware + 'static) -> &mut Self {
117 self.persistent.push(std::sync::Arc::new(guard));
118
119 self
120 }
121
122 pub(crate) fn persistent_guards(&self) -> &[std::sync::Arc<dyn crate::persistent::PersistentMiddleware>] {
124 &self.persistent
125 }
126
127 pub fn hook(&mut self, callback: impl Fn(&crate::hooks::HookEvent<'_>) + Send + Sync + 'static) -> &mut Self {
131 self.hooks.push(std::sync::Arc::new(callback));
132
133 self
134 }
135
136 pub(crate) fn run_hooks(&self, event: &crate::hooks::HookEvent<'_>) {
138 self.hooks.run(event);
139 }
140
141 pub fn register<C: Component + Default>(&mut self, name: impl Into<String>) -> Result<&mut Self, RegistryError> {
147 let name = normalize_name(&name.into())?;
148
149 self.insert(
150 name,
151 Registration {
152 factory: Box::new(|| Box::new(C::default()) as Box<dyn Component>),
153 fields: C::wire_fields,
154 type_name: std::any::type_name::<C>(),
155 },
156 )?;
157
158 Ok(self)
159 }
160
161 pub fn register_with<C: Component + Default>(
167 &mut self,
168 name: impl Into<String>,
169 factory: impl Fn() -> C + Send + Sync + 'static,
170 ) -> Result<&mut Self, RegistryError> {
171 let name = normalize_name(&name.into())?;
172
173 self.insert(
174 name,
175 Registration {
176 factory: Box::new(move || Box::new(factory()) as Box<dyn Component>),
177 fields: C::wire_fields,
178 type_name: std::any::type_name::<C>(),
179 },
180 )?;
181
182 Ok(self)
183 }
184
185 fn insert(&mut self, name: String, registration: Registration) -> Result<(), RegistryError> {
186 if self.components.contains_key(&name) {
187 return Err(RegistryError::DuplicateComponent { name });
188 }
189
190 self.components.insert(name, registration);
191
192 Ok(())
193 }
194
195 pub fn register_synth<S: Synth>(&mut self) -> Result<&mut Self, RegistryError> {
201 self.register_synth_key(S::KEY)
202 }
203
204 pub fn register_synth_key(&mut self, key: &'static str) -> Result<&mut Self, RegistryError> {
210 if !self.synthesizers.insert(key) {
211 return Err(RegistryError::DuplicateSynth { key: key.to_owned() });
212 }
213
214 Ok(self)
215 }
216
217 pub fn templates(&mut self, configure: impl Fn(&mut Environment<'static>) + Send + Sync + 'static) -> &mut Self {
220 self.templates.push(Arc::new(configure));
221 self
222 }
223
224 #[must_use]
226 pub fn has_synth(&self, key: &str) -> bool {
227 self.synthesizers.contains(key)
228 }
229
230 pub fn synth_keys(&self) -> impl Iterator<Item = &'static str> + '_ {
232 self.synthesizers.iter().copied()
233 }
234
235 #[must_use]
237 pub fn instantiate(&self, name: &str) -> Option<Box<dyn Component>> {
238 self.components.get(name).map(|registration| (registration.factory)())
239 }
240
241 #[must_use]
243 pub fn wire_fields(&self, name: &str) -> Option<&'static [WireField]> {
244 self.components.get(name).map(|registration| (registration.fields)())
245 }
246
247 pub fn names(&self) -> impl ExactSizeIterator<Item = &str> {
249 self.components.keys().map(String::as_str)
250 }
251
252 #[must_use]
254 pub fn contains(&self, name: &str) -> bool {
255 self.components.contains_key(name)
256 }
257
258 #[must_use]
260 pub fn template_configurators(&self) -> &[TemplateConfigurator] {
261 &self.templates
262 }
263
264 #[must_use]
266 pub fn config(&self) -> &LivewireConfig {
267 &self.config
268 }
269
270 #[must_use]
272 pub fn synthesize_placeholder(&self) -> bool {
273 self.synthesize_placeholder
274 }
275
276 pub fn without_placeholder(&mut self) -> &mut Self {
278 self.synthesize_placeholder = false;
279 self
280 }
281}
282
283pub fn normalize_name(name: &str) -> Result<String, RegistryError> {
291 let name: String = name.trim().chars().filter(|character| *character != '⚡').collect();
292 let name = name.trim_start_matches('/').replace('/', ".");
293
294 let invalid = name.is_empty()
295 || !name
296 .chars()
297 .all(|character| character.is_alphanumeric() || matches!(character, '-' | '_' | '.' | ':' | '⚡'))
298 || name.contains("..")
299 || name.starts_with('.')
300 || name.ends_with('.');
301
302 if invalid {
303 return Err(RegistryError::InvalidName { name });
304 }
305
306 Ok(name)
307}
308
309#[cfg(test)]
310mod tests {
311 use super::*;
312 use crate::component::ComponentContext;
313 use crate::{LivewireComponent, component};
314
315 #[derive(Default, LivewireComponent)]
316 #[livewire(inline = "<div></div>")]
317 struct Counter {
318 count: i32,
319 }
320
321 #[component]
322 impl Counter {
323 pub fn increment(&mut self) {
324 self.count += 1;
325 }
326 }
327
328 #[derive(Default, LivewireComponent)]
329 #[livewire(inline = "<div></div>")]
330 struct Other {
331 count: i32,
332 }
333
334 #[component]
335 impl Other {}
336
337 #[test]
338 fn a_registered_component_can_be_instantiated_and_updated() {
339 let mut registry = ComponentRegistry::new(LivewireConfig::default());
340 registry.register::<Counter>("counter").expect("registers");
341
342 assert!(registry.contains("counter"));
343 assert_eq!(registry.names().collect::<Vec<_>>(), ["counter"]);
344
345 let mut component = registry.instantiate("counter").expect("a component");
346 futures_util::FutureExt::now_or_never(component.call(
347 crate::component::Call {
348 method: "increment".to_owned(),
349 params: crate::component::Params::default(),
350 metadata: serde_json::Map::new(),
351 },
352 &mut ComponentContext::mounting("id", "counter", None),
353 ))
354 .expect("ready")
355 .expect("runs");
356 }
357
358 #[test]
359 fn the_wire_fields_come_from_the_registered_type() {
360 let mut registry = ComponentRegistry::new(LivewireConfig::default());
361 registry.register::<Counter>("counter").expect("registers");
362
363 let fields = registry.wire_fields("counter").expect("fields");
364
365 assert_eq!(fields.iter().map(|field| field.name).collect::<Vec<_>>(), ["count"]);
366 assert!(registry.wire_fields("other").is_none());
367 }
368
369 #[test]
370 fn two_components_may_not_share_a_name() {
371 let mut registry = ComponentRegistry::new(LivewireConfig::default());
372 registry.register::<Counter>("counter").expect("registers");
373
374 let error = registry.register::<Other>("counter").expect_err("duplicate");
375
376 assert_eq!(
377 error,
378 RegistryError::DuplicateComponent {
379 name: "counter".to_owned()
380 }
381 );
382 }
383
384 #[test]
385 fn a_name_is_normalized_before_it_is_checked() {
386 let mut registry = ComponentRegistry::new(LivewireConfig::default());
387
388 registry.register::<Counter>("/pages/⚡counter").expect("registers");
389
390 assert!(registry.contains("pages.counter"));
391 assert!(!registry.contains("/pages/⚡counter"));
392 }
393
394 #[test]
395 fn a_name_that_would_escape_its_path_is_rejected() {
396 for name in ["", "..", "a..b", "pages/../../etc/passwd", ".hidden"] {
397 assert!(normalize_name(name).is_err(), "{name}");
398 }
399 }
400
401 #[test]
402 fn a_namespace_separator_is_kept() {
403 assert_eq!(normalize_name("pages::counter").expect("valid"), "pages::counter");
404 }
405
406 #[test]
407 fn every_adapter_is_registered_by_default() {
408 let registry = ComponentRegistry::new(LivewireConfig::default());
409
410 for key in ["arr", "std", "str", "int", "float"] {
411 assert!(registry.has_synth(key), "{key}");
412 }
413 assert!(!registry.has_synth("mdl"));
414 }
415
416 #[test]
417 fn a_synthesizer_key_may_not_be_registered_twice() {
418 let mut registry = ComponentRegistry::new(LivewireConfig::default());
419
420 let error = registry
421 .register_synth::<crate::synthesizers::Arr>()
422 .expect_err("duplicate");
423
424 assert_eq!(error, RegistryError::DuplicateSynth { key: "arr".to_owned() });
425 }
426}