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
//! Custom row-level and bulk actions for admin resources.

use std::collections::BTreeMap;
use std::future::Future;
use std::sync::Arc;

use futures_util::future::BoxFuture;
use laravel::http::Request;
use laravel::model::Model;

use crate::protocol::{ActionConfirmationDto, ActionResponse, ActionSchemaDto};
use crate::schema::form::Field;

/// Confirmation dialog configuration for a row or bulk action.
#[derive(Debug, Clone)]
pub struct ActionConfirmation {
    /// The dialog's heading, such as `Refund this order?`.
    pub title: String,
    /// What will happen, in a sentence or two.
    pub description: String,
    /// The text of the button that runs the action.
    pub confirm_label: String,
}

impl ActionConfirmation {
    /// A confirmation with a heading and a description. Its button says `Confirm`.
    #[must_use]
    pub fn new(title: impl Into<String>, description: impl Into<String>) -> Self {
        Self {
            title: title.into(),
            description: description.into(),
            confirm_label: "Confirm".to_owned(),
        }
    }

    /// Sets the text of the button that runs the action, such as `Refund`.
    #[must_use]
    pub fn confirm_label(mut self, label: impl Into<String>) -> Self {
        self.confirm_label = label.into();
        self
    }

    pub(crate) fn to_dto(&self) -> ActionConfirmationDto {
        ActionConfirmationDto {
            title: self.title.clone(),
            description: self.description.clone(),
            confirm_label: self.confirm_label.clone(),
        }
    }
}

/// What an action's handler knows besides the records it runs on: the request, and what the user
/// entered in the action's fields.
///
/// The context owns what it holds, so a handler can move it into an `async move` block and keep
/// using it across `.await`s:
///
/// ```ignore
/// RowAction::new("refund", "Refund", |context, mut order: Order| async move {
///     let reason = context.string("reason").unwrap_or_default();
///     let staff = context.request().user::<User>().await?;
///     // ...
///     Ok(ActionOutcome::message("Refunded."))
/// })
/// ```
#[derive(Debug, Clone)]
pub struct ActionContext {
    request: Arc<Request>,
    data: Arc<BTreeMap<String, serde_json::Value>>,
}

impl ActionContext {
    pub(crate) fn new(request: &Arc<Request>, data: BTreeMap<String, serde_json::Value>) -> Self {
        Self {
            request: Arc::clone(request),
            data: Arc::new(data),
        }
    }

    /// The request that runs the action, for reading the user or the session.
    #[must_use]
    pub fn request(&self) -> &Request {
        &self.request
    }

    /// Everything the user entered in the action's fields, by field name.
    #[must_use]
    pub fn data(&self) -> &BTreeMap<String, serde_json::Value> {
        &self.data
    }

    /// Read a string field submitted in an action modal form.
    #[must_use]
    pub fn string(&self, key: &str) -> Option<&str> {
        self.data.get(key).and_then(serde_json::Value::as_str)
    }

    /// Read a boolean field submitted in an action modal form.
    #[must_use]
    pub fn bool(&self, key: &str) -> Option<bool> {
        self.data.get(key).and_then(serde_json::Value::as_bool)
    }

    /// Read a raw JSON value submitted in an action modal form.
    #[must_use]
    pub fn get(&self, key: &str) -> Option<&serde_json::Value> {
        self.data.get(key)
    }
}

/// Outcome returned from an action handler.
#[derive(Debug, Clone)]
pub struct ActionOutcome {
    /// What the panel tells the user once the action is done.
    pub message: String,
    /// How many records the action changed.
    pub affected: u64,
    /// A path inside the panel to go to afterward, such as `/resources/orders`.
    pub redirect_to: Option<String>,
    /// Whether the panel reloads the table afterward.
    pub refresh: bool,
}

impl ActionOutcome {
    /// Return a success toast message and refresh the current table/record.
    #[must_use]
    pub fn message(message: impl Into<String>) -> Self {
        Self {
            message: message.into(),
            affected: 1,
            redirect_to: None,
            refresh: true,
        }
    }

    /// Set how many rows were affected by the action.
    #[must_use]
    pub fn affected(mut self, count: u64) -> Self {
        self.affected = count;
        self
    }

    /// Redirect the SPA to another path after showing the toast.
    #[must_use]
    pub fn redirect(mut self, path: impl Into<String>) -> Self {
        self.redirect_to = Some(path.into());
        self
    }

    pub(crate) fn into_response(self) -> ActionResponse {
        ActionResponse {
            message: self.message,
            affected: self.affected,
            redirect_to: self.redirect_to,
            refresh: self.refresh,
        }
    }
}

type Handler<T> = Arc<dyn Fn(ActionContext, T) -> BoxFuture<'static, laravel::Result<ActionOutcome>> + Send + Sync>;

