✨ (base): Oculta separadores en menús sin opciones
`Dropdown::items()` devuelve `dropdown::Items`, cuyo `render()` sólo pinta un encabezado si su grupo tiene algún elemento visible, y un separador sólo entre elementos visibles. Lo aprovecha cualquier tema que pinte el menú con `items().render()`.
This commit is contained in:
parent
e2e2ccb31e
commit
c940403869
9 changed files with 292 additions and 10 deletions
|
|
@ -15,7 +15,7 @@ mod props;
|
|||
pub use props::{AutoClose, Direction, MenuAlign, MenuPosition};
|
||||
|
||||
pub use pagetop::base::component::Dropdown;
|
||||
pub use pagetop::base::component::dropdown::{Item, ItemKind};
|
||||
pub use pagetop::base::component::dropdown::{Item, ItemKind, Items};
|
||||
|
||||
const EXTRA_BUTTON_GROUPED: &str = "bootsier.dropdown.button_grouped";
|
||||
const EXTRA_AUTO_CLOSE: &str = "bootsier.dropdown.auto_close";
|
||||
|
|
|
|||
|
|
@ -66,6 +66,9 @@ fn menu() -> Nav {
|
|||
.with_item(bs::nav::Item::dropdown(
|
||||
Dropdown::new()
|
||||
.with_title(Lc::n("dropdown-partial"))
|
||||
.with_item(dropdown::Item::header(Lc::n("header-empty")))
|
||||
.with_item(dropdown::Item::link(Lc::n("x"), TestRoute::Forbidden))
|
||||
.with_item(dropdown::Item::divider())
|
||||
.with_item(dropdown::Item::link(
|
||||
Lc::n("in-allowed"),
|
||||
TestRoute::Allowed,
|
||||
|
|
@ -97,9 +100,18 @@ fn assert_only_allowed_links(html: &str) {
|
|||
for shown in ["nav-allowed", "dropdown-partial", "in-allowed"] {
|
||||
assert!(html.contains(shown), "`{shown}` is missing in {html}");
|
||||
}
|
||||
for hidden in ["nav-forbidden", "dropdown-empty", "in-forbidden"] {
|
||||
for hidden in [
|
||||
"nav-forbidden",
|
||||
"dropdown-empty",
|
||||
"in-forbidden",
|
||||
"header-empty",
|
||||
] {
|
||||
assert!(!html.contains(hidden), "`{hidden}` is shown in {html}");
|
||||
}
|
||||
assert!(
|
||||
!html.contains("dropdown-divider"),
|
||||
"a divider is shown in {html}"
|
||||
);
|
||||
}
|
||||
|
||||
#[pagetop::test]
|
||||
|
|
|
|||
|
|
@ -5,3 +5,6 @@ pub use component::Dropdown;
|
|||
|
||||
mod item;
|
||||
pub use item::{Item, ItemKind};
|
||||
|
||||
mod items;
|
||||
pub use items::Items;
|
||||
|
|
|
|||
|
|
@ -2,13 +2,15 @@ use crate::prelude::*;
|
|||
|
||||
/// Componente para crear un **menú desplegable**.
|
||||
///
|
||||
/// Renderiza un botón (único o desdoblado, ver [`with_button_split()`](Self::with_button_split))
|
||||
/// que despliega u oculta una lista de elementos [`dropdown::Item`](super::Item).
|
||||
/// Renderiza un botón (único o desdoblado, ver [`with_button_split()`]) que despliega u oculta una
|
||||
/// lista de elementos [`dropdown::Item`].
|
||||
///
|
||||
/// Sin título (ver [`with_title()`](Self::with_title)), se muestra únicamente la lista de
|
||||
/// elementos, sin ningún botón para interactuar, sólo un menú contextual estático.
|
||||
/// Sin título (ver [`with_title()`]), se muestra únicamente la lista de elementos, sin ningún botón
|
||||
/// para interactuar, sólo un menú contextual estático.
|
||||
///
|
||||
/// Si no contiene elementos, el componente **no se renderiza**.
|
||||
/// Un encabezado sólo se muestra si su grupo tiene algún elemento visible, y un separador sólo
|
||||
/// entre elementos visibles (ver [`dropdown::Items`]). Si no quedan elementos para mostrar, el
|
||||
/// componente **no se renderiza**.
|
||||
///
|
||||
/// # Ejemplo
|
||||
///
|
||||
|
|
@ -23,6 +25,11 @@ use crate::prelude::*;
|
|||
/// .with_item(dropdown::Item::header(Lc::n("User session")))
|
||||
/// .with_item(dropdown::Item::button(Lc::n("Sign out")));
|
||||
/// ```
|
||||
///
|
||||
/// [`with_title()`]: Self::with_title
|
||||
/// [`with_button_split()`]: Self::with_button_split
|
||||
/// [`dropdown::Item`]: super::Item
|
||||
/// [`dropdown::Items`]: super::Items
|
||||
#[derive(AutoDefault, Clone, Debug, Getters)]
|
||||
pub struct Dropdown {
|
||||
/// Devuelve identificador, clases CSS, atributos HTML y valores extra del componente.
|
||||
|
|
@ -40,7 +47,7 @@ pub struct Dropdown {
|
|||
/// Devuelve si el menú se alinea al final del botón (por defecto, al inicio).
|
||||
menu_end: bool,
|
||||
/// Devuelve la lista de elementos del menú.
|
||||
items: Children,
|
||||
items: dropdown::Items,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
|
|
@ -210,7 +217,7 @@ impl Dropdown {
|
|||
/// ]));
|
||||
/// ```
|
||||
pub fn with_item(mut self, op: impl Into<TypedOp<dropdown::Item>>) -> Self {
|
||||
self.items.alter_child(op.into());
|
||||
self.items.alter_item(op.into());
|
||||
self
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -42,7 +42,8 @@ pub enum ItemKind {
|
|||
/// asociada, manteniendo una interfaz común para renderizar todos los elementos del menú.
|
||||
///
|
||||
/// Un enlace no se renderiza si el usuario actual no puede acceder a su ruta (ver [`Endpoint`]).
|
||||
/// Los encabezados y separadores no dependen de ningún enlace y se muestran aunque queden solos.
|
||||
/// Tampoco se muestra un encabezado si su grupo no tiene ningún elemento visible, ni un separador
|
||||
/// que no quede entre elementos visibles (ver [`dropdown::Items`](super::Items)).
|
||||
#[derive(AutoDefault, Clone, Debug, Getters)]
|
||||
pub struct Item {
|
||||
/// Devuelve identificador, clases CSS, atributos HTML y valores extra del componente.
|
||||
|
|
|
|||
68
src/base/component/dropdown/items.rs
Normal file
68
src/base/component/dropdown/items.rs
Normal file
|
|
@ -0,0 +1,68 @@
|
|||
use crate::prelude::*;
|
||||
|
||||
use super::{Item, ItemKind};
|
||||
|
||||
/// Lista de elementos [`Item`] de un menú desplegable [`Dropdown`](super::Dropdown).
|
||||
///
|
||||
/// Se renderiza sin los encabezados ni los separadores que no separan nada (ver
|
||||
/// [`render()`](Self::render)), así que cualquier tema que pinte el menú con `items().render(cx)`
|
||||
/// aprovecha la limpieza sin hacer nada más.
|
||||
#[derive(AutoDefault, Clone, Debug)]
|
||||
pub struct Items(Children);
|
||||
|
||||
impl Items {
|
||||
/// Devuelve el número de elementos de la lista, también los que no se mostrarán.
|
||||
pub fn len(&self) -> usize {
|
||||
self.0.len()
|
||||
}
|
||||
|
||||
/// Indica si la lista está vacía.
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.0.is_empty()
|
||||
}
|
||||
|
||||
/// Renderiza los elementos sin los encabezados ni los separadores que no separan nada.
|
||||
///
|
||||
/// Un encabezado sólo se muestra si le sigue algún elemento visible antes del siguiente
|
||||
/// encabezado o separador, y un separador sólo entre dos elementos visibles, una sola vez.
|
||||
/// Así, si se ocultan todos los enlaces de un grupo (por ejemplo, porque el usuario no tiene
|
||||
/// acceso a sus rutas, ver [`Endpoint`]), su encabezado desaparece con ellos. Un elemento es
|
||||
/// visible si su renderizado no queda vacío. Cada uno se renderiza como mucho una vez: los
|
||||
/// encabezados y separadores, sólo si se muestran.
|
||||
pub async fn render(&self, cx: &mut Context) -> Markup {
|
||||
let mut shown: Vec<Markup> = Vec::with_capacity(self.0.len());
|
||||
// Encabezado y separador a la espera de un elemento visible que los justifique.
|
||||
let mut header = None;
|
||||
let mut divider = None;
|
||||
for item in self.0.iter() {
|
||||
match item.downcast_ref::<Item>().map(Item::item_kind) {
|
||||
Some(ItemKind::Header(_)) => header = Some(item),
|
||||
Some(ItemKind::Divider) => {
|
||||
header = None;
|
||||
if !shown.is_empty() {
|
||||
divider = Some(item);
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
let markup = item.render(cx).await;
|
||||
if markup.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if let Some(divider) = divider.take() {
|
||||
shown.push(divider.render(cx).await);
|
||||
}
|
||||
if let Some(header) = header.take() {
|
||||
shown.push(header.render(cx).await);
|
||||
}
|
||||
shown.push(markup);
|
||||
}
|
||||
}
|
||||
}
|
||||
html! { @for markup in &shown { (markup) } }
|
||||
}
|
||||
|
||||
// Añade un elemento o modifica la lista con una operación `TypedOp`.
|
||||
pub(crate) fn alter_item(&mut self, op: TypedOp<Item>) {
|
||||
self.0.alter_child(op);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,3 +1,4 @@
|
|||
use crate::core::AnyCast;
|
||||
use crate::core::component::{Component, Context};
|
||||
use crate::html::{Markup, html};
|
||||
use crate::{AutoDefault, UniqueId, builder_impl};
|
||||
|
|
@ -71,6 +72,24 @@ impl Child {
|
|||
}
|
||||
}
|
||||
|
||||
/// Devuelve una referencia al componente si es del tipo `C`, o `None` si es de otro tipo o el
|
||||
/// `Child` está vacío.
|
||||
///
|
||||
/// Permite consultar el estado de un componente concreto de una lista sin renderizarlo (p. ej.
|
||||
/// el tipo de cada [`dropdown::Item`](crate::base::component::dropdown::Item)).
|
||||
///
|
||||
/// # Ejemplo
|
||||
///
|
||||
/// ```rust
|
||||
/// # use pagetop::prelude::*;
|
||||
/// let child = Child::with(Html::with(|_| html! { "Prueba" }));
|
||||
/// assert!(child.downcast_ref::<Html>().is_some());
|
||||
/// assert!(child.downcast_ref::<Button>().is_none());
|
||||
/// ```
|
||||
pub fn downcast_ref<C: Component>(&self) -> Option<&C> {
|
||||
self.0.as_deref().and_then(|c| c.downcast_ref::<C>())
|
||||
}
|
||||
|
||||
// **< Child HELPERS >**************************************************************************
|
||||
|
||||
// Devuelve el [`UniqueId`] del tipo del componente, si el Child no está vacío.
|
||||
|
|
@ -440,6 +459,11 @@ impl Children {
|
|||
self.0.iter().filter(move |c| c.type_id() == Some(type_id))
|
||||
}
|
||||
|
||||
/// Devuelve un iterador sobre todos los componentes hijo, en orden.
|
||||
pub fn iter(&self) -> impl Iterator<Item = &Child> {
|
||||
self.0.iter()
|
||||
}
|
||||
|
||||
// **< Children RENDER >************************************************************************
|
||||
|
||||
/// Renderiza todos los componentes hijo, en orden.
|
||||
|
|
|
|||
|
|
@ -68,6 +68,15 @@ async fn child_id_returns_component_id() {
|
|||
assert_eq!(child.id(), Some("my-id".to_string()));
|
||||
}
|
||||
|
||||
#[pagetop::test]
|
||||
async fn child_downcast_ref_returns_the_component_only_with_its_type() {
|
||||
let child = Child::with(TestComp::text("hello"));
|
||||
let component = child.downcast_ref::<TestComp>().expect("a TestComp");
|
||||
assert_eq!(component.text, "hello");
|
||||
assert!(child.downcast_ref::<Html>().is_none());
|
||||
assert!(Child::default().downcast_ref::<TestComp>().is_none());
|
||||
}
|
||||
|
||||
#[pagetop::test]
|
||||
async fn child_from_component_is_equivalent_to_with() {
|
||||
let child: Child = TestComp::text("from-trait").into();
|
||||
|
|
@ -257,6 +266,19 @@ async fn children_iter_by_id_yields_all_matching_children() {
|
|||
assert_eq!(c.iter_by_id("none").count(), 0);
|
||||
}
|
||||
|
||||
#[pagetop::test]
|
||||
async fn children_iter_yields_all_children_in_order() {
|
||||
let c = Children::new()
|
||||
.with_child(TestComp::text("a"))
|
||||
.with_child(TestComp::text("b"));
|
||||
let texts: Vec<&str> = c
|
||||
.iter()
|
||||
.filter_map(|child| child.downcast_ref::<TestComp>())
|
||||
.map(|component| component.text.as_str())
|
||||
.collect();
|
||||
assert_eq!(texts, ["a", "b"]);
|
||||
}
|
||||
|
||||
#[pagetop::test]
|
||||
async fn children_render_concatenates_all_outputs_in_order() {
|
||||
let c = Children::new()
|
||||
|
|
|
|||
|
|
@ -48,3 +48,148 @@ async fn menu_end_is_ignored_without_title() {
|
|||
assert!(html.contains(r#"<ul class="dropdown-menu">"#));
|
||||
assert!(!html.contains("dropdown-menu-end"));
|
||||
}
|
||||
|
||||
// **< Separators >*********************************************************************************
|
||||
|
||||
// A route that nobody can see without a request: its links are always hidden in these tests.
|
||||
#[derive(Clone, Copy)]
|
||||
struct Hidden;
|
||||
|
||||
impl Endpoint for Hidden {
|
||||
fn path(&self) -> CowStr {
|
||||
"/hidden".into()
|
||||
}
|
||||
|
||||
fn access(&self) -> Access {
|
||||
Access::Authenticated
|
||||
}
|
||||
}
|
||||
|
||||
fn shown(label: &'static str) -> dropdown::Item {
|
||||
dropdown::Item::link(Lc::n(label), "/shown")
|
||||
}
|
||||
|
||||
fn hidden(label: &'static str) -> dropdown::Item {
|
||||
dropdown::Item::link(Lc::n(label), Hidden)
|
||||
}
|
||||
|
||||
fn header(label: &'static str) -> dropdown::Item {
|
||||
dropdown::Item::header(Lc::n(label))
|
||||
}
|
||||
|
||||
// Position of `text` in `html`, which must contain it.
|
||||
fn at(html: &str, text: &str) -> usize {
|
||||
html.find(text)
|
||||
.unwrap_or_else(|| panic!("`{text}` is missing in {html}"))
|
||||
}
|
||||
|
||||
async fn render_menu(items: Vec<dropdown::Item>) -> String {
|
||||
Dropdown::new()
|
||||
.with_title(Lc::n("Menu"))
|
||||
.with_item(TypedOp::AddMany(items))
|
||||
.render(&mut Context::default())
|
||||
.await
|
||||
.into_string()
|
||||
}
|
||||
|
||||
#[pagetop::test]
|
||||
async fn a_header_without_visible_items_is_not_shown() {
|
||||
let html = render_menu(vec![
|
||||
header("group-empty"),
|
||||
hidden("item-hidden"),
|
||||
header("group-full"),
|
||||
shown("item-shown"),
|
||||
])
|
||||
.await;
|
||||
|
||||
assert!(!html.contains("group-empty"), "{html}");
|
||||
assert!(!html.contains("item-hidden"), "{html}");
|
||||
assert!(html.contains("group-full"), "{html}");
|
||||
assert!(at(&html, "group-full") < at(&html, "item-shown"), "{html}");
|
||||
}
|
||||
|
||||
#[pagetop::test]
|
||||
async fn dividers_only_separate_visible_items() {
|
||||
let html = render_menu(vec![
|
||||
dropdown::Item::divider(),
|
||||
shown("first"),
|
||||
dropdown::Item::divider(),
|
||||
hidden("item-hidden"),
|
||||
dropdown::Item::divider(),
|
||||
shown("second"),
|
||||
dropdown::Item::divider(),
|
||||
])
|
||||
.await;
|
||||
|
||||
assert_eq!(html.matches("dropdown-divider").count(), 1, "{html}");
|
||||
let divider = at(&html, "dropdown-divider");
|
||||
assert!(
|
||||
at(&html, "first") < divider && divider < at(&html, "second"),
|
||||
"{html}"
|
||||
);
|
||||
}
|
||||
|
||||
#[pagetop::test]
|
||||
async fn a_divider_and_a_header_are_shown_before_the_next_visible_group() {
|
||||
let html = render_menu(vec![
|
||||
shown("first"),
|
||||
dropdown::Item::divider(),
|
||||
header("group"),
|
||||
shown("second"),
|
||||
])
|
||||
.await;
|
||||
|
||||
let (divider, group) = (at(&html, "dropdown-divider"), at(&html, "group"));
|
||||
assert!(at(&html, "first") < divider && divider < group, "{html}");
|
||||
assert!(group < at(&html, "second"), "{html}");
|
||||
}
|
||||
|
||||
#[pagetop::test]
|
||||
async fn labels_and_buttons_count_as_visible_items() {
|
||||
let html = render_menu(vec![
|
||||
header("group-label"),
|
||||
dropdown::Item::label(Lc::n("text")),
|
||||
header("group-button"),
|
||||
dropdown::Item::button(Lc::n("action")),
|
||||
])
|
||||
.await;
|
||||
|
||||
assert!(html.contains("group-label"), "{html}");
|
||||
assert!(html.contains("group-button"), "{html}");
|
||||
}
|
||||
|
||||
#[pagetop::test]
|
||||
async fn a_dropdown_with_only_separators_left_is_not_rendered() {
|
||||
let html = render_menu(vec![
|
||||
header("group"),
|
||||
hidden("item-hidden"),
|
||||
dropdown::Item::divider(),
|
||||
])
|
||||
.await;
|
||||
|
||||
assert!(html.is_empty(), "{html}");
|
||||
}
|
||||
|
||||
#[pagetop::test]
|
||||
async fn separators_are_also_cleaned_in_a_dropdown_inside_a_nav() {
|
||||
let menu = Dropdown::new()
|
||||
.with_title(Lc::n("menu-empty"))
|
||||
.with_item(header("group-empty"))
|
||||
.with_item(hidden("item-hidden"));
|
||||
let partial = Dropdown::new()
|
||||
.with_title(Lc::n("menu-partial"))
|
||||
.with_item(header("group-empty"))
|
||||
.with_item(hidden("item-hidden"))
|
||||
.with_item(dropdown::Item::divider())
|
||||
.with_item(shown("item-shown"));
|
||||
let mut nav = Nav::new()
|
||||
.with_item(nav::Item::dropdown(menu))
|
||||
.with_item(nav::Item::dropdown(partial));
|
||||
let html = nav.render(&mut Context::default()).await.into_string();
|
||||
|
||||
assert!(!html.contains("menu-empty"), "{html}");
|
||||
assert!(html.contains("menu-partial"), "{html}");
|
||||
assert!(!html.contains("group-empty"), "{html}");
|
||||
assert!(!html.contains("dropdown-divider"), "{html}");
|
||||
assert!(html.contains("item-shown"), "{html}");
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue