Skip to main content

tablo_core/resource/action/
def.rs

1//! [`ActionDef`]: where an [`Action`](super::Action)'s button renders, how it reads, and which
2//! records it runs on.
3
4use std::sync::Arc;
5
6use topcoat::{context::Cx, icon::IconData};
7
8use super::Places;
9use crate::{Color, Text, resource::Resource};
10
11/// A closure over the request and one record.
12pub(crate) type RecordFn<M, T> = Arc<dyn Fn(&Cx, &M) -> T + Send + Sync>;
13
14/// A message over a record count.
15pub(crate) type CountFn = Arc<dyn Fn(usize) -> Text + Send + Sync>;
16
17/// What an [`Action`](super::Action) declares besides its name, input and body: where its button
18/// renders, how it reads on each record, and which records it runs on. Every setting has a
19/// default, so [`ActionDef::new`] alone is a button on each row, page header and the bulk bar,
20/// labelled after the action's `NAME`, that runs on every record the policy allows.
21///
22/// ```rust
23/// # #[derive(Debug, Clone, toasty::Model, tablo_core::PanelModel)]
24/// # struct Post {
25/// #     #[key] #[auto] id: uuid::Uuid,
26/// #     status: String,
27/// # }
28/// # use tablo_core::{ActionDef, Color, NoForm, Places, Resource};
29/// # struct PostResource;
30/// # impl Resource for PostResource {
31/// #     type Model = Post;
32/// #     type Form = NoForm<Post>;
33/// # }
34/// let def = ActionDef::<PostResource>::new()
35///     .places(Places::ROW.with(Places::DETAIL))
36///     .icon(tablo_ui::icons::CHECK)
37///     .color(Color::Success)
38///     .can_run(|_cx, post: &Post| post.status != "published")
39///     .disabled_reason(|_cx, _post| Some("Already published".into()));
40/// # let _ = def;
41/// ```
42pub struct ActionDef<R: Resource> {
43    pub(super) places: Places,
44    pub(super) confirm: bool,
45    pub(super) confirmation: Option<Text>,
46    pub(super) icon: Option<IconData>,
47    pub(super) color: Color,
48    pub(super) label: Option<Text>,
49    pub(super) label_for: Option<RecordFn<R::Model, Text>>,
50    pub(super) icon_for: Option<RecordFn<R::Model, Option<IconData>>>,
51    pub(super) tooltip: Option<Text>,
52    pub(super) can_run: Option<RecordFn<R::Model, bool>>,
53    pub(super) disabled_reason: Option<RecordFn<R::Model, Option<Text>>>,
54    pub(super) success: Option<CountFn>,
55}
56
57impl<R: Resource> Default for ActionDef<R> {
58    fn default() -> Self {
59        Self {
60            places: Places::ALL,
61            confirm: false,
62            confirmation: None,
63            icon: None,
64            color: Color::Gray,
65            label: None,
66            label_for: None,
67            icon_for: None,
68            tooltip: None,
69            can_run: None,
70            disabled_reason: None,
71            success: None,
72        }
73    }
74}
75
76impl<R: Resource> std::fmt::Debug for ActionDef<R> {
77    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
78        f.debug_struct("ActionDef")
79            .field("places", &self.places)
80            .field("confirm", &self.confirm)
81            .field("label", &self.label)
82            .finish_non_exhaustive()
83    }
84}
85
86impl<R: Resource> ActionDef<R> {
87    /// Every default: a gray button on each row, page header and the bulk bar, labelled after the
88    /// action's `NAME`, running without confirmation on every record the policy allows.
89    #[must_use]
90    pub fn new() -> Self {
91        Self::default()
92    }
93
94    /// Where the button renders. Defaults to [`Places::ALL`]: each row, the detail and edit
95    /// pages' headers, and the bulk bar.
96    ///
97    /// It decides where the button shows, not who may run it: the record route serves an action
98    /// placed on any of [`Places::RECORD`], and the bulk route one placed on [`Places::BULK`];
99    /// any other POST answers 404. A place no page renders shows the button nowhere:
100    /// [`Places::EDIT`] on a resource without a form, or [`Places::DETAIL`] on one that turns its
101    /// view page off ([`ResourcePage::View`](crate::ResourcePage::View)).
102    #[must_use]
103    pub fn places(mut self, places: Places) -> Self {
104        self.places = places;
105        self
106    }
107
108    /// Asks first, through a confirmation dialog sharing the delete dialog's mechanism and
109    /// destructive wording.
110    ///
111    /// An action with input confirms in its input dialog, or on its input page, instead, which
112    /// say the action cannot be undone and whose submit renders destructive. An unconfirmed POST
113    /// that would write answers 400. Both dialogs need JavaScript: without it their buttons do
114    /// nothing.
115    #[must_use]
116    pub fn confirm(mut self) -> Self {
117        self.confirm = true;
118        self
119    }
120
121    /// Asks first, as [`confirm`](Self::confirm) does, with `question` in place of the message
122    /// `tablo-confirm-run`, "Run this action?". An action with input confirms in its input
123    /// dialog instead, which its label titles.
124    #[must_use]
125    pub fn confirmation(mut self, question: impl Into<Text>) -> Self {
126        self.confirm = true;
127        self.confirmation = Some(question.into());
128        self
129    }
130
131    /// The icon before the button's label, in every place. Defaults to none.
132    #[must_use]
133    pub fn icon(mut self, icon: IconData) -> Self {
134        self.icon = Some(icon);
135        self
136    }
137
138    /// The colour the button is tinted in, as Delete's is in [`Color::Danger`]. Defaults to
139    /// [`Color::Gray`], the untinted button.
140    ///
141    /// It changes how the button looks, not what it asks: [`confirm`](Self::confirm) asks first.
142    #[must_use]
143    pub fn color(mut self, color: Color) -> Self {
144        self.color = color;
145        self
146    }
147
148    /// The button text. Defaults to the message `action-{NAME}` of the panel's catalogs, else
149    /// `NAME` in sentence case: `"publish"` reads "Publish", and `"send-invite"` reads "Send
150    /// invite".
151    ///
152    /// The bulk bar, the input dialogs and the messages read it; a record's button reads
153    /// [`label_for`](Self::label_for) when one is declared.
154    #[must_use]
155    pub fn label(mut self, label: impl Into<Text>) -> Self {
156        self.label = Some(label.into());
157        self
158    }
159
160    /// The text of the button on one record: its row's, or its record page's. Defaults to the
161    /// [`label`](Self::label).
162    ///
163    /// Declare it when the record's state changes what the action reads: "Deactivate" on an
164    /// active employee, "Activate" on one that is not.
165    #[must_use]
166    pub fn label_for(
167        mut self,
168        label: impl Fn(&Cx, &R::Model) -> Text + Send + Sync + 'static,
169    ) -> Self {
170        self.label_for = Some(Arc::new(label));
171        self
172    }
173
174    /// The icon of the button on one record, in its row and on its record page. Defaults to the
175    /// [`icon`](Self::icon).
176    #[must_use]
177    pub fn icon_for(
178        mut self,
179        icon: impl Fn(&Cx, &R::Model) -> Option<IconData> + Send + Sync + 'static,
180    ) -> Self {
181        self.icon_for = Some(Arc::new(icon));
182        self
183    }
184
185    /// The hint a row's button shows on hover, for an action whose label says too little.
186    /// Defaults to none.
187    ///
188    /// A button refused on its record shows its [`disabled_reason`](Self::disabled_reason)
189    /// instead.
190    #[must_use]
191    pub fn tooltip(mut self, tooltip: impl Into<Text>) -> Self {
192        self.tooltip = Some(tooltip.into());
193        self
194    }
195
196    /// Whether the action itself runs on a record, wherever it is mounted: a published post
197    /// refuses "publish". Defaults to every record.
198    ///
199    /// It is one half of [`Ability::Run`](crate::Ability::Run), which the resource allows only
200    /// when both this and its policy do: [`can`](crate::can) answers the two together. Who may
201    /// run the action belongs in the policy, which each panel mounts its own; a rule written here
202    /// holds on every panel and cannot be lifted by one. Asking `can` for this action's own `Run`
203    /// from here would ask this closure again.
204    #[must_use]
205    pub fn can_run(
206        mut self,
207        check: impl Fn(&Cx, &R::Model) -> bool + Send + Sync + 'static,
208    ) -> Self {
209        self.can_run = Some(Arc::new(check));
210        self
211    }
212
213    /// Why the button shows disabled on a record [`can_run`](Self::can_run) refuses, rather than
214    /// hidden: "Already published" for a published post. Defaults to none, which hides it.
215    ///
216    /// It is asked only of a record the policy lets the user view and run the action on, so the
217    /// reason speaks to the record's state and never tells a user what the policy refuses them.
218    /// The route refuses a disabled record as it refuses one `can_run` hides.
219    #[must_use]
220    pub fn disabled_reason(
221        mut self,
222        reason: impl Fn(&Cx, &R::Model) -> Option<Text> + Send + Sync + 'static,
223    ) -> Self {
224        self.disabled_reason = Some(Arc::new(reason));
225        self
226    }
227
228    /// The success notification after a commit that ran on `count` records. Defaults to the
229    /// label and the record count: `"Publish: 3 records"`. A bulk run the action refused on some
230    /// records appends their count out of the selection: `"Publish: 3 records (2 of 5
231    /// skipped)"`.
232    #[must_use]
233    pub fn success(mut self, message: impl Fn(usize) -> Text + Send + Sync + 'static) -> Self {
234        self.success = Some(Arc::new(message));
235        self
236    }
237}