renox_admin/lib.rs
1//! An admin panel for Renox apps, generated from their models (Laravel's
2//! Filament resources): each model is declared once, as an
3//! [`AdminResource`] (its grid columns, its form fields, its policy), and
4//! the panel gives it a list with search, filters, sorting, bulk actions
5//! and exports, and create, edit, view and delete pages, on the UI kit and
6//! `renox::grid`.
7//!
8//! ```
9//! use renox::prelude::*;
10//! use renox_admin::Admin;
11//! # use renox::grid::Column;
12//! # use renox_admin::{AdminResource, Field};
13//! # #[derive(Model, serde::Serialize, Default)] struct Product { id: i64, name: String }
14//! # impl Policy for Product { fn allows(&self, _: &User, _: &str) -> bool { true } }
15//! # #[derive(serde::Deserialize, serde::Serialize, Validate)] struct ProductForm { #[validate(required)] name: String }
16//! # struct Products;
17//! # impl AdminResource for Products {
18//! # type Model = Product;
19//! # type Form = ProductForm;
20//! # fn label(&self) -> &str { "Product" }
21//! # fn plural_label(&self) -> &str { "Products" }
22//! # fn columns(&self) -> Vec<Column> { vec![Column::text("name", "Name")] }
23//! # fn fields(&self) -> Vec<Field> { vec![Field::text("name", "Name")] }
24//! # fn fill(&self, p: &mut Product, f: ProductForm) { p.name = f.name; }
25//! # }
26//!
27//! # let _ =
28//! App::new()
29//! .module(Auth::new())
30//! .module(
31//! Admin::new()
32//! .title("Back office")
33//! .authorize(|user| user.has_role("staff")) // who may open the panel
34//! .resource(Products),
35//! )
36//! # ;
37//! ```
38//!
39//! The panel lives at `/admin` (`path`), behind a login. Nobody gets in
40//! until [`Admin::authorize`] (or [`Admin::gate`]) says who may; then each
41//! page asks the resource's [`AdminResource::allows`], which by default
42//! asks the model's [`Policy`] (`viewAny`, `view`, `create`, `update`,
43//! `delete`, …). Pages are built-in templates (`renox-admin/*.html`) that
44//! an app replaces with files of the same name. The guide is
45//! docs/admin.md in the Renox repository.
46
47#![warn(missing_docs)]
48
49use std::fmt;
50use std::sync::Arc;
51
52use renox::prelude::*;
53
54pub mod entry;
55pub mod field;
56mod panel;
57pub mod resource;
58
59pub use entry::Entry;
60pub use field::{Field, FieldKind};
61pub use resource::{ActionContext, AdminAction, AdminResource, BoxFuture, Filter};
62
63use panel::{Access, Holder, Listed, Panel};
64
65/// The templates, compiled in. An app replaces one with a file of the same
66/// name under its views directory (`resources/views/renox-admin/layout.html`).
67const VIEWS: &[(&str, &str)] = &[
68 (
69 "renox-admin/layout.html",
70 include_str!("../views/layout.html"),
71 ),
72 (
73 "renox-admin/dashboard.html",
74 include_str!("../views/dashboard.html"),
75 ),
76 (
77 "renox-admin/index.html",
78 include_str!("../views/index.html"),
79 ),
80 ("renox-admin/form.html", include_str!("../views/form.html")),
81 ("renox-admin/show.html", include_str!("../views/show.html")),
82 (
83 "renox-admin/fields.html",
84 include_str!("../views/fields.html"),
85 ),
86];
87
88/// The admin panel module: its address, its title, who may use it and its
89/// resources.
90#[derive(Clone)]
91pub struct Admin {
92 path: String,
93 title: String,
94 access: Option<Access>,
95 resources: Vec<Arc<dyn Listed>>,
96}
97
98impl Default for Admin {
99 fn default() -> Self {
100 Self::new()
101 }
102}
103
104impl fmt::Debug for Admin {
105 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
106 f.debug_struct("Admin")
107 .field("path", &self.path)
108 .field("title", &self.title)
109 .field(
110 "resources",
111 &self.resources.iter().map(|r| r.slug()).collect::<Vec<_>>(),
112 )
113 .finish_non_exhaustive()
114 }
115}
116
117impl Admin {
118 /// A panel at `/admin`, titled "Admin", with no resources yet, that
119 /// nobody may open until [`authorize`](Self::authorize) says who may.
120 pub fn new() -> Self {
121 Self {
122 path: "/admin".into(),
123 title: "Admin".into(),
124 access: None,
125 resources: Vec::new(),
126 }
127 }
128
129 /// Where the panel lives (`/admin` by default). The route names stay
130 /// `admin.*`.
131 ///
132 /// # Panics
133 ///
134 /// If `path` doesn't start with `/` or ends with one.
135 pub fn path(mut self, path: &str) -> Self {
136 assert!(
137 path.starts_with('/') && !path.ends_with('/'),
138 "Admin::path(\"{path}\"): it must start with `/` and not end with one"
139 );
140 self.path = path.to_owned();
141 self
142 }
143
144 /// The panel's name, at the top of its navigation and in page titles.
145 pub fn title(mut self, title: &str) -> Self {
146 self.title = title.to_owned();
147 self
148 }
149
150 /// Who may open the panel at all: logged-in users for whom `allows`
151 /// says yes (others get 403, guests go to log in). Without it, nobody
152 /// may.
153 pub fn authorize(mut self, allows: impl Fn(&AuthUser) -> bool + Send + Sync + 'static) -> Self {
154 self.access = Some(Arc::new(allows));
155 self
156 }
157
158 /// Lets in the users the gate `name` lets through (`App::gate`, or a
159 /// permission of that name with the `Permissions` module, after
160 /// `App::gate_before`).
161 pub fn gate(self, name: &str) -> Self {
162 let name = name.to_owned();
163 self.authorize(move |user| user.allows(&name))
164 }
165
166 /// Adds a resource, after the ones before it in the navigation.
167 ///
168 /// # Panics
169 ///
170 /// If its slug isn't letters, digits, `_` and `-`, or another resource
171 /// has it.
172 pub fn resource<R: AdminResource>(mut self, resource: R) -> Self {
173 let slug = resource.slug().to_owned();
174 assert!(
175 !slug.is_empty()
176 && slug.len() <= 64
177 && slug
178 .chars()
179 .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-'),
180 "Admin::resource: the slug `{slug}` may only have letters, digits, `_` and `-`"
181 );
182 assert!(
183 self.resources.iter().all(|r| r.slug() != slug),
184 "Admin::resource: two resources have the slug `{slug}`"
185 );
186 self.resources.push(Arc::new(Holder(Arc::new(resource))));
187 self
188 }
189}
190
191impl Module for Admin {
192 fn name(&self) -> &'static str {
193 "admin"
194 }
195
196 fn routes(&self) -> Routes {
197 panel::routes(Arc::new(Panel {
198 path: self.path.clone(),
199 title: self.title.clone(),
200 access: self.access.clone(),
201 resources: self.resources.clone(),
202 }))
203 }
204
205 fn register(&self, app: &mut Registry) {
206 app.templates(|env| {
207 for (name, source) in VIEWS {
208 // The app's own file of that name wins.
209 if env.get_template(name).is_err() {
210 let _ = env.add_template(name, source);
211 }
212 }
213 });
214 }
215}
216
217/// Compiles the Rust in docs/admin.md (the guide) as doctests.
218#[cfg(doctest)]
219#[doc = include_str!("../../../docs/admin.md")]
220pub struct Guide;