✨ Añade iconos a botones y menús

Nuevo componente Icon con un pequeño conjunto propio (`icon::Core`) que
cada tema puede sustituir; Bootsier usa Bootstrap Icons. `Button`,
`nav::Item` y `dropdown::Item` admiten iconos al principio y al final, y
el panel de administración los usa en secciones y páginas.
This commit is contained in:
Manuel Cillero 2026-11-22 23:08:28 +01:00
parent d83f8b0f7f
commit 5d6852382a
23 changed files with 1098 additions and 161 deletions

View file

@ -226,6 +226,63 @@ fieldset > legend {
@extend .alert-danger;
}
// Inline SVG icons (`Icon`) sit on the text baseline like the Bootstrap Icons glyphs.
svg.icon {
flex-shrink: 0;
vertical-align: -0.125em;
}
// Color of an icon with an intent (`Icon::with_intent()`), named after the Bootsier palette.
@each $color in primary, secondary, success, info, warning, danger {
.icon-#{$color} {
color: var(--bs-#{$color});
}
}
// Icons of menu items (`with_icon_start()`/`with_icon_end()` of `nav::Item` and `dropdown::Item`).
// In a row of links, each icon keeps its distance from the label.
.nav-link > .icon-start {
margin-inline-end: 0.5em;
}
.nav-link > .icon-end {
margin-inline-start: 0.5em;
}
// In a vertical list (dropdown menu or vertical nav) with any icon, every item is a flex row: the
// end icon goes to the edge, and an item without an icon on one side keeps that space empty, so
// that all the labels line up. The `:has()` selectors look only at the items of this list, not at
// those of a nested menu.
.dropdown-menu:has(> li > * > .icon) > li > :is(.dropdown-item, .dropdown-item-text),
.nav-vertical:has(> li > .nav-link > .icon) > li > .nav-link {
display: flex;
align-items: center;
gap: 0.5em;
> .icon-start,
> .icon-end {
margin: 0;
}
> .icon-end {
margin-inline-start: auto;
}
}
.dropdown-menu:has(> li > * > .icon-start) > li > :is(.dropdown-item, .dropdown-item-text),
.nav-vertical:has(> li > .nav-link > .icon-start) > li > .nav-link {
&:not(:has(> .icon-start))::before {
content: "";
flex: 0 0 1em;
}
}
// The toggle of a dropdown already shows its arrow at the end.
.dropdown-menu:has(> li > * > .icon-end) > li > :is(.dropdown-item, .dropdown-item-text),
.nav-vertical:has(> li > .nav-link > .icon-end) > li > .nav-link:not(.dropdown-toggle) {
&:not(:has(> .icon-end))::after {
content: "";
flex: 0 0 1em;
margin-inline-start: auto;
}
}
// Sort indicator on sortable table headers (`table::SortLink`), using Bootstrap Icons'
// sort-up/sort-down glyphs instead of the plain triangle from basic.css.
.table-sort::after {

View file

@ -283,6 +283,7 @@ impl Theme for Bootsier {
Container => |c| theme::bs::container::setup(c),
Dialog => |c| theme::bs::dialog::setup(c),
Dropdown => |c| theme::bs::dropdown::setup(c),
Icon => |c| theme::bs::icon::setup(c),
Image => |c| theme::bs::image::setup(c),
Nav => |c| theme::bs::nav::setup(c),
Navbar => |c| theme::bs::navbar::setup(c),

View file

@ -82,6 +82,8 @@ pub use bs::form::select::SelectBsExt;
#[doc(hidden)]
pub use bs::form::textarea::TextareaBsExt;
#[doc(hidden)]
pub use bs::icon::IconBsExt;
#[doc(hidden)]
pub use bs::nav::NavBsExt;
#[doc(hidden)]
pub use bs::navbar::NavbarBsExt;

View file

@ -50,6 +50,13 @@ pub use form::select::SelectBsExt;
#[doc(inline)]
pub use form::textarea::TextareaBsExt;
// Icon.
pub mod icon;
#[doc(inline)]
pub use icon::Icon;
#[doc(inline)]
pub use icon::IconBsExt;
// Image.
pub mod image;
#[doc(inline)]

View file

@ -1,128 +1,68 @@
use crate::theme::*;
//! Definiciones para mostrar iconos ([`Icon`]).
const DEFAULT_VIEWBOX: &str = "0 0 16 16";
use pagetop::prelude::*;
#[derive(AutoDefault, Clone)]
pub enum IconKind {
#[default]
None,
Font(FontSize),
Svg {
shapes: Markup,
viewbox: AttrValue,
},
pub use pagetop::base::component::icon::{Core, Icon, Source};
/// Extensión de Bootsier para [`Icon`].
///
/// Añade los iconos de [Bootstrap Icons](https://icons.getbootstrap.com/), que Bootsier ya carga
/// como fuente de iconos en todas las páginas. Además, Bootsier muestra los iconos del conjunto de
/// PageTop ([`Core`]) con su equivalente de Bootstrap Icons.
///
/// ```rust,no_run
/// use pagetop::prelude::*;
/// use pagetop_bootsier::theme::*;
///
/// let home = bs::Icon::bi("house-fill").with_label(Lc::n("Home"));
/// ```
pub trait IconBsExt: Sized {
/// Crea un icono de Bootstrap Icons a partir de su nombre, sin el prefijo `bi-` (p. ej.
/// `"house-fill"`).
fn bi(name: impl AsRef<str>) -> Self;
}
#[derive(AutoDefault, Clone, Debug, Getters)]
pub struct Icon {
/// Devuelve identificador, clases CSS, atributos HTML y valores extra del componente.
props: Props,
icon_kind: IconKind,
aria_label: AttrLc,
}
#[async_trait]
impl Component for Icon {
fn new() -> Self {
Self::default()
}
fn id(&self) -> Option<String> {
self.props.get_id()
}
fn setup(&mut self, _cx: &mut Context) {
if !matches!(self.icon_kind(), IconKind::None) {
self.alter_prop(PropsOp::prepend_classes("icon"));
}
if let IconKind::Font(font_size) = self.icon_kind() {
self.alter_prop(PropsOp::add_classes(font_size.as_str()));
}
}
async fn prepare(&self, cx: &mut Context) -> Result<Markup, ComponentError> {
Ok(match self.icon_kind() {
IconKind::None => html! {},
IconKind::Font(_) => {
let aria_label = self.aria_label().lookup(cx);
let has_label = aria_label.is_some();
html! {
i
(self.props().unpack(cx))
role=[has_label.then_some("img")]
aria-label=[aria_label]
aria-hidden=[(!has_label).then_some("true")]
{}
}
}
IconKind::Svg { shapes, viewbox } => {
let aria_label = self.aria_label().lookup(cx);
let has_label = aria_label.is_some();
let viewbox = viewbox.get().unwrap_or_else(|| DEFAULT_VIEWBOX.to_string());
html! {
svg
xmlns="http://www.w3.org/2000/svg"
viewBox=(viewbox)
fill="currentColor"
focusable="false"
(self.props().unpack(cx))
role=[has_label.then_some("img")]
aria-label=[aria_label]
aria-hidden=[(!has_label).then_some("true")]
{
(shapes)
}
}
}
})
impl IconBsExt for Icon {
fn bi(name: impl AsRef<str>) -> Self {
Icon::with(Source::font(util::join!("bi bi-", name.as_ref())))
}
}
#[builder_impl]
impl Icon {
pub fn font() -> Self {
Self::default().with_icon_kind(IconKind::Font(FontSize::default()))
}
// **< Icon SETUP >*********************************************************************************
pub fn font_sized(font_size: FontSize) -> Self {
Self::default().with_icon_kind(IconKind::Font(font_size))
}
// Sustituye cada icono del conjunto de PageTop por su equivalente de Bootstrap Icons. El `setup()`
// del icono ya se ha ejecutado, así que las clases del glifo se añaden aquí; el origen cambia para
// que se pinte como glifo.
pub(crate) fn setup(icon: &mut Icon) {
let Some(&Source::Core(core)) = icon.source() else {
return;
};
let classes = bi_classes(core);
icon.alter_prop(PropsOp::add_classes(classes));
icon.alter_source(Source::font(classes));
}
pub fn svg(shapes: Markup) -> Self {
Self::default().with_icon_kind(IconKind::Svg {
shapes,
viewbox: AttrValue::default(),
})
}
pub fn svg_with_viewbox(shapes: Markup, viewbox: impl AsRef<str>) -> Self {
Self::default().with_icon_kind(IconKind::Svg {
shapes,
viewbox: AttrValue::new(viewbox),
})
}
// **< Icon BUILDER >***************************************************************************
/// Establece el identificador único del componente; igual a `with_prop(PropsOp::set_id(id))`.
pub fn with_id(mut self, id: impl Into<CowStr>) -> Self {
self.props.alter_id(id);
self
}
/// Modifica identificador, clases CSS, atributos HTML o valores extra del componente.
pub fn with_prop(mut self, op: impl Into<PropsOp>) -> Self {
self.props.alter_prop(op);
self
}
pub fn with_icon_kind(mut self, icon_kind: IconKind) -> Self {
self.icon_kind = icon_kind;
self
}
pub fn with_aria_label(mut self, label: Lc) -> Self {
self.aria_label.alter_value(label);
self
#[rustfmt::skip]
const fn bi_classes(icon: Core) -> &'static str {
match icon {
Core::BarChart => "bi bi-bar-chart",
Core::Check => "bi bi-check-lg",
Core::ChevronDown => "bi bi-chevron-down",
Core::ChevronLeft => "bi bi-chevron-left",
Core::ChevronRight => "bi bi-chevron-right",
Core::ChevronUp => "bi bi-chevron-up",
Core::Close => "bi bi-x-lg",
Core::Gear => "bi bi-gear",
Core::Home => "bi bi-house",
Core::Key => "bi bi-key",
Core::Layers => "bi bi-layers",
Core::Minus => "bi bi-dash-lg",
Core::People => "bi bi-people",
Core::Person => "bi bi-person",
Core::Plus => "bi bi-plus-lg",
Core::QuestionCircle => "bi bi-question-circle",
Core::Shield => "bi bi-shield-lock",
Core::SignOut => "bi bi-box-arrow-right",
Core::Sliders => "bi bi-sliders",
}
}

View file

@ -95,13 +95,15 @@ fn layout_class(layout: nav::Layout, classes: &mut String) {
// `data-bs-toggle="dropdown"` para que el JS de Bootstrap lo reconozca (la clase `dropdown-toggle`
// por sí sola sólo aporta el estilo, no la inicialización).
pub(crate) async fn item_render(item: &Item, cx: &mut Context) -> Result<Markup, ComponentError> {
let start = item.icon_start().render(cx).await;
let end = item.icon_end().render(cx).await;
Ok(match item.item_kind() {
ItemKind::Void => html! {},
ItemKind::Label(label) => html! {
li (item.props().unpack(cx)) {
span class="nav-link disabled" aria-disabled="true" {
(label.using(cx))
(start) (label.using(cx)) (end)
}
}
},
@ -144,7 +146,7 @@ pub(crate) async fn item_render(item: &Item, cx: &mut Context) -> Result<Markup,
aria-current=[aria_current]
aria-disabled=[aria_disabled]
{
(label.using(cx))
(start) (label.using(cx)) (end)
}
}
}
@ -182,7 +184,7 @@ pub(crate) async fn item_render(item: &Item, cx: &mut Context) -> Result<Markup,
aria-haspopup="true"
aria-expanded="false"
{
(title)
(start) (title) (end)
}
ul class=(menu_classes) {
(items)

View file

@ -0,0 +1,67 @@
use pagetop::prelude::*;
use pagetop_bootsier::theme::*;
#[pagetop::test]
async fn bi_creates_a_bootstrap_icons_glyph() {
let mut icon = bs::Icon::bi("house-fill");
let html = icon.render(&mut Context::default()).await.into_string();
assert!(html.starts_with("<i"));
assert!(html.contains(r#"class="icon bi bi-house-fill""#));
}
#[pagetop::test]
async fn bootsier_nav_item_renders_its_icons() {
let mut cx = Context::default().with_theme(&pagetop_bootsier::Bootsier);
let mut item = bs::nav::Item::link(Lc::n("Home"), "/")
.with_icon_start(bs::Icon::bi("house"))
.with_icon_end(bs::Icon::bi("box-arrow-up-right"));
let html = item.render(&mut cx).await.into_string();
let start = html.find("bi-house").unwrap();
let label = html.find("Home").unwrap();
let end = html.find("bi-box-arrow-up-right").unwrap();
assert!(start < label && label < end);
}
#[pagetop::test]
async fn bootsier_nav_dropdown_title_renders_its_icons() {
let mut cx = Context::default().with_theme(&pagetop_bootsier::Bootsier);
let mut item = bs::nav::Item::dropdown(
bs::Dropdown::new()
.with_title(Lc::n("More"))
.with_item(bs::dropdown::Item::link(Lc::n("One"), "/one")),
)
.with_icon_start(bs::Icon::bi("list"))
.with_icon_end(bs::Icon::bi("star"));
let html = item.render(&mut cx).await.into_string();
let start = html.find("bi-list").unwrap();
let title = html.find("More").unwrap();
let end = html.find("bi-star").unwrap();
assert!(start < title && title < end, "{html}");
}
#[pagetop::test]
async fn core_icons_are_shown_with_their_bootstrap_icons_glyph() {
let mut cx = Context::default().with_theme(&pagetop_bootsier::Bootsier);
let mut icon = Icon::with(icon::Core::Gear).with_intent(Intent::Primary);
let html = icon.render(&mut cx).await.into_string();
assert!(html.starts_with("<i"));
assert!(html.contains("bi bi-gear"));
assert!(html.contains("icon-primary"));
assert!(!html.contains("<svg"));
}
#[pagetop::test]
async fn core_icons_keep_the_icon_class_and_their_label_as_glyphs() {
let mut cx = Context::default().with_theme(&pagetop_bootsier::Bootsier);
let mut icon = Icon::with(icon::Core::Close).with_label(Lc::n("Close"));
let html = icon.render(&mut cx).await.into_string();
// The menu styles find the icons by the `icon` class.
assert!(html.contains(r#"class="icon bi bi-x-lg""#), "{html}");
assert!(html.contains(r#"role="img""#), "{html}");
assert!(html.contains(r#"aria-label="Close""#), "{html}");
}