Compare commits

...

5 commits

Author SHA1 Message Date
86e12e0bcb ✨ (examples): Iconos y recuadros en theme-showcase 2026-11-23 03:03:14 +01:00
ad80c09eff ✨ (pagetop): Añade el componente Tile y Accent
Recuadro de acceso a una sección con icono, descripción, color de acento
e imagen de fondo difuminada; se oculta sin acceso a su ruta. Basic y
Bootsier definen las clases `accent-<color>`.
2026-11-23 02:59:42 +01:00
4adb8cb1ec ✨ (pagetop): Añade métodos ..._blank() 2026-11-23 02:17:25 +01:00
f1fd34f974 ♻️ (pagetop): Deshabilita menús con with_disabled()
Cambia `link_disabled()`, `link_blank_disabled()` y `button_disabled()`
de `nav::Item` y `dropdown::Item` por `with_disabled(bool)`, como en
Button.
2026-11-23 02:01:06 +01:00
5d6852382a ✨ 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.
2026-11-22 23:08:28 +01:00
45 changed files with 2631 additions and 273 deletions

View file

@ -14,6 +14,9 @@
@use "basic/root";
@use "basic/base";
// Accent colors shared by the components that take one (`accent-<color>` classes).
@use "basic/accent";
// Components, in alphabetical order. `buttons` must go before `dropdown` and `nav`, see the notes
// in `basic/_buttons.scss`.
@use "basic/badge";
@ -25,6 +28,7 @@
@use "basic/dialog";
@use "basic/dropdown";
@use "basic/form";
@use "basic/icon";
@use "basic/image";
@use "basic/list-filter";
@use "basic/list-view";
@ -33,6 +37,7 @@
@use "basic/navbar";
@use "basic/pager";
@use "basic/table";
@use "basic/tile";
// Theme regions.
@use "basic/regions";

View file

@ -0,0 +1,16 @@
// Accent colors (`Accent`): every component that takes one adds the same `accent-<color>` class,
// which sets --val-color--accent to the tone of the theme for that color (`_root.scss`). The
// styles of each component only read that variable.
.accent-blue { --val-color--accent: var(--val-color--blue); }
.accent-indigo { --val-color--accent: var(--val-color--indigo); }
.accent-purple { --val-color--accent: var(--val-color--purple); }
.accent-magenta { --val-color--accent: var(--val-color--magenta); }
.accent-pink { --val-color--accent: var(--val-color--pink); }
.accent-red { --val-color--accent: var(--val-color--red); }
.accent-orange { --val-color--accent: var(--val-color--orange); }
.accent-yellow { --val-color--accent: var(--val-color--yellow); }
.accent-lime { --val-color--accent: var(--val-color--lime); }
.accent-green { --val-color--accent: var(--val-color--green); }
.accent-teal { --val-color--accent: var(--val-color--teal); }
.accent-cyan { --val-color--accent: var(--val-color--cyan); }
.accent-gray { --val-color--accent: var(--val-color--gray); }

View 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;
}
}

View file

@ -17,6 +17,20 @@
--val-color--info: #0dcaf0;
--val-color--warning: #ffc107;
--val-color--danger: #dc3545;
// Accent Colors (`Accent`): no meaning, only to tell elements apart
--val-color--blue: #0d6efd;
--val-color--indigo: #6610f2;
--val-color--purple: #6f42c1;
--val-color--magenta: #c026d3;
--val-color--pink: #d63384;
--val-color--red: #dc3545;
--val-color--orange: #fd7e14;
--val-color--yellow: #ffc107;
--val-color--lime: #65a30d;
--val-color--green: #198754;
--val-color--teal: #20c997;
--val-color--cyan: #0dcaf0;
--val-color--gray: #6c757d;
// Other Colors
--val-color--bg: #fafafa;
--val-color--bg--muted: #dee2e6;

View file

@ -0,0 +1,105 @@
// Access tiles (Tile): a large link with white text over its accent color and, when it has one, a
// blurred background image. The image goes below a veil of the accent color (from translucent to
// darkened), so the text keeps its contrast whatever the picture. The icon stays at the top and the
// texts at the bottom (also without an icon), so the icons of a row line up whatever the length of
// the descriptions.
.tile {
// The accent of the tile (`accent-<color>`, see `_accent.scss`), with a fallback.
--tile-accent: var(--val-color--accent, var(--val-color--primary));
position: relative;
isolation: isolate;
display: flex;
flex-direction: column;
min-height: 11rem;
padding: 1.5rem;
overflow: hidden;
color: #fff;
text-decoration: none;
background-color: var(--tile-accent);
border-radius: 0.75rem;
box-shadow: 0 0.25rem 0.75rem rgb(0 0 0 / 15%);
transition: transform 0.2s ease, box-shadow 0.2s ease;
}
.tile::before {
content: "";
position: absolute;
inset: 0;
z-index: -1;
background: linear-gradient(
135deg,
color-mix(in srgb, var(--tile-accent) 75%, transparent),
color-mix(in srgb, var(--tile-accent) 55%, #000)
);
}
// Scaled up a little so that the blur does not leave light edges.
.tile > .tile-image {
position: absolute;
inset: 0;
z-index: -2;
width: 100%;
height: 100%;
object-fit: cover;
filter: blur(3px) saturate(80%);
transform: scale(1.08);
transition: transform 0.4s ease;
}
.tile:hover,
.tile:focus-visible {
color: #fff;
transform: translateY(-0.25rem);
box-shadow: 0 0.75rem 1.5rem rgb(0 0 0 / 25%);
}
.tile:hover > .tile-image,
.tile:focus-visible > .tile-image {
transform: scale(1.15);
}
.tile:focus-visible {
outline: 3px solid var(--tile-accent);
outline-offset: 3px;
}
.tile-body {
flex-grow: 1;
display: flex;
flex-direction: column;
justify-content: flex-end;
gap: 0.25rem;
text-shadow: 0 1px 3px rgb(0 0 0 / 40%);
}
.tile-icon {
margin-bottom: auto;
padding-bottom: 1rem;
font-size: 2.5rem;
line-height: 1;
}
.tile-title {
font-size: 1.375rem;
font-weight: 600;
line-height: 1.2;
}
.tile-description {
font-size: 0.9375rem;
opacity: 0.9;
}
// Disabled (`Tile::with_disabled()`): dimmed, without a link and without reacting to the pointer.
.tile.disabled {
pointer-events: none;
opacity: 0.65;
box-shadow: none;
}
@media (prefers-reduced-motion: reduce) {
.tile,
.tile > .tile-image {
transition: none;
}
}

View file

@ -24,7 +24,7 @@ impl Extension for NavDemo {
.with_item(dropdown::Item::header(Lc::n("Danger zone")))
.with_item(dropdown::Item::button(Lc::n("Reset settings"))),
))
.with_item(nav::Item::link_disabled(Lc::n("Disabled"), "#"));
.with_item(nav::Item::link(Lc::n("Disabled"), "#").with_disabled(true));
let user_menu = Dropdown::new()
.with_title(Lc::n("Account"))

View file

@ -38,10 +38,7 @@ impl Extension for NavbarDemo {
)),
))
.with_item(nav::Item::link(Lc::t("navbar_active", &LOC), "/active").with_active(true))
.with_item(nav::Item::link_disabled(
Lc::t("navbar_disabled", &LOC),
"#",
));
.with_item(nav::Item::link(Lc::t("navbar_disabled", &LOC), "#").with_disabled(true));
let navbar = Navbar::brand_left(brand).with_item(navbar::Item::nav(main_nav));

View file

@ -65,6 +65,63 @@ showcase_empty_table = A table without rows shows its message:
showcase_block_buttons = Buttons
showcase_block_icons = Icons
showcase_icons_sizes =
Icons of the example's own set, the same with any theme, and of PageTop
(<code>icon::Core</code>), which each theme may replace with its own. Their size follows the
font size and their color, the intent:
showcase_icons_cards = Status cards with a large icon:
showcase_card_switch = Living room switch
showcase_card_outlet = Night outlet
showcase_card_battery = Server battery
showcase_card_active = Activated
showcase_card_low = Low power
showcase_icons_toolbar =
Icon-only buttons; the icon label names the button and shows up on hover:
showcase_tag = Tag
showcase_view = View
showcase_comment_action = Comment
showcase_notify = Notify
showcase_pin = Pin
showcase_hide = Hide
showcase_align_left = Align left
showcase_align_center = Center
showcase_align_right = Align right
showcase_align_justify = Justify
showcase_bold = Bold
showcase_italic = Italic
showcase_underline = Underline
showcase_icons_buttons =
Buttons with icon and text, with the icon at the start, at the end or on both sides:
showcase_new = New
showcase_filter = Filter
showcase_insert_image = Insert image
showcase_save = Save
showcase_discard = Discard
showcase_next = Next
showcase_move_to = Move to
showcase_icons_menus =
Menus with icons: options without an icon keep their space and the end icon sits at the edge.
showcase_nav_start = Get started
showcase_nav_styles = Styles
showcase_nav_grid = Grid
showcase_nav_folders = Folders
showcase_nav_templates = Templates
showcase_actions = Actions
showcase_duplicate = Duplicate
showcase_icons_table = Icons in a table:
showcase_col_name = Name
showcase_col_type = Type
showcase_type_folder = Folder
showcase_type_document = Document
showcase_delete = Delete
showcase_block_tiles = Access tiles
showcase_tile_image = With a blurred background image under its color
showcase_tile_color = Only with its accent color
showcase_tile_no_icon = Without an icon
showcase_tile_disabled = Disabled: dimmed and without a link
showcase_block_misc = Links, badges and pagination
showcase_link_text = A paragraph with <a href="#">a link</a> in the middle of the text.
showcase_msg_info = An informative message.

View file

