rustango_cms/admin/admin_page.rs
1//! Extension point for **custom admin pages**.
2//!
3//! Authors building on top of `rustango-cms` register a unit-struct
4//! handler via [`crate::register_admin_page!`] and it appears as a
5//! sidebar entry under its declared [`SidebarSection`]. All registered
6//! handlers route through a single dispatcher mounted at
7//! `/cms-admin/x/{slug}`; no per-page router scaffolding to maintain.
8//!
9//! Custom pages inherit the bundled admin chrome — they extend
10//! [`rcms_admin/_base.html`](../templates/_base.html) and get the
11//! sidebar, topbar, action-bar slot, flash banners, theme tokens,
12//! and every class from [`cms.css`](../static/cms.css) for free.
13//!
14//! ## Example
15//!
16//! ```ignore
17//! use axum::response::Response;
18//! use async_trait::async_trait;
19//! use rustango_cms::admin::admin_page::{AdminPageCtx, AdminPageHandler, SidebarSection};
20//!
21//! #[derive(Default)]
22//! pub struct ReportsDashboard;
23//!
24//! #[async_trait]
25//! impl AdminPageHandler for ReportsDashboard {
26//! fn slug(&self) -> &'static str { "reports" } // → /cms-admin/x/reports
27//! fn label(&self) -> &'static str { "Reports" }
28//! fn icon(&self) -> Option<&'static str> { Some("insights") }
29//! fn section(&self) -> SidebarSection { SidebarSection::Site }
30//! async fn render(&self, ctx: AdminPageCtx<'_>) -> Response {
31//! // Build a Tera context, render `reports.html` (host-registered),
32//! // return the response.
33//! todo!()
34//! }
35//! }
36//!
37//! rustango_cms::register_admin_page!(ReportsDashboard);
38//! ```
39
40use axum::http::HeaderMap;
41use axum::response::Response;
42use rustango::extractors::Tenant;
43use std::sync::Arc;
44
45/// Where the custom page's sidebar entry lands. Built-ins:
46/// `Content`, `Site`, `Settings`. Use `Custom(&'static str)` to spin
47/// up a new section heading on demand (e.g. `Custom("Tools")`).
48#[derive(Clone, Copy, Debug, PartialEq, Eq)]
49pub enum SidebarSection {
50 Content,
51 Site,
52 Settings,
53 Custom(&'static str),
54}
55
56impl SidebarSection {
57 /// Human-readable section heading (also the bucket key when
58 /// `_base.html` groups custom pages for rendering).
59 #[must_use]
60 pub fn label(&self) -> &'static str {
61 match self {
62 Self::Content => "Content",
63 Self::Site => "Site",
64 Self::Settings => "Settings",
65 Self::Custom(name) => name,
66 }
67 }
68}
69
70/// Request-scoped context handed to every custom admin page.
71/// References rather than owns so the handler doesn't have to clone
72/// the Tera instance / per-tenant pool.
73pub struct AdminPageCtx<'a> {
74 pub tera: &'a Arc<tera::Tera>,
75 pub tenant: &'a Tenant,
76 pub headers: &'a HeaderMap,
77 /// The signed-in user, which the dispatcher has already resolved.
78 ///
79 /// Without it a custom page can know only that *somebody* is logged
80 /// in, so it cannot gate on a codename — and a page that manages
81 /// anything sensitive has to. It is also what
82 /// [`crate::admin::handlers::add_chrome`] needs to fill in the
83 /// per-user half of the sidebar.
84 pub user: Option<&'a rustango::tenancy::auth::User>,
85}
86
87/// Trait every custom admin page implements. Compiled-in via the
88/// `inventory` registry — see [`crate::register_admin_page!`].
89#[async_trait::async_trait]
90pub trait AdminPageHandler: Send + Sync + 'static {
91 /// URL slug. The page mounts at `/cms-admin/x/<slug>`. Must
92 /// stay stable; bookmarks / links reference this value.
93 fn slug(&self) -> &'static str;
94
95 /// Visible label rendered in the sidebar.
96 fn label(&self) -> &'static str;
97
98 /// Optional Material-symbols icon name (e.g. `"insights"`,
99 /// `"bug_report"`).
100 fn icon(&self) -> Option<&'static str> {
101 None
102 }
103
104 /// Which sidebar section the entry lives under. Defaults to a
105 /// generic `Custom("Tools")` bucket so out-of-the-box behaviour
106 /// keeps third-party pages visually separated from built-ins.
107 fn section(&self) -> SidebarSection {
108 SidebarSection::Custom("Tools")
109 }
110
111 /// Sibling order within the section (ascending). Defaults to 100
112 /// so most third-party pages slot in between built-ins (which use
113 /// lower numbers) without needing to think about ordering.
114 fn sort_order(&self) -> i32 {
115 100
116 }
117
118 /// Codename prefix to surface this page in the role permissions
119 /// matrix. Returning `Some("acme_reports")` adds a
120 /// "Custom admin pages → `<label>`" row with `view` + `edit`
121 /// columns, granting / revoking codenames `acme_reports.view`
122 /// and `acme_reports.edit`. Default `None` means the page is
123 /// not access-controlled by the matrix — hosts can still gate
124 /// inside `render()` manually.
125 fn permission_resource(&self) -> Option<&'static str> {
126 None
127 }
128
129 /// Render the page. The implementation owns its template + form
130 /// dispatch (handlers usually render via Tera with the bundled
131 /// chrome by extending `rcms_admin/_base.html`).
132 async fn render(&self, ctx: AdminPageCtx<'_>) -> Response;
133}
134
135/// Registration entry submitted via `inventory::submit!` by the
136/// `register_admin_page!` macro. Mirrors `PageTypeHandlerRegistration`.
137pub struct AdminPageHandlerRegistration {
138 pub factory: fn() -> Box<dyn AdminPageHandler>,
139}
140
141inventory::collect!(AdminPageHandlerRegistration);
142
143/// Iterator over every registered handler. Used by the sidebar
144/// enumeration in `add_chrome()` and by the route dispatcher.
145pub fn registered_admin_pages() -> impl Iterator<Item = Box<dyn AdminPageHandler>> {
146 inventory::iter::<AdminPageHandlerRegistration>
147 .into_iter()
148 .map(|r| (r.factory)())
149}
150
151/// Find a registered handler by `slug`. Returns `None` for unknown
152/// slugs — the dispatch route maps that to a 404.
153#[must_use]
154pub fn find_admin_page(slug: &str) -> Option<Box<dyn AdminPageHandler>> {
155 registered_admin_pages().find(|h| h.slug() == slug)
156}