laravel-rust-admin 0.1.0

Admin panel framework for Laravel for Rust: auto-generated CRUD tables, forms, actions, and dashboard widgets from your models.
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
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
//! `AdminPanel` builder and `laravel::foundation::ServiceProvider` integration.

use std::collections::HashMap;
use std::future::Future;
use std::marker::PhantomData;
use std::str::FromStr;
use std::sync::Arc;

use futures_util::future::BoxFuture;
use laravel::config::app::Environment;
use laravel::config::{Config, Env};
use laravel::container::{Container, Registrar};
use laravel::foundation::ServiceProvider;
use laravel::http::{IntoMiddleware, MiddlewareGroup, Request};
use laravel::model::Model;
use serde::Serialize;

use crate::config::{AccentColor, AdminConfig};
use crate::http::{AuthorizePanel, LOCKED_MESSAGE, LockedPanel, register_routes};
use crate::protocol::{AdminUserDto, BadgeColor, DashboardWidgetDto, ShellBootstrap};
use crate::resource::{AdminResource, ErasedResource, ResourceAdapter};
use crate::widget::{DashboardWidget, ErasedWidget, FnWidget, RequestWidget, StatWidget};

/// Signed-in user details displayed in the admin sidebar footer and dashboard greeting.
#[derive(Debug, Clone)]
pub struct AdminUser {
    /// The name shown in the sidebar, and greeted on the dashboard.
    pub name: String,
    /// The address shown under the name in the user menu.
    pub email: Option<String>,
    /// The URL of a picture to show instead of the user's initials.
    pub avatar_url: Option<String>,
    /// What the user is to the application, such as `Owner`. The user menu shows it when there's no email.
    pub role: Option<String>,
}

impl AdminUser {
    /// A user with a name, and nothing else yet.
    #[must_use]
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            email: None,
            avatar_url: None,
            role: None,
        }
    }

    /// Sets the email address shown in the user menu.
    #[must_use]
    pub fn email(mut self, email: impl Into<String>) -> Self {
        self.email = Some(email.into());
        self
    }

    /// Sets the URL of the user's picture.
    #[must_use]
    pub fn avatar_url(mut self, url: impl Into<String>) -> Self {
        self.avatar_url = Some(url.into());
        self
    }

    /// Sets the user's role, such as `Owner`.
    #[must_use]
    pub fn role(mut self, role: impl Into<String>) -> Self {
        self.role = Some(role.into());
        self
    }

    pub(crate) fn into_dto(self) -> AdminUserDto {
        AdminUserDto {
            name: self.name,
            email: self.email,
            avatar_url: self.avatar_url,
            role: self.role,
        }
    }
}

/// An async function of the request, which is how the panel asks your application who may enter,
/// and who the current user is.
///
/// Every `async fn` that takes a `&Request` and returns a `laravel::Result<T>` implements this
/// trait, so write one and pass its name:
///
/// ```ignore
/// async fn admins_only(request: &Request) -> laravel::Result<bool> {
///     Ok(request.user::<User>().await?.is_some_and(|user| user.is_admin))
/// }
///
/// AdminPanel::new().authorize(admins_only)
/// ```
///
/// A closure works too when it names its argument's type and returns a boxed future, such as
/// `|_request: &Request| Box::pin(async { Ok(true) })`.
pub trait RequestFn<'a, T>: Send + Sync + 'static {
    /// The future the function returns.
    type Future: Future<Output = laravel::Result<T>> + Send + 'a;

    /// Calls the function with the request.
    fn call(&self, request: &'a Request) -> Self::Future;
}

impl<'a, T, F, Fut> RequestFn<'a, T> for F
where
    F: Fn(&'a Request) -> Fut + Send + Sync + 'static,
    Fut: Future<Output = laravel::Result<T>> + Send + 'a,
{
    type Future = Fut;

    fn call(&self, request: &'a Request) -> Fut {
        self(request)
    }
}

/// A [`RequestFn`] behind a pointer, which the panel can keep and call.
pub(crate) type RequestHook<T> = Arc<dyn for<'a> Fn(&'a Request) -> BoxFuture<'a, laravel::Result<T>> + Send + Sync>;

fn hook<T: 'static>(function: impl for<'a> RequestFn<'a, T>) -> RequestHook<T> {
    Arc::new(move |request| Box::pin(function.call(request)))
}

pub(crate) type PanelGate = RequestHook<bool>;

pub(crate) type UserResolver = RequestHook<Option<AdminUser>>;