@ -65,6 +65,63 @@ showcase_empty_table = Una tabla sin filas muestra su mensaje:
showcase_block_buttons = Botones
showcase_block_icons = Iconos
showcase_icons_sizes =
Iconos del conjunto propio del ejemplo, iguales con cualquier tema, y de PageTop
(<code>icon::Core</code>), que cada tema puede sustituir por los suyos. Su tamaño sigue al de la
fuente y su color, a la intención:
showcase_icons_cards = Tarjetas de estado con un icono grande:
showcase_card_switch = Interruptor del salón
showcase_card_outlet = Enchufe nocturno
showcase_card_battery = Batería del servidor
showcase_card_active = Activado
showcase_card_low = Carga baja
showcase_icons_toolbar =
Botones sólo con icono; la etiqueta del icono da nombre al botón y aparece al pasar por encima:
showcase_tag = Etiquetar
showcase_view = Ver
showcase_comment_action = Comentar
showcase_notify = Avisar
showcase_pin = Fijar
showcase_hide = Ocultar
showcase_align_left = Alinear a la izquierda
showcase_align_center = Centrar
showcase_align_right = Alinear a la derecha
showcase_align_justify = Justificar
showcase_bold = Negrita
showcase_italic = Cursiva
showcase_underline = Subrayado
showcase_icons_buttons =
Botones con icono y texto, con el icono al principio, al final o a los dos lados:
showcase_new = Nuevo
showcase_filter = Filtrar
showcase_insert_image = Insertar imagen
showcase_save = Guardar
showcase_discard = Descartar
showcase_next = Siguiente
showcase_move_to = Mover a
showcase_icons_menus =
Menús con iconos: las opciones sin icono dejan su hueco y el icono final va junto al borde.
showcase_nav_start = Primeros pasos
showcase_nav_styles = Estilos
showcase_nav_grid = Rejilla
showcase_nav_folders = Carpetas
showcase_nav_templates = Plantillas
showcase_actions = Acciones
showcase_duplicate = Duplicar
showcase_icons_table = Iconos en una tabla:
showcase_col_name = Nombre
showcase_col_type = Tipo
showcase_type_folder = Carpeta
showcase_type_document = Documento
showcase_delete = Eliminar
showcase_block_tiles = Recuadros de acceso
showcase_tile_image = Con una imagen de fondo difuminada bajo su color
showcase_tile_color = Sólo con su color de acento
showcase_tile_no_icon = Sin icono
showcase_tile_disabled = Deshabilitado: atenuado y sin enlace
showcase_block_misc = Enlaces, insignias y paginación
showcase_link_text = Un párrafo con <a href="#">un enlace</a> en medio del texto.
showcase_msg_info = Un mensaje informativo.

View file

