use std::collections::{BTreeMap, BTreeSet};
use std::fmt;
use std::sync::Arc;
use laravel::view::minijinja::Environment;
use crate::component::{Component, WireField};
use crate::config::LivewireConfig;
use crate::synthesizers::Synth;
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum RegistryError {
#[error("two components are registered as [{name}]: a component name must be unique")]
DuplicateComponent {
name: String,
},
#[error("two synthesizers are registered with the key [{key}]: a synthesizer key must be unique")]
DuplicateSynth {
key: String,
},
#[error("the component name [{name}] is not valid: use letters, digits, dashes, dots, slashes, or `::`")]
InvalidName {
name: String,
},
}
struct Registration {
factory: Box<dyn Fn() -> Box<dyn Component> + Send + Sync>,
fields: fn() -> &'static [WireField],
type_name: &'static str,
}
impl fmt::Debug for Registration {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("Registration")
.field("type_name", &self.type_name)
.finish_non_exhaustive()
}
}
pub type TemplateConfigurator = Arc<dyn Fn(&mut Environment<'static>) + Send + Sync>;
pub struct ComponentRegistry {
components: BTreeMap<String, Registration>,
synthesizers: BTreeSet<&'static str>,
templates: Vec<TemplateConfigurator>,
config: LivewireConfig,
synthesize_placeholder: bool,
hooks: crate::hooks::Hooks,
persistent: Vec<std::sync::Arc<dyn crate::persistent::PersistentMiddleware>>,
}
impl fmt::Debug for ComponentRegistry {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("ComponentRegistry")
.field("components", &self.components)
.field("synthesizers", &self.synthesizers)
.field("templates", &self.templates.len())
.field("config", &self.config)
.field("hooks", &self.hooks)
.field("persistent", &self.persistent.len())
.finish_non_exhaustive()
}
}
impl ComponentRegistry {
#[must_use]
pub fn new(config: LivewireConfig) -> Self {
let mut registry = Self {
components: BTreeMap::new(),
synthesizers: BTreeSet::new(),
templates: Vec::new(),
config,
synthesize_placeholder: true,
hooks: crate::hooks::Hooks::default(),
persistent: Vec::new(),
};
registry.synthesizers.insert(crate::synthesizers::Arr::KEY);
registry.synthesizers.insert(crate::synthesizers::Std::KEY);
registry.synthesizers.insert(crate::synthesizers::Str::KEY);
registry.synthesizers.insert(crate::synthesizers::Int::KEY);
registry.synthesizers.insert(crate::synthesizers::Float::KEY);
registry
}
pub fn persistent(&mut self, guard: impl crate::persistent::PersistentMiddleware + 'static) -> &mut Self {
self.persistent.push(std::sync::Arc::new(guard));
self
}
pub(crate) fn persistent_guards(&self) -> &[std::sync::Arc<dyn crate::persistent::PersistentMiddleware>] {
&self.persistent
}
pub fn hook(&mut self, callback: impl Fn(&crate::hooks::HookEvent<'_>) + Send + Sync + 'static) -> &mut Self {
self.hooks.push(std::sync::Arc::new(callback));
self
}
pub(crate) fn run_hooks(&self, event: &crate::hooks::HookEvent<'_>) {
self.hooks.run(event);
}
pub fn register<C: Component + Default>(&mut self, name: impl Into<String>) -> Result<&mut Self, RegistryError> {
let name = normalize_name(&name.into())?;
self.insert(
name,
Registration {
factory: Box::new(|| Box::new(C::default()) as Box<dyn Component>),
fields: C::wire_fields,
type_name: std::any::type_name::<C>(),
},
)?;
Ok(self)
}
pub fn register_with<C: Component + Default>(
&mut self,
name: impl Into<String>,
factory: impl Fn() -> C + Send + Sync + 'static,
) -> Result<&mut Self, RegistryError> {
let name = normalize_name(&name.into())?;
self.insert(
name,
Registration {
factory: Box::new(move || Box::new(factory()) as Box<dyn Component>),
fields: C::wire_fields,
type_name: std::any::type_name::<C>(),
},
)?;
Ok(self)
}
fn insert(&mut self, name: String, registration: Registration) -> Result<(), RegistryError> {
if self.components.contains_key(&name) {
return Err(RegistryError::DuplicateComponent { name });
}
self.components.insert(name, registration);
Ok(())
}
pub fn register_synth<S: Synth>(&mut self) -> Result<&mut Self, RegistryError> {
self.register_synth_key(S::KEY)
}
pub fn register_synth_key(&mut self, key: &'static str) -> Result<&mut Self, RegistryError> {
if !self.synthesizers.insert(key) {
return Err(RegistryError::DuplicateSynth { key: key.to_owned() });
}
Ok(self)
}
pub fn templates(&mut self, configure: impl Fn(&mut Environment<'static>) + Send + Sync + 'static) -> &mut Self {
self.templates.push(Arc::new(configure));
self
}
#[must_use]
pub fn has_synth(&self, key: &str) -> bool {
self.synthesizers.contains(key)
}
pub fn synth_keys(&self) -> impl Iterator<Item = &'static str> + '_ {
self.synthesizers.iter().copied()
}
#[must_use]
pub fn instantiate(&self, name: &str) -> Option<Box<dyn Component>> {
self.components.get(name).map(|registration| (registration.factory)())
}
#[must_use]
pub fn wire_fields(&self, name: &str) -> Option<&'static [WireField]> {
self.components.get(name).map(|registration| (registration.fields)())
}
pub fn names(&self) -> impl ExactSizeIterator<Item = &str> {
self.components.keys().map(String::as_str)
}
#[must_use]
pub fn contains(&self, name: &str) -> bool {
self.components.contains_key(name)
}
#[must_use]
pub fn template_configurators(&self) -> &[TemplateConfigurator] {
&self.templates
}
#[must_use]
pub fn config(&self) -> &LivewireConfig {
&self.config
}
#[must_use]
pub fn synthesize_placeholder(&self) -> bool {
self.synthesize_placeholder
}
pub fn without_placeholder(&mut self) -> &mut Self {
self.synthesize_placeholder = false;
self
}
}
pub fn normalize_name(name: &str) -> Result<String, RegistryError> {
let name: String = name.trim().chars().filter(|character| *character != '⚡').collect();
let name = name.trim_start_matches('/').replace('/', ".");
let invalid = name.is_empty()
|| !name
.chars()
.all(|character| character.is_alphanumeric() || matches!(character, '-' | '_' | '.' | ':' | '⚡'))
|| name.contains("..")
|| name.starts_with('.')
|| name.ends_with('.');
if invalid {
return Err(RegistryError::InvalidName { name });
}
Ok(name)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::component::ComponentContext;
use crate::{LivewireComponent, component};
#[derive(Default, LivewireComponent)]
#[livewire(inline = "<div></div>")]
struct Counter {
count: i32,
}
#[component]
impl Counter {
pub fn increment(&mut self) {
self.count += 1;
}
}
#[derive(Default, LivewireComponent)]
#[livewire(inline = "<div></div>")]
struct Other {
count: i32,
}
#[component]
impl Other {}
#[test]
fn a_registered_component_can_be_instantiated_and_updated() {
let mut registry = ComponentRegistry::new(LivewireConfig::default());
registry.register::<Counter>("counter").expect("registers");
assert!(registry.contains("counter"));
assert_eq!(registry.names().collect::<Vec<_>>(), ["counter"]);
let mut component = registry.instantiate("counter").expect("a component");
futures_util::FutureExt::now_or_never(component.call(
crate::component::Call {
method: "increment".to_owned(),
params: crate::component::Params::default(),
metadata: serde_json::Map::new(),
},
&mut ComponentContext::mounting("id", "counter", None),
))
.expect("ready")
.expect("runs");
}
#[test]
fn the_wire_fields_come_from_the_registered_type() {
let mut registry = ComponentRegistry::new(LivewireConfig::default());
registry.register::<Counter>("counter").expect("registers");
let fields = registry.wire_fields("counter").expect("fields");
assert_eq!(fields.iter().map(|field| field.name).collect::<Vec<_>>(), ["count"]);
assert!(registry.wire_fields("other").is_none());
}
#[test]
fn two_components_may_not_share_a_name() {
let mut registry = ComponentRegistry::new(LivewireConfig::default());
registry.register::<Counter>("counter").expect("registers");
let error = registry.register::<Other>("counter").expect_err("duplicate");
assert_eq!(
error,
RegistryError::DuplicateComponent {
name: "counter".to_owned()
}
);
}
#[test]
fn a_name_is_normalized_before_it_is_checked() {
let mut registry = ComponentRegistry::new(LivewireConfig::default());
registry.register::<Counter>("/pages/⚡counter").expect("registers");
assert!(registry.contains("pages.counter"));
assert!(!registry.contains("/pages/⚡counter"));
}
#[test]
fn a_name_that_would_escape_its_path_is_rejected() {
for name in ["", "..", "a..b", "pages/../../etc/passwd", ".hidden"] {
assert!(normalize_name(name).is_err(), "{name}");
}
}
#[test]
fn a_namespace_separator_is_kept() {
assert_eq!(normalize_name("pages::counter").expect("valid"), "pages::counter");
}
#[test]
fn every_adapter_is_registered_by_default() {
let registry = ComponentRegistry::new(LivewireConfig::default());
for key in ["arr", "std", "str", "int", "float"] {
assert!(registry.has_synth(key), "{key}");
}
assert!(!registry.has_synth("mdl"));
}
#[test]
fn a_synthesizer_key_may_not_be_registered_twice() {
let mut registry = ComponentRegistry::new(LivewireConfig::default());
let error = registry
.register_synth::<crate::synthesizers::Arr>()
.expect_err("duplicate");
assert_eq!(error, RegistryError::DuplicateSynth { key: "arr".to_owned() });
}
}