laravel-rust-admin 0.1.1

Admin panel framework for Laravel for Rust: auto-generated CRUD tables, forms, actions, and dashboard widgets from your models.
Documentation
//! Route handlers serving the embedded SPA shell and typed JSON admin API.

use std::sync::Arc;

use laravel::container::Inject;
use laravel::http::{Json, Request, StatusCode, Streamed};
use laravel::routing::Params;
use laravel::view::Html;

use crate::panel::PanelState;
use crate::protocol::{
    ActionResponse, DashboardResponse, GlobalSearchResponse, PanelSchemaResponse, RecordResponse, ResourceListResponse,
    RunBulkActionRequest, RunRowActionRequest,
};
use crate::resource::ListQuery;

const ASSET_NAMESPACE: &str = "laravel-rust-admin";

/// `GET {base}` — The page that loads the panel's browser app.
pub async fn shell_root(panel: Inject<PanelState>, request: Request) -> laravel::Result<Html> {
    render_shell(&panel, &request)
}

/// `GET {base}/{*path}` — Client-side SPA route fallback (rejects unknown `/api/...` paths with 404).
pub async fn shell_fallback(
    panel: Inject<PanelState>,
    Params(path): Params<String>,
    request: Request,
) -> laravel::Result<Html> {
    if path == "api" || path.starts_with("api/") {
        return Err(laravel::abort_with(
            StatusCode::NOT_FOUND,
            "Admin API endpoint not found.",
        ));
    }
    render_shell(&panel, &request)
}

/// `GET {base}/api/panel` — Panel configuration, navigation, user, and resource schemas.
pub async fn panel_schema(panel: Inject<PanelState>, request: Request) -> laravel::Result<Json<PanelSchemaResponse>> {
    let user = panel.resolve_user(&request).await?;
    let mut resources = Vec::with_capacity(panel.resources.len());
    for resource in panel.resources.iter() {
        let schema = resource.schema(&request).await?;
        if schema.permissions.view_any {
            resources.push(schema);
        }
    }

    Ok(Json(PanelSchemaResponse {
        brand: panel.brand.clone(),
        subtitle: panel.subtitle.clone(),
        base_path: panel.base_path.clone(),
        accent: panel.accent,
        logout_url: panel.logout_url.clone(),
        user,
        resources,
    }))
}

/// `GET {base}/api/dashboard` — The dashboard's widgets.
pub async fn dashboard(panel: Inject<PanelState>, request: Request) -> laravel::Result<Json<DashboardResponse>> {
    let widgets = panel.resolve_dashboard_widgets(&request).await?;
    Ok(Json(DashboardResponse { widgets }))
}

/// `GET {base}/api/search?q=...` — Global command-palette search across searchable resources.
pub async fn global_search(panel: Inject<PanelState>, request: Request) -> laravel::Result<Json<GlobalSearchResponse>> {
    let query = ListQuery::from_query_str(request.uri().query())
        .search
        .unwrap_or_default();

    if query.is_empty() {
        return Ok(Json(GlobalSearchResponse {
            query,
            groups: Vec::new(),
        }));
    }

    let mut groups = Vec::new();
    for resource in panel.resources.iter() {
        if let Some(group) = resource.global_search(&request, query.clone(), 5).await? {
            groups.push(group);
        }
    }

    Ok(Json(GlobalSearchResponse { query, groups }))
}

/// `GET {base}/api/resources/{slug}` — Paginated, searchable, filterable, sortable record list.
pub async fn list_records(
    panel: Inject<PanelState>,
    Params(slug): Params<String>,
    request: Request,
) -> laravel::Result<Json<ResourceListResponse>> {
    let resource = resolve_resource(&panel, &slug)?;
    let query = ListQuery::from_query_str(request.uri().query());
    let response = resource.list(&request, query).await?;
    Ok(Json(response))
}

/// `GET {base}/api/resources/{slug}/export` — CSV export honoring current query/filters/sort.
pub async fn export_records(
    panel: Inject<PanelState>,
    Params(slug): Params<String>,
    request: Request,
) -> laravel::Result<Streamed> {
    let resource = resolve_resource(&panel, &slug)?;
    let query = ListQuery::from_query_str(request.uri().query());
    resource.export_csv(&request, query).await
}

/// `POST {base}/api/resources/{slug}` — Validate and create a new record.
pub async fn create_record(
    panel: Inject<PanelState>,
    Params(slug): Params<String>,
    request: Request,
) -> laravel::Result<(StatusCode, Json<RecordResponse>)> {
    let resource = resolve_resource(&panel, &slug)?;
    let response = resource.create(&request).await?;
    Ok((StatusCode::CREATED, Json(response)))
}

/// `GET {base}/api/resources/{slug}/records/{id}` — Retrieve a single record.
pub async fn show_record(
    panel: Inject<PanelState>,
    Params((slug, id)): Params<(String, String)>,
    request: Request,
) -> laravel::Result<Json<RecordResponse>> {
    let resource = resolve_resource(&panel, &slug)?;
    let response = resource.show(&request, id).await?;
    Ok(Json(response))
}

/// `PATCH/PUT {base}/api/resources/{slug}/records/{id}` — Validate and update an existing record.
pub async fn update_record(
    panel: Inject<PanelState>,
    Params((slug, id)): Params<(String, String)>,
    request: Request,
) -> laravel::Result<Json<RecordResponse>> {
    let resource = resolve_resource(&panel, &slug)?;
    let response = resource.update(&request, id).await?;
    Ok(Json(response))
}