@ -106,15 +106,14 @@ fn menus_block() -> Block {
))
.with_item(dropdown::Item::divider())
.with_item(dropdown::Item::label(Lc::t("menus_item_label", &LOC)))
.with_item(dropdown::Item::link_disabled(
Lc::t("menus_item_disabled", &LOC),
"#",
)),
.with_item(
dropdown::Item::link(Lc::t("menus_item_disabled", &LOC), "#")
.with_disabled(true),
),
))
.with_item(nav::Item::link_disabled(
Lc::t("menus_item_disabled", &LOC),
"#",
)),
.with_item(
nav::Item::link(Lc::t("menus_item_disabled", &LOC), "#").with_disabled(true),
),
))
.with_item(navbar::Item::nav(
Nav::new()
@ -686,10 +685,7 @@ fn demo_nav() -> Nav {
"/something",
)),
))
.with_item(nav::Item::link_disabled(
Lc::t("menus_item_disabled", &LOC),
"#",
))
.with_item(nav::Item::link(Lc::t("menus_item_disabled", &LOC), "#").with_disabled(true))
}
fn is_bootsier() -> bool {

View file

@ -24,41 +24,46 @@ impl Extension for ThemeShowcase {
// Menú completo: enlace activo, desplegable con secciones, enlace externo y deshabilitado.
// Ocupa el espacio libre entre la marca y el menú de la cuenta, con sus opciones centradas.
// Algunas opciones llevan icono; en el desplegable, las que no lo tienen dejan su hueco.
let main_menu = Nav::new()
.with_layout(nav::Layout::Center)
.with_prop(FlexItem::new().with_grow(flex::ItemGrow::Is1))
.with_item(nav::Item::link(Lc::t("showcase_menu_home", &LOC), "/").with_active(true))
.with_item(
nav::Item::link(Lc::t("showcase_menu_home", &LOC), "/")
.with_active(true)
.with_icon_start(Icon::with(icon::Core::Home)),
)
.with_item(nav::Item::dropdown(
Dropdown::new()
.with_title(Lc::t("showcase_menu_components", &LOC))
.with_item(dropdown::Item::header(Lc::t("showcase_menu_forms", &LOC)))
.with_item(dropdown::Item::link(
Lc::t("showcase_menu_fields", &LOC),
"#",
))
.with_item(
dropdown::Item::link(Lc::t("showcase_menu_fields", &LOC), "#")
.with_icon_start(Icon::with(ShowcaseIcon::Pencil)),
)
.with_item(dropdown::Item::link(
Lc::t("showcase_menu_buttons", &LOC),
"#",
))
.with_item(dropdown::Item::divider())
.with_item(dropdown::Item::header(Lc::t("showcase_menu_others", &LOC)))
.with_item(dropdown::Item::link(
Lc::t("showcase_menu_messages", &LOC),
"#",
.with_item(
dropdown::Item::link(Lc::t("showcase_menu_messages", &LOC), "#")
.with_icon_start(Icon::with(ShowcaseIcon::Chat))
.with_icon_end(Icon::with(icon::Core::ChevronRight)),
)
.with_item(
dropdown::Item::link(Lc::t("showcase_menu_disabled", &LOC), "#")
.with_disabled(true),
),
))
.with_item(dropdown::Item::link_disabled(
Lc::t("showcase_menu_disabled", &LOC),
"#",
)),
))
.with_item(nav::Item::link_blank(
Lc::t("showcase_menu_docs", &LOC),
"https://docs.rs/pagetop",
))
.with_item(nav::Item::link_disabled(
Lc::t("showcase_menu_disabled", &LOC),
"#",
));
.with_item(
nav::Item::link_blank(Lc::t("showcase_menu_docs", &LOC), "https://docs.rs/pagetop")
.with_icon_end(Icon::with(ShowcaseIcon::External)),
)
.with_item(
nav::Item::link(Lc::t("showcase_menu_disabled", &LOC), "#").with_disabled(true),
);
// Menú de la cuenta al final de la barra y, con Bootsier, el selector de modo de color
// (claro, oscuro o automático).
@ -91,6 +96,8 @@ async fn theme_showcase(request: HttpRequest) -> Result<Markup, ErrorPage> {
.with_child(checks_block())
.with_child(tables_block())
.with_child(buttons_block())
.with_child(icons_block())
.with_child(tiles_block())
.with_child(misc_block());
// Un mensaje de cada nivel, que muestra el listado del bloque de tablas entre su botón y la
@ -446,6 +453,476 @@ fn buttons(outline: bool) -> Flex {
row
}
// Conjunto de iconos propio del ejemplo, para mostrar cómo se integra uno: basta implementar
// `From<ShowcaseIcon> for icon::Source` para pasarlos a `Icon::with()`. Son SVG en línea y se ven
// igual con cualquier tema, a diferencia de los de `icon::Core`, que cada tema puede sustituir por
// los de su propio conjunto (Bootsier, por los de Bootstrap Icons).
#[derive(Clone, Copy)]
enum ShowcaseIcon {
AlertCircle,
AlignCenter,
AlignJustify,
AlignLeft,
AlignRight,
Bell,
Bold,
Chat,
CheckCircle,
Eye,
EyeOff,
External,
File,
Filter,
Folder,
Image,
Italic,
Lightbulb,
Pencil,
Pin,
Plug,
Search,
Tag,
Underline,
}
impl From<ShowcaseIcon> for icon::Source {
fn from(icon: ShowcaseIcon) -> Self {
use ShowcaseIcon::*;
let shapes = match icon {
AlertCircle => html! {
circle cx="8" cy="8" r="6.5" {}
path d="M8 4.75v3.75M8 11.25v.01" {}
},
AlignCenter => html! { path d="M2 3.5h12M4 6.5h8M2 9.5h12M4 12.5h8" {} },
AlignJustify => html! { path d="M2 3.5h12M2 6.5h12M2 9.5h12M2 12.5h12" {} },
AlignLeft => html! { path d="M2 3.5h12M2 6.5h8M2 9.5h12M2 12.5h8" {} },
AlignRight => html! { path d="M2 3.5h12M6 6.5h8M2 9.5h12M6 12.5h8" {} },
Bell => html! { path d="M4 11.5V7a4 4 0 0 1 8 0v4.5l1 1H3zM6.5 14.5h3" {} },
Bold => html! {
path d="M4.5 2.5H9a2.75 2.75 0 0 1 0 5.5H4.5zM4.5 8h5a2.75 2.75 0 0 1 0 5.5h-5z" {}
},
Chat => html! { path d="M2.5 3.5h11V11H7l-3 2.5V11H2.5z" {} },
CheckCircle => html! {
circle cx="8" cy="8" r="6.5" {}
path d="M5 8.25l2 2 4-4" {}
},
Eye => html! {
path d="M1.5 8S4 3.5 8 3.5 14.5 8 14.5 8 12 12.5 8 12.5 1.5 8 1.5 8z" {}
circle cx="8" cy="8" r="2" {}
},
EyeOff => html! {
path d="M1.5 8S4 3.5 8 3.5 14.5 8 14.5 8 12 12.5 8 12.5 1.5 8 1.5 8z" {}
circle cx="8" cy="8" r="2" {}
path d="M2.5 2.5l11 11" {}
},
External => html! { path d="M9 2.5h4.5V7M13.5 2.5l-6 6M11.5 9.5v4h-9v-9h4" {} },
File => html! { path d="M3.5 1.5h6l3 3v10h-9zM9.5 1.5v3h3" {} },
Filter => html! { path d="M2 3h12l-4.5 5.5V13l-3-1.5v-3z" {} },
Folder => html! { path d="M1.5 3.5H6L7.5 5h7v7.5h-13z" {} },
Image => html! {
rect x="1.5" y="2.5" width="13" height="11" rx="1.5" {}
circle cx="10.5" cy="6" r="1.25" {}
path d="M1.5 11.5l4-4 3 3 2-2 4 4" {}
},
Italic => html! { path d="M7 2.5h5M4 13.5h5M10 2.5l-4 11" {} },
Lightbulb => html! {
path d="M6 11c0-.9-.4-1.5-1.2-2.3a4.25 4.25 0 1 1 6.4 0C10.4 9.5 10 10.1 10 11" {}
path d="M6 11h4M6.75 14h2.5" {}
},
Pencil => html! { path d="M10.5 2.5l3 3L6 13H3v-3zM9 4l3 3" {} },
Pin => html! { path d="M6 1.5h4M7 1.5v4L4.5 8.5h7L9 5.5v-4M8 8.5v6" {} },
Plug => {
html! { path d="M5.5 1.5v3M10.5 1.5v3M3.5 4.5h9V7a4.5 4.5 0 0 1-9 0zM8 11.5v3" {} }
}
Search => html! {
circle cx="7" cy="7" r="4.5" {}
path d="M10.5 10.5l3.5 3.5" {}
},
Tag => html! {
path d="M2.5 2.5h5l6 6-5 5-6-6z" {}
circle cx="5.5" cy="5.5" r="1" {}
},
Underline => html! { path d="M4.5 2.5V7a3.5 3.5 0 0 0 7 0V2.5M3 14.5h10" {} },
};
icon::Source::svg(
"0 0 16 16",
html! {
g
fill="none"
stroke="currentColor"
stroke-width="1.5"
stroke-linecap="round"
stroke-linejoin="round"
{
(shapes)
}
},
)
}
}
// Iconos en sus distintos usos: tamaños y colores, tarjetas de estado, barras de botones sólo con
// icono, botones con icono y texto, y una tabla. Mezcla el conjunto propio con el de PageTop.
fn icons_block() -> Block {
use ShowcaseIcon::*;
let row = || {
Flex::new()
.with_wrap(flex::Behavior::Wrap)
.with_align(align::Items::Center)
.with_gap(align::Gap::Both(UnitValue::RelRem(0.75)))
.with_prop(Margin::new().with_bottom(UnitValue::RelRem(1.5)))
};
let caption = |key: &'static str| {
Html::with(move |cx| {
html! {
p { (Lc::t(key, &LOC).using(cx)) }
}
})
};
// Botón sólo con icono: la etiqueta del icono es el nombre accesible del botón, y el texto
// emergente la muestra al pasar por encima.
let icon_button = |source: icon::Source, key: &'static str, style: button::Style| {
Button::plain(Lc::none())
.with_style(style)
.with_title(Lc::t(key, &LOC))
.with_icon_start(Icon::with(source).with_label(Lc::t(key, &LOC)))
};
// El tamaño sigue al de la fuente; el color, a la intención.
let mut sizes = row();
for size in [1.0, 1.5, 2.0, 2.5, 3.0] {
sizes = sizes.with_child(Icon::with(Lightbulb).with_size(UnitValue::RelRem(size)));
}
let mut colors = row();
for (source, intent) in [
(icon::Source::from(Pin), Intent::Primary),
(Bell.into(), Intent::Neutral),
(Chat.into(), Intent::Info),
(CheckCircle.into(), Intent::Success),
(AlertCircle.into(), Intent::Warning),
(icon::Core::Close.into(), Intent::Severe),
] {
colors = colors.with_child(
Icon::with(source)
.with_size(UnitValue::RelRem(1.5))
.with_intent(intent),
);
}
// Tarjetas de estado: un icono grande de color, el nombre del aparato y su estado.
let card = |source: ShowcaseIcon, intent: Intent, title: &'static str, badge: Badge| {
Flex::new()
.with_direction(flex::Direction::Column)
.with_align(align::Items::Start)
.with_gap(align::Gap::Both(UnitValue::RelRem(0.5)))
.with_prop(Margin::new().with_bottom(UnitValue::RelRem(1.5)))
.with_child(
Icon::with(source)
.with_size(UnitValue::RelRem(2.5))
.with_intent(intent),
)
.with_child(Lc::t(title, &LOC))
.with_child(badge)
};
let cards = columns()
.with_child(card(
Lightbulb,
Intent::Warning,
"showcase_card_switch",
Badge::success(Lc::t("showcase_card_active", &LOC)),
))
.with_child(card(
Plug,
Intent::Primary,
"showcase_card_outlet",
Badge::info(Lc::n("32 %")),
))
.with_child(card(
AlertCircle,
Intent::Severe,
"showcase_card_battery",
Badge::severe(Lc::t("showcase_card_low", &LOC)),
));
// Barra de acciones de una nota, con botones de estilo enlace. Su propio relleno ya los separa,
// así que la fila no añade hueco entre ellos.
let mut actions = row().with_gap(align::Gap::Both(UnitValue::Zero));
for (source, key) in [
(Pencil, "showcase_edit"),
(Tag, "showcase_tag"),
(Eye, "showcase_view"),
(Chat, "showcase_comment_action"),
(Bell, "showcase_notify"),
(Pin, "showcase_pin"),
(EyeOff, "showcase_hide"),
] {
actions = actions.with_child(icon_button(source.into(), key, button::Style::Link));
}
// Grupos de formato de texto, con botones pequeños de contorno.
let format_group = |items: &[(ShowcaseIcon, &'static str)]| {
let mut group = Flex::new().with_gap(align::Gap::Both(UnitValue::RelRem(0.25)));
for (source, key) in items {
group = group.with_child(
icon_button(
(*source).into(),
key,
button::Style::Outline(Intent::Neutral),
)
.with_size(button::Size::Small),
);
}
group
};
let format = row()
.with_child(format_group(&[
(AlignLeft, "showcase_align_left"),
(AlignCenter, "showcase_align_center"),
(AlignRight, "showcase_align_right"),
(AlignJustify, "showcase_align_justify"),
]))
.with_child(format_group(&[
(Bold, "showcase_bold"),
(Italic, "showcase_italic"),
(Underline, "showcase_underline"),
]));
// Botones con icono y texto: al principio, al final o a los dos lados de la etiqueta.
let mut buttons = row();
for (start, key, end, style) in [
(
Some(icon::Source::from(icon::Core::Plus)),
"showcase_new",
None::<icon::Source>,
button::Style::Solid(Intent::Primary),
),
(
Some(Search.into()),
"showcase_search",
None,
button::Style::Outline(Intent::Primary),
),
(
Some(Filter.into()),
"showcase_filter",
None,
button::Style::Outline(Intent::Neutral),
),
(
Some(Image.into()),
"showcase_insert_image",
None,
button::Style::Outline(Intent::Neutral),
),
(
Some(icon::Core::Check.into()),
"showcase_save",
None,
button::Style::Solid(Intent::Success),
),
(
Some(icon::Core::Close.into()),
"showcase_discard",
None,
button::Style::Outline(Intent::Severe),
),
(
None,
"showcase_next",
Some(icon::Core::ChevronRight.into()),
button::Style::Outline(Intent::Primary),
),
(
Some(Folder.into()),
"showcase_move_to",
Some(icon::Core::ChevronDown.into()),
button::Style::Outline(Intent::Neutral),
),
] {
buttons = buttons.with_child(
Button::plain(Lc::t(key, &LOC))
.with_style(style)
.with_icon_start(start.map(Icon::with))
.with_icon_end(end.map(Icon::with)),
);
}
// Menú vertical, como una barra lateral, y menú desplegable de acciones. Las opciones sin icono
// dejan su hueco para que las etiquetas queden alineadas; el icono final va junto al borde.
let sidebar = Nav::new()
.with_layout(nav::Layout::Vertical)
.with_prop(FlexItem::new().with_size(flex::ItemSize::Custom(UnitValue::RelRem(14.0))))
.with_item(
nav::Item::link(Lc::t("showcase_nav_start", &LOC), "#")
.with_icon_start(Icon::with(Lightbulb)),
)
.with_item(
nav::Item::link(Lc::t("showcase_nav_styles", &LOC), "#")
.with_icon_start(Icon::with(Pencil)),
)
.with_item(nav::Item::link(Lc::t("showcase_nav_grid", &LOC), "#"))
.with_item(
nav::Item::link(Lc::t("showcase_nav_folders", &LOC), "#")
.with_icon_start(Icon::with(Folder))
.with_icon_end(Icon::with(icon::Core::ChevronRight)),
)
.with_item(
nav::Item::link(Lc::t("showcase_nav_templates", &LOC), "#")
.with_disabled(true)
.with_icon_start(Icon::with(File))
.with_icon_end(Icon::with(Pin)),
);
let actions_menu = Dropdown::new()
.with_title(Lc::t("showcase_actions", &LOC))
.with_button_style(button::Style::Outline(Intent::Neutral))
.with_item(
dropdown::Item::button(Lc::t("showcase_edit", &LOC))
.with_icon_start(Icon::with(Pencil)),
)
.with_item(
dropdown::Item::button(Lc::t("showcase_tag", &LOC)).with_icon_start(Icon::with(Tag)),
)
.with_item(dropdown::Item::button(Lc::t("showcase_duplicate", &LOC)))
.with_item(
dropdown::Item::button(Lc::t("showcase_pin", &LOC))
.with_icon_start(Icon::with(Pin))
.with_icon_end(Icon::with(icon::Core::Check)),
)
.with_item(dropdown::Item::divider())
.with_item(
dropdown::Item::button(Lc::t("showcase_delete", &LOC))
.with_icon_start(Icon::with(icon::Core::Close).with_intent(Intent::Severe)),
);
let menus = Flex::new()
.with_wrap(flex::Behavior::Wrap)
.with_align(align::Items::Start)
.with_gap(align::Gap::Both(UnitValue::RelRem(2.0)))
.with_prop(Margin::new().with_bottom(UnitValue::RelRem(1.5)))
.with_child(sidebar)
.with_child(actions_menu);
// Tabla con el tipo de cada fila en un icono y las acciones como botones sólo con icono.
let mut files = Table::new()
.with_column(Lc::t("showcase_col_name", &LOC))
.with_column(Lc::t("showcase_col_type", &LOC))
.with_column(Lc::t("showcase_col_actions", &LOC));
for (name, folder) in [
("Backgrounds", true),
("Shadows", true),
("Document.txt", false),
("Projects.draft", false),
] {
let (source, kind) = match folder {
true => (Folder, "showcase_type_folder"),
false => (File, "showcase_type_document"),
};
files.alter_row(
table::Row::new()
.with_cell(table::Cell::new(
Flex::new()
.with_align(align::Items::Center)
.with_gap(align::Gap::Both(UnitValue::RelRem(0.5)))
.with_child(Icon::with(source).with_intent(Intent::Neutral))
.with_child(Lc::n(name)),
))
.with_cell(Lc::t(kind, &LOC))
.with_cell(table::Cell::new(
Flex::new()
.with_child(icon_button(
Eye.into(),
"showcase_view",
button::Style::Link,
))
.with_child(icon_button(
Pencil.into(),
"showcase_edit",
button::Style::Link,
))
.with_child(icon_button(
icon::Core::Close.into(),
"showcase_delete",
button::Style::Link,
)),
)),
);
}
Block::new()
.with_title(Lc::t("showcase_block_icons", &LOC))
.with_child(caption("showcase_icons_sizes"))
.with_child(sizes)
.with_child(colors)
.with_child(caption("showcase_icons_cards"))
.with_child(cards)
.with_child(caption("showcase_icons_toolbar"))
.with_child(actions)
.with_child(format)
.with_child(caption("showcase_icons_buttons"))
.with_child(buttons)
.with_child(caption("showcase_icons_menus"))
.with_child(menus)
.with_child(caption("showcase_icons_table"))
.with_child(files)
}
// Un recuadro de acceso por color de acento, en la rejilla habitual de una portada (una, dos y tres
// columnas). Alternan los casos: con la imagen de fondo que trae PageTop para `Intro` (difuminada
// bajo el color) o sólo con el color, y con o sin descripción. Al final, uno sin icono y otro
// deshabilitado.
fn tiles_block() -> Block {
use Accent::*;
let tracks = |n| grid::Tracks::repeat(n, grid::AxisTrack::Fraction(1.0));
let mut grid = Grid::new()
.with_columns(tracks(1))
.with_columns_at(Breakpoint::Md, tracks(2))
.with_columns_at(Breakpoint::Lg, tracks(3))
.with_gap(align::Gap::Both(UnitValue::RelRem(1.5)));
let accents = [
(Blue, "Blue", Icon::with(ShowcaseIcon::Folder)),
(Orange, "Orange", Icon::with(ShowcaseIcon::Image)),
(Green, "Green", Icon::with(ShowcaseIcon::CheckCircle)),
(Purple, "Purple", Icon::with(ShowcaseIcon::Lightbulb)),
(Red, "Red", Icon::with(ShowcaseIcon::AlertCircle)),
(Teal, "Teal", Icon::with(ShowcaseIcon::Tag)),
(Indigo, "Indigo", Icon::with(ShowcaseIcon::Chat)),
(Pink, "Pink", Icon::with(ShowcaseIcon::Bell)),
(Yellow, "Yellow", Icon::with(ShowcaseIcon::Pin)),
(Cyan, "Cyan", Icon::with(ShowcaseIcon::Plug)),
(Lime, "Lime", Icon::with(ShowcaseIcon::Eye)),
(Magenta, "Magenta", Icon::with(ShowcaseIcon::Search)),
];
for (i, (accent, name, icon)) in accents.into_iter().enumerate() {
let tile = Tile::link(Lc::n(name), "#")
.with_icon(icon)
.with_accent(accent);
grid = grid.with_child(match i % 3 {
0 => tile
.with_description(Lc::t("showcase_tile_image", &LOC))
.with_image(image::Source::plain("/pagetop/img/intro-header-sm.jpg")),
1 => tile.with_description(Lc::t("showcase_tile_color", &LOC)),
_ => tile,
});
}
grid = grid.with_child(
Tile::link(Lc::n("Gray"), "#")
.with_description(Lc::t("showcase_tile_no_icon", &LOC))
.with_accent(Gray),
);
grid = grid.with_child(
Tile::link(Lc::n("Disabled"), "#")
.with_description(Lc::t("showcase_tile_disabled", &LOC))
.with_icon(Icon::with(ShowcaseIcon::EyeOff))
.with_disabled(true),
);
Block::new()
.with_title(Lc::t("showcase_block_tiles", &LOC))
.with_child(grid)
}
// Enlaces, insignias, paginación y mensajes, que también toman los colores del tema.
fn misc_block() -> Block {
let mut badges = Flex::new()

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 {
@ -533,3 +590,119 @@ fieldset > legend {
@extend .alert;
@extend .alert-danger;
}
// Accent colors (`Accent`): every component that takes one adds the same `accent-<color>` class,
// which sets --bootsier-accent to the Bootstrap color of the same name (lime and magenta are added
// by Bootsier, see _bootsier-variables.scss). The styles of each component only read that variable.
// Quoted: unquoted, Sass reads names such as `yellow` or `cyan` as colors, not as text.
@each $name in "blue", "indigo", "purple", "magenta", "pink", "red", "orange", "yellow", "lime",
"green", "teal", "cyan", "gray" {
.accent-#{$name} {
--bootsier-accent: var(--bs-#{$name});
}
}
// Access tiles (Tile): a large link with white text over its accent color and, when it has one, a
// blurred background image. The image goes below a veil of the accent color (from translucent to
// darkened), so the text keeps its contrast whatever the picture. The icon stays at the top and the
// texts at the bottom (also without an icon), so the icons of a row line up whatever the length of
// the descriptions.
.tile {
// The accent of the tile (`accent-<color>`, see above), with a fallback.
--tile-accent: var(--bootsier-accent, var(--bs-primary));
position: relative;
isolation: isolate;
display: flex;
flex-direction: column;
min-height: 11rem;
padding: $spacer * 1.5;
overflow: hidden;
color: $white;
text-decoration: none;
background-color: var(--tile-accent);
border-radius: var(--bs-border-radius-xl);
box-shadow: var(--bs-box-shadow-sm);
transition: transform .2s ease, box-shadow .2s ease;
&::before {
content: "";
position: absolute;
inset: 0;
z-index: -1;
background: linear-gradient(
135deg,
color-mix(in srgb, var(--tile-accent) 75%, transparent),
color-mix(in srgb, var(--tile-accent) 55%, #000)
);
}
// Scaled up a little so that the blur does not leave light edges.
> .tile-image {
position: absolute;
inset: 0;
z-index: -2;
width: 100%;
height: 100%;
object-fit: cover;
filter: blur(3px) saturate(80%);
transform: scale(1.08);
transition: transform .4s ease;
}
&:hover,
&:focus-visible {
color: $white;
transform: translateY(-.25rem);
box-shadow: var(--bs-box-shadow);
> .tile-image {
transform: scale(1.15);
}
}
&:focus-visible {
outline: 3px solid var(--tile-accent);
outline-offset: 3px;
}
// Disabled (`Tile::with_disabled()`): dimmed, without a link and without reacting to the pointer.
&.disabled {
pointer-events: none;
opacity: $btn-disabled-opacity;
box-shadow: none;
}
@media (prefers-reduced-motion: reduce) {
&,
> .tile-image {
transition: none;
}
}
}
.tile-body {
flex-grow: 1;
display: flex;
flex-direction: column;
justify-content: flex-end;
gap: $spacer * .25;
text-shadow: 0 1px 3px rgba($black, .4);
}
.tile-icon {
margin-bottom: auto;
padding-bottom: $spacer;
font-size: 2.5rem;
line-height: 1;
}
.tile-title {
font-size: $h4-font-size;
font-weight: $font-weight-semibold;
line-height: $headings-line-height;
}
.tile-description {
font-size: .9375rem;
opacity: .9;
}

View file

@ -22,6 +22,11 @@ $info: #4cb5c4; // Teal of the screens in the Intro illustration.
$light: #fff1db; // Cream of the Intro blocks.
$dark: #1a202c; // Text color of Intro.
// Accent colors (`Accent`) that Bootstrap lacks, added to its $colors map in bootsier.scss so that
// they get their own --bs-lime and --bs-magenta like the others. Same tones as in Basic.
$lime: #65a30d;
$magenta: #c026d3;
// Filled form fields: text fields, dropdowns and checks take a gray background, one for each color
// mode (--bootsier-input-bg, declared in _bootsier-custom.scss), and the same color as their
// border, which only shows when it changes color (validation). Checked checks already take the

View file

@ -16,6 +16,12 @@
@import "bootstrap-5.3.8/scss/mixins";
@import "bootstrap-5.3.8/scss/utilities";
// Bootsier additions to the Bootstrap maps
// ---------------------------------------------------
// The accent colors that Bootstrap lacks (see _bootsier-variables.scss). Only `root` uses $colors,
// to declare the --bs-* variables, so they must be added before importing it.
$colors: map-merge($colors, ("lime": $lime, "magenta": $magenta));
// Bootstrap Layout & components
// No "grid": page layout comes from PageTop's own Flex and Grid components.
@import "bootstrap-5.3.8/scss/root";

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)]
@ -85,6 +92,9 @@ pub use pagetop::base::component::table;
#[doc(inline)]
pub use table::Table;
// Tile.
pub use pagetop::base::component::Tile;
// Theme toggle.
mod theme_toggle;
pub use theme_toggle::theme_toggle;

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

@ -42,7 +42,7 @@ pub(crate) const EXTRA_IN_NAVBAR: &str = "bootsier.nav.in_navbar";
/// bs::dropdown::Item::link(Lc::n("Another"), "/another"),
/// ])),
/// ))
/// .with_item(bs::nav::Item::link_disabled(Lc::n("Disabled"), "#"));
/// .with_item(bs::nav::Item::link(Lc::n("Disabled"), "#").with_disabled(true));
/// ```
#[builder_impl]
pub trait NavBsExt {
@ -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

@ -74,7 +74,7 @@ const EXTRA_LAYOUT: &str = "bootsier.navbar.layout";
/// Lc::n("Reports"), "/tools/reports")
/// )
/// ))
/// .with_item(bs::nav::Item::link_disabled(Lc::n("Disabled"), "#"))
/// .with_item(bs::nav::Item::link(Lc::n("Disabled"), "#").with_disabled(true))
/// ));
/// ```
///

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}");
}

View file

@ -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
// (ver `logout_post`, que responde con `HX-Redirect` a las peticiones htmx).
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()));
let mut menu = Dropdown::new()
.with_title(title)
.with_menu_end(true)
.with_item(dropdown::Item::link(
Lc::t("menu-profile", &LOCALES_USER),
cx.route(PROFILE_PATH),
));
.with_item(
dropdown::Item::link(Lc::t("menu-profile", &LOCALES_USER), cx.route(PROFILE_PATH))
.with_icon_start(Icon::with(icon::Core::Person)),
);
if can_access_admin(cx) {
menu = menu.with_item(dropdown::Item::link(
Lc::t("menu-admin", &LOCALES_USER),
cx.route(admin_path("")),
));
menu = menu.with_item(
dropdown::Item::link(Lc::t("menu-admin", &LOCALES_USER), cx.route(admin_path("")))
.with_icon_start(Icon::with(icon::Core::Gear)),
);
}
nav.with_item(nav::Item::dropdown(
menu.with_item(dropdown::Item::divider()).with_item(logout),

View file

@ -343,7 +343,8 @@ fn declare_admin_pages(bag: &mut AdminPageBag) {
Lc::t("title-admin-users", &LOCALES_USER),
&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(
AdminPage::new(
@ -353,7 +354,8 @@ fn declare_admin_pages(bag: &mut AdminPageBag) {
&permission::UserPermission::AdminRoles,
)
.with_description(Lc::t("description-admin-roles", &LOCALES_USER))
.with_weight(10),
.with_weight(10)
.with_icon(Icon::with(icon::Core::Shield)),
);
bag.add(
AdminPage::new(
@ -363,7 +365,8 @@ fn declare_admin_pages(bag: &mut AdminPageBag) {
&permission::UserPermission::AdminPermissions,
)
.with_description(Lc::t("description-admin-permissions", &LOCALES_USER))
.with_weight(20),
.with_weight(20)
.with_icon(Icon::with(icon::Core::Key)),
);
}

View file

@ -2,6 +2,7 @@ use crate::auth::{PermissionRef, PermissionRegistry, has_permission};
use crate::base::action::admin::{
DeclareAdminActions, DeclareAdminPages, DeclareAdminSections, DeclareAdminTasks,
};
use crate::base::component::{Icon, icon};
use crate::core::component::{Context, Contextual};
use crate::locale::Lc;
use crate::{Getters, Weight, builder_impl, trace, util};
@ -36,6 +37,8 @@ pub struct AdminSection {
/// Devuelve el peso para ordenar las secciones (menor = antes).
#[getters(copy)]
weight: Weight,
/// Devuelve el icono que acompaña al título en la navegación (si lo tiene).
icon: Option<Icon>,
}
#[builder_impl]
@ -48,6 +51,7 @@ impl AdminSection {
key,
title,
weight: 0,
icon: None,
}
}
@ -70,6 +74,13 @@ impl AdminSection {
self.weight = weight;
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 >**********************************************************************************
@ -104,6 +115,8 @@ pub struct AdminPage {
/// ([`Routes::admin_route()`](crate::web::Routes::admin_route)).
#[getters(copy)]
permission: PermissionRef,
/// Devuelve el icono que acompaña al título en la navegación (si lo tiene).
icon: Option<Icon>,
}
#[builder_impl]
@ -126,6 +139,7 @@ impl AdminPage {
description: Lc::none(),
weight: 0,
permission,
icon: None,
}
}
@ -149,6 +163,16 @@ impl AdminPage {
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 >**********************************************************************
/// 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.
fn default_sections() -> Vec<AdminSection> {
[
("people", "admin_section_people", 10),
("structure", "admin_section_structure", 20),
("config", "admin_section_config", 30),
("reports", "admin_section_reports", 40),
("help", "admin_section_help", 50),
]
#[rustfmt::skip]
let sections = [
("people", "admin_section_people", 10, icon::Core::People),
("structure", "admin_section_structure", 20, icon::Core::Layers),
("config", "admin_section_config", 30, icon::Core::Sliders),
("reports", "admin_section_reports", 40, icon::Core::BarChart),
("help", "admin_section_help", 50, icon::Core::QuestionCircle),
];
sections
.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()
}

View file

@ -43,6 +43,10 @@ pub use grid::Grid;
mod html;
pub use html::Html;
pub mod icon;
#[doc(inline)]
pub use icon::Icon;
pub mod image;
#[doc(inline)]
pub use image::Image;
@ -77,3 +81,6 @@ pub use poweredby::PoweredBy;
pub mod table;
#[doc(inline)]
pub use table::Table;
mod tile;
pub use tile::Tile;

View file

@ -8,6 +8,7 @@ use crate::prelude::*;
/// - [`Button::reset()`]: botón de restablecimiento de valores.
/// - [`Button::plain()`]: botón genérico sin comportamiento predeterminado.
/// - [`Button::anchor()`]: enlace de navegación real con el aspecto de un botón.
/// - [`Button::anchor_blank()`]: igual, pero se abre en una nueva ventana o pestaña.
///
/// No confundir [`Button::anchor()`] con [`button::Style::Link`]: el primero renderiza un `<a
/// href=...>` real que navega; el segundo es sólo un estilo visual (clase `button-link`) que se
@ -25,6 +26,12 @@ use crate::prelude::*;
/// let cancel = Button::plain(Lc::n("Cancel"));
/// let clear = Button::reset(Lc::n("Clear"));
/// 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
@ -56,12 +63,18 @@ pub struct Button {
value: AttrValue,
/// Devuelve la etiqueta del botón.
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`).
title: Lc,
/// Devuelve la ruta de destino cuando el botón se renderiza como enlace de navegación
/// (`<a href=...>` en vez de `<button>`). Vacía por defecto: en ese caso `prepare()` renderiza
/// un `<button>` normal, ignorando este campo.
href: Route,
/// Devuelve si el enlace se abre en una nueva ventana o pestaña (sólo con una ruta de destino).
blank: bool,
/// Devuelve si el botón recibe el foco automáticamente al cargar la página.
autofocus: bool,
/// Devuelve si el botón está deshabilitado.
@ -102,9 +115,37 @@ impl Component for Button {
if *self.disabled() {
self.alter_prop(PropsOp::add_classes("disabled"));
}
// Por `Props` y no en el `<a>` de `prepare()`: un atributo escrito en el elemento omite el
// mismo atributo de `Props`, y se perdería un `target` añadido con `with_prop()`.
if *self.blank() && !*self.disabled() && self.href().try_resolve(cx).is_some() {
self.alter_prop(PropsOp::set("target", "_blank"));
self.alter_prop(PropsOp::set("rel", "noopener noreferrer"));
}
}
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) {
let disabled = *self.disabled();
let href = (!disabled).then_some(route);
@ -120,7 +161,7 @@ impl Component for Button {
aria-disabled=[aria_disabled]
tabindex=[tabindex]
{
(self.label().using(cx))
(content)
}
});
}
@ -135,7 +176,7 @@ impl Component for Button {
autofocus[*self.autofocus()]
disabled[*self.disabled()]
{
(self.label().using(cx))
(content)
}
})
}
@ -196,6 +237,15 @@ impl Button {
}
}
/// Crea un **enlace de navegación** con el aspecto de un botón que se abre en una nueva ventana
/// o pestaña. Ver [`Button::anchor()`].
pub fn anchor_blank(label: Lc, route: impl Into<Route>) -> Self {
Self {
blank: true,
..Self::anchor(label, route)
}
}
// **< Button BUILDER >*************************************************************************
/// Establece el identificador único del componente; igual a `with_prop(PropsOp::set_id(id))`.
@ -252,6 +302,26 @@ impl Button {
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).
pub fn with_title(mut self, title: Lc) -> Self {
self.title = title;

View file

@ -41,6 +41,9 @@ pub enum ItemKind {
/// 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ú.
///
/// 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`]).
/// 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)).
@ -50,6 +53,10 @@ pub struct Item {
props: Props,
/// Devuelve el tipo de elemento representado.
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]
@ -70,13 +77,15 @@ impl Component for Item {
}
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() {
ItemKind::Void => html! {},
ItemKind::Label(label) => html! {
li (self.props().unpack(cx)) {
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]
tabindex=[tabindex]
{
(label.using(cx))
(start) (label.using(cx)) (end)
}
}
}
@ -141,7 +150,7 @@ impl Component for Item {
aria-disabled=[aria_disabled]
disabled=[disabled_attr]
{
(label.using(cx))
(start) (label.using(cx)) (end)
}
}
}
@ -189,19 +198,6 @@ impl Item {
}
}
/// Crea un enlace deshabilitado que no permite la interacción.
pub fn link_disabled(label: Lc, route: impl Into<Route>) -> Self {
Self {
item_kind: ItemKind::Link {
label,
route: route.into(),
blank: false,
disabled: true,
},
..Default::default()
}
}
/// Crea un enlace que se abre en una nueva ventana o pestaña.
pub fn link_blank(label: Lc, route: impl Into<Route>) -> Self {
Self {
@ -215,19 +211,6 @@ impl Item {
}
}
/// Crea un enlace inicialmente deshabilitado que se abriría en una nueva ventana.
pub fn link_blank_disabled(label: Lc, route: impl Into<Route>) -> Self {
Self {
item_kind: ItemKind::Link {
label,
route: route.into(),
blank: true,
disabled: true,
},
..Default::default()
}
}
/// Crea un botón de acción local, sin navegación asociada.
pub fn button(label: Lc) -> Self {
Self {
@ -239,17 +222,6 @@ impl Item {
}
}
/// Crea un botón deshabilitado.
pub fn button_disabled(label: Lc) -> Self {
Self {
item_kind: ItemKind::Button {
label,
disabled: true,
},
..Default::default()
}
}
/// Crea un encabezado para un grupo de elementos dentro del menú.
pub fn header(label: Lc) -> Self {
Self {
@ -279,4 +251,41 @@ impl Item {
self.props.alter_prop(op);
self
}
/// Establece si el elemento está deshabilitado: se muestra atenuado y no permite la
/// interacción. Sólo se aplica a los enlaces y los botones; en los demás tipos no tiene efecto.
pub fn with_disabled(mut self, disabled: bool) -> Self {
if let ItemKind::Link { disabled: d, .. } | ItemKind::Button { disabled: d, .. } =
&mut self.item_kind
{
*d = disabled;
}
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
}
}

View 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;

View 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
}
}

View 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)
}
}

