From 71ea609088bb7a812681307a032e9b2faa029498 Mon Sep 17 00:00:00 2001 From: Manuel Cillero Date: Sat, 7 Nov 2026 07:58:01 +0100 Subject: [PATCH] =?UTF-8?q?=E2=99=BB=EF=B8=8F=20(admin):=20Construye=20pie?= =?UTF-8?q?zas=20del=20panel=20con=20new()?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit AdminSection, AdminPage, AdminTask y AdminAction pasan a campos privados con constructores y pesos Weight. --- src/admin.rs | 16 +- src/admin/pages.rs | 48 +- src/admin/registry.rs | 741 ++++++++++++------ .../action/admin/declare_admin_actions.rs | 10 +- .../action/admin/declare_admin_sections.rs | 7 +- src/base/action/admin/declare_admin_tasks.rs | 13 +- src/base/component/admin_frame.rs | 45 +- src/base/component/admin_menu.rs | 12 +- tests/admin_invalid_route.rs | 14 +- tests/admin_registry.rs | 64 +- tests/admin_template.rs | 91 +-- 11 files changed, 616 insertions(+), 445 deletions(-) diff --git a/src/admin.rs b/src/admin.rs index 578a44ac..625ff7d7 100644 --- a/src/admin.rs +++ b/src/admin.rs @@ -44,14 +44,10 @@ //! } //! //! fn declare_pages(bag: &mut AdminPageBag) { -//! bag.add(AdminPage { -//! path: "config/export".to_owned(), -//! section: "config".to_owned(), -//! title: Lc::n("Export"), -//! description: Lc::n("Export site data."), -//! weight: 0, -//! permission: &ToolsPermission::Export, -//! }); +//! bag.add( +//! AdminPage::new("config/export", "config", Lc::n("Export"), &ToolsPermission::Export) +//! .with_description(Lc::n("Export site data.")), +//! ); //! } //! //! // 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(); registry .pages() - .values() - .any(|page| registry.sections().contains_key(&page.section) && page.is_accessible(cx)) + .iter() + .any(|page| registry.section(page.section()).is_some() && page.is_accessible(cx)) } diff --git a/src/admin/pages.rs b/src/admin/pages.rs index 11ba8b78..2deee864 100644 --- a/src/admin/pages.rs +++ b/src/admin/pages.rs @@ -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 // 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 -// arranque): si dos secciones la comparten, sirve la primera por clave, la misma que encuentra -// `section_page()`. +// arranque): si dos secciones la comparten, sirve la primera por peso. pub(crate) fn configure_routes(router: Router) -> Router { let registry = AdminRegistry::global(); 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 mounted = std::collections::BTreeSet::new(); - for section in registry.sections().values() { - if section.path.is_empty() - || registry.pages().contains_key(§ion.path) - || registry.pages_for_section(§ion.key).is_empty() - || !mounted.insert(section.path.as_str()) + for section in registry.sections() { + if section.path().is_empty() + || registry.page(section.path()).is_some() + || registry.pages_for_section(section.key()).is_empty() + || !mounted.insert(section.path()) { continue; } - router = router.route(&admin_path(§ion.path), web::get(section_page)); + router = router.route(&admin_path(section.path()), web::get(section_page)); } 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. async fn dashboard(request: HttpRequest) -> Response { let page = Page::admin(request.clone()); - let sections = AdminRegistry::global().ordered_sections(); - let Some(content) = sections_with_pages(page.context(), §ions) else { + let sections = AdminRegistry::global().sections(); + let Some(content) = sections_with_pages(page.context(), sections) else { return deny_access(request); }; 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. async fn section_page(request: HttpRequest) -> Response { let path = strip_admin_path(request.path()).unwrap_or_default(); - let Some(section) = AdminRegistry::global() - .sections() - .values() - .find(|s| s.path == path) - else { + let Some(section) = AdminRegistry::global().section_by_path(path) else { return ErrorPage::NotFound(Some(request)).into_response(); }; 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); }; - page.with_title(section.title.clone()) + page.with_title(section.title().clone()) .with_child(content) .render() .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 // no queda ninguna. -fn sections_with_pages(cx: &Context, candidates: &[&'static AdminSection]) -> Option { +fn sections_with_pages(cx: &Context, candidates: &'static [AdminSection]) -> Option { let registry = AdminRegistry::global(); let visible: Vec<_> = candidates .iter() - .copied() .map(|section| { let pages: Vec<_> = registry - .pages_for_section(§ion.key) - .into_iter() + .pages_for_section(section.key()) + .iter() .filter(|p| p.is_accessible(cx)) .collect(); (section, pages) @@ -99,19 +93,19 @@ fn sections_with_pages(cx: &Context, candidates: &[&'static AdminSection]) -> Op .with_child(Html::with(move |cx| { html! { h2 class="admin-dashboard-section-title" { - a href=(cx.route(admin_path(§ion.path))) { - (section.title.using(cx)) + a href=(cx.route(admin_path(section.path()))) { + (section.title().using(cx)) } } ul class="admin-dashboard-section-links" { @for page in &pages { li class="admin-dashboard-link" { - a href=(cx.route(admin_path(&page.path))) { - (page.title.using(cx)) + a href=(cx.route(admin_path(page.path()))) { + (page.title().using(cx)) } - @if !page.description.is_none() { + @if !page.description().is_none() { span class="admin-dashboard-link-desc" { - " - " (page.description.using(cx)) + " - " (page.description().using(cx)) } } } diff --git a/src/admin/registry.rs b/src/admin/registry.rs index 5cb4a5ff..37f64093 100644 --- a/src/admin/registry.rs +++ b/src/admin/registry.rs @@ -1,56 +1,156 @@ -use crate::Getters; use crate::auth::{PermissionRef, PermissionRegistry, has_permission}; use crate::base::action::admin::{ DeclareAdminActions, DeclareAdminPages, DeclareAdminSections, DeclareAdminTasks, }; use crate::core::component::{Context, Contextual}; use crate::locale::Lc; -use crate::{trace, util}; +use crate::{Getters, Weight, builder_impl, trace, util}; use super::bag::{AdminActionBag, AdminPageBag, AdminSectionBag, AdminTaskBag}; use std::collections::BTreeMap; +use std::ops::Range; 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*). /// /// 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. -#[derive(Clone)] +/// se oculta si no le queda ninguna. Una sección declarada con la misma clave que otra anterior la +/// 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 { - /// Identificador único de la sección (p. ej. `"config"`). - pub key: String, - /// Ruta de la sección, relativa a la raíz del panel (p. ej. `"config"`). - pub path: String, - /// Título visible en la navegación. - pub title: Lc, - /// Peso para ordenar las secciones (menor = antes). - pub weight: i32, + /// Devuelve el identificador único de la sección (p. ej. `"config"`). + key: String, + /// Devuelve la ruta de la sección, relativa a la raíz del panel (p. ej. `"config"`). + path: String, + /// Devuelve el título visible en la navegación. + title: Lc, + /// Devuelve el peso para ordenar las secciones (menor = antes). + #[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, 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) -> 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. -#[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 { - /// Ruta de la página, relativa a la raíz del panel (p. ej. `"config/site"`). - pub path: String, - /// Clave de la sección a la que pertenece. - pub section: String, - /// Título visible en la navegación y en el encabezado de la página. - pub title: Lc, - /// Descripción breve para el *dashboard* y las páginas de sección, o [`Lc::none()`] si no - /// tiene. - pub description: Lc, - /// Peso dentro de la sección (menor = antes). - pub weight: i32, - /// 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 + /// Devuelve la ruta de la página, relativa a la raíz del panel (p. ej. `"config/site"`). + path: String, + /// Devuelve la clave de la sección a la que pertenece. + section: String, + /// Devuelve el título visible en la navegación y en el encabezado de la página. + title: Lc, + /// Devuelve la descripción breve para el *dashboard* y las páginas de sección, o + /// [`Lc::none()`] si no tiene. + description: Lc, + /// Devuelve el peso dentro de la sección (menor = antes). + #[getters(copy)] + weight: Weight, + /// 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)). - pub permission: PermissionRef, + #[getters(copy)] + permission: PermissionRef, } +#[builder_impl] 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, + section: impl Into, + 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. /// /// 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. -#[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 { - /// Ruta de la tarea, relativa a la raíz del panel. - pub path: String, - /// Ruta de la página padre, relativa a la raíz del panel. - pub parent_path: String, - /// Etiqueta de la pestaña. - pub title: Lc, - /// Peso (menor = primera pestaña). - pub weight: i32, - /// Si es la tarea por defecto (pestaña activa al entrar a la página padre). - pub is_default: bool, - /// Permiso requerido para mostrar la pestaña (`None` = se muestra a quien vea la página padre). - /// Su ruta sólo exige el permiso de la página de la que cuelga; si la pestaña pide otro, lo - /// comprueba su *handler*. - pub permission: Option, + /// Devuelve la ruta de la tarea, relativa a la raíz del panel. + path: String, + /// Devuelve la ruta de la página padre, relativa a la raíz del panel. + parent_path: String, + /// Devuelve la etiqueta de la pestaña. + title: Lc, + /// Devuelve el peso de la pestaña (menor = antes). + #[getters(copy)] + weight: Weight, + /// Devuelve el permiso requerido para mostrar la pestaña (`None` = se muestra a quien vea la + /// página padre). Su ruta sólo exige el permiso de la página de la que cuelga; si la pestaña + /// pide otro, lo comprueba su *handler*. + #[getters(copy)] + permission: Option, } +#[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, parent_path: impl Into, 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. -#[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 { - /// Ruta de destino de la acción, relativa a la raíz del panel. - pub url: String, - /// Página en la que aparece el botón, relativa a la raíz del panel. - pub for_path: String, - /// Etiqueta del botón. - pub title: Lc, - /// Peso (menor = primero). - pub weight: i32, - /// Permiso requerido para mostrar el botón (`None` = se muestra a quien vea la página). - /// Su ruta de destino sólo exige el permiso de la página de la que cuelga; si el botón pide - /// otro, lo comprueba su *handler*. - pub permission: Option, + /// Devuelve la ruta de destino de la acción, relativa a la raíz del panel. + url: String, + /// Devuelve la ruta de la página en la que aparece el botón, relativa a la raíz del panel. + for_path: String, + /// Devuelve la etiqueta del botón. + title: Lc, + /// Devuelve el peso del botón (menor = antes). + #[getters(copy)] + weight: Weight, + /// Devuelve el permiso requerido para mostrar el botón (`None` = se muestra a quien vea la + /// página). Su ruta de destino sólo exige el permiso de la página de la que cuelga; si el botón + /// pide otro, lo comprueba su *handler*. + #[getters(copy)] + permission: Option, +} + +#[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, for_path: impl Into, 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 >****************************************************************************** @@ -103,24 +293,29 @@ pub struct AdminAction { /// /// 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 -/// panel. -#[derive(Getters)] +/// panel. Las listas se ordenan por peso al construirlo. pub struct AdminRegistry { - /// Devuelve las secciones indexadas por clave (`BTreeMap` para orden estable por clave). - sections: BTreeMap, - /// Devuelve las páginas indexadas por ruta. - pages: BTreeMap, - /// Devuelve las tareas indexadas por ruta de página padre. + // Por peso. + sections: Vec, + // Agrupadas por clave de sección y, en cada una, por peso. + pages: Vec, + // Posición en `pages` de cada página, por su ruta. + page_index: BTreeMap, + // Páginas de cada sección en `pages`, por clave de sección. + section_pages: BTreeMap>, + // Por ruta de la página padre y, en cada una, por peso. tasks: BTreeMap>, - /// Devuelve las acciones indexadas por ruta de página. + // Por ruta de la página y, en cada una, por peso. actions: BTreeMap>, } static REGISTRY: OnceLock = OnceLock::new(); static EMPTY_REGISTRY: AdminRegistry = AdminRegistry { - sections: BTreeMap::new(), - pages: BTreeMap::new(), + sections: Vec::new(), + pages: Vec::new(), + page_index: BTreeMap::new(), + section_pages: BTreeMap::new(), tasks: BTreeMap::new(), actions: BTreeMap::new(), }; @@ -134,57 +329,143 @@ impl AdminRegistry { 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"` // para `"user/users/5/edit"`). pub(crate) fn nearest_page(&self, path: &str) -> Option<&AdminPage> { let mut candidate = path; loop { - if let Some(page) = self.pages.get(candidate) { + if let Some(page) = self.page(candidate) { return Some(page); } candidate = candidate.rsplit_once('/')?.0; } } - /// Devuelve las páginas de una sección ordenadas por peso. - pub fn pages_for_section(&self, section_key: &str) -> Vec<&AdminPage> { - let mut pages: Vec<&AdminPage> = self - .pages - .values() - .filter(|p| p.section == section_key) - .collect(); - pages.sort_by_key(|p| p.weight); - pages + // Pestaña declarada con la ruta indicada. + pub(crate) fn task(&self, path: &str) -> Option<&AdminTask> { + self.tasks.values().flatten().find(|t| t.path == path) } - /// Devuelve las secciones ordenadas por peso. - pub fn ordered_sections(&self) -> Vec<&AdminSection> { - let mut sections: Vec<&AdminSection> = self.sections.values().collect(); + // Construye el registro con lo declarado, en orden de declaración, y devuelve también los + // avisos de las páginas que no se registran tal cual. Una sección con la clave de otra anterior + // 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, + pages: Vec, + tasks: Vec, + actions: Vec, + ) -> (Self, Vec) { + 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 - } - /// Devuelve las tareas de una página ordenadas por peso. - pub fn tasks_for(&self, path: &str) -> Vec<&AdminTask> { - let Some(tasks) = self.tasks.get(path) else { - return vec![]; - }; - let mut t: Vec<&AdminTask> = tasks.iter().collect(); - t.sort_by_key(|t| t.weight); - t - } + 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> = 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 acciones de una página ordenadas por peso. - pub fn actions_for(&self, path: &str) -> Vec<&AdminAction> { - let Some(actions) = self.actions.get(path) else { - return vec![]; + let registry = AdminRegistry { + sections, + pages, + 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 a: Vec<&AdminAction> = actions.iter().collect(); - a.sort_by_key(|a| a.weight); - a + (registry, warnings) } } +// Agrupa por la clave y ordena cada grupo por peso, conservando el orden de declaración entre los +// del mismo peso. +fn grouped( + items: Vec, + key: impl Fn(&T) -> &String, + weight: impl Fn(&T) -> Weight, +) -> BTreeMap> { + let mut groups: BTreeMap> = 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 >****************************************************************** // Construye el registro despachando las acciones de declaración, después de las secciones @@ -194,63 +475,25 @@ impl AdminRegistry { // nada. pub(crate) fn build_admin_registry() { 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 { sections: default_sections(), }; 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() }; 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() }; 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 { actions: Vec::new(), }; 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(®istry)); warnings.extend(check_permissions(®istry, PermissionRegistry::global())); 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 // 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 { let mut warnings = Vec::new(); let mut section_paths: BTreeMap<&str, &str> = BTreeMap::new(); - for section in registry.sections.values() { + for section in ®istry.sections { let first = *section_paths.entry(§ion.path).or_insert(§ion.key); if first != section.key { warnings.push(format!( @@ -276,8 +519,8 @@ fn check_references(registry: &AdminRegistry) -> Vec { )); } } - for page in registry.pages.values() { - if !registry.sections.contains_key(&page.section) { + for page in ®istry.pages { + if registry.section(&page.section).is_none() { warnings.push(format!( "Admin page \"{}\" belongs to the unknown section \"{}\", not shown", page.path, page.section @@ -285,7 +528,7 @@ fn check_references(registry: &AdminRegistry) -> Vec { } } for (parent, tasks) in ®istry.tasks { - if !registry.pages.contains_key(parent) { + if registry.page(parent).is_none() { for task in tasks { warnings.push(format!( "Admin task \"{}\" belongs to the undeclared page \"{parent}\", not shown", @@ -294,9 +537,8 @@ fn check_references(registry: &AdminRegistry) -> Vec { } } } - let is_task = |path: &str| registry.tasks.values().flatten().any(|t| t.path == path); for (for_path, actions) in ®istry.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 { warnings.push(format!( "Admin action \"{}\" is for the undeclared page \"{for_path}\", not shown", @@ -321,7 +563,9 @@ fn check_permissions(registry: &AdminRegistry, catalog: &PermissionRegistry) -> .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, "\"")); } for task in registry.tasks.values().flatten() { @@ -369,12 +613,7 @@ fn default_sections() -> Vec { ("help", "admin_section_help", 50), ] .into_iter() - .map(|(key, title, weight)| AdminSection { - key: key.to_owned(), - path: key.to_owned(), - title: Lc::l(title), - weight, - }) + .map(|(key, title, weight)| AdminSection::new(key, Lc::l(title)).with_weight(weight)) .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(®istry); - 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; 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::>(); + 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(®istry); + 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] fn permissions_missing_from_the_catalog_are_reported_once_each() { - let mut registry = AdminRegistry { - sections: BTreeMap::new(), - pages: BTreeMap::new(), - tasks: BTreeMap::new(), - actions: BTreeMap::new(), - }; - for p in [ - page("config/site", "config"), - page("config/other", "config"), - ] { - registry.pages.insert(p.path.clone(), p); - } - let mut advanced = task("config/site/advanced", "config/site"); - advanced.permission = Some(&OtherPermission); - registry - .tasks - .insert("config/site".to_owned(), vec![advanced]); + let (registry, _) = AdminRegistry::new( + vec![], + vec![ + page("config/site", "config"), + page("config/other", "config"), + ], + vec![task("config/site/advanced", "config/site").with_permission(&OtherPermission)], + vec![], + ); let mut catalog = PermissionRegistry::default(); catalog.register(&AnyPermission); diff --git a/src/base/action/admin/declare_admin_actions.rs b/src/base/action/admin/declare_admin_actions.rs index 33b9d0c5..8978bbaf 100644 --- a/src/base/action/admin/declare_admin_actions.rs +++ b/src/base/action/admin/declare_admin_actions.rs @@ -4,20 +4,14 @@ use super::FnActionDeclareAdminActions; /// 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 /// /// ```rust,no_run /// # use pagetop::prelude::*; /// fn declare_actions(bag: &mut AdminActionBag) { -/// bag.add(AdminAction { -/// url: "config/export/new".to_owned(), -/// for_path: "config/export".to_owned(), -/// title: Lc::n("Add export"), -/// weight: 0, -/// permission: None, -/// }); +/// bag.add(AdminAction::new("config/export/new", "config/export", Lc::n("Add export"))); /// } /// // En Extension::actions(): /// // action::admin::DeclareAdminActions::new(declare_actions) diff --git a/src/base/action/admin/declare_admin_sections.rs b/src/base/action/admin/declare_admin_sections.rs index 3d341642..335a47b6 100644 --- a/src/base/action/admin/declare_admin_sections.rs +++ b/src/base/action/admin/declare_admin_sections.rs @@ -12,12 +12,7 @@ use super::FnActionDeclareAdminSections; /// ```rust,no_run /// # use pagetop::prelude::*; /// fn declare_sections(bag: &mut AdminSectionBag) { -/// bag.add(AdminSection { -/// key: "tools".to_owned(), -/// path: "tools".to_owned(), -/// title: Lc::n("Tools"), -/// weight: 60, -/// }); +/// bag.add(AdminSection::new("tools", Lc::n("Tools")).with_weight(60)); /// } /// // En Extension::actions(): /// // action::admin::DeclareAdminSections::new(declare_sections) diff --git a/src/base/action/admin/declare_admin_tasks.rs b/src/base/action/admin/declare_admin_tasks.rs index 0b885296..0971b256 100644 --- a/src/base/action/admin/declare_admin_tasks.rs +++ b/src/base/action/admin/declare_admin_tasks.rs @@ -4,21 +4,16 @@ use super::FnActionDeclareAdminTasks; /// 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 /// /// ```rust,no_run /// # use pagetop::prelude::*; /// fn declare_tasks(bag: &mut AdminTaskBag) { -/// bag.add(AdminTask { -/// path: "config/export/csv".to_owned(), -/// parent_path: "config/export".to_owned(), -/// title: Lc::n("CSV"), -/// weight: 0, -/// is_default: true, -/// permission: None, -/// }); +/// bag.add(AdminTask::new("config/export", "config/export", Lc::n("All"))); +/// bag.add(AdminTask::new("config/export/csv", "config/export", Lc::n("CSV")).with_weight(1)); /// } /// // En Extension::actions(): /// // action::admin::DeclareAdminTasks::new(declare_tasks) diff --git a/src/base/component/admin_frame.rs b/src/base/component/admin_frame.rs index efc5d2ca..e77c66f1 100644 --- a/src/base/component/admin_frame.rs +++ b/src/base/component/admin_frame.rs @@ -49,9 +49,9 @@ impl Component for AdminFrame { // Sin título propio, la página declarada aporta el suyo, también al `` (que se // renderiza después del ``). 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; @@ -89,26 +89,26 @@ fn breadcrumbs(cx: &Context, path: &str) -> Breadcrumb { admin_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( - section.title.clone(), - admin_path(§ion.path), + section.title().clone(), + admin_path(section.path()), )); } - if page.path == path { - bc = bc.with_crumb(breadcrumb::Crumb::current(page.title.clone())); + if page.path() == path { + bc = bc.with_crumb(breadcrumb::Crumb::current(page.title().clone())); } else { bc = bc.with_crumb(breadcrumb::Crumb::new( - page.title.clone(), - admin_path(&page.path), + page.title().clone(), + admin_path(page.path()), )); if !cx.title().is_none() { 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. - bc = bc.with_crumb(breadcrumb::Crumb::current(section.title.clone())); + bc = bc.with_crumb(breadcrumb::Crumb::current(section.title().clone())); } bc } @@ -117,16 +117,11 @@ fn breadcrumbs(cx: &Context, path: &str) -> Breadcrumb { // permiso que el usuario no tiene no se muestran. fn local_tasks(cx: &Context, path: &str) -> Markup { let registry = AdminRegistry::global(); - let parent = registry - .tasks() - .values() - .flatten() - .find(|task| task.path == path) - .map_or(path, |task| task.parent_path.as_str()); + let parent = registry.task(path).map_or(path, |task| task.parent_path()); let tasks: Vec<_> = registry .tasks_for(parent) - .into_iter() - .filter(|task| is_granted(cx, task.permission)) + .iter() + .filter(|task| is_granted(cx, task.permission())) .collect(); if tasks.is_empty() { return html! {}; @@ -134,8 +129,8 @@ fn local_tasks(cx: &Context, path: &str) -> Markup { html! { ul class="admin-tasks-list" { @for task in tasks { - li class="admin-task" .admin-task-active[task.path == path] { - a href=(cx.route(admin_path(&task.path))) { (task.title.using(cx)) } + li class="admin-task" .admin-task-active[task.path() == path] { + 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 { let actions: Vec<_> = AdminRegistry::global() .actions_for(path) - .into_iter() - .filter(|action| is_granted(cx, action.permission)) + .iter() + .filter(|action| is_granted(cx, action.permission())) .collect(); if actions.is_empty() { return html! {}; @@ -157,8 +152,8 @@ fn local_actions(cx: &Context, path: &str) -> Markup { ul class="admin-actions-list" { @for action in actions { li class="admin-action" { - a class="admin-action-link" href=(cx.route(admin_path(&action.url))) { - (action.title.using(cx)) + a class="admin-action-link" href=(cx.route(admin_path(action.url()))) { + (action.title().using(cx)) } } } diff --git a/src/base/component/admin_menu.rs b/src/base/component/admin_menu.rs index aa4dc5bb..80929429 100644 --- a/src/base/component/admin_menu.rs +++ b/src/base/component/admin_menu.rs @@ -32,20 +32,20 @@ impl Component for AdminMenu { let mut nav = 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 - .pages_for_section(§ion.key) - .into_iter() + .pages_for_section(section.key()) + .iter() .filter(|p| p.is_accessible(cx)) .collect(); if pages.is_empty() { 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 { menu = menu.with_item(dropdown::Item::link( - page.title.clone(), - admin_path(&page.path), + page.title().clone(), + admin_path(page.path()), )); } nav = nav.with_item(nav::Item::dropdown(menu)); diff --git a/tests/admin_invalid_route.rs b/tests/admin_invalid_route.rs index cfcad9ab..7c2786cd 100644 --- a/tests/admin_invalid_route.rs +++ b/tests/admin_invalid_route.rs @@ -11,14 +11,12 @@ impl Permission for ToolsPermission { } fn declare_pages(bag: &mut AdminPageBag) { - bag.add(AdminPage { - path: "config/export".to_owned(), - section: "config".to_owned(), - title: Lc::n("Export"), - description: Lc::none(), - weight: 0, - permission: &ToolsPermission, - }); + bag.add(AdminPage::new( + "config/export", + "config", + Lc::n("Export"), + &ToolsPermission, + )); } struct Ext; diff --git a/tests/admin_registry.rs b/tests/admin_registry.rs index 2400a7e7..65311160 100644 --- a/tests/admin_registry.rs +++ b/tests/admin_registry.rs @@ -12,55 +12,33 @@ impl Permission for ToolsPermission { } fn declare_sections(bag: &mut AdminSectionBag) { - bag.add(AdminSection { - key: "tools".to_owned(), - path: "tools".to_owned(), - title: Lc::n("Tools"), - weight: 35, - }); + bag.add(AdminSection::new("tools", Lc::n("Tools")).with_weight(35)); // Replaces the built-in section with the same key. - bag.add(AdminSection { - key: "help".to_owned(), - path: "support".to_owned(), - title: Lc::n("Support"), - weight: 5, - }); + bag.add( + AdminSection::new("help", Lc::n("Support")) + .with_path("support") + .with_weight(5), + ); } fn declare_pages(bag: &mut AdminPageBag) { for (path, weight) in [("tools/export", 10), ("/tools/import/", 0)] { - bag.add(AdminPage { - path: path.to_owned(), - section: "tools".to_owned(), - title: Lc::n(path), - description: Lc::none(), - weight, - permission: &ToolsPermission, - }); + bag.add(AdminPage::new(path, "tools", Lc::n(path), &ToolsPermission).with_weight(weight)); } } fn declare_tasks(bag: &mut AdminTaskBag) { for (path, weight) in [("tools/export/json", 1), ("tools/export/csv", 0)] { - bag.add(AdminTask { - path: path.to_owned(), - parent_path: "/tools/export".to_owned(), - title: Lc::n(path), - weight, - is_default: weight == 0, - permission: None, - }); + bag.add(AdminTask::new(path, "/tools/export", Lc::n(path)).with_weight(weight)); } } fn declare_actions(bag: &mut AdminActionBag) { - bag.add(AdminAction { - url: "tools/export/new/".to_owned(), - for_path: "tools/export".to_owned(), - title: Lc::n("New export"), - weight: 0, - permission: None, - }); + bag.add(AdminAction::new( + "tools/export/new/", + "tools/export", + Lc::n("New export"), + )); } struct Ext; @@ -87,9 +65,9 @@ async fn start() { async fn built_in_sections_come_first_and_can_be_replaced() { start().await; let keys: Vec<_> = AdminRegistry::global() - .ordered_sections() - .into_iter() - .map(|s| (s.key.as_str(), s.path.as_str())) + .sections() + .iter() + .map(|s| (s.key(), s.path())) .collect(); assert_eq!( keys, @@ -110,21 +88,21 @@ async fn paths_are_kept_relative_without_surrounding_slashes() { let registry = AdminRegistry::global(); let pages: Vec<_> = registry .pages_for_section("tools") - .into_iter() - .map(|p| p.path.as_str()) + .iter() + .map(|p| p.path()) .collect(); assert_eq!(pages, ["tools/import", "tools/export"]); let tasks: Vec<_> = registry .tasks_for("tools/export") - .into_iter() - .map(|t| t.path.as_str()) + .iter() + .map(|t| t.path()) .collect(); assert_eq!(tasks, ["tools/export/csv", "tools/export/json"]); let actions = registry.actions_for("tools/export"); assert_eq!(actions.len(), 1); - assert_eq!(actions[0].url, "tools/export/new"); + assert_eq!(actions[0].url(), "tools/export/new"); } #[pagetop::test] diff --git a/tests/admin_template.rs b/tests/admin_template.rs index 6b092031..64a4bb49 100644 --- a/tests/admin_template.rs +++ b/tests/admin_template.rs @@ -28,66 +28,49 @@ fn grant_tools(_: &HttpRequest, perm: PermissionRef, granted: &mut bool) { } fn declare_pages(bag: &mut AdminPageBag) { - bag.add(AdminPage { - path: "config/export".to_owned(), - section: "config".to_owned(), - title: Lc::n("Export"), - description: Lc::none(), - weight: 0, - permission: &ToolsPermission, - }); - bag.add(AdminPage { - path: "reports/audit".to_owned(), - section: "reports".to_owned(), - title: Lc::n("Audit"), - description: Lc::none(), - weight: 0, - permission: &AuditPermission, - }); + bag.add(AdminPage::new( + "config/export", + "config", + Lc::n("Export"), + &ToolsPermission, + )); + bag.add(AdminPage::new( + "reports/audit", + "reports", + Lc::n("Audit"), + &AuditPermission, + )); } fn declare_tasks(bag: &mut AdminTaskBag) { - bag.add(AdminTask { - path: "config/export".to_owned(), - parent_path: "config/export".to_owned(), - title: Lc::n("All"), - weight: 0, - is_default: true, - permission: None, - }); - bag.add(AdminTask { - path: "config/export/csv".to_owned(), - 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), - }); + bag.add(AdminTask::new( + "config/export", + "config/export", + Lc::n("All"), + )); + bag.add(AdminTask::new("config/export/csv", "config/export", Lc::n("CSV")).with_weight(1)); + bag.add( + AdminTask::new("config/export/log", "config/export", Lc::n("Log")) + .with_weight(2) + .with_permission(&AuditPermission), + ); } fn declare_actions(bag: &mut AdminActionBag) { - bag.add(AdminAction { - url: "config/export/new".to_owned(), - for_path: "config/export".to_owned(), - title: Lc::n("New export"), - weight: 0, - permission: None, - }); - bag.add(AdminAction { - url: "config/export/purge".to_owned(), - for_path: "config/export".to_owned(), - title: Lc::n("Purge exports"), - weight: 1, - permission: Some(&AuditPermission), - }); + bag.add(AdminAction::new( + "config/export/new", + "config/export", + Lc::n("New export"), + )); + bag.add( + AdminAction::new( + "config/export/purge", + "config/export", + Lc::n("Purge exports"), + ) + .with_weight(1) + .with_permission(&AuditPermission), + ); } struct Ext;