Skip to main content

livewire/
config.rs

1//! The `livewire` config section and its defaults, which mirror `config/livewire.php` in upstream
2//! Livewire 4.x.
3
4use std::collections::BTreeMap;
5use std::fmt;
6
7use std::time::Duration;
8
9use laravel::time::ExactDuration;
10
11/// Everything the `livewire` section configures.
12///
13/// The defaults match upstream Livewire's `config/livewire.php`. An application replaces any of
14/// them with a `livewire` config section of its own, or by changing the section in
15/// `with_config`.
16#[derive(Clone, Debug, PartialEq, Eq)]
17pub struct LivewireConfig {
18    /// The directories that hold view components, searched in order.
19    pub component_locations: Vec<String>,
20    /// Namespaces that resolve relative to a directory, such as `layouts` to
21    /// `resources/views/layouts`.
22    pub component_namespaces: BTreeMap<String, String>,
23    /// The view that wraps a page component, or `None` to render the component alone.
24    pub component_layout: Option<String>,
25    /// The view a lazy component shows before it loads, or `None` for the built-in placeholder.
26    pub component_placeholder: Option<String>,
27    /// The defaults of `make:livewire`.
28    pub make_command: MakeCommand,
29    /// Where `make:livewire` writes component modules.
30    pub component_path: String,
31    /// Where `make:livewire` writes `.livewire` views.
32    pub view_path: String,
33    /// How temporary uploads are stored and validated.
34    pub temporary_file_upload: TemporaryFileUpload,
35    /// Whether to render a component that redirected, before answering with the redirect.
36    pub render_on_redirect: bool,
37    /// Whether `wire:model` may bind a model directly, as Livewire 2 did.
38    pub legacy_model_binding: bool,
39    /// Whether the server injects its styles and scripts into HTML responses.
40    pub inject_assets: bool,
41    /// How `wire:navigate` presents a visit.
42    pub navigate: Navigate,
43    /// Whether to inject morph markers around conditionals, loops, and class output.
44    pub inject_morph_markers: bool,
45    /// Whether to derive keys for nested components inside loops.
46    pub smart_wire_keys: bool,
47    /// The CSS framework the pagination views target.
48    pub pagination_theme: PaginationTheme,
49    /// The token in each snapshot that a redeployment changes.
50    pub release_token: String,
51    /// Whether to serve and run the CSP-safe Alpine build.
52    pub csp_safe: bool,
53    /// A base URL that serves the frontend assets from somewhere other than the application.
54    pub asset_url: Option<String>,
55    /// A path for the update endpoint other than the default one.
56    pub update_uri: Option<String>,
57    /// The limits that guard the update endpoint against oversized requests.
58    pub payload: PayloadLimits,
59}
60
61impl Default for LivewireConfig {
62    fn default() -> Self {
63        Self {
64            component_locations: vec![
65                "resources/views/components".to_owned(),
66                "resources/views/livewire".to_owned(),
67            ],
68            component_namespaces: BTreeMap::from([
69                ("layouts".to_owned(), "resources/views/layouts".to_owned()),
70                ("pages".to_owned(), "resources/views/pages".to_owned()),
71            ]),
72            component_layout: Some("layouts::app".to_owned()),
73            component_placeholder: None,
74            make_command: MakeCommand::default(),
75            component_path: "src/livewire".to_owned(),
76            view_path: "resources/views/livewire".to_owned(),
77            temporary_file_upload: TemporaryFileUpload::default(),
78            render_on_redirect: false,
79            legacy_model_binding: false,
80            inject_assets: true,
81            navigate: Navigate::default(),
82            inject_morph_markers: true,
83            smart_wire_keys: true,
84            pagination_theme: PaginationTheme::Tailwind,
85            release_token: "a".to_owned(),
86            csp_safe: false,
87            asset_url: None,
88            update_uri: None,
89            payload: PayloadLimits::default(),
90        }
91    }
92}
93
94impl LivewireConfig {
95    /// The `livewire` section of a framework configuration, or the defaults when the application
96    /// never set one.
97    #[must_use]
98    pub fn of(config: &laravel::config::Config) -> &Self {
99        static DEFAULTS: std::sync::LazyLock<LivewireConfig> = std::sync::LazyLock::new(LivewireConfig::default);
100
101        config.get::<LivewireConfig>().unwrap_or(&DEFAULTS)
102    }
103
104    /// The first configured component directory, which `make:livewire` writes new components to.
105    #[must_use]
106    pub fn first_component_location(&self) -> Option<&str> {
107        self.component_locations.first().map(String::as_str)
108    }
109
110    /// The `temporary_file_upload.middleware` as a route throttle, or `None` when the
111    /// configuration names no allowed attempts.
112    #[must_use]
113    pub fn upload_throttle(&self) -> Option<laravel::http::middleware::Throttle> {
114        let middleware = &self.temporary_file_upload.middleware;
115        Some(laravel::http::middleware::Throttle::per(
116            middleware.max_attempts,
117            ExactDuration::from(Duration::from_secs(middleware.decay_seconds)),
118        ))
119    }
120}
121
122/// The kind of component `make:livewire` creates by default.
123#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
124pub enum ComponentKind {
125    /// A view component whose markup and module live in one `.livewire` file.
126    #[default]
127    Sfc,
128    /// A view component whose Rust module sits beside a `.livewire` file.
129    Mfc,
130    /// A component whose module declares its own view. In this port it writes the same files as
131    /// [`Mfc`](Self::Mfc), because a Rust component always has a module.
132    Class,
133}
134
135impl ComponentKind {
136    /// The name the configuration uses, as upstream names it.
137    #[must_use]
138    pub const fn as_str(self) -> &'static str {
139        match self {
140            Self::Sfc => "sfc",
141            Self::Mfc => "mfc",
142            Self::Class => "class",
143        }
144    }
145}
146
147impl fmt::Display for ComponentKind {
148    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
149        formatter.write_str(self.as_str())
150    }
151}
152
153/// The defaults of `make:livewire`.
154#[derive(Clone, Copy, Debug, PartialEq, Eq)]
155pub struct MakeCommand {
156    /// The component kind to create.
157    pub kind: ComponentKind,
158    /// Whether view component names carry the `⚡` counting emoji.
159    pub emoji: bool,
160    /// Whether to create a `.js` module beside the component.
161    pub js: bool,
162    /// Whether to create a `.css` module beside the component.
163    pub css: bool,
164    /// Whether to create a test file beside the component.
165    pub test: bool,
166}
167
168impl Default for MakeCommand {
169    fn default() -> Self {
170        Self {
171            kind: ComponentKind::Sfc,
172            emoji: true,
173            js: false,
174            css: false,
175            test: false,
176        }
177    }
178}
179
180/// How temporary uploads are stored, validated, and cleaned up.
181#[derive(Clone, Debug, PartialEq, Eq)]
182pub struct TemporaryFileUpload {
183    /// The disk to store temporary uploads on, or `None` for the application's default disk.
184    pub disk: Option<String>,
185    /// The validation rules of an upload.
186    pub rules: Vec<String>,
187    /// The directory on the disk, or `None` for `livewire-tmp`.
188    pub directory: Option<String>,
189    /// The throttle on the upload endpoint.
190    pub middleware: UploadMiddleware,
191    /// The extensions a temporary upload's preview may have.
192    pub preview_mimes: Vec<String>,
193    /// How long an upload stays valid, in minutes.
194    pub max_upload_time: u64,
195    /// Whether expired uploads are removed on the scheduled cleanup.
196    pub cleanup: bool,
197}
198
199impl Default for TemporaryFileUpload {
200    fn default() -> Self {
201        Self {
202            disk: None,
203            rules: vec!["required".to_owned(), "file".to_owned(), "max:12288".to_owned()],
204            directory: None,
205            middleware: UploadMiddleware::default(),
206            preview_mimes: [
207                "png", "gif", "bmp", "svg", "wav", "mp4", "mov", "avi", "wmv", "mp3", "m4a", "jpg", "jpeg", "mpga",
208                "webp", "wma",
209            ]
210            .into_iter()
211            .map(str::to_owned)
212            .collect(),
213            max_upload_time: 5,
214            cleanup: true,
215        }
216    }
217}
218
219impl TemporaryFileUpload {
220    /// The directory that holds temporary uploads.
221    #[must_use]
222    pub fn directory(&self) -> &str {
223        self.directory.as_deref().unwrap_or("livewire-tmp")
224    }
225
226    /// How long an upload stays valid.
227    #[must_use]
228    pub fn max_upload_time(&self) -> ExactDuration {
229        ExactDuration::from(Duration::from_secs(self.max_upload_time.saturating_mul(60)))
230    }
231}
232
233/// The throttle on the upload endpoint, written as `throttle:{max_attempts},{decay_seconds}`.
234#[derive(Clone, Copy, Debug, PartialEq, Eq)]
235pub struct UploadMiddleware {
236    /// How many uploads one client may make in the decay window.
237    pub max_attempts: u32,
238    /// The length of the decay window, in seconds.
239    pub decay_seconds: u64,
240}
241
242impl Default for UploadMiddleware {
243    fn default() -> Self {
244        Self {
245            max_attempts: 60,
246            decay_seconds: 60,
247        }
248    }
249}
250
251/// How `wire:navigate` presents a visit.
252#[derive(Clone, Debug, PartialEq, Eq)]
253pub struct Navigate {
254    /// Whether a progress bar shows while a visit loads.
255    pub show_progress_bar: bool,
256    /// The progress bar's colour.
257    pub progress_bar_color: String,
258}
259
260impl Default for Navigate {
261    fn default() -> Self {
262        Self {
263            show_progress_bar: true,
264            progress_bar_color: "#2299dd".to_owned(),
265        }
266    }
267}
268
269/// The CSS framework the pagination views target.
270#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
271pub enum PaginationTheme {
272    /// Tailwind CSS, the default.
273    #[default]
274    Tailwind,
275    /// Bootstrap.
276    Bootstrap,
277}
278
279impl PaginationTheme {
280    /// The name the configuration uses.
281    #[must_use]
282    pub const fn as_str(self) -> &'static str {
283        match self {
284            Self::Tailwind => "tailwind",
285            Self::Bootstrap => "bootstrap",
286        }
287    }
288}
289
290impl fmt::Display for PaginationTheme {
291    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
292        formatter.write_str(self.as_str())
293    }
294}
295
296/// The limits that guard the update endpoint. `None` disables a limit.
297#[derive(Clone, Copy, Debug, PartialEq, Eq)]
298pub struct PayloadLimits {
299    /// The largest request body, in bytes.
300    pub max_size: Option<usize>,
301    /// The deepest dot-notation property path an update may set.
302    pub max_nesting_depth: Option<usize>,
303    /// The most method calls a batch may make.
304    pub max_calls: Option<usize>,
305    /// The most components a batch may update.
306    pub max_components: Option<usize>,
307}
308
309impl Default for PayloadLimits {
310    fn default() -> Self {
311        Self {
312            max_size: Some(1_048_576),
313            max_nesting_depth: Some(10),
314            max_calls: Some(50),
315            max_components: Some(200),
316        }
317    }
318}
319
320#[cfg(test)]
321mod tests {
322    use super::*;
323
324    #[test]
325    fn matches_upstream_config_defaults() {
326        let config = LivewireConfig::default();
327
328        assert_eq!(
329            config.component_locations,
330            ["resources/views/components", "resources/views/livewire"]
331        );
332        assert_eq!(config.component_layout.as_deref(), Some("layouts::app"));
333        assert_eq!(config.component_namespaces["pages"], "resources/views/pages");
334        assert_eq!(config.make_command.kind, ComponentKind::Sfc);
335        assert!(config.make_command.emoji);
336        assert_eq!(config.temporary_file_upload.rules, ["required", "file", "max:12288"]);
337        assert_eq!(config.temporary_file_upload.directory(), "livewire-tmp");
338        assert_eq!(config.temporary_file_upload.preview_mimes.len(), 16);
339        assert_eq!(
340            config.temporary_file_upload.max_upload_time(),
341            ExactDuration::from(Duration::from_secs(300))
342        );
343        assert!(config.temporary_file_upload.cleanup);
344        assert_eq!(config.navigate.progress_bar_color, "#2299dd");
345        assert_eq!(config.pagination_theme, PaginationTheme::Tailwind);
346        assert_eq!(config.release_token, "a");
347        assert_eq!(config.payload.max_size, Some(1_048_576));
348        assert_eq!(config.payload.max_nesting_depth, Some(10));
349        assert_eq!(config.payload.max_calls, Some(50));
350        assert_eq!(config.payload.max_components, Some(200));
351    }
352
353    #[test]
354    fn the_upload_throttle_is_a_sixty_per_minute_limit() {
355        let throttle = LivewireConfig::default().upload_throttle().expect("a throttle");
356
357        assert_eq!(
358            throttle,
359            laravel::http::middleware::Throttle::per(60, ExactDuration::from(Duration::from_secs(60)))
360        );
361    }
362}