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/// `template` with each `{key}` replaced by the record's value for `key`, percent-encoded but
291/// for the URL's unreserved characters.
292fn fill(template: &str, record: &Row) -> String {
293 let mut out = String::with_capacity(template.len());
294 let mut rest = template;
295 while let Some(open) = rest.find('{') {
296 let Some(close) = rest[open..].find('}') else {
297 break;
298 };
299 out.push_str(&rest[..open]);
300 let key = &rest[open + 1..open + close];
301 let value = match record.get(key) {
302 Some(Value::String(text)) => text.clone(),
303 Some(Value::Null) | None => String::new(),
304 Some(other) => other.to_string(),
305 };
306 for byte in value.bytes() {
307 if byte.is_ascii_alphanumeric() || b"-._~".contains(&byte) {
308 out.push(byte as char);
309 } else {
310 out.push_str(&format!("%{byte:02X}"));
311 }
312 }
313 rest = &rest[open + close + 1..];
314 }
315 out.push_str(rest);
316 out
317}
318
319#[cfg(test)]
320mod tests {
321 use super::*;
322 use serde_json::json;
323
324 fn row(value: Value) -> Row {
325 value.as_object().unwrap().clone()
326 }
327
328 #[test]
329 fn the_label_defaults_to_the_name_made_readable() {
330 assert_eq!(
331 RowAction::make("delete_permanently").get_label(),
332 "Delete permanently"
333 );
334 assert_eq!(
335 RowAction::make("move-to-trash").get_label(),
336 "Move to trash"
337 );
338 assert_eq!(RowAction::make("x").label("Restore").get_label(), "Restore");
339 }
340
341 #[test]
342 fn a_url_fills_the_record_values_encoded() {
343 let action = RowAction::make("view").url("/blog/{slug}?id={id}&none={missing}");
344 let record = row(json!({"id": 7, "slug": "a b&c"}));
345 assert_eq!(
346 action.url_for(&record).unwrap(),
347 "/blog/a%20b%26c?id=7&none="
348 );
349 assert!(!action.is_post());
350 }
351
352 #[test]
353 fn visibility_rules_all_hold() {
354 let action = RowAction::make("restore")
355 .visible_when(ListFilter::new().where_eq("status", "trash"))
356 .hidden(|row| row.get("locked") == Some(&json!(true)));
357 assert!(action.is_visible(&row(json!({"status": "trash"}))));
358 assert!(!action.is_visible(&row(json!({"status": "publish"}))));
359 assert!(!action.is_visible(&row(json!({"status": "trash", "locked": true}))));
360 }
361
362 #[test]
363 fn confirmation_defaults_to_filaments_text() {
364 let action = RowAction::make("trash").requires_confirmation();
365 assert_eq!(action.confirmation(), Some(DEFAULT_CONFIRMATION));
366 let action = RowAction::make("trash").modal_description("Sure?");
367 assert_eq!(action.confirmation(), Some("Sure?"));
368 assert_eq!(RowAction::make("trash").confirmation(), None);
369 }
370}