/// Runtime state registered in Laravel's service container as a singleton.
#[derive(Clone)]
pub struct PanelState {
    pub(crate) base_path: String,
    pub(crate) brand: String,
    pub(crate) subtitle: Option<String>,
    pub(crate) accent: AccentColor,
    pub(crate) logout_url: Option<String>,
    pub(crate) vite_dev_url: Option<String>,
    pub(crate) resources: Arc<Vec<Arc<dyn ErasedResource>>>,
    pub(crate) resource_index: Arc<HashMap<String, usize>>,
    pub(crate) widgets: Arc<Vec<Arc<dyn ErasedWidget>>>,
    pub(crate) user_resolver: Option<UserResolver>,
}

impl std::fmt::Debug for PanelState {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("PanelState")
            .field("base_path", &self.base_path)
            .field("brand", &self.brand)
            .field("resources", &self.resources.len())
            .field("widgets", &self.widgets.len())
            .finish_non_exhaustive()
    }
}

impl PanelState {
    pub(crate) fn find_resource(&self, slug: &str) -> Option<&Arc<dyn ErasedResource>> {
        let index = *self.resource_index.get(slug)?;
        self.resources.get(index)
    }

    pub(crate) fn bootstrap(&self) -> ShellBootstrap {
        ShellBootstrap {
            base_path: self.base_path.clone(),
            api_base: format!("{}/api", self.base_path),
            brand: self.brand.clone(),
            subtitle: self.subtitle.clone(),
            accent: self.accent,
            logout_url: self.logout_url.clone(),
        }
    }

    pub(crate) async fn resolve_user(&self, request: &Request) -> laravel::Result<Option<AdminUserDto>> {
        let Some(resolver) = &self.user_resolver else {
            return Ok(None);
        };
        Ok(resolver(request).await?.map(AdminUser::into_dto))
    }

    pub(crate) async fn resolve_dashboard_widgets(
        &self,
        request: &Request,
    ) -> laravel::Result<Vec<DashboardWidgetDto>> {
        if !self.widgets.is_empty() {
            let mut resolved = Vec::with_capacity(self.widgets.len());
            for widget in self.widgets.iter() {
                resolved.push(widget.resolve(request).await?);
            }
            return Ok(resolved);
        }

        // A panel without widgets of its own shows how many records each resource has.
        let mut resolved = Vec::with_capacity(self.resources.len());
        for resource in self.resources.iter() {
            let count = resource.total_count(request).await?;
            let slug = resource.slug();
            resolved.push(
                StatWidget::new(
                    format!("resource_count_{slug}"),
                    resource.plural_label(),
                    format_number(count),
                )
                .description(format!("Total {} in database", resource.plural_label().to_lowercase()))
                .icon(resource.icon())
                .color(BadgeColor::Zinc)
                .href(format!("{}/resources/{slug}", self.base_path))
                .build(),
            );
        }
        Ok(resolved)
    }
}

/// Fluent builder for configuring and mounting an admin panel as a Laravel `ServiceProvider`.
///
/// ```no_run
/// use laravel::Application;
/// use laravel_rust_admin::AdminPanel;
///
/// let admin = AdminPanel::new()
///     .path("/admin")
///     .brand("Acme Console");
///
/// Application::configure()
///     .with_providers(|providers| {
///         providers.add(admin);
///     });
/// ```
pub struct AdminPanel {
    path: Option<String>,
    brand: Option<String>,
    subtitle: Option<String>,
    accent: AccentColor,
    logout_url: Option<String>,
    vite_dev_url: Option<String>,
    middleware: MiddlewareGroup,
    /// Whether the application attached middleware of its own, such as `Authenticate`.
    has_middleware: bool,
    resources: Vec<Arc<dyn ErasedResource>>,
    widgets: Vec<Arc<dyn ErasedWidget>>,
    gate: Option<PanelGate>,
    user_resolver: Option<UserResolver>,
}

impl std::fmt::Debug for AdminPanel {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("AdminPanel")
            .field("path", &self.path)
            .field("brand", &self.brand)
            .field("accent", &self.accent)
            .field("resources", &self.resources.len())
            .field("widgets", &self.widgets.len())
            .finish_non_exhaustive()
    }
}

impl Default for AdminPanel {
    fn default() -> Self {
        Self::new()
    }
}

impl AdminPanel {
    /// Create a new admin panel mounted at `/admin` by default.
    #[must_use]
    pub fn new() -> Self {
        Self {
            path: None,
            brand: None,
            subtitle: None,
            accent: AccentColor::Zinc,
            logout_url: None,
            vite_dev_url: None,
            middleware: MiddlewareGroup::new(),
            has_middleware: false,
            resources: Vec::new(),
            widgets: Vec::new(),
            gate: None,
            user_resolver: None,
        }
    }

