ignite-core 0.7.3

Core types for Ignite, the admin panel for Rocket.rs: resources, fields, forms and runtime resources.
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
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
//! Row actions, as Filament's table actions (`$table->recordActions([...])`): buttons on each
//! row of a resource's list that open a URL or run a task on the record, such as Restore,
//! Move to trash and Delete permanently.
//!
//! ```ignore
//! RuntimeResource::new("posts", "Posts", "Post", PostData)
//!     .row_action(
//!         RowAction::make("restore")
//!             .visible_when(ListFilter::new().where_eq("status", "trash"))
//!             .action(|db, user, id, record| Box::pin(async move {
//!                 restore(db, id).await?;
//!                 Ok(Ok(()))
//!             }))
//!             .success_notification_title("Post restored."),
//!     )
//!     .row_action(
//!         RowAction::make("delete_permanently")
//!             .color(BadgeColor::Danger)
//!             .authorize(ActionAbility::Delete)
//!             .requires_confirmation()
//!             .modal_description("Delete this post permanently? This cannot be undone.")
//!             .visible_when(ListFilter::new().where_eq("status", "trash"))
//!             .action(|db, _, id, _| Box::pin(async move {
//!                 delete(db, id).await?;
//!                 Ok(Ok(()))
//!             })),
//!     )
//! ```
//!
//! An action with [`url`](RowAction::url) is a link. An action with
//! [`action`](RowAction::action) is a form that posts to the panel, at
//! `{mount}/{slug}/{id}/actions/{name}`, with the CSRF token. The panel checks the token, the
//! user's ability on the resource ([`authorize`](RowAction::authorize): update by default, or
//! delete), the resource's policy for the record, and the action's visibility rule for the
//! record, then runs the handler. The handler answers `Ok(())`, or `Err(message)` to refuse:
//! the panel shows the message, as Filament's failure notification.

use std::fmt;
use std::sync::Arc;

use orbit_orm::Database;
use serde_json::Value;

use crate::list::{BadgeColor, ListFilter};
use crate::policy::ActingUser;
use crate::runtime_resource::{Row, RuntimeFuture};

/// What a row action's handler answers: `Ok(())` when it is done, or `Err(message)` when it
/// refuses, such as "This post is locked." The panel shows the message to the user.
pub type ActionResult = Result<(), String>;

/// The ability a row action needs on the resource, as Filament's `authorize('update')`: the
/// same check, ability and policy, as the resource's edit or delete.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ActionAbility {
    /// The ability to update the record, as the Edit button needs. The default.
    #[default]
    Update,
    /// The ability to delete the record, as the Delete button needs.
    Delete,
}

/// The default description of a confirmation, as Filament's `requiresConfirmation()` modal.
pub const DEFAULT_CONFIRMATION: &str = "Are you sure you would like to do this?";

type Handler = Arc<
    dyn for<'a> Fn(&'a Database, &'a ActingUser, i64, &'a Row) -> RuntimeFuture<'a, ActionResult>
        + Send
        + Sync,
>;
type Rule = Arc<dyn Fn(&Row) -> bool + Send + Sync>;

/// One action on each row of a resource's list, as Filament's `Action::make($name)` in
/// `recordActions()`. See the [module](self) documentation.
#[derive(Clone)]
pub struct RowAction {
    name: String,
    label: Option<String>,
    url: Option<String>,
    handler: Option<Handler>,
    confirmation: Option<String>,
    rules: Vec<Rule>,
    color: Option<BadgeColor>,
    ability: ActionAbility,
    success: Option<String>,
}

impl fmt::Debug for RowAction {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("RowAction")
            .field("name", &self.name)
            .field("label", &self.label)
            .field("url", &self.url)
            .field("posts", &self.handler.is_some())
            .field("confirmation", &self.confirmation)
            .field("rules", &self.rules.len())
            .field("color", &self.color)
            .field("ability", &self.ability)
            .field("success", &self.success)
            .finish()
    }
}

