#![warn(missing_docs)]
use std::fmt;
use std::sync::Arc;
use renox::prelude::*;
mod custom_fields;
pub mod entry;
pub mod field;
mod panel;
pub mod relation;
pub mod resource;
pub mod settings;
mod texts;
pub use entry::Entry;
pub use field::{Field, FieldKind};
pub use relation::RelationManager;
pub use resource::{
ActionContext, ActionInput, AdminAction, AdminResource, BoxFuture, Filter, SaveContext,
};
pub use settings::AdminSettings;
use panel::{Access, Holder, Listed, Panel};
use settings::{Page, SettingsPage};
const VIEWS: &[(&str, &str)] = &[
(
"renox-admin/layout.html",
include_str!("../views/layout.html"),
),
(
"renox-admin/dashboard.html",
include_str!("../views/dashboard.html"),
),
(
"renox-admin/index.html",
include_str!("../views/index.html"),
),
("renox-admin/form.html", include_str!("../views/form.html")),
(
"renox-admin/relation.html",
include_str!("../views/relation.html"),
),
("renox-admin/show.html", include_str!("../views/show.html")),
(
"renox-admin/fields.html",
include_str!("../views/fields.html"),
),
(
"renox-admin/settings.html",
include_str!("../views/settings.html"),
),
];
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Slot {
Head,
SidebarStart,
SidebarEnd,
NavbarEnd,
BeforeContent,
AfterContent,
}
impl Slot {
pub fn template(self) -> &'static str {
match self {
Self::Head => "renox-admin/slots/head.html",
Self::SidebarStart => "renox-admin/slots/sidebar_start.html",
Self::SidebarEnd => "renox-admin/slots/sidebar_end.html",
Self::NavbarEnd => "renox-admin/slots/navbar_end.html",
Self::BeforeContent => "renox-admin/slots/before_content.html",
Self::AfterContent => "renox-admin/slots/after_content.html",
}
}
}
#[derive(Clone)]
pub struct Admin {
path: String,
title: String,
access: Option<Access>,
resources: Vec<Arc<dyn Listed>>,
settings: Vec<Arc<dyn SettingsPage>>,
slots: Vec<(Slot, String)>,
name: Option<String>,
own_only: bool,
}
#[derive(Clone)]
pub struct AdminEntry {
resource: Arc<dyn Listed>,
panel: Option<String>,
}
impl AdminEntry {
pub fn new<R: AdminResource>(resource: R) -> Self {
check_slug("AdminEntry::new", resource.slug());
Self {
resource: Arc::new(Holder(Arc::new(resource))),
panel: None,
}
}
pub fn panel(mut self, name: &str) -> Self {
self.panel = Some(name.to_owned());
self
}
}
pub fn contribute<R: AdminResource>(app: &mut Registry, resource: R) {
app.contribute(AdminEntry::new(resource));
}
struct PanelName(String);
fn check_slug(what: &str, slug: &str) {
assert!(
!slug.is_empty()
&& slug.len() <= 64
&& slug
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-'),
"{what}: the slug `{slug}` may only have letters, digits, `_` and `-`"
);
}
impl Default for Admin {
fn default() -> Self {
Self::new()
}
}
impl fmt::Debug for Admin {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Admin")
.field("path", &self.path)
.field("title", &self.title)
.field(
"resources",
&self.resources.iter().map(|r| r.slug()).collect::<Vec<_>>(),
)
.finish_non_exhaustive()
}
}
impl Admin {
pub fn new() -> Self {
Self {
path: "/admin".into(),
title: "Admin".into(),
access: None,
resources: Vec::new(),
settings: Vec::new(),
slots: Vec::new(),
name: None,
own_only: false,
}
}
pub fn named(mut self, name: &str) -> Self {
self.name = Some(name.to_owned());
self
}
pub fn only_own_resources(mut self) -> Self {
self.own_only = true;
self
}
pub fn path(mut self, path: &str) -> Self {
assert!(
path.starts_with('/') && !path.ends_with('/'),
"Admin::path(\"{path}\"): it must start with `/` and not end with one"
);
self.path = path.to_owned();
self
}
pub fn title(mut self, title: &str) -> Self {
self.title = title.to_owned();
self
}
pub fn authorize(mut self, allows: impl Fn(&AuthUser) -> bool + Send + Sync + 'static) -> Self {
self.access = Some(Arc::new(allows));
self
}
pub fn gate(self, name: &str) -> Self {
let name = name.to_owned();
self.authorize(move |user| user.allows(&name))
}
pub fn slot(mut self, slot: Slot, template: &str) -> Self {
self.slots.push((slot, template.to_owned()));
self
}
pub fn resource<R: AdminResource>(mut self, resource: R) -> Self {
let slug = resource.slug().to_owned();
check_slug("Admin::resource", &slug);
assert!(
self.resources.iter().all(|r| r.slug() != slug),
"Admin::resource: two resources have the slug `{slug}`"
);
self.resources.push(Arc::new(Holder(Arc::new(resource))));
self
}
pub fn settings<S: AdminSettings>(mut self, label: &str) -> Self {
assert!(
self.settings.iter().all(|page| page.key() != S::KEY),
"Admin::settings: two pages edit the group `{}`",
S::KEY
);
self.settings.push(Arc::new(Page::<S>::new(label)));
self
}
}
impl Admin {
fn panel_routes(&self, mut resources: Vec<Arc<dyn Listed>>) -> Routes {
let models: Vec<(String, String)> = resources
.iter()
.filter_map(|r| r.custom_fields_model())
.collect();
if !models.is_empty() && resources.iter().all(|r| r.slug() != custom_fields::SLUG) {
resources.push(Arc::new(Holder(Arc::new(custom_fields::CustomFields {
models,
}))));
}
panel::routes(Arc::new(Panel {
path: self.path.clone(),
title: self.title.clone(),
name: self.name.clone(),
access: self.access.clone(),
resources,
settings: self.settings.clone(),
}))
}
}
impl Module for Admin {
fn name(&self) -> &'static str {
match &self.name {
None => "admin",
Some(name) => Box::leak(format!("admin.{name}").into_boxed_str()),
}
}
fn routes(&self) -> Routes {
self.panel_routes(self.resources.clone())
}
fn routes_with(&self, contributions: &Contributions) -> Routes {
let mut resources = self.resources.clone();
let mut from: Vec<String> = vec!["the app's Admin".into(); resources.len()];
let names: Vec<&str> = contributions
.all::<PanelName>()
.iter()
.map(|n| n.0.as_str())
.collect();
for (module, entry) in contributions.all_from::<AdminEntry>() {
if let Some(panel) = &entry.panel {
assert!(
names.contains(&panel.as_str()),
"{module} contributes an admin resource to the panel \"{panel}\", \
but no Admin is named \"{panel}\" (Admin::named)"
);
}
}
if !self.own_only {
for (module, entry) in contributions.all_from::<AdminEntry>() {
if entry.panel != self.name {
continue;
}
let slug = entry.resource.slug();
let who = if module == "app" {
"the app".to_owned()
} else {
module.to_owned()
};
if let Some(at) = resources.iter().position(|r| r.slug() == slug) {
panic!("\"{slug}\" is contributed by {} and by {who}", from[at]);
}
resources.push(entry.resource.clone());
from.push(who);
}
}
self.panel_routes(resources)
}
fn register(&self, app: &mut Registry) {
if let Some(name) = &self.name {
app.contribute(PanelName(name.clone()));
}
for page in &self.settings {
page.declare(app);
}
let mut slots: Vec<(&'static str, String)> = Vec::new();
for (slot, source) in &self.slots {
match slots.iter_mut().find(|(name, _)| *name == slot.template()) {
Some((_, all)) => {
all.push('\n');
all.push_str(source);
}
None => slots.push((slot.template(), source.clone())),
}
}
app.templates(move |env| {
for (name, source) in VIEWS {
if env.get_template(name).is_err() {
renox::view::add_template(env, *name, *source)
.expect("a built-in template compiles");
}
}
for (name, source) in &slots {
if env.get_template(name).is_err() {
renox::view::add_template(env, *name, source.clone())
.expect("a built-in template compiles");
}
}
});
}
}
#[cfg(doctest)]
#[doc = include_str!("../../../docs/admin.md")]
pub struct Guide;
#[cfg(doctest)]
#[doc = include_str!("../../../docs/settings.md")]
pub struct SettingsGuide;