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
54mod custom_fields;
55pub mod entry;
56pub mod field;
57mod panel;
58pub mod relation;
59pub mod resource;
60pub mod settings;
61mod texts;
62
63pub use entry::Entry;
64pub use field::{Field, FieldKind};
65pub use relation::RelationManager;
66pub use resource::{
67    ActionContext, ActionInput, AdminAction, AdminResource, BoxFuture, Filter, SaveContext,
68};
69pub use settings::AdminSettings;
70
71use panel::{Access, Holder, Listed, Panel};
72use settings::{Page, SettingsPage};
73
74/// The templates, compiled in. An app replaces one with a file of the same
75/// name under its views directory (`resources/views/renox-admin/layout.html`).
76const VIEWS: &[(&str, &str)] = &[
77    (
78        "renox-admin/layout.html",
79        include_str!("../views/layout.html"),
80    ),
81    (
82        "renox-admin/dashboard.html",
83        include_str!("../views/dashboard.html"),
84    ),
85    (
86        "renox-admin/index.html",
87        include_str!("../views/index.html"),
88    ),
89    ("renox-admin/form.html", include_str!("../views/form.html")),
90    (
91        "renox-admin/relation.html",
92        include_str!("../views/relation.html"),
93    ),
94    ("renox-admin/show.html", include_str!("../views/show.html")),
95    (
96        "renox-admin/fields.html",
97        include_str!("../views/fields.html"),
98    ),
99    (
100        "renox-admin/settings.html",
101        include_str!("../views/settings.html"),
102    ),
103];
104
105/// A place in the panel's layout where an app (or a module) adds content
106/// without replacing the layout: [`Admin::slot`], or a file of the slot's
107/// name under the app's views (`renox-admin/slots/after_content.html`).
108/// A slot's template sees the page's values (`admin`, `resource`, `record`,
109/// `title`, …) and the request's globals (`request.route`, `auth`, …).
110///
111/// ```
112/// use renox_admin::Slot;
113///
114/// assert_eq!(Slot::AfterContent.template(), "renox-admin/slots/after_content.html");
115/// ```
116#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
117#[non_exhaustive]
118pub enum Slot {
119    /// In the page's `<head>`, after the app's `head` stack.
120    Head,
121    /// At the top of the sidebar, before the Dashboard link.
122    SidebarStart,
123    /// At the bottom of the sidebar, after the resources.
124    SidebarEnd,
125    /// In the top bar, before the account menu.
126    NavbarEnd,
127    /// Above the page's content.
128    BeforeContent,
129    /// Below the page's content ("About this page").
130    AfterContent,
131}
132
133impl Slot {
134    /// The template the layout includes for the slot, if there is one.
135    pub fn template(self) -> &'static str {
136        match self {
137            Self::Head => "renox-admin/slots/head.html",
138            Self::SidebarStart => "renox-admin/slots/sidebar_start.html",
139            Self::SidebarEnd => "renox-admin/slots/sidebar_end.html",
140            Self::NavbarEnd => "renox-admin/slots/navbar_end.html",
141            Self::BeforeContent => "renox-admin/slots/before_content.html",
142            Self::AfterContent => "renox-admin/slots/after_content.html",
143        }
144    }
145}
146
147/// The admin panel module: its address, its title, who may use it and its
148/// resources.
149#[derive(Clone)]
150pub struct Admin {
151    path: String,
152    title: String,
153    access: Option<Access>,
154    resources: Vec<Arc<dyn Listed>>,
155    settings: Vec<Arc<dyn SettingsPage>>,
156    slots: Vec<(Slot, String)>,
157    name: Option<String>,
158    own_only: bool,
159}
160
161/// A resource a module adds to an admin panel from its `register`, see
162/// [`contribute`]. By default it joins the panel without a name; with
163/// [`panel`](Self::panel) it joins the [`Admin::named`] panel of that name.
164///
165/// ```
166/// # use renox::prelude::*;
167/// # use renox_admin::{AdminEntry, AdminResource};
168/// # fn demo<R: AdminResource>(resource: R, app: &mut Registry) {
169/// app.contribute(AdminEntry::new(resource).panel("staff"));
170/// # }
171/// ```
172#[derive(Clone)]
173pub struct AdminEntry {
174    resource: Arc<dyn Listed>,
175    panel: Option<String>,
176}
177
178impl AdminEntry {
179    /// An entry for `resource`, for the panel without a name.
180    ///
181    /// # Panics
182    ///
183    /// If the slug isn't letters, digits, `_` and `-`.
184    pub fn new<R: AdminResource>(resource: R) -> Self {
185        check_slug("AdminEntry::new", resource.slug());
186        Self {
187            resource: Arc::new(Holder(Arc::new(resource))),
188            panel: None,
189        }
190    }
191
192    /// Sends the resource to the panel named `name` ([`Admin::named`])
193    /// instead of the unnamed one. A name no `Admin` has fails at boot.
194    pub fn panel(mut self, name: &str) -> Self {
195        self.panel = Some(name.to_owned());
196        self
197    }
198}
199
200/// Adds `resource` to the app's admin panel from a module's `register`
201/// (shorthand for `app.contribute(AdminEntry::new(resource))`). The panel
202/// shows it after its own resources, with the same gate and navigation.
203///
204/// ```
205/// # use renox::prelude::*;
206/// # use renox_admin::AdminResource;
207/// # fn demo<R: AdminResource>(resource: R, app: &mut Registry) {
208/// renox_admin::contribute(app, resource);
209/// # }
210/// ```
211pub fn contribute<R: AdminResource>(app: &mut Registry, resource: R) {
212    app.contribute(AdminEntry::new(resource));
213}
214
215/// The name of a panel, so entries aimed at an unknown one fail at boot.
216struct PanelName(String);
217
218fn check_slug(what: &str, slug: &str) {
219    assert!(
220        !slug.is_empty()
221            && slug.len() <= 64
222            && slug
223                .chars()
224                .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-'),
225        "{what}: the slug `{slug}` may only have letters, digits, `_` and `-`"
226    );
227}
228
229impl Default for Admin {
230    fn default() -> Self {
231        Self::new()
232    }
233}
234
235impl fmt::Debug for Admin {
236    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
237        f.debug_struct("Admin")
238            .field("path", &self.path)
239            .field("title", &self.title)
240            .field(
241                "resources",
242                &self.resources.iter().map(|r| r.slug()).collect::<Vec<_>>(),
243            )
244            .finish_non_exhaustive()
245    }
246}
247
248impl Admin {
249    /// A panel at `/admin`, titled "Admin", with no resources yet, that
250    /// nobody may open until [`authorize`](Self::authorize) says who may.
251    pub fn new() -> Self {
252        Self {
253            path: "/admin".into(),
254            title: "Admin".into(),
255            access: None,
256            resources: Vec::new(),
257            settings: Vec::new(),
258            slots: Vec::new(),
259            name: None,
260            own_only: false,
261        }
262    }
263
264    /// Names the panel, so it takes the [`AdminEntry`]s aimed at that name
265    /// (`AdminEntry::panel`) instead of the unnamed ones. A named panel has
266    /// its own route names, `admin.<name>.*` (`admin.staff.dashboard`), and
267    /// module name `admin.<name>`, so several panels can run in one app.
268    pub fn named(mut self, name: &str) -> Self {
269        self.name = Some(name.to_owned());
270        self
271    }
272
273    /// Ignores what modules contribute: only the resources added here.
274    pub fn only_own_resources(mut self) -> Self {
275        self.own_only = true;
276        self
277    }
278
279    /// Where the panel lives (`/admin` by default). The route names stay
280    /// `admin.*` (`admin.<name>.*` for a [named](Self::named) panel).
281    ///
282    /// # Panics
283    ///
284    /// If `path` doesn't start with `/` or ends with one.
285    pub fn path(mut self, path: &str) -> Self {
286        assert!(
287            path.starts_with('/') && !path.ends_with('/'),
288            "Admin::path(\"{path}\"): it must start with `/` and not end with one"
289        );
290        self.path = path.to_owned();
291        self
292    }
293
294    /// The panel's name, at the top of its navigation and in page titles.
295    pub fn title(mut self, title: &str) -> Self {
296        self.title = title.to_owned();
297        self
298    }
299
300    /// Who may open the panel at all: logged-in users for whom `allows`
301    /// says yes (others get 403, guests go to log in). Without it, nobody
302    /// may.
303    pub fn authorize(mut self, allows: impl Fn(&AuthUser) -> bool + Send + Sync + 'static) -> Self {
304        self.access = Some(Arc::new(allows));
305        self
306    }
307
308    /// Lets in the users the gate `name` lets through (`App::gate`, or a
309    /// permission of that name with the `Permissions` module, after
310    /// `App::gate_before`).
311    pub fn gate(self, name: &str) -> Self {
312        let name = name.to_owned();
313        self.authorize(move |user| user.allows(&name))
314    }
315
316    /// Adds `template` (MiniJinja source) to a place in every page's
317    /// layout, without replacing the layout. Several for one slot are drawn
318    /// in the order added. A file of the slot's name under the app's views
319    /// ([`Slot::template`]) replaces them.
320    ///
321    /// ```
322    /// use renox_admin::{Admin, Slot};
323    ///
324    /// let admin = Admin::new().slot(
325    ///     Slot::AfterContent,
326    ///     r#"<aside class="about"><h2>About this page</h2><p>{{ request.route }}</p></aside>"#,
327    /// );
328    /// # let _ = admin;
329    /// ```
330    pub fn slot(mut self, slot: Slot, template: &str) -> Self {
331        self.slots.push((slot, template.to_owned()));
332        self
333    }
334
335    /// Adds a resource, after the ones before it in the navigation.
336    ///
337    /// # Panics
338    ///
339    /// If its slug isn't letters, digits, `_` and `-`, or another resource
340    /// has it.
341    pub fn resource<R: AdminResource>(mut self, resource: R) -> Self {
342        let slug = resource.slug().to_owned();
343        check_slug("Admin::resource", &slug);
344        assert!(
345            self.resources.iter().all(|r| r.slug() != slug),
346            "Admin::resource: two resources have the slug `{slug}`"
347        );
348        self.resources.push(Arc::new(Holder(Arc::new(resource))));
349        self
350    }
351
352    /// Adds a page that edits a group of settings kept in the database
353    /// (`renox::settings`), at `/admin/settings/<key>` under a "Settings"
354    /// heading of the navigation. The form comes from
355    /// [`AdminSettings::fields`]; saving runs the group's rules and
356    /// `AppState::save_settings`, so it is audited and emits
357    /// `SettingsChanged`. The app needs the `renox::settings::Settings`
358    /// module (the group is declared for you).
359    ///
360    /// A group marked `ENCRYPTED` never prints its values: its fields start
361    /// empty with a note saying whether they are set and when they changed,
362    /// and a field left empty keeps its stored value.
363    ///
364    /// # Panics
365    ///
366    /// If another page has the same group.
367    pub fn settings<S: AdminSettings>(mut self, label: &str) -> Self {
368        assert!(
369            self.settings.iter().all(|page| page.key() != S::KEY),
370            "Admin::settings: two pages edit the group `{}`",
371            S::KEY
372        );
373        self.settings.push(Arc::new(Page::<S>::new(label)));
374        self
375    }
376}
377
378impl Admin {
379    fn panel_routes(&self, mut resources: Vec<Arc<dyn Listed>>) -> Routes {
380        // Models with custom fields get the screen that manages them.
381        let models: Vec<(String, String)> = resources
382            .iter()
383            .filter_map(|r| r.custom_fields_model())
384            .collect();
385        if !models.is_empty() && resources.iter().all(|r| r.slug() != custom_fields::SLUG) {
386            resources.push(Arc::new(Holder(Arc::new(custom_fields::CustomFields {
387                models,
388            }))));
389        }
390        panel::routes(Arc::new(Panel {
391            path: self.path.clone(),
392            title: self.title.clone(),
393            name: self.name.clone(),
394            access: self.access.clone(),
395            resources,
396            settings: self.settings.clone(),
397        }))
398    }
399}
400
401impl Module for Admin {
402    fn name(&self) -> &'static str {
403        match &self.name {
404            None => "admin",
405            // Once per panel at boot; the name must outlive the module list.
406            Some(name) => Box::leak(format!("admin.{name}").into_boxed_str()),
407        }
408    }
409
410    fn routes(&self) -> Routes {
411        self.panel_routes(self.resources.clone())
412    }
413
414    fn routes_with(&self, contributions: &Contributions) -> Routes {
415        let mut resources = self.resources.clone();
416        let mut from: Vec<String> = vec!["the app's Admin".into(); resources.len()];
417        // An entry for a panel no Admin has is a mistake worth failing on.
418        let names: Vec<&str> = contributions
419            .all::<PanelName>()
420            .iter()
421            .map(|n| n.0.as_str())
422            .collect();
423        for (module, entry) in contributions.all_from::<AdminEntry>() {
424            if let Some(panel) = &entry.panel {
425                assert!(
426                    names.contains(&panel.as_str()),
427                    "{module} contributes an admin resource to the panel \"{panel}\", \
428                     but no Admin is named \"{panel}\" (Admin::named)"
429                );
430            }
431        }
432        if !self.own_only {
433            for (module, entry) in contributions.all_from::<AdminEntry>() {
434                if entry.panel != self.name {
435                    continue;
436                }
437                let slug = entry.resource.slug();
438                let who = if module == "app" {
439                    "the app".to_owned()
440                } else {
441                    module.to_owned()
442                };
443                if let Some(at) = resources.iter().position(|r| r.slug() == slug) {
444                    panic!("\"{slug}\" is contributed by {} and by {who}", from[at]);
445                }
446                resources.push(entry.resource.clone());
447                from.push(who);
448            }
449        }
450        self.panel_routes(resources)
451    }
452
453    fn register(&self, app: &mut Registry) {
454        if let Some(name) = &self.name {
455            app.contribute(PanelName(name.clone()));
456        }
457        for page in &self.settings {
458            page.declare(app);
459        }
460        // One template per slot: what was added to it, in order.
461        let mut slots: Vec<(&'static str, String)> = Vec::new();
462        for (slot, source) in &self.slots {
463            match slots.iter_mut().find(|(name, _)| *name == slot.template()) {
464                Some((_, all)) => {
465                    all.push('\n');
466                    all.push_str(source);
467                }
468                None => slots.push((slot.template(), source.clone())),
469            }
470        }
471        app.templates(move |env| {
472            for (name, source) in VIEWS {
473                // The app's own file of that name wins.
474                if env.get_template(name).is_err() {
475                    renox::view::add_template(env, *name, *source)
476                        .expect("a built-in template compiles");
477                }
478            }
479            for (name, source) in &slots {
480                if env.get_template(name).is_err() {
481                    renox::view::add_template(env, *name, source.clone())
482                        .expect("a built-in template compiles");
483                }
484            }
485        });
486    }
487}
488
489/// Compiles the Rust in docs/admin.md (the guide) as doctests.
490#[cfg(doctest)]
491#[doc = include_str!("../../../docs/admin.md")]
492pub struct Guide;
493
494/// Compiles the Rust in docs/settings.md (the guide) as doctests; it lives
495/// here because its admin page example needs this crate.
496#[cfg(doctest)]
497#[doc = include_str!("../../../docs/settings.md")]
498pub struct SettingsGuide;