Skip to main content

tablo_core/resource/
action.rs

1//! Custom actions: the [`Action`] trait, and the [`Actions`] list a
2//! [`ResourceDef`](super::ResourceDef) declares them in.
3
4use std::{any::Any, future::Future, sync::Arc};
5
6use derive_where::derive_where;
7use topcoat::{Result, context::Cx, icon::IconData};
8
9mod abilities;
10mod builtin;
11mod def;
12mod keys;
13mod places;
14mod submit;
15
16pub use def::ActionDef;
17pub use keys::filter_keys;
18pub use places::Places;
19pub(crate) use submit::SubmitSpec;
20pub use submit::Submits;
21
22use super::{Mounted, Resource, WriteError};
23use crate::{
24    BoxFuture, Color,
25    form::{FieldError, FieldErrors, FormInput, FormValues},
26    naming::{derived_id, sentence_case},
27    policy::Ability,
28    schema::Schema,
29};
30
31/// The keys an action's POST carries besides its input, which no input field may post.
32pub(crate) const RESERVED_KEYS: [&str; 4] = [crate::csrf::FIELD_NAME, "confirm", "ids", "matching"];
33
34/// A mutation beyond create, update and delete: "publish", "archive",
35/// "resend the invite".
36///
37/// An action runs on one record, from a button in its table row or in the header of its detail or
38/// edit page, or on the selection, from the bulk bar: [`ActionDef::places`] says which.
39/// [`ResourceDef::action`](super::ResourceDef::action) declares it:
40///
41/// ```rust
42/// # #[derive(Debug, Clone, toasty::Model, tablo_core::PanelModel)]
43/// # struct Post {
44/// #     #[key] #[auto] id: uuid::Uuid,
45/// #     title: String,
46/// #     status: String,
47/// # }
48/// # use tablo_core::{Action, ActionDef, NoForm, Resource};
49/// # use toasty::Executor;
50/// # use topcoat::{Result, context::Cx};
51/// # struct PostResource;
52/// #
53/// # impl Resource for PostResource {
54/// #     type Model = Post;
55/// #     type Form = NoForm<Post>;
56/// # }
57/// struct Publish;
58///
59/// impl Action<PostResource> for Publish {
60///     type Input = ();
61///     const NAME: &'static str = "publish";
62///
63///     fn declare() -> ActionDef<PostResource> {
64///         ActionDef::new().can_run(|_cx, post: &Post| post.status != "published")
65///     }
66///
67///     async fn run(
68///         _cx: &Cx,
69///         posts: &[Post],
70///         _: (),
71///         ex: &mut dyn Executor,
72///     ) -> Result<tablo_core::Outcome, tablo_core::WriteError<()>> {
73///         Post::filter(tablo_core::filter_keys(posts))
74///             .update()
75///             .status("published".to_string())
76///             .exec(ex)
77///             .await?;
78///         Ok(tablo_core::Outcome::done())
79///     }
80/// }
81/// ```
82///
83/// The framework owns everything around [`run`](Self::run), as it does for
84/// a delete:
85///
86/// - the route, `{list}/{key}/-/actions/{NAME}` for one record and `{list}/-/actions/{NAME}` for
87///   the selection, and its CSRF check;
88/// - the transaction: the records are loaded through [`scoped_query`](super::scoped_query) inside
89///   it, `run` writes through the same executor, and an error rolls everything back;
90/// - the policy: [`Ability::RunAny`] with the action's `NAME`, asked before the body is read, then
91///   [`Ability::View`] and [`Ability::Run`] on every loaded record before `run`. A record `View`
92///   refuses fails the whole POST with 403;
93/// - the refusal: a row refused `Run`, by the policy or by [`ActionDef::can_run`], answers 403, and
94///   a bulk selection runs the records that pass and reports the refused count as skipped. A
95///   selection that passes on none writes nothing and answers with an error notification;
96/// - the hooks, with [`Change::Action`](super::Change::Action), each record as loaded before `run`
97///   and as reloaded after it: [`Resource::before_commit`] in the transaction after `run`, then
98///   [`Resource::after_commit`] once it commits; and the success notification.
99///
100/// An action that asks for an [`Input`](Self::Input) asks for it first: its button opens the
101/// input's form in a dialog over the page, whose submit runs the action with the parsed value. The
102/// submit parses the input, asks [`validate_input`](Self::validate_input) and checks its choices
103/// before the transaction opens, then re-checks a relationship choice inside it. A refused value
104/// renders the input as a page with its errors and writes nothing; a key the input does not
105/// declare answers 400. The page is titled with the label and the record's title, or the record
106/// count for a selection, and its Cancel returns to the page the button was on. Cancel and Escape
107/// close the dialog, and opening it again starts from a blank form. A searchable relationship
108/// choice searches `{list}/-/actions/{NAME}/options`, behind the checks the POST makes before it
109/// loads a record. The dialog needs JavaScript.
110///
111/// A run from a detail or edit page lands back on that page, its query kept; one from a row or
112/// the bulk bar lands on the list. An action that takes the record out of the resource's
113/// [`query`](super::ResourceDef::query) or its `View`, such as an archive the list hides, lands on
114/// that page's 404: place it on rows and the bulk bar instead.
115///
116/// The bulk bar of a resource's list whose rows span pages offers Select all matching: the
117/// selection then takes every record the list's search and filters select, on any page, rather
118/// than the rows checked. The POST carries the list's query, and the route re-runs it inside the
119/// transaction, so it takes the records that match when it runs. A record the user may not view
120/// is skipped as a refused one is, and more matches than
121/// [`Limits::bulk_records`](crate::Limits::bulk_records) write nothing. A filter the list would
122/// ignore answers 400.
123///
124/// No place renders a button for an action the policy refuses `RunAny`, and no row or page renders
125/// one for a record that fails `View` or `Run`. A record `can_run` refuses shows its button
126/// disabled, saying why, when [`ActionDef::disabled_reason`] gives a reason, and none
127/// otherwise. A row that no bulk action and no delete allows renders no checkbox.
128pub trait Action<R: Resource>: 'static {
129    /// What the action asks for before it runs: `()` for nothing, or an
130    /// [`FormInput`](derive@crate::FormInput) struct, such as a rejection's reason.
131    type Input: FormInput;
132
133    /// The action's URL segment, distinct among the resource's actions.
134    ///
135    /// [`ResourceDef::action`](super::ResourceDef::action) refuses to compile a name that is not
136    /// a single path segment: empty, `.` or `..`, or holding whitespace, a control character, a
137    /// quote, a backslash or one of `/ ? # % & = { } ( )`.
138    /// [`RouterBuilderPanelExt::panel`](crate::RouterBuilderPanelExt::panel) refuses a name that
139    /// another action of the resource shares.
140    ///
141    /// ```rust,compile_fail,E0080
142    /// # use tablo_core::{Action, NoForm, Resource, ResourceDef};
143    /// # use topcoat::{Result, context::Cx};
144    /// # #[derive(Debug, Clone, toasty::Model, tablo_core::PanelModel)]
145    /// # struct Post { #[key] #[auto] id: uuid::Uuid, title: String }
146    /// # struct PostResource;
147    /// # impl Resource for PostResource {
148    /// #     type Model = Post;
149    /// #     type Form = NoForm<Post>;
150    /// # }
151    /// struct Archive;
152    ///
153    /// impl Action<PostResource> for Archive {
154    ///     type Input = ();
155    ///     const NAME: &'static str = "archive/all";
156    /// #   async fn run(_: &Cx, _: &[Post], _: (), _: &mut dyn toasty::Executor) -> Result<tablo_core::Outcome, tablo_core::WriteError<()>> { Ok(tablo_core::Outcome::done()) }
157    /// }
158    ///
159    /// let def = ResourceDef::<PostResource>::new().action::<Archive>();
160    /// ```
161    const NAME: &'static str;
162
163    /// Where the action's button renders, how it reads on each record, and which records it runs
164    /// on. Defaults to [`ActionDef::new`]: a gray button on each row, page header and the bulk
165    /// bar, labelled after [`NAME`](Self::NAME), running without confirmation on every record the
166    /// policy allows.
167    ///
168    /// The resource builds it once, when [`ResourceDef::action`](super::ResourceDef::action)
169    /// adds the action, so it takes no request: what changes per record is a closure, such as
170    /// [`ActionDef::label_for`] or [`ActionDef::can_run`], which receives `cx`.
171    fn declare() -> ActionDef<R> {
172        ActionDef::new()
173    }
174
175    /// Refuse an input [`run`](Self::run) should not receive, such as a reason too short to
176    /// act on: each error names a field of the input, picked off its
177    /// [`Keys`](crate::FormFields::Keys), and renders under its control. Defaults to none.
178    ///
179    /// ```rust
180    /// # use tablo_core::{FieldErrors, FormInput};
181    /// # #[derive(tablo_core::FormInput)]
182    /// # struct Closing { reason: String }
183    /// # fn validate_input(_cx: &topcoat::context::Cx, closing: &Closing) -> FieldErrors<Closing> {
184    /// let mut errors = FieldErrors::<Closing>::new();
185    /// if closing.reason.trim().len() < 10 {
186    ///     errors.add(|f| f.reason, "Say why in ten characters or more");
187    /// }
188    /// # errors
189    /// # }
190    /// ```
191    ///
192    /// It runs after the input parses and before the transaction opens, so it sees no record; a
193    /// rule that reads the database refuses from [`run`](Self::run).
194    fn validate_input(_cx: &Cx, _input: &Self::Input) -> FieldErrors<Self::Input> {
195        FieldErrors::new()
196    }
197
198    /// The input dialog's buttons beside the action's own, each running the action with one
199    /// checkbox of the input checked, such as "Ship and notify" beside "Ship": see [`Submits`].
200    /// Defaults to none.
201    fn submits(submits: Submits<Self::Input>) -> Submits<Self::Input> {
202        submits
203    }
204
205    /// Perform the action on `records`, the records of the row or selection that
206    /// passed [`Ability::Run`] and [`ActionDef::can_run`], with the parsed `input`, through
207    /// the framework's transaction `ex`, and say what the response does once it commits:
208    /// [`Outcome::done`](crate::Outcome::done) for the [`ActionDef::success`] notification,
209    /// landing back where the action ran from. [`filter_keys`](crate::filter_keys) writes one
210    /// change to every record in one statement.
211    ///
212    /// A rule that reads the database refuses the input with [`WriteError::Refused`], keyed by
213    /// the input, as [`validate_input`](Self::validate_input) is: the transaction
214    /// rolls back and the input page renders with the errors. An action that asks for nothing has
215    /// no field to refuse, its `WriteError<()>`, and declines with
216    /// [`WriteError::declined`] instead, which rolls back and flashes the message.
217    fn run(
218        cx: &Cx,
219        records: &[R::Model],
220        input: Self::Input,
221        ex: &mut dyn toasty::Executor,
222    ) -> impl Future<Output = Result<crate::Outcome, WriteError<Self::Input>>> + Send;
223}
224
225/// An erased action's body: it acts on the records with the parsed input inside the transaction.
226pub(crate) type RunAction<R> = for<'a> fn(
227    &'a Cx,
228    &'a [<R as Resource>::Model],
229    ErasedInput,
230    &'a mut dyn toasty::Executor,
231) -> BoxFuture<'a, Result<crate::Outcome, WriteError>>;
232
233/// A parsed [`Action::Input`] with its type erased; `run` downcasts it back.
234pub(crate) type ErasedInput = Box<dyn Any + Send>;
235
236/// What an erased input parse returns.
237pub(crate) type InputResult = std::result::Result<ErasedInput, Vec<FieldError>>;
238
239/// What an action asks for before it runs, its type erased: the input's schema and its parse.
240#[derive(Clone, Copy)]
241pub(crate) struct InputSpec {
242    /// The input form's schema: empty for a delete and an action asking for nothing.
243    pub(crate) schema: fn() -> Schema,
244    /// Whether [`schema`](Self::schema) declares a field, so the action asks for it on a page.
245    pub(crate) takes_input: bool,
246    /// Parses and validates the input from a submission, as the value `run` takes.
247    pub(crate) parse: fn(&Cx, &FormValues) -> InputResult,
248    /// The dialog's buttons beside the action's own, each posting one checkbox checked.
249    pub(crate) submits: fn() -> Vec<SubmitSpec>,
250}
251
252impl InputSpec {
253    /// The input of type `I`, parsed and validated by `parse`, with `submits`' buttons.
254    pub(crate) fn of<I: FormInput>(
255        parse: fn(&Cx, &FormValues) -> InputResult,
256        submits: fn() -> Vec<SubmitSpec>,
257    ) -> Self {
258        Self {
259            schema: I::schema,
260            takes_input: !I::schema().is_empty(),
261            parse,
262            submits,
263        }
264    }
265
266    /// No input: a delete's.
267    pub(crate) fn none() -> Self {
268        Self {
269            schema: Schema::empty,
270            takes_input: false,
271            parse: parse_nothing,
272            submits: Vec::new,
273        }
274    }
275
276    /// The input's form as its dialog and page render it: without the checkboxes a submit posts.
277    pub(crate) fn mask(&self) -> crate::schema::FormMask {
278        (self.submits)()
279            .iter()
280            .fold(crate::schema::FormMask::default(), |mask, submit| {
281                mask.hiding(submit.key)
282            })
283    }
284}
285
286/// The buttons `declare` adds, past the input's type.
287pub(crate) fn erase_submits<I: FormInput>(
288    declare: fn(Submits<I>) -> Submits<I>,
289) -> Vec<SubmitSpec> {
290    declare(Submits::new()).into_specs()
291}
292
293/// The actions a [`Resource`] declares, in button order.
294pub(crate) struct Actions<R: Resource> {
295    entries: Vec<ActionEntry<R>>,
296}
297
298impl<R: Resource> Default for Actions<R> {
299    fn default() -> Self {
300        Self {
301            entries: Vec::new(),
302        }
303    }
304}
305
306impl<R: Resource> std::fmt::Debug for Actions<R> {
307    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
308        f.debug_list()
309            .entries(self.entries.iter().map(|e| e.name))
310            .finish()
311    }
312}
313
314impl<R: Resource> Actions<R> {
315    /// Appends the action `A`, failing to compile when `A::NAME` is not a single path segment.
316    pub(crate) fn add<A: Action<R>>(mut self) -> Self {
317        const {
318            assert!(
319                crate::declaration::segment_fault(A::NAME).is_none(),
320                "`Action::NAME` must be a single path segment"
321            );
322        }
323        let def = A::declare();
324        let label = def.label.unwrap_or_else(|| {
325            crate::Text::derived(derived_id("action", A::NAME), sentence_case(A::NAME))
326        });
327        let state = def.can_run.unwrap_or_else(|| Arc::new(|_, _| true));
328        let success = def.success.unwrap_or_else(|| {
329            let label = label.clone();
330            Arc::new(move |count| {
331                crate::text!(
332                    "tablo-action-on-records",
333                    action = label.clone(),
334                    count = count
335                )
336            })
337        });
338        let confirmation = def
339            .confirmation
340            .unwrap_or_else(|| crate::text!("tablo-confirm-run"));
341        let icon = def.icon;
342        let label_for = def.label_for.unwrap_or_else(|| {
343            let label = label.clone();
344            Arc::new(move |_, _| label.clone())
345        });
346        let icon_for = def.icon_for.unwrap_or_else(|| {
347            let icon = icon.clone();
348            Arc::new(move |_, _| icon.clone())
349        });
350        self.entries.push(ActionEntry {
351            name: A::NAME,
352            label: Arc::new({
353                let label = label.clone();
354                move || label.clone()
355            }),
356            places: def.places,
357            resource_wide: Ability::RunAny { action: A::NAME },
358            can_run: can_run_erased::<R, A>,
359            disabled: disabled_erased::<R>(A::NAME, state.clone(), def.disabled_reason),
360            state,
361            input: InputSpec::of::<A::Input>(parse_input_erased::<R, A>, || {
362                erase_submits(A::submits)
363            }),
364            run: run_erased::<R, A>,
365            success,
366            change: Reports::Acted,
367            failure: "tablo-failed-run",
368            confirm: def.confirm,
369            trashed: super::Trashed::Without,
370            removes: false,
371            prompt: Arc::new(move |_| confirmation.clone()),
372            icon: Arc::new(move || icon.clone()),
373            label_for,
374            icon_for,
375            tooltip: Arc::new({
376                let tooltip = def.tooltip;
377                move || tooltip.clone()
378            }),
379            color: def.color,
380        });
381        self
382    }
383
384    /// Appends the built-in restore and force delete a soft-deleting resource offers on its
385    /// trashed records.
386    pub(crate) fn add_trash_actions(&mut self) {
387        self.entries.push(ActionEntry::restore());
388        self.entries.push(ActionEntry::force_delete());
389    }
390
391    /// The declared actions, in order.
392    pub(crate) fn entries(&self) -> &[ActionEntry<R>] {
393        &self.entries
394    }
395
396    /// The action named `name`.
397    pub(crate) fn find(&self, name: &str) -> Option<&ActionEntry<R>> {
398        self.entries.iter().find(|e| e.name == name)
399    }
400}
401
402/// How a mutation reports its run to the hooks.
403#[derive_where(Clone, Copy)]
404pub(crate) enum Reports<M> {
405    /// The records as the handler loaded them, before the run: a delete names what it removed,
406    /// a restore what it brought back.
407    Snapshot(fn(Vec<M>) -> super::Change<M>),
408    /// [`Change::Action`](super::Change::Action) under the entry's name, each record reloaded
409    /// after the run.
410    Acted,
411}
412
413/// One mutation of a record or a selection with its type erased: a declared action, or the
414/// built-in delete. The panel runs every one through the same pipeline.
415#[derive_where(Clone)]
416pub(crate) struct ActionEntry<R: Resource> {
417    pub(crate) name: &'static str,
418    pub(crate) label: Arc<dyn Fn() -> crate::Text + Send + Sync>,
419    pub(crate) places: Places,
420    /// The resource-wide ability checked before the body is read.
421    pub(crate) resource_wide: Ability<'static, R::Model>,
422    /// Whether the mutation may write `record`, which already passed `View`.
423    pub(crate) can_run: fn(&Mounted<R>, &Cx, &R::Model) -> bool,
424    /// A declared action's own [`ActionDef::can_run`], which [`Ability::Run`] is allowed only
425    /// with.
426    pub(crate) state: def::RecordFn<R::Model, bool>,
427    /// Why its button shows disabled on `record`, which already passed `View`, when the policy
428    /// allows it and the record's state refuses it.
429    pub(crate) disabled: DisabledFn<R>,
430    pub(crate) input: InputSpec,
431    pub(crate) run: RunAction<R>,
432    pub(crate) success: def::CountFn,
433    /// What a run on the records changed, for the hooks.
434    pub(crate) change: Reports<R::Model>,
435    /// The message the failure toast's title reads.
436    pub(crate) failure: &'static str,
437    pub(crate) confirm: bool,
438    /// The records the mutation takes: the live ones, or the trashed ones.
439    pub(crate) trashed: super::Trashed,
440    /// Whether the mutation removes its records, so its button lands on the list rather than on
441    /// the page of a record that no longer exists.
442    pub(crate) removes: bool,
443    /// The question the dialog confirming it asks, of one record or, when `bulk`, of a selection.
444    pub(crate) prompt: Arc<dyn Fn(bool) -> crate::Text + Send + Sync>,
445    /// The icon before its button's label.
446    pub(crate) icon: Arc<dyn Fn() -> Option<IconData> + Send + Sync>,
447    /// The text of its button on one record, in the record's row or on its record page.
448    pub(crate) label_for: def::RecordFn<R::Model, crate::Text>,
449    /// The icon of its button on one record.
450    pub(crate) icon_for: def::RecordFn<R::Model, Option<IconData>>,
451    /// The hint its row's button shows on hover.
452    pub(crate) tooltip: Arc<dyn Fn() -> Option<crate::Text> + Send + Sync>,
453    /// The colour its button is tinted in.
454    pub(crate) color: Color,
455}
456
457impl<R: Resource> ActionEntry<R> {
458    /// Whether the mutation may write `record`, which already passed `View`: the record is live
459    /// or trashed as the mutation takes it, and the mutation's own check allows it.
460    pub(crate) fn allows(&self, resource: &Mounted<R>, cx: &Cx, record: &R::Model) -> bool {
461        self.trashed.admits(resource.is_trashed(record)) && (self.can_run)(resource, cx, record)
462    }
463
464    /// Why the mutation's button shows disabled on `record`, which already passed `View`: the
465    /// record is live or trashed as the mutation takes it, and the reason its own check refuses
466    /// it, if it gives one. `None` for a record it allows.
467    pub(crate) fn disabled_on(
468        &self,
469        resource: &Mounted<R>,
470        cx: &Cx,
471        record: &R::Model,
472    ) -> Option<crate::Text> {
473        if !self.trashed.admits(resource.is_trashed(record)) {
474            return None;
475        }
476        (self.disabled)(resource, cx, record)
477    }
478}
479
480/// [`Ability::Run`] as the resource answers it, [`ActionDef::can_run`] included, behind a function
481/// pointer.
482fn can_run_erased<R: Resource, A: Action<R>>(
483    resource: &Mounted<R>,
484    cx: &Cx,
485    record: &R::Model,
486) -> bool {
487    resource.can(
488        cx,
489        Ability::Run {
490            action: A::NAME,
491            record,
492        },
493    )
494}
495
496/// Why a mutation's button shows disabled on a record, which already passed `View`.
497pub(crate) type DisabledFn<R> =
498    Arc<dyn Fn(&Mounted<R>, &Cx, &<R as Resource>::Model) -> Option<crate::Text> + Send + Sync>;
499
500/// [`ActionDef::disabled_reason`] for a record the mounted policy allows [`Ability::Run`] on and
501/// [`ActionDef::can_run`] refuses.
502fn disabled_erased<R: Resource>(
503    name: &'static str,
504    state: def::RecordFn<R::Model, bool>,
505    reason: Option<def::RecordFn<R::Model, Option<crate::Text>>>,
506) -> DisabledFn<R> {
507    let Some(reason) = reason else {
508        return Arc::new(|_, _, _| None);
509    };
510    Arc::new(move |resource, cx, record| {
511        let run = Ability::Run {
512            action: name,
513            record,
514        };
515        if !resource.policy_allows(cx, run) || state(cx, record) {
516            return None;
517        }
518        reason(cx, record)
519    })
520}
521
522/// [`FormInput::parse`], then [`Action::validate_input`], behind a function pointer.
523fn parse_input_erased<R: Resource, A: Action<R>>(cx: &Cx, values: &FormValues) -> InputResult {
524    parse_validated(cx, values, A::validate_input)
525}
526
527/// `I`'s [`FormInput::parse`], then `validate`, its errors keyed by the form keys they name.
528pub(crate) fn parse_validated<I: FormInput>(
529    cx: &Cx,
530    values: &FormValues,
531    validate: fn(&Cx, &I) -> FieldErrors<I>,
532) -> InputResult {
533    let input = I::parse(cx, values)?;
534    let refused: Vec<FieldError> = validate(cx, &input)
535        .into_iter()
536        .map(|error| FieldError {
537            key: I::key(error.key).to_string(),
538            kind: error.kind,
539        })
540        .collect();
541    if !refused.is_empty() {
542        return Err(refused);
543    }
544    Ok(Box::new(input))
545}
546
547/// A delete's input: nothing.
548fn parse_nothing(_cx: &Cx, _values: &FormValues) -> InputResult {
549    Ok(Box::new(()))
550}
551
552/// [`Action::run`] behind a function pointer.
553fn run_erased<'a, R: Resource, A: Action<R>>(
554    cx: &'a Cx,
555    records: &'a [R::Model],
556    input: ErasedInput,
557    ex: &'a mut dyn toasty::Executor,
558) -> BoxFuture<'a, Result<crate::Outcome, WriteError>> {
559    let input = *input
560        .downcast::<A::Input>()
561        .expect("the pipeline parses the input `run` takes");
562    Box::pin(async move {
563        A::run(cx, records, input, ex)
564            .await
565            .map_err(|error| error.keyed(<A::Input as FormInput>::key))
566    })
567}