♻️ (admin): Construye piezas del panel con new()

AdminSection, AdminPage, AdminTask y AdminAction pasan a campos
privados con constructores y pesos Weight.
This commit is contained in:
Manuel Cillero 2026-11-07 07:58:01 +01:00
parent 8e0c887ba6
commit 71ea609088
11 changed files with 616 additions and 445 deletions

View file

@ -44,14 +44,10 @@
//! } //! }
//! //!
//! fn declare_pages(bag: &mut AdminPageBag) { //! fn declare_pages(bag: &mut AdminPageBag) {
//! bag.add(AdminPage { //! bag.add(
//! path: "config/export".to_owned(), //! AdminPage::new("config/export", "config", Lc::n("Export"), &ToolsPermission::Export)
//! section: "config".to_owned(), //! .with_description(Lc::n("Export site data.")),
//! title: Lc::n("Export"), //! );
//! description: Lc::n("Export site data."),
//! weight: 0,
//! permission: &ToolsPermission::Export,
//! });
//! } //! }
//! //!
//! // PageTop ya ha comprobado el permiso de la página antes de llegar aquí. //! // PageTop ya ha comprobado el permiso de la página antes de llegar aquí.
@ -137,6 +133,6 @@ pub fn can_access_admin(cx: &Context) -> bool {
let registry = AdminRegistry::global(); let registry = AdminRegistry::global();
registry registry
.pages() .pages()
.values() .iter()
.any(|page| registry.sections().contains_key(&page.section) && page.is_accessible(cx)) .any(|page| registry.section(page.section()).is_some() && page.is_accessible(cx))
} }

View file