    /// Set the URL prefix where the panel is mounted (e.g. `"/admin"` or `"/ops"`).
    #[must_use]
    pub fn path(mut self, path: impl Into<String>) -> Self {
        self.path = Some(normalize_path(&path.into()));
        self
    }

    /// Set the brand title displayed in the sidebar header and browser tab.
    #[must_use]
    pub fn brand(mut self, brand: impl Into<String>) -> Self {
        self.brand = Some(brand.into());
        self
    }

    /// Optional subtitle shown beneath the brand name (e.g. `"Production"` or `"Workspace"`).
    #[must_use]
    pub fn subtitle(mut self, subtitle: impl Into<String>) -> Self {
        self.subtitle = Some(subtitle.into());
        self
    }

    /// Sets the color of the panel's primary buttons, checked controls, and brand mark.
    #[must_use]
    pub fn accent(mut self, accent: AccentColor) -> Self {
        self.accent = accent;
        self
    }

    /// Optional logout URL rendered in the sidebar user profile dropdown.
    #[must_use]
    pub fn logout_url(mut self, url: impl Into<String>) -> Self {
        self.logout_url = Some(url.into());
        self
    }

    /// Optional Vite dev server URL (e.g. `"http://localhost:5173"`) for hot-reloading UI work.
    #[must_use]
    pub fn vite_dev_url(mut self, url: impl Into<String>) -> Self {
        self.vite_dev_url = Some(url.into().trim_end_matches('/').to_owned());
        self
    }

    /// Attach Laravel middleware (such as `laravel::auth::Authenticate`) to all admin routes.
    ///
    /// A panel with neither middleware nor an [`authorize`](Self::authorize) gate is open to
    /// everyone, so it only answers in the `local` and `testing` environments. Everywhere else
    /// it responds with a `403` until you add one of the two.
    #[must_use]
    pub fn middleware(mut self, middleware: impl IntoMiddleware) -> Self {
        self.middleware.append(middleware);
        self.has_middleware = true;
        self
    }

    /// Decide who may use the panel, with a gate that runs before every panel request.
    ///
    /// Returning `Ok(false)` rejects the request with `403 Forbidden`. The gate runs after the
    /// panel's [`middleware`](Self::middleware), so it can read the user that `Authenticate`
    /// loaded:
    ///
    /// ```ignore
    /// async fn admins_only(request: &Request) -> laravel::Result<bool> {
    ///     Ok(request.user::<User>().await?.is_some_and(|user| user.is_admin))
    /// }
    ///
    /// AdminPanel::new()
    ///     .middleware(laravel::auth::Authenticate)
    ///     .authorize(admins_only)
    /// ```
    #[must_use]
    pub fn authorize(mut self, gate: impl for<'a> RequestFn<'a, bool>) -> Self {
        self.gate = Some(hook(gate));
        self
    }

    /// Tell the panel who is using it, for the user menu in the sidebar and the greeting on the
    /// dashboard. Return `None` when there is no one to show.
    ///
    /// ```ignore
    /// async fn current_user(request: &Request) -> laravel::Result<Option<AdminUser>> {
    ///     let user = request.user::<User>().await?;
    ///     Ok(user.map(|user| AdminUser::new(user.name).email(user.email)))
    /// }
    ///
    /// AdminPanel::new().user_resolver(current_user)
    /// ```
    #[must_use]
    pub fn user_resolver(mut self, resolver: impl for<'a> RequestFn<'a, Option<AdminUser>>) -> Self {
        self.user_resolver = Some(hook(resolver));
        self
    }

    /// Register an [`AdminResource`] with this panel.
    #[must_use]
    pub fn resource<R>(mut self) -> Self
    where
        R: AdminResource,
        <R::Model as Model>::Key: FromStr,
        R::Model: Serialize,
    {
        // Two resources at one URL would make the second unreachable without a word of warning.
        assert!(
            self.resources.iter().all(|resource| resource.slug() != R::slug()),
            "two admin resources share the slug `{}`; give one of them a different `slug()`",
            R::slug(),
        );
        self.resources.push(ResourceAdapter::<R>::erased());
        self
    }

    /// Add a widget to the dashboard. Widgets appear in the order you add them.
    ///
    /// A panel without widgets shows a count of each resource's records instead.
    #[must_use]
    pub fn widget(mut self, widget: impl DashboardWidget) -> Self {
        self.widgets.push(Arc::new(widget));
        self
    }

