livewire-rust 0.1.3

Livewire for Rust: server-rendered reactive components for Laravel for Rust.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
//! The components, synthesizers, and template hooks an application registers once, frozen into one
//! shared value before the application boots.
//!
//! Component definitions live in the application, never in a global: the registry is built from the
//! application's provider, shared through the container, and handed to the engine and the update
//! handler. Two applications in one test process therefore keep their own components.

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;

/// Why an application's component registration was rejected.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum RegistryError {
    /// Two components were registered under one name.
    #[error("two components are registered as [{name}]: a component name must be unique")]
    DuplicateComponent {
        /// The name both components claimed.
        name: String,
    },
    /// Two synthesizers were registered under one key.
    #[error("two synthesizers are registered with the key [{key}]: a synthesizer key must be unique")]
    DuplicateSynth {
        /// The key both synthesizers claimed.
        key: String,
    },
    /// A component name is empty, or carries characters a name cannot.
    #[error("the component name [{name}] is not valid: use letters, digits, dashes, dots, slashes, or `::`")]
    InvalidName {
        /// The rejected name.
        name: String,
    },
}

/// The definition of one registered component.
struct Registration {
    /// Builds a default instance, which the server then hydrates or mounts.
    factory: Box<dyn Fn() -> Box<dyn Component> + Send + Sync>,
    /// The component's wire-public fields, which the derive monomorphized for its type.
    fields: fn() -> &'static [WireField],
    /// The Rust type, for diagnostics.
    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()
    }
}

/// A callback that configures the `.livewire` engine's environment.
pub type TemplateConfigurator = Arc<dyn Fn(&mut Environment<'static>) + Send + Sync>;

/// The components and template hooks one application registered.
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 {
    /// An empty registry for an application configured with `config`.
    #[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(),
        };

        // The adapters every application has, whether or not it registers its own.
        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
    }

    /// Registers a guard that runs on every update of a component mounted by a page.
    ///
    /// The guard sees the update's request and the page the component was mounted from, so a route
    /// guard the page ran runs again when the browser drives the component.
    pub fn persistent(&mut self, guard: impl crate::persistent::PersistentMiddleware + 'static) -> &mut Self {
        self.persistent.push(std::sync::Arc::new(guard));

        self
    }

    /// The guards an update runs, in registration order.
    pub(crate) fn persistent_guards(&self) -> &[std::sync::Arc<dyn crate::persistent::PersistentMiddleware>] {
        &self.persistent
    }

    /// Registers a lifecycle hook, which the pipeline runs at each step.
    ///
    /// Hooks run in registration order, on every request, for every component.
    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
    }

    /// Runs the registered hooks with `event`.
    pub(crate) fn run_hooks(&self, event: &crate::hooks::HookEvent<'_>) {
        self.hooks.run(event);
    }

    /// Registers a component under `name`.
    ///
    /// # Errors
    ///
    /// Fails when the name is invalid, or when another component already has it.
    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)
    }

    /// Registers a component that is built by `factory` rather than by `Default`.
    ///
    /// # Errors
    ///
    /// Fails when the name is invalid, or when another component already has it.
    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(())
    }

    /// Registers a synthesizer, so that a snapshot may name its key.
    ///
    /// # Errors
    ///
    /// Fails when another synthesizer already has the key.
    pub fn register_synth<S: Synth>(&mut self) -> Result<&mut Self, RegistryError> {
        self.register_synth_key(S::KEY)
    }

    /// Registers a synthesizer key that a field already names.
    ///
    /// # Errors
    ///
    /// Fails when another synthesizer already has the 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)
    }

    /// Adds a callback that configures the `.livewire` engine, such as filters of the application's
    /// own.
    pub fn templates(&mut self, configure: impl Fn(&mut Environment<'static>) + Send + Sync + 'static) -> &mut Self {
        self.templates.push(Arc::new(configure));
        self
    }

    /// Whether a snapshot may name `key` as a synthesizer.
    #[must_use]
    pub fn has_synth(&self, key: &str) -> bool {
        self.synthesizers.contains(key)
    }

    /// The synthesizer keys the application registered.
    pub fn synth_keys(&self) -> impl Iterator<Item = &'static str> + '_ {
        self.synthesizers.iter().copied()
    }

    /// A new instance of the component registered as `name`.
    #[must_use]
    pub fn instantiate(&self, name: &str) -> Option<Box<dyn Component>> {
        self.components.get(name).map(|registration| (registration.factory)())
    }

    /// The wire-public fields of the component registered as `name`.
    #[must_use]
    pub fn wire_fields(&self, name: &str) -> Option<&'static [WireField]> {
        self.components.get(name).map(|registration| (registration.fields)())
    }

    /// The names of the registered components, in order.
    pub fn names(&self) -> impl ExactSizeIterator<Item = &str> {
        self.components.keys().map(String::as_str)
    }

    /// Whether a component is registered.
    #[must_use]
    pub fn contains(&self, name: &str) -> bool {
        self.components.contains_key(name)
    }

    /// The callbacks that configure the engine.
    #[must_use]
    pub fn template_configurators(&self) -> &[TemplateConfigurator] {
        &self.templates
    }

    /// The configuration the application froze the registry with.
    #[must_use]
    pub fn config(&self) -> &LivewireConfig {
        &self.config
    }

    /// Whether the built-in placeholder renders a lazy component before it loads.
    #[must_use]
    pub fn synthesize_placeholder(&self) -> bool {
        self.synthesize_placeholder
    }

    /// Turns the built-in lazy placeholder off, for an application that renders its own.
    pub fn without_placeholder(&mut self) -> &mut Self {
        self.synthesize_placeholder = false;
        self
    }
}

/// Normalizes a component name: `/` becomes `.`, a leading `⚡` is removed, and `::` namespaces are
/// kept.
///
/// # Errors
///
/// Fails when the name is empty, or when it holds a character a name cannot, which keeps a crafted
/// name from escaping the registry or a view path.
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() });
    }
}