livewire-rust 0.1.4

Livewire for Rust: server-rendered reactive components for Laravel for Rust.
Documentation
//! Lifecycle hooks: one place to observe every mount, update, and action.
//!
//! An application registers a callback once, and the pipeline calls it at each step. Upstream spells
//! this `Livewire::hook('mounted', …)`; here one callback matches on [`HookEvent`], so a hook that
//! only cares about calls needs no registration per event.
//!
//! ```
//! # use livewire::ComponentRegistry;
//! # use livewire::hooks::HookEvent;
//! # let mut registry = ComponentRegistry::new(Default::default());
//! registry.hook(|event| {
//!     if let HookEvent::Mount { name, id } = event {
//!         println!("{name} mounted as {id}");
//!     }
//! });
//! ```

use std::sync::Arc;

/// One step of a component's life, borrowed for the length of the call that ran it.
#[derive(Debug, Clone, Copy)]
pub enum HookEvent<'a> {
    /// Before a component's `mount` runs, when its view has not rendered.
    BeforeMount {
        /// The component's registered name.
        name: &'a str,
    },
    /// After a component mounted and rendered, with the instance ID the page embeds.
    Mount {
        /// The component's registered name.
        name: &'a str,
        /// The instance ID.
        id: &'a str,
    },
    /// Before an update applies its field changes.
    BeforeUpdate {
        /// The component's registered name.
        name: &'a str,
        /// The instance ID.
        id: &'a str,
    },
    /// After an update rendered, before the response is written.
    Update {
        /// The component's registered name.
        name: &'a str,
        /// The instance ID.
        id: &'a str,
    },
    /// Before one action runs, after the browser's updates were applied.
    BeforeCall {
        /// The component's registered name.
        name: &'a str,
        /// The instance ID.
        id: &'a str,
        /// The method the browser called.
        method: &'a str,
    },
    /// After one action ran, whether it succeeded or reported an error.
    Call {
        /// The component's registered name.
        name: &'a str,
        /// The instance ID.
        id: &'a str,
        /// The method the browser called.
        method: &'a str,
    },
}

impl HookEvent<'_> {
    /// The component the event is about.
    #[must_use]
    pub fn name(&self) -> &str {
        match self {
            Self::BeforeMount { name } => name,
            Self::Mount { name, .. }
            | Self::BeforeUpdate { name, .. }
            | Self::Update { name, .. }
            | Self::BeforeCall { name, .. }
            | Self::Call { name, .. } => name,
        }
    }

    /// The instance ID, when the event knows it.
    #[must_use]
    pub fn id(&self) -> Option<&str> {
        match self {
            Self::BeforeMount { .. } => None,
            Self::Mount { id, .. }
            | Self::BeforeUpdate { id, .. }
            | Self::Update { id, .. }
            | Self::BeforeCall { id, .. }
            | Self::Call { id, .. } => Some(id),
        }
    }

    /// The method, for a call event.
    #[must_use]
    pub fn method(&self) -> Option<&str> {
        match self {
            Self::BeforeCall { method, .. } | Self::Call { method, .. } => Some(method),
            _ => None,
        }
    }
}

/// A callback an application registers once.
pub type HookCallback = Arc<dyn for<'a> Fn(&HookEvent<'a>) + Send + Sync>;

/// The hooks an application registered, run in registration order.
#[derive(Default, Clone)]
pub struct Hooks {
    callbacks: Vec<HookCallback>,
}

impl std::fmt::Debug for Hooks {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("Hooks")
            .field("callbacks", &self.callbacks.len())
            .finish()
    }
}

impl Hooks {
    /// Adds `callback` to the end of the list.
    pub fn push(&mut self, callback: HookCallback) {
        self.callbacks.push(callback);
    }

    /// Runs every registered callback with `event`.
    pub fn run(&self, event: &HookEvent<'_>) {
        for callback in &self.callbacks {
            callback(event);
        }
    }

    /// How many callbacks are registered.
    #[must_use]
    pub fn len(&self) -> usize {
        self.callbacks.len()
    }

    /// Whether no callback is registered.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.callbacks.is_empty()
    }
}

#[cfg(test)]
mod tests {
    use super::{HookEvent, Hooks};
    use std::sync::{Arc, Mutex};

    #[test]
    fn the_callbacks_run_in_the_order_they_were_added() {
        let seen: Arc<Mutex<Vec<&'static str>>> = Arc::default();
        let mut hooks = Hooks::default();

        for label in ["first", "second", "third"] {
            let seen = Arc::clone(&seen);
            hooks.push(Arc::new(move |_event| {
                seen.lock().expect("the recorder is not poisoned").push(label);
            }));
        }

        hooks.run(&HookEvent::BeforeMount { name: "counter" });

        assert_eq!(
            *seen.lock().expect("the recorder is not poisoned"),
            ["first", "second", "third"]
        );
        assert_eq!(hooks.len(), 3);
        assert!(!hooks.is_empty());
    }

    #[test]
    fn no_callback_runs_when_none_is_registered() {
        let hooks = Hooks::default();

        hooks.run(&HookEvent::Mount {
            name: "counter",
            id: "abc",
        });

        assert!(hooks.is_empty());
        assert_eq!(hooks.len(), 0);
    }

    #[test]
    fn an_event_answers_what_it_knows() {
        let mounted = HookEvent::BeforeMount { name: "counter" };
        assert_eq!(mounted.name(), "counter");
        assert_eq!(mounted.id(), None, "a component has no id before it mounts");
        assert_eq!(mounted.method(), None);

        let called = HookEvent::Call {
            name: "counter",
            id: "abc",
            method: "increment",
        };
        assert_eq!(called.name(), "counter");
        assert_eq!(called.id(), Some("abc"));
        assert_eq!(called.method(), Some("increment"));

        let rendered = HookEvent::Update {
            name: "counter",
            id: "abc",
        };
        assert_eq!(rendered.method(), None, "an update names no method");

        let mounting = HookEvent::Mount {
            name: "counter",
            id: "abc",
        };
        assert_eq!(mounting.id(), Some("abc"));
    }
}