impl RowAction {
    /// An action named `name`, as Filament's `Action::make('restore')`. The name is the last
    /// segment of the action's address, so it should be a slug such as `delete_permanently`.
    /// Its label defaults to the name with `_` and `-` as spaces and a capital first letter:
    /// "Delete permanently".
    pub fn make(name: impl Into<String>) -> Self {
        RowAction {
            name: name.into(),
            label: None,
            url: None,
            handler: None,
            confirmation: None,
            rules: Vec::new(),
            color: None,
            ability: ActionAbility::Update,
            success: None,
        }
    }

    /// The button's text, as Filament's `label()`.
    pub fn label(mut self, label: impl Into<String>) -> Self {
        self.label = Some(label.into());
        self
    }

    /// Makes the action a link to `template`, as Filament's `url()`. Each `{key}` in it is
    /// replaced by the record's value for `key`, URL-encoded, such as
    /// `"/blog/{slug}?preview=1"` or `"/admin/posts/{id}/revisions"`; a key the record does not
    /// have is replaced by nothing. A link needs no [`authorize`](Self::authorize): the page it
    /// opens checks access, as Filament says of `url()`.
    pub fn url(mut self, template: impl Into<String>) -> Self {
        self.url = Some(template.into());
        self
    }

    /// Makes the action a POST that runs `handler`, as Filament's `action()`. The handler is
    /// given the database, the signed-in user, the record's id and the record, and answers
    /// `Ok(Ok(()))` when done, `Ok(Err(message))` to refuse with a message, or `Err(error)` for
    /// a database error (a server error). Write it as
    /// `|db, user, id, record| Box::pin(async move { ... })`.
    pub fn action<F>(mut self, handler: F) -> Self
    where
        F: for<'a> Fn(
                &'a Database,
                &'a ActingUser,
                i64,
                &'a Row,
            ) -> RuntimeFuture<'a, ActionResult>
            + Send
            + Sync
            + 'static,
    {
        self.handler = Some(Arc::new(handler));
        self
    }

    /// Asks the user before the action runs, as Filament's `requiresConfirmation()`, with
    /// Filament's default text, "Are you sure you would like to do this?".
    pub fn requires_confirmation(mut self) -> Self {
        if self.confirmation.is_none() {
            self.confirmation = Some(DEFAULT_CONFIRMATION.to_string());
        }
        self
    }

    /// The question the confirmation asks, as Filament's `modalDescription()`. It also turns
    /// the confirmation on.
    pub fn modal_description(mut self, text: impl Into<String>) -> Self {
        self.confirmation = Some(text.into());
        self
    }

    /// Shows the action only on the rows for which `rule` holds, as Filament's `visible()`
    /// with a `$record` closure. The panel also refuses to run it on another record. Several
    /// rules must all hold.
    pub fn visible(mut self, rule: impl Fn(&Row) -> bool + Send + Sync + 'static) -> Self {
        self.rules.push(Arc::new(rule));
        self
    }

    /// Hides the action on the rows for which `rule` holds, as Filament's `hidden()`.
    pub fn hidden(mut self, rule: impl Fn(&Row) -> bool + Send + Sync + 'static) -> Self {
        self.rules.push(Arc::new(move |row: &Row| !rule(row)));
        self
    }

    /// Shows the action only on the rows that meet `filter`, such as
    /// `ListFilter::new().where_eq("status", "trash")`: [`visible`](Self::visible) for a rule
    /// that is data, as a runtime resource loads it.
    pub fn visible_when(self, filter: ListFilter) -> Self {
        self.visible(move |row| filter.matches(row))
    }

    /// The button's colour, as Filament's `color()`. `Danger` renders the panel's danger
    /// button; the others render its plain button, with the class `ig-action-<color>` for a
    /// theme. The default is none.
    pub fn color(mut self, color: BadgeColor) -> Self {
        self.color = Some(color);
        self
    }

    /// The ability the action needs, as Filament's `authorize('update')` or
    /// `authorize('delete')`. The default is [`ActionAbility::Update`].
    pub fn authorize(mut self, ability: ActionAbility) -> Self {
        self.ability = ability;
        self
    }

    /// The message shown after the action ran, as Filament's `successNotificationTitle()`.
    /// The default is none: the list shows again without a message.
    pub fn success_notification_title(mut self, title: impl Into<String>) -> Self {
        self.success = Some(title.into());
        self
    }

    /// The action's name.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// The button's text: the label, or the name made readable.
    pub fn get_label(&self) -> String {
        match &self.label {
            Some(label) => label.clone(),
            None => {
                let words = self.name.replace(['_', '-'], " ");
                let mut chars = words.chars();
                match chars.next() {
                    Some(first) => first.to_uppercase().chain(chars).collect(),
                    None => String::new(),
                }
            }
        }
    }

    /// Whether the action posts to the panel: it has a handler.
    pub fn is_post(&self) -> bool {
        self.handler.is_some()
    }

    /// The link of the action for `record`, when it is a link.
    pub fn url_for(&self, record: &Row) -> Option<String> {
        self.url.as_deref().map(|template| fill(template, record))
    }

    /// The confirmation's text, when the action asks first.
    pub fn confirmation(&self) -> Option<&str> {
        self.confirmation.as_deref()
    }

    /// Whether the action shows on `record`: every visibility rule holds.
    pub fn is_visible(&self, record: &Row) -> bool {
        self.rules.iter().all(|rule| rule(record))
    }

    /// The button's colour, if set.
    pub fn get_color(&self) -> Option<BadgeColor> {
        self.color
    }

    /// The ability the action needs.
    pub fn ability(&self) -> ActionAbility {
        self.ability
    }

    /// The message shown after the action ran, if set.
    pub fn success_message(&self) -> Option<&str> {
        self.success.as_deref()
    }

    /// Runs the handler on the record `id`. An action without a handler (a link) answers
    /// `Ok(Err(..))`; the panel does not call it then.
    pub async fn run(
        &self,
        db: &Database,
        user: &ActingUser,
        id: i64,
        record: &Row,
    ) -> Result<ActionResult, orbit_orm::Error> {
        match &self.handler {
            Some(handler) => handler(db, user, id, record).await,
            None => Ok(Err("This action is a link.".to_string())),
        }
    }
}

