tablo_core/panel/url.rs
1//! URLs into the request's panel, so app code never spells a prefix.
2//!
3//! Each helper answers for the panel serving the request: the one whose
4//! prefix the request is under, or the one it entered with
5//! [`PanelHandle::enter`](crate::PanelHandle::enter).
6//! A resource or page that panel does not register has no URL there, and the
7//! helper returns `None`. [`auth`] answers for the pages auth serves: sign-in, profile,
8//! two-factor and the rest of [`AuthPage`].
9//!
10//! Every helper but [`file`](fn@file) also answers in a
11//! [`PanelHandle::context`](crate::PanelHandle::context), so a job or a test spells no path: a
12//! page, a resource, an auth page or a record. A handle [`Panel::handle`](crate::Panel::handle)
13//! gives, which no router mounts, knows only its records' URLs.
14//!
15//! Each helper answers a path. An absolute URL, for a mail or a payment provider's return,
16//! joins it to the router's [`BaseUrl`](topcoat::context::BaseUrl), which a handle's context
17//! carries too: `topcoat::context::try_base_url(cx)?.join(&path)`.
18//!
19//! ```rust,no_run
20//! # use tablo_core::{NoForm, Page, Resource};
21//! # use topcoat::{Result, context::Cx, view::View};
22//! # #[derive(Debug, Clone, toasty::Model, tablo_core::PanelModel)]
23//! # struct Post { #[key] #[auto] id: uuid::Uuid, title: String }
24//! # struct PostResource;
25//! # impl Resource for PostResource {
26//! # type Model = Post;
27//! # type Form = NoForm<Post>;
28//! # }
29//! # struct MediaLibraryPage;
30//! # impl Page for MediaLibraryPage {
31//! # async fn render(_cx: &Cx) -> Result<impl View> { Ok(()) }
32//! # }
33//! # let cx: &Cx = todo!();
34//! let posts = tablo_core::url::resource::<PostResource>(cx); // Some("/admin/posts")
35//! let media = tablo_core::url::page::<MediaLibraryPage>(cx); // Some("/admin/media-library")
36//! let home = tablo_core::url::panel(cx); // Some("/admin")
37//! ```
38
39use std::any::TypeId;
40
41use topcoat::context::Cx;
42
43use super::state::{PanelState, current};
44pub(crate) use crate::naming::{
45 CREATE_ROUTE_SEGMENT, DASH_ROUTE_SEGMENT, create_page_url, list_route,
46};
47use crate::{
48 Page, RecordPage,
49 resource::{Action, Mounted, Places, Resource, mounted},
50 topcoat_compat::href,
51};
52
53/// The panel the helpers answer for: the request's, or a handle's in its context.
54fn serving(cx: &Cx) -> Option<&std::sync::Arc<PanelState>> {
55 current(cx).or_else(|| {
56 topcoat::context::try_context::<super::build::HandlePanel>(cx)
57 .map(|super::build::HandlePanel(panel)| panel)
58 })
59}
60
61/// The request's panel prefix, e.g. `/admin`.
62pub fn panel(cx: &Cx) -> Option<String> {
63 serving(cx).map(|panel| panel.realm.prefix.clone())
64}
65
66/// `R`'s list URL in the request's panel, e.g. `/admin/posts`.
67pub fn resource<R: Resource>(cx: &Cx) -> Option<String> {
68 registered::<R>(cx)
69}
70
71/// `P`'s URL in the request's panel: `{prefix}/{slug}`, or the prefix itself
72/// for the panel's [`home`](super::Panel::home) page.
73pub fn page<P: Page>(cx: &Cx) -> Option<String> {
74 registered::<P>(cx)
75}
76
77/// A page or an endpoint auth serves on a panel, for [`auth`].
78#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
79#[non_exhaustive]
80pub enum AuthPage {
81 /// The sign-in page, `{prefix}/login`: on every panel but an [`Auth::disabled`] one.
82 ///
83 /// [`Auth::disabled`]: crate::Auth::disabled
84 Login,
85 /// Where a sign-out form posts, `{prefix}/logout`, with the CSRF field.
86 Logout,
87 /// The sign-up page of [`Auth::registration`](crate::Auth::registration).
88 Register,
89 /// The forgot-password page of [`Auth::password_reset`](crate::Auth::password_reset).
90 ForgotPassword,
91 /// The notice that asks a user to prove their address, of
92 /// [`Auth::email_verification`](crate::Auth::email_verification).
93 VerifyEmail,
94 /// The profile page of [`Auth::profile`](crate::Auth::profile).
95 Profile,
96 /// The two-factor settings page of [`Auth::two_factor`](crate::Auth::two_factor).
97 TwoFactor,
98 /// The tenant settings page of [`Auth::tenant_profile`](crate::Auth::tenant_profile).
99 TenantProfile,
100 /// The page that creates a tenant, of
101 /// [`Auth::tenant_registration`](crate::Auth::tenant_registration).
102 RegisterTenant,
103 /// Where the tenant switch posts [`TENANT_FIELD`](crate::auth::TENANT_FIELD), on a panel that
104 /// acts for tenants.
105 SwitchTenant,
106 /// Where a form posts [`IMPERSONATE_FIELD`](crate::auth::IMPERSONATE_FIELD) to act as a user,
107 /// under [`Auth::impersonation`](crate::Auth::impersonation).
108 Impersonate,
109 /// Where the Stop form posts to end acting as a user.
110 StopImpersonating,
111}
112
113/// The URL of `page` in the request's panel, such as `/admin/profile`; `None` when the panel's
114/// [`Auth`](crate::Auth) does not serve it, as the other helpers answer for a resource the panel
115/// does not register.
116///
117/// A settings page an [`Area`](crate::Area) holds is served under that area, which this answers.
118///
119/// ```rust,no_run
120/// # use tablo_core::url::{self, AuthPage};
121/// # let cx: &topcoat::context::Cx = todo!();
122/// let profile = url::auth(cx, AuthPage::Profile); // Some("/admin/profile")
123/// ```
124pub fn auth(cx: &Cx, page: AuthPage) -> Option<String> {
125 let realm = &serving(cx)?.realm;
126 let (prefix, auth) = (&realm.prefix, &realm.auth);
127 let under = |served: bool, path: &str| served.then(|| format!("{prefix}/{path}"));
128 match page {
129 AuthPage::Login => under(realm.gates(), "login"),
130 AuthPage::Logout => under(realm.gates(), "logout"),
131 AuthPage::Register => under(auth.registrar().is_some(), "register"),
132 AuthPage::ForgotPassword => under(auth.reset().is_some(), "forgot-password"),
133 AuthPage::VerifyEmail => under(auth.verification().is_some(), "verify-email"),
134 AuthPage::Profile => auth.profile_editor().map(|_| realm.pages.profile.clone()),
135 AuthPage::TwoFactor => auth
136 .asks_two_factor()
137 .then(|| realm.pages.two_factor.clone()),
138 AuthPage::TenantProfile => auth
139 .tenant_editor()
140 .map(|_| realm.pages.tenant_profile.clone()),
141 AuthPage::RegisterTenant => {
142 under(auth.tenant_registration_page().is_some(), "register-tenant")
143 }
144 AuthPage::SwitchTenant => under(realm.gates() && realm.serves_tenants, "tenant"),
145 AuthPage::Impersonate => under(auth.impersonation().is_some(), "impersonate"),
146 AuthPage::StopImpersonating => under(auth.impersonation().is_some(), "impersonate/stop"),
147 }
148}
149
150/// The URL to link or show a stored file at: `path` with a signature that expires, when it
151/// names a file under a [`Panel::uploads_dir`](super::Panel::uploads_dir) of any panel on the
152/// router, and `path` itself otherwise.
153///
154/// Call it only on a page that has checked the user may see the record storing `path`: the URL
155/// opens the file for whoever holds it, for two hours. Each call signs under a fresh nonce, so
156/// two calls for the same path return different URLs.
157///
158/// ```rust,no_run
159/// # let cx: &topcoat::context::Cx = todo!();
160/// let src = tablo_core::url::file(cx, "/uploads/0b9c…-cover.png");
161/// // "/uploads/0b9c…-cover.png?expires=…&signature=…"
162/// ```
163pub fn file(cx: &Cx, path: &str) -> String {
164 let signed = !path.contains(['?', '#'])
165 && topcoat::context::try_context::<super::state::Panels>(cx).is_some_and(|panels| {
166 panels.0.iter().any(|panel| {
167 panel
168 .signed_roots
169 .iter()
170 .any(|root| path.starts_with(root.as_str()))
171 })
172 });
173 if signed {
174 crate::upload::signed::sign(cx, path, crate::upload::signed::now())
175 } else {
176 path.to_owned()
177 }
178}
179
180fn registered<T: 'static>(cx: &Cx) -> Option<String> {
181 serving(cx).and_then(|panel| panel.urls.get(&TypeId::of::<T>()).cloned())
182}
183
184/// `record`'s detail page in the context's panel, e.g. `/admin/posts/42`, or `None` when `R`
185/// declares no detail.
186///
187/// This and the other record helpers return `None` when the panel does not mount `R`, when `R`'s
188/// key has no URL form, or when the panel serves no such route for `R`.
189pub fn record<R: Resource>(cx: &Cx, record: &R::Model) -> Option<String> {
190 keyed::<R>(cx, record, Mounted::viewed).map(|(list, key)| row_view_url(&list, &key))
191}
192
193/// `record`'s edit page, e.g. `/admin/posts/42/edit`, or `None` when `R` has no record form.
194pub fn edit<R: Resource>(cx: &Cx, record: &R::Model) -> Option<String> {
195 keyed::<R>(cx, record, |mounted| mounted.pages.edit)
196 .map(|(list, key)| row_edit_url(&list, &key))
197}
198
199/// `record`'s record page `P`, e.g. `/admin/orders/42/history`, or `None` when `R` does not
200/// declare `P`. The URL answers 403 to a request the page's access refuses.
201pub fn record_page<R: Resource, P: RecordPage<R>>(cx: &Cx, record: &R::Model) -> Option<String> {
202 let page = TypeId::of::<P>();
203 let mounted = mounted::<R>(cx)?;
204 let slug = &mounted
205 .record_pages
206 .iter()
207 .find(|entry| entry.page == page)?
208 .slug;
209 keyed::<R>(cx, record, |_| true).map(|(list, key)| record_page_url(&list, &key, slug))
210}
211
212/// The route that deletes `record`, e.g. `/admin/posts/42/delete`, which takes `confirm=1`.
213pub fn delete<R: Resource>(cx: &Cx, record: &R::Model) -> Option<String> {
214 keyed::<R>(cx, record, |_| true).map(|(list, key)| delete_action_url(&list, &key))
215}
216
217/// `R`'s create page, e.g. `/admin/posts/-/create`, or `None` when `R` serves none.
218pub fn create<R: Resource>(cx: &Cx) -> Option<String> {
219 mounted::<R>(cx)
220 .filter(|mounted| mounted.pages.create)
221 .map(|mounted| create_page_url(&mounted.url))
222}
223
224/// The route the action `A` runs on `record` at, e.g. `/admin/posts/42/-/actions/publish`, or
225/// `None` when `R` does not declare `A` on a record: on its rows, detail or edit page.
226pub fn action<R: Resource, A: Action<R>>(cx: &Cx, record: &R::Model) -> Option<String> {
227 keyed::<R>(cx, record, |mounted| {
228 declares::<R, A>(mounted, Places::RECORD)
229 })
230 .map(|(list, key)| row_action_url(&list, &key, A::NAME))
231}
232
233/// The route the action `A` runs on a selection at, e.g. `/admin/posts/-/actions/publish`, which
234/// takes the selected keys in its `ids` field, or `None` when `R` does not declare `A` in its
235/// bulk bar.
236pub fn bulk_action<R: Resource, A: Action<R>>(cx: &Cx) -> Option<String> {
237 mounted::<R>(cx)
238 .filter(|mounted| declares::<R, A>(mounted, Places::BULK))
239 .map(|mounted| bulk_action_url(&mounted.url, A::NAME))
240}
241
242/// `R`'s list URL and `record`'s key, when `R` is mounted, its rows have routes, and `serves`
243/// holds for it.
244fn keyed<R: Resource>(
245 cx: &Cx,
246 record: &R::Model,
247 serves: impl FnOnce(&Mounted<R>) -> bool,
248) -> Option<(String, String)> {
249 let mounted = mounted::<R>(cx)?;
250 (mounted.table.is_addressable() && serves(&*mounted))
251 .then(|| (mounted.url.clone(), mounted.table.key_of(record)))
252}
253
254/// Whether `R` declares `A` in one of `places`: the action routes refuse it elsewhere.
255fn declares<R: Resource, A: Action<R>>(mounted: &Mounted<R>, places: Places) -> bool {
256 mounted
257 .actions
258 .find(A::NAME)
259 .is_some_and(|action| action.places.intersects(places))
260}
261
262// The panel's URL scheme: the path segments its route table registers and the builders its
263// links use, so the routes `register` serves and the links a page emits are spelled once.
264// `TableState` owns a list link's query parameters.
265
266/// The record placeholder the route table registers: `{id}`.
267///
268/// A route *pattern*, not a URL — the link helpers below take the encoded
269/// primary key instead.
270pub(crate) const RECORD_ROUTE_PARAM: &str = "{id}";
271
272/// Path segment of the list's CSV export, under [`DASH_ROUTE_SEGMENT`].
273pub(crate) const EXPORT_ROUTE_SEGMENT: &str = "export";
274
275/// Path segment of the list's CSV import page, under [`DASH_ROUTE_SEGMENT`].
276pub(crate) const IMPORT_ROUTE_SEGMENT: &str = "import";
277
278/// Path segment of the import's template file, under the import page.
279pub(crate) const TEMPLATE_ROUTE_SEGMENT: &str = "template";
280
281/// Path segment of the record form's option search, under [`DASH_ROUTE_SEGMENT`].
282pub(crate) const OPTIONS_ROUTE_SEGMENT: &str = "options";
283
284/// Path segment of a row's edit page.
285pub(crate) const EDIT_ROUTE_SEGMENT: &str = "edit";
286
287/// Path segment of a row's delete POST.
288pub(crate) const DELETE_ROUTE_SEGMENT: &str = "delete";
289
290/// Path segment of the bulk-delete POST, under [`DASH_ROUTE_SEGMENT`].
291pub(crate) const BULK_DELETE_ROUTE_SEGMENT: &str = "bulk-delete";
292
293/// Path segment of the column picker's POST, under [`DASH_ROUTE_SEGMENT`].
294pub(crate) const COLUMNS_ROUTE_SEGMENT: &str = "columns";
295
296/// Path segment before a custom action's name, on a row
297/// (`{prefix}/{key}/-/actions/{name}`) and on the list
298/// (`{list}/-/actions/{name}`).
299pub(crate) const ACTIONS_ROUTE_SEGMENT: &str = "actions";
300
301/// The action-name placeholder the route table registers: `{action}`.
302pub(crate) const ACTION_ROUTE_PARAM: &str = "{action}";
303
304/// Path segment before a record's relation, whose table posts its attach and detach under
305/// `{list}/{key}/-/relations/{relation}`.
306pub(crate) const RELATIONS_ROUTE_SEGMENT: &str = "relations";
307
308/// The relation placeholder the route table registers: `{relation}`, the related resource's slug.
309pub(crate) const RELATION_ROUTE_PARAM: &str = "{relation}";
310
311/// The related record's placeholder the route table registers: `{related}`.
312pub(crate) const RELATED_ROUTE_PARAM: &str = "{related}";
313
314/// A record's relation to the resource at `slug`, which its writes post under:
315/// `{list}/{key}/-/relations/{slug}`.
316pub(crate) fn relation_url(list: &str, key: &str, slug: &str) -> String {
317 format!(
318 "{list}/{}/{DASH_ROUTE_SEGMENT}/{RELATIONS_ROUTE_SEGMENT}/{slug}",
319 href::encode_path_segment(key)
320 )
321}
322
323/// The row's `Edit` link: `{prefix}/{key}/edit`.
324pub(crate) fn row_edit_url(prefix: &str, key: &str) -> String {
325 format!(
326 "{prefix}/{}/{EDIT_ROUTE_SEGMENT}",
327 href::encode_path_segment(key)
328 )
329}
330
331/// The row's `View` link: `{prefix}/{key}` — the detail page.
332pub(crate) fn row_view_url(prefix: &str, key: &str) -> String {
333 format!("{prefix}/{}", href::encode_path_segment(key))
334}
335
336/// A record page's URL: `{prefix}/{key}/{slug}`.
337pub(crate) fn record_page_url(prefix: &str, key: &str, slug: &str) -> String {
338 format!("{prefix}/{}/{slug}", href::encode_path_segment(key))
339}
340
341/// The row delete form's POST target: `{prefix}/{key}/delete`.
342pub(crate) fn delete_action_url(prefix: &str, key: &str) -> String {
343 format!(
344 "{prefix}/{}/{DELETE_ROUTE_SEGMENT}",
345 href::encode_path_segment(key)
346 )
347}
348
349/// A row action's POST target: `{prefix}/{key}/-/actions/{name}`.
350pub(crate) fn row_action_url(prefix: &str, key: &str, name: &str) -> String {
351 format!(
352 "{prefix}/{}/{DASH_ROUTE_SEGMENT}/{ACTIONS_ROUTE_SEGMENT}/{name}",
353 href::encode_path_segment(key)
354 )
355}
356
357/// A bulk or header action's POST target: `{url}/-/actions/{name}` under a list or a page.
358pub(crate) fn bulk_action_url(list_path: &str, name: &str) -> String {
359 format!("{list_path}/{DASH_ROUTE_SEGMENT}/{ACTIONS_ROUTE_SEGMENT}/{name}")
360}
361
362/// The option search of the input of the action `name` under a list or a page:
363/// `{url}/-/actions/{name}/options`.
364pub(crate) fn action_options_url(url: &str, name: &str) -> String {
365 format!(
366 "{}/options",
367 bulk_action_url(url.trim_end_matches('/'), name)
368 )
369}
370
371/// The query parameter marking a page as framed by a creatable choice's dialog: the page renders
372/// without the panel's shell, and a create lands on [`picked_url`] instead of the list.
373pub(crate) const PICK_PARAM: &str = "pick";
374
375/// The route segment of the page a create in pick mode lands on: `{list_path}/-/picked`.
376pub(crate) const PICKED_ROUTE_SEGMENT: &str = "picked";
377
378/// Where a create in pick mode lands: `{list_path}/-/picked?pick=1&key={key}`.
379pub(crate) fn picked_url(list_path: &str, key: &str) -> String {
380 let query = form_urlencoded::Serializer::new(String::new())
381 .append_pair(PICK_PARAM, "1")
382 .append_pair("key", key)
383 .finish();
384 format!("{}?{query}", list_route(list_path, PICKED_ROUTE_SEGMENT))
385}
386
387/// Whether the request's page is framed by a creatable choice's dialog.
388pub(crate) fn picking(cx: &Cx) -> bool {
389 topcoat::router::request::original_uri(cx)
390 .query()
391 .is_some_and(|query| {
392 form_urlencoded::parse(query.as_bytes())
393 .any(|(key, value)| key == PICK_PARAM && value == "1")
394 })
395}
396
397/// The record form's option search: `{list_path}/-/options`.
398pub(crate) fn options_url(list_path: &str) -> String {
399 list_route(list_path, OPTIONS_ROUTE_SEGMENT)
400}
401
402/// The list page's export link: `{list_path}/-/export`.
403pub(crate) fn export_url(list_path: &str) -> String {
404 list_route(list_path, EXPORT_ROUTE_SEGMENT)
405}
406
407/// The list page's import link: `{list_path}/-/import`.
408pub(crate) fn import_url(list_path: &str) -> String {
409 list_route(list_path, IMPORT_ROUTE_SEGMENT)
410}
411
412/// The import page's template link: `{list_path}/-/import/template`.
413pub(crate) fn import_template_url(list_path: &str) -> String {
414 format!("{}/{TEMPLATE_ROUTE_SEGMENT}", import_url(list_path))
415}
416
417/// The column picker's POST target: `{list_path}/-/columns`.
418pub(crate) fn columns_url(list_path: &str) -> String {
419 list_route(list_path, COLUMNS_ROUTE_SEGMENT)
420}
421
422/// The bulk form's POST target: `{list_path}/-/bulk-delete`.
423pub(crate) fn bulk_delete_url(list_path: &str) -> String {
424 list_route(list_path, BULK_DELETE_ROUTE_SEGMENT)
425}
426
427/// The query parameter naming the page a write lands on after it commits,
428/// in place of the resource's list: `?return=/admin/posts/1`. The panel
429/// honours it only for a path under its own prefix.
430pub(crate) const RETURN_PARAM: &str = "return";
431
432/// `url`, which carries no query, with `?return={target}`.
433pub(crate) fn with_return(url: &str, target: &str) -> String {
434 format!("{url}?{RETURN_PARAM}={}", href::encode_query_value(target))
435}