tablo_core/panel/pages.rs
1//! The handlers behind every registered [`Page`]: its `GET`, and its header actions' `POST`; and
2//! the page as the request's panel mounted it, with the header buttons it renders.
3
4use std::{any::TypeId, sync::Arc};
5
6use topcoat::{
7 context::Cx,
8 router::{
9 Body, RouteFuture,
10 error::{forbidden, not_found},
11 path_param_segment,
12 },
13 view::{BoxView, ViewExt, view},
14};
15
16use super::actions::{input_options, run_header};
17use crate::{
18 FormInput, FormValue, FormValues, HeaderAction, Page, page::MountedPage,
19 topcoat_compat::async_page,
20};
21
22/// `P` as the request's panel mounted it, if it did.
23pub(crate) fn mounted_page<P: Page>(cx: &Cx) -> Option<&Arc<MountedPage>> {
24 mounted(cx, TypeId::of::<P>())
25}
26
27/// The page of type `page` as the request's panel mounted it, if it did.
28fn mounted(cx: &Cx, page: TypeId) -> Option<&Arc<MountedPage>> {
29 super::state::current(cx)?.mounted_pages.get(&page)
30}
31
32/// The page of type `page` as the request's panel mounted it, once the panel's sign-in and the
33/// page's [`PageDef::access`](crate::PageDef::access) admit the request.
34pub(super) fn mounted_admitted(cx: &Cx, page: TypeId) -> Option<&Arc<MountedPage>> {
35 mounted(cx, page).filter(|page| crate::auth::guard(cx).is_ok() && page.admits(cx))
36}
37
38/// The body [`Page::render`] defaults to, installed as the [`PageBody`](crate::page::PageBody):
39/// the page's title and description, its header buttons, and its widget grid.
40pub(super) fn declared_body(cx: &Cx, page: TypeId) -> BoxView<'_> {
41 let Some(mounted) = mounted_admitted(cx, page) else {
42 return ().boxed();
43 };
44 let title = mounted.title.localize(cx);
45 let description = mounted
46 .description
47 .as_ref()
48 .map(|description| description.localize(cx));
49 let buttons = header_buttons(cx, page, mounted);
50 let filters = filter_bar(cx, page, mounted);
51 let grid = super::widgets::page_grid(cx, mounted);
52 view! {
53 tablo_ui::page(
54 tablo_ui::page_header(
55 tablo_ui::page_title((title))
56 if let Some(description) = description {
57 tablo_ui::page_description((description))
58 }
59 tablo_ui::page_actions((buttons))
60 )
61 if let Some(filters) = filters {
62 (filters)
63 }
64 tablo_ui::page_content((grid))
65 )
66 }
67 .boxed()
68}
69
70/// The filter bar of `mounted`, the page of type `page`; `None` when it declares no filter.
71fn filter_bar<'a>(cx: &'a Cx, page: TypeId, mounted: &MountedPage) -> Option<BoxView<'a>> {
72 let url = super::state::current(cx)?.urls.get(&page)?;
73 let held = crate::page::filters::read(&mounted.filters, &crate::table::request_query(cx));
74 super::page_filters::bar(cx, &mounted.filters, &held, url)
75}
76
77/// The filter bar of the page `P`, for a page that renders itself: a form holding each
78/// [`PageDef::filter`](crate::PageDef::filter)'s value, which submits to the page, so its widgets
79/// read the new values through [`page_filters`](crate::page_filters). The default
80/// [`Page::render`](crate::Page::render) places it under the header.
81///
82/// It renders nothing outside a request to `P`'s panel, for a request the panel's sign-in or
83/// [`PageDef::access`](crate::PageDef::access) refuses, and for a page declaring no filter.
84pub fn page_filter_bar<P: Page>(cx: &Cx) -> BoxView<'_> {
85 let page = TypeId::of::<P>();
86 mounted_admitted(cx, page)
87 .and_then(|mounted| filter_bar(cx, page, mounted))
88 .unwrap_or_else(|| ().boxed())
89}
90
91/// The registered page the request's path names, once the panel's sign-in and the page's access
92/// admit the request.
93pub(crate) fn current_page(cx: &Cx) -> Option<&Arc<MountedPage>> {
94 current_entry(cx).and_then(|(page, _)| mounted_admitted(cx, page))
95}
96
97/// The registered page the request is to, and its URL.
98fn current_entry(cx: &Cx) -> Option<(TypeId, &str)> {
99 let panel = super::state::current(cx)?;
100 let path = topcoat::router::request::uri(cx)
101 .path()
102 .trim_end_matches('/');
103 panel
104 .urls
105 .iter()
106 .find(|(page, url)| {
107 url.trim_end_matches('/') == path && panel.mounted_pages.contains_key(*page)
108 })
109 .map(|(page, url)| (*page, url.as_str()))
110}
111
112/// The header bar of the registered page the request is to, holding the actions it may run; empty
113/// on a request to no such page or one it may not open. A page whose body auth renders, such as
114/// the profile placed in an area, shows it so.
115pub(super) fn current_header_bar(cx: &Cx) -> super::bar::ActionBar {
116 current_entry(cx)
117 .and_then(|(page, url)| {
118 let mounted = mounted_admitted(cx, page)?;
119 Some(super::header_bar(
120 cx,
121 url,
122 &mounted.header_actions,
123 |_| true,
124 &[],
125 ))
126 })
127 .unwrap_or_default()
128}
129
130/// The header buttons of `mounted`, the page of type `page`, that the request may run.
131fn header_buttons<'a>(cx: &'a Cx, page: TypeId, mounted: &MountedPage) -> BoxView<'a> {
132 let Some(url) = super::state::current(cx).and_then(|panel| panel.urls.get(&page)) else {
133 return ().boxed();
134 };
135 super::header_bar(cx, url, &mounted.header_actions, |_| true, &[]).render(cx)
136}
137
138/// The header buttons of the page `P` the request may run, for its
139/// [`page_actions`](tablo_ui::page_actions):
140///
141/// ```rust
142/// # use tablo_core::{HeaderAction, Page, PageDef};
143/// # use topcoat::{Result, context::Cx, view::{View, view}};
144/// # struct ClearCache;
145/// # impl HeaderAction for ClearCache {
146/// # type Input = ();
147/// # const NAME: &'static str = "clear-cache";
148/// # async fn run(_: &Cx, _: (), _: &mut dyn toasty::Executor) -> Result<tablo_core::Outcome, tablo_core::WriteError<()>> { Ok(tablo_core::Outcome::done()) }
149/// # }
150/// struct MaintenancePage;
151///
152/// impl Page for MaintenancePage {
153/// fn declare() -> PageDef {
154/// PageDef::new().header_action::<ClearCache>()
155/// }
156///
157/// async fn render(cx: &Cx) -> Result<impl View> {
158/// Ok(view! {
159/// tablo_ui::page(
160/// tablo_ui::page_header(
161/// tablo_ui::page_title("Maintenance")
162/// tablo_ui::page_actions((tablo_core::header_action_buttons::<Self>(cx)))
163/// )
164/// )
165/// })
166/// }
167/// }
168/// ```
169///
170/// It renders nothing outside a request to `P`'s panel, for a request the panel's sign-in or
171/// [`PageDef::access`](crate::PageDef::access) refuses, and no button for an action whose
172/// [`can_run`](crate::HeaderActionDef::can_run) refuses the request.
173pub fn header_action_buttons<P: Page>(cx: &Cx) -> BoxView<'_> {
174 let page = TypeId::of::<P>();
175 match mounted_admitted(cx, page) {
176 Some(mounted) => header_buttons(cx, page, mounted),
177 None => ().boxed(),
178 }
179}
180
181/// The button of `P`'s action `A`, posting `input` instead of asking for it, to place in the page's
182/// content: a plan card's Subscribe, carrying the plan and the interval it offers. `P` declares `A`
183/// with [`PageDef::action`](crate::PageDef::action), which keeps it out of the header, or with
184/// [`PageDef::header_action`](crate::PageDef::header_action).
185///
186/// ```rust
187/// # use tablo_core::{FormInput, HeaderAction, Page, PageDef};
188/// # use topcoat::{Result, context::Cx, view::{View, view}};
189/// #[derive(FormInput)]
190/// struct Plan {
191/// name: String,
192/// }
193///
194/// struct Subscribe;
195///
196/// impl HeaderAction for Subscribe {
197/// type Input = Plan;
198/// const NAME: &'static str = "subscribe";
199/// # async fn run(_: &Cx, _: Plan, _: &mut dyn toasty::Executor) -> Result<tablo_core::Outcome, tablo_core::WriteError<Plan>> { Ok(tablo_core::Outcome::done()) }
200/// }
201///
202/// struct PlansPage;
203///
204/// impl Page for PlansPage {
205/// fn declare() -> PageDef {
206/// PageDef::new().action::<Subscribe>()
207/// }
208///
209/// async fn render(cx: &Cx) -> Result<impl View> {
210/// let plan = Plan { name: "pro".to_string() };
211/// Ok(view! {
212/// tablo_ui::page(
213/// tablo_ui::page_content(
214/// (tablo_core::header_action_button::<Self, Subscribe>(cx, &plan))
215/// )
216/// )
217/// })
218/// }
219/// }
220/// ```
221///
222/// The POST runs as the header bar's would: `input` is parsed and checked again, and a refused one
223/// lands on the action's input page. `A` confirms first when it sets
224/// [`confirm`](crate::HeaderActionDef::confirm). It renders nothing to a request the page or `A`'s
225/// [`can_run`](crate::HeaderActionDef::can_run) refuses, when `P` does not declare `A`, and when
226/// `input` holds a repeater's rows, which no hidden field carries.
227pub fn header_action_button<'a, P: Page, A: HeaderAction>(
228 cx: &'a Cx,
229 input: &A::Input,
230) -> BoxView<'a> {
231 let mut values = FormValues::new();
232 input.write(&mut values);
233 preset_button(cx, TypeId::of::<P>(), A::NAME, values)
234}
235
236/// [`header_action_button`] past its types, so it compiles once.
237fn preset_button<'a>(
238 cx: &'a Cx,
239 page: TypeId,
240 name: &'static str,
241 values: FormValues,
242) -> BoxView<'a> {
243 let mut pairs = Vec::new();
244 for (key, value) in values {
245 match value {
246 FormValue::Text(text) => pairs.push((key, text)),
247 FormValue::List(items) => {
248 pairs.extend(items.into_iter().map(|item| (key.clone(), item)))
249 }
250 FormValue::Rows(_) => {
251 tracing::error!(
252 action = name,
253 key,
254 "a preset input cannot post a repeater's rows"
255 );
256 return ().boxed();
257 }
258 }
259 }
260 let Some(mounted) = mounted_admitted(cx, page) else {
261 return ().boxed();
262 };
263 let (Some(action), Some(url)) = (
264 mounted.header_actions.find(name),
265 super::state::current(cx).and_then(|panel| panel.urls.get(&page)),
266 ) else {
267 return ().boxed();
268 };
269 super::bar::preset_button(cx, url, action, pairs).render(cx)
270}
271
272/// `P` as the request's panel mounted it, once the auth re-check every panel handler runs and the
273/// page's [`PageDef::access`](crate::PageDef::access) admit the request.
274fn admitted<P: Page>(cx: &Cx) -> topcoat::Result<&Arc<MountedPage>> {
275 crate::auth::guard(cx)?;
276 let page = mounted_page::<P>(cx).ok_or_else(not_found)?;
277 if !page.admits(cx) {
278 return Err(forbidden().into());
279 }
280 Ok(page)
281}
282
283/// `GET` for a registered page: [`admitted`], then the page's own body.
284pub(super) fn page_handler<P: Page>(cx: &Cx, _body: Body) -> BoxView<'_> {
285 async_page(async move {
286 admitted::<P>(cx)?;
287 P::render(cx).await
288 })
289}
290
291/// `POST {url}/-/actions/{name}` for a registered page: the same checks as its `GET`, then the
292/// header action's [`can_run`](crate::HeaderActionDef::can_run), landing back on the page.
293pub(super) fn page_action<P: Page>(cx: &Cx, body: Body) -> BoxView<'_> {
294 async_page(async move {
295 let page = admitted::<P>(cx)?;
296 let Some(action) = page
297 .header_actions
298 .find(path_param_segment(cx, "action"))
299 .cloned()
300 else {
301 return Err(not_found().into());
302 };
303 if !(action.can_run)(cx) {
304 return Err(forbidden().into());
305 }
306 let Some(home) = crate::panel::url::page::<P>(cx) else {
307 return Err(not_found().into());
308 };
309 run_header(cx, body, action, &home, None).await
310 })
311}
312
313/// `GET {url}/-/actions/{name}/options` for a registered page: the option search of a header
314/// action's input, behind the same checks as the action's `POST`.
315pub(super) fn page_action_options<P: Page>(cx: &Cx, _body: Body) -> RouteFuture<'_> {
316 Box::pin(async move {
317 let page = admitted::<P>(cx)?;
318 let Some(action) = page.header_actions.find(path_param_segment(cx, "action")) else {
319 return Err(not_found().into());
320 };
321 if !(action.can_run)(cx) {
322 return Err(forbidden().into());
323 }
324 input_options(cx, action.input).await
325 })
326}
327
328#[cfg(test)]
329mod tests;