/// One action on the records the user ticked in a resource's list, as Filament's
/// `BulkAction::make($name)` in `toolbarActions()`. The list shows a checkbox on each row and a
/// select of the bulk actions above the table, with an Apply button, as WordPress's "Bulk
/// actions". See the [module](self) documentation of the row actions for the handler.
///
/// ```ignore
/// RuntimeResource::new("posts", "Posts", "Post", PostData)
///     .bulk_action(
///         BulkAction::make("trash")
///             .label("Move to Trash")
///             .authorize(ActionAbility::Delete)
///             .hidden(|row| row.get("status") == Some(&json!("trash")))
///             .action(|db, user, id, record| Box::pin(async move {
///                 trash(db, id).await?;
///                 Ok(Ok(()))
///             }))
///             .success_notification_title("Moved :count posts to the Trash."),
///     )
/// ```
///
/// The form posts at `{mount}/{slug}/bulk`, with the CSRF token, the action's name
/// (`bulk_action`) and the ids of the ticked records (`ids[]`). The panel checks the token and
/// the user's ability on the resource ([`authorize`](Self::authorize): update by default, or
/// delete), then, for each record, that the user's query finds it, that the resource's policy
/// allows the ability on it, and that the action is not hidden for it, and runs the handler.
/// A record that fails any of these, or whose handler refuses with `Ok(Err(message))`, is
/// reported and the others still run, as WordPress's "N of M updated".
#[derive(Clone)]
pub struct BulkAction {
    name: String,
    label: Option<String>,
    handler: Option<Handler>,
    rules: Vec<Rule>,
    ability: ActionAbility,
    success: Option<String>,
}