/// `DELETE {base}/api/resources/{slug}/records/{id}` — Delete a single record.
pub async fn delete_record(
    panel: Inject<PanelState>,
    Params((slug, id)): Params<(String, String)>,
    request: Request,
) -> laravel::Result<Json<ActionResponse>> {
    let resource = resolve_resource(&panel, &slug)?;
    let response = resource.delete(&request, id).await?;
    Ok(Json(response))
}

/// `POST {base}/api/resources/{slug}/records/{id}/actions/{action}` — Run a custom row action.
pub async fn run_row_action(
    panel: Inject<PanelState>,
    Params((slug, id, action)): Params<(String, String, String)>,
    request: Request,
) -> laravel::Result<Json<ActionResponse>> {
    let resource = resolve_resource(&panel, &slug)?;
    // `Request::json` reads the body the way the framework reads every body, so a malformed
    // payload is a `422` that names the field, never a panic or a silent default.
    let payload: RunRowActionRequest = request.json()?;
    let response = resource
        .run_row_action(&Arc::new(request), id, action, payload.data)
        .await?;
    Ok(Json(response))
}

/// `POST {base}/api/resources/{slug}/bulk/{action}` — Run a custom bulk action or built-in bulk delete.
pub async fn run_bulk_action(
    panel: Inject<PanelState>,
    Params((slug, action)): Params<(String, String)>,
    request: Request,
) -> laravel::Result<Json<ActionResponse>> {
    let resource = resolve_resource(&panel, &slug)?;
    let payload: RunBulkActionRequest = request.json()?;
    let response = resource
        .run_bulk_action(&Arc::new(request), action, payload.ids, payload.data)
        .await?;
    Ok(Json(response))
}

fn resolve_resource<'a>(
    panel: &'a PanelState,
    slug: &str,
) -> laravel::Result<&'a std::sync::Arc<dyn crate::resource::ErasedResource>> {
    panel
        .find_resource(slug)
        .ok_or_else(|| laravel::abort_with(StatusCode::NOT_FOUND, format!("Resource `{slug}` not found.")))
}

/// Sets the `dark` class before the first paint, so a dark page never flashes white. The app's
/// `useTheme` hook reads the same `localStorage` key.
const APPEARANCE_SCRIPT: &str = "(()=>{let s;try{s=localStorage['laravel-admin.appearance']}catch{}\
const d=s==='dark'||(s!=='light'&&matchMedia('(prefers-color-scheme: dark)').matches),\
h=document.documentElement;h.classList.toggle('dark',d);h.style.colorScheme=d?'dark':'light'})()";

fn render_shell(panel: &PanelState, request: &Request) -> laravel::Result<Html> {
    // Without a session there's no token to send, and the app falls back to the `XSRF-TOKEN`
    // cookie, or to the browser's `Sec-Fetch-Site` header.
    let csrf = request.session().map(|session| session.token()).unwrap_or_default();

    // The JSON sits inside a `<script>` element, where `</script>` or `<!--` in a value (such as
    // the brand) would end or corrupt the element. `\u003c` is the same character to a JSON parser.
    let bootstrap = serde_json::to_string(&panel.bootstrap())?.replace('<', "\\u003c");

    // An application with a Content Security Policy allows inline scripts by their nonce.
    let nonce = laravel::view::csp_nonce()
        .map(|nonce| format!(r#" nonce="{}""#, html_escape(&nonce)))
        .unwrap_or_default();

    let assets = if let Some(dev_url) = &panel.vite_dev_url {
        // The Vite dev server, for working on the panel's own frontend with hot reloading.
        let dev = html_escape(dev_url);
        format!(
            r#"<script type="module"{nonce}>
import RefreshRuntime from '{dev}/@react-refresh';
RefreshRuntime.injectIntoGlobalHook(window);
window.$RefreshReg$ = () => {{}};
window.$RefreshSig$ = () => (type) => type;
window.__vite_plugin_react_preamble_installed__ = true;
</script>
    <script type="module" src="{dev}/@vite/client"></script>
    <script type="module" src="{dev}/src/main.tsx"></script>"#
        )
    } else {
        let css = html_escape(&laravel::url::vendor_asset(ASSET_NAMESPACE, "style.css"));
        let js = html_escape(&laravel::url::vendor_asset(ASSET_NAMESPACE, "app.js"));
        format!(
            r#"<link rel="stylesheet" href="{css}">
    <script type="module" src="{js}"></script>"#
        )
    };

    let html = format!(
        r#"<!DOCTYPE html>
<html lang="en" data-accent="{accent}">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="csrf-token" content="{csrf}">
    <meta name="robots" content="noindex, nofollow">
    <title>{title}</title>
    <script{nonce}>{APPEARANCE_SCRIPT}</script>
    <script id="laravel-admin-bootstrap" type="application/json">{bootstrap}</script>
    {assets}
</head>
<body class="admin-canvas">
    <div id="root"></div>
</body>
</html>"#,
        accent = panel.accent.as_str(),
        csrf = html_escape(&csrf),
        title = html_escape(&panel.brand),
    );

    Ok(Html::raw(html))
}

fn html_escape(input: &str) -> String {
    input
        .replace('&', "&amp;")
        .replace('<', "&lt;")
        .replace('>', "&gt;")
        .replace('"', "&quot;")
        .replace('\'', "&#39;")
}