/// Decides, from a record alone, whether a row action applies to it.
type Availability<M> = Arc<dyn Fn(&M) -> bool + Send + Sync>;

/// A custom action on one record, offered in the row's menu and in the record's details.
pub struct RowAction<M: Model> {
    pub(crate) name: String,
    pub(crate) label: String,
    pub(crate) icon: Option<String>,
    pub(crate) destructive: bool,
    pub(crate) confirmation: Option<ActionConfirmation>,
    pub(crate) fields: Vec<Field>,
    pub(crate) handler: Handler<M>,
    pub(crate) available: Option<Availability<M>>,
}

/// A custom action on every selected record, offered in the bar that appears once rows are
/// selected.
pub struct BulkAction<M: Model> {
    pub(crate) name: String,
    pub(crate) label: String,
    pub(crate) icon: Option<String>,
    pub(crate) destructive: bool,
    pub(crate) confirmation: Option<ActionConfirmation>,
    pub(crate) fields: Vec<Field>,
    pub(crate) handler: Handler<Vec<M>>,
}

/// What row actions and bulk actions have in common, which is everything but what they run on.
macro_rules! action {
    ($name:ident, $target:ty, $new_doc:literal $(, $field:ident: $value:expr)?) => {
        impl<M: Model> $name<M> {
            #[doc = $new_doc]
            ///
            /// `name` identifies the action in URLs and in
            /// [`authorize_action`](crate::AdminResource::authorize_action), and `label` is what
            /// the user sees. The handler returns the [`ActionOutcome`] to show, or an error,
            /// whose message the panel shows instead.
            #[must_use]
            pub fn new<F, Fut>(name: impl Into<String>, label: impl Into<String>, handler: F) -> Self
            where
                F: Fn(ActionContext, $target) -> Fut + Send + Sync + 'static,
                Fut: Future<Output = laravel::Result<ActionOutcome>> + Send + 'static,
            {
                Self {
                    name: name.into(),
                    label: label.into(),
                    icon: None,
                    destructive: false,
                    confirmation: None,
                    fields: Vec::new(),
                    handler: Arc::new(move |context, target| Box::pin(handler(context, target))),
                    $($field: $value,)?
                }
            }

            /// Sets the icon shown beside the action's label, by name, such as `package`.
            #[must_use]
            pub fn icon(mut self, icon: impl Into<String>) -> Self {
                self.icon = Some(icon.into());
                self
            }

            /// Marks the action as destructive, so the panel shows it in red.
            #[must_use]
            pub fn destructive(mut self) -> Self {
                self.destructive = true;
                self
            }

            /// Asks the user to confirm before the action runs, with this heading and description.
            #[must_use]
            pub fn confirm(mut self, title: impl Into<String>, description: impl Into<String>) -> Self {
                self.confirmation = Some(ActionConfirmation::new(title, description));
                self
            }

            /// Asks the user to confirm before the action runs, with a confirmation you built,
            /// such as one with its own button label.
            #[must_use]
            pub fn confirmation(mut self, confirmation: ActionConfirmation) -> Self {
                self.confirmation = Some(confirmation);
                self
            }

            /// Adds a field to fill in before the action runs, such as a reason. The handler
            /// reads what the user entered from its [`ActionContext`].
            #[must_use]
            pub fn field(mut self, field: Field) -> Self {
                self.fields.push(field);
                self
            }

            pub(crate) fn to_dto(&self) -> ActionSchemaDto {
                ActionSchemaDto {
                    name: self.name.clone(),
                    label: self.label.clone(),
                    icon: self.icon.clone(),
                    destructive: self.destructive,
                    confirmation: self.confirmation.as_ref().map(ActionConfirmation::to_dto),
                    fields: self.fields.iter().map(Field::to_dto).collect(),
                }
            }
        }
    };
}

action!(
    RowAction,
    M,
    "An action whose handler receives the record it runs on.",
    available: None
);

action!(
    BulkAction,
    Vec<M>,
    "An action whose handler receives every selected record."
);

impl<M: Model> RowAction<M> {
    /// Offers the action only for the records the closure accepts, such as "ship" only for an
    /// order that is paid. The panel leaves the action out of every other record's menu, and
    /// refuses to run it on them.
    ///
    /// ```ignore
    /// RowAction::new("ship", "Mark as shipped", ship)
    ///     .available_when(|order: &Order| order.status == OrderStatus::Paid)
    /// ```
    ///
    /// This is about the record. Whether the user may run the action is for
    /// [`authorize_action`](crate::AdminResource::authorize_action) to say.
    #[must_use]
    pub fn available_when(mut self, available: impl Fn(&M) -> bool + Send + Sync + 'static) -> Self {
        self.available = Some(Arc::new(available));
        self
    }

    /// Whether the action applies to the record.
    pub(crate) fn is_available(&self, record: &M) -> bool {
        self.available.as_ref().is_none_or(|available| available(record))
    }
}