✨ (pagetop): Añade métodos ..._blank()
This commit is contained in:
parent
f1fd34f974
commit
4adb8cb1ec
4 changed files with 121 additions and 5 deletions
|
|
@ -8,6 +8,7 @@ use crate::prelude::*;
|
||||||
/// - [`Button::reset()`]: botón de restablecimiento de valores.
|
/// - [`Button::reset()`]: botón de restablecimiento de valores.
|
||||||
/// - [`Button::plain()`]: botón genérico sin comportamiento predeterminado.
|
/// - [`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()`]: 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
|
/// 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
|
/// href=...>` real que navega; el segundo es sólo un estilo visual (clase `button-link`) que se
|
||||||
|
|
@ -72,6 +73,8 @@ pub struct Button {
|
||||||
/// (`<a href=...>` en vez de `<button>`). Vacía por defecto: en ese caso `prepare()` renderiza
|
/// (`<a href=...>` en vez de `<button>`). Vacía por defecto: en ese caso `prepare()` renderiza
|
||||||
/// un `<button>` normal, ignorando este campo.
|
/// un `<button>` normal, ignorando este campo.
|
||||||
href: Route,
|
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.
|
/// Devuelve si el botón recibe el foco automáticamente al cargar la página.
|
||||||
autofocus: bool,
|
autofocus: bool,
|
||||||
/// Devuelve si el botón está deshabilitado.
|
/// Devuelve si el botón está deshabilitado.
|
||||||
|
|
@ -112,6 +115,13 @@ impl Component for Button {
|
||||||
if *self.disabled() {
|
if *self.disabled() {
|
||||||
self.alter_prop(PropsOp::add_classes("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> {
|
async fn prepare(&self, cx: &mut Context) -> Result<Markup, ComponentError> {
|
||||||
|
|
@ -227,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 >*************************************************************************
|
// **< Button BUILDER >*************************************************************************
|
||||||
|
|
||||||
/// Establece el identificador único del componente; igual a `with_prop(PropsOp::set_id(id))`.
|
/// Establece el identificador único del componente; igual a `with_prop(PropsOp::set_id(id))`.
|
||||||
|
|
|
||||||
|
|
@ -77,6 +77,8 @@ pub struct Intro {
|
||||||
slogan: Lc,
|
slogan: Lc,
|
||||||
/// Devuelve el botón de llamada a la acción, si existe.
|
/// Devuelve el botón de llamada a la acción, si existe.
|
||||||
button: Option<(Lc, Route)>,
|
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.
|
/// Devuelve el tipo de introducción, fijado al construirla.
|
||||||
kind: intro::Kind,
|
kind: intro::Kind,
|
||||||
/// Devuelve el ancho máximo del área de contenidos.
|
/// Devuelve el ancho máximo del área de contenidos.
|
||||||
|
|
@ -93,6 +95,7 @@ impl Default for Intro {
|
||||||
title: Lc::l("intro_default_title"),
|
title: Lc::l("intro_default_title"),
|
||||||
slogan: Lc::l("intro_default_slogan").with_arg("app", &global::SETTINGS.app.name),
|
slogan: Lc::l("intro_default_slogan").with_arg("app", &global::SETTINGS.app.name),
|
||||||
button: Some((Lc::l("intro_default_button"), BUTTON_LINK.into())),
|
button: Some((Lc::l("intro_default_button"), BUTTON_LINK.into())),
|
||||||
|
button_blank: true,
|
||||||
kind: intro::Kind::default(),
|
kind: intro::Kind::default(),
|
||||||
width: intro::Width::default(),
|
width: intro::Width::default(),
|
||||||
children: Children::default(),
|
children: Children::default(),
|
||||||
|
|
@ -160,8 +163,8 @@ impl Component for Intro {
|
||||||
a
|
a
|
||||||
class="intro-button-link"
|
class="intro-button-link"
|
||||||
href=(lnk.resolve(cx))
|
href=(lnk.resolve(cx))
|
||||||
target="_blank"
|
target=[self.button_blank().then_some("_blank")]
|
||||||
rel="noopener noreferrer"
|
rel=[self.button_blank().then_some("noopener noreferrer")]
|
||||||
{
|
{
|
||||||
span {} span {} span {}
|
span {} span {} span {}
|
||||||
div class="intro-button-text" {
|
div class="intro-button-text" {
|
||||||
|
|
@ -276,12 +279,15 @@ impl Intro {
|
||||||
self
|
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
|
/// - 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.
|
/// pulsar el botón según el contexto de renderizado.
|
||||||
/// - Usa `None` para ocultarlo.
|
/// - Usa `None` para ocultarlo.
|
||||||
///
|
///
|
||||||
|
/// Para abrirlo en una nueva ventana o pestaña se usa
|
||||||
|
/// [`with_button_blank()`](Self::with_button_blank).
|
||||||
|
///
|
||||||
/// # Ejemplo
|
/// # Ejemplo
|
||||||
///
|
///
|
||||||
/// ```rust,no_run
|
/// ```rust,no_run
|
||||||
|
|
@ -293,6 +299,24 @@ impl Intro {
|
||||||
/// ```
|
/// ```
|
||||||
pub fn with_button(mut self, button: impl Into<Option<(Lc, Route)>>) -> Self {
|
pub fn with_button(mut self, button: impl Into<Option<(Lc, Route)>>) -> Self {
|
||||||
self.button = button.into();
|
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
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -116,8 +116,8 @@ async fn button_without_href_renders_as_button_tag() {
|
||||||
|
|
||||||
#[pagetop::test]
|
#[pagetop::test]
|
||||||
async fn anchor_falls_back_to_button_when_href_is_reset() {
|
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
|
// `Route::default()` resolves to an empty path; `prepare()` must ignore `href` and render a
|
||||||
// renderizar un `<button>`, tal y como documenta `Button::with_href()`.
|
// `<button>` again, as documented in `Button::with_href()`.
|
||||||
let mut button = Button::anchor(Lc::n("Edit"), "/items/1/edit").with_href(Route::default());
|
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();
|
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""#));
|
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
|
// 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
|
// `<button disabled>`; the `disabled` class is what both Basic (`.button.disabled`) and Bootsier
|
||||||
// (Bootstrap's own `.btn.disabled`) actually style.
|
// (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""#));
|
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}");
|
||||||
|
}
|
||||||
|
|
|
||||||
45
tests/component_intro.rs
Normal file
45
tests/component_intro.rs
Normal 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""#));
|
||||||
|
}
|
||||||
Loading…
Add table
Add a link
Reference in a new issue