tablo_core/resource/header_action.rs
1//! Actions on no record: the [`HeaderAction`] trait, and the [`HeaderActions`] a
2//! [`Page`](crate::Page) or a [`ResourceDef`](super::ResourceDef) declares them in.
3
4use std::{future::Future, sync::Arc};
5
6use topcoat::{Result, context::Cx, icon::IconData};
7
8mod def;
9
10pub use def::HeaderActionDef;
11
12use super::{ErasedInput, InputResult, InputSpec, parse_validated};
13use crate::{
14 BoxFuture, Color, FormInput,
15 form::{FieldErrors, FormValues},
16 naming::{derived_id, sentence_case},
17 policy::Ability,
18};
19
20/// A mutation that acts on no record, run from a button in a page's header: "import posts",
21/// "clear the cache", "recompute the totals".
22///
23/// A resource declares one with
24/// [`ResourceDef::header_action`](crate::ResourceDef::header_action), and its list page renders
25/// the button; a [`Page`](crate::Page) declares one with
26/// [`PageDef::header_action`](crate::PageDef::header_action), and renders the buttons with
27/// [`header_action_buttons`](crate::header_action_buttons):
28///
29/// ```rust
30/// # use tablo_core::HeaderAction;
31/// # use toasty::Executor;
32/// # use topcoat::{Result, context::Cx};
33/// struct RecountTags;
34///
35/// impl HeaderAction for RecountTags {
36/// type Input = ();
37/// const NAME: &'static str = "recount-tags";
38///
39/// async fn run(
40/// _cx: &Cx,
41/// _: (),
42/// _ex: &mut dyn Executor,
43/// ) -> Result<tablo_core::Outcome, tablo_core::WriteError<()>> {
44/// // Recount through `ex`, the framework's transaction.
45/// Ok(tablo_core::Outcome::done())
46/// }
47/// }
48/// ```
49///
50/// The framework owns everything around [`run`](Self::run), as it does for a record's
51/// [`Action`](crate::Action):
52///
53/// - the route, `{url}/-/actions/{NAME}` under the list or page URL, and its CSRF check;
54/// - who may run it: on a resource, the policy's [`Ability::ViewAny`] and [`Ability::RunHeader`]
55/// with the action's `NAME`; on a page, [`PageDef::access`](crate::PageDef::access); on either,
56/// then [`HeaderActionDef::can_run`]. None runs while someone acts as another user, unless the
57/// [`Impersonation`](crate::Impersonation) is [`writable`](crate::Impersonation::writable). A
58/// refusal answers 403 and renders no button;
59/// - the transaction: `run` writes through its executor, and an error rolls everything back;
60/// - on a resource, the hooks, with [`Change::HeaderAction`](crate::Change::HeaderAction):
61/// [`Resource::before_commit`](crate::Resource::before_commit) in the transaction after `run`,
62/// then [`Resource::after_commit`](crate::Resource::after_commit) once it commits;
63/// - the success notification, and the redirect back to the list as it was left, its search, sort
64/// and filters kept, or to the page.
65///
66/// No record is loaded, so nothing scopes [`run`](Self::run) to the request's tenant: an action
67/// over a tenant's records reads them through [`scoped_query`](crate::scoped_query).
68///
69/// An action that asks for an [`Input`](Self::Input) asks for it as a record's action does, in a
70/// dialog or a page titled with its label, and runs on its submit.
71pub trait HeaderAction: 'static {
72 /// What the action asks for before it runs: `()` for nothing, or an
73 /// [`FormInput`](derive@crate::FormInput) struct.
74 type Input: FormInput;
75
76 /// The action's URL segment, distinct among the actions of its resource or page.
77 ///
78 /// A name that is not a single path segment does not compile, as for
79 /// [`Action::NAME`](crate::Action::NAME).
80 const NAME: &'static str;
81
82 /// How the button reads, whether it asks first, and who it runs for beyond the policy or
83 /// the page's access. Defaults to [`HeaderActionDef::new`]: a gray button labelled after
84 /// [`NAME`](Self::NAME).
85 ///
86 /// The resource or page builds it once, when it adds the action, so it takes no request:
87 /// [`HeaderActionDef::can_run`] receives `cx`.
88 fn declare() -> HeaderActionDef {
89 HeaderActionDef::new()
90 }
91
92 /// Refuse an input [`run`](Self::run) should not receive. Each error names a field of the
93 /// input, picked off its [`Keys`](crate::FormFields::Keys), and renders under its control, as
94 /// [`Action::validate_input`](crate::Action::validate_input) does. Defaults to none.
95 fn validate_input(_cx: &Cx, _input: &Self::Input) -> FieldErrors<Self::Input> {
96 FieldErrors::new()
97 }
98
99 /// The input dialog's buttons beside the action's own, each running the action with one
100 /// checkbox of the input checked, as [`Action::submits`](crate::Action::submits)' do.
101 /// Defaults to none.
102 fn submits(submits: crate::Submits<Self::Input>) -> crate::Submits<Self::Input> {
103 submits
104 }
105
106 /// Perform the action with the parsed `input`, through the framework's transaction `ex`,
107 /// and say what the response does once it commits: [`Outcome::done`](crate::Outcome::done)
108 /// for the [`HeaderActionDef::success`] notification, landing back on the list or page.
109 ///
110 /// Refuses the input with [`WriteError::Refused`](crate::WriteError::Refused), or declines
111 /// with [`WriteError::declined`](crate::WriteError::declined), as
112 /// [`Action::run`](crate::Action::run) does.
113 fn run(
114 cx: &Cx,
115 input: Self::Input,
116 ex: &mut dyn toasty::Executor,
117 ) -> impl Future<Output = Result<crate::Outcome, crate::WriteError<Self::Input>>> + Send;
118}
119
120impl<M> Ability<'_, M> {
121 /// Whether the ability is [`RunHeader`](Ability::RunHeader) for the header action `A`, which
122 /// a resource's policy answers to let the request run it.
123 ///
124 /// ```rust
125 /// # use tablo_core::{Ability, HeaderAction};
126 /// # use topcoat::{Result, context::Cx};
127 /// # #[derive(Debug, Clone, toasty::Model, tablo_core::PanelModel)]
128 /// # struct Post { #[key] #[auto] id: uuid::Uuid }
129 /// # struct RecountTags;
130 /// # impl HeaderAction for RecountTags {
131 /// # type Input = ();
132 /// # const NAME: &'static str = "recount-tags";
133 /// # async fn run(_: &Cx, _: (), _: &mut dyn toasty::Executor) -> Result<tablo_core::Outcome, tablo_core::WriteError<()>> { Ok(tablo_core::Outcome::done()) }
134 /// # }
135 /// # fn is_admin(_cx: &Cx) -> bool { true }
136 /// fn post_policy(cx: &Cx, ability: Ability<'_, Post>) -> bool {
137 /// match ability {
138 /// _ if ability.is_header_action::<RecountTags>() => is_admin(cx),
139 /// Ability::ViewAny | Ability::View(_) => true,
140 /// _ => false,
141 /// }
142 /// }
143 /// ```
144 pub fn is_header_action<A: HeaderAction>(self) -> bool {
145 matches!(self, Ability::RunHeader { action } if action == A::NAME)
146 }
147}
148
149impl<M> crate::policy::Abilities<M> {
150 /// Who may run the header action `A` from the list's header:
151 /// [`RunHeader`](Ability::RunHeader) with `A`'s [`NAME`](HeaderAction::NAME). A header
152 /// action no `run_header` declares is refused.
153 #[must_use]
154 pub fn run_header<A: HeaderAction>(
155 mut self,
156 check: impl Fn(&Cx) -> bool + Send + Sync + 'static,
157 ) -> Self {
158 self.set_header_action(A::NAME, Box::new(check));
159 self
160 }
161}
162
163/// The [`HeaderAction`]s a page or a resource declares, in button order.
164///
165/// ```rust
166/// # use tablo_core::{HeaderAction, HeaderActions};
167/// # use topcoat::{Result, context::Cx};
168/// # struct ClearCache;
169/// # impl HeaderAction for ClearCache {
170/// # type Input = ();
171/// # const NAME: &'static str = "clear-cache";
172/// # async fn run(_: &Cx, _: (), _: &mut dyn toasty::Executor) -> Result<tablo_core::Outcome, tablo_core::WriteError<()>> { Ok(tablo_core::Outcome::done()) }
173/// # }
174/// let actions = HeaderActions::new().add::<ClearCache>();
175/// # let _ = actions;
176/// ```
177#[derive(Default)]
178pub struct HeaderActions {
179 entries: Vec<HeaderEntry>,
180}
181
182impl std::fmt::Debug for HeaderActions {
183 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
184 f.debug_list()
185 .entries(self.entries.iter().map(|e| e.name))
186 .finish()
187 }
188}
189
190impl HeaderActions {
191 /// No action.
192 #[must_use]
193 pub fn new() -> Self {
194 Self::default()
195 }
196
197 /// Appends the action `A`, failing to compile when `A::NAME` is not a single path segment.
198 ///
199 /// The check is a constant evaluated when `A` is instantiated, so `cargo check` does not
200 /// report it; `cargo build` does. The doctest builds the program. Its `E0080` names the
201 /// error, but rustdoc checks the code on nightly only.
202 ///
203 /// ```rust,compile_fail,E0080
204 /// # use tablo_core::{HeaderAction, HeaderActions};
205 /// # use topcoat::{Result, context::Cx};
206 /// struct ClearCache;
207 ///
208 /// impl HeaderAction for ClearCache {
209 /// type Input = ();
210 /// const NAME: &'static str = "clear cache";
211 ///
212 /// async fn run(_: &Cx, _: (), _: &mut dyn toasty::Executor) -> Result<tablo_core::Outcome, tablo_core::WriteError<()>> {
213 /// Ok(tablo_core::Outcome::done())
214 /// }
215 /// }
216 ///
217 /// let _actions = HeaderActions::new().add::<ClearCache>();
218 /// ```
219 #[must_use]
220 pub fn add<A: HeaderAction>(self) -> Self {
221 self.push::<A>(true)
222 }
223
224 /// Appends the action `A`, routed as [`add`](Self::add) routes it, but left out of the header
225 /// bar: the page places its button itself.
226 pub(crate) fn add_unplaced<A: HeaderAction>(self) -> Self {
227 self.push::<A>(false)
228 }
229
230 /// Appends the action `A`, in the header bar when `placed`.
231 fn push<A: HeaderAction>(mut self, placed: bool) -> Self {
232 const {
233 assert!(
234 crate::declaration::segment_fault(A::NAME).is_none(),
235 "`HeaderAction::NAME` must be a single path segment"
236 );
237 }
238 let def = A::declare();
239 let label = def.label.unwrap_or_else(|| {
240 crate::Text::derived(derived_id("action", A::NAME), sentence_case(A::NAME))
241 });
242 let success = def
243 .success
244 .unwrap_or_else(|| crate::text!("tablo-action-done", action = label.clone()));
245 let confirmation = def
246 .confirmation
247 .unwrap_or_else(|| crate::text!("tablo-confirm-run"));
248 let icon = def.icon;
249 self.entries.push(HeaderEntry {
250 name: A::NAME,
251 label: Arc::new(move || label.clone()),
252 can_run: refused_while_writes_are(def.can_run),
253 input: InputSpec::of::<A::Input>(parse_header_input::<A>, || {
254 super::action::erase_submits(A::submits)
255 }),
256 run: run_header_erased::<A>,
257 success: Arc::new(move || success.clone()),
258 confirm: def.confirm,
259 prompt: Arc::new(move || confirmation.clone()),
260 icon: Arc::new(move || icon.clone()),
261 color: def.color,
262 placed,
263 });
264 self
265 }
266
267 /// Whether no action is declared.
268 #[must_use]
269 pub fn is_empty(&self) -> bool {
270 self.entries.is_empty()
271 }
272
273 /// The declared actions, in order.
274 pub(crate) fn entries(&self) -> &[HeaderEntry] {
275 &self.entries
276 }
277
278 /// The action named `name`.
279 pub(crate) fn find(&self, name: &str) -> Option<&HeaderEntry> {
280 self.entries.iter().find(|e| e.name == name)
281 }
282}
283
284/// An erased header action's body: it acts with the parsed input inside the transaction.
285pub(crate) type RunHeader = for<'a> fn(
286 &'a Cx,
287 ErasedInput,
288 &'a mut dyn toasty::Executor,
289) -> BoxFuture<'a, Result<crate::Outcome, crate::WriteError>>;
290
291/// A [`HeaderAction`] with its type erased.
292#[derive(Clone)]
293pub(crate) struct HeaderEntry {
294 pub(crate) name: &'static str,
295 pub(crate) label: Arc<dyn Fn() -> crate::Text + Send + Sync>,
296 pub(crate) can_run: def::RequestCheck,
297 pub(crate) input: InputSpec,
298 pub(crate) run: RunHeader,
299 pub(crate) success: Arc<dyn Fn() -> crate::Text + Send + Sync>,
300 pub(crate) confirm: bool,
301 /// The question the dialog confirming it asks.
302 pub(crate) prompt: Arc<dyn Fn() -> crate::Text + Send + Sync>,
303 /// The icon before its button's label.
304 pub(crate) icon: Arc<dyn Fn() -> Option<IconData> + Send + Sync>,
305 /// The colour its button is tinted in.
306 pub(crate) color: Color,
307 /// Whether the header bar shows its button; one that is not is placed by the page.
308 pub(crate) placed: bool,
309}
310
311/// The action's own check, refusing every request whose writes the panel refuses: one made while
312/// someone acts as another user. Every route and button asks the entry's check, so no caller can
313/// leave it out.
314fn refused_while_writes_are(can_run: Option<def::RequestCheck>) -> def::RequestCheck {
315 Arc::new(move |cx| {
316 !crate::policy::writes_refused(cx) && can_run.as_ref().is_none_or(|can_run| can_run(cx))
317 })
318}
319
320/// [`FormInput::parse`], then [`HeaderAction::validate_input`], behind a function pointer.
321fn parse_header_input<A: HeaderAction>(cx: &Cx, values: &FormValues) -> InputResult {
322 parse_validated(cx, values, A::validate_input)
323}
324
325/// [`HeaderAction::run`] behind a function pointer.
326fn run_header_erased<'a, A: HeaderAction>(
327 cx: &'a Cx,
328 input: ErasedInput,
329 ex: &'a mut dyn toasty::Executor,
330) -> BoxFuture<'a, Result<crate::Outcome, crate::WriteError>> {
331 let input = *input
332 .downcast::<A::Input>()
333 .expect("the pipeline parses the input `run` takes");
334 Box::pin(async move {
335 A::run(cx, input, ex)
336 .await
337 .map_err(|error| error.keyed(<A::Input as FormInput>::key))
338 })
339}