Skip to main content

ignite_core/
action.rs

1//! Row actions, as Filament's table actions (`$table->recordActions([...])`): buttons on each
2//! row of a resource's list that open a URL or run a task on the record, such as Restore,
3//! Move to trash and Delete permanently.
4//!
5//! ```ignore
6//! RuntimeResource::new("posts", "Posts", "Post", PostData)
7//!     .row_action(
8//!         RowAction::make("restore")
9//!             .visible_when(ListFilter::new().where_eq("status", "trash"))
10//!             .action(|db, user, id, record| Box::pin(async move {
11//!                 restore(db, id).await?;
12//!                 Ok(Ok(()))
13//!             }))
14//!             .success_notification_title("Post restored."),
15//!     )
16//!     .row_action(
17//!         RowAction::make("delete_permanently")
18//!             .color(BadgeColor::Danger)
19//!             .authorize(ActionAbility::Delete)
20//!             .requires_confirmation()
21//!             .modal_description("Delete this post permanently? This cannot be undone.")
22//!             .visible_when(ListFilter::new().where_eq("status", "trash"))
23//!             .action(|db, _, id, _| Box::pin(async move {
24//!                 delete(db, id).await?;
25//!                 Ok(Ok(()))
26//!             })),
27//!     )
28//! ```
29//!
30//! An action with [`url`](RowAction::url) is a link. An action with
31//! [`action`](RowAction::action) is a form that posts to the panel, at
32//! `{mount}/{slug}/{id}/actions/{name}`, with the CSRF token. The panel checks the token, the
33//! user's ability on the resource ([`authorize`](RowAction::authorize): update by default, or
34//! delete), the resource's policy for the record, and the action's visibility rule for the
35//! record, then runs the handler. The handler answers `Ok(())`, or `Err(message)` to refuse:
36//! the panel shows the message, as Filament's failure notification.
37
38use std::fmt;
39use std::sync::Arc;
40
41use orbit_orm::Database;
42use serde_json::Value;
43
44use crate::list::{BadgeColor, ListFilter};
45use crate::policy::ActingUser;
46use crate::runtime_resource::{Row, RuntimeFuture};
47
48/// What a row action's handler answers: `Ok(())` when it is done, or `Err(message)` when it
49/// refuses, such as "This post is locked." The panel shows the message to the user.
50pub type ActionResult = Result<(), String>;
51
52/// The ability a row action needs on the resource, as Filament's `authorize('update')`: the
53/// same check, ability and policy, as the resource's edit or delete.
54#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
55pub enum ActionAbility {
56    /// The ability to update the record, as the Edit button needs. The default.
57    #[default]
58    Update,
59    /// The ability to delete the record, as the Delete button needs.
60    Delete,
61}
62
63/// The default description of a confirmation, as Filament's `requiresConfirmation()` modal.
64pub const DEFAULT_CONFIRMATION: &str = "Are you sure you would like to do this?";
65
66type Handler = Arc<
67    dyn for<'a> Fn(&'a Database, &'a ActingUser, i64, &'a Row) -> RuntimeFuture<'a, ActionResult>
68        + Send
69        + Sync,
70>;
71type Rule = Arc<dyn Fn(&Row) -> bool + Send + Sync>;
72
73/// One action on each row of a resource's list, as Filament's `Action::make($name)` in
74/// `recordActions()`. See the [module](self) documentation.
75#[derive(Clone)]
76pub struct RowAction {
77    name: String,
78    label: Option<String>,
79    url: Option<String>,
80    handler: Option<Handler>,
81    confirmation: Option<String>,
82    rules: Vec<Rule>,
83    color: Option<BadgeColor>,
84    ability: ActionAbility,
85    success: Option<String>,
86}
87
88impl fmt::Debug for RowAction {
89    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
90        f.debug_struct("RowAction")
91            .field("name", &self.name)
92            .field("label", &self.label)
93            .field("url", &self.url)
94            .field("posts", &self.handler.is_some())
95            .field("confirmation", &self.confirmation)
96            .field("rules", &self.rules.len())
97            .field("color", &self.color)
98            .field("ability", &self.ability)
99            .field("success", &self.success)
100            .finish()
101    }
102}
103
104impl RowAction {
105    /// An action named `name`, as Filament's `Action::make('restore')`. The name is the last
106    /// segment of the action's address, so it should be a slug such as `delete_permanently`.
107    /// Its label defaults to the name with `_` and `-` as spaces and a capital first letter:
108    /// "Delete permanently".
109    pub fn make(name: impl Into<String>) -> Self {
110        RowAction {
111            name: name.into(),
112            label: None,
113            url: None,
114            handler: None,
115            confirmation: None,
116            rules: Vec::new(),
117            color: None,
118            ability: ActionAbility::Update,
119            success: None,
120        }
121    }
122
123    /// The button's text, as Filament's `label()`.
124    pub fn label(mut self, label: impl Into<String>) -> Self {
125        self.label = Some(label.into());
126        self
127    }
128
129    /// Makes the action a link to `template`, as Filament's `url()`. Each `{key}` in it is
130    /// replaced by the record's value for `key`, URL-encoded, such as
131    /// `"/blog/{slug}?preview=1"` or `"/admin/posts/{id}/revisions"`; a key the record does not
132    /// have is replaced by nothing. A link needs no [`authorize`](Self::authorize): the page it
133    /// opens checks access, as Filament says of `url()`.
134    pub fn url(mut self, template: impl Into<String>) -> Self {
135        self.url = Some(template.into());
136        self
137    }
138
139    /// Makes the action a POST that runs `handler`, as Filament's `action()`. The handler is
140    /// given the database, the signed-in user, the record's id and the record, and answers
141    /// `Ok(Ok(()))` when done, `Ok(Err(message))` to refuse with a message, or `Err(error)` for
142    /// a database error (a server error). Write it as
143    /// `|db, user, id, record| Box::pin(async move { ... })`.
144    pub fn action<F>(mut self, handler: F) -> Self
145    where
146        F: for<'a> Fn(
147                &'a Database,
148                &'a ActingUser,
149                i64,
150                &'a Row,
151            ) -> RuntimeFuture<'a, ActionResult>
152            + Send
153            + Sync
154            + 'static,
155    {
156        self.handler = Some(Arc::new(handler));
157        self
158    }
159
160    /// Asks the user before the action runs, as Filament's `requiresConfirmation()`, with
161    /// Filament's default text, "Are you sure you would like to do this?".
162    pub fn requires_confirmation(mut self) -> Self {
163        if self.confirmation.is_none() {
164            self.confirmation = Some(DEFAULT_CONFIRMATION.to_string());
165        }
166        self
167    }
168
169    /// The question the confirmation asks, as Filament's `modalDescription()`. It also turns
170    /// the confirmation on.
171    pub fn modal_description(mut self, text: impl Into<String>) -> Self {
172        self.confirmation = Some(text.into());
173        self
174    }
175
176    /// Shows the action only on the rows for which `rule` holds, as Filament's `visible()`
177    /// with a `$record` closure. The panel also refuses to run it on another record. Several
178    /// rules must all hold.
179    pub fn visible(mut self, rule: impl Fn(&Row) -> bool + Send + Sync + 'static) -> Self {
180        self.rules.push(Arc::new(rule));
181        self
182    }
183
184    /// Hides the action on the rows for which `rule` holds, as Filament's `hidden()`.
185    pub fn hidden(mut self, rule: impl Fn(&Row) -> bool + Send + Sync + 'static) -> Self {
186        self.rules.push(Arc::new(move |row: &Row| !rule(row)));
187        self
188    }
189
190    /// Shows the action only on the rows that meet `filter`, such as
191    /// `ListFilter::new().where_eq("status", "trash")`: [`visible`](Self::visible) for a rule
192    /// that is data, as a runtime resource loads it.
193    pub fn visible_when(self, filter: ListFilter) -> Self {
194        self.visible(move |row| filter.matches(row))
195    }
196
197    /// The button's colour, as Filament's `color()`. `Danger` renders the panel's danger
198    /// button; the others render its plain button, with the class `ig-action-<color>` for a
199    /// theme. The default is none.
200    pub fn color(mut self, color: BadgeColor) -> Self {
201        self.color = Some(color);
202        self
203    }
204
205    /// The ability the action needs, as Filament's `authorize('update')` or
206    /// `authorize('delete')`. The default is [`ActionAbility::Update`].
207    pub fn authorize(mut self, ability: ActionAbility) -> Self {
208        self.ability = ability;
209        self
210    }
211
212    /// The message shown after the action ran, as Filament's `successNotificationTitle()`.
213    /// The default is none: the list shows again without a message.
214    pub fn success_notification_title(mut self, title: impl Into<String>) -> Self {
215        self.success = Some(title.into());
216        self
217    }
218
219    /// The action's name.
220    pub fn name(&self) -> &str {
221        &self.name
222    }
223
224    /// The button's text: the label, or the name made readable.
225    pub fn get_label(&self) -> String {
226        match &self.label {
227            Some(label) => label.clone(),
228            None => {
229                let words = self.name.replace(['_', '-'], " ");
230                let mut chars = words.chars();
231                match chars.next() {
232                    Some(first) => first.to_uppercase().chain(chars).collect(),
233                    None => String::new(),
234                }
235            }
236        }
237    }
238
239    /// Whether the action posts to the panel: it has a handler.
240    pub fn is_post(&self) -> bool {
241        self.handler.is_some()
242    }
243
244    /// The link of the action for `record`, when it is a link.
245    pub fn url_for(&self, record: &Row) -> Option<String> {
246        self.url.as_deref().map(|template| fill(template, record))
247    }
248
249    /// The confirmation's text, when the action asks first.
250    pub fn confirmation(&self) -> Option<&str> {
251        self.confirmation.as_deref()
252    }
253
254    /// Whether the action shows on `record`: every visibility rule holds.
255    pub fn is_visible(&self, record: &Row) -> bool {
256        self.rules.iter().all(|rule| rule(record))
257    }
258
259    /// The button's colour, if set.
260    pub fn get_color(&self) -> Option<BadgeColor> {
261        self.color
262    }
263
264    /// The ability the action needs.
265    pub fn ability(&self) -> ActionAbility {
266        self.ability
267    }
268
269    /// The message shown after the action ran, if set.
270    pub fn success_message(&self) -> Option<&str> {
271        self.success.as_deref()
272    }
273
274    /// Runs the handler on the record `id`. An action without a handler (a link) answers
275    /// `Ok(Err(..))`; the panel does not call it then.
276    pub async fn run(
277        &self,
278        db: &Database,
279        user: &ActingUser,
280        id: i64,
281        record: &Row,
282    ) -> Result<ActionResult, orbit_orm::Error> {
283        match &self.handler {
284            Some(handler) => handler(db, user, id, record).await,
285            None => Ok(Err("This action is a link.".to_string())),
286        }
287    }
288}
289
290/// One action on the records the user ticked in a resource's list, as Filament's
291/// `BulkAction::make($name)` in `toolbarActions()`. The list shows a checkbox on each row and a
292/// select of the bulk actions above the table, with an Apply button, as WordPress's "Bulk
293/// actions". See the [module](self) documentation of the row actions for the handler.
294///
295/// ```ignore
296/// RuntimeResource::new("posts", "Posts", "Post", PostData)
297///     .bulk_action(
298///         BulkAction::make("trash")
299///             .label("Move to Trash")
300///             .authorize(ActionAbility::Delete)
301///             .hidden(|row| row.get("status") == Some(&json!("trash")))
302///             .action(|db, user, id, record| Box::pin(async move {
303///                 trash(db, id).await?;
304///                 Ok(Ok(()))
305///             }))
306///             .success_notification_title("Moved :count posts to the Trash."),
307///     )
308/// ```
309///
310/// The form posts at `{mount}/{slug}/bulk`, with the CSRF token, the action's name
311/// (`bulk_action`) and the ids of the ticked records (`ids[]`). The panel checks the token and
312/// the user's ability on the resource ([`authorize`](Self::authorize): update by default, or
313/// delete), then, for each record, that the user's query finds it, that the resource's policy
314/// allows the ability on it, and that the action is not hidden for it, and runs the handler.
315/// A record that fails any of these, or whose handler refuses with `Ok(Err(message))`, is
316/// reported and the others still run, as WordPress's "N of M updated".
317#[derive(Clone)]
318pub struct BulkAction {
319    name: String,
320    label: Option<String>,
321    handler: Option<Handler>,
322    rules: Vec<Rule>,
323    ability: ActionAbility,
324    success: Option<String>,
325}
326
327impl fmt::Debug for BulkAction {
328    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
329        f.debug_struct("BulkAction")
330            .field("name", &self.name)
331            .field("label", &self.label)
332            .field("posts", &self.handler.is_some())
333            .field("rules", &self.rules.len())
334            .field("ability", &self.ability)
335            .field("success", &self.success)
336            .finish()
337    }
338}
339
340impl BulkAction {
341    /// An action named `name`, as Filament's `BulkAction::make('trash')`. The name is the value
342    /// the select posts, so it should be a slug. Its label defaults to the name made readable,
343    /// as [`RowAction::make`]'s.
344    pub fn make(name: impl Into<String>) -> Self {
345        BulkAction {
346            name: name.into(),
347            label: None,
348            handler: None,
349            rules: Vec::new(),
350            ability: ActionAbility::Update,
351            success: None,
352        }
353    }
354
355    /// The option's text in the select, as Filament's `label()`.
356    pub fn label(mut self, label: impl Into<String>) -> Self {
357        self.label = Some(label.into());
358        self
359    }
360
361    /// The task run for each selected record, as Filament's `action()`: the database, the
362    /// signed-in user, the record's id and the record, answering `Ok(Ok(()))` when done,
363    /// `Ok(Err(message))` to refuse that record, or `Err(error)` for a database error (that
364    /// record is reported as failed). Write it as `|db, user, id, record| Box::pin(async move { ... })`.
365    pub fn action<F>(mut self, handler: F) -> Self
366    where
367        F: for<'a> Fn(
368                &'a Database,
369                &'a ActingUser,
370                i64,
371                &'a Row,
372            ) -> RuntimeFuture<'a, ActionResult>
373            + Send
374            + Sync
375            + 'static,
376    {
377        self.handler = Some(Arc::new(handler));
378        self
379    }
380
381    /// Runs the action only on the records for which `rule` holds, as Filament's `visible()`
382    /// with a `$record` closure. A selected record for which it does not hold is skipped and
383    /// reported. Several rules must all hold.
384    pub fn visible(mut self, rule: impl Fn(&Row) -> bool + Send + Sync + 'static) -> Self {
385        self.rules.push(Arc::new(rule));
386        self
387    }
388
389    /// Skips the records for which `rule` holds, as Filament's `hidden()`.
390    pub fn hidden(mut self, rule: impl Fn(&Row) -> bool + Send + Sync + 'static) -> Self {
391        self.rules.push(Arc::new(move |row: &Row| !rule(row)));
392        self
393    }
394
395    /// The ability the action needs on the resource and on each record, as Filament's
396    /// `authorize('update')` or `authorize('delete')`. The default is [`ActionAbility::Update`].
397    pub fn authorize(mut self, ability: ActionAbility) -> Self {
398        self.ability = ability;
399        self
400    }
401
402    /// The message shown when the action ran on every selected record, as Filament's
403    /// `successNotificationTitle()`. `:count` is replaced by the number of records, as a Laravel
404    /// translation's `:count` (Filament takes a closure here): "Changed roles for :count users.".
405    /// The default is none.
406    pub fn success_notification_title(mut self, title: impl Into<String>) -> Self {
407        self.success = Some(title.into());
408        self
409    }
410
411    /// The action's name.
412    pub fn name(&self) -> &str {
413        &self.name
414    }
415
416    /// The option's text: the label, or the name made readable.
417    pub fn get_label(&self) -> String {
418        match &self.label {
419            Some(label) => label.clone(),
420            None => RowAction::make(self.name.clone()).get_label(),
421        }
422    }
423
424    /// Whether the action has a handler. An action without one is not listed and not run.
425    pub fn is_runnable(&self) -> bool {
426        self.handler.is_some()
427    }
428
429    /// The ability the action needs.
430    pub fn ability(&self) -> ActionAbility {
431        self.ability
432    }
433
434    /// Whether the action may run on `record`: every visibility rule holds.
435    pub fn is_visible(&self, record: &Row) -> bool {
436        self.rules.iter().all(|rule| rule(record))
437    }
438
439    /// The success message for `count` records, if set.
440    pub fn success_message(&self, count: usize) -> Option<String> {
441        self.success
442            .as_ref()
443            .map(|title| title.replace(":count", &count.to_string()))
444    }
445
446    /// Runs the handler on the record `id`. An action without a handler answers `Ok(Err(..))`.
447    pub async fn run(
448        &self,
449        db: &Database,
450        user: &ActingUser,
451        id: i64,
452        record: &Row,
453    ) -> Result<ActionResult, orbit_orm::Error> {
454        match &self.handler {
455            Some(handler) => handler(db, user, id, record).await,
456            None => Ok(Err("This action has no handler.".to_string())),
457        }
458    }
459}
460
461/// `template` with each `{key}` replaced by the record's value for `key`, percent-encoded but
462/// for the URL's unreserved characters.
463fn fill(template: &str, record: &Row) -> String {
464    let mut out = String::with_capacity(template.len());
465    let mut rest = template;
466    while let Some(open) = rest.find('{') {
467        let Some(close) = rest[open..].find('}') else {
468            break;
469        };
470        out.push_str(&rest[..open]);
471        let key = &rest[open + 1..open + close];
472        let value = match record.get(key) {
473            Some(Value::String(text)) => text.clone(),
474            Some(Value::Null) | None => String::new(),
475            Some(other) => other.to_string(),
476        };
477        for byte in value.bytes() {
478            if byte.is_ascii_alphanumeric() || b"-._~".contains(&byte) {
479                out.push(byte as char);
480            } else {
481                out.push_str(&format!("%{byte:02X}"));
482            }
483        }
484        rest = &rest[open + close + 1..];
485    }
486    out.push_str(rest);
487    out
488}
489
490#[cfg(test)]
491mod tests {
492    use super::*;
493    use serde_json::json;
494
495    fn row(value: Value) -> Row {
496        value.as_object().unwrap().clone()
497    }
498
499    #[test]
500    fn the_label_defaults_to_the_name_made_readable() {
501        assert_eq!(
502            RowAction::make("delete_permanently").get_label(),
503            "Delete permanently"
504        );
505        assert_eq!(
506            RowAction::make("move-to-trash").get_label(),
507            "Move to trash"
508        );
509        assert_eq!(RowAction::make("x").label("Restore").get_label(), "Restore");
510    }
511
512    #[test]
513    fn a_url_fills_the_record_values_encoded() {
514        let action = RowAction::make("view").url("/blog/{slug}?id={id}&none={missing}");
515        let record = row(json!({"id": 7, "slug": "a b&c"}));
516        assert_eq!(
517            action.url_for(&record).unwrap(),
518            "/blog/a%20b%26c?id=7&none="
519        );
520        assert!(!action.is_post());
521    }
522
523    #[test]
524    fn visibility_rules_all_hold() {
525        let action = RowAction::make("restore")
526            .visible_when(ListFilter::new().where_eq("status", "trash"))
527            .hidden(|row| row.get("locked") == Some(&json!(true)));
528        assert!(action.is_visible(&row(json!({"status": "trash"}))));
529        assert!(!action.is_visible(&row(json!({"status": "publish"}))));
530        assert!(!action.is_visible(&row(json!({"status": "trash", "locked": true}))));
531    }
532
533    #[test]
534    fn a_bulk_action_has_a_label_a_rule_and_a_count_message() {
535        let action = BulkAction::make("move_to_trash")
536            .hidden(|row| row.get("status") == Some(&json!("trash")))
537            .success_notification_title("Moved :count posts.");
538        assert_eq!(action.get_label(), "Move to trash");
539        assert_eq!(BulkAction::make("x").label("Trash").get_label(), "Trash");
540        assert!(action.is_visible(&row(json!({"status": "draft"}))));
541        assert!(!action.is_visible(&row(json!({"status": "trash"}))));
542        assert_eq!(action.success_message(3).as_deref(), Some("Moved 3 posts."));
543        assert_eq!(BulkAction::make("x").success_message(3), None);
544        assert!(!action.is_runnable());
545    }
546
547    #[test]
548    fn confirmation_defaults_to_filaments_text() {
549        let action = RowAction::make("trash").requires_confirmation();
550        assert_eq!(action.confirmation(), Some(DEFAULT_CONFIRMATION));
551        let action = RowAction::make("trash").modal_description("Sure?");
552        assert_eq!(action.confirmation(), Some("Sure?"));
553        assert_eq!(RowAction::make("trash").confirmation(), None);
554    }
555}