✨ 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:
parent
d83f8b0f7f
commit
5d6852382a
23 changed files with 1098 additions and 161 deletions
|
|
@ -25,6 +25,7 @@
|
||||||
@use "basic/dialog";
|
@use "basic/dialog";
|
||||||
@use "basic/dropdown";
|
@use "basic/dropdown";
|
||||||
@use "basic/form";
|
@use "basic/form";
|
||||||
|
@use "basic/icon";
|
||||||
@use "basic/image";
|
@use "basic/image";
|
||||||
@use "basic/list-filter";
|
@use "basic/list-filter";
|
||||||
@use "basic/list-view";
|
@use "basic/list-view";
|
||||||
|
|
|
||||||
57
assets/scss/basic/_icon.scss
Normal file
57
assets/scss/basic/_icon.scss
Normal file
|
|
@ -0,0 +1,57 @@
|
||||||
|
// Inline SVG icons (`Icon`) sit on the text baseline like a glyph of the surrounding font.
|
||||||
|
svg.icon {
|
||||||
|
flex-shrink: 0;
|
||||||
|
vertical-align: -0.125em;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Color of an icon with an intent (`Icon::with_intent()`).
|
||||||
|
.icon-primary { color: var(--val-color--primary); }
|
||||||
|
.icon-neutral { color: var(--val-color--secondary); }
|
||||||
|
.icon-info { color: var(--val-color--info); }
|
||||||
|
.icon-success { color: var(--val-color--success); }
|
||||||
|
.icon-warning { color: var(--val-color--warning); }
|
||||||
|
.icon-severe { color: var(--val-color--danger); }
|
||||||
|
|
||||||
|
// 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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -226,6 +226,63 @@ fieldset > legend {
|
||||||
@extend .alert-danger;
|
@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 indicator on sortable table headers (`table::SortLink`), using Bootstrap Icons'
|
||||||
// sort-up/sort-down glyphs instead of the plain triangle from basic.css.
|
// sort-up/sort-down glyphs instead of the plain triangle from basic.css.
|
||||||
.table-sort::after {
|
.table-sort::after {
|
||||||
|
|
|
||||||
|
|
@ -283,6 +283,7 @@ impl Theme for Bootsier {
|
||||||
Container => |c| theme::bs::container::setup(c),
|
Container => |c| theme::bs::container::setup(c),
|
||||||
Dialog => |c| theme::bs::dialog::setup(c),
|
Dialog => |c| theme::bs::dialog::setup(c),
|
||||||
Dropdown => |c| theme::bs::dropdown::setup(c),
|
Dropdown => |c| theme::bs::dropdown::setup(c),
|
||||||
|
Icon => |c| theme::bs::icon::setup(c),
|
||||||
Image => |c| theme::bs::image::setup(c),
|
Image => |c| theme::bs::image::setup(c),
|
||||||
Nav => |c| theme::bs::nav::setup(c),
|
Nav => |c| theme::bs::nav::setup(c),
|
||||||
Navbar => |c| theme::bs::navbar::setup(c),
|
Navbar => |c| theme::bs::navbar::setup(c),
|
||||||
|
|
|
||||||
|
|
@ -82,6 +82,8 @@ pub use bs::form::select::SelectBsExt;
|
||||||
#[doc(hidden)]
|
#[doc(hidden)]
|
||||||
pub use bs::form::textarea::TextareaBsExt;
|
pub use bs::form::textarea::TextareaBsExt;
|
||||||
#[doc(hidden)]
|
#[doc(hidden)]
|
||||||
|
pub use bs::icon::IconBsExt;
|
||||||
|
#[doc(hidden)]
|
||||||
pub use bs::nav::NavBsExt;
|
pub use bs::nav::NavBsExt;
|
||||||
#[doc(hidden)]
|
#[doc(hidden)]
|
||||||
pub use bs::navbar::NavbarBsExt;
|
pub use bs::navbar::NavbarBsExt;
|
||||||
|
|
|
||||||
|
|
@ -50,6 +50,13 @@ pub use form::select::SelectBsExt;
|
||||||
#[doc(inline)]
|
#[doc(inline)]
|
||||||
pub use form::textarea::TextareaBsExt;
|
pub use form::textarea::TextareaBsExt;
|
||||||
|
|
||||||
|
// Icon.
|
||||||
|
pub mod icon;
|
||||||
|
#[doc(inline)]
|
||||||
|
pub use icon::Icon;
|
||||||
|
#[doc(inline)]
|
||||||
|
pub use icon::IconBsExt;
|
||||||
|
|
||||||
// Image.
|
// Image.
|
||||||
pub mod image;
|
pub mod image;
|
||||||
#[doc(inline)]
|
#[doc(inline)]
|
||||||
|
|
|
||||||
|
|
@ -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 use pagetop::base::component::icon::{Core, Icon, Source};
|
||||||
pub enum IconKind {
|
|
||||||
#[default]
|
/// Extensión de Bootsier para [`Icon`].
|
||||||
None,
|
///
|
||||||
Font(FontSize),
|
/// Añade los iconos de [Bootstrap Icons](https://icons.getbootstrap.com/), que Bootsier ya carga
|
||||||
Svg {
|
/// como fuente de iconos en todas las páginas. Además, Bootsier muestra los iconos del conjunto de
|
||||||
shapes: Markup,
|
/// PageTop ([`Core`]) con su equivalente de Bootstrap Icons.
|
||||||
viewbox: AttrValue,
|
///
|
||||||
},
|
/// ```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)]
|
impl IconBsExt for Icon {
|
||||||
pub struct Icon {
|
fn bi(name: impl AsRef<str>) -> Self {
|
||||||
/// Devuelve identificador, clases CSS, atributos HTML y valores extra del componente.
|
Icon::with(Source::font(util::join!("bi bi-", name.as_ref())))
|
||||||
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> {
|
// **< Icon SETUP >*********************************************************************************
|
||||||
Ok(match self.icon_kind() {
|
|
||||||
IconKind::None => html! {},
|
// Sustituye cada icono del conjunto de PageTop por su equivalente de Bootstrap Icons. El `setup()`
|
||||||
IconKind::Font(_) => {
|
// del icono ya se ha ejecutado, así que las clases del glifo se añaden aquí; el origen cambia para
|
||||||
let aria_label = self.aria_label().lookup(cx);
|
// que se pinte como glifo.
|
||||||
let has_label = aria_label.is_some();
|
pub(crate) fn setup(icon: &mut Icon) {
|
||||||
html! {
|
let Some(&Source::Core(core)) = icon.source() else {
|
||||||
i
|
return;
|
||||||
(self.props().unpack(cx))
|
};
|
||||||
role=[has_label.then_some("img")]
|
let classes = bi_classes(core);
|
||||||
aria-label=[aria_label]
|
icon.alter_prop(PropsOp::add_classes(classes));
|
||||||
aria-hidden=[(!has_label).then_some("true")]
|
icon.alter_source(Source::font(classes));
|
||||||
{}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
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)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[builder_impl]
|
#[rustfmt::skip]
|
||||||
impl Icon {
|
const fn bi_classes(icon: Core) -> &'static str {
|
||||||
pub fn font() -> Self {
|
match icon {
|
||||||
Self::default().with_icon_kind(IconKind::Font(FontSize::default()))
|
Core::BarChart => "bi bi-bar-chart",
|
||||||
}
|
Core::Check => "bi bi-check-lg",
|
||||||
|
Core::ChevronDown => "bi bi-chevron-down",
|
||||||
pub fn font_sized(font_size: FontSize) -> Self {
|
Core::ChevronLeft => "bi bi-chevron-left",
|
||||||
Self::default().with_icon_kind(IconKind::Font(font_size))
|
Core::ChevronRight => "bi bi-chevron-right",
|
||||||
}
|
Core::ChevronUp => "bi bi-chevron-up",
|
||||||
|
Core::Close => "bi bi-x-lg",
|
||||||
pub fn svg(shapes: Markup) -> Self {
|
Core::Gear => "bi bi-gear",
|
||||||
Self::default().with_icon_kind(IconKind::Svg {
|
Core::Home => "bi bi-house",
|
||||||
shapes,
|
Core::Key => "bi bi-key",
|
||||||
viewbox: AttrValue::default(),
|
Core::Layers => "bi bi-layers",
|
||||||
})
|
Core::Minus => "bi bi-dash-lg",
|
||||||
}
|
Core::People => "bi bi-people",
|
||||||
|
Core::Person => "bi bi-person",
|
||||||
pub fn svg_with_viewbox(shapes: Markup, viewbox: impl AsRef<str>) -> Self {
|
Core::Plus => "bi bi-plus-lg",
|
||||||
Self::default().with_icon_kind(IconKind::Svg {
|
Core::QuestionCircle => "bi bi-question-circle",
|
||||||
shapes,
|
Core::Shield => "bi bi-shield-lock",
|
||||||
viewbox: AttrValue::new(viewbox),
|
Core::SignOut => "bi bi-box-arrow-right",
|
||||||
})
|
Core::Sliders => "bi bi-sliders",
|
||||||
}
|
|
||||||
|
|
||||||
// **< 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
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -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`
|
// `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).
|
// 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> {
|
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() {
|
Ok(match item.item_kind() {
|
||||||
ItemKind::Void => html! {},
|
ItemKind::Void => html! {},
|
||||||
|
|
||||||
ItemKind::Label(label) => html! {
|
ItemKind::Label(label) => html! {
|
||||||
li (item.props().unpack(cx)) {
|
li (item.props().unpack(cx)) {
|
||||||
span class="nav-link disabled" aria-disabled="true" {
|
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-current=[aria_current]
|
||||||
aria-disabled=[aria_disabled]
|
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-haspopup="true"
|
||||||
aria-expanded="false"
|
aria-expanded="false"
|
||||||
{
|
{
|
||||||
(title)
|
(start) (title) (end)
|
||||||
}
|
}
|
||||||
ul class=(menu_classes) {
|
ul class=(menu_classes) {
|
||||||
(items)
|
(items)
|
||||||
|
|
|
||||||
67
extensions/pagetop-bootsier/tests/icon.rs
Normal file
67
extensions/pagetop-bootsier/tests/icon.rs
Normal 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}");
|
||||||
|
}
|
||||||
|
|
@ -37,19 +37,20 @@ pub fn account_menu(cx: &Context) -> Nav {
|
||||||
// El cierre de sesión requiere POST; el atributo `hx-post` viaja en el `<li>` del elemento
|
// El cierre de sesión requiere POST; el atributo `hx-post` viaja en el `<li>` del elemento
|
||||||
// (ver `logout_post`, que responde con `HX-Redirect` a las peticiones htmx).
|
// (ver `logout_post`, que responde con `HX-Redirect` a las peticiones htmx).
|
||||||
let logout = dropdown::Item::button(Lc::t("btn-logout", &LOCALES_USER))
|
let logout = dropdown::Item::button(Lc::t("btn-logout", &LOCALES_USER))
|
||||||
|
.with_icon_start(Icon::with(icon::Core::SignOut))
|
||||||
.with_prop(PropsOp::set(hx::POST, cx.route(LOGOUT_PATH).to_string()));
|
.with_prop(PropsOp::set(hx::POST, cx.route(LOGOUT_PATH).to_string()));
|
||||||
let mut menu = Dropdown::new()
|
let mut menu = Dropdown::new()
|
||||||
.with_title(title)
|
.with_title(title)
|
||||||
.with_menu_end(true)
|
.with_menu_end(true)
|
||||||
.with_item(dropdown::Item::link(
|
.with_item(
|
||||||
Lc::t("menu-profile", &LOCALES_USER),
|
dropdown::Item::link(Lc::t("menu-profile", &LOCALES_USER), cx.route(PROFILE_PATH))
|
||||||
cx.route(PROFILE_PATH),
|
.with_icon_start(Icon::with(icon::Core::Person)),
|
||||||
));
|
);
|
||||||
if can_access_admin(cx) {
|
if can_access_admin(cx) {
|
||||||
menu = menu.with_item(dropdown::Item::link(
|
menu = menu.with_item(
|
||||||
Lc::t("menu-admin", &LOCALES_USER),
|
dropdown::Item::link(Lc::t("menu-admin", &LOCALES_USER), cx.route(admin_path("")))
|
||||||
cx.route(admin_path("")),
|
.with_icon_start(Icon::with(icon::Core::Gear)),
|
||||||
));
|
);
|
||||||
}
|
}
|
||||||
nav.with_item(nav::Item::dropdown(
|
nav.with_item(nav::Item::dropdown(
|
||||||
menu.with_item(dropdown::Item::divider()).with_item(logout),
|
menu.with_item(dropdown::Item::divider()).with_item(logout),
|
||||||
|
|
|
||||||
|
|
@ -343,7 +343,8 @@ fn declare_admin_pages(bag: &mut AdminPageBag) {
|
||||||
Lc::t("title-admin-users", &LOCALES_USER),
|
Lc::t("title-admin-users", &LOCALES_USER),
|
||||||
&permission::UserPermission::AdminUsers,
|
&permission::UserPermission::AdminUsers,
|
||||||
)
|
)
|
||||||
.with_description(Lc::t("description-admin-users", &LOCALES_USER)),
|
.with_description(Lc::t("description-admin-users", &LOCALES_USER))
|
||||||
|
.with_icon(Icon::with(icon::Core::Person)),
|
||||||
);
|
);
|
||||||
bag.add(
|
bag.add(
|
||||||
AdminPage::new(
|
AdminPage::new(
|
||||||
|
|
@ -353,7 +354,8 @@ fn declare_admin_pages(bag: &mut AdminPageBag) {
|
||||||
&permission::UserPermission::AdminRoles,
|
&permission::UserPermission::AdminRoles,
|
||||||
)
|
)
|
||||||
.with_description(Lc::t("description-admin-roles", &LOCALES_USER))
|
.with_description(Lc::t("description-admin-roles", &LOCALES_USER))
|
||||||
.with_weight(10),
|
.with_weight(10)
|
||||||
|
.with_icon(Icon::with(icon::Core::Shield)),
|
||||||
);
|
);
|
||||||
bag.add(
|
bag.add(
|
||||||
AdminPage::new(
|
AdminPage::new(
|
||||||
|
|
@ -363,7 +365,8 @@ fn declare_admin_pages(bag: &mut AdminPageBag) {
|
||||||
&permission::UserPermission::AdminPermissions,
|
&permission::UserPermission::AdminPermissions,
|
||||||
)
|
)
|
||||||
.with_description(Lc::t("description-admin-permissions", &LOCALES_USER))
|
.with_description(Lc::t("description-admin-permissions", &LOCALES_USER))
|
||||||
.with_weight(20),
|
.with_weight(20)
|
||||||
|
.with_icon(Icon::with(icon::Core::Key)),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -2,6 +2,7 @@ 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::base::component::{Icon, icon};
|
||||||
use crate::core::component::{Context, Contextual};
|
use crate::core::component::{Context, Contextual};
|
||||||
use crate::locale::Lc;
|
use crate::locale::Lc;
|
||||||
use crate::{Getters, Weight, builder_impl, trace, util};
|
use crate::{Getters, Weight, builder_impl, trace, util};
|
||||||
|
|
@ -36,6 +37,8 @@ pub struct AdminSection {
|
||||||
/// Devuelve el peso para ordenar las secciones (menor = antes).
|
/// Devuelve el peso para ordenar las secciones (menor = antes).
|
||||||
#[getters(copy)]
|
#[getters(copy)]
|
||||||
weight: Weight,
|
weight: Weight,
|
||||||
|
/// Devuelve el icono que acompaña al título en la navegación (si lo tiene).
|
||||||
|
icon: Option<Icon>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[builder_impl]
|
#[builder_impl]
|
||||||
|
|
@ -48,6 +51,7 @@ impl AdminSection {
|
||||||
key,
|
key,
|
||||||
title,
|
title,
|
||||||
weight: 0,
|
weight: 0,
|
||||||
|
icon: None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -70,6 +74,13 @@ impl AdminSection {
|
||||||
self.weight = weight;
|
self.weight = weight;
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Asigna o quita el icono que acompaña al título de la sección en la navegación del panel
|
||||||
|
/// ([`Nav::admin()`](crate::base::component::Nav::admin)).
|
||||||
|
pub fn with_icon(mut self, icon: impl Into<Option<Icon>>) -> Self {
|
||||||
|
self.icon = icon.into();
|
||||||
|
self
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// **< AdminPage >**********************************************************************************
|
// **< AdminPage >**********************************************************************************
|
||||||
|
|
@ -104,6 +115,8 @@ pub struct AdminPage {
|
||||||
/// ([`Routes::admin_route()`](crate::web::Routes::admin_route)).
|
/// ([`Routes::admin_route()`](crate::web::Routes::admin_route)).
|
||||||
#[getters(copy)]
|
#[getters(copy)]
|
||||||
permission: PermissionRef,
|
permission: PermissionRef,
|
||||||
|
/// Devuelve el icono que acompaña al título en la navegación (si lo tiene).
|
||||||
|
icon: Option<Icon>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[builder_impl]
|
#[builder_impl]
|
||||||
|
|
@ -126,6 +139,7 @@ impl AdminPage {
|
||||||
description: Lc::none(),
|
description: Lc::none(),
|
||||||
weight: 0,
|
weight: 0,
|
||||||
permission,
|
permission,
|
||||||
|
icon: None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -149,6 +163,16 @@ impl AdminPage {
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Asigna o quita el icono que acompaña al título de la página en la navegación del panel
|
||||||
|
/// ([`Nav::admin()`](crate::base::component::Nav::admin)).
|
||||||
|
///
|
||||||
|
/// Con un icono del conjunto de PageTop ([`icon::Core`](crate::base::component::icon::Core)),
|
||||||
|
/// la extensión no depende de ningún tema y cada tema puede mostrar el equivalente del suyo.
|
||||||
|
pub fn with_icon(mut self, icon: impl Into<Option<Icon>>) -> Self {
|
||||||
|
self.icon = icon.into();
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
// **< AdminPage GETTERS >**********************************************************************
|
// **< 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.
|
||||||
|
|
@ -605,15 +629,21 @@ fn relative(path: String) -> String {
|
||||||
|
|
||||||
// Secciones habituales del panel, declaradas antes que las de las extensiones.
|
// Secciones habituales del panel, declaradas antes que las de las extensiones.
|
||||||
fn default_sections() -> Vec<AdminSection> {
|
fn default_sections() -> Vec<AdminSection> {
|
||||||
[
|
#[rustfmt::skip]
|
||||||
("people", "admin_section_people", 10),
|
let sections = [
|
||||||
("structure", "admin_section_structure", 20),
|
("people", "admin_section_people", 10, icon::Core::People),
|
||||||
("config", "admin_section_config", 30),
|
("structure", "admin_section_structure", 20, icon::Core::Layers),
|
||||||
("reports", "admin_section_reports", 40),
|
("config", "admin_section_config", 30, icon::Core::Sliders),
|
||||||
("help", "admin_section_help", 50),
|
("reports", "admin_section_reports", 40, icon::Core::BarChart),
|
||||||
]
|
("help", "admin_section_help", 50, icon::Core::QuestionCircle),
|
||||||
|
];
|
||||||
|
sections
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.map(|(key, title, weight)| AdminSection::new(key, Lc::l(title)).with_weight(weight))
|
.map(|(key, title, weight, icon)| {
|
||||||
|
AdminSection::new(key, Lc::l(title))
|
||||||
|
.with_weight(weight)
|
||||||
|
.with_icon(Icon::with(icon))
|
||||||
|
})
|
||||||
.collect()
|
.collect()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -43,6 +43,10 @@ pub use grid::Grid;
|
||||||
mod html;
|
mod html;
|
||||||
pub use html::Html;
|
pub use html::Html;
|
||||||
|
|
||||||
|
pub mod icon;
|
||||||
|
#[doc(inline)]
|
||||||
|
pub use icon::Icon;
|
||||||
|
|
||||||
pub mod image;
|
pub mod image;
|
||||||
#[doc(inline)]
|
#[doc(inline)]
|
||||||
pub use image::Image;
|
pub use image::Image;
|
||||||
|
|
|
||||||
|
|
@ -25,6 +25,12 @@ use crate::prelude::*;
|
||||||
/// let cancel = Button::plain(Lc::n("Cancel"));
|
/// let cancel = Button::plain(Lc::n("Cancel"));
|
||||||
/// let clear = Button::reset(Lc::n("Clear"));
|
/// let clear = Button::reset(Lc::n("Clear"));
|
||||||
/// let edit = Button::anchor(Lc::n("Edit"), "/items/1/edit");
|
/// let edit = Button::anchor(Lc::n("Edit"), "/items/1/edit");
|
||||||
|
///
|
||||||
|
/// // Con un icono al principio o al final de la etiqueta, o sólo con el icono.
|
||||||
|
/// let add = Button::plain(Lc::n("Add")).with_icon_start(Icon::with(icon::Core::Plus));
|
||||||
|
/// let next = Button::plain(Lc::n("Next")).with_icon_end(Icon::with(icon::Core::ChevronRight));
|
||||||
|
/// let close = Button::plain(Lc::none())
|
||||||
|
/// .with_icon_start(Icon::with(icon::Core::Close).with_label(Lc::n("Close")));
|
||||||
/// ```
|
/// ```
|
||||||
///
|
///
|
||||||
/// Cuando el botón activa el envío, el navegador incluye el par `name=value` en los datos del
|
/// Cuando el botón activa el envío, el navegador incluye el par `name=value` en los datos del
|
||||||
|
|
@ -56,6 +62,10 @@ pub struct Button {
|
||||||
value: AttrValue,
|
value: AttrValue,
|
||||||
/// Devuelve la etiqueta del botón.
|
/// Devuelve la etiqueta del botón.
|
||||||
label: Lc,
|
label: Lc,
|
||||||
|
/// Devuelve el icono al principio del botón, antes de la etiqueta (si lo hay).
|
||||||
|
icon_start: Embed<Icon>,
|
||||||
|
/// Devuelve el icono al final del botón, después de la etiqueta (si lo hay).
|
||||||
|
icon_end: Embed<Icon>,
|
||||||
/// Devuelve el texto emergente del botón (atributo `title`).
|
/// Devuelve el texto emergente del botón (atributo `title`).
|
||||||
title: Lc,
|
title: Lc,
|
||||||
/// Devuelve la ruta de destino cuando el botón se renderiza como enlace de navegación
|
/// Devuelve la ruta de destino cuando el botón se renderiza como enlace de navegación
|
||||||
|
|
@ -105,6 +115,27 @@ impl Component for Button {
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn prepare(&self, cx: &mut Context) -> Result<Markup, ComponentError> {
|
async fn prepare(&self, cx: &mut Context) -> Result<Markup, ComponentError> {
|
||||||
|
// Sin iconos, el contenido es la etiqueta tal cual. Con alguno, un espacio separa cada
|
||||||
|
// pieza de la siguiente, sólo si las dos tienen contenido.
|
||||||
|
let label = self.label().using(cx);
|
||||||
|
let content = if self.icon_start().get().is_none() && self.icon_end().get().is_none() {
|
||||||
|
label
|
||||||
|
} else {
|
||||||
|
let start = self.icon_start().render(cx).await;
|
||||||
|
let end = self.icon_end().render(cx).await;
|
||||||
|
html! {
|
||||||
|
(start)
|
||||||
|
@if !start.is_empty() && (!label.is_empty() || !end.is_empty()) {
|
||||||
|
(" ")
|
||||||
|
}
|
||||||
|
(label)
|
||||||
|
@if !label.is_empty() && !end.is_empty() {
|
||||||
|
(" ")
|
||||||
|
}
|
||||||
|
(end)
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
if let Some(route) = self.href().try_resolve(cx) {
|
if let Some(route) = self.href().try_resolve(cx) {
|
||||||
let disabled = *self.disabled();
|
let disabled = *self.disabled();
|
||||||
let href = (!disabled).then_some(route);
|
let href = (!disabled).then_some(route);
|
||||||
|
|
@ -120,7 +151,7 @@ impl Component for Button {
|
||||||
aria-disabled=[aria_disabled]
|
aria-disabled=[aria_disabled]
|
||||||
tabindex=[tabindex]
|
tabindex=[tabindex]
|
||||||
{
|
{
|
||||||
(self.label().using(cx))
|
(content)
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
@ -135,7 +166,7 @@ impl Component for Button {
|
||||||
autofocus[*self.autofocus()]
|
autofocus[*self.autofocus()]
|
||||||
disabled[*self.disabled()]
|
disabled[*self.disabled()]
|
||||||
{
|
{
|
||||||
(self.label().using(cx))
|
(content)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
@ -252,6 +283,26 @@ impl Button {
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Asigna o quita el icono al principio del botón, antes de la etiqueta. Si se pasa `None`, no
|
||||||
|
/// se mostrará.
|
||||||
|
///
|
||||||
|
/// *Principio* y *final* siguen el sentido de la escritura: en un idioma que se escribe de
|
||||||
|
/// derecha a izquierda, el principio queda a la derecha.
|
||||||
|
///
|
||||||
|
/// Un botón sólo con icono (etiqueta [`Lc::none()`]) necesita un nombre accesible: se lo da la
|
||||||
|
/// etiqueta del propio icono ([`Icon::with_label()`]).
|
||||||
|
pub fn with_icon_start(mut self, icon: impl Into<Option<Icon>>) -> Self {
|
||||||
|
self.icon_start.alter_component(icon);
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Asigna o quita el icono al final del botón, después de la etiqueta. Si se pasa `None`, no se
|
||||||
|
/// mostrará. Ver [`with_icon_start()`](Self::with_icon_start).
|
||||||
|
pub fn with_icon_end(mut self, icon: impl Into<Option<Icon>>) -> Self {
|
||||||
|
self.icon_end.alter_component(icon);
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
/// Establece el texto emergente del botón (usa [`Lc::none()`] para quitarlo).
|
/// Establece el texto emergente del botón (usa [`Lc::none()`] para quitarlo).
|
||||||
pub fn with_title(mut self, title: Lc) -> Self {
|
pub fn with_title(mut self, title: Lc) -> Self {
|
||||||
self.title = title;
|
self.title = title;
|
||||||
|
|
|
||||||
|
|
@ -41,6 +41,9 @@ pub enum ItemKind {
|
||||||
/// Permite definir el identificador, las clases de estilo adicionales y el tipo de interacción
|
/// Permite definir el identificador, las clases de estilo adicionales y el tipo de interacción
|
||||||
/// asociada, manteniendo una interfaz común para renderizar todos los elementos del menú.
|
/// asociada, manteniendo una interfaz común para renderizar todos los elementos del menú.
|
||||||
///
|
///
|
||||||
|
/// Las etiquetas, los enlaces y los botones pueden llevar un icono al principio y otro al final
|
||||||
|
/// ([`with_icon_start()`](Self::with_icon_start) y [`with_icon_end()`](Self::with_icon_end)).
|
||||||
|
///
|
||||||
/// Un enlace no se renderiza si el usuario actual no puede acceder a su ruta (ver [`Endpoint`]).
|
/// Un enlace no se renderiza si el usuario actual no puede acceder a su ruta (ver [`Endpoint`]).
|
||||||
/// Tampoco se muestra un encabezado si su grupo no tiene ningún elemento visible, ni un separador
|
/// 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)).
|
/// que no quede entre elementos visibles (ver [`dropdown::Items`](super::Items)).
|
||||||
|
|
@ -50,6 +53,10 @@ pub struct Item {
|
||||||
props: Props,
|
props: Props,
|
||||||
/// Devuelve el tipo de elemento representado.
|
/// Devuelve el tipo de elemento representado.
|
||||||
item_kind: ItemKind,
|
item_kind: ItemKind,
|
||||||
|
/// Devuelve el icono al principio del elemento, antes de la etiqueta (si lo hay).
|
||||||
|
icon_start: Embed<Icon>,
|
||||||
|
/// Devuelve el icono al final del elemento, después de la etiqueta (si lo hay).
|
||||||
|
icon_end: Embed<Icon>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
|
|
@ -70,13 +77,15 @@ impl Component for Item {
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn prepare(&self, cx: &mut Context) -> Result<Markup, ComponentError> {
|
async fn prepare(&self, cx: &mut Context) -> Result<Markup, ComponentError> {
|
||||||
|
let start = self.icon_start().render(cx).await;
|
||||||
|
let end = self.icon_end().render(cx).await;
|
||||||
Ok(match self.item_kind() {
|
Ok(match self.item_kind() {
|
||||||
ItemKind::Void => html! {},
|
ItemKind::Void => html! {},
|
||||||
|
|
||||||
ItemKind::Label(label) => html! {
|
ItemKind::Label(label) => html! {
|
||||||
li (self.props().unpack(cx)) {
|
li (self.props().unpack(cx)) {
|
||||||
span class="dropdown-item-text" {
|
span class="dropdown-item-text" {
|
||||||
(label.using(cx))
|
(start) (label.using(cx)) (end)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|
@ -118,7 +127,7 @@ impl Component for Item {
|
||||||
aria-disabled=[aria_disabled]
|
aria-disabled=[aria_disabled]
|
||||||
tabindex=[tabindex]
|
tabindex=[tabindex]
|
||||||
{
|
{
|
||||||
(label.using(cx))
|
(start) (label.using(cx)) (end)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -141,7 +150,7 @@ impl Component for Item {
|
||||||
aria-disabled=[aria_disabled]
|
aria-disabled=[aria_disabled]
|
||||||
disabled=[disabled_attr]
|
disabled=[disabled_attr]
|
||||||
{
|
{
|
||||||
(label.using(cx))
|
(start) (label.using(cx)) (end)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -279,4 +288,30 @@ impl Item {
|
||||||
self.props.alter_prop(op);
|
self.props.alter_prop(op);
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Asigna o quita el icono al principio del elemento, antes de la etiqueta. Si se pasa `None`,
|
||||||
|
/// no se mostrará.
|
||||||
|
///
|
||||||
|
/// *Principio* y *final* siguen el sentido de la escritura. Se aplica a las etiquetas, los
|
||||||
|
/// enlaces y los botones. El icono lleva la clase `icon-start` (`icon-end` el del final) para
|
||||||
|
/// que cada tema lo coloque. Basic deja ese hueco libre en los elementos sin icono, para que
|
||||||
|
/// todas las etiquetas del menú queden alineadas.
|
||||||
|
pub fn with_icon_start(mut self, icon: impl Into<Option<Icon>>) -> Self {
|
||||||
|
let icon = icon
|
||||||
|
.into()
|
||||||
|
.map(|icon| icon.with_prop(PropsOp::add_classes("icon-start")));
|
||||||
|
self.icon_start.alter_component(icon);
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Asigna o quita el icono al final del elemento, después de la etiqueta. Si se pasa `None`, no
|
||||||
|
/// se mostrará. Basic lo lleva junto al borde del menú. Ver
|
||||||
|
/// [`with_icon_start()`](Self::with_icon_start).
|
||||||
|
pub fn with_icon_end(mut self, icon: impl Into<Option<Icon>>) -> Self {
|
||||||
|
let icon = icon
|
||||||
|
.into()
|
||||||
|
.map(|icon| icon.with_prop(PropsOp::add_classes("icon-end")));
|
||||||
|
self.icon_end.alter_component(icon);
|
||||||
|
self
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
14
src/base/component/icon.rs
Normal file
14
src/base/component/icon.rs
Normal file
|
|
@ -0,0 +1,14 @@
|
||||||
|
//! Definiciones para mostrar iconos ([`Icon`]).
|
||||||
|
//!
|
||||||
|
//! Un icono se construye a partir de un [`icon::Source`](Source): un SVG en línea, un icono del
|
||||||
|
//! pequeño conjunto que incluye PageTop ([`icon::Core`](Core)) o un glifo de una fuente de iconos.
|
||||||
|
//! Cualquier otro conjunto se integra implementando `From<T> for icon::Source` para su propio tipo.
|
||||||
|
|
||||||
|
mod source;
|
||||||
|
pub use source::Source;
|
||||||
|
|
||||||
|
mod core_set;
|
||||||
|
pub use core_set::Core;
|
||||||
|
|
||||||
|
mod component;
|
||||||
|
pub use component::Icon;
|
||||||
161
src/base/component/icon/component.rs
Normal file
161
src/base/component/icon/component.rs
Normal file
|
|
@ -0,0 +1,161 @@
|
||||||
|
use crate::prelude::*;
|
||||||
|
|
||||||
|
/// Componente para mostrar un **icono**.
|
||||||
|
///
|
||||||
|
/// El icono se define con un [`icon::Source`]: un SVG en línea, un icono del conjunto de PageTop
|
||||||
|
/// ([`icon::Core`]) o un glifo de una fuente de iconos. Acepta también cualquier tipo convertible
|
||||||
|
/// en él. Sin origen no se renderiza nada.
|
||||||
|
///
|
||||||
|
/// El icono mide `1em`, así que toma el tamaño de la fuente del texto que lo rodea; se puede
|
||||||
|
/// cambiar con [`with_size()`](Self::with_size). Toma el color del texto, salvo que se le asigne
|
||||||
|
/// una intención ([`with_intent()`](Self::with_intent)). Siempre se le añade la clase `icon`.
|
||||||
|
///
|
||||||
|
/// Sin etiqueta el icono es **decorativo** (`aria-hidden="true"`); con una etiqueta que resuelva a
|
||||||
|
/// texto ([`with_label()`](Self::with_label)) se anuncia como imagen (`role="img"` y `aria-label`).
|
||||||
|
///
|
||||||
|
/// # Ejemplo
|
||||||
|
///
|
||||||
|
/// ```rust,no_run
|
||||||
|
/// use pagetop::prelude::*;
|
||||||
|
///
|
||||||
|
/// let close = Icon::with(icon::Core::Close).with_label(Lc::n("Close"));
|
||||||
|
///
|
||||||
|
/// let big = Icon::with(icon::Core::Check)
|
||||||
|
/// .with_size(UnitValue::RelRem(2.0))
|
||||||
|
/// .with_intent(Intent::Success);
|
||||||
|
/// ```
|
||||||
|
#[derive(AutoDefault, Clone, Debug, Getters)]
|
||||||
|
pub struct Icon {
|
||||||
|
/// Devuelve identificador, clases CSS, atributos HTML y valores extra del componente.
|
||||||
|
props: Props,
|
||||||
|
/// Devuelve el origen del icono, si lo tiene.
|
||||||
|
source: Option<icon::Source>,
|
||||||
|
/// Devuelve el tamaño del icono.
|
||||||
|
#[getters(copy)]
|
||||||
|
size: UnitValue,
|
||||||
|
/// Devuelve la intención semántica que da color al icono (si la tiene).
|
||||||
|
#[getters(copy)]
|
||||||
|
intent: Option<Intent>,
|
||||||
|
/// Devuelve la etiqueta de accesibilidad del icono.
|
||||||
|
label: Lc,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[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) {
|
||||||
|
match self.source() {
|
||||||
|
None => return,
|
||||||
|
Some(icon::Source::Svg { .. } | icon::Source::Core(_)) => {
|
||||||
|
self.alter_prop(PropsOp::prepend_classes("icon"))
|
||||||
|
}
|
||||||
|
Some(icon::Source::Font(classes)) => {
|
||||||
|
let classes = util::join!("icon ", classes.as_ref());
|
||||||
|
self.alter_prop(PropsOp::prepend_classes(classes))
|
||||||
|
}
|
||||||
|
};
|
||||||
|
if let Some(intent) = self.intent() {
|
||||||
|
self.alter_prop(PropsOp::add_classes(util::join!("icon-", intent.color(cx))));
|
||||||
|
}
|
||||||
|
if self.size() != UnitValue::None {
|
||||||
|
let size = self.size().to_string();
|
||||||
|
self.alter_prop(PropsOp::add_style("font-size", size));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn prepare(&self, cx: &mut Context) -> Result<Markup, ComponentError> {
|
||||||
|
let Some(source) = self.source() else {
|
||||||
|
return Ok(html! {});
|
||||||
|
};
|
||||||
|
// Una etiqueta en blanco no da nombre al icono: se trata como decorativo.
|
||||||
|
let label = self
|
||||||
|
.label()
|
||||||
|
.lookup(cx)
|
||||||
|
.filter(|label| !label.trim().is_empty());
|
||||||
|
let has_label = label.is_some();
|
||||||
|
let (viewbox, shapes) = match source {
|
||||||
|
icon::Source::Svg { viewbox, shapes } => (viewbox.as_ref(), shapes.0.as_str()),
|
||||||
|
icon::Source::Core(icon) => ("0 0 16 16", icon.svg()),
|
||||||
|
icon::Source::Font(_) => {
|
||||||
|
return Ok(html! {
|
||||||
|
i
|
||||||
|
role=[has_label.then_some("img")]
|
||||||
|
aria-label=[label]
|
||||||
|
aria-hidden=[(!has_label).then_some("true")]
|
||||||
|
(self.props().unpack(cx)) {}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
Ok(html! {
|
||||||
|
svg
|
||||||
|
xmlns="http://www.w3.org/2000/svg"
|
||||||
|
viewBox=(viewbox)
|
||||||
|
width="1em"
|
||||||
|
height="1em"
|
||||||
|
fill="currentColor"
|
||||||
|
focusable="false"
|
||||||
|
role=[has_label.then_some("img")]
|
||||||
|
aria-label=[label]
|
||||||
|
aria-hidden=[(!has_label).then_some("true")]
|
||||||
|
(self.props().unpack(cx))
|
||||||
|
{
|
||||||
|
(PreEscaped(shapes))
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[builder_impl]
|
||||||
|
impl Icon {
|
||||||
|
/// Crea un icono a partir de su origen, o de cualquier tipo convertible en él.
|
||||||
|
pub fn with(source: impl Into<icon::Source>) -> Self {
|
||||||
|
Self::default().with_source(source.into())
|
||||||
|
}
|
||||||
|
|
||||||
|
// **< 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
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Asigna o quita el origen del icono. Con `None` no se renderiza.
|
||||||
|
pub fn with_source(mut self, source: impl Into<Option<icon::Source>>) -> Self {
|
||||||
|
self.source = source.into();
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Establece el tamaño del icono como tamaño de fuente (`font-size`). Con
|
||||||
|
/// [`UnitValue::None`] toma el del texto que lo rodea.
|
||||||
|
pub fn with_size(mut self, size: UnitValue) -> Self {
|
||||||
|
self.size = size;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Asigna o quita la intención semántica que da color al icono. Añade la clase `icon-*` con el
|
||||||
|
/// color que el tema activo asocia a la intención; sin intención, toma el color del texto.
|
||||||
|
pub fn with_intent(mut self, intent: impl Into<Option<Intent>>) -> Self {
|
||||||
|
self.intent = intent.into();
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Establece la etiqueta de accesibilidad del icono. Con [`Lc::none()`] el icono es decorativo.
|
||||||
|
pub fn with_label(mut self, label: Lc) -> Self {
|
||||||
|
self.label = label;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
}
|
||||||
140
src/base/component/icon/core_set.rs
Normal file
140
src/base/component/icon/core_set.rs
Normal file
|
|
@ -0,0 +1,140 @@
|
||||||
|
use crate::prelude::*;
|
||||||
|
|
||||||
|
/// Pequeño conjunto de **iconos SVG** incluido en PageTop.
|
||||||
|
///
|
||||||
|
/// Son iconos de trazo sencillos, sin dependencias ni recursos externos, que funcionan con
|
||||||
|
/// cualquier tema. Incluye los que usa el panel de administración y otros de uso general, y sirve
|
||||||
|
/// de ejemplo de cómo integrar un conjunto de iconos (ver [`icon::Source`](super::Source)).
|
||||||
|
///
|
||||||
|
/// Como el icono conserva su identidad hasta el renderizado ([`icon::Source::Core`]), un tema puede
|
||||||
|
/// sustituirlo por el equivalente de su propio conjunto. Así una extensión puede usarlos sin
|
||||||
|
/// depender de ningún tema, y verlos con el aspecto del que esté activo.
|
||||||
|
///
|
||||||
|
/// [`icon::Source::Core`]: super::Source::Core
|
||||||
|
///
|
||||||
|
/// # Ejemplo
|
||||||
|
///
|
||||||
|
/// ```rust,no_run
|
||||||
|
/// # use pagetop::prelude::*;
|
||||||
|
/// let check = Icon::with(icon::Core::Check).with_label(Lc::n("Done"));
|
||||||
|
/// ```
|
||||||
|
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||||
|
pub enum Core {
|
||||||
|
/// Gráfico de barras, para informes.
|
||||||
|
BarChart,
|
||||||
|
/// Marca de verificación.
|
||||||
|
Check,
|
||||||
|
/// Flecha angular hacia abajo.
|
||||||
|
ChevronDown,
|
||||||
|
/// Flecha angular hacia la izquierda.
|
||||||
|
ChevronLeft,
|
||||||
|
/// Flecha angular hacia la derecha.
|
||||||
|
ChevronRight,
|
||||||
|
/// Flecha angular hacia arriba.
|
||||||
|
ChevronUp,
|
||||||
|
/// Aspa, para cerrar o descartar.
|
||||||
|
Close,
|
||||||
|
/// Engranaje, para la administración.
|
||||||
|
Gear,
|
||||||
|
/// Casa, para la página de inicio.
|
||||||
|
Home,
|
||||||
|
/// Llave, para permisos o accesos.
|
||||||
|
Key,
|
||||||
|
/// Capas apiladas, para la estructura.
|
||||||
|
Layers,
|
||||||
|
/// Signo menos, para quitar.
|
||||||
|
Minus,
|
||||||
|
/// Grupo de personas.
|
||||||
|
People,
|
||||||
|
/// Una persona.
|
||||||
|
Person,
|
||||||
|
/// Signo más, para añadir.
|
||||||
|
Plus,
|
||||||
|
/// Interrogación en un círculo, para la ayuda.
|
||||||
|
QuestionCircle,
|
||||||
|
/// Escudo, para roles o seguridad.
|
||||||
|
Shield,
|
||||||
|
/// Flecha que sale de una puerta, para cerrar sesión.
|
||||||
|
SignOut,
|
||||||
|
/// Controles deslizantes, para la configuración o los ajustes.
|
||||||
|
Sliders,
|
||||||
|
}
|
||||||
|
|
||||||
|
// Envuelve las formas de un icono, dibujadas en una cuadrícula de 16 x 16, en el trazo común del
|
||||||
|
// conjunto. El resultado es una cadena estática, que se copia tal cual al pintar el icono.
|
||||||
|
macro_rules! stroked {
|
||||||
|
( $($shape:expr),+ $(,)? ) => {
|
||||||
|
concat!(
|
||||||
|
r#"<g fill="none" stroke="currentColor" stroke-width="1.5" "#,
|
||||||
|
r#"stroke-linecap="round" stroke-linejoin="round">"#,
|
||||||
|
$($shape,)+
|
||||||
|
"</g>",
|
||||||
|
)
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Core {
|
||||||
|
// Contenido del `<svg>` del icono, para el `viewBox` común `0 0 16 16`.
|
||||||
|
pub(super) const fn svg(&self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
Self::BarChart => stroked!(r#"<path d="M2 14h12M4 14V9M8 14V3.5M12 14V6.5"/>"#),
|
||||||
|
Self::Check => stroked!(r#"<path d="M3 8.5l3 3 7-7"/>"#),
|
||||||
|
Self::ChevronDown => stroked!(r#"<path d="M3 5.5l5 5 5-5"/>"#),
|
||||||
|
Self::ChevronLeft => stroked!(r#"<path d="M10.5 3l-5 5 5 5"/>"#),
|
||||||
|
Self::ChevronRight => stroked!(r#"<path d="M5.5 3l5 5-5 5"/>"#),
|
||||||
|
Self::ChevronUp => stroked!(r#"<path d="M3 10.5l5-5 5 5"/>"#),
|
||||||
|
Self::Close => stroked!(r#"<path d="M4 4l8 8M12 4l-8 8"/>"#),
|
||||||
|
Self::Gear => stroked!(
|
||||||
|
r#"<path d="M12.9 6.9 14.7 7.1 14.7 8.9 12.9 9.1 12.2 10.7 13.4 12.1 12.1 13.4 "#,
|
||||||
|
r#"10.7 12.2 9.1 12.9 8.9 14.7 7.1 14.7 6.9 12.9 5.3 12.2 3.9 13.4 2.6 12.1 "#,
|
||||||
|
r#"3.8 10.7 3.1 9.1 1.3 8.9 1.3 7.1 3.1 6.9 3.8 5.3 2.6 3.9 3.9 2.6 5.3 3.8 "#,
|
||||||
|
r#"6.9 3.1 7.1 1.3 8.9 1.3 9.1 3.1 10.7 3.8 12.1 2.6 13.4 3.9 12.2 5.3z"/>"#,
|
||||||
|
r#"<circle cx="8" cy="8" r="2"/>"#,
|
||||||
|
),
|
||||||
|
Self::Home => {
|
||||||
|
stroked!(r#"<path d="M2 7.5l6-5 6 5M3.5 6.5v7h9v-7M6.5 13.5V10h3v3.5"/>"#)
|
||||||
|
}
|
||||||
|
Self::Key => stroked!(
|
||||||
|
r#"<circle cx="5" cy="11" r="2.5"/>"#,
|
||||||
|
r#"<path d="M6.8 9.2l6.7-6.7M11 5l2 2M12.5 3.5L14 5"/>"#,
|
||||||
|
),
|
||||||
|
Self::Layers => stroked!(
|
||||||
|
r#"<path d="M8 2l6 3.25-6 3.25-6-3.25zM2 8.25l6 3.25 6-3.25"#,
|
||||||
|
r#"M2 11.25l6 3.25 6-3.25"/>"#,
|
||||||
|
),
|
||||||
|
Self::Minus => stroked!(r#"<path d="M3 8h10"/>"#),
|
||||||
|
Self::People => stroked!(
|
||||||
|
r#"<circle cx="6" cy="5.5" r="2.25"/>"#,
|
||||||
|
r#"<path d="M1.5 13.5c.4-2.6 2.1-3.75 4.5-3.75s4.1 1.15 4.5 3.75"/>"#,
|
||||||
|
r#"<circle cx="11.25" cy="5" r="1.75"/>"#,
|
||||||
|
r#"<path d="M11.5 9.25c1.7.2 2.75 1.4 3 3.25"/>"#,
|
||||||
|
),
|
||||||
|
Self::Person => stroked!(
|
||||||
|
r#"<circle cx="8" cy="5" r="2.75"/>"#,
|
||||||
|
r#"<path d="M2.5 14c.5-3 2.7-4.5 5.5-4.5s5 1.5 5.5 4.5"/>"#,
|
||||||
|
),
|
||||||
|
Self::Plus => stroked!(r#"<path d="M8 3v10M3 8h10"/>"#),
|
||||||
|
Self::QuestionCircle => stroked!(
|
||||||
|
r#"<circle cx="8" cy="8" r="6.5"/>"#,
|
||||||
|
r#"<path d="M6.25 6.25a1.75 1.75 0 1 1 2.5 1.6c-.5.25-.75.6-.75 1.15v.5"#,
|
||||||
|
r#"M8 11.5v.01"/>"#,
|
||||||
|
),
|
||||||
|
Self::Shield => stroked!(
|
||||||
|
r#"<path d="M8 1.5l5.5 2v4c0 3.3-2.3 5.9-5.5 7-3.2-1.1-5.5-3.7-5.5-7v-4z"/>"#,
|
||||||
|
),
|
||||||
|
Self::SignOut => stroked!(r#"<path d="M6.5 2.5h-3v11h3M10 5l3 3-3 3M13 8H6.5"/>"#),
|
||||||
|
Self::Sliders => stroked!(
|
||||||
|
r#"<path d="M2 4h2M6.5 4H14M2 8h7M11.5 8H14M2 12h3.5M8 12h6"/>"#,
|
||||||
|
r#"<circle cx="5.25" cy="4" r="1.25"/>"#,
|
||||||
|
r#"<circle cx="10.25" cy="8" r="1.25"/>"#,
|
||||||
|
r#"<circle cx="6.75" cy="12" r="1.25"/>"#,
|
||||||
|
),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<Core> for icon::Source {
|
||||||
|
fn from(icon: Core) -> Self {
|
||||||
|
icon::Source::Core(icon)
|
||||||
|
}
|
||||||
|
}
|
||||||
76
src/base/component/icon/source.rs
Normal file
76
src/base/component/icon/source.rs
Normal file
|
|
@ -0,0 +1,76 @@
|
||||||
|
use crate::prelude::*;
|
||||||
|
|
||||||
|
/// Especifica el **origen** de un icono ([`Icon`](super::Icon)).
|
||||||
|
///
|
||||||
|
/// Es el punto de integración de cualquier conjunto de iconos: basta con implementar
|
||||||
|
/// `From<T> for icon::Source` para que su tipo pueda pasarse directamente a
|
||||||
|
/// [`Icon::with()`](super::Icon::with).
|
||||||
|
///
|
||||||
|
/// # Ejemplo
|
||||||
|
///
|
||||||
|
/// ```rust,no_run
|
||||||
|
/// use pagetop::prelude::*;
|
||||||
|
///
|
||||||
|
/// // Un conjunto propio de iconos SVG.
|
||||||
|
/// enum MyIcons {
|
||||||
|
/// Dot,
|
||||||
|
/// }
|
||||||
|
///
|
||||||
|
/// impl From<MyIcons> for icon::Source {
|
||||||
|
/// fn from(icon: MyIcons) -> Self {
|
||||||
|
/// match icon {
|
||||||
|
/// MyIcons::Dot => {
|
||||||
|
/// icon::Source::svg("0 0 16 16", html! { circle cx="8" cy="8" r="4" {} })
|
||||||
|
/// }
|
||||||
|
/// }
|
||||||
|
/// }
|
||||||
|
/// }
|
||||||
|
///
|
||||||
|
/// let dot = Icon::with(MyIcons::Dot);
|
||||||
|
///
|
||||||
|
/// // Un glifo de una fuente de iconos cuyas hojas de estilo ya se han cargado en la página.
|
||||||
|
/// let star = Icon::with(icon::Source::font("my-icons my-icons-star"));
|
||||||
|
/// ```
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub enum Source {
|
||||||
|
/// Icono SVG en línea.
|
||||||
|
///
|
||||||
|
/// Se renderiza como un elemento `<svg>` de `1em` de ancho y alto, que escala con el tamaño de
|
||||||
|
/// la fuente, y rellena con el color del texto (`fill="currentColor"`), salvo que las formas
|
||||||
|
/// indiquen otra cosa.
|
||||||
|
Svg {
|
||||||
|
/// Valor del atributo `viewBox` del `<svg>`, p. ej. `"0 0 16 16"`.
|
||||||
|
viewbox: CowStr,
|
||||||
|
/// Formas del icono (`path`, `circle`...), insertadas tal cual dentro del `<svg>`.
|
||||||
|
shapes: Markup,
|
||||||
|
},
|
||||||
|
/// Icono del conjunto incluido en PageTop.
|
||||||
|
///
|
||||||
|
/// Se renderiza como un icono SVG en línea, salvo que el tema activo lo sustituya por el
|
||||||
|
/// equivalente de su propio conjunto en su `setup_component()`. Como el `setup()` del icono ya
|
||||||
|
/// se ha ejecutado, el tema debe añadir también las clases CSS del nuevo origen (p. ej. las del
|
||||||
|
/// glifo, si lo cambia por [`Font`](Self::Font)).
|
||||||
|
Core(icon::Core),
|
||||||
|
/// Glifo de una fuente de iconos, identificado por sus clases CSS.
|
||||||
|
///
|
||||||
|
/// Se renderiza como un elemento `<i>` con esas clases. Las hojas de estilo y la fuente deben
|
||||||
|
/// cargarse aparte, normalmente desde el tema.
|
||||||
|
Font(CowStr),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Source {
|
||||||
|
/// Icono SVG en línea con el `viewBox` y las formas indicadas.
|
||||||
|
#[inline]
|
||||||
|
pub fn svg(viewbox: impl Into<CowStr>, shapes: Markup) -> Self {
|
||||||
|
Self::Svg {
|
||||||
|
viewbox: viewbox.into(),
|
||||||
|
shapes,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Glifo de una fuente de iconos con las clases CSS indicadas.
|
||||||
|
#[inline]
|
||||||
|
pub fn font(classes: impl Into<CowStr>) -> Self {
|
||||||
|
Self::Font(classes.into())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -149,7 +149,10 @@ impl Nav {
|
||||||
fn add_admin_items(&mut self, cx: &Context) {
|
fn add_admin_items(&mut self, cx: &Context) {
|
||||||
let registry = AdminRegistry::global();
|
let registry = AdminRegistry::global();
|
||||||
|
|
||||||
self.alter_item(nav::Item::link(Lc::l("admin_dashboard"), admin_path("")));
|
self.alter_item(
|
||||||
|
nav::Item::link(Lc::l("admin_dashboard"), admin_path(""))
|
||||||
|
.with_icon_start(Icon::with(icon::Core::Gear)),
|
||||||
|
);
|
||||||
for section in registry.sections() {
|
for section in registry.sections() {
|
||||||
let mut pages = registry
|
let mut pages = registry
|
||||||
.pages_for_section(section.key())
|
.pages_for_section(section.key())
|
||||||
|
|
@ -161,12 +164,12 @@ impl Nav {
|
||||||
}
|
}
|
||||||
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(
|
||||||
page.title().clone(),
|
dropdown::Item::link(page.title().clone(), admin_path(page.path()))
|
||||||
admin_path(page.path()),
|
.with_icon_start(page.icon().cloned()),
|
||||||
));
|
);
|
||||||
}
|
}
|
||||||
self.alter_item(nav::Item::dropdown(menu));
|
self.alter_item(nav::Item::dropdown(menu).with_icon_start(section.icon().cloned()));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -53,6 +53,10 @@ impl ItemKind {
|
||||||
/// Permite definir el identificador, las clases de estilo adicionales y el tipo de interacción
|
/// Permite definir el identificador, las clases de estilo adicionales y el tipo de interacción
|
||||||
/// asociada, manteniendo una interfaz común para renderizar todos los elementos del menú.
|
/// asociada, manteniendo una interfaz común para renderizar todos los elementos del menú.
|
||||||
///
|
///
|
||||||
|
/// Las etiquetas, los enlaces y el título de un desplegable pueden llevar un icono al principio y
|
||||||
|
/// otro al final ([`with_icon_start()`](Self::with_icon_start) y
|
||||||
|
/// [`with_icon_end()`](Self::with_icon_end)).
|
||||||
|
///
|
||||||
/// Un enlace no se renderiza si el usuario actual no puede acceder a su ruta (ver [`Endpoint`]).
|
/// Un enlace no se renderiza si el usuario actual no puede acceder a su ruta (ver [`Endpoint`]).
|
||||||
#[derive(AutoDefault, Clone, Debug, Getters)]
|
#[derive(AutoDefault, Clone, Debug, Getters)]
|
||||||
pub struct Item {
|
pub struct Item {
|
||||||
|
|
@ -67,6 +71,10 @@ pub struct Item {
|
||||||
/// permite otros criterios, como marcar activa una sección mientras la ruta actual sea
|
/// permite otros criterios, como marcar activa una sección mientras la ruta actual sea
|
||||||
/// cualquiera de sus subrutas.
|
/// cualquiera de sus subrutas.
|
||||||
active_override: Option<bool>,
|
active_override: Option<bool>,
|
||||||
|
/// Devuelve el icono al principio del elemento, antes de la etiqueta (si lo hay).
|
||||||
|
icon_start: Embed<Icon>,
|
||||||
|
/// Devuelve el icono al final del elemento, después de la etiqueta (si lo hay).
|
||||||
|
icon_end: Embed<Icon>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
|
|
@ -91,13 +99,15 @@ impl Component for Item {
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn prepare(&self, cx: &mut Context) -> Result<Markup, ComponentError> {
|
async fn prepare(&self, cx: &mut Context) -> Result<Markup, ComponentError> {
|
||||||
|
let start = self.icon_start().render(cx).await;
|
||||||
|
let end = self.icon_end().render(cx).await;
|
||||||
Ok(match self.item_kind() {
|
Ok(match self.item_kind() {
|
||||||
ItemKind::Void => html! {},
|
ItemKind::Void => html! {},
|
||||||
|
|
||||||
ItemKind::Label(label) => html! {
|
ItemKind::Label(label) => html! {
|
||||||
li (self.props().unpack(cx)) {
|
li (self.props().unpack(cx)) {
|
||||||
span class="nav-link disabled" aria-disabled="true" {
|
span class="nav-link disabled" aria-disabled="true" {
|
||||||
(label.using(cx))
|
(start) (label.using(cx)) (end)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|
@ -137,7 +147,7 @@ impl Component for Item {
|
||||||
aria-current=[aria_current]
|
aria-current=[aria_current]
|
||||||
aria-disabled=[aria_disabled]
|
aria-disabled=[aria_disabled]
|
||||||
{
|
{
|
||||||
(label.using(cx))
|
(start) (label.using(cx)) (end)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -170,7 +180,7 @@ impl Component for Item {
|
||||||
aria-haspopup="true"
|
aria-haspopup="true"
|
||||||
aria-expanded="false"
|
aria-expanded="false"
|
||||||
{
|
{
|
||||||
(title)
|
(start) (title) (end)
|
||||||
}
|
}
|
||||||
ul class=(dd.menu_classes()) {
|
ul class=(dd.menu_classes()) {
|
||||||
(items)
|
(items)
|
||||||
|
|
@ -289,6 +299,33 @@ impl Item {
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Asigna o quita el icono al principio del elemento, antes de la etiqueta. Si se pasa `None`,
|
||||||
|
/// no se mostrará.
|
||||||
|
///
|
||||||
|
/// *Principio* y *final* siguen el sentido de la escritura. Se aplica a las etiquetas, los
|
||||||
|
/// enlaces y el título de un desplegable. El icono lleva la clase `icon-start` (`icon-end` el
|
||||||
|
/// del final) para que cada tema lo coloque. Basic, en un menú vertical, deja ese hueco libre
|
||||||
|
/// en los elementos sin icono, para que todas las etiquetas queden alineadas.
|
||||||
|
pub fn with_icon_start(mut self, icon: impl Into<Option<Icon>>) -> Self {
|
||||||
|
let icon = icon
|
||||||
|
.into()
|
||||||
|
.map(|icon| icon.with_prop(PropsOp::add_classes("icon-start")));
|
||||||
|
self.icon_start.alter_component(icon);
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Asigna o quita el icono al final del elemento, después de la etiqueta. Si se pasa `None`, no
|
||||||
|
/// se mostrará. Basic, en un menú vertical, lo lleva junto al borde (en el título de un
|
||||||
|
/// desplegable, seguido de su flecha). Ver
|
||||||
|
/// [`with_icon_start()`](Self::with_icon_start).
|
||||||
|
pub fn with_icon_end(mut self, icon: impl Into<Option<Icon>>) -> Self {
|
||||||
|
let icon = icon
|
||||||
|
.into()
|
||||||
|
.map(|icon| icon.with_prop(PropsOp::add_classes("icon-end")));
|
||||||
|
self.icon_end.alter_component(icon);
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
/// Fuerza si un [`ItemKind::Link`] se marca activo, o `None` para volver a la detección
|
/// Fuerza si un [`ItemKind::Link`] se marca activo, o `None` para volver a la detección
|
||||||
/// automática por coincidencia exacta de ruta.
|
/// automática por coincidencia exacta de ruta.
|
||||||
pub fn with_active(mut self, active: impl Into<Option<bool>>) -> Self {
|
pub fn with_active(mut self, active: impl Into<Option<bool>>) -> Self {
|
||||||
|
|
|
||||||
|
|
@ -28,12 +28,10 @@ fn grant_tools(_: &HttpRequest, perm: PermissionRef, granted: &mut bool) {
|
||||||
}
|
}
|
||||||
|
|
||||||
fn declare_pages(bag: &mut AdminPageBag) {
|
fn declare_pages(bag: &mut AdminPageBag) {
|
||||||
bag.add(AdminPage::new(
|
bag.add(
|
||||||
"config/export",
|
AdminPage::new("config/export", "config", Lc::n("Export"), &ToolsPermission)
|
||||||
"config",
|
.with_icon(Icon::with(icon::Core::Plus)),
|
||||||
Lc::n("Export"),
|
);
|
||||||
&ToolsPermission,
|
|
||||||
));
|
|
||||||
bag.add(AdminPage::new(
|
bag.add(AdminPage::new(
|
||||||
"reports/audit",
|
"reports/audit",
|
||||||
"reports",
|
"reports",
|
||||||
|
|
@ -194,6 +192,22 @@ async fn the_admin_menu_goes_where_the_application_places_it() {
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[pagetop::test]
|
||||||
|
async fn the_admin_menu_shows_the_icons_of_the_dashboard_sections_and_pages() {
|
||||||
|
let _ = Application::prepare(&Ext).await;
|
||||||
|
let page = Page::admin(request("/admin/config/export/csv"))
|
||||||
|
.with_child_in(&CoreRegions::Header, admin_navbar());
|
||||||
|
let html = render(page).await;
|
||||||
|
|
||||||
|
// The dashboard, the "config" section (the only one with an accessible page) and its page.
|
||||||
|
let header = &html[html.find(r#"id="header""#).unwrap()..html.find("admin-content").unwrap()];
|
||||||
|
assert_eq!(
|
||||||
|
header.matches(r#"class="icon icon-start""#).count(),
|
||||||
|
3,
|
||||||
|
"{header}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
#[pagetop::test]
|
#[pagetop::test]
|
||||||
async fn the_admin_menu_only_shows_in_the_panel() {
|
async fn the_admin_menu_only_shows_in_the_panel() {
|
||||||
let _ = Application::prepare(&Ext).await;
|
let _ = Application::prepare(&Ext).await;
|
||||||
|
|
|
||||||
234
tests/component_icon.rs
Normal file
234
tests/component_icon.rs
Normal file
|
|
@ -0,0 +1,234 @@
|
||||||
|
use pagetop::prelude::*;
|
||||||
|
|
||||||
|
async fn render(mut icon: Icon) -> String {
|
||||||
|
icon.render(&mut Context::default()).await.into_string()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[pagetop::test]
|
||||||
|
async fn icon_without_source_renders_nothing() {
|
||||||
|
assert!(render(Icon::new()).await.is_empty());
|
||||||
|
assert!(
|
||||||
|
render(Icon::with(icon::Core::Check).with_source(None))
|
||||||
|
.await
|
||||||
|
.is_empty()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[pagetop::test]
|
||||||
|
async fn svg_icon_renders_an_inline_svg_scaled_to_the_font() {
|
||||||
|
let html = render(Icon::with(icon::Core::Check)).await;
|
||||||
|
|
||||||
|
assert!(html.starts_with("<svg"));
|
||||||
|
assert!(html.contains(r#"class="icon""#));
|
||||||
|
assert!(html.contains(r#"viewBox="0 0 16 16""#));
|
||||||
|
assert!(html.contains(r#"width="1em" height="1em""#));
|
||||||
|
assert!(html.contains("<path"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[pagetop::test]
|
||||||
|
async fn font_icon_renders_an_i_element_with_its_classes() {
|
||||||
|
let html = render(Icon::with(icon::Source::font("my-icons my-icons-star"))).await;
|
||||||
|
|
||||||
|
assert!(html.starts_with("<i"));
|
||||||
|
assert!(html.contains(r#"class="icon my-icons my-icons-star""#));
|
||||||
|
assert!(html.ends_with("</i>"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[pagetop::test]
|
||||||
|
async fn icon_without_label_is_decorative() {
|
||||||
|
for icon in [
|
||||||
|
Icon::with(icon::Core::Close),
|
||||||
|
Icon::with(icon::Source::font("my-icons-star")),
|
||||||
|
] {
|
||||||
|
let html = render(icon).await;
|
||||||
|
|
||||||
|
assert!(html.contains(r#"aria-hidden="true""#));
|
||||||
|
assert!(!html.contains("role="));
|
||||||
|
assert!(!html.contains("aria-label"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[pagetop::test]
|
||||||
|
async fn icon_with_a_blank_label_is_decorative() {
|
||||||
|
let html = render(Icon::with(icon::Core::Close).with_label(Lc::n(" "))).await;
|
||||||
|
|
||||||
|
assert!(html.contains(r#"aria-hidden="true""#), "{html}");
|
||||||
|
assert!(!html.contains("role="), "{html}");
|
||||||
|
assert!(!html.contains("aria-label"), "{html}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[pagetop::test]
|
||||||
|
async fn icon_with_label_is_announced_as_an_image() {
|
||||||
|
for icon in [
|
||||||
|
Icon::with(icon::Core::Close),
|
||||||
|
Icon::with(icon::Source::font("my-icons-star")),
|
||||||
|
] {
|
||||||
|
let html = render(icon.with_label(Lc::n("Close"))).await;
|
||||||
|
|
||||||
|
assert!(html.contains(r#"role="img""#));
|
||||||
|
assert!(html.contains(r#"aria-label="Close""#));
|
||||||
|
assert!(!html.contains("aria-hidden"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[pagetop::test]
|
||||||
|
async fn icon_size_sets_the_font_size() {
|
||||||
|
let sized = render(Icon::with(icon::Core::Plus).with_size(UnitValue::RelRem(2.0))).await;
|
||||||
|
let unsized_icon = render(Icon::with(icon::Core::Plus)).await;
|
||||||
|
|
||||||
|
assert!(sized.contains(r#"style="font-size: 2rem""#));
|
||||||
|
assert!(!unsized_icon.contains("style="));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[pagetop::test]
|
||||||
|
async fn custom_classes_are_kept_after_the_icon_class() {
|
||||||
|
let html =
|
||||||
|
render(Icon::with(icon::Core::Minus).with_prop(PropsOp::add_classes("text-red"))).await;
|
||||||
|
|
||||||
|
assert!(html.contains(r#"class="icon text-red""#));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[pagetop::test]
|
||||||
|
async fn any_type_convertible_into_a_source_is_an_icon_set() {
|
||||||
|
enum MyIcons {
|
||||||
|
Dot,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<MyIcons> for icon::Source {
|
||||||
|
fn from(icon: MyIcons) -> Self {
|
||||||
|
match icon {
|
||||||
|
MyIcons::Dot => {
|
||||||
|
icon::Source::svg("0 0 10 10", html! { circle cx="5" cy="5" r="2" {} })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let html = render(Icon::with(MyIcons::Dot)).await;
|
||||||
|
|
||||||
|
assert!(html.contains(r#"viewBox="0 0 10 10""#));
|
||||||
|
assert!(html.contains("<circle"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[pagetop::test]
|
||||||
|
async fn icon_intent_adds_the_theme_color_class() {
|
||||||
|
let html = render(Icon::with(icon::Core::Check).with_intent(Intent::Success)).await;
|
||||||
|
|
||||||
|
assert!(html.contains(r#"class="icon icon-success""#));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[pagetop::test]
|
||||||
|
async fn button_renders_its_start_icon_before_the_label() {
|
||||||
|
let mut button = Button::plain(Lc::n("Add")).with_icon_start(Icon::with(icon::Core::Plus));
|
||||||
|
let html = button.render(&mut Context::default()).await.into_string();
|
||||||
|
|
||||||
|
assert!(html.contains("</svg> Add</button>"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[pagetop::test]
|
||||||
|
async fn icon_only_button_takes_its_name_from_the_icon_label() {
|
||||||
|
let mut button = Button::plain(Lc::none())
|
||||||
|
.with_icon_start(Icon::with(icon::Core::Close).with_label(Lc::n("Close")));
|
||||||
|
let html = button.render(&mut Context::default()).await.into_string();
|
||||||
|
|
||||||
|
assert!(html.contains(r#"aria-label="Close""#));
|
||||||
|
// No separator without a label.
|
||||||
|
assert!(html.contains("</svg></button>"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[pagetop::test]
|
||||||
|
async fn button_renders_its_end_icon_after_the_label() {
|
||||||
|
let mut button =
|
||||||
|
Button::plain(Lc::n("Next")).with_icon_end(Icon::with(icon::Core::ChevronRight));
|
||||||
|
let html = button.render(&mut Context::default()).await.into_string();
|
||||||
|
|
||||||
|
assert!(html.contains("Next <svg"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[pagetop::test]
|
||||||
|
async fn button_separates_both_icons_from_the_label_with_one_space_each() {
|
||||||
|
let start = || Icon::with(icon::Core::Plus).with_id("start");
|
||||||
|
let end = || Icon::with(icon::Core::ChevronDown).with_id("end");
|
||||||
|
|
||||||
|
let mut labeled = Button::plain(Lc::n("Add"))
|
||||||
|
.with_icon_start(start())
|
||||||
|
.with_icon_end(end());
|
||||||
|
let mut unlabeled = Button::plain(Lc::none())
|
||||||
|
.with_icon_start(start())
|
||||||
|
.with_icon_end(end());
|
||||||
|
let labeled = labeled.render(&mut Context::default()).await.into_string();
|
||||||
|
let unlabeled = unlabeled
|
||||||
|
.render(&mut Context::default())
|
||||||
|
.await
|
||||||
|
.into_string();
|
||||||
|
|
||||||
|
assert!(labeled.contains("</svg> Add <svg"));
|
||||||
|
assert!(labeled.find(r#"id="start""#) < labeled.find(r#"id="end""#));
|
||||||
|
assert!(unlabeled.contains("</svg> <svg"));
|
||||||
|
assert!(!unlabeled.contains(" "));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[pagetop::test]
|
||||||
|
async fn nav_link_renders_its_icons_around_the_label() {
|
||||||
|
let mut item = nav::Item::link(Lc::n("Home"), "/")
|
||||||
|
.with_icon_start(Icon::with(icon::Core::Check))
|
||||||
|
.with_icon_end(Icon::with(icon::Core::ChevronRight));
|
||||||
|
let html = item.render(&mut Context::default()).await.into_string();
|
||||||
|
|
||||||
|
let start = html.find(r#"class="icon icon-start""#).unwrap();
|
||||||
|
let label = html.find("Home").unwrap();
|
||||||
|
let end = html.find(r#"class="icon icon-end""#).unwrap();
|
||||||
|
assert!(start < label && label < end);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[pagetop::test]
|
||||||
|
async fn nav_dropdown_title_renders_its_icons() {
|
||||||
|
let mut item = nav::Item::dropdown(
|
||||||
|
Dropdown::new()
|
||||||
|
.with_title(Lc::n("More"))
|
||||||
|
.with_item(dropdown::Item::link(Lc::n("One"), "/one")),
|
||||||
|
)
|
||||||
|
.with_icon_start(Icon::with(icon::Core::Plus));
|
||||||
|
let html = item.render(&mut Context::default()).await.into_string();
|
||||||
|
|
||||||
|
assert!(html.contains(r#"class="icon icon-start""#));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[pagetop::test]
|
||||||
|
async fn dropdown_items_render_their_icons_around_the_label() {
|
||||||
|
for item in [
|
||||||
|
dropdown::Item::label(Lc::n("Text")),
|
||||||
|
dropdown::Item::link(Lc::n("Text"), "/"),
|
||||||
|
dropdown::Item::button(Lc::n("Text")),
|
||||||
|
] {
|
||||||
|
let mut item = item
|
||||||
|
.with_icon_start(Icon::with(icon::Core::Check))
|
||||||
|
.with_icon_end(Icon::with(icon::Core::ChevronRight));
|
||||||
|
let html = item.render(&mut Context::default()).await.into_string();
|
||||||
|
|
||||||
|
let start = html.find(r#"class="icon icon-start""#).unwrap();
|
||||||
|
let label = html.find("Text").unwrap();
|
||||||
|
let end = html.find(r#"class="icon icon-end""#).unwrap();
|
||||||
|
assert!(start < label && label < end);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[pagetop::test]
|
||||||
|
async fn menu_item_without_icons_renders_as_before() {
|
||||||
|
let mut item = dropdown::Item::link(Lc::n("Text"), "/");
|
||||||
|
let html = item.render(&mut Context::default()).await.into_string();
|
||||||
|
|
||||||
|
assert!(!html.contains("<svg"));
|
||||||
|
assert!(html.contains(">Text</a>"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[pagetop::test]
|
||||||
|
async fn core_icon_keeps_its_identity_until_rendered() {
|
||||||
|
let icon = Icon::with(icon::Core::Gear);
|
||||||
|
|
||||||
|
assert!(matches!(
|
||||||
|
icon.source(),
|
||||||
|
Some(icon::Source::Core(icon::Core::Gear))
|
||||||
|
));
|
||||||
|
assert!(render(icon).await.starts_with("<svg"));
|
||||||
|
}
|
||||||
Loading…
Add table
Add a link
Reference in a new issue