diff --git a/src/base/component/button/component.rs b/src/base/component/button/component.rs
index 23981e48..198b999d 100644
--- a/src/base/component/button/component.rs
+++ b/src/base/component/button/component.rs
@@ -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 `` real que navega; el segundo es sólo un estilo visual (clase `button-link`) que se
@@ -72,6 +73,8 @@ pub struct Button {
/// (` ` en vez de ``). Vacía por defecto: en ese caso `prepare()` renderiza
/// un `` 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.
@@ -112,6 +115,13 @@ impl Component for Button {
if *self.disabled() {
self.alter_prop(PropsOp::add_classes("disabled"));
}
+
+ // Por `Props` y no en el `` 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 {
@@ -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) -> Self {
+ Self {
+ blank: true,
+ ..Self::anchor(label, route)
+ }
+ }
+
// **< Button BUILDER >*************************************************************************
/// Establece el identificador único del componente; igual a `with_prop(PropsOp::set_id(id))`.
diff --git a/src/base/component/intro/component.rs b/src/base/component/intro/component.rs
index b53e618a..744822ce 100644
--- a/src/base/component/intro/component.rs
+++ b/src/base/component/intro/component.rs
@@ -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>) -> 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 >) -> Self {
+ self.button = button.into();
+ self.button_blank = true;
self
}
diff --git a/tests/component_button.rs b/tests/component_button.rs
index 79f56a2e..ce67462d 100644
--- a/tests/component_button.rs
+++ b/tests/component_button.rs
@@ -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 ``, tal y como documenta `Button::with_href()`.
+ // `Route::default()` resolves to an empty path; `prepare()` must ignore `href` and render a
+ // `` 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("` has no native equivalent to `:disabled` that CSS can hook into, unlike a
// ``; 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}");
+}
diff --git a/tests/component_intro.rs b/tests/component_intro.rs
new file mode 100644
index 00000000..7b19d6ec
--- /dev/null
+++ b/tests/component_intro.rs
@@ -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#"').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""#));
+}