impl fmt::Debug for BulkAction {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("BulkAction")
            .field("name", &self.name)
            .field("label", &self.label)
            .field("posts", &self.handler.is_some())
            .field("rules", &self.rules.len())
            .field("ability", &self.ability)
            .field("success", &self.success)
            .finish()
    }
}

impl BulkAction {
    /// An action named `name`, as Filament's `BulkAction::make('trash')`. The name is the value
    /// the select posts, so it should be a slug. Its label defaults to the name made readable,
    /// as [`RowAction::make`]'s.
    pub fn make(name: impl Into<String>) -> Self {
        BulkAction {
            name: name.into(),
            label: None,
            handler: None,
            rules: Vec::new(),
            ability: ActionAbility::Update,
            success: None,
        }
    }

    /// The option's text in the select, as Filament's `label()`.
    pub fn label(mut self, label: impl Into<String>) -> Self {
        self.label = Some(label.into());
        self
    }

    /// The task run for each selected record, as Filament's `action()`: the database, the
    /// signed-in user, the record's id and the record, answering `Ok(Ok(()))` when done,
    /// `Ok(Err(message))` to refuse that record, or `Err(error)` for a database error (that
    /// record is reported as failed). Write it as `|db, user, id, record| Box::pin(async move { ... })`.
    pub fn action<F>(mut self, handler: F) -> Self
    where
        F: for<'a> Fn(
                &'a Database,
                &'a ActingUser,
                i64,
                &'a Row,
            ) -> RuntimeFuture<'a, ActionResult>
            + Send
            + Sync
            + 'static,
    {
        self.handler = Some(Arc::new(handler));
        self
    }

    /// Runs the action only on the records for which `rule` holds, as Filament's `visible()`
    /// with a `$record` closure. A selected record for which it does not hold is skipped and
    /// reported. Several rules must all hold.
    pub fn visible(mut self, rule: impl Fn(&Row) -> bool + Send + Sync + 'static) -> Self {
        self.rules.push(Arc::new(rule));
        self
    }

    /// Skips the records for which `rule` holds, as Filament's `hidden()`.
    pub fn hidden(mut self, rule: impl Fn(&Row) -> bool + Send + Sync + 'static) -> Self {
        self.rules.push(Arc::new(move |row: &Row| !rule(row)));
        self
    }

    /// The ability the action needs on the resource and on each record, as Filament's
    /// `authorize('update')` or `authorize('delete')`. The default is [`ActionAbility::Update`].
    pub fn authorize(mut self, ability: ActionAbility) -> Self {
        self.ability = ability;
        self
    }

    /// The message shown when the action ran on every selected record, as Filament's
    /// `successNotificationTitle()`. `:count` is replaced by the number of records, as a Laravel
    /// translation's `:count` (Filament takes a closure here): "Changed roles for :count users.".
    /// The default is none.
    pub fn success_notification_title(mut self, title: impl Into<String>) -> Self {
        self.success = Some(title.into());
        self
    }

    /// The action's name.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// The option's text: the label, or the name made readable.
    pub fn get_label(&self) -> String {
        match &self.label {
            Some(label) => label.clone(),
            None => RowAction::make(self.name.clone()).get_label(),
        }
    }

    /// Whether the action has a handler. An action without one is not listed and not run.
    pub fn is_runnable(&self) -> bool {
        self.handler.is_some()
    }

    /// The ability the action needs.
    pub fn ability(&self) -> ActionAbility {
        self.ability
    }

    /// Whether the action may run on `record`: every visibility rule holds.
    pub fn is_visible(&self, record: &Row) -> bool {
        self.rules.iter().all(|rule| rule(record))
    }

    /// The success message for `count` records, if set.
    pub fn success_message(&self, count: usize) -> Option<String> {
        self.success
            .as_ref()
            .map(|title| title.replace(":count", &count.to_string()))
    }

    /// Runs the handler on the record `id`. An action without a handler answers `Ok(Err(..))`.
    pub async fn run(
        &self,
        db: &Database,
        user: &ActingUser,
        id: i64,
        record: &Row,
    ) -> Result<ActionResult, orbit_orm::Error> {
        match &self.handler {
            Some(handler) => handler(db, user, id, record).await,
            None => Ok(Err("This action has no handler.".to_string())),
        }
    }
}

