livewire-rust 0.1.3

Livewire for Rust: server-rendered reactive components for Laravel for Rust.
Documentation
//! The `livewire` config section and its defaults, which mirror `config/livewire.php` in upstream
//! Livewire 4.x.

use std::collections::BTreeMap;
use std::fmt;

use std::time::Duration;

use laravel::time::ExactDuration;

/// Everything the `livewire` section configures.
///
/// The defaults match upstream Livewire's `config/livewire.php`. An application replaces any of
/// them with a `livewire` config section of its own, or by changing the section in
/// `with_config`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct LivewireConfig {
    /// The directories that hold view components, searched in order.
    pub component_locations: Vec<String>,
    /// Namespaces that resolve relative to a directory, such as `layouts` to
    /// `resources/views/layouts`.
    pub component_namespaces: BTreeMap<String, String>,
    /// The view that wraps a page component, or `None` to render the component alone.
    pub component_layout: Option<String>,
    /// The view a lazy component shows before it loads, or `None` for the built-in placeholder.
    pub component_placeholder: Option<String>,
    /// The defaults of `make:livewire`.
    pub make_command: MakeCommand,
    /// Where `make:livewire` writes component modules.
    pub component_path: String,
    /// Where `make:livewire` writes `.livewire` views.
    pub view_path: String,
    /// How temporary uploads are stored and validated.
    pub temporary_file_upload: TemporaryFileUpload,
    /// Whether to render a component that redirected, before answering with the redirect.
    pub render_on_redirect: bool,
    /// Whether `wire:model` may bind a model directly, as Livewire 2 did.
    pub legacy_model_binding: bool,
    /// Whether the server injects its styles and scripts into HTML responses.
    pub inject_assets: bool,
    /// How `wire:navigate` presents a visit.
    pub navigate: Navigate,
    /// Whether to inject morph markers around conditionals, loops, and class output.
    pub inject_morph_markers: bool,
    /// Whether to derive keys for nested components inside loops.
    pub smart_wire_keys: bool,
    /// The CSS framework the pagination views target.
    pub pagination_theme: PaginationTheme,
    /// The token in each snapshot that a redeployment changes.
    pub release_token: String,
    /// Whether to serve and run the CSP-safe Alpine build.
    pub csp_safe: bool,
    /// A base URL that serves the frontend assets from somewhere other than the application.
    pub asset_url: Option<String>,
    /// A path for the update endpoint other than the default one.
    pub update_uri: Option<String>,
    /// The limits that guard the update endpoint against oversized requests.
    pub payload: PayloadLimits,
}

impl Default for LivewireConfig {
    fn default() -> Self {
        Self {
            component_locations: vec![
                "resources/views/components".to_owned(),
                "resources/views/livewire".to_owned(),
            ],
            component_namespaces: BTreeMap::from([
                ("layouts".to_owned(), "resources/views/layouts".to_owned()),
                ("pages".to_owned(), "resources/views/pages".to_owned()),
            ]),
            component_layout: Some("layouts::app".to_owned()),
            component_placeholder: None,
            make_command: MakeCommand::default(),
            component_path: "src/livewire".to_owned(),
            view_path: "resources/views/livewire".to_owned(),
            temporary_file_upload: TemporaryFileUpload::default(),
            render_on_redirect: false,
            legacy_model_binding: false,
            inject_assets: true,
            navigate: Navigate::default(),
            inject_morph_markers: true,
            smart_wire_keys: true,
            pagination_theme: PaginationTheme::Tailwind,
            release_token: "a".to_owned(),
            csp_safe: false,
            asset_url: None,
            update_uri: None,
            payload: PayloadLimits::default(),
        }
    }
}

impl LivewireConfig {
    /// The `livewire` section of a framework configuration, or the defaults when the application
    /// never set one.
    #[must_use]
    pub fn of(config: &laravel::config::Config) -> &Self {
        static DEFAULTS: std::sync::LazyLock<LivewireConfig> = std::sync::LazyLock::new(LivewireConfig::default);

        config.get::<LivewireConfig>().unwrap_or(&DEFAULTS)
    }

    /// The first configured component directory, which `make:livewire` writes new components to.
    #[must_use]
    pub fn first_component_location(&self) -> Option<&str> {
        self.component_locations.first().map(String::as_str)
    }

    /// The `temporary_file_upload.middleware` as a route throttle, or `None` when the
    /// configuration names no allowed attempts.
    #[must_use]
    pub fn upload_throttle(&self) -> Option<laravel::http::middleware::Throttle> {
        let middleware = &self.temporary_file_upload.middleware;
        Some(laravel::http::middleware::Throttle::per(
            middleware.max_attempts,
            ExactDuration::from(Duration::from_secs(middleware.decay_seconds)),
        ))
    }
}

/// The kind of component `make:livewire` creates by default.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum ComponentKind {
    /// A view component whose markup and module live in one `.livewire` file.
    #[default]
    Sfc,
    /// A view component whose Rust module sits beside a `.livewire` file.
    Mfc,
    /// A component whose module declares its own view. In this port it writes the same files as
    /// [`Mfc`](Self::Mfc), because a Rust component always has a module.
    Class,
}

impl ComponentKind {
    /// The name the configuration uses, as upstream names it.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Sfc => "sfc",
            Self::Mfc => "mfc",
            Self::Class => "class",
        }
    }
}

impl fmt::Display for ComponentKind {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(self.as_str())
    }
}

/// The defaults of `make:livewire`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct MakeCommand {
    /// The component kind to create.
    pub kind: ComponentKind,
    /// Whether view component names carry the `âš¡` counting emoji.
    pub emoji: bool,
    /// Whether to create a `.js` module beside the component.
    pub js: bool,
    /// Whether to create a `.css` module beside the component.
    pub css: bool,
    /// Whether to create a test file beside the component.
    pub test: bool,
}

