Skip to main content

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 relation;
58pub mod resource;
59mod texts;
60
61pub use entry::Entry;
62pub use field::{Field, FieldKind};
63pub use relation::RelationManager;
64pub use resource::{
65    ActionContext, ActionInput, AdminAction, AdminResource, BoxFuture, Filter, SaveContext,
66};
67
68use panel::{Access, Holder, Listed, Panel};
69
70/// The templates, compiled in. An app replaces one with a file of the same
71/// name under its views directory (`resources/views/renox-admin/layout.html`).
72const VIEWS: &[(&str, &str)] = &[
73    (
74        "renox-admin/layout.html",
75        include_str!("../views/layout.html"),
76    ),
77    (
78        "renox-admin/dashboard.html",
79        include_str!("../views/dashboard.html"),
80    ),
81    (
82        "renox-admin/index.html",
83        include_str!("../views/index.html"),
84    ),
85    ("renox-admin/form.html", include_str!("../views/form.html")),
86    (
87        "renox-admin/relation.html",
88        include_str!("../views/relation.html"),
89    ),
90    ("renox-admin/show.html", include_str!("../views/show.html")),
91    (
92        "renox-admin/fields.html",
93        include_str!("../views/fields.html"),
94    ),
95];
96
97/// A place in the panel's layout where an app (or a module) adds content
98/// without replacing the layout: [`Admin::slot`], or a file of the slot's
99/// name under the app's views (`renox-admin/slots/after_content.html`).
100/// A slot's template sees the page's values (`admin`, `resource`, `record`,
101/// `title`, …) and the request's globals (`request.route`, `auth`, …).
102///
103/// ```
104/// use renox_admin::Slot;
105///
106/// assert_eq!(Slot::AfterContent.template(), "renox-admin/slots/after_content.html");
107/// ```
108#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
109#[non_exhaustive]
110pub enum Slot {
111    /// In the page's `<head>`, after the app's `head` stack.
112    Head,
113    /// At the top of the sidebar, before the Dashboard link.
114    SidebarStart,
115    /// At the bottom of the sidebar, after the resources.
116    SidebarEnd,
117    /// In the top bar, before the account menu.
118    NavbarEnd,
119    /// Above the page's content.
120    BeforeContent,
121    /// Below the page's content ("About this page").
122    AfterContent,
123}
124
125impl Slot {
126    /// The template the layout includes for the slot, if there is one.
127    pub fn template(self) -> &'static str {
128        match self {
129            Self::Head => "renox-admin/slots/head.html",
130            Self::SidebarStart => "renox-admin/slots/sidebar_start.html",
131            Self::SidebarEnd => "renox-admin/slots/sidebar_end.html",
132            Self::NavbarEnd => "renox-admin/slots/navbar_end.html",
133            Self::BeforeContent => "renox-admin/slots/before_content.html",
134            Self::AfterContent => "renox-admin/slots/after_content.html",
135        }
136    }
137}
138
139/// The admin panel module: its address, its title, who may use it and its
140/// resources.
141#[derive(Clone)]
142pub struct Admin {
143    path: String,
144    title: String,
145    access: Option<Access>,
146    resources: Vec<Arc<dyn Listed>>,
147    slots: Vec<(Slot, String)>,
148}
149
150impl Default for Admin {
151    fn default() -> Self {
152        Self::new()
153    }
154}
155
156impl fmt::Debug for Admin {
157    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
158        f.debug_struct("Admin")
159            .field("path", &self.path)
160            .field("title", &self.title)
161            .field(
162                "resources",
163                &self.resources.iter().map(|r| r.slug()).collect::<Vec<_>>(),
164            )
165            .finish_non_exhaustive()
166    }
167}
168
169impl Admin {
170    /// A panel at `/admin`, titled "Admin", with no resources yet, that
171    /// nobody may open until [`authorize`](Self::authorize) says who may.
172    pub fn new() -> Self {
173        Self {
174            path: "/admin".into(),
175            title: "Admin".into(),
176            access: None,
177            resources: Vec::new(),
178            slots: Vec::new(),
179        }
180    }
181
182    /// Where the panel lives (`/admin` by default). The route names stay
183    /// `admin.*`.
184    ///
185    /// # Panics
186    ///
187    /// If `path` doesn't start with `/` or ends with one.
188    pub fn path(mut self, path: &str) -> Self {
189        assert!(
190            path.starts_with('/') && !path.ends_with('/'),
191            "Admin::path(\"{path}\"): it must start with `/` and not end with one"
192        );
193        self.path = path.to_owned();
194        self
195    }
196
197    /// The panel's name, at the top of its navigation and in page titles.
198    pub fn title(mut self, title: &str) -> Self {
199        self.title = title.to_owned();
200        self
201    }
202
203    /// Who may open the panel at all: logged-in users for whom `allows`
204    /// says yes (others get 403, guests go to log in). Without it, nobody
205    /// may.
206    pub fn authorize(mut self, allows: impl Fn(&AuthUser) -> bool + Send + Sync + 'static) -> Self {
207        self.access = Some(Arc::new(allows));
208        self
209    }
210
211    /// Lets in the users the gate `name` lets through (`App::gate`, or a
212    /// permission of that name with the `Permissions` module, after
213    /// `App::gate_before`).
214    pub fn gate(self, name: &str) -> Self {
215        let name = name.to_owned();
216        self.authorize(move |user| user.allows(&name))
217    }
218
219    /// Adds `template` (MiniJinja source) to a place in every page's
220    /// layout, without replacing the layout. Several for one slot are drawn
221    /// in the order added. A file of the slot's name under the app's views
222    /// ([`Slot::template`]) replaces them.
223    ///
224    /// ```
225    /// use renox_admin::{Admin, Slot};
226    ///
227    /// let admin = Admin::new().slot(
228    ///     Slot::AfterContent,
229    ///     r#"<aside class="about"><h2>About this page</h2><p>{{ request.route }}</p></aside>"#,
230    /// );
231    /// # let _ = admin;
232    /// ```
233    pub fn slot(mut self, slot: Slot, template: &str) -> Self {
234        self.slots.push((slot, template.to_owned()));
235        self
236    }
237
238    /// Adds a resource, after the ones before it in the navigation.
239    ///
240    /// # Panics
241    ///
242    /// If its slug isn't letters, digits, `_` and `-`, or another resource
243    /// has it.
244    pub fn resource<R: AdminResource>(mut self, resource: R) -> Self {
245        let slug = resource.slug().to_owned();
246        assert!(
247            !slug.is_empty()
248                && slug.len() <= 64
249                && slug
250                    .chars()
251                    .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-'),
252            "Admin::resource: the slug `{slug}` may only have letters, digits, `_` and `-`"
253        );
254        assert!(
255            self.resources.iter().all(|r| r.slug() != slug),
256            "Admin::resource: two resources have the slug `{slug}`"
257        );
258        self.resources.push(Arc::new(Holder(Arc::new(resource))));
259        self
260    }
261}
262
263impl Module for Admin {
264    fn name(&self) -> &'static str {
265        "admin"
266    }
267
268    fn routes(&self) -> Routes {
269        panel::routes(Arc::new(Panel {
270            path: self.path.clone(),
271            title: self.title.clone(),
272            access: self.access.clone(),
273            resources: self.resources.clone(),
274        }))
275    }
276
277    fn register(&self, app: &mut Registry) {
278        // One template per slot: what was added to it, in order.
279        let mut slots: Vec<(&'static str, String)> = Vec::new();
280        for (slot, source) in &self.slots {
281            match slots.iter_mut().find(|(name, _)| *name == slot.template()) {
282                Some((_, all)) => {
283                    all.push('\n');
284                    all.push_str(source);
285                }
286                None => slots.push((slot.template(), source.clone())),
287            }
288        }
289        app.templates(move |env| {
290            for (name, source) in VIEWS {
291                // The app's own file of that name wins.
292                if env.get_template(name).is_err() {
293                    renox::view::add_template(env, *name, *source)
294                        .expect("a built-in template compiles");
295                }
296            }
297            for (name, source) in &slots {
298                if env.get_template(name).is_err() {
299                    renox::view::add_template(env, *name, source.clone())
300                        .expect("a built-in template compiles");
301                }
302            }
303        });
304    }
305}
306
307/// Compiles the Rust in docs/admin.md (the guide) as doctests.
308#[cfg(doctest)]
309#[doc = include_str!("../../../docs/admin.md")]
310pub struct Guide;