/// `template` with each `{key}` replaced by the record's value for `key`, percent-encoded but
/// for the URL's unreserved characters.
fn fill(template: &str, record: &Row) -> String {
    let mut out = String::with_capacity(template.len());
    let mut rest = template;
    while let Some(open) = rest.find('{') {
        let Some(close) = rest[open..].find('}') else {
            break;
        };
        out.push_str(&rest[..open]);
        let key = &rest[open + 1..open + close];
        let value = match record.get(key) {
            Some(Value::String(text)) => text.clone(),
            Some(Value::Null) | None => String::new(),
            Some(other) => other.to_string(),
        };
        for byte in value.bytes() {
            if byte.is_ascii_alphanumeric() || b"-._~".contains(&byte) {
                out.push(byte as char);
            } else {
                out.push_str(&format!("%{byte:02X}"));
            }
        }
        rest = &rest[open + close + 1..];
    }
    out.push_str(rest);
    out
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    fn row(value: Value) -> Row {
        value.as_object().unwrap().clone()
    }

    #[test]
    fn the_label_defaults_to_the_name_made_readable() {
        assert_eq!(
            RowAction::make("delete_permanently").get_label(),
            "Delete permanently"
        );
        assert_eq!(
            RowAction::make("move-to-trash").get_label(),
            "Move to trash"
        );
        assert_eq!(RowAction::make("x").label("Restore").get_label(), "Restore");
    }

    #[test]
    fn a_url_fills_the_record_values_encoded() {
        let action = RowAction::make("view").url("/blog/{slug}?id={id}&none={missing}");
        let record = row(json!({"id": 7, "slug": "a b&c"}));
        assert_eq!(
            action.url_for(&record).unwrap(),
            "/blog/a%20b%26c?id=7&none="
        );
        assert!(!action.is_post());
    }

    #[test]
    fn visibility_rules_all_hold() {
        let action = RowAction::make("restore")
            .visible_when(ListFilter::new().where_eq("status", "trash"))
            .hidden(|row| row.get("locked") == Some(&json!(true)));
        assert!(action.is_visible(&row(json!({"status": "trash"}))));
        assert!(!action.is_visible(&row(json!({"status": "publish"}))));
        assert!(!action.is_visible(&row(json!({"status": "trash", "locked": true}))));
    }

    #[test]
    fn a_bulk_action_has_a_label_a_rule_and_a_count_message() {
        let action = BulkAction::make("move_to_trash")
            .hidden(|row| row.get("status") == Some(&json!("trash")))
            .success_notification_title("Moved :count posts.");
        assert_eq!(action.get_label(), "Move to trash");
        assert_eq!(BulkAction::make("x").label("Trash").get_label(), "Trash");
        assert!(action.is_visible(&row(json!({"status": "draft"}))));
        assert!(!action.is_visible(&row(json!({"status": "trash"}))));
        assert_eq!(action.success_message(3).as_deref(), Some("Moved 3 posts."));
        assert_eq!(BulkAction::make("x").success_message(3), None);
        assert!(!action.is_runnable());
    }

    #[test]
    fn confirmation_defaults_to_filaments_text() {
        let action = RowAction::make("trash").requires_confirmation();
        assert_eq!(action.confirmation(), Some(DEFAULT_CONFIRMATION));
        let action = RowAction::make("trash").modal_description("Sure?");
        assert_eq!(action.confirmation(), Some("Sure?"));
        assert_eq!(RowAction::make("trash").confirmation(), None);
    }
}