#![warn(missing_docs)]
use std::fmt;
use std::sync::Arc;
use renox::prelude::*;
pub mod entry;
pub mod field;
mod panel;
pub mod resource;
pub use entry::Entry;
pub use field::{Field, FieldKind};
pub use resource::{ActionContext, AdminAction, AdminResource, BoxFuture, Filter};
use panel::{Access, Holder, Listed, Panel};
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/show.html", include_str!("../views/show.html")),
(
"renox-admin/fields.html",
include_str!("../views/fields.html"),
),
];
#[derive(Clone)]
pub struct Admin {
path: String,
title: String,
access: Option<Access>,
resources: Vec<Arc<dyn Listed>>,
}
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(),
}
}
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 resource<R: AdminResource>(mut self, resource: R) -> Self {
let slug = resource.slug().to_owned();
assert!(
!slug.is_empty()
&& slug.len() <= 64
&& slug
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-'),
"Admin::resource: the slug `{slug}` may only have letters, digits, `_` and `-`"
);
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
}
}
impl Module for Admin {
fn name(&self) -> &'static str {
"admin"
}
fn routes(&self) -> Routes {
panel::routes(Arc::new(Panel {
path: self.path.clone(),
title: self.title.clone(),
access: self.access.clone(),
resources: self.resources.clone(),
}))
}
fn register(&self, app: &mut Registry) {
app.templates(|env| {
for (name, source) in VIEWS {
if env.get_template(name).is_err() {
let _ = env.add_template(name, source);
}
}
});
}
}
#[cfg(doctest)]
#[doc = include_str!("../../../docs/admin.md")]
pub struct Guide;