impl Default for MakeCommand {
    fn default() -> Self {
        Self {
            kind: ComponentKind::Sfc,
            emoji: true,
            js: false,
            css: false,
            test: false,
        }
    }
}

/// How temporary uploads are stored, validated, and cleaned up.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TemporaryFileUpload {
    /// The disk to store temporary uploads on, or `None` for the application's default disk.
    pub disk: Option<String>,
    /// The validation rules of an upload.
    pub rules: Vec<String>,
    /// The directory on the disk, or `None` for `livewire-tmp`.
    pub directory: Option<String>,
    /// The throttle on the upload endpoint.
    pub middleware: UploadMiddleware,
    /// The extensions a temporary upload's preview may have.
    pub preview_mimes: Vec<String>,
    /// How long an upload stays valid, in minutes.
    pub max_upload_time: u64,
    /// Whether expired uploads are removed on the scheduled cleanup.
    pub cleanup: bool,
}

impl Default for TemporaryFileUpload {
    fn default() -> Self {
        Self {
            disk: None,
            rules: vec!["required".to_owned(), "file".to_owned(), "max:12288".to_owned()],
            directory: None,
            middleware: UploadMiddleware::default(),
            preview_mimes: [
                "png", "gif", "bmp", "svg", "wav", "mp4", "mov", "avi", "wmv", "mp3", "m4a", "jpg", "jpeg", "mpga",
                "webp", "wma",
            ]
            .into_iter()
            .map(str::to_owned)
            .collect(),
            max_upload_time: 5,
            cleanup: true,
        }
    }
}

impl TemporaryFileUpload {
    /// The directory that holds temporary uploads.
    #[must_use]
    pub fn directory(&self) -> &str {
        self.directory.as_deref().unwrap_or("livewire-tmp")
    }

    /// How long an upload stays valid.
    #[must_use]
    pub fn max_upload_time(&self) -> ExactDuration {
        ExactDuration::from(Duration::from_secs(self.max_upload_time.saturating_mul(60)))
    }
}

/// The throttle on the upload endpoint, written as `throttle:{max_attempts},{decay_seconds}`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct UploadMiddleware {
    /// How many uploads one client may make in the decay window.
    pub max_attempts: u32,
    /// The length of the decay window, in seconds.
    pub decay_seconds: u64,
}

impl Default for UploadMiddleware {
    fn default() -> Self {
        Self {
            max_attempts: 60,
            decay_seconds: 60,
        }
    }
}

/// How `wire:navigate` presents a visit.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Navigate {
    /// Whether a progress bar shows while a visit loads.
    pub show_progress_bar: bool,
    /// The progress bar's colour.
    pub progress_bar_color: String,
}

impl Default for Navigate {
    fn default() -> Self {
        Self {
            show_progress_bar: true,
            progress_bar_color: "#2299dd".to_owned(),
        }
    }
}

/// The CSS framework the pagination views target.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum PaginationTheme {
    /// Tailwind CSS, the default.
    #[default]
    Tailwind,
    /// Bootstrap.
    Bootstrap,
}

impl PaginationTheme {
    /// The name the configuration uses.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Tailwind => "tailwind",
            Self::Bootstrap => "bootstrap",
        }
    }
}

impl fmt::Display for PaginationTheme {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(self.as_str())
    }
}

/// The limits that guard the update endpoint. `None` disables a limit.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct PayloadLimits {
    /// The largest request body, in bytes.
    pub max_size: Option<usize>,
    /// The deepest dot-notation property path an update may set.
    pub max_nesting_depth: Option<usize>,
    /// The most method calls a batch may make.
    pub max_calls: Option<usize>,
    /// The most components a batch may update.
    pub max_components: Option<usize>,
}

impl Default for PayloadLimits {
    fn default() -> Self {
        Self {
            max_size: Some(1_048_576),
            max_nesting_depth: Some(10),
            max_calls: Some(50),
            max_components: Some(200),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn matches_upstream_config_defaults() {
        let config = LivewireConfig::default();

        assert_eq!(
            config.component_locations,
            ["resources/views/components", "resources/views/livewire"]
        );
        assert_eq!(config.component_layout.as_deref(), Some("layouts::app"));
        assert_eq!(config.component_namespaces["pages"], "resources/views/pages");
        assert_eq!(config.make_command.kind, ComponentKind::Sfc);
        assert!(config.make_command.emoji);
        assert_eq!(config.temporary_file_upload.rules, ["required", "file", "max:12288"]);
        assert_eq!(config.temporary_file_upload.directory(), "livewire-tmp");
        assert_eq!(config.temporary_file_upload.preview_mimes.len(), 16);
        assert_eq!(
            config.temporary_file_upload.max_upload_time(),
            ExactDuration::from(Duration::from_secs(300))
        );
        assert!(config.temporary_file_upload.cleanup);
        assert_eq!(config.navigate.progress_bar_color, "#2299dd");
        assert_eq!(config.pagination_theme, PaginationTheme::Tailwind);
        assert_eq!(config.release_token, "a");
        assert_eq!(config.payload.max_size, Some(1_048_576));
        assert_eq!(config.payload.max_nesting_depth, Some(10));
        assert_eq!(config.payload.max_calls, Some(50));
        assert_eq!(config.payload.max_components, Some(200));
    }

    #[test]
    fn the_upload_throttle_is_a_sixty_per_minute_limit() {
        let throttle = LivewireConfig::default().upload_throttle().expect("a throttle");

        assert_eq!(
            throttle,
            laravel::http::middleware::Throttle::per(60, ExactDuration::from(Duration::from_secs(60)))
        );
    }
}