✨ (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>`.
This commit is contained in:
Manuel Cillero 2026-11-23 02:59:42 +01:00
parent 4adb8cb1ec
commit ad80c09eff
13 changed files with 684 additions and 1 deletions

View file

@ -14,6 +14,9 @@
@use "basic/root"; @use "basic/root";
@use "basic/base"; @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 // Components, in alphabetical order. `buttons` must go before `dropdown` and `nav`, see the notes
// in `basic/_buttons.scss`. // in `basic/_buttons.scss`.
@use "basic/badge"; @use "basic/badge";
@ -34,6 +37,7 @@
@use "basic/navbar"; @use "basic/navbar";
@use "basic/pager"; @use "basic/pager";
@use "basic/table"; @use "basic/table";
@use "basic/tile";
// Theme regions. // Theme regions.
@use "basic/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

@ -17,6 +17,20 @@
--val-color--info: #0dcaf0; --val-color--info: #0dcaf0;
--val-color--warning: #ffc107; --val-color--warning: #ffc107;
--val-color--danger: #dc3545; --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 // Other Colors
--val-color--bg: #fafafa; --val-color--bg: #fafafa;
--val-color--bg--muted: #dee2e6; --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

@ -590,3 +590,119 @@ svg.icon {
@extend .alert; @extend .alert;
@extend .alert-danger; @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. $light: #fff1db; // Cream of the Intro blocks.
$dark: #1a202c; // Text color of Intro. $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 // 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 // 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 // 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/mixins";
@import "bootstrap-5.3.8/scss/utilities"; @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 // Bootstrap Layout & components
// No "grid": page layout comes from PageTop's own Flex and Grid components. // No "grid": page layout comes from PageTop's own Flex and Grid components.
@import "bootstrap-5.3.8/scss/root"; @import "bootstrap-5.3.8/scss/root";

View file

@ -92,6 +92,9 @@ pub use pagetop::base::component::table;
#[doc(inline)] #[doc(inline)]
pub use table::Table; pub use table::Table;
// Tile.
pub use pagetop::base::component::Tile;
// Theme toggle. // Theme toggle.
mod theme_toggle; mod theme_toggle;
pub use theme_toggle::theme_toggle; pub use theme_toggle::theme_toggle;

View file

@ -81,3 +81,6 @@ pub use poweredby::PoweredBy;
pub mod table; pub mod table;
#[doc(inline)] #[doc(inline)]
pub use table::Table; pub use table::Table;
mod tile;
pub use tile::Tile;

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 //! 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`, //! 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 //! `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 //! 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 //! 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 //! para añadir métodos exclusivos (guardando su estado en valores extra con
@ -159,6 +161,9 @@
mod intent; mod intent;
pub use intent::Intent; pub use intent::Intent;
mod accent;
pub use accent::Accent;
mod breakpoint; mod breakpoint;
pub use breakpoint::{Breakpoint, BreakpointEntry, Responsive}; 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",
}
}
}

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