View 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())
}
}

View file

@ -77,6 +77,8 @@ pub struct Intro {
slogan: Lc,
/// Devuelve el botón de llamada a la acción, si existe.
button: Option<(Lc, Route)>,
/// Devuelve si el botón de llamada a la acción se abre en una nueva ventana o pestaña.
button_blank: bool,
/// Devuelve el tipo de introducción, fijado al construirla.
kind: intro::Kind,
/// Devuelve el ancho máximo del área de contenidos.
@ -93,6 +95,7 @@ impl Default for Intro {
title: Lc::l("intro_default_title"),
slogan: Lc::l("intro_default_slogan").with_arg("app", &global::SETTINGS.app.name),
button: Some((Lc::l("intro_default_button"), BUTTON_LINK.into())),
button_blank: true,
kind: intro::Kind::default(),
width: intro::Width::default(),
children: Children::default(),
@ -160,8 +163,8 @@ impl Component for Intro {
a
class="intro-button-link"
href=(lnk.resolve(cx))
target="_blank"
rel="noopener noreferrer"
target=[self.button_blank().then_some("_blank")]
rel=[self.button_blank().then_some("noopener noreferrer")]
{
span {} span {} span {}
div class="intro-button-text" {
@ -276,12 +279,15 @@ impl Intro {
self
}
/// Configura el botón opcional de llamada a la acción.
/// Configura el botón opcional de llamada a la acción, que se abre en la misma ventana.
///
/// - Usa `Some((texto, ruta))` para mostrarlo, donde [`Route`] resuelve la ruta o URL final al
/// pulsar el botón según el contexto de renderizado.
/// - Usa `None` para ocultarlo.
///
/// Para abrirlo en una nueva ventana o pestaña se usa
/// [`with_button_blank()`](Self::with_button_blank).
///
/// # Ejemplo
///
/// ```rust,no_run
@ -293,6 +299,24 @@ impl Intro {
/// ```
pub fn with_button(mut self, button: impl Into<Option<(Lc, Route)>>) -> Self {
self.button = button.into();
self.button_blank = false;
self
}
/// Configura el botón opcional de llamada a la acción, que se abre en una nueva ventana o
/// pestaña. Es el de la introducción por defecto, que lleva a la web de PageTop. Ver
/// [`with_button()`](Self::with_button).
///
/// # Ejemplo
///
/// ```rust,no_run
/// # use pagetop::prelude::*;
/// let intro = Intro::default()
/// .with_button_blank(Some((Lc::n("Docs"), "https://docs.rs/pagetop".into())));
/// ```
pub fn with_button_blank(mut self, button: impl Into<Option<(Lc, Route)>>) -> Self {
self.button = button.into();
self.button_blank = true;
self
}

View file

@ -25,7 +25,7 @@ use crate::prelude::*;
/// .with_item(dropdown::Item::link(Lc::n("Action"), "/action"))
/// .with_item(dropdown::Item::link(Lc::n("Another"), "/another")),
/// ))
/// .with_item(nav::Item::link_disabled(Lc::n("Disabled"), "#"));
/// .with_item(nav::Item::link(Lc::n("Disabled"), "#").with_disabled(true));
/// ```
#[derive(AutoDefault, Clone, Debug, Getters)]
pub struct Nav {
@ -149,7 +149,10 @@ impl Nav {
fn add_admin_items(&mut self, cx: &Context) {
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() {
let mut pages = registry
.pages_for_section(section.key())
@ -161,12 +164,12 @@ impl Nav {
}
let mut menu = Dropdown::new().with_title(section.title().clone());
for page in pages {
menu = menu.with_item(dropdown::Item::link(
page.title().clone(),
admin_path(page.path()),
));
menu = menu.with_item(
dropdown::Item::link(page.title().clone(), 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()));
}
}
}
@ -234,7 +237,7 @@ impl Nav {
/// nav.with_item(nav::Item::link("Inicio", "/"));
/// nav.with_item(TypedOp::AddMany(vec![
/// nav::Item::link(...),
/// nav::Item::link_disabled(...),
/// nav::Item::link(...).with_disabled(true),
/// ]));
/// ```
pub fn with_item(mut self, op: impl Into<TypedOp<nav::Item>>) -> Self {

View file

@ -53,6 +53,10 @@ impl ItemKind {
/// 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ú.
///
/// 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`]).
#[derive(AutoDefault, Clone, Debug, Getters)]
pub struct Item {
@ -67,6 +71,10 @@ pub struct Item {
/// permite otros criterios, como marcar activa una sección mientras la ruta actual sea
/// cualquiera de sus subrutas.
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]
@ -91,13 +99,15 @@ impl Component for Item {
}
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() {
ItemKind::Void => html! {},
ItemKind::Label(label) => html! {
li (self.props().unpack(cx)) {
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-disabled=[aria_disabled]
{
(label.using(cx))
(start) (label.using(cx)) (end)
}
}
}
@ -170,7 +180,7 @@ impl Component for Item {
aria-haspopup="true"
aria-expanded="false"
{
(title)
(start) (title) (end)
}
ul class=(dd.menu_classes()) {
(items)
@ -212,19 +222,6 @@ impl Item {
}
}
/// Crea un enlace deshabilitado que no permite la interacción.
pub fn link_disabled(label: Lc, route: impl Into<Route>) -> Self {
Self {
item_kind: ItemKind::Link {
label,
route: route.into(),
blank: false,
disabled: true,
},
..Default::default()
}
}
/// Crea un enlace que se abre en una nueva ventana o pestaña.
pub fn link_blank(label: Lc, route: impl Into<Route>) -> Self {
Self {
@ -238,19 +235,6 @@ impl Item {
}
}
/// Crea un enlace inicialmente deshabilitado que se abriría en una nueva ventana.
pub fn link_blank_disabled(label: Lc, route: impl Into<Route>) -> Self {
Self {
item_kind: ItemKind::Link {
label,
route: route.into(),
blank: true,
disabled: true,
},
..Default::default()
}
}
/// Crea un elemento con contenido HTML arbitrario.
///
/// El contenido se renderiza tal cual lo devuelve el componente [`Html`], dentro de un `<li>`
@ -289,6 +273,42 @@ impl Item {
self
}
/// Establece si el elemento está deshabilitado: se muestra atenuado y no permite la
/// interacción. Sólo se aplica a los enlaces; en los demás tipos no tiene efecto.
pub fn with_disabled(mut self, disabled: bool) -> Self {
if let ItemKind::Link { disabled: d, .. } = &mut self.item_kind {
*d = disabled;
}
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
/// automática por coincidencia exacta de ruta.
pub fn with_active(mut self, active: impl Into<Option<bool>>) -> Self {

View file

@ -57,7 +57,7 @@ use crate::prelude::*;
/// .with_item(dropdown::Item::link(Lc::n("Generator"), "/tools/gen"))
/// .with_item(dropdown::Item::link(Lc::n("Reports"), "/tools/reports")),
/// ))
/// .with_item(nav::Item::link_disabled(Lc::n("Disabled"), "#")),
/// .with_item(nav::Item::link(Lc::n("Disabled"), "#").with_disabled(true)),
/// ));
/// ```
///

204
src/base/component/tile.rs Normal file
View file

@ -0,0 +1,204 @@
use crate::prelude::*;
/// Componente para crear un **recuadro de acceso** (*tile*) a una sección.
///
/// Es un enlace grande con un título, una descripción breve opcional y un icono, pensado para la
/// portada de una aplicación o de una sección: varios recuadros dentro de un [`Grid`] forman un
/// panel de accesos. Cada uno lleva un color de acento ([`Accent`]) que lo distingue de los
/// demás y, opcionalmente, una imagen de fondo que el tema difumina bajo una capa de ese color
/// para que el texto se lea siempre bien. La imagen es decorativa: el enlace se nombra con el
/// título y la descripción.
///
/// Un recuadro no se renderiza si el usuario actual no puede acceder a su ruta (ver [`Endpoint`]),
/// así que un panel de accesos muestra a cada uno sólo lo que puede abrir. Para mostrar un acceso
/// que aún no se puede usar, se deshabilita con [`with_disabled()`](Self::with_disabled), y para
/// abrirlo en una nueva ventana o pestaña se crea con [`Tile::link_blank()`].
///
/// # Ejemplo
///
/// ```rust,no_run
/// # use pagetop::prelude::*;
/// let panel = Grid::new()
/// .with_columns(grid::Tracks::repeat(1, grid::AxisTrack::Fraction(1.0)))
/// .with_columns_at(
/// Breakpoint::Md,
/// grid::Tracks::repeat(2, grid::AxisTrack::Fraction(1.0)),
/// )
/// .with_columns_at(
/// Breakpoint::Lg,
/// grid::Tracks::repeat(3, grid::AxisTrack::Fraction(1.0)),
/// )
/// .with_gap(align::Gap::Both(UnitValue::RelRem(1.5)))
/// .with_child(
/// Tile::link(Lc::n("Orders"), "/orders")
/// .with_description(Lc::n("Check and process the orders"))
/// .with_icon(Icon::with(icon::Core::ChevronRight))
/// .with_image(image::Source::plain("/assets/img/orders.jpg"))
/// .with_accent(Accent::Orange),
/// );
/// ```
#[derive(AutoDefault, Clone, Debug, Getters)]
pub struct Tile {
/// Devuelve identificador, clases CSS, atributos HTML y valores extra del componente.
props: Props,
/// Devuelve la ruta a la que lleva el recuadro.
route: Route,
/// Devuelve el título del recuadro.
title: Lc,
/// Devuelve la descripción breve del recuadro (puede ser [`Lc::none()`]).
description: Lc,
/// Devuelve el icono del recuadro (si lo hay).
icon: Embed<Icon>,
/// Devuelve la imagen de fondo del recuadro (si la hay).
image: Embed<Image>,
/// Devuelve el color de acento del recuadro.
#[getters(copy)]
accent: Accent,
/// Devuelve si el recuadro se abre en una nueva ventana o pestaña.
blank: bool,
/// Devuelve si el recuadro está deshabilitado.
disabled: bool,
}
#[async_trait]
impl Component for Tile {
fn new() -> Self {
Self::default()
}
fn id(&self) -> Option<String> {
self.props.get_id()
}
fn is_renderable(&self, cx: &Context) -> bool {
self.route().is_accessible(cx)
}
fn setup(&mut self, cx: &mut Context) {
self.alter_prop(PropsOp::prepend_classes(util::join!(
"tile accent-",
self.accent().as_str()
)));
// Un `<a>` sin `href` (ver `prepare()`) no tiene un estado deshabilitado nativo.
if *self.disabled() {
self.alter_prop(PropsOp::add_classes("disabled"));
}
// Por `Props` y no en el `<a>` de `prepare()`: un atributo escrito en el elemento omite el
// mismo atributo de `Props`, y se perdería un `target` añadido con `with_prop()`.
if *self.blank() && !*self.disabled() && self.route().try_resolve(cx).is_some() {
self.alter_prop(PropsOp::set("target", "_blank"));
self.alter_prop(PropsOp::set("rel", "noopener noreferrer"));
}
if let Some(image) = self.image.get_mut() {
image.alter_prop(PropsOp::add_classes("tile-image"));
image.alter_alternative(Lc::none());
}
}
async fn prepare(&self, cx: &mut Context) -> Result<Markup, ComponentError> {
let disabled = *self.disabled();
// Deshabilitado, sin `href`: evita resolver la ruta para nada.
let href = (!disabled).then(|| self.route().try_resolve(cx)).flatten();
let image = self.image().render(cx).await;
let icon = self.icon().render(cx).await;
Ok(html! {
a
href=[href]
aria-disabled=[disabled.then_some("true")]
(self.props().unpack(cx))
{
(image)
span class="tile-body" {
@if self.icon().get().is_some() {
span class="tile-icon" { (icon) }
}
span class="tile-title" { (self.title().using(cx)) }
@if !self.description().is_none() {
span class="tile-description" { (self.description().using(cx)) }
}
}
}
})
}
}
#[builder_impl]
impl Tile {
/// Crea un recuadro con el título indicado que lleva a la ruta dada.
pub fn link(title: Lc, route: impl Into<Route>) -> Self {
Self {
route: route.into(),
title,
..Default::default()
}
}
/// Crea un recuadro con el título indicado que abre la ruta dada en una nueva ventana o
/// pestaña.
pub fn link_blank(title: Lc, route: impl Into<Route>) -> Self {
Self {
blank: true,
..Self::link(title, route)
}
}
// **< Tile 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
}
/// Establece la ruta a la que lleva el recuadro.
pub fn with_route(mut self, route: impl Into<Route>) -> Self {
self.route = route.into();
self
}
/// Establece el título del recuadro.
pub fn with_title(mut self, title: Lc) -> Self {
self.title = title;
self
}
/// Establece la descripción breve que se muestra bajo el título; [`Lc::none()`] la quita.
pub fn with_description(mut self, description: Lc) -> Self {
self.description = description;
self
}
/// Establece el icono que se muestra sobre el título, o lo quita con `None`.
pub fn with_icon(mut self, icon: impl Into<Option<Icon>>) -> Self {
self.icon.alter_component(icon);
self
}
/// Establece la imagen de fondo del recuadro, o la quita con `None`.
///
/// Admite directamente un [`image::Source`](crate::base::component::image::Source). La imagen
/// es decorativa: se renderiza sin texto alternativo, aunque la [`Image`] lo tenga, y el tema
/// la recorta para cubrir el recuadro. Sin imagen, el fondo es sólo el color de acento.
pub fn with_image(mut self, image: impl Into<Option<Image>>) -> Self {
self.image.alter_component(image);
self
}
/// Establece el color de acento del recuadro.
pub fn with_accent(mut self, accent: Accent) -> Self {
self.accent = accent;
self
}
/// Establece si el recuadro está deshabilitado: se muestra atenuado y sin enlace.
pub fn with_disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled;
self
}
}

View file

@ -95,7 +95,9 @@
//! ejemplo, uno basado en Bootstrap) debe traducir cada variante al nombre que le corresponda en
//! su paleta. Los componentes que generan clases CSS a partir de una [`Intent`] (`Button`,
//! `Badge`, `Dropdown`, etc.) consultan este método a través de [`Intent::color()`], así que la
//! clase resultante ya nace en la paleta del tema activo.
//! clase resultante ya nace en la paleta del tema activo. Los colores de acento ([`Accent`]), en
//! cambio, no pasan por el tema: el tema define en su CSS las clases `accent-<color>` que añaden
//! los componentes (como `Tile`) con los tonos de su paleta.
//! 6. **Reexportar, extender o añadir componentes**. Un tema puede reexportar tal cual los
//! componentes propios de PageTop que no requieran adaptación, extenderlos con un trait propio
//! para añadir métodos exclusivos (guardando su estado en valores extra con
@ -159,6 +161,9 @@
mod intent;
pub use intent::Intent;
mod accent;
pub use accent::Accent;
mod breakpoint;
pub use breakpoint::{Breakpoint, BreakpointEntry, Responsive};

69
src/core/theme/accent.rs Normal file
View file

@ -0,0 +1,69 @@
use crate::AutoDefault;
/// **Color de acento** de un componente visual.
///
/// A diferencia de [`Intent`](super::Intent), no tiene significado: sólo sirve para distinguir a la
/// vista unos elementos de otros (las secciones de una portada, las categorías de unas
/// etiquetas...).
///
/// Todos los componentes que lo admiten añaden la misma clase, `accent-<color>` (`accent-blue`,
/// `accent-orange`...; ver [`as_str()`](Self::as_str)), como hace
/// [`Tile`](crate::base::component::Tile). Cada tema define esas clases una sola vez: fijan una
/// variable CSS con el tono que el tema elige para ese color, y el estilo de cada componente sólo
/// lee esa variable. Basic usa `--val-color--accent` y Bootsier, `--bootsier-accent`.
///
/// Como cualquier variable CSS, se hereda: un elemento sin acento propio dentro de otro que lo
/// tiene toma el del contenedor. Por eso conviene que cada componente que admita un acento lo lleve
/// siempre (como `Tile`, azul por defecto) o lea la variable con un valor de reserva.
#[derive(AutoDefault, Clone, Copy, Debug, Eq, PartialEq)]
pub enum Accent {
/// Azul (por defecto).
#[default]
Blue,
/// Añil.
Indigo,
/// Morado.
Purple,
/// Magenta.
Magenta,
/// Rosa.
Pink,
/// Rojo.
Red,
/// Naranja.
Orange,
/// Amarillo.
Yellow,
/// Lima.
Lime,
/// Verde.
Green,
/// Verde azulado.
Teal,
/// Cian.
Cyan,
/// Gris.
Gray,
}
impl Accent {
/// Devuelve el nombre del color (`"blue"`, `"orange"`...), para componer las clases CSS de cada
/// componente.
pub const fn as_str(&self) -> &'static str {
match self {
Self::Blue => "blue",
Self::Indigo => "indigo",
Self::Purple => "purple",
Self::Magenta => "magenta",
Self::Pink => "pink",
Self::Red => "red",
Self::Orange => "orange",
Self::Yellow => "yellow",
Self::Lime => "lime",
Self::Green => "green",
Self::Teal => "teal",
Self::Cyan => "cyan",
Self::Gray => "gray",
}
}
}

View file

@ -28,12 +28,10 @@ fn grant_tools(_: &HttpRequest, perm: PermissionRef, granted: &mut bool) {
}
fn declare_pages(bag: &mut AdminPageBag) {
bag.add(AdminPage::new(
"config/export",
"config",
Lc::n("Export"),
&ToolsPermission,
));
bag.add(
AdminPage::new("config/export", "config", Lc::n("Export"), &ToolsPermission)
.with_icon(Icon::with(icon::Core::Plus)),
);
bag.add(AdminPage::new(
"reports/audit",
"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]
async fn the_admin_menu_only_shows_in_the_panel() {
let _ = Application::prepare(&Ext).await;

View file

@ -116,8 +116,8 @@ async fn button_without_href_renders_as_button_tag() {
#[pagetop::test]
async fn anchor_falls_back_to_button_when_href_is_reset() {
// `Route::default()` resuelve a una ruta vacía; `prepare()` debe ignorar `href` y volver a
// renderizar un `<button>`, tal y como documenta `Button::with_href()`.
// `Route::default()` resolves to an empty path; `prepare()` must ignore `href` and render a
// `<button>` again, as documented in `Button::with_href()`.
let mut button = Button::anchor(Lc::n("Edit"), "/items/1/edit").with_href(Route::default());
let html = button.render(&mut Context::default()).await.into_string();
@ -143,6 +143,25 @@ async fn disabled_anchor_omits_href_and_sets_aria_disabled() {
assert!(html.contains(r#"tabindex="-1""#));
}
#[pagetop::test]
async fn anchor_blank_opens_in_a_new_window() {
let mut button = Button::anchor(Lc::n("Docs"), "https://docs.rs");
let html = button.render(&mut Context::default()).await.into_string();
assert!(!html.contains("target="), "{html}");
let mut button = Button::anchor_blank(Lc::n("Docs"), "https://docs.rs");
let html = button.render(&mut Context::default()).await.into_string();
assert!(html.starts_with("<a "), "{html}");
assert!(html.contains(r#"target="_blank""#));
assert!(html.contains(r#"rel="noopener noreferrer""#));
// Disabled, it has no link to open.
let mut button = Button::anchor_blank(Lc::n("Docs"), "https://docs.rs").with_disabled(true);
let html = button.render(&mut Context::default()).await.into_string();
assert!(!html.contains("target="), "{html}");
assert!(!html.contains("rel="));
}
// A disabled `<a>` has no native equivalent to `:disabled` that CSS can hook into, unlike a
// `<button disabled>`; the `disabled` class is what both Basic (`.button.disabled`) and Bootsier
// (Bootstrap's own `.btn.disabled`) actually style.
@ -161,3 +180,12 @@ async fn disabled_button_also_gets_the_disabled_class() {
assert!(html.contains(r#"class="button disabled""#));
}
// `ListFilter` relies on this for its reset link (`target="_top"`).
#[pagetop::test]
async fn anchor_keeps_a_target_set_with_props() {
let mut button =
Button::anchor(Lc::n("Clear"), "/items").with_prop(PropsOp::set("target", "_top"));
let html = button.render(&mut Context::default()).await.into_string();
assert!(html.contains(r#"target="_top""#), "{html}");
}

View file

@ -193,3 +193,42 @@ async fn separators_are_also_cleaned_in_a_dropdown_inside_a_nav() {
assert!(!html.contains("dropdown-divider"), "{html}");
assert!(html.contains("item-shown"), "{html}");
}
// **< Disabled items >*****************************************************************************
async fn render_item(mut item: dropdown::Item) -> String {
item.render(&mut Context::default()).await.into_string()
}
#[pagetop::test]
async fn a_disabled_link_has_no_href() {
let html = render_item(dropdown::Item::link(Lc::n("Home"), "/").with_disabled(true)).await;
assert!(html.contains(r#"class="dropdown-item disabled""#), "{html}");
assert!(html.contains(r#"aria-disabled="true""#));
assert!(!html.contains("href="));
// Opening in a new window does not apply to a link that cannot be followed.
let html = render_item(
dropdown::Item::link_blank(Lc::n("Docs"), "https://docs.rs").with_disabled(true),
)
.await;
assert!(!html.contains("target="), "{html}");
let html = render_item(dropdown::Item::link(Lc::n("Home"), "/").with_disabled(false)).await;
assert!(html.contains(r#"href="/""#), "{html}");
assert!(!html.contains("disabled"));
}
#[pagetop::test]
async fn a_disabled_button_is_disabled() {
let html = render_item(dropdown::Item::button(Lc::n("Save")).with_disabled(true)).await;
assert!(html.contains(r#"aria-disabled="true""#), "{html}");
assert!(html.contains(r#" disabled"#));
}
#[pagetop::test]
async fn disabled_does_not_apply_to_labels() {
let label = render_item(dropdown::Item::label(Lc::n("Note"))).await;
let disabled = render_item(dropdown::Item::label(Lc::n("Note")).with_disabled(true)).await;
assert_eq!(label, disabled);
}

234
tests/component_icon.rs Normal file
View 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"));
}

45
tests/component_intro.rs Normal file
View file

@ -0,0 +1,45 @@
use pagetop::prelude::*;
async fn render(mut intro: Intro) -> String {
intro.render(&mut Context::default()).await.into_string()
}
// The opening tag of the call to action button.
fn button_link(html: &str) -> &str {
let start = html
.find(r#"<a class="intro-button-link""#)
.unwrap_or_else(|| panic!("the button is missing in {html}"));
let end = start + html[start..].find('>').expect("unclosed tag");
&html[start..=end]
}
#[pagetop::test]
async fn default_button_opens_in_a_new_window() {
let html = render(Intro::default()).await;
let link = button_link(&html);
assert!(
link.contains(r#"href="https://pagetop.cillero.es""#),
"{link}"
);
assert!(link.contains(r#"target="_blank""#));
assert!(link.contains(r#"rel="noopener noreferrer""#));
}
#[pagetop::test]
async fn button_opens_in_the_same_window() {
let html = render(Intro::default().with_button(Some((Lc::n("Start"), "/start".into())))).await;
let link = button_link(&html);
assert!(link.contains(r#"href="/start""#), "{link}");
assert!(!link.contains("target="));
assert!(!link.contains("rel="));
}
#[pagetop::test]
async fn button_blank_opens_in_a_new_window() {
let html =
render(Intro::custom().with_button_blank(Some((Lc::n("Docs"), "https://docs.rs".into()))))
.await;
let link = button_link(&html);
assert!(link.contains(r#"target="_blank""#), "{link}");
assert!(link.contains(r#"rel="noopener noreferrer""#));
}

42
tests/component_nav.rs Normal file
View file

@ -0,0 +1,42 @@
use pagetop::prelude::*;
async fn render_item(mut item: nav::Item) -> String {
item.render(&mut Context::default()).await.into_string()
}
#[pagetop::test]
async fn a_disabled_link_has_no_href() {
let html = render_item(nav::Item::link(Lc::n("Shop"), "/shop").with_disabled(true)).await;
assert!(html.contains(r#"class="nav-link disabled""#), "{html}");
assert!(html.contains(r#"aria-disabled="true""#));
assert!(!html.contains("href="));
// Opening in a new window does not apply to a link that cannot be followed.
let html =
render_item(nav::Item::link_blank(Lc::n("Docs"), "https://docs.rs").with_disabled(true))
.await;
assert!(!html.contains("target="), "{html}");
assert!(!html.contains("rel="));
let html = render_item(nav::Item::link_blank(Lc::n("Docs"), "https://docs.rs")).await;
assert!(html.contains(r#"target="_blank""#), "{html}");
}
#[pagetop::test]
async fn disabled_can_be_turned_off() {
let html = render_item(
nav::Item::link(Lc::n("Shop"), "/shop")
.with_disabled(true)
.with_disabled(false),
)
.await;
assert!(html.contains(r#"href="/shop""#), "{html}");
assert!(!html.contains("disabled"));
}
#[pagetop::test]
async fn disabled_does_not_apply_to_labels() {
let label = render_item(nav::Item::label(Lc::n("Note"))).await;
let disabled = render_item(nav::Item::label(Lc::n("Note")).with_disabled(true)).await;
assert_eq!(label, disabled);
}

133
tests/component_tile.rs Normal file
View file

@ -0,0 +1,133 @@
use pagetop::prelude::*;
async fn render(mut tile: Tile) -> String {
tile.render(&mut Context::default()).await.into_string()
}
enum TestRoute {
Open,
Signed,
}
impl Endpoint for TestRoute {
fn path(&self) -> CowStr {
match self {
Self::Open => "/open".into(),
Self::Signed => "/signed".into(),
}
}
fn access(&self) -> Access {
match self {
Self::Open => Access::Public,
Self::Signed => Access::Authenticated,
}
}
}
#[pagetop::test]
async fn tile_is_a_link_with_its_title_and_accent() {
let html = render(Tile::link(Lc::n("Orders"), "/orders")).await;
assert!(
html.starts_with(r#"<a href="/orders" class="tile accent-blue">"#),
"{html}"
);
assert!(html.contains(r#"<span class="tile-title">Orders</span>"#));
assert!(html.ends_with("</a>"));
let html = render(Tile::link(Lc::n("Orders"), "/orders").with_accent(Accent::Orange)).await;
assert!(html.contains(r#"class="tile accent-orange""#));
}
#[pagetop::test]
async fn description_icon_and_image_are_optional() {
let html = render(Tile::link(Lc::n("Orders"), "/orders")).await;
assert!(!html.contains("tile-description"));
assert!(!html.contains("tile-icon"));
assert!(!html.contains("<img"));
let html = render(
Tile::link(Lc::n("Orders"), "/orders")
.with_description(Lc::n("Check the orders"))
.with_icon(Icon::with(icon::Core::Check))
.with_image(image::Source::plain("/img/orders.jpg")),
)
.await;
assert!(html.contains(r#"<span class="tile-description">Check the orders</span>"#));
assert!(html.contains(r#"<span class="tile-icon"><svg"#));
assert!(html.contains(r#"src="/img/orders.jpg""#));
assert!(html.contains(r#"class="image tile-image""#));
}
#[pagetop::test]
async fn background_image_is_decorative() {
let html = render(
Tile::link(Lc::n("Orders"), "/orders").with_image(image::Source::plain("/img/orders.jpg")),
)
.await;
assert!(html.contains(r#"alt="""#));
// Also when the image comes with an alternative text.
let html = render(
Tile::link(Lc::n("Orders"), "/orders").with_image(
Image::with(image::Source::plain("/img/orders.jpg"))
.with_alternative(Lc::n("Boxes in a warehouse")),
),
)
.await;
assert!(html.contains(r#"alt="""#), "{html}");
assert!(!html.contains("Boxes in a warehouse"));
}
#[pagetop::test]
async fn blank_tile_opens_in_a_new_window() {
let html = render(Tile::link(Lc::n("Docs"), "https://docs.rs")).await;
assert!(!html.contains("target="));
let html = render(Tile::link_blank(Lc::n("Docs"), "https://docs.rs")).await;
assert!(html.starts_with(r#"<a href="https://docs.rs" "#), "{html}");
assert!(html.contains(r#"target="_blank""#));
assert!(html.contains(r#"rel="noopener noreferrer""#));
// Disabled, it has no link to open.
let html = render(Tile::link_blank(Lc::n("Docs"), "https://docs.rs").with_disabled(true)).await;
assert!(!html.contains("target="));
assert!(!html.contains("rel="));
// Neither without a route.
let html = render(Tile::link_blank(Lc::n("Docs"), Route::default())).await;
assert!(!html.contains("target="), "{html}");
assert!(!html.contains("rel="));
}
#[pagetop::test]
async fn disabled_tile_has_no_link() {
let html = render(Tile::link(Lc::n("Orders"), "/orders").with_disabled(true)).await;
assert!(
html.starts_with(r#"<a aria-disabled="true" class="tile accent-blue disabled">"#),
"{html}"
);
assert!(!html.contains("href"));
}
#[pagetop::test]
async fn tile_is_only_shown_with_access_to_its_route() {
let html = render(Tile::link(Lc::n("Open"), TestRoute::Open)).await;
assert!(html.contains(r#"href="/open""#));
// Without a request nobody is signed in.
assert!(
render(Tile::link(Lc::n("Signed"), TestRoute::Signed))
.await
.is_empty()
);
}
#[pagetop::test]
async fn tile_keeps_a_target_set_with_props() {
let html =
render(Tile::link(Lc::n("Orders"), "/orders").with_prop(PropsOp::set("target", "_top")))
.await;
assert!(html.contains(r#"target="_top""#), "{html}");
}