    /// Add a dashboard widget that is an async function, which runs each time the dashboard
    /// loads. It returns a [`StatWidget`], a [`ChartWidget`](crate::ChartWidget), or a
    /// [`TableWidget`](crate::TableWidget):
    ///
    /// ```ignore
    /// async fn open_orders() -> laravel::Result<StatWidget> {
    ///     let count = Order::query().filter(Order::status.eq(OrderStatus::Pending)).count().await?;
    ///     Ok(StatWidget::new("open_orders", "Open orders", count.to_string()))
    /// }
    ///
    /// AdminPanel::new().widget_fn(open_orders)
    /// ```
    #[must_use]
    pub fn widget_fn<F, Fut, W>(self, widget: F) -> Self
    where
        F: Fn() -> Fut + Send + Sync + 'static,
        Fut: Future<Output = laravel::Result<W>> + Send + 'static,
        W: Into<DashboardWidgetDto> + 'static,
    {
        self.widget(FnWidget(widget))
    }

    /// Add a dashboard widget that is an async function of the request, such as one that shows
    /// the logged-in user's own numbers. Like [`authorize`](Self::authorize), it takes an
    /// `async fn(&Request)`.
    #[must_use]
    pub fn widget_for_request<F, W>(self, widget: F) -> Self
    where
        F: for<'a> RequestFn<'a, W>,
        W: Into<DashboardWidgetDto> + 'static,
    {
        self.widget(RequestWidget(widget, PhantomData))
    }
}

impl ServiceProvider for AdminPanel {
    fn config(&self, config: &mut Config, env: &Env) {
        config.discover(env!("CARGO_CRATE_NAME"), env);
    }

    fn register(&self, app: &mut Registrar) {
        let cfg = app.config().section::<AdminConfig>();
        let base_path = normalize_path(self.path.as_deref().unwrap_or(&cfg.path));
        let brand = self.brand.clone().unwrap_or_else(|| cfg.brand.clone());
        let vite_dev_url = self
            .vite_dev_url
            .clone()
            .or_else(|| cfg.vite_dev_url.clone())
            .map(|url| url.trim_end_matches('/').to_owned());

        let mut resources = self.resources.clone();
        resources.sort_by_key(|r| r.navigation_sort());

        let mut resource_index = HashMap::with_capacity(resources.len());
        for (idx, resource) in resources.iter().enumerate() {
            resource_index.insert(resource.slug().to_owned(), idx);
        }

        let state = PanelState {
            base_path: base_path.clone(),
            brand,
            subtitle: self.subtitle.clone(),
            accent: self.accent,
            logout_url: self.logout_url.clone(),
            vite_dev_url,
            resources: Arc::new(resources),
            resource_index: Arc::new(resource_index),
            widgets: Arc::new(self.widgets.clone()),
            user_resolver: self.user_resolver.clone(),
        };

        app.instance(state.clone());
        app.routing().assets("laravel-rust-admin", laravel::embed!("dist"));

        let mut middleware = self.middleware.clone();
        if let Some(gate) = self.gate.clone() {
            middleware.append(AuthorizePanel::new(gate));
        }
        if self.is_locked(&app.config().app.env) {
            middleware.append(LockedPanel);
        }

        app.routing().web(move |router| {
            register_routes(router, &base_path, middleware);
        });
    }

    async fn boot(&self, app: &Container) -> laravel::Result<()> {
        let environment = &app.config().app.env;
        if self.is_locked(environment) {
            tracing::warn!(
                environment = environment.as_str(),
                "laravel-rust-admin: {LOCKED_MESSAGE}"
            );
        }

        Ok(())
    }
}

impl AdminPanel {
    /// Whether the panel refuses every request, because nothing decides who may use it and the
    /// application isn't running on a developer's machine or in a test.
    fn is_locked(&self, environment: &Environment) -> bool {
        let unprotected = self.gate.is_none() && !self.has_middleware;
        unprotected && !matches!(environment, Environment::Local | Environment::Testing)
    }
}

fn normalize_path(raw: &str) -> String {
    let trimmed = raw.trim().trim_matches('/');
    if trimmed.is_empty() {
        "/admin".to_owned()
    } else {
        format!("/{trimmed}")
    }
}

fn format_number(n: u64) -> String {
    let digits = n.to_string();
    let mut out = String::with_capacity(digits.len() + digits.len() / 3);
    for (idx, ch) in digits.chars().rev().enumerate() {
        if idx > 0 && idx % 3 == 0 {
            out.push(',');
        }
        out.push(ch);
    }
    out.chars().rev().collect()
}