@ -5,8 +5,7 @@ use crate::prelude::*;
// Monta el inicio del panel (*dashboard*) y la página de cada sección con páginas declaradas, sólo // Monta el inicio del panel (*dashboard*) y la página de cada sección con páginas declaradas, sólo
// si hay alguna. Una sección cuya ruta reclama una página declarada no se monta: esa página la // si hay alguna. Una sección cuya ruta reclama una página declarada no se monta: esa página la
// monta su extensión y gana. Una ruta se monta una sola vez (montarla dos veces detendría el // monta su extensión y gana. Una ruta se monta una sola vez (montarla dos veces detendría el
// arranque): si dos secciones la comparten, sirve la primera por clave, la misma que encuentra // arranque): si dos secciones la comparten, sirve la primera por peso.
// `section_page()`.
pub(crate) fn configure_routes(router: Router) -> Router { pub(crate) fn configure_routes(router: Router) -> Router {
let registry = AdminRegistry::global(); let registry = AdminRegistry::global();
if registry.pages().is_empty() { if registry.pages().is_empty() {
@ -14,15 +13,15 @@ pub(crate) fn configure_routes(router: Router) -> Router {
} }
let mut router = router.route(&admin_path(""), web::get(dashboard)); let mut router = router.route(&admin_path(""), web::get(dashboard));
let mut mounted = std::collections::BTreeSet::new(); let mut mounted = std::collections::BTreeSet::new();
for section in registry.sections().values() { for section in registry.sections() {
if section.path.is_empty() if section.path().is_empty()
|| registry.pages().contains_key(&section.path) || registry.page(section.path()).is_some()
|| registry.pages_for_section(&section.key).is_empty() || registry.pages_for_section(section.key()).is_empty()
|| !mounted.insert(section.path.as_str()) || !mounted.insert(section.path())
{ {
continue; continue;
} }
router = router.route(&admin_path(&section.path), web::get(section_page)); router = router.route(&admin_path(section.path()), web::get(section_page));
} }
router router
} }
@ -33,8 +32,8 @@ pub(crate) fn configure_routes(router: Router) -> Router {
// puede acceder a ninguna, se le deniega el acceso como en cualquier otra ruta. // puede acceder a ninguna, se le deniega el acceso como en cualquier otra ruta.
async fn dashboard(request: HttpRequest) -> Response { async fn dashboard(request: HttpRequest) -> Response {
let page = Page::admin(request.clone()); let page = Page::admin(request.clone());
let sections = AdminRegistry::global().ordered_sections(); let sections = AdminRegistry::global().sections();
let Some(content) = sections_with_pages(page.context(), &sections) else { let Some(content) = sections_with_pages(page.context(), sections) else {
return deny_access(request); return deny_access(request);
}; };
page.with_title(Lc::l("admin_dashboard")) page.with_title(Lc::l("admin_dashboard"))
@ -50,19 +49,15 @@ async fn dashboard(request: HttpRequest) -> Response {
// ninguna, se le deniega el acceso como en cualquier otra ruta. // ninguna, se le deniega el acceso como en cualquier otra ruta.
async fn section_page(request: HttpRequest) -> Response { async fn section_page(request: HttpRequest) -> Response {
let path = strip_admin_path(request.path()).unwrap_or_default(); let path = strip_admin_path(request.path()).unwrap_or_default();
let Some(section) = AdminRegistry::global() let Some(section) = AdminRegistry::global().section_by_path(path) else {
.sections()
.values()
.find(|s| s.path == path)
else {
return ErrorPage::NotFound(Some(request)).into_response(); return ErrorPage::NotFound(Some(request)).into_response();
}; };
let page = Page::admin(request.clone()); let page = Page::admin(request.clone());
let Some(content) = sections_with_pages(page.context(), &[section]) else { let Some(content) = sections_with_pages(page.context(), std::slice::from_ref(section)) else {
return deny_access(request); return deny_access(request);
}; };
page.with_title(section.title.clone()) page.with_title(section.title().clone())
.with_child(content) .with_child(content)
.render() .render()
.await .await
@ -73,15 +68,14 @@ async fn section_page(request: HttpRequest) -> Response {
// Secciones con sus páginas (título y descripción) a las que puede acceder el usuario, o `None` si // Secciones con sus páginas (título y descripción) a las que puede acceder el usuario, o `None` si
// no queda ninguna. // no queda ninguna.
fn sections_with_pages(cx: &Context, candidates: &[&'static AdminSection]) -> Option<Container> { fn sections_with_pages(cx: &Context, candidates: &'static [AdminSection]) -> Option<Container> {
let registry = AdminRegistry::global(); let registry = AdminRegistry::global();
let visible: Vec<_> = candidates let visible: Vec<_> = candidates
.iter() .iter()
.copied()
.map(|section| { .map(|section| {
let pages: Vec<_> = registry let pages: Vec<_> = registry
.pages_for_section(&section.key) .pages_for_section(section.key())
.into_iter() .iter()
.filter(|p| p.is_accessible(cx)) .filter(|p| p.is_accessible(cx))
.collect(); .collect();
(section, pages) (section, pages)
@ -99,19 +93,19 @@ fn sections_with_pages(cx: &Context, candidates: &[&'static AdminSection]) -> Op
.with_child(Html::with(move |cx| { .with_child(Html::with(move |cx| {
html! { html! {
h2 class="admin-dashboard-section-title" { h2 class="admin-dashboard-section-title" {
a href=(cx.route(admin_path(&section.path))) { a href=(cx.route(admin_path(section.path()))) {
(section.title.using(cx)) (section.title().using(cx))
} }
} }
ul class="admin-dashboard-section-links" { ul class="admin-dashboard-section-links" {
@for page in &pages { @for page in &pages {
li class="admin-dashboard-link" { li class="admin-dashboard-link" {
a href=(cx.route(admin_path(&page.path))) { a href=(cx.route(admin_path(page.path()))) {
(page.title.using(cx)) (page.title().using(cx))
} }
@if !page.description.is_none() { @if !page.description().is_none() {
span class="admin-dashboard-link-desc" { span class="admin-dashboard-link-desc" {
" - " (page.description.using(cx)) " - " (page.description().using(cx))
} }
} }
} }

View file

@ -1,56 +1,156 @@
use crate::Getters;
use crate::auth::{PermissionRef, PermissionRegistry, has_permission}; use crate::auth::{PermissionRef, PermissionRegistry, has_permission};
use crate::base::action::admin::{ use crate::base::action::admin::{
DeclareAdminActions, DeclareAdminPages, DeclareAdminSections, DeclareAdminTasks, DeclareAdminActions, DeclareAdminPages, DeclareAdminSections, DeclareAdminTasks,
}; };
use crate::core::component::{Context, Contextual}; use crate::core::component::{Context, Contextual};
use crate::locale::Lc; use crate::locale::Lc;
use crate::{trace, util}; use crate::{Getters, Weight, builder_impl, trace, util};
use super::bag::{AdminActionBag, AdminPageBag, AdminSectionBag, AdminTaskBag}; use super::bag::{AdminActionBag, AdminPageBag, AdminSectionBag, AdminTaskBag};
use std::collections::BTreeMap; use std::collections::BTreeMap;
use std::ops::Range;
use std::sync::OnceLock; use std::sync::OnceLock;
// **< Tipos del registro >************************************************************************* // **< AdminSection >*******************************************************************************
/// Sección del panel de administración (agrupa páginas en la navegación y en el *dashboard*). /// Sección del panel de administración (agrupa páginas en la navegación y en el *dashboard*).
/// ///
/// Una sección no tiene permiso propio: se muestra a quien pueda acceder a alguna de sus páginas, y /// Una sección no tiene permiso propio: se muestra a quien pueda acceder a alguna de sus páginas, y
/// se oculta si no le queda ninguna. /// se oculta si no le queda ninguna. Una sección declarada con la misma clave que otra anterior la
#[derive(Clone)] /// sustituye.
///
/// ```rust
/// # use pagetop::prelude::*;
/// let section = AdminSection::new("tools", Lc::n("Tools")).with_weight(35);
/// assert_eq!(section.path(), "tools");
/// ```
#[derive(Clone, Getters)]
pub struct AdminSection { pub struct AdminSection {
/// Identificador único de la sección (p. ej. `"config"`). /// Devuelve el identificador único de la sección (p. ej. `"config"`).
pub key: String, key: String,
/// Ruta de la sección, relativa a la raíz del panel (p. ej. `"config"`). /// Devuelve la ruta de la sección, relativa a la raíz del panel (p. ej. `"config"`).
pub path: String, path: String,
/// Título visible en la navegación. /// Devuelve el título visible en la navegación.
pub title: Lc, title: Lc,
/// Peso para ordenar las secciones (menor = antes). /// Devuelve el peso para ordenar las secciones (menor = antes).
pub weight: i32, #[getters(copy)]
weight: Weight,
} }
#[builder_impl]
impl AdminSection {
/// Crea una sección con su clave y su título. Su ruta es la propia clave y su peso, 0.
pub fn new(key: impl Into<String>, title: Lc) -> Self {
let key = key.into();
AdminSection {
path: relative(key.clone()),
key,
title,
weight: 0,
}
}
// **< AdminSection BUILDER >*******************************************************************
/// Establece la ruta de la sección, relativa a la raíz del panel, si no es la propia clave.
pub fn with_path(mut self, path: impl Into<String>) -> Self {
self.path = relative(path.into());
self
}
/// Establece el título de la sección.
pub fn with_title(mut self, title: Lc) -> Self {
self.title = title;
self
}
/// Establece el peso de la sección.
pub fn with_weight(mut self, weight: Weight) -> Self {
self.weight = weight;
self
}
}
// **< AdminPage >**********************************************************************************
/// Página del panel de administración. /// Página del panel de administración.
#[derive(Clone)] ///
/// ```rust,no_run
/// # use pagetop::prelude::*;
/// # struct ToolsPermission;
/// # impl Permission for ToolsPermission {
/// # fn key(&self) -> CowStr { "tools:export".into() }
/// # }
/// let page = AdminPage::new("config/export", "config", Lc::n("Export"), &ToolsPermission)
/// .with_description(Lc::n("Export site data."));
/// ```
#[derive(Clone, Getters)]
pub struct AdminPage { pub struct AdminPage {
/// Ruta de la página, relativa a la raíz del panel (p. ej. `"config/site"`). /// Devuelve la ruta de la página, relativa a la raíz del panel (p. ej. `"config/site"`).
pub path: String, path: String,
/// Clave de la sección a la que pertenece. /// Devuelve la clave de la sección a la que pertenece.
pub section: String, section: String,
/// Título visible en la navegación y en el encabezado de la página. /// Devuelve el título visible en la navegación y en el encabezado de la página.
pub title: Lc, title: Lc,
/// Descripción breve para el *dashboard* y las páginas de sección, o [`Lc::none()`] si no /// Devuelve la descripción breve para el *dashboard* y las páginas de sección, o
/// tiene. /// [`Lc::none()`] si no tiene.
pub description: Lc, description: Lc,
/// Peso dentro de la sección (menor = antes). /// Devuelve el peso dentro de la sección (menor = antes).
pub weight: i32, #[getters(copy)]
/// Permiso requerido para acceder a la página: decide si se muestra en la navegación, y si se weight: Weight,
/// muestra su sección, y lo exigen su ruta y las que cuelgan de ella /// Devuelve el permiso requerido para acceder a la página: decide si se muestra en la
/// navegación, y si se muestra su sección, y lo exigen su ruta y las que cuelgan de ella
/// ([`Routes::admin_route()`](crate::web::Routes::admin_route)). /// ([`Routes::admin_route()`](crate::web::Routes::admin_route)).
pub permission: PermissionRef, #[getters(copy)]
permission: PermissionRef,
} }
#[builder_impl]
impl AdminPage { impl AdminPage {
/// Crea una página con su ruta relativa a la raíz del panel, la clave de su sección, su título
/// y el permiso para acceder a ella. No tiene descripción y su peso es 0.
///
/// La ruta no puede quedar vacía, porque la raíz del panel es el *dashboard*: una página sin
/// ruta no se registra y se avisa al arrancar.
pub fn new(
path: impl Into<String>,
section: impl Into<String>,
title: Lc,
permission: PermissionRef,
) -> Self {
AdminPage {
path: relative(path.into()),
section: section.into(),
title,
description: Lc::none(),
weight: 0,
permission,
}
}
// **< AdminPage BUILDER >**********************************************************************
/// Establece el título de la página.
pub fn with_title(mut self, title: Lc) -> Self {
self.title = title;
self
}
/// Establece la descripción breve de la página.
pub fn with_description(mut self, description: Lc) -> Self {
self.description = description;
self
}
/// Establece el peso de la página dentro de su sección.
pub fn with_weight(mut self, weight: Weight) -> Self {
self.weight = weight;
self
}
// **< AdminPage GETTERS >**********************************************************************
/// Devuelve `true` si el usuario actual puede acceder a esta página. /// Devuelve `true` si el usuario actual puede acceder a esta página.
/// ///
/// Sirve para decidir qué se muestra; las rutas de la página ya exigen su permiso (ver el /// Sirve para decidir qué se muestra; las rutas de la página ya exigen su permiso (ver el
@ -61,40 +161,130 @@ impl AdminPage {
} }
} }
// **< AdminTask >**********************************************************************************
/// Tarea (pestaña) local dentro de una página de administración. /// Tarea (pestaña) local dentro de una página de administración.
#[derive(Clone)] ///
/// Las pestañas de una página se muestran en ella y en la ruta de cada una, con la de la ruta
/// actual activa. La pestaña cuya ruta es la de la propia página es la activa al entrar en ella.
///
/// ```rust,no_run
/// # use pagetop::prelude::*;
/// let all = AdminTask::new("config/export", "config/export", Lc::n("All"));
/// let csv = AdminTask::new("config/export/csv", "config/export", Lc::n("CSV")).with_weight(1);
/// ```
#[derive(Clone, Getters)]
pub struct AdminTask { pub struct AdminTask {
/// Ruta de la tarea, relativa a la raíz del panel. /// Devuelve la ruta de la tarea, relativa a la raíz del panel.
pub path: String, path: String,
/// Ruta de la página padre, relativa a la raíz del panel. /// Devuelve la ruta de la página padre, relativa a la raíz del panel.
pub parent_path: String, parent_path: String,
/// Etiqueta de la pestaña. /// Devuelve la etiqueta de la pestaña.
pub title: Lc, title: Lc,
/// Peso (menor = primera pestaña). /// Devuelve el peso de la pestaña (menor = antes).
pub weight: i32, #[getters(copy)]
/// Si es la tarea por defecto (pestaña activa al entrar a la página padre). weight: Weight,
pub is_default: bool, /// Devuelve el permiso requerido para mostrar la pestaña (`None` = se muestra a quien vea la
/// Permiso requerido para mostrar la pestaña (`None` = se muestra a quien vea la página padre). /// página padre). Su ruta sólo exige el permiso de la página de la que cuelga; si la pestaña
/// Su ruta sólo exige el permiso de la página de la que cuelga; si la pestaña pide otro, lo /// pide otro, lo comprueba su *handler*.
/// comprueba su *handler*. #[getters(copy)]
pub permission: Option<PermissionRef>, permission: Option<PermissionRef>,
} }
#[builder_impl]
impl AdminTask {
/// Crea una pestaña con su ruta y la de su página padre, ambas relativas a la raíz del panel,
/// y su etiqueta. Su peso es 0 y se muestra a quien vea la página padre.
pub fn new(path: impl Into<String>, parent_path: impl Into<String>, title: Lc) -> Self {
AdminTask {
path: relative(path.into()),
parent_path: relative(parent_path.into()),
title,
weight: 0,
permission: None,
}
}
// **< AdminTask BUILDER >**********************************************************************
/// Establece la etiqueta de la pestaña.
pub fn with_title(mut self, title: Lc) -> Self {
self.title = title;
self
}
/// Establece el peso de la pestaña.
pub fn with_weight(mut self, weight: Weight) -> Self {
self.weight = weight;
self
}
/// Establece el permiso requerido para mostrar la pestaña.
pub fn with_permission(mut self, permission: PermissionRef) -> Self {
self.permission = Some(permission);
self
}
}
// **< AdminAction >********************************************************************************
/// Acción local (botón de acción) en una página de administración. /// Acción local (botón de acción) en una página de administración.
#[derive(Clone)] ///
/// ```rust,no_run
/// # use pagetop::prelude::*;
/// let add = AdminAction::new("config/export/new", "config/export", Lc::n("Add export"));
/// ```
#[derive(Clone, Getters)]
pub struct AdminAction { pub struct AdminAction {
/// Ruta de destino de la acción, relativa a la raíz del panel. /// Devuelve la ruta de destino de la acción, relativa a la raíz del panel.
pub url: String, url: String,
/// Página en la que aparece el botón, relativa a la raíz del panel. /// Devuelve la ruta de la página en la que aparece el botón, relativa a la raíz del panel.
pub for_path: String, for_path: String,
/// Etiqueta del botón. /// Devuelve la etiqueta del botón.
pub title: Lc, title: Lc,
/// Peso (menor = primero). /// Devuelve el peso del botón (menor = antes).
pub weight: i32, #[getters(copy)]
/// Permiso requerido para mostrar el botón (`None` = se muestra a quien vea la página). weight: Weight,
/// Su ruta de destino sólo exige el permiso de la página de la que cuelga; si el botón pide /// Devuelve el permiso requerido para mostrar el botón (`None` = se muestra a quien vea la
/// otro, lo comprueba su *handler*. /// página). Su ruta de destino sólo exige el permiso de la página de la que cuelga; si el botón
pub permission: Option<PermissionRef>, /// pide otro, lo comprueba su *handler*.
#[getters(copy)]
permission: Option<PermissionRef>,
}
#[builder_impl]
impl AdminAction {
/// Crea un botón con su ruta de destino y la de la página en la que aparece, ambas relativas a
/// la raíz del panel, y su etiqueta. Su peso es 0 y se muestra a quien vea la página.
pub fn new(url: impl Into<String>, for_path: impl Into<String>, title: Lc) -> Self {
AdminAction {
url: relative(url.into()),
for_path: relative(for_path.into()),
title,
weight: 0,
permission: None,
}
}
// **< AdminAction BUILDER >********************************************************************
/// Establece la etiqueta del botón.
pub fn with_title(mut self, title: Lc) -> Self {
self.title = title;
self
}
/// Establece el peso del botón.
pub fn with_weight(mut self, weight: Weight) -> Self {
self.weight = weight;
self
}
/// Establece el permiso requerido para mostrar el botón.
pub fn with_permission(mut self, permission: PermissionRef) -> Self {
self.permission = Some(permission);
self
}
} }
// **< AdminRegistry >****************************************************************************** // **< AdminRegistry >******************************************************************************
@ -103,24 +293,29 @@ pub struct AdminAction {
/// ///
/// Reúne lo que declaran las extensiones con las acciones de /// Reúne lo que declaran las extensiones con las acciones de
/// [`action::admin`](crate::base::action::admin), con todas las rutas relativas a la raíz del /// [`action::admin`](crate::base::action::admin), con todas las rutas relativas a la raíz del
/// panel. /// panel. Las listas se ordenan por peso al construirlo.
#[derive(Getters)]
pub struct AdminRegistry { pub struct AdminRegistry {
/// Devuelve las secciones indexadas por clave (`BTreeMap` para orden estable por clave). // Por peso.
sections: BTreeMap<String, AdminSection>, sections: Vec<AdminSection>,
/// Devuelve las páginas indexadas por ruta. // Agrupadas por clave de sección y, en cada una, por peso.
pages: BTreeMap<String, AdminPage>, pages: Vec<AdminPage>,
/// Devuelve las tareas indexadas por ruta de página padre. // Posición en `pages` de cada página, por su ruta.
page_index: BTreeMap<String, usize>,
// Páginas de cada sección en `pages`, por clave de sección.
section_pages: BTreeMap<String, Range<usize>>,
// Por ruta de la página padre y, en cada una, por peso.
tasks: BTreeMap<String, Vec<AdminTask>>, tasks: BTreeMap<String, Vec<AdminTask>>,
/// Devuelve las acciones indexadas por ruta de página. // Por ruta de la página y, en cada una, por peso.
actions: BTreeMap<String, Vec<AdminAction>>, actions: BTreeMap<String, Vec<AdminAction>>,
} }
static REGISTRY: OnceLock<AdminRegistry> = OnceLock::new(); static REGISTRY: OnceLock<AdminRegistry> = OnceLock::new();
static EMPTY_REGISTRY: AdminRegistry = AdminRegistry { static EMPTY_REGISTRY: AdminRegistry = AdminRegistry {
sections: BTreeMap::new(), sections: Vec::new(),
pages: BTreeMap::new(), pages: Vec::new(),
page_index: BTreeMap::new(),
section_pages: BTreeMap::new(),
tasks: BTreeMap::new(), tasks: BTreeMap::new(),
actions: BTreeMap::new(), actions: BTreeMap::new(),
}; };
@ -134,55 +329,141 @@ impl AdminRegistry {
REGISTRY.get().unwrap_or(&EMPTY_REGISTRY) REGISTRY.get().unwrap_or(&EMPTY_REGISTRY)
} }
/// Devuelve las secciones ordenadas por peso.
pub fn sections(&self) -> &[AdminSection] {
&self.sections
}
/// Devuelve la sección con la clave indicada.
pub fn section(&self, key: &str) -> Option<&AdminSection> {
self.sections.iter().find(|s| s.key == key)
}
// Sección con la ruta indicada; si varias la comparten, la primera por peso.
pub(crate) fn section_by_path(&self, path: &str) -> Option<&AdminSection> {
self.sections.iter().find(|s| s.path == path)
}
/// Devuelve todas las páginas, agrupadas por la clave de su sección y, en cada grupo, ordenadas
/// por peso.
pub fn pages(&self) -> &[AdminPage] {
&self.pages
}
/// Devuelve la página declarada con la ruta indicada, relativa a la raíz del panel.
pub fn page(&self, path: &str) -> Option<&AdminPage> {
self.page_index.get(path).map(|&i| &self.pages[i])
}
/// Devuelve las páginas de una sección ordenadas por peso.
pub fn pages_for_section(&self, section_key: &str) -> &[AdminPage] {
self.section_pages
.get(section_key)
.map_or(&[], |range| &self.pages[range.clone()])
}
/// Devuelve las tareas de una página ordenadas por peso.
pub fn tasks_for(&self, path: &str) -> &[AdminTask] {
self.tasks.get(path).map_or(&[], Vec::as_slice)
}
/// Devuelve las acciones de una página ordenadas por peso.
pub fn actions_for(&self, path: &str) -> &[AdminAction] {
self.actions.get(path).map_or(&[], Vec::as_slice)
}
// Página declarada que corresponde a la ruta, o la más cercana que la contiene (`"user/users"` // Página declarada que corresponde a la ruta, o la más cercana que la contiene (`"user/users"`
// para `"user/users/5/edit"`). // para `"user/users/5/edit"`).
pub(crate) fn nearest_page(&self, path: &str) -> Option<&AdminPage> { pub(crate) fn nearest_page(&self, path: &str) -> Option<&AdminPage> {
let mut candidate = path; let mut candidate = path;
loop { loop {
if let Some(page) = self.pages.get(candidate) { if let Some(page) = self.page(candidate) {
return Some(page); return Some(page);
} }
candidate = candidate.rsplit_once('/')?.0; candidate = candidate.rsplit_once('/')?.0;
} }
} }
/// Devuelve las páginas de una sección ordenadas por peso. // Pestaña declarada con la ruta indicada.
pub fn pages_for_section(&self, section_key: &str) -> Vec<&AdminPage> { pub(crate) fn task(&self, path: &str) -> Option<&AdminTask> {
let mut pages: Vec<&AdminPage> = self self.tasks.values().flatten().find(|t| t.path == path)
.pages
.values()
.filter(|p| p.section == section_key)
.collect();
pages.sort_by_key(|p| p.weight);
pages
} }
/// Devuelve las secciones ordenadas por peso. // Construye el registro con lo declarado, en orden de declaración, y devuelve también los
pub fn ordered_sections(&self) -> Vec<&AdminSection> { // avisos de las páginas que no se registran tal cual. Una sección con la clave de otra anterior
let mut sections: Vec<&AdminSection> = self.sections.values().collect(); // la sustituye, y una página con la ruta de otra anterior, también. Una página sin ruta se
// descarta: la raíz del panel es el *dashboard*, y montar ahí su ruta impediría arrancar.
fn new(
sections: Vec<AdminSection>,
pages: Vec<AdminPage>,
tasks: Vec<AdminTask>,
actions: Vec<AdminAction>,
) -> (Self, Vec<String>) {
let mut warnings = Vec::new();
let mut by_key = BTreeMap::new();
for s in sections {
by_key.insert(s.key.clone(), s);
}
let mut sections: Vec<_> = by_key.into_values().collect();
sections.sort_by_key(|s| s.weight); sections.sort_by_key(|s| s.weight);
sections
let mut by_path = BTreeMap::new();
for p in pages {
if p.path.is_empty() {
warnings.push(format!(
"An admin page of the section \"{}\" has an empty path, ignored: the root of \
the panel is the dashboard",
p.section
));
continue;
}
if let Some(previous) = by_path.insert(p.path.clone(), p) {
warnings.push(format!(
"Admin page \"{}\" is declared more than once; the last declaration wins",
previous.path
));
}
}
let mut pages: Vec<_> = by_path.into_values().collect();
pages.sort_by(|a, b| a.section.cmp(&b.section).then(a.weight.cmp(&b.weight)));
let mut page_index = BTreeMap::new();
let mut section_pages: BTreeMap<String, Range<usize>> = BTreeMap::new();
for (i, p) in pages.iter().enumerate() {
page_index.insert(p.path.clone(), i);
section_pages
.entry(p.section.clone())
.and_modify(|range| range.end = i + 1)
.or_insert(i..i + 1);
} }
/// Devuelve las tareas de una página ordenadas por peso. let registry = AdminRegistry {
pub fn tasks_for(&self, path: &str) -> Vec<&AdminTask> { sections,
let Some(tasks) = self.tasks.get(path) else { pages,
return vec![]; page_index,
section_pages,
tasks: grouped(tasks, |t| &t.parent_path, |t| t.weight),
actions: grouped(actions, |a| &a.for_path, |a| a.weight),
}; };
let mut t: Vec<&AdminTask> = tasks.iter().collect(); (registry, warnings)
t.sort_by_key(|t| t.weight);
t
} }
}
/// Devuelve las acciones de una página ordenadas por peso. // Agrupa por la clave y ordena cada grupo por peso, conservando el orden de declaración entre los
pub fn actions_for(&self, path: &str) -> Vec<&AdminAction> { // del mismo peso.
let Some(actions) = self.actions.get(path) else { fn grouped<T>(
return vec![]; items: Vec<T>,
}; key: impl Fn(&T) -> &String,
let mut a: Vec<&AdminAction> = actions.iter().collect(); weight: impl Fn(&T) -> Weight,
a.sort_by_key(|a| a.weight); ) -> BTreeMap<String, Vec<T>> {
a let mut groups: BTreeMap<String, Vec<T>> = BTreeMap::new();
for item in items {
groups.entry(key(&item).clone()).or_default().push(item);
} }
for group in groups.values_mut() {
group.sort_by_key(&weight);
}
groups
} }
// **< Construcción del registro >****************************************************************** // **< Construcción del registro >******************************************************************
@ -194,63 +475,25 @@ impl AdminRegistry {
// nada. // nada.
pub(crate) fn build_admin_registry() { pub(crate) fn build_admin_registry() {
REGISTRY.get_or_init(|| { REGISTRY.get_or_init(|| {
let mut registry = AdminRegistry {
sections: BTreeMap::new(),
pages: BTreeMap::new(),
tasks: BTreeMap::new(),
actions: BTreeMap::new(),
};
let mut section_bag = AdminSectionBag { let mut section_bag = AdminSectionBag {
sections: default_sections(), sections: default_sections(),
}; };
DeclareAdminSections::dispatch(&mut section_bag); DeclareAdminSections::dispatch(&mut section_bag);
for mut s in section_bag.sections {
s.path = relative(s.path);
registry.sections.insert(s.key.clone(), s);
}
let mut warnings = Vec::new();
let mut page_bag = AdminPageBag { pages: Vec::new() }; let mut page_bag = AdminPageBag { pages: Vec::new() };
DeclareAdminPages::dispatch(&mut page_bag); DeclareAdminPages::dispatch(&mut page_bag);
for mut p in page_bag.pages {
p.path = relative(p.path);
if registry.pages.contains_key(&p.path) {
warnings.push(format!(
"Admin page \"{}\" is declared more than once; the last declaration wins",
p.path
));
}
registry.pages.insert(p.path.clone(), p);
}
let mut task_bag = AdminTaskBag { tasks: Vec::new() }; let mut task_bag = AdminTaskBag { tasks: Vec::new() };
DeclareAdminTasks::dispatch(&mut task_bag); DeclareAdminTasks::dispatch(&mut task_bag);
for mut t in task_bag.tasks {
t.path = relative(t.path);
t.parent_path = relative(t.parent_path);
registry
.tasks
.entry(t.parent_path.clone())
.or_default()
.push(t);
}
let mut action_bag = AdminActionBag { let mut action_bag = AdminActionBag {
actions: Vec::new(), actions: Vec::new(),
}; };
DeclareAdminActions::dispatch(&mut action_bag); DeclareAdminActions::dispatch(&mut action_bag);
for mut a in action_bag.actions {
a.url = relative(a.url);
a.for_path = relative(a.for_path);
registry
.actions
.entry(a.for_path.clone())
.or_default()
.push(a);
}
let (registry, mut warnings) = AdminRegistry::new(
section_bag.sections,
page_bag.pages,
task_bag.tasks,
action_bag.actions,
);
warnings.extend(check_references(&registry)); warnings.extend(check_references(&registry));
warnings.extend(check_permissions(&registry, PermissionRegistry::global())); warnings.extend(check_permissions(&registry, PermissionRegistry::global()));
for warning in warnings { for warning in warnings {
@ -262,11 +505,11 @@ pub(crate) fn build_admin_registry() {
// Avisos de las referencias por texto que no llevan a nada: la pieza no se mostraría y nada lo // Avisos de las referencias por texto que no llevan a nada: la pieza no se mostraría y nada lo
// indicaría. Una sección declarada dos veces no se avisa, porque sustituir una es lo previsto; sí // indicaría. Una sección declarada dos veces no se avisa, porque sustituir una es lo previsto; sí
// dos secciones con la misma ruta, porque sólo la primera por clave tendría página. // dos secciones con la misma ruta, porque sólo la primera por peso tendría página.
fn check_references(registry: &AdminRegistry) -> Vec<String> { fn check_references(registry: &AdminRegistry) -> Vec<String> {
let mut warnings = Vec::new(); let mut warnings = Vec::new();
let mut section_paths: BTreeMap<&str, &str> = BTreeMap::new(); let mut section_paths: BTreeMap<&str, &str> = BTreeMap::new();
for section in registry.sections.values() { for section in &registry.sections {
let first = *section_paths.entry(&section.path).or_insert(&section.key); let first = *section_paths.entry(&section.path).or_insert(&section.key);
if first != section.key { if first != section.key {
warnings.push(format!( warnings.push(format!(
@ -276,8 +519,8 @@ fn check_references(registry: &AdminRegistry) -> Vec<String> {
)); ));
} }
} }
for page in registry.pages.values() { for page in &registry.pages {
if !registry.sections.contains_key(&page.section) { if registry.section(&page.section).is_none() {
warnings.push(format!( warnings.push(format!(
"Admin page \"{}\" belongs to the unknown section \"{}\", not shown", "Admin page \"{}\" belongs to the unknown section \"{}\", not shown",
page.path, page.section page.path, page.section
@ -285,7 +528,7 @@ fn check_references(registry: &AdminRegistry) -> Vec<String> {
} }
} }
for (parent, tasks) in &registry.tasks { for (parent, tasks) in &registry.tasks {
if !registry.pages.contains_key(parent) { if registry.page(parent).is_none() {
for task in tasks { for task in tasks {
warnings.push(format!( warnings.push(format!(
"Admin task \"{}\" belongs to the undeclared page \"{parent}\", not shown", "Admin task \"{}\" belongs to the undeclared page \"{parent}\", not shown",
@ -294,9 +537,8 @@ fn check_references(registry: &AdminRegistry) -> Vec<String> {
} }
} }
} }
let is_task = |path: &str| registry.tasks.values().flatten().any(|t| t.path == path);
for (for_path, actions) in &registry.actions { for (for_path, actions) in &registry.actions {
if !registry.pages.contains_key(for_path) && !is_task(for_path) { if registry.page(for_path).is_none() && registry.task(for_path).is_none() {
for action in actions { for action in actions {
warnings.push(format!( warnings.push(format!(
"Admin action \"{}\" is for the undeclared page \"{for_path}\", not shown", "Admin action \"{}\" is for the undeclared page \"{for_path}\", not shown",
@ -321,7 +563,9 @@ fn check_permissions(registry: &AdminRegistry, catalog: &PermissionRegistry) ->
.push(piece); .push(piece);
} }
}; };
for page in registry.pages.values() { let mut pages: Vec<_> = registry.pages.iter().collect();
pages.sort_by_key(|p| &p.path);
for page in pages {
check(page.permission, util::join!("page \"", &page.path, "\"")); check(page.permission, util::join!("page \"", &page.path, "\""));
} }
for task in registry.tasks.values().flatten() { for task in registry.tasks.values().flatten() {
@ -369,12 +613,7 @@ fn default_sections() -> Vec<AdminSection> {
("help", "admin_section_help", 50), ("help", "admin_section_help", 50),
] ]
.into_iter() .into_iter()
.map(|(key, title, weight)| AdminSection { .map(|(key, title, weight)| AdminSection::new(key, Lc::l(title)).with_weight(weight))
key: key.to_owned(),
path: key.to_owned(),
title: Lc::l(title),
weight,
})
.collect() .collect()
} }
@ -392,83 +631,6 @@ mod tests {
} }
} }
fn page(path: &str, section: &str) -> AdminPage {
AdminPage {
path: path.to_owned(),
section: section.to_owned(),
title: Lc::n("Page"),
description: Lc::none(),
weight: 0,
permission: &AnyPermission,
}
}
fn task(path: &str, parent_path: &str) -> AdminTask {
AdminTask {
path: path.to_owned(),
parent_path: parent_path.to_owned(),
title: Lc::n("Task"),
weight: 0,
is_default: false,
permission: None,
}
}
fn action(url: &str, for_path: &str) -> AdminAction {
AdminAction {
url: url.to_owned(),
for_path: for_path.to_owned(),
title: Lc::n("Action"),
weight: 0,
permission: None,
}
}
#[test]
fn references_to_undeclared_pieces_are_reported() {
let mut registry = AdminRegistry {
sections: default_sections()
.into_iter()
.map(|s| (s.key.clone(), s))
.collect(),
pages: BTreeMap::new(),
tasks: BTreeMap::new(),
actions: BTreeMap::new(),
};
let mut settings = registry.sections["config"].clone();
settings.key = "settings".to_owned();
registry.sections.insert(settings.key.clone(), settings);
for p in [page("config/site", "config"), page("tools/x", "tools")] {
registry.pages.insert(p.path.clone(), p);
}
registry.tasks.insert(
"config/site".to_owned(),
vec![task("config/site/advanced", "config/site")],
);
registry.tasks.insert(
"config/sit".to_owned(),
vec![task("config/sit/typo", "config/sit")],
);
for a in [
action("config/site/new", "config/site"),
action("config/site/advanced/new", "config/site/advanced"),
action("config/other/new", "config/other"),
] {
registry
.actions
.entry(a.for_path.clone())
.or_default()
.push(a);
}
let warnings = check_references(&registry);
assert_eq!(warnings.len(), 4, "{warnings:?}");
assert!(warnings[0].contains("\"config\" and \"settings\" share the path \"config\""));
assert!(warnings[1].contains("\"tools/x\" belongs to the unknown section \"tools\""));
assert!(warnings[2].contains("\"config/sit/typo\" belongs to the undeclared page"));
assert!(warnings[3].contains("\"config/other/new\" is for the undeclared page"));
}
struct OtherPermission; struct OtherPermission;
impl Permission for OtherPermission { impl Permission for OtherPermission {
@ -477,25 +639,106 @@ mod tests {
} }
} }
fn page(path: &str, section: &str) -> AdminPage {
AdminPage::new(path, section, Lc::n("Page"), &AnyPermission)
}
fn task(path: &str, parent_path: &str) -> AdminTask {
AdminTask::new(path, parent_path, Lc::n("Task"))
}
fn action(url: &str, for_path: &str) -> AdminAction {
AdminAction::new(url, for_path, Lc::n("Action"))
}
#[test]
fn duplicated_pages_and_pages_without_path_are_reported() {
let (registry, warnings) = AdminRegistry::new(
default_sections(),
vec![
page("config/site", "config"),
page("config/site", "config").with_weight(5),
page("/", "config"),
],
vec![],
vec![],
);
assert_eq!(warnings.len(), 2, "{warnings:?}");
assert!(warnings[0].contains("\"config/site\" is declared more than once"));
assert!(warnings[1].contains("\"config\" has an empty path, ignored"));
assert_eq!(registry.page("config/site").unwrap().weight(), 5);
assert!(registry.page("").is_none());
}
#[test]
fn lists_are_sorted_by_weight_once() {
let (registry, _) = AdminRegistry::new(
default_sections(),
vec![
page("config/b", "config").with_weight(2),
page("people/a", "people"),
page("config/a", "config").with_weight(1),
page("config/c", "config").with_weight(1),
],
vec![
task("config/a/y", "config/a").with_weight(1),
task("config/a/x", "config/a"),
],
vec![],
);
let paths = |pages: &[AdminPage]| pages.iter().map(|p| p.path.clone()).collect::<Vec<_>>();
assert_eq!(
paths(registry.pages_for_section("config")),
["config/a", "config/c", "config/b"]
);
assert_eq!(paths(registry.pages_for_section("people")), ["people/a"]);
assert!(registry.pages_for_section("help").is_empty());
assert_eq!(registry.page("config/b").unwrap().weight(), 2);
let tasks: Vec<_> = registry
.tasks_for("config/a")
.iter()
.map(|t| t.path())
.collect();
assert_eq!(tasks, ["config/a/x", "config/a/y"]);
}
#[test]
fn references_to_undeclared_pieces_are_reported() {
let mut sections = default_sections();
sections.push(AdminSection::new("settings", Lc::n("Settings")).with_path("config"));
let (registry, _) = AdminRegistry::new(
sections,
vec![page("config/site", "config"), page("tools/x", "tools")],
vec![
task("config/site/advanced", "config/site"),
task("config/sit/typo", "config/sit"),
],
vec![
action("config/site/new", "config/site"),
action("config/site/advanced/new", "config/site/advanced"),
action("config/other/new", "config/other"),
],
);
let warnings = check_references(&registry);
assert_eq!(warnings.len(), 4, "{warnings:?}");
assert!(warnings[0].contains("\"settings\" and \"config\" share the path \"config\""));
assert!(warnings[1].contains("\"tools/x\" belongs to the unknown section \"tools\""));
assert!(warnings[2].contains("\"config/sit/typo\" belongs to the undeclared page"));
assert!(warnings[3].contains("\"config/other/new\" is for the undeclared page"));
}
#[test] #[test]
fn permissions_missing_from_the_catalog_are_reported_once_each() { fn permissions_missing_from_the_catalog_are_reported_once_each() {
let mut registry = AdminRegistry { let (registry, _) = AdminRegistry::new(
sections: BTreeMap::new(), vec![],
pages: BTreeMap::new(), vec![
tasks: BTreeMap::new(),
actions: BTreeMap::new(),
};
for p in [
page("config/site", "config"), page("config/site", "config"),
page("config/other", "config"), page("config/other", "config"),
] { ],
registry.pages.insert(p.path.clone(), p); vec![task("config/site/advanced", "config/site").with_permission(&OtherPermission)],
} vec![],
let mut advanced = task("config/site/advanced", "config/site"); );
advanced.permission = Some(&OtherPermission);
registry
.tasks
.insert("config/site".to_owned(), vec![advanced]);
let mut catalog = PermissionRegistry::default(); let mut catalog = PermissionRegistry::default();
catalog.register(&AnyPermission); catalog.register(&AnyPermission);

View file

@ -4,20 +4,14 @@ use super::FnActionDeclareAdminActions;
/// Acción para declarar acciones locales (botones de acción) en páginas del panel. /// Acción para declarar acciones locales (botones de acción) en páginas del panel.
/// ///
/// Cada [`AdminAction`] indica en `for_path` la página en la que aparece el botón. /// Cada [`AdminAction`] indica la página en la que aparece el botón.
/// ///
/// # Ejemplo /// # Ejemplo
/// ///
/// ```rust,no_run /// ```rust,no_run
/// # use pagetop::prelude::*; /// # use pagetop::prelude::*;
/// fn declare_actions(bag: &mut AdminActionBag) { /// fn declare_actions(bag: &mut AdminActionBag) {
/// bag.add(AdminAction { /// bag.add(AdminAction::new("config/export/new", "config/export", Lc::n("Add export")));
/// url: "config/export/new".to_owned(),
/// for_path: "config/export".to_owned(),
/// title: Lc::n("Add export"),
/// weight: 0,
/// permission: None,
/// });
/// } /// }
/// // En Extension::actions(): /// // En Extension::actions():
/// // action::admin::DeclareAdminActions::new(declare_actions) /// // action::admin::DeclareAdminActions::new(declare_actions)

View file

@ -12,12 +12,7 @@ use super::FnActionDeclareAdminSections;
/// ```rust,no_run /// ```rust,no_run
/// # use pagetop::prelude::*; /// # use pagetop::prelude::*;
/// fn declare_sections(bag: &mut AdminSectionBag) { /// fn declare_sections(bag: &mut AdminSectionBag) {
/// bag.add(AdminSection { /// bag.add(AdminSection::new("tools", Lc::n("Tools")).with_weight(60));
/// key: "tools".to_owned(),
/// path: "tools".to_owned(),
/// title: Lc::n("Tools"),
/// weight: 60,
/// });
/// } /// }
/// // En Extension::actions(): /// // En Extension::actions():
/// // action::admin::DeclareAdminSections::new(declare_sections) /// // action::admin::DeclareAdminSections::new(declare_sections)

View file

@ -4,21 +4,16 @@ use super::FnActionDeclareAdminTasks;
/// Acción para declarar tareas (pestañas) locales en páginas del panel. /// Acción para declarar tareas (pestañas) locales en páginas del panel.
/// ///
/// Cada [`AdminTask`] indica en `parent_path` la página a la que pertenece. /// Cada [`AdminTask`] indica la página a la que pertenece; la pestaña con la ruta de la propia
/// página es la activa al entrar en ella.
/// ///
/// # Ejemplo /// # Ejemplo
/// ///
/// ```rust,no_run /// ```rust,no_run
/// # use pagetop::prelude::*; /// # use pagetop::prelude::*;
/// fn declare_tasks(bag: &mut AdminTaskBag) { /// fn declare_tasks(bag: &mut AdminTaskBag) {
/// bag.add(AdminTask { /// bag.add(AdminTask::new("config/export", "config/export", Lc::n("All")));
/// path: "config/export/csv".to_owned(), /// bag.add(AdminTask::new("config/export/csv", "config/export", Lc::n("CSV")).with_weight(1));
/// parent_path: "config/export".to_owned(),
/// title: Lc::n("CSV"),
/// weight: 0,
/// is_default: true,
/// permission: None,
/// });
/// } /// }
/// // En Extension::actions(): /// // En Extension::actions():
/// // action::admin::DeclareAdminTasks::new(declare_tasks) /// // action::admin::DeclareAdminTasks::new(declare_tasks)

View file

@ -49,9 +49,9 @@ impl Component for AdminFrame {
// Sin título propio, la página declarada aporta el suyo, también al `<head>` (que se // Sin título propio, la página declarada aporta el suyo, también al `<head>` (que se
// renderiza después del `<body>`). // renderiza después del `<body>`).
if cx.title().is_none() if cx.title().is_none()
&& let Some(page) = AdminRegistry::global().pages().get(&path) && let Some(page) = AdminRegistry::global().page(&path)
{ {
cx.alter_title(page.title.clone()); cx.alter_title(page.title().clone());
} }
let breadcrumbs = breadcrumbs(cx, &path).render(cx).await; let breadcrumbs = breadcrumbs(cx, &path).render(cx).await;
@ -89,26 +89,26 @@ fn breadcrumbs(cx: &Context, path: &str) -> Breadcrumb {
admin_path(""), admin_path(""),
)); ));
if let Some(page) = registry.nearest_page(path) { if let Some(page) = registry.nearest_page(path) {
if let Some(section) = registry.sections().get(&page.section) { if let Some(section) = registry.section(page.section()) {
bc = bc.with_crumb(breadcrumb::Crumb::new( bc = bc.with_crumb(breadcrumb::Crumb::new(
section.title.clone(), section.title().clone(),
admin_path(&section.path), admin_path(section.path()),
)); ));
} }
if page.path == path { if page.path() == path {
bc = bc.with_crumb(breadcrumb::Crumb::current(page.title.clone())); bc = bc.with_crumb(breadcrumb::Crumb::current(page.title().clone()));
} else { } else {
bc = bc.with_crumb(breadcrumb::Crumb::new( bc = bc.with_crumb(breadcrumb::Crumb::new(
page.title.clone(), page.title().clone(),
admin_path(&page.path), admin_path(page.path()),
)); ));
if !cx.title().is_none() { if !cx.title().is_none() {
bc = bc.with_crumb(breadcrumb::Crumb::current(cx.title().clone())); bc = bc.with_crumb(breadcrumb::Crumb::current(cx.title().clone()));
} }
} }
} else if let Some(section) = registry.sections().values().find(|s| s.path == path) { } else if let Some(section) = registry.section_by_path(path) {
// La ruta es la propia sección (su página de aterrizaje), no una página declarada en ella. // La ruta es la propia sección (su página de aterrizaje), no una página declarada en ella.
bc = bc.with_crumb(breadcrumb::Crumb::current(section.title.clone())); bc = bc.with_crumb(breadcrumb::Crumb::current(section.title().clone()));
} }
bc bc
} }
@ -117,16 +117,11 @@ fn breadcrumbs(cx: &Context, path: &str) -> Breadcrumb {
// permiso que el usuario no tiene no se muestran. // permiso que el usuario no tiene no se muestran.
fn local_tasks(cx: &Context, path: &str) -> Markup { fn local_tasks(cx: &Context, path: &str) -> Markup {
let registry = AdminRegistry::global(); let registry = AdminRegistry::global();
let parent = registry let parent = registry.task(path).map_or(path, |task| task.parent_path());
.tasks()
.values()
.flatten()
.find(|task| task.path == path)
.map_or(path, |task| task.parent_path.as_str());
let tasks: Vec<_> = registry let tasks: Vec<_> = registry
.tasks_for(parent) .tasks_for(parent)
.into_iter() .iter()
.filter(|task| is_granted(cx, task.permission)) .filter(|task| is_granted(cx, task.permission()))
.collect(); .collect();
if tasks.is_empty() { if tasks.is_empty() {
return html! {}; return html! {};
@ -134,8 +129,8 @@ fn local_tasks(cx: &Context, path: &str) -> Markup {
html! { html! {
ul class="admin-tasks-list" { ul class="admin-tasks-list" {
@for task in tasks { @for task in tasks {
li class="admin-task" .admin-task-active[task.path == path] { li class="admin-task" .admin-task-active[task.path() == path] {
a href=(cx.route(admin_path(&task.path))) { (task.title.using(cx)) } a href=(cx.route(admin_path(task.path()))) { (task.title().using(cx)) }
} }
} }
} }
@ -147,8 +142,8 @@ fn local_tasks(cx: &Context, path: &str) -> Markup {
fn local_actions(cx: &Context, path: &str) -> Markup { fn local_actions(cx: &Context, path: &str) -> Markup {
let actions: Vec<_> = AdminRegistry::global() let actions: Vec<_> = AdminRegistry::global()
.actions_for(path) .actions_for(path)
.into_iter() .iter()
.filter(|action| is_granted(cx, action.permission)) .filter(|action| is_granted(cx, action.permission()))
.collect(); .collect();
if actions.is_empty() { if actions.is_empty() {
return html! {}; return html! {};
@ -157,8 +152,8 @@ fn local_actions(cx: &Context, path: &str) -> Markup {
ul class="admin-actions-list" { ul class="admin-actions-list" {
@for action in actions { @for action in actions {
li class="admin-action" { li class="admin-action" {
a class="admin-action-link" href=(cx.route(admin_path(&action.url))) { a class="admin-action-link" href=(cx.route(admin_path(action.url()))) {
(action.title.using(cx)) (action.title().using(cx))
} }
} }
} }

View file

@ -32,20 +32,20 @@ impl Component for AdminMenu {
let mut nav = let mut nav =
Nav::new().with_item(nav::Item::link(Lc::l("admin_dashboard"), admin_path(""))); Nav::new().with_item(nav::Item::link(Lc::l("admin_dashboard"), admin_path("")));
for section in registry.ordered_sections() { for section in registry.sections() {
let pages: Vec<_> = registry let pages: Vec<_> = registry
.pages_for_section(&section.key) .pages_for_section(section.key())
.into_iter() .iter()
.filter(|p| p.is_accessible(cx)) .filter(|p| p.is_accessible(cx))
.collect(); .collect();
if pages.is_empty() { if pages.is_empty() {
continue; continue;
} }
let mut menu = Dropdown::new().with_title(section.title.clone()); let mut menu = Dropdown::new().with_title(section.title().clone());
for page in pages { for page in pages {
menu = menu.with_item(dropdown::Item::link( menu = menu.with_item(dropdown::Item::link(
page.title.clone(), page.title().clone(),
admin_path(&page.path), admin_path(page.path()),
)); ));
} }
nav = nav.with_item(nav::Item::dropdown(menu)); nav = nav.with_item(nav::Item::dropdown(menu));

View file

@ -11,14 +11,12 @@ impl Permission for ToolsPermission {
} }
fn declare_pages(bag: &mut AdminPageBag) { fn declare_pages(bag: &mut AdminPageBag) {
bag.add(AdminPage { bag.add(AdminPage::new(
path: "config/export".to_owned(), "config/export",
section: "config".to_owned(), "config",
title: Lc::n("Export"), Lc::n("Export"),
description: Lc::none(), &ToolsPermission,
weight: 0, ));
permission: &ToolsPermission,
});
} }
struct Ext; struct Ext;

View file

@ -12,55 +12,33 @@ impl Permission for ToolsPermission {
} }
fn declare_sections(bag: &mut AdminSectionBag) { fn declare_sections(bag: &mut AdminSectionBag) {
bag.add(AdminSection { bag.add(AdminSection::new("tools", Lc::n("Tools")).with_weight(35));
key: "tools".to_owned(),
path: "tools".to_owned(),
title: Lc::n("Tools"),
weight: 35,
});
// Replaces the built-in section with the same key. // Replaces the built-in section with the same key.
bag.add(AdminSection { bag.add(
key: "help".to_owned(), AdminSection::new("help", Lc::n("Support"))
path: "support".to_owned(), .with_path("support")
title: Lc::n("Support"), .with_weight(5),
weight: 5, );
});
} }
fn declare_pages(bag: &mut AdminPageBag) { fn declare_pages(bag: &mut AdminPageBag) {
for (path, weight) in [("tools/export", 10), ("/tools/import/", 0)] { for (path, weight) in [("tools/export", 10), ("/tools/import/", 0)] {
bag.add(AdminPage { bag.add(AdminPage::new(path, "tools", Lc::n(path), &ToolsPermission).with_weight(weight));
path: path.to_owned(),
section: "tools".to_owned(),
title: Lc::n(path),
description: Lc::none(),
weight,
permission: &ToolsPermission,
});
} }
} }
fn declare_tasks(bag: &mut AdminTaskBag) { fn declare_tasks(bag: &mut AdminTaskBag) {
for (path, weight) in [("tools/export/json", 1), ("tools/export/csv", 0)] { for (path, weight) in [("tools/export/json", 1), ("tools/export/csv", 0)] {
bag.add(AdminTask { bag.add(AdminTask::new(path, "/tools/export", Lc::n(path)).with_weight(weight));
path: path.to_owned(),
parent_path: "/tools/export".to_owned(),
title: Lc::n(path),
weight,
is_default: weight == 0,
permission: None,
});
} }
} }
fn declare_actions(bag: &mut AdminActionBag) { fn declare_actions(bag: &mut AdminActionBag) {
bag.add(AdminAction { bag.add(AdminAction::new(
url: "tools/export/new/".to_owned(), "tools/export/new/",
for_path: "tools/export".to_owned(), "tools/export",
title: Lc::n("New export"), Lc::n("New export"),
weight: 0, ));
permission: None,
});
} }
struct Ext; struct Ext;
@ -87,9 +65,9 @@ async fn start() {
async fn built_in_sections_come_first_and_can_be_replaced() { async fn built_in_sections_come_first_and_can_be_replaced() {
start().await; start().await;
let keys: Vec<_> = AdminRegistry::global() let keys: Vec<_> = AdminRegistry::global()
.ordered_sections() .sections()
.into_iter() .iter()
.map(|s| (s.key.as_str(), s.path.as_str())) .map(|s| (s.key(), s.path()))
.collect(); .collect();
assert_eq!( assert_eq!(
keys, keys,
@ -110,21 +88,21 @@ async fn paths_are_kept_relative_without_surrounding_slashes() {
let registry = AdminRegistry::global(); let registry = AdminRegistry::global();
let pages: Vec<_> = registry let pages: Vec<_> = registry
.pages_for_section("tools") .pages_for_section("tools")
.into_iter() .iter()
.map(|p| p.path.as_str()) .map(|p| p.path())
.collect(); .collect();
assert_eq!(pages, ["tools/import", "tools/export"]); assert_eq!(pages, ["tools/import", "tools/export"]);
let tasks: Vec<_> = registry let tasks: Vec<_> = registry
.tasks_for("tools/export") .tasks_for("tools/export")
.into_iter() .iter()
.map(|t| t.path.as_str()) .map(|t| t.path())
.collect(); .collect();
assert_eq!(tasks, ["tools/export/csv", "tools/export/json"]); assert_eq!(tasks, ["tools/export/csv", "tools/export/json"]);
let actions = registry.actions_for("tools/export"); let actions = registry.actions_for("tools/export");
assert_eq!(actions.len(), 1); assert_eq!(actions.len(), 1);
assert_eq!(actions[0].url, "tools/export/new"); assert_eq!(actions[0].url(), "tools/export/new");
} }
#[pagetop::test] #[pagetop::test]

View file

@ -28,66 +28,49 @@ fn grant_tools(_: &HttpRequest, perm: PermissionRef, granted: &mut bool) {
} }
fn declare_pages(bag: &mut AdminPageBag) { fn declare_pages(bag: &mut AdminPageBag) {
bag.add(AdminPage { bag.add(AdminPage::new(
path: "config/export".to_owned(), "config/export",
section: "config".to_owned(), "config",
title: Lc::n("Export"), Lc::n("Export"),
description: Lc::none(), &ToolsPermission,
weight: 0, ));
permission: &ToolsPermission, bag.add(AdminPage::new(
}); "reports/audit",
bag.add(AdminPage { "reports",
path: "reports/audit".to_owned(), Lc::n("Audit"),
section: "reports".to_owned(), &AuditPermission,
title: Lc::n("Audit"), ));
description: Lc::none(),
weight: 0,
permission: &AuditPermission,
});
} }
fn declare_tasks(bag: &mut AdminTaskBag) { fn declare_tasks(bag: &mut AdminTaskBag) {
bag.add(AdminTask { bag.add(AdminTask::new(
path: "config/export".to_owned(), "config/export",
parent_path: "config/export".to_owned(), "config/export",
title: Lc::n("All"), Lc::n("All"),
weight: 0, ));
is_default: true, bag.add(AdminTask::new("config/export/csv", "config/export", Lc::n("CSV")).with_weight(1));
permission: None, bag.add(
}); AdminTask::new("config/export/log", "config/export", Lc::n("Log"))
bag.add(AdminTask { .with_weight(2)
path: "config/export/csv".to_owned(), .with_permission(&AuditPermission),
parent_path: "config/export".to_owned(), );
title: Lc::n("CSV"),
weight: 1,
is_default: false,
permission: None,
});
bag.add(AdminTask {
path: "config/export/log".to_owned(),
parent_path: "config/export".to_owned(),
title: Lc::n("Log"),
weight: 2,
is_default: false,
permission: Some(&AuditPermission),
});
} }
fn declare_actions(bag: &mut AdminActionBag) { fn declare_actions(bag: &mut AdminActionBag) {
bag.add(AdminAction { bag.add(AdminAction::new(
url: "config/export/new".to_owned(), "config/export/new",
for_path: "config/export".to_owned(), "config/export",
title: Lc::n("New export"), Lc::n("New export"),
weight: 0, ));
permission: None, bag.add(
}); AdminAction::new(
bag.add(AdminAction { "config/export/purge",
url: "config/export/purge".to_owned(), "config/export",
for_path: "config/export".to_owned(), Lc::n("Purge exports"),
title: Lc::n("Purge exports"), )
weight: 1, .with_weight(1)
permission: Some(&AuditPermission), .with_permission(&AuditPermission),
}); );
} }
struct Ext; struct Ext;