Compare commits
4 commits
08d673b89d
...
d80a6787c7
| Author | SHA1 | Date | |
|---|---|---|---|
| d80a6787c7 | |||
| 8690f994c3 | |||
| fc71a077ee | |||
| 144127776d |
39 changed files with 1722 additions and 215 deletions
|
|
@ -70,21 +70,21 @@ mod token;
|
|||
pub use token::*;
|
||||
|
||||
#[doc(hidden)]
|
||||
pub use bs::badge::BadgeBootsier;
|
||||
pub use bs::badge::BadgeBsExt;
|
||||
#[doc(hidden)]
|
||||
pub use bs::button::ButtonBootsier;
|
||||
pub use bs::button::ButtonBsExt;
|
||||
#[doc(hidden)]
|
||||
pub use bs::dropdown::DropdownBootsier;
|
||||
pub use bs::dropdown::DropdownBsExt;
|
||||
#[doc(hidden)]
|
||||
pub use bs::form::input::InputBootsier;
|
||||
pub use bs::form::input::InputBsExt;
|
||||
#[doc(hidden)]
|
||||
pub use bs::form::select::SelectBootsier;
|
||||
pub use bs::form::select::SelectBsExt;
|
||||
#[doc(hidden)]
|
||||
pub use bs::form::textarea::TextareaBootsier;
|
||||
pub use bs::form::textarea::TextareaBsExt;
|
||||
#[doc(hidden)]
|
||||
pub use bs::nav::NavBootsier;
|
||||
pub use bs::nav::NavBsExt;
|
||||
#[doc(hidden)]
|
||||
pub use bs::navbar::NavbarBootsier;
|
||||
pub use bs::navbar::NavbarBsExt;
|
||||
|
||||
// Añade la clase de un punto de corte con un prefijo y un sufijo (opcional) a la cadena de clases,
|
||||
// separada con un espacio de las que ya hubiera: `prefix-name-suffix`, sin `-suffix` si no hay
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@ pub(crate) mod layout;
|
|||
|
||||
// Badge.
|
||||
pub(crate) mod badge;
|
||||
pub use badge::{Badge, BadgeBootsier};
|
||||
pub use badge::{Badge, BadgeBsExt};
|
||||
|
||||
// Block.
|
||||
pub use pagetop::base::component::Block;
|
||||
|
|
@ -20,7 +20,7 @@ pub use pagetop::base::component::breadcrumb;
|
|||
|
||||
// Button.
|
||||
pub mod button;
|
||||
pub use button::{Button, ButtonBootsier};
|
||||
pub use button::{Button, ButtonBsExt};
|
||||
|
||||
// Container.
|
||||
pub mod container;
|
||||
|
|
@ -37,18 +37,18 @@ pub mod dropdown;
|
|||
#[doc(inline)]
|
||||
pub use dropdown::Dropdown;
|
||||
#[doc(inline)]
|
||||
pub use dropdown::DropdownBootsier;
|
||||
pub use dropdown::DropdownBsExt;
|
||||
|
||||
// Form.
|
||||
pub mod form;
|
||||
#[doc(inline)]
|
||||
pub use form::Form;
|
||||
#[doc(inline)]
|
||||
pub use form::input::InputBootsier;
|
||||
pub use form::input::InputBsExt;
|
||||
#[doc(inline)]
|
||||
pub use form::select::SelectBootsier;
|
||||
pub use form::select::SelectBsExt;
|
||||
#[doc(inline)]
|
||||
pub use form::textarea::TextareaBootsier;
|
||||
pub use form::textarea::TextareaBsExt;
|
||||
|
||||
// Image.
|
||||
pub mod image;
|
||||
|
|
@ -63,14 +63,14 @@ pub mod nav;
|
|||
#[doc(inline)]
|
||||
pub use nav::Nav;
|
||||
#[doc(inline)]
|
||||
pub use nav::NavBootsier;
|
||||
pub use nav::NavBsExt;
|
||||
|
||||
// Navbar.
|
||||
pub mod navbar;
|
||||
#[doc(inline)]
|
||||
pub use navbar::Navbar;
|
||||
#[doc(inline)]
|
||||
pub use navbar::NavbarBootsier;
|
||||
pub use navbar::NavbarBsExt;
|
||||
|
||||
// Offcanvas.
|
||||
pub mod offcanvas;
|
||||
|
|
|
|||
|
|
@ -19,14 +19,14 @@ const EXTRA_COLOR: &str = "bootsier.badge.color";
|
|||
/// let badge = bs::Badge::labeled(Lc::n("Beta")).with_color(BootsierColors::Dark);
|
||||
/// ```
|
||||
#[builder_impl]
|
||||
pub trait BadgeBootsier {
|
||||
pub trait BadgeBsExt {
|
||||
/// Fuerza un color de la paleta de Bootsier, ignorando el que le correspondería a la `Intent`
|
||||
/// del badge. `None` restablece el comportamiento por defecto (color derivado de la `Intent`).
|
||||
fn with_color(self, color: impl Into<Option<BootsierColors>>) -> Self;
|
||||
}
|
||||
|
||||
#[builder_impl]
|
||||
impl BadgeBootsier for Badge {
|
||||
impl BadgeBsExt for Badge {
|
||||
fn with_color(mut self, color: impl Into<Option<BootsierColors>>) -> Self {
|
||||
match color.into() {
|
||||
Some(color) => self.alter_prop(PropsOp::set_extra(EXTRA_COLOR, color)),
|
||||
|
|
@ -41,7 +41,7 @@ impl BadgeBootsier for Badge {
|
|||
pub(crate) fn setup(badge: &mut Badge) {
|
||||
// `Badge::setup()` (core) ya ha traducido la intención con `Theme::intent_color()`. La clase
|
||||
// `badge-*` que hay que localizar es siempre la derivada de la `Intent`, con independencia de
|
||||
// que `BadgeBootsier::with_color()` fuerce un color distinto para el destino `text-bg-*`.
|
||||
// que `BadgeBsExt::with_color()` fuerce un color distinto para el destino `text-bg-*`.
|
||||
let intent_color = BootsierColors::from(badge.intent()).as_str();
|
||||
let color = badge
|
||||
.props()
|
||||
|
|
|
|||
|
|
@ -10,7 +10,7 @@ const EXTRA_ACTIVE: &str = "bootsier.button.active";
|
|||
const EXTRA_FULL_WIDTH: &str = "bootsier.button.full_width";
|
||||
const EXTRA_COLOR: &str = "bootsier.button.color";
|
||||
|
||||
// **< ButtonBootsier >*****************************************************************************
|
||||
// **< ButtonBsExt >********************************************************************************
|
||||
|
||||
/// Extensión de Bootsier para [`Button`].
|
||||
///
|
||||
|
|
@ -36,7 +36,7 @@ const EXTRA_COLOR: &str = "bootsier.button.color";
|
|||
/// .with_color(BootsierColors::Light);
|
||||
/// ```
|
||||
#[builder_impl]
|
||||
pub trait ButtonBootsier {
|
||||
pub trait ButtonBsExt {
|
||||
/// Marca el botón como activo (`.active`, `aria-pressed="true"`).
|
||||
fn with_active(self, active: bool) -> Self;
|
||||
|
||||
|
|
@ -50,7 +50,7 @@ pub trait ButtonBootsier {
|
|||
}
|
||||
|
||||
#[builder_impl]
|
||||
impl ButtonBootsier for Button {
|
||||
impl ButtonBsExt for Button {
|
||||
fn with_active(mut self, active: bool) -> Self {
|
||||
self.alter_prop(PropsOp::set_extra(EXTRA_ACTIVE, active));
|
||||
self
|
||||
|
|
|
|||
|
|
@ -45,7 +45,7 @@ const EXTRA_MENU_POSITION: &str = "bootsier.dropdown.menu_position";
|
|||
/// .with_item(bs::dropdown::Item::button(Lc::n("Sign out")));
|
||||
/// ```
|
||||
#[builder_impl]
|
||||
pub trait DropdownBootsier {
|
||||
pub trait DropdownBsExt {
|
||||
/// Indica si el botón del menú está integrado en un grupo de botones.
|
||||
fn with_button_grouped(self, grouped: bool) -> Self;
|
||||
|
||||
|
|
@ -68,7 +68,7 @@ pub trait DropdownBootsier {
|
|||
}
|
||||
|
||||
#[builder_impl]
|
||||
impl DropdownBootsier for Dropdown {
|
||||
impl DropdownBsExt for Dropdown {
|
||||
fn with_button_grouped(mut self, grouped: bool) -> Self {
|
||||
self.alter_prop(PropsOp::set_extra(EXTRA_BUTTON_GROUPED, grouped));
|
||||
self
|
||||
|
|
|
|||
|
|
@ -14,16 +14,24 @@ pub use pagetop::base::component::form::radio;
|
|||
|
||||
pub mod select;
|
||||
#[doc(inline)]
|
||||
pub use select::SelectBootsier;
|
||||
pub use select::SelectBsExt;
|
||||
|
||||
pub use pagetop::base::component::form::SelectLanguage;
|
||||
|
||||
pub use pagetop::base::component::form::SelectTheme;
|
||||
|
||||
pub use pagetop::base::component::form::SelectTimezone;
|
||||
|
||||
pub mod input;
|
||||
#[doc(inline)]
|
||||
pub use input::InputBootsier;
|
||||
pub use input::InputBsExt;
|
||||
|
||||
pub mod textarea;
|
||||
pub use textarea::Textarea;
|
||||
#[doc(inline)]
|
||||
pub use textarea::TextareaBootsier;
|
||||
pub use textarea::TextareaBsExt;
|
||||
|
||||
pub use pagetop::base::component::form::date;
|
||||
|
||||
pub use pagetop::base::component::form::Number;
|
||||
|
||||
|
|
|
|||
|
|
@ -23,7 +23,7 @@ const EXTRA_FLOATING_LABEL: &str = "bootsier.form.input.floating_label";
|
|||
/// .with_floating_label(true);
|
||||
/// ```
|
||||
#[builder_impl]
|
||||
pub trait InputBootsier {
|
||||
pub trait InputBsExt {
|
||||
/// Establece si la etiqueta se muestra flotante sobre el campo.
|
||||
///
|
||||
/// Cuando está activo, la etiqueta se superpone al campo y asciende al enfocarlo o cuando tiene
|
||||
|
|
@ -33,7 +33,7 @@ pub trait InputBootsier {
|
|||
}
|
||||
|
||||
#[builder_impl]
|
||||
impl InputBootsier for Field {
|
||||
impl InputBsExt for Field {
|
||||
fn with_floating_label(mut self, floating: bool) -> Self {
|
||||
self.alter_prop(PropsOp::set_extra(EXTRA_FLOATING_LABEL, floating));
|
||||
self
|
||||
|
|
@ -55,6 +55,7 @@ pub(crate) fn setup(field: &mut Field) {
|
|||
pub(crate) fn render(field: &Field, cx: &mut Context) -> Result<Markup, ComponentError> {
|
||||
let container_id = field.id();
|
||||
let input_id = container_id.as_deref().map(|id| util::join!(id, "-input"));
|
||||
let help = form::parts::Help::new(field.help_text(), input_id.as_deref());
|
||||
let input_class = if *field.plaintext() {
|
||||
"form-control-plaintext"
|
||||
} else {
|
||||
|
|
@ -76,29 +77,16 @@ pub(crate) fn render(field: &Field, cx: &mut Context) -> Result<Markup, Componen
|
|||
} else {
|
||||
field.placeholder().lookup(cx)
|
||||
};
|
||||
let label = match field.label().lookup(cx) {
|
||||
Some(text) => html! {
|
||||
label for=[input_id.as_deref()] class="form-label" {
|
||||
(text)
|
||||
@if *field.required() {
|
||||
span
|
||||
class="form-required"
|
||||
title=[Lc::l("field_required").lookup(cx)]
|
||||
{
|
||||
"*"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
None => html! {},
|
||||
};
|
||||
let label = form::parts::Label::new(field.label(), input_id.as_deref())
|
||||
.with_required(*field.required());
|
||||
|
||||
Ok(html! {
|
||||
div (field.props().unpack(cx)) {
|
||||
@if !floating { (label) }
|
||||
@if !floating { (label.render(cx)) }
|
||||
input
|
||||
type=(field.kind())
|
||||
id=[input_id.as_deref()]
|
||||
aria-describedby=[help.id()]
|
||||
class=(input_class)
|
||||
name=[field.name().as_deref()]
|
||||
value=[field.value().as_deref()]
|
||||
|
|
@ -115,10 +103,8 @@ pub(crate) fn render(field: &Field, cx: &mut Context) -> Result<Markup, Componen
|
|||
onfocus=[strict.then_some("this.removeAttribute('readonly')")]
|
||||
required[*field.required()]
|
||||
disabled[*field.disabled()];
|
||||
@if floating { (label) }
|
||||
@if let Some(description) = field.help_text().lookup(cx) {
|
||||
div class="form-text" { (description) }
|
||||
}
|
||||
@if floating { (label.render(cx)) }
|
||||
(help.render(cx))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
|
|
|||
|
|
@ -25,7 +25,7 @@ const EXTRA_FLOATING_LABEL: &str = "bootsier.form.select.floating_label";
|
|||
/// .with_item(bs::form::select::Item::new("en", Lc::n("English")));
|
||||
/// ```
|
||||
#[builder_impl]
|
||||
pub trait SelectBootsier {
|
||||
pub trait SelectBsExt {
|
||||
/// Establece si la etiqueta se muestra flotante sobre el campo.
|
||||
///
|
||||
/// Cuando está activo, la etiqueta se superpone al control y permanece flotante siempre que
|
||||
|
|
@ -38,7 +38,7 @@ pub trait SelectBootsier {
|
|||
}
|
||||
|
||||
#[builder_impl]
|
||||
impl SelectBootsier for Field {
|
||||
impl SelectBsExt for Field {
|
||||
fn with_floating_label(mut self, floating: bool) -> Self {
|
||||
self.alter_prop(PropsOp::set_extra(EXTRA_FLOATING_LABEL, floating));
|
||||
self
|
||||
|
|
@ -62,28 +62,16 @@ pub(crate) fn setup(field: &mut Field) {
|
|||
pub(crate) fn render(field: &Field, cx: &mut Context) -> Result<Markup, ComponentError> {
|
||||
let container_id = field.id();
|
||||
let select_id = container_id.as_deref().map(|id| util::join!(id, "-select"));
|
||||
let help = form::parts::Help::new(field.help_text(), select_id.as_deref());
|
||||
let floating = field.props().extra_or(EXTRA_FLOATING_LABEL, false);
|
||||
let label = match field.label().lookup(cx) {
|
||||
Some(text) => html! {
|
||||
label for=[select_id.as_deref()] class="form-label" {
|
||||
(text)
|
||||
@if *field.required() {
|
||||
span
|
||||
class="form-required"
|
||||
title=[Lc::l("field_required").lookup(cx)]
|
||||
{
|
||||
"*"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
None => html! {},
|
||||
};
|
||||
let label = form::parts::Label::new(field.label(), select_id.as_deref())
|
||||
.with_required(*field.required());
|
||||
Ok(html! {
|
||||
div (field.props().unpack(cx)) {
|
||||
@if !floating { (label) }
|
||||
@if !floating { (label.render(cx)) }
|
||||
select
|
||||
id=[select_id.as_deref()]
|
||||
aria-describedby=[help.id()]
|
||||
class="form-select"
|
||||
name=[field.name().as_deref()]
|
||||
multiple[*field.multiple()]
|
||||
|
|
@ -123,10 +111,8 @@ pub(crate) fn render(field: &Field, cx: &mut Context) -> Result<Markup, Componen
|
|||
}
|
||||
}
|
||||
}
|
||||
@if floating { (label) }
|
||||
@if let Some(description) = field.help_text().lookup(cx) {
|
||||
div class="form-text" { (description) }
|
||||
}
|
||||
@if floating { (label.render(cx)) }
|
||||
(help.render(cx))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
|
|
|||
|
|
@ -23,7 +23,7 @@ const EXTRA_FLOATING_LABEL: &str = "bootsier.form.textarea.floating_label";
|
|||
/// .with_floating_label(true);
|
||||
/// ```
|
||||
#[builder_impl]
|
||||
pub trait TextareaBootsier {
|
||||
pub trait TextareaBsExt {
|
||||
/// Establece si la etiqueta se muestra flotante sobre el campo.
|
||||
///
|
||||
/// Cuando está activo, la etiqueta se superpone al área de texto y asciende al enfocarlo o
|
||||
|
|
@ -36,7 +36,7 @@ pub trait TextareaBootsier {
|
|||
}
|
||||
|
||||
#[builder_impl]
|
||||
impl TextareaBootsier for Textarea {
|
||||
impl TextareaBsExt for Textarea {
|
||||
fn with_floating_label(mut self, floating: bool) -> Self {
|
||||
self.alter_prop(PropsOp::set_extra(EXTRA_FLOATING_LABEL, floating));
|
||||
self
|
||||
|
|
@ -61,6 +61,7 @@ pub(crate) fn render(field: &Textarea, cx: &mut Context) -> Result<Markup, Compo
|
|||
let textarea_id = container_id
|
||||
.as_deref()
|
||||
.map(|id| util::join!(id, "-textarea"));
|
||||
let help = form::parts::Help::new(field.help_text(), textarea_id.as_deref());
|
||||
let floating = field.props().extra_or(EXTRA_FLOATING_LABEL, false);
|
||||
// La etiqueta flotante requiere `placeholder` para animar la etiqueta; si no está definido se
|
||||
// fuerza `placeholder=""`.
|
||||
|
|
@ -69,27 +70,14 @@ pub(crate) fn render(field: &Textarea, cx: &mut Context) -> Result<Markup, Compo
|
|||
} else {
|
||||
field.placeholder().lookup(cx)
|
||||
};
|
||||
let label = match field.label().lookup(cx) {
|
||||
Some(text) => html! {
|
||||
label for=[textarea_id.as_deref()] class="form-label" {
|
||||
(text)
|
||||
@if *field.required() {
|
||||
span
|
||||
class="form-required"
|
||||
title=[Lc::l("field_required").lookup(cx)]
|
||||
{
|
||||
"*"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
None => html! {},
|
||||
};
|
||||
let label = form::parts::Label::new(field.label(), textarea_id.as_deref())
|
||||
.with_required(*field.required());
|
||||
Ok(html! {
|
||||
div (field.props().unpack(cx)) {
|
||||
@if !floating { (label) }
|
||||
@if !floating { (label.render(cx)) }
|
||||
textarea
|
||||
id=[textarea_id.as_deref()]
|
||||
aria-describedby=[help.id()]
|
||||
class="form-control"
|
||||
name=[field.name().as_deref()]
|
||||
rows=[field.rows()]
|
||||
|
|
@ -104,10 +92,8 @@ pub(crate) fn render(field: &Textarea, cx: &mut Context) -> Result<Markup, Compo
|
|||
{
|
||||
@if let Some(value) = field.value().as_deref() { (value) }
|
||||
}
|
||||
@if floating { (label) }
|
||||
@if let Some(description) = field.help_text().lookup(cx) {
|
||||
div class="form-text" { (description) }
|
||||
}
|
||||
@if floating { (label.render(cx)) }
|
||||
(help.render(cx))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
|
|
|||
|
|
@ -19,8 +19,8 @@ pub use pagetop::base::component::nav::{Item, ItemKind};
|
|||
|
||||
const EXTRA_KIND: &str = "bootsier.nav.kind";
|
||||
|
||||
// Marca interna (nunca expuesta en `NavBootsier`) que `theme::bs::navbar::item` fija sobre el clon
|
||||
// de un `Nav` embebido en una `Navbar`, para que use `navbar-nav` en vez de `nav` como clase base.
|
||||
// Marca interna (nunca expuesta en `NavBsExt`) que `theme::bs::navbar::item` fija sobre el clon de
|
||||
// un `Nav` embebido en una `Navbar`, para que use `navbar-nav` en vez de `nav` como clase base.
|
||||
pub(crate) const EXTRA_IN_NAVBAR: &str = "bootsier.nav.in_navbar";
|
||||
|
||||
/// Extensión de Bootsier para [`Nav`].
|
||||
|
|
@ -47,13 +47,13 @@ pub(crate) const EXTRA_IN_NAVBAR: &str = "bootsier.nav.in_navbar";
|
|||
/// .with_item(bs::nav::Item::link_disabled(Lc::n("Disabled"), "#"));
|
||||
/// ```
|
||||
#[builder_impl]
|
||||
pub trait NavBootsier {
|
||||
pub trait NavBsExt {
|
||||
/// Cambia el estilo del menú (*Tabs*, *Pills*, *Underline* o *Default*).
|
||||
fn with_kind(self, kind: Kind) -> Self;
|
||||
}
|
||||
|
||||
#[builder_impl]
|
||||
impl NavBootsier for Nav {
|
||||
impl NavBsExt for Nav {
|
||||
fn with_kind(mut self, kind: Kind) -> Self {
|
||||
self.alter_prop(PropsOp::set_extra(EXTRA_KIND, kind));
|
||||
self
|
||||
|
|
|
|||
|
|
@ -19,7 +19,7 @@ mod panel;
|
|||
pub use panel::Panel;
|
||||
|
||||
mod component;
|
||||
pub use component::NavbarBootsier;
|
||||
pub use component::NavbarBsExt;
|
||||
pub(crate) use component::{render, setup};
|
||||
|
||||
mod item;
|
||||
|
|
|
|||
|
|
@ -140,7 +140,7 @@ const EXTRA_LAYOUT: &str = "bootsier.navbar.layout";
|
|||
/// ));
|
||||
/// ```
|
||||
#[builder_impl]
|
||||
pub trait NavbarBootsier {
|
||||
pub trait NavbarBsExt {
|
||||
/// Crea una barra de navegación cuyo contenido se muestra en un panel lateral.
|
||||
fn offcanvas(panel: bs::navbar::Panel) -> Self;
|
||||
|
||||
|
|
@ -154,7 +154,7 @@ pub trait NavbarBootsier {
|
|||
}
|
||||
|
||||
#[builder_impl]
|
||||
impl NavbarBootsier for Navbar {
|
||||
impl NavbarBsExt for Navbar {
|
||||
fn offcanvas(panel: bs::navbar::Panel) -> Self {
|
||||
let mut navbar = Self::new();
|
||||
navbar.alter_prop(PropsOp::set_extra(
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
// Verifies `BadgeBootsier::with_color()`: it overrides the Bootstrap color that `Badge` would
|
||||
// Verifies `BadgeBsExt::with_color()`: it overrides the Bootstrap color that `Badge` would
|
||||
// otherwise derive from its `Intent`, without disturbing the class that `Badge::setup()` (core)
|
||||
// already generated from that `Intent`.
|
||||
|
||||
|
|
|
|||
57
extensions/pagetop-bootsier/tests/form_help_text.rs
Normal file
57
extensions/pagetop-bootsier/tests/form_help_text.rs
Normal file
|
|
@ -0,0 +1,57 @@
|
|||
// Bootsier renders its own markup for text inputs, selects and textareas: the help text must stay
|
||||
// linked to the control with `aria-describedby`, as in the core components.
|
||||
|
||||
use pagetop::prelude::*;
|
||||
use pagetop_bootsier::Bootsier;
|
||||
use pagetop_bootsier::theme::*;
|
||||
|
||||
async fn render(component: &mut impl Component) -> String {
|
||||
component
|
||||
.render(&mut Context::default().with_theme(&Bootsier))
|
||||
.await
|
||||
.into_string()
|
||||
}
|
||||
|
||||
#[pagetop::test]
|
||||
async fn bootsier_fields_point_to_their_help_text() {
|
||||
let help = || Lc::n("Help");
|
||||
let cases: [(String, &str); 3] = [
|
||||
(
|
||||
render(
|
||||
&mut bs::form::input::Field::text()
|
||||
.with_name("a")
|
||||
.with_help_text(help()),
|
||||
)
|
||||
.await,
|
||||
"edit-a-input-help",
|
||||
),
|
||||
(
|
||||
render(
|
||||
&mut bs::form::select::Field::new()
|
||||
.with_name("b")
|
||||
.with_help_text(help()),
|
||||
)
|
||||
.await,
|
||||
"edit-b-select-help",
|
||||
),
|
||||
(
|
||||
render(
|
||||
&mut bs::form::Textarea::new()
|
||||
.with_name("c")
|
||||
.with_help_text(help()),
|
||||
)
|
||||
.await,
|
||||
"edit-c-textarea-help",
|
||||
),
|
||||
];
|
||||
for (html, id) in cases {
|
||||
assert!(
|
||||
html.contains(&format!(r#"aria-describedby="{id}""#)),
|
||||
"{html}"
|
||||
);
|
||||
assert!(
|
||||
html.contains(&format!(r#"<div id="{id}" class="form-text">Help</div>"#)),
|
||||
"{html}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
@ -6,6 +6,8 @@ pub use props::{Autocomplete, AutofillField, CheckboxKind, Method};
|
|||
mod component;
|
||||
pub use component::Form;
|
||||
|
||||
pub mod parts;
|
||||
|
||||
mod fieldset;
|
||||
pub use fieldset::Fieldset;
|
||||
|
||||
|
|
@ -29,6 +31,8 @@ pub use select_timezone::SelectTimezone;
|
|||
|
||||
pub mod input;
|
||||
|
||||
pub mod date;
|
||||
|
||||
mod number;
|
||||
pub use number::Number;
|
||||
|
||||
|
|
|
|||
|
|
@ -142,12 +142,18 @@ impl Component for Field {
|
|||
// En `setup()` se garantiza que `name` e `id` están definidos antes del renderizado.
|
||||
let name = self.name().as_deref().unwrap();
|
||||
let container_id = self.id().unwrap();
|
||||
// El contenedor agrupa las opciones: su etiqueta y su texto de ayuda describen al grupo.
|
||||
let label = form::parts::Label::group(self.label(), &container_id);
|
||||
let help = form::parts::Help::new(self.help_text(), Some(&container_id));
|
||||
|
||||
Ok(html! {
|
||||
div (self.props().unpack(cx)) {
|
||||
@if let Some(label) = self.label().lookup(cx) {
|
||||
label class="form-label" { (label) }
|
||||
}
|
||||
div
|
||||
(self.props().unpack(cx))
|
||||
role="group"
|
||||
aria-labelledby=[label.id()]
|
||||
aria-describedby=[help.id()]
|
||||
{
|
||||
(label.render(cx))
|
||||
@let item_classes = if *self.inline() {
|
||||
"form-check form-check-inline"
|
||||
} else {
|
||||
|
|
@ -170,9 +176,7 @@ impl Component for Field {
|
|||
}
|
||||
}
|
||||
}
|
||||
@if let Some(description) = self.help_text().lookup(cx) {
|
||||
div class="form-text" { (description) }
|
||||
}
|
||||
(help.render(cx))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
|
|
|||
|
|
@ -102,6 +102,8 @@ impl Component for Checkbox {
|
|||
let container_id = self.id().unwrap();
|
||||
|
||||
let checkbox_id = util::join!(&container_id, "-checkbox");
|
||||
let label = form::parts::Label::check(self.label(), Some(&checkbox_id))
|
||||
.with_required(*self.required());
|
||||
let is_switch = *self.checkbox_kind() == form::CheckboxKind::Switch;
|
||||
|
||||
Ok(html! {
|
||||
|
|
@ -117,19 +119,7 @@ impl Component for Checkbox {
|
|||
autofocus[*self.autofocus()]
|
||||
required[*self.required()]
|
||||
disabled[*self.disabled()];
|
||||
@if let Some(label) = self.label().lookup(cx) {
|
||||
label class="form-check-label" for=(&checkbox_id) {
|
||||
(label)
|
||||
@if *self.required() {
|
||||
span
|
||||
class="form-required"
|
||||
title=[Lc::l("field_required").lookup(cx)]
|
||||
{
|
||||
"*"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
(label.render(cx))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
|
|
|||
322
src/base/component/form/date.rs
Normal file
322
src/base/component/form/date.rs
Normal file
|
|
@ -0,0 +1,322 @@
|
|||
//! Definiciones para crear campos de fecha y hora.
|
||||
|
||||
use crate::datetime::input;
|
||||
use crate::prelude::*;
|
||||
|
||||
// **< Kind >***************************************************************************************
|
||||
|
||||
/// Tipo de dato de un [`form::date::Field`].
|
||||
///
|
||||
/// Se aplica al crear el campo con [`Field::date()`], [`Field::time()`] o [`Field::datetime()`].
|
||||
#[derive(AutoDefault, Clone, Copy, Debug, PartialEq)]
|
||||
pub enum Kind {
|
||||
/// Fecha sin hora ([`NaiveDate`]). Es el tipo por defecto.
|
||||
#[default]
|
||||
Date,
|
||||
/// Hora del día ([`NaiveTime`]).
|
||||
Time,
|
||||
/// Fecha y hora de un instante ([`DateTime<Utc>`](DateTime)), en la zona horaria efectiva.
|
||||
DateTime,
|
||||
}
|
||||
|
||||
impl Kind {
|
||||
// Sufijo de la clase CSS del contenedor (`form-field-date`...).
|
||||
const fn as_str(&self) -> &'static str {
|
||||
match self {
|
||||
Kind::Date => "date",
|
||||
Kind::Time => "time",
|
||||
Kind::DateTime => "datetime",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Valor inicial del campo: un dato con su tipo, que se muestra con el formato del idioma, o el
|
||||
// texto tal como lo escribió el usuario (para volver a mostrarlo, p. ej. si no se pudo leer).
|
||||
#[derive(AutoDefault, Clone, Debug)]
|
||||
enum Value {
|
||||
#[default]
|
||||
None,
|
||||
Date(NaiveDate),
|
||||
Time(NaiveTime),
|
||||
DateTime(DateTime<Utc>),
|
||||
Text(String),
|
||||
}
|
||||
|
||||
// **< Field >**************************************************************************************
|
||||
|
||||
/// Componente para crear un **campo de fecha, de hora o de fecha y hora**.
|
||||
///
|
||||
/// Muestra el valor **con el formato del idioma efectivo** del documento, el mismo con el que se
|
||||
/// muestra el resto de la página y con el que lo leen después los métodos `parse_*` de
|
||||
/// [`Contextual`]. Por ejemplo, una fecha se escribe `dd/mm/aaaa` en español y `mm/dd/yyyy` en
|
||||
/// inglés de Estados Unidos, y ese formato se indica en el propio campo (como texto indicativo y
|
||||
/// como texto de ayuda asociado al campo). Una fecha y hora se muestra y se escribe en la **zona
|
||||
/// horaria efectiva** del documento ([`Contextual::timezone()`]), normalmente la del usuario, y se
|
||||
/// lee convertida a UTC.
|
||||
///
|
||||
/// Es un campo de texto (`type="text"`), no un selector nativo (`type="date"`): el navegador
|
||||
/// muestra los selectores nativos con el formato de **su** configuración regional, no con el del
|
||||
/// idioma de la página, y la página no puede cambiarlo.
|
||||
///
|
||||
/// - [`Field::date()`]: fecha sin hora ([`NaiveDate`]), p. ej. una fecha de caducidad. No se
|
||||
/// convierte de zona horaria.
|
||||
/// - [`Field::time()`]: hora del día ([`NaiveTime`]).
|
||||
/// - [`Field::datetime()`]: fecha y hora de un instante ([`DateTime<Utc>`](DateTime)).
|
||||
///
|
||||
/// # Ejemplo
|
||||
///
|
||||
/// ```rust,no_run
|
||||
/// # use pagetop::prelude::*;
|
||||
/// # fn build(expires: Option<NaiveDate>) {
|
||||
/// let field = form::date::Field::date()
|
||||
/// .with_name("expires")
|
||||
/// .with_label(Lc::n("Expiry date"))
|
||||
/// .with_date(expires)
|
||||
/// .with_required(true);
|
||||
/// # }
|
||||
/// ```
|
||||
///
|
||||
/// El navegador envía el texto escrito, que se deserializa como `String` y se lee con
|
||||
/// [`Contextual::parse_date()`], [`Contextual::parse_time()`] o [`Contextual::parse_datetime()`]
|
||||
/// según el tipo de campo. Si no se puede leer, el error ([`DateInputError`]) tiene un mensaje
|
||||
/// traducido, y [`with_text()`](Field::with_text) vuelve a mostrar lo que escribió el usuario:
|
||||
///
|
||||
/// ```rust,no_run
|
||||
/// # use pagetop::prelude::*;
|
||||
/// # fn handle(cx: &Context, text: String) {
|
||||
/// match cx.parse_date(&text) {
|
||||
/// Ok(expires) => { /* Guardar `expires` (`Option<NaiveDate>`). */ }
|
||||
/// Err(error) => {
|
||||
/// let field = form::date::Field::date().with_name("expires").with_text(text);
|
||||
/// let message = error.message(); // Para mostrarlo junto al formulario.
|
||||
/// }
|
||||
/// }
|
||||
/// # }
|
||||
/// ```
|
||||
#[derive(AutoDefault, Clone, Debug, Getters)]
|
||||
pub struct Field {
|
||||
/// Devuelve identificador, clases CSS, atributos HTML y valores extra del componente.
|
||||
props: Props,
|
||||
/// Devuelve el tipo de dato del campo.
|
||||
#[getters(copy)]
|
||||
kind: Kind,
|
||||
/// Devuelve el nombre del campo.
|
||||
name: AttrName,
|
||||
#[getters(skip)]
|
||||
value: Value,
|
||||
/// Devuelve la etiqueta del campo.
|
||||
label: Lc,
|
||||
/// Devuelve el texto de ayuda del campo.
|
||||
help_text: Lc,
|
||||
/// Devuelve la configuración de autocompletado del campo; sin ella, se desactiva (`off`).
|
||||
autocomplete: Option<form::Autocomplete>,
|
||||
/// Devuelve si el campo recibe el foco automáticamente al cargar la página.
|
||||
autofocus: bool,
|
||||
/// Devuelve si el campo es de sólo lectura.
|
||||
readonly: bool,
|
||||
/// Devuelve si el campo es obligatorio.
|
||||
required: bool,
|
||||
/// Devuelve si el campo está deshabilitado.
|
||||
disabled: bool,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Component for Field {
|
||||
fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
fn id(&self) -> Option<String> {
|
||||
self.props.get_id()
|
||||
}
|
||||
|
||||
fn setup(&mut self, _cx: &mut Context) {
|
||||
if let Some(container_id) = self
|
||||
.id()
|
||||
.or_else(|| self.name().as_deref().map(|n| util::join!("edit-", n)))
|
||||
{
|
||||
self.alter_prop(PropsOp::ensure_id(container_id));
|
||||
}
|
||||
|
||||
// Clases CSS del contenedor del campo.
|
||||
self.alter_prop(PropsOp::prepend_classes(util::join!(
|
||||
"form-field form-field-",
|
||||
self.kind().as_str()
|
||||
)));
|
||||
}
|
||||
|
||||
async fn prepare(&self, cx: &mut Context) -> Result<Markup, ComponentError> {
|
||||
let container_id = self.id();
|
||||
let input_id = container_id.as_deref().map(|id| util::join!(id, "-input"));
|
||||
let tz = cx.timezone();
|
||||
let value = match (self.kind(), &self.value) {
|
||||
(_, Value::Text(text)) => Some(text.clone()),
|
||||
(Kind::Date, Value::Date(date)) => Some(input::format_date(*date, cx)),
|
||||
(Kind::Time, Value::Time(time)) => Some(input::format_time(*time, cx)),
|
||||
(Kind::DateTime, Value::DateTime(dt)) => Some(input::format_datetime(*dt, cx, tz)),
|
||||
_ => None,
|
||||
};
|
||||
let hint = match self.kind() {
|
||||
Kind::Date => input::date_hint(cx),
|
||||
Kind::Time => input::time_hint(cx),
|
||||
Kind::DateTime => input::datetime_hint(cx),
|
||||
};
|
||||
let format = Lc::l("input_format_help").with_arg("format", hint.clone());
|
||||
let format = form::parts::Help::suffixed(&format, input_id.as_deref(), "-format");
|
||||
let help = form::parts::Help::new(self.help_text(), input_id.as_deref());
|
||||
let label = form::parts::Label::new(self.label(), input_id.as_deref())
|
||||
.with_required(*self.required());
|
||||
// El formato y, si lo hay, el texto de ayuda describen el campo, en ese orden.
|
||||
let described_by = util::join_pair!(
|
||||
format.id().unwrap_or_default(),
|
||||
" ",
|
||||
help.id().unwrap_or_default()
|
||||
);
|
||||
// Sin autocompletado explícito se desactiva: el navegador sugeriría fechas escritas antes
|
||||
// en otros formularios, que rara vez son las que se quieren introducir.
|
||||
let autocomplete = self.autocomplete().unwrap_or(&form::Autocomplete::Off);
|
||||
Ok(html! {
|
||||
div (self.props().unpack(cx)) {
|
||||
(label.render(cx))
|
||||
input
|
||||
type="text"
|
||||
id=[input_id.as_deref()]
|
||||
class="form-control"
|
||||
name=[self.name().as_deref()]
|
||||
value=[value]
|
||||
placeholder=(hint)
|
||||
aria-describedby=[util::non_blank(&described_by)]
|
||||
autocomplete=(autocomplete)
|
||||
autofocus[*self.autofocus()]
|
||||
readonly[*self.readonly()]
|
||||
required[*self.required()]
|
||||
disabled[*self.disabled()];
|
||||
(format.render(cx))
|
||||
(help.render(cx))
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[builder_impl]
|
||||
impl Field {
|
||||
/// Crea un campo de **fecha sin hora** ([`NaiveDate`]), p. ej. una fecha de nacimiento o de
|
||||
/// caducidad. Se lee con [`Contextual::parse_date()`].
|
||||
pub fn date() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
/// Crea un campo de **hora del día** ([`NaiveTime`]). Se lee con
|
||||
/// [`Contextual::parse_time()`].
|
||||
pub fn time() -> Self {
|
||||
Self {
|
||||
kind: Kind::Time,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// Crea un campo de **fecha y hora de un instante** ([`DateTime<Utc>`](DateTime)), que el
|
||||
/// usuario ve y escribe en su hora local. Se lee con [`Contextual::parse_datetime()`].
|
||||
pub fn datetime() -> Self {
|
||||
Self {
|
||||
kind: Kind::DateTime,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
// **< Field 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 el nombre del campo (atributo `name`).
|
||||
pub fn with_name(mut self, name: impl AsRef<str>) -> Self {
|
||||
self.name.alter_name(name);
|
||||
self
|
||||
}
|
||||
|
||||
/// Establece la fecha inicial de un campo de [`Field::date()`] (`None` para dejarlo vacío). En
|
||||
/// un campo de otro tipo se ignora.
|
||||
pub fn with_date(mut self, date: impl Into<Option<NaiveDate>>) -> Self {
|
||||
self.value = date.into().map_or(Value::None, Value::Date);
|
||||
self
|
||||
}
|
||||
|
||||
/// Establece la hora inicial de un campo de [`Field::time()`] (`None` para dejarlo vacío). En
|
||||
/// un campo de otro tipo se ignora.
|
||||
pub fn with_time(mut self, time: impl Into<Option<NaiveTime>>) -> Self {
|
||||
self.value = time.into().map_or(Value::None, Value::Time);
|
||||
self
|
||||
}
|
||||
|
||||
/// Establece el instante inicial de un campo de [`Field::datetime()`] (`None` para dejarlo
|
||||
/// vacío). Se muestra en la zona horaria efectiva del documento. En un campo de otro tipo se
|
||||
/// ignora.
|
||||
pub fn with_datetime(mut self, dt: impl Into<Option<DateTime<Utc>>>) -> Self {
|
||||
self.value = dt.into().map_or(Value::None, Value::DateTime);
|
||||
self
|
||||
}
|
||||
|
||||
/// Establece el texto inicial tal cual, sin interpretarlo. Útil para volver a mostrar lo que
|
||||
/// escribió el usuario cuando no se ha podido leer.
|
||||
pub fn with_text(mut self, text: impl Into<String>) -> Self {
|
||||
self.value = Value::Text(text.into());
|
||||
self
|
||||
}
|
||||
|
||||
/// Establece la etiqueta visible del campo (usa [`Lc::none()`] para quitarla).
|
||||
pub fn with_label(mut self, label: Lc) -> Self {
|
||||
self.label = label;
|
||||
self
|
||||
}
|
||||
|
||||
/// Establece el texto de ayuda del campo (usa [`Lc::none()`] para quitarlo).
|
||||
pub fn with_help_text(mut self, help_text: Lc) -> Self {
|
||||
self.help_text = help_text;
|
||||
self
|
||||
}
|
||||
|
||||
/// Establece la configuración de autocompletado del campo (`None` para desactivarlo, que es lo
|
||||
/// predeterminado). Por ejemplo, para una fecha de nacimiento:
|
||||
/// `form::Autocomplete::token(form::AutofillField::Bday)`.
|
||||
pub fn with_autocomplete(
|
||||
mut self,
|
||||
autocomplete: impl Into<Option<form::Autocomplete>>,
|
||||
) -> Self {
|
||||
self.autocomplete = autocomplete.into();
|
||||
self
|
||||
}
|
||||
|
||||
/// Establece si el campo recibe el foco automáticamente al cargar la página.
|
||||
pub fn with_autofocus(mut self, autofocus: bool) -> Self {
|
||||
self.autofocus = autofocus;
|
||||
self
|
||||
}
|
||||
|
||||
/// Establece si el campo es de sólo lectura.
|
||||
pub fn with_readonly(mut self, readonly: bool) -> Self {
|
||||
self.readonly = readonly;
|
||||
self
|
||||
}
|
||||
|
||||
/// Establece si el campo es obligatorio.
|
||||
pub fn with_required(mut self, required: bool) -> Self {
|
||||
self.required = required;
|
||||
self
|
||||
}
|
||||
|
||||
/// Establece si el campo está deshabilitado.
|
||||
pub fn with_disabled(mut self, disabled: bool) -> Self {
|
||||
self.disabled = disabled;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
|
@ -220,6 +220,9 @@ impl Component for Field {
|
|||
async fn prepare(&self, cx: &mut Context) -> Result<Markup, ComponentError> {
|
||||
let container_id = self.id();
|
||||
let input_id = container_id.as_deref().map(|id| util::join!(id, "-input"));
|
||||
let help = form::parts::Help::new(self.help_text(), input_id.as_deref());
|
||||
let label = form::parts::Label::new(self.label(), input_id.as_deref())
|
||||
.with_required(*self.required());
|
||||
let input_class = if *self.plaintext() {
|
||||
"form-control-plaintext"
|
||||
} else {
|
||||
|
|
@ -235,22 +238,11 @@ impl Component for Field {
|
|||
|
||||
Ok(html! {
|
||||
div (self.props().unpack(cx)) {
|
||||
@if let Some(label) = self.label().lookup(cx) {
|
||||
label for=[input_id.as_deref()] class="form-label" {
|
||||
(label)
|
||||
@if *self.required() {
|
||||
span
|
||||
class="form-required"
|
||||
title=[Lc::l("field_required").lookup(cx)]
|
||||
{
|
||||
"*"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
(label.render(cx))
|
||||
input
|
||||
type=(self.kind())
|
||||
id=[input_id.as_deref()]
|
||||
aria-describedby=[help.id()]
|
||||
class=(input_class)
|
||||
name=[self.name().as_deref()]
|
||||
value=[self.value().as_deref()]
|
||||
|
|
@ -267,9 +259,7 @@ impl Component for Field {
|
|||
onfocus=[strict.then_some("this.removeAttribute('readonly')")]
|
||||
required[*self.required()]
|
||||
disabled[*self.disabled()];
|
||||
@if let Some(description) = self.help_text().lookup(cx) {
|
||||
div class="form-text" { (description) }
|
||||
}
|
||||
(help.render(cx))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
|
|
|||
|
|
@ -85,24 +85,16 @@ impl Component for Number {
|
|||
async fn prepare(&self, cx: &mut Context) -> Result<Markup, ComponentError> {
|
||||
let container_id = self.id();
|
||||
let input_id = container_id.as_deref().map(|id| util::join!(id, "-input"));
|
||||
let help = form::parts::Help::new(self.help_text(), input_id.as_deref());
|
||||
let label = form::parts::Label::new(self.label(), input_id.as_deref())
|
||||
.with_required(*self.required());
|
||||
Ok(html! {
|
||||
div (self.props().unpack(cx)) {
|
||||
@if let Some(label) = self.label().lookup(cx) {
|
||||
label for=[input_id.as_deref()] class="form-label" {
|
||||
(label)
|
||||
@if *self.required() {
|
||||
span
|
||||
class="form-required"
|
||||
title=[Lc::l("field_required").lookup(cx)]
|
||||
{
|
||||
"*"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
(label.render(cx))
|
||||
input
|
||||
type="number"
|
||||
id=[input_id.as_deref()]
|
||||
aria-describedby=[help.id()]
|
||||
class="form-control"
|
||||
name=[self.name().as_deref()]
|
||||
min=[self.min()]
|
||||
|
|
@ -113,9 +105,7 @@ impl Component for Number {
|
|||
readonly[*self.readonly()]
|
||||
required[*self.required()]
|
||||
disabled[*self.disabled()];
|
||||
@if let Some(description) = self.help_text().lookup(cx) {
|
||||
div class="form-text" { (description) }
|
||||
}
|
||||
(help.render(cx))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
|
|
|||
123
src/base/component/form/parts.rs
Normal file
123
src/base/component/form/parts.rs
Normal file
|
|
@ -0,0 +1,123 @@
|
|||
//! Piezas de marcado compartidas por los campos de formulario.
|
||||
//!
|
||||
//! [`form::parts::Label`](Label) (la etiqueta del campo, más la marca opcional de campo
|
||||
//! obligatorio) y [`form::parts::Help`](Help) (el texto de ayuda) generan marcado común para los
|
||||
//! principales campos de formularios, y quedan disponibles para los temas que puedan necesitarlos.
|
||||
//!
|
||||
//! **No son componentes**. Se crean dentro de `prepare()` (o del renderizado de un tema) a partir
|
||||
//! de los textos del campo, y se insertan en [`html!`] con su método `render()`, que los traduce al
|
||||
//! idioma del contexto.
|
||||
//!
|
||||
//! # Accesibilidad
|
||||
//!
|
||||
//! Es uno de sus puntos fuertes. Permiten aplicar de forma uniforme las relaciones que las pautas
|
||||
//! [WCAG 2.2] exigen en los formularios desde el nivel A, con atributos [WAI-ARIA] cuando HTML no
|
||||
//! basta:
|
||||
//!
|
||||
//! - **Cada etiqueta queda asociada a su control** con `for` o, en un grupo de controles, al
|
||||
//! contenedor del grupo, que la enlaza con `aria-labelledby`. Así el control o el grupo quedan
|
||||
//! con un nombre accesible.
|
||||
//! - **El texto de ayuda queda asociado al control** (o al contenedor del grupo) con
|
||||
//! `aria-describedby`, de modo que las tecnologías de apoyo suelen anunciarlo como descripción.
|
||||
//! - **No dejan referencias rotas**. Sin texto, o sin identificador al que enlazar, no se genera la
|
||||
//! relación.
|
||||
//!
|
||||
//! La marca de obligatorio (`*`) es texto de la etiqueta. Que el campo es obligatorio lo determina
|
||||
//! el atributo `required` del propio control, que pone cada componente, igual que el `role="group"`
|
||||
//! del contenedor de un grupo. Los atributos `aria-describedby` y `aria-labelledby` también los
|
||||
//! escribe el componente, con los identificadores que dan [`Help::id()`] y [`Label::id()`].
|
||||
//!
|
||||
//! [WCAG 2.2]: https://www.w3.org/TR/WCAG22/
|
||||
//! [WAI-ARIA]: https://www.w3.org/TR/wai-aria-1.2/
|
||||
//!
|
||||
//! # En un tema
|
||||
//!
|
||||
//! Un tema que renderice su propio marcado de un campo (con `render_component()`) puede:
|
||||
//!
|
||||
//! - **Reutilizarlas**, que es lo recomendable. Basta con añadir `aria-describedby=[help.id()]` al
|
||||
//! control (y `aria-labelledby=[label.id()]` al contenedor de un grupo) para conservar los
|
||||
//! enlaces de accesibilidad. Las piezas sirven aunque el tema cambie el orden de los elementos
|
||||
//! (p. ej. la etiqueta detrás del control, para una etiqueta flotante) o use otras clases
|
||||
//! (`with_class()` de cada pieza).
|
||||
//! - **Reimplementar el marcado por completo**, si necesita otro distinto. En ese caso se
|
||||
//! recomienda mantener los enlaces de accesibilidad: la etiqueta asociada al control con `for`
|
||||
//! (o, en un grupo de controles, al contenedor con `aria-labelledby`) y el texto de ayuda
|
||||
//! asociado con `aria-describedby`.
|
||||
//!
|
||||
//! # Ejemplo
|
||||
//!
|
||||
//! Un control con su etiqueta, marcado como obligatorio, y su texto de ayuda:
|
||||
//!
|
||||
//! ```rust
|
||||
//! # use pagetop::prelude::*;
|
||||
//! # let cx = Context::default().with_langid(&Locale::resolve("en-US"));
|
||||
//! let (name, hint) = (Lc::n("Name"), Lc::n("As on your ID card."));
|
||||
//! let label = form::parts::Label::new(&name, Some("edit-name-input")).with_required(true);
|
||||
//! let help = form::parts::Help::new(&hint, Some("edit-name-input"));
|
||||
//! let markup = html! {
|
||||
//! (label.render(&cx))
|
||||
//! input type="text" id="edit-name-input" aria-describedby=[help.id()];
|
||||
//! (help.render(&cx))
|
||||
//! };
|
||||
//! # assert_eq!(markup.into_string(), concat!(
|
||||
//! # r#"<label for="edit-name-input" class="form-label">Name"#,
|
||||
//! # r#"<span class="form-required" title="This field is required">*</span></label>"#,
|
||||
//! # r#"<input type="text" id="edit-name-input" aria-describedby="edit-name-input-help">"#,
|
||||
//! # r#"<div id="edit-name-input-help" class="form-text">As on your ID card.</div>"#,
|
||||
//! # ));
|
||||
//! ```
|
||||
//!
|
||||
//! genera:
|
||||
//!
|
||||
//! ```html
|
||||
//! <label for="edit-name-input" class="form-label">
|
||||
//! Name<span class="form-required" title="This field is required">*</span>
|
||||
//! </label>
|
||||
//! <input type="text" id="edit-name-input" aria-describedby="edit-name-input-help">
|
||||
//! <div id="edit-name-input-help" class="form-text">As on your ID card.</div>
|
||||
//! ```
|
||||
//!
|
||||
//! Un grupo de controles (casillas o botones de opción), cuyo contenedor enlaza la etiqueta y el
|
||||
//! texto de ayuda del grupo:
|
||||
//!
|
||||
//! ```rust
|
||||
//! # use pagetop::prelude::*;
|
||||
//! # let cx = Context::default().with_langid(&Locale::resolve("en-US"));
|
||||
//! let (name, hint) = (Lc::n("Notifications"), Lc::n("Choose one or more."));
|
||||
//! let label = form::parts::Label::group(&name, "edit-notify");
|
||||
//! let help = form::parts::Help::new(&hint, Some("edit-notify"));
|
||||
//! let markup = html! {
|
||||
//! div id="edit-notify" role="group"
|
||||
//! aria-labelledby=[label.id()] aria-describedby=[help.id()]
|
||||
//! {
|
||||
//! (label.render(&cx))
|
||||
//! // Aquí, las casillas o los botones de opción del grupo.
|
||||
//! (help.render(&cx))
|
||||
//! }
|
||||
//! };
|
||||
//! # assert_eq!(markup.into_string(), concat!(
|
||||
//! # r#"<div id="edit-notify" role="group" aria-labelledby="edit-notify-label" "#,
|
||||
//! # r#"aria-describedby="edit-notify-help">"#,
|
||||
//! # r#"<label id="edit-notify-label" class="form-label">Notifications</label>"#,
|
||||
//! # r#"<div id="edit-notify-help" class="form-text">Choose one or more.</div></div>"#,
|
||||
//! # ));
|
||||
//! ```
|
||||
//!
|
||||
//! genera:
|
||||
//!
|
||||
//! ```html
|
||||
//! <div id="edit-notify" role="group"
|
||||
//! aria-labelledby="edit-notify-label" aria-describedby="edit-notify-help">
|
||||
//! <label id="edit-notify-label" class="form-label">Notifications</label>
|
||||
//! <!-- Aquí, las casillas o los botones de opción del grupo. -->
|
||||
//! <div id="edit-notify-help" class="form-text">Choose one or more.</div>
|
||||
//! </div>
|
||||
//! ```
|
||||
//!
|
||||
//! [`html!`]: crate::html::html
|
||||
|
||||
mod help;
|
||||
pub use help::Help;
|
||||
|
||||
mod label;
|
||||
pub use label::Label;
|
||||
87
src/base/component/form/parts/help.rs
Normal file
87
src/base/component/form/parts/help.rs
Normal file
|
|
@ -0,0 +1,87 @@
|
|||
use crate::prelude::*;
|
||||
|
||||
/// Texto de ayuda de un campo de formulario.
|
||||
///
|
||||
/// Muestra el texto de ayuda de un control (o de un grupo de controles), con un identificador para
|
||||
/// que el control (o el contenedor del grupo) lo enlace con `aria-describedby`, de modo que las
|
||||
/// tecnologías de apoyo suelen anunciarlo al entrar en el campo. Se renderiza con
|
||||
/// [`render()`](Self::render), que genera un `<div>`, o nada si el texto es [`Lc::none()`]. La
|
||||
/// clase predeterminada (`form-text`) puede cambiarse con [`with_class()`](Self::with_class).
|
||||
///
|
||||
/// Se puede crear con:
|
||||
///
|
||||
/// - [`new()`](Self::new): para el texto de ayuda de un control, con el identificador
|
||||
/// `{anchor_id}-help`.
|
||||
/// - [`suffixed()`](Self::suffixed): para otro texto que describa al mismo control, con otro sufijo
|
||||
/// en el identificador.
|
||||
///
|
||||
/// # Ejemplo
|
||||
///
|
||||
/// ```rust,no_run
|
||||
/// # use pagetop::prelude::*;
|
||||
/// # fn render(help_text: &Lc, input_id: Option<&str>, cx: &Context) -> Markup {
|
||||
/// let help = form::parts::Help::new(help_text, input_id);
|
||||
/// html! {
|
||||
/// input type="text" id=[input_id] aria-describedby=[help.id()];
|
||||
/// (help.render(cx))
|
||||
/// }
|
||||
/// # }
|
||||
/// ```
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Help<'a> {
|
||||
text: &'a Lc,
|
||||
id: Option<String>,
|
||||
class: CowStr,
|
||||
}
|
||||
|
||||
impl<'a> Help<'a> {
|
||||
/// Texto de ayuda `help_text` con el identificador `{anchor_id}-help`, donde `anchor_id` es el
|
||||
/// identificador del control (o del contenedor, si el texto describe a un grupo de controles).
|
||||
/// Sin `anchor_id` el texto se muestra igual, pero sin identificador.
|
||||
pub fn new(help_text: &'a Lc, anchor_id: Option<&str>) -> Self {
|
||||
Self::suffixed(help_text, anchor_id, "-help")
|
||||
}
|
||||
|
||||
/// Igual que [`new()`](Self::new), pero con otro sufijo para el identificador, que se añade tal
|
||||
/// cual (p. ej. `-format` da `{anchor_id}-format`). Es útil cuando un mismo control tiene más
|
||||
/// de un texto que lo describe: cada uno necesita un sufijo distinto, y el control los enlaza
|
||||
/// todos en `aria-describedby`, separados por espacios.
|
||||
pub fn suffixed(help_text: &'a Lc, anchor_id: Option<&str>, suffix: &str) -> Self {
|
||||
// Sin texto no hay nada que enlazar, y sin identificador del control no hay de qué derivar
|
||||
// uno: en ambos casos se omite el identificador para no dejar una referencia rota.
|
||||
let id = anchor_id
|
||||
.filter(|_| !help_text.is_none())
|
||||
.map(|anchor_id| util::join!(anchor_id, suffix));
|
||||
Self {
|
||||
text: help_text,
|
||||
id,
|
||||
class: CowStr::Borrowed("form-text"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Devuelve el identificador para `aria-describedby`, o `None` si el texto es [`Lc::none()`] o
|
||||
/// si no se indicó `anchor_id`.
|
||||
pub fn id(&self) -> Option<&str> {
|
||||
self.id.as_deref()
|
||||
}
|
||||
|
||||
/// Renderiza el texto de ayuda traducido al idioma del contexto.
|
||||
pub fn render(&self, cx: &Context) -> Markup {
|
||||
// Se genera el elemento aunque falte la traducción, para que `id()` no quede sin destino.
|
||||
html! {
|
||||
@if !self.text.is_none() {
|
||||
div id=[self.id()] class=(self.class) { (self.text.lookup(cx).unwrap_or_default()) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[builder_impl]
|
||||
impl<'a> Help<'a> {
|
||||
/// Sustituye la clase del texto de ayuda (por defecto, `form-text`) por otra u otras, separadas
|
||||
/// por espacios; útil para un tema cuyo marcado use otras clases.
|
||||
pub fn with_class(mut self, class: impl Into<CowStr>) -> Self {
|
||||
self.class = class.into();
|
||||
self
|
||||
}
|
||||
}
|
||||
119
src/base/component/form/parts/label.rs
Normal file
119
src/base/component/form/parts/label.rs
Normal file
|
|
@ -0,0 +1,119 @@
|
|||
use crate::prelude::*;
|
||||
|
||||
/// Etiqueta de un campo de formulario, con la marca opcional de campo obligatorio.
|
||||
///
|
||||
/// Muestra la etiqueta del campo y, si es obligatorio ([`with_required()`](Self::with_required)),
|
||||
/// le añade un asterisco con un texto emergente traducido (`field_required`). Se renderiza con
|
||||
/// [`render()`](Self::render), que genera un `<label>`, o nada si el texto es [`Lc::none()`]. La
|
||||
/// clase predeterminada (`form-label`, o `form-check-label` en [`check()`](Self::check)) puede
|
||||
/// cambiarse con [`with_class()`](Self::with_class).
|
||||
///
|
||||
/// Se puede crear con:
|
||||
///
|
||||
/// - [`new()`](Self::new): para añadir la etiqueta a un control, enlazada con su atributo `for`.
|
||||
/// - [`check()`](Self::check): para el texto de una casilla de verificación, junto a ella.
|
||||
/// - [`group()`](Self::group): para el nombre de un grupo de controles (casillas, botones de
|
||||
/// opción), con un identificador para enlazarlo desde el grupo con `aria-labelledby`.
|
||||
///
|
||||
/// # Ejemplo
|
||||
///
|
||||
/// ```rust,no_run
|
||||
/// # use pagetop::prelude::*;
|
||||
/// # fn render(label: &Lc, input_id: Option<&str>, required: bool, cx: &Context) -> Markup {
|
||||
/// let label = form::parts::Label::new(label, input_id).with_required(required);
|
||||
/// html! {
|
||||
/// (label.render(cx))
|
||||
/// input type="text" id=[input_id] required[required];
|
||||
/// }
|
||||
/// # }
|
||||
/// ```
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Label<'a> {
|
||||
text: &'a Lc,
|
||||
for_id: Option<&'a str>,
|
||||
id: Option<String>,
|
||||
class: CowStr,
|
||||
required: bool,
|
||||
}
|
||||
|
||||
impl<'a> Label<'a> {
|
||||
/// Etiqueta del control con identificador `control_id` (atributo `for`), con la clase
|
||||
/// `form-label`.
|
||||
pub fn new(label: &'a Lc, control_id: Option<&'a str>) -> Self {
|
||||
Self::build(label, control_id, None, "form-label")
|
||||
}
|
||||
|
||||
/// Texto de una casilla de verificación con identificador `control_id`, que se coloca junto a
|
||||
/// ella, con la clase `form-check-label`.
|
||||
pub fn check(label: &'a Lc, control_id: Option<&'a str>) -> Self {
|
||||
Self::build(label, control_id, None, "form-check-label")
|
||||
}
|
||||
|
||||
/// Nombre de un grupo de controles cuyo contenedor tiene el identificador `group_id`, con la
|
||||
/// clase `form-label`. No se enlaza con `for` (no hay un único control), sino que recibe el
|
||||
/// identificador `{group_id}-label` para que el contenedor lo enlace con `aria-labelledby`.
|
||||
pub fn group(label: &'a Lc, group_id: &str) -> Self {
|
||||
// Sin texto no se genera la etiqueta, así que tampoco hay identificador al que enlazar.
|
||||
let id = (!label.is_none()).then(|| util::join!(group_id, "-label"));
|
||||
Self::build(label, None, id, "form-label")
|
||||
}
|
||||
|
||||
fn build(
|
||||
label: &'a Lc,
|
||||
for_id: Option<&'a str>,
|
||||
id: Option<String>,
|
||||
class: &'static str,
|
||||
) -> Self {
|
||||
Self {
|
||||
text: label,
|
||||
for_id,
|
||||
id,
|
||||
class: CowStr::Borrowed(class),
|
||||
required: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Devuelve el identificador para `aria-labelledby` (sólo en [`group()`](Self::group)), o
|
||||
/// `None` si el texto es [`Lc::none()`].
|
||||
pub fn id(&self) -> Option<&str> {
|
||||
self.id.as_deref()
|
||||
}
|
||||
|
||||
/// Renderiza la etiqueta traducida al idioma del contexto.
|
||||
pub fn render(&self, cx: &Context) -> Markup {
|
||||
// Se genera el elemento aunque falte la traducción, para que `id()` no quede sin destino.
|
||||
html! {
|
||||
@if !self.text.is_none() {
|
||||
label for=[self.for_id] id=[self.id()] class=(self.class) {
|
||||
(self.text.lookup(cx).unwrap_or_default())
|
||||
@if self.required {
|
||||
span
|
||||
class="form-required"
|
||||
title=[Lc::l("field_required").lookup(cx)]
|
||||
{
|
||||
"*"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[builder_impl]
|
||||
impl<'a> Label<'a> {
|
||||
/// Sustituye la clase de la etiqueta (por defecto, `form-label`, o `form-check-label` en
|
||||
/// [`check()`](Self::check)) por otra u otras, separadas por espacios; útil para un tema cuyo
|
||||
/// marcado use otras clases.
|
||||
pub fn with_class(mut self, class: impl Into<CowStr>) -> Self {
|
||||
self.class = class.into();
|
||||
self
|
||||
}
|
||||
|
||||
/// Indica si el campo es obligatorio, para añadir el asterisco a la etiqueta. El atributo
|
||||
/// `required` lo pone el propio control.
|
||||
pub fn with_required(mut self, required: bool) -> Self {
|
||||
self.required = required;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
|
@ -142,22 +142,19 @@ impl Component for Field {
|
|||
// En `setup()` se garantiza que `name` e `id` están definidos antes del renderizado.
|
||||
let name = self.name().as_deref().unwrap();
|
||||
let container_id = self.id().unwrap();
|
||||
// El contenedor agrupa las opciones: su etiqueta y su texto de ayuda describen al grupo.
|
||||
let label =
|
||||
form::parts::Label::group(self.label(), &container_id).with_required(*self.required());
|
||||
let help = form::parts::Help::new(self.help_text(), Some(&container_id));
|
||||
|
||||
Ok(html! {
|
||||
div (self.props().unpack(cx)) {
|
||||
@if let Some(label) = self.label().lookup(cx) {
|
||||
label class="form-label" {
|
||||
(label)
|
||||
@if *self.required() {
|
||||
span
|
||||
class="form-required"
|
||||
title=[Lc::l("field_required").lookup(cx)]
|
||||
{
|
||||
"*"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
div
|
||||
(self.props().unpack(cx))
|
||||
role="group"
|
||||
aria-labelledby=[label.id()]
|
||||
aria-describedby=[help.id()]
|
||||
{
|
||||
(label.render(cx))
|
||||
@let item_classes = if *self.inline() {
|
||||
"form-check form-check-inline"
|
||||
} else {
|
||||
|
|
@ -187,9 +184,7 @@ impl Component for Field {
|
|||
}
|
||||
}
|
||||
}
|
||||
@if let Some(description) = self.help_text().lookup(cx) {
|
||||
div class="form-text" { (description) }
|
||||
}
|
||||
(help.render(cx))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
|
|
|||
|
|
@ -82,14 +82,15 @@ impl Component for Range {
|
|||
async fn prepare(&self, cx: &mut Context) -> Result<Markup, ComponentError> {
|
||||
let container_id = self.id();
|
||||
let range_id = container_id.as_deref().map(|id| util::join!(id, "-range"));
|
||||
let help = form::parts::Help::new(self.help_text(), range_id.as_deref());
|
||||
let label = form::parts::Label::new(self.label(), range_id.as_deref());
|
||||
Ok(html! {
|
||||
div (self.props().unpack(cx)) {
|
||||
@if let Some(label) = self.label().lookup(cx) {
|
||||
label for=[range_id.as_deref()] class="form-label" { (label) }
|
||||
}
|
||||
(label.render(cx))
|
||||
input
|
||||
type="range"
|
||||
id=[range_id.as_deref()]
|
||||
aria-describedby=[help.id()]
|
||||
class="form-range"
|
||||
name=[self.name().as_deref()]
|
||||
min=[self.min()]
|
||||
|
|
@ -98,9 +99,7 @@ impl Component for Range {
|
|||
value=[self.value()]
|
||||
autofocus[*self.autofocus()]
|
||||
disabled[*self.disabled()];
|
||||
@if let Some(description) = self.help_text().lookup(cx) {
|
||||
div class="form-text" { (description) }
|
||||
}
|
||||
(help.render(cx))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
|
|
|||
|
|
@ -240,24 +240,16 @@ impl Component for Field {
|
|||
async fn prepare(&self, cx: &mut Context) -> Result<Markup, ComponentError> {
|
||||
let container_id = self.id();
|
||||
let select_id = container_id.as_deref().map(|id| util::join!(id, "-select"));
|
||||
let help = form::parts::Help::new(self.help_text(), select_id.as_deref());
|
||||
let label = form::parts::Label::new(self.label(), select_id.as_deref())
|
||||
.with_required(*self.required());
|
||||
|
||||
Ok(html! {
|
||||
div (self.props().unpack(cx)) {
|
||||
@if let Some(label) = self.label().lookup(cx) {
|
||||
label for=[select_id.as_deref()] class="form-label" {
|
||||
(label)
|
||||
@if *self.required() {
|
||||
span
|
||||
class="form-required"
|
||||
title=[Lc::l("field_required").lookup(cx)]
|
||||
{
|
||||
"*"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
(label.render(cx))
|
||||
select
|
||||
id=[select_id.as_deref()]
|
||||
aria-describedby=[help.id()]
|
||||
class="form-select"
|
||||
name=[self.name().as_deref()]
|
||||
multiple[*self.multiple()]
|
||||
|
|
@ -297,9 +289,7 @@ impl Component for Field {
|
|||
}
|
||||
}
|
||||
}
|
||||
@if let Some(description) = self.help_text().lookup(cx) {
|
||||
div class="form-text" { (description) }
|
||||
}
|
||||
(help.render(cx))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
|
|
|||
|
|
@ -93,24 +93,16 @@ impl Component for Textarea {
|
|||
let textarea_id = container_id
|
||||
.as_deref()
|
||||
.map(|id| util::join!(id, "-textarea"));
|
||||
let help = form::parts::Help::new(self.help_text(), textarea_id.as_deref());
|
||||
let label = form::parts::Label::new(self.label(), textarea_id.as_deref())
|
||||
.with_required(*self.required());
|
||||
|
||||
Ok(html! {
|
||||
div (self.props().unpack(cx)) {
|
||||
@if let Some(label) = self.label().lookup(cx) {
|
||||
label for=[textarea_id.as_deref()] class="form-label" {
|
||||
(label)
|
||||
@if *self.required() {
|
||||
span
|
||||
class="form-required"
|
||||
title=[Lc::l("field_required").lookup(cx)]
|
||||
{
|
||||
"*"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
(label.render(cx))
|
||||
textarea
|
||||
id=[textarea_id.as_deref()]
|
||||
aria-describedby=[help.id()]
|
||||
class="form-control"
|
||||
name=[self.name().as_deref()]
|
||||
rows=[self.rows()]
|
||||
|
|
@ -127,9 +119,7 @@ impl Component for Textarea {
|
|||
(value)
|
||||
}
|
||||
}
|
||||
@if let Some(description) = self.help_text().lookup(cx) {
|
||||
div class="form-text" { (description) }
|
||||
}
|
||||
(help.render(cx))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@ use crate::builder_impl;
|
|||
use crate::core::component::ChildOp;
|
||||
use crate::core::theme::{RegionRef, TemplateRef, ThemeRef};
|
||||
use crate::datetime::{DateFormat, DatePrecision, RelativeFormat, TimeFormat};
|
||||
use crate::datetime::{DateTime, NaiveDate, Tz, Utc};
|
||||
use crate::datetime::{DateInputError, DateTime, NaiveDate, NaiveTime, Tz, Utc};
|
||||
use crate::html::{Assets, Favicon, JavaScript, Props, PropsOp, ResponsiveStyles, StyleSheet};
|
||||
use crate::locale::{LangId, Lc};
|
||||
use crate::web::HttpRequest;
|
||||
|
|
@ -399,6 +399,79 @@ pub trait Contextual: LangId {
|
|||
precision.apply_until(date, self)
|
||||
}
|
||||
|
||||
/// Lee una fecha sin hora escrita por el usuario (p. ej. en un
|
||||
/// [`form::date::Field::date()`](crate::base::component::form::date::Field::date)).
|
||||
///
|
||||
/// Acepta el formato de fecha del idioma efectivo del documento (p. ej. `dd/mm/aaaa` en
|
||||
/// español o `mm/dd/yyyy` en inglés de Estados Unidos), con día y mes de una o dos cifras y el
|
||||
/// año siempre con cuatro, y también el formato ISO 8601 (`aaaa-mm-dd`). Es el mismo formato
|
||||
/// con el que el campo muestra el valor. Una fecha sin hora no se convierte de zona horaria
|
||||
/// (ver [`format_date()`](Self::format_date)).
|
||||
///
|
||||
/// Devuelve `Ok(None)` si el texto está en blanco; comprobar si el campo es obligatorio queda
|
||||
/// a cargo de quien llama.
|
||||
///
|
||||
/// # Ejemplo
|
||||
///
|
||||
/// ```rust,no_run
|
||||
/// # use pagetop::prelude::*;
|
||||
/// # fn read(cx: &Context, text: &str) -> Result<(), Lc> {
|
||||
/// let expires: Option<NaiveDate> = cx.parse_date(text).map_err(|e| e.message())?;
|
||||
/// # Ok(())
|
||||
/// # }
|
||||
/// ```
|
||||
fn parse_date(&self, text: &str) -> Result<Option<NaiveDate>, DateInputError>
|
||||
where
|
||||
Self: Sized,
|
||||
{
|
||||
crate::datetime::input::parse_date(text, self)
|
||||
}
|
||||
|
||||
/// Lee una hora del día escrita por el usuario (p. ej. en un
|
||||
/// [`form::date::Field::time()`](crate::base::component::form::date::Field::time)).
|
||||
///
|
||||
/// Acepta el formato de hora del idioma efectivo (p. ej. `hh:mm`), con la hora y los minutos de
|
||||
/// una o dos cifras, y también `hh:mm` en ISO 8601. No se convierte de zona horaria: es una
|
||||
/// hora civil. Devuelve `Ok(None)` si el texto está en blanco.
|
||||
fn parse_time(&self, text: &str) -> Result<Option<NaiveTime>, DateInputError>
|
||||
where
|
||||
Self: Sized,
|
||||
{
|
||||
crate::datetime::input::parse_time(text, self)
|
||||
}
|
||||
|
||||
/// Lee una fecha y hora escrita por el usuario en su hora local (p. ej. en un
|
||||
/// [`form::date::Field::datetime()`](crate::base::component::form::date::Field::datetime)) y
|
||||
/// la convierte a UTC, que es como se graban siempre los instantes.
|
||||
///
|
||||
/// Acepta el formato del idioma efectivo (la fecha y la hora separadas por un espacio, p. ej.
|
||||
/// `dd/mm/aaaa hh:mm`) y también ISO 8601 (`aaaa-mm-ddThh:mm`, con `T` o con un espacio entre
|
||||
/// la fecha y la hora), y lo interpreta en la zona horaria efectiva del documento
|
||||
/// ([`timezone()`](Self::timezone)). Devuelve `Ok(None)` si el texto está en blanco.
|
||||
///
|
||||
/// En los cambios de hora:
|
||||
///
|
||||
/// - Una hora que no existe, porque el reloj se adelanta (p. ej. las 02:30 del último domingo
|
||||
/// de marzo en Madrid), devuelve [`DateInputError::NonexistentTime`].
|
||||
/// - Una hora que existe dos veces, porque el reloj se retrasa (p. ej. las 02:30 del último
|
||||
/// domingo de octubre en Madrid), se interpreta como la primera de las dos.
|
||||
///
|
||||
/// # Ejemplo
|
||||
///
|
||||
/// ```rust,no_run
|
||||
/// # use pagetop::prelude::*;
|
||||
/// # fn read(cx: &Context, text: &str) -> Result<(), Lc> {
|
||||
/// let extracted: Option<DateTime<Utc>> = cx.parse_datetime(text).map_err(|e| e.message())?;
|
||||
/// # Ok(())
|
||||
/// # }
|
||||
/// ```
|
||||
fn parse_datetime(&self, text: &str) -> Result<Option<DateTime<Utc>>, DateInputError>
|
||||
where
|
||||
Self: Sized,
|
||||
{
|
||||
crate::datetime::input::parse_datetime(text, self, self.timezone())
|
||||
}
|
||||
|
||||
/// Elimina un parámetro del contexto. Devuelve `true` si la clave existía y se eliminó.
|
||||
///
|
||||
/// # Ejemplo
|
||||
|
|
|
|||
|
|
@ -99,8 +99,8 @@
|
|||
//! [`PropsOp::set_extra()`] para consumirlos en el `setup()` vía [`Theme::setup_component()`] o
|
||||
//! en el `render()` vía [`Theme::render_component()`]), o aportar componentes propios.
|
||||
//! `pagetop-bootsier` combina las tres estrategias: reexporta `Form`/`Fieldset` sin cambios,
|
||||
//! extiende `Button`/`Badge`/`Dropdown`/`Nav`/`Navbar` con sus propios traits (`ButtonBootsier`,
|
||||
//! `BadgeBootsier`, etc.), y añade componentes propios como `Offcanvas`.
|
||||
//! extiende `Button`/`Badge`/`Dropdown`/`Nav`/`Navbar` con sus propios traits (`ButtonBsExt`,
|
||||
//! `BadgeBsExt`, etc.), y añade componentes propios como `Offcanvas`.
|
||||
//!
|
||||
//! Para forzar una plantilla completamente distinta en una página concreta, se puede llamar
|
||||
//! manualmente a [`with_template()`].
|
||||
|
|
|
|||
|
|
@ -23,6 +23,12 @@
|
|||
//! (`src/locale/{lang}/datetime.ftl`), con el mismo mecanismo que cualquier otro texto traducido de
|
||||
//! PageTop.
|
||||
//!
|
||||
//! Las fechas y horas que escribe el usuario se leen en el formato del idioma efectivo (p. ej.
|
||||
//! `dd/mm/aaaa` en español) y, si son instantes, en su hora local, para grabarlas en UTC. Los
|
||||
//! campos de [`form::date::Field`] las muestran así, y [`Contextual::parse_date()`],
|
||||
//! [`Contextual::parse_time()`] y [`Contextual::parse_datetime()`] las leen y devuelven un
|
||||
//! [`DateInputError`] si no se pueden interpretar.
|
||||
//!
|
||||
//! [`RelativeFormat`] muestra una fecha en relación al momento actual ("hace 3 años", "dentro de 5
|
||||
//! días") en vez de como fecha absoluta, con el mismo mecanismo de claves Fluent, vía
|
||||
//! [`Contextual::format_relative()`].
|
||||
|
|
@ -33,12 +39,20 @@
|
|||
//! [ISO 8601]: https://en.wikipedia.org/wiki/ISO_8601
|
||||
//! [chrono]: https://docs.rs/chrono
|
||||
//! [chrono-tz]: https://docs.rs/chrono-tz
|
||||
//! [`CurrentUser::timezone()`]: crate::auth::CurrentUser::timezone
|
||||
//! [`timezone_per_user`]: crate::global::App::timezone_per_user
|
||||
//! [`CurrentUser::timezone()`]: crate::auth::CurrentUser::timezone
|
||||
//! [`form::date::Field`]: crate::base::component::form::date::Field
|
||||
//! [`Contextual::format_datetime()`]: crate::core::component::Contextual::format_datetime
|
||||
//! [`Contextual::format_relative()`]: crate::core::component::Contextual::format_relative
|
||||
//! [`Contextual::format_since()`]: crate::core::component::Contextual::format_since
|
||||
//! [`Contextual::format_until()`]: crate::core::component::Contextual::format_until
|
||||
//! [`Contextual::parse_date()`]: crate::core::component::Contextual::parse_date
|
||||
//! [`Contextual::parse_time()`]: crate::core::component::Contextual::parse_time
|
||||
//! [`Contextual::parse_datetime()`]: crate::core::component::Contextual::parse_datetime
|
||||
|
||||
use crate::locale::Lc;
|
||||
|
||||
use thiserror::Error;
|
||||
|
||||
// Reexportado para que el resto del código y las extensiones se refieran siempre a `datetime::X`,
|
||||
// nunca a `chrono` directamente (mismo criterio que `Tz`/`TZ_VARIANTS` más abajo). No es todo el
|
||||
|
|
@ -79,3 +93,62 @@ pub use relative::RelativeFormat;
|
|||
|
||||
mod precision;
|
||||
pub use precision::DatePrecision;
|
||||
|
||||
pub(crate) mod input;
|
||||
|
||||
/// Errores al leer una fecha u hora escrita por el usuario.
|
||||
///
|
||||
/// Los devuelven [`Contextual::parse_date()`], [`Contextual::parse_time()`] y
|
||||
/// [`Contextual::parse_datetime()`]. [`message()`](Self::message) da un mensaje traducido para
|
||||
/// mostrarlo junto al formulario.
|
||||
///
|
||||
/// [`Contextual::parse_date()`]: crate::core::component::Contextual::parse_date
|
||||
/// [`Contextual::parse_time()`]: crate::core::component::Contextual::parse_time
|
||||
/// [`Contextual::parse_datetime()`]: crate::core::component::Contextual::parse_datetime
|
||||
#[derive(Clone, Debug, Error, PartialEq)]
|
||||
pub enum DateInputError {
|
||||
/// La fecha no está escrita en el formato del idioma (`hint`, p. ej. `dd/mm/aaaa`) ni en el
|
||||
/// formato ISO 8601, o no es una fecha válida (p. ej. `31/02/2026`).
|
||||
#[error("invalid date, expected format {hint}")]
|
||||
InvalidDate {
|
||||
/// Indicación del formato esperado, en el idioma del usuario.
|
||||
hint: String,
|
||||
},
|
||||
/// La hora no está escrita en el formato del idioma (`hint`, p. ej. `hh:mm`) ni en el formato
|
||||
/// ISO 8601, o no es una hora válida (p. ej. `25:00`).
|
||||
#[error("invalid time, expected format {hint}")]
|
||||
InvalidTime {
|
||||
/// Indicación del formato esperado, en el idioma del usuario.
|
||||
hint: String,
|
||||
},
|
||||
/// La fecha y hora no está escrita en el formato del idioma (`hint`, p. ej. `dd/mm/aaaa hh:mm`)
|
||||
/// ni en el formato ISO 8601, o no es una fecha y hora válida.
|
||||
#[error("invalid date and time, expected format {hint}")]
|
||||
InvalidDateTime {
|
||||
/// Indicación del formato esperado, en el idioma del usuario.
|
||||
hint: String,
|
||||
},
|
||||
/// La hora no existe en la zona horaria en la que se interpreta (la efectiva del documento)
|
||||
/// porque coincide con el adelanto del reloj al horario de verano (p. ej. las 02:30 del último
|
||||
/// domingo de marzo en Madrid).
|
||||
#[error("nonexistent local time due to a daylight saving time change")]
|
||||
NonexistentTime,
|
||||
}
|
||||
|
||||
impl DateInputError {
|
||||
/// Devuelve un mensaje traducido para el usuario, con el formato esperado si procede.
|
||||
pub fn message(&self) -> Lc {
|
||||
match self {
|
||||
Self::InvalidDate { hint } => {
|
||||
Lc::l("date_input_invalid").with_arg("format", hint.clone())
|
||||
}
|
||||
Self::InvalidTime { hint } => {
|
||||
Lc::l("time_input_invalid").with_arg("format", hint.clone())
|
||||
}
|
||||
Self::InvalidDateTime { hint } => {
|
||||
Lc::l("datetime_input_invalid").with_arg("format", hint.clone())
|
||||
}
|
||||
Self::NonexistentTime => Lc::l("datetime_input_nonexistent"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
144
src/datetime/input.rs
Normal file
144
src/datetime/input.rs
Normal file
|
|
@ -0,0 +1,144 @@
|
|||
use crate::locale::{LangId, Lc};
|
||||
|
||||
use super::{DateInputError, DateTime, NaiveDate, NaiveDateTime, NaiveTime, TimeZone, Tz, Utc};
|
||||
|
||||
use chrono::LocalResult;
|
||||
|
||||
// Patrones de respaldo (ISO 8601), sólo si faltase la clave Fluent del idioma (no debería ocurrir
|
||||
// porque el idioma de respaldo `en-US` siempre las define).
|
||||
const FALLBACK_DATE_FORMAT: &str = "%Y-%m-%d";
|
||||
const FALLBACK_TIME_FORMAT: &str = "%H:%M";
|
||||
|
||||
// Formatos ISO 8601 que se aceptan siempre, además del propio del idioma, para no rechazar un valor
|
||||
// pegado de otra fuente. No hay ambigüedad posible: empiezan por el año con cuatro cifras.
|
||||
const ISO_DATE: &str = "%Y-%m-%d";
|
||||
const ISO_TIME: &str = "%H:%M";
|
||||
const ISO_DATETIME: [&str; 2] = ["%Y-%m-%dT%H:%M", "%Y-%m-%d %H:%M"];
|
||||
|
||||
// Años admitidos. `chrono` acepta `%Y` con cualquier número de cifras, así que "06/10/26" se leería
|
||||
// como el año 26; se rechaza para que no pase inadvertido un año escrito con dos cifras.
|
||||
const YEARS: std::ops::RangeInclusive<i32> = 1000..=9999;
|
||||
|
||||
// Patrón `strftime` de fecha del idioma, el mismo para mostrar y para leer (p. ej. `%d/%m/%Y`).
|
||||
pub(crate) fn date_format(language: &impl LangId) -> String {
|
||||
Lc::l("date_input_format")
|
||||
.lookup(language)
|
||||
.unwrap_or_else(|| FALLBACK_DATE_FORMAT.to_string())
|
||||
}
|
||||
|
||||
// Patrón `strftime` de hora del idioma (p. ej. `%H:%M`).
|
||||
pub(crate) fn time_format(language: &impl LangId) -> String {
|
||||
Lc::l("time_input_format")
|
||||
.lookup(language)
|
||||
.unwrap_or_else(|| FALLBACK_TIME_FORMAT.to_string())
|
||||
}
|
||||
|
||||
// Patrón de fecha y hora: el de fecha y el de hora separados por un espacio.
|
||||
pub(crate) fn datetime_format(language: &impl LangId) -> String {
|
||||
let (date, time) = (date_format(language), time_format(language));
|
||||
crate::util::join!(date, " ", time)
|
||||
}
|
||||
|
||||
// Indicación del formato para el usuario (p. ej. `dd/mm/aaaa`).
|
||||
pub(crate) fn date_hint(language: &impl LangId) -> String {
|
||||
Lc::l("date_input_hint")
|
||||
.lookup(language)
|
||||
.unwrap_or_else(|| "yyyy-mm-dd".to_string())
|
||||
}
|
||||
|
||||
// Indicación del formato de hora para el usuario (p. ej. `hh:mm`).
|
||||
pub(crate) fn time_hint(language: &impl LangId) -> String {
|
||||
Lc::l("time_input_hint")
|
||||
.lookup(language)
|
||||
.unwrap_or_else(|| "hh:mm".to_string())
|
||||
}
|
||||
|
||||
// Indicación del formato de fecha y hora para el usuario (p. ej. `dd/mm/aaaa hh:mm`).
|
||||
pub(crate) fn datetime_hint(language: &impl LangId) -> String {
|
||||
let (date, time) = (date_hint(language), time_hint(language));
|
||||
crate::util::join!(date, " ", time)
|
||||
}
|
||||
|
||||
// Lee una fecha con el formato del idioma o en ISO 8601. En blanco devuelve `None`.
|
||||
pub(crate) fn parse_date(
|
||||
text: &str,
|
||||
language: &impl LangId,
|
||||
) -> Result<Option<NaiveDate>, DateInputError> {
|
||||
let text = text.trim();
|
||||
if text.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
[date_format(language).as_str(), ISO_DATE]
|
||||
.into_iter()
|
||||
.find_map(|format| NaiveDate::parse_from_str(text, format).ok())
|
||||
.filter(|date| YEARS.contains(&chrono::Datelike::year(date)))
|
||||
.map(Some)
|
||||
.ok_or_else(|| DateInputError::InvalidDate {
|
||||
hint: date_hint(language),
|
||||
})
|
||||
}
|
||||
|
||||
// Lee una hora con el formato del idioma o en ISO 8601. En blanco devuelve `None`.
|
||||
pub(crate) fn parse_time(
|
||||
text: &str,
|
||||
language: &impl LangId,
|
||||
) -> Result<Option<NaiveTime>, DateInputError> {
|
||||
let text = text.trim();
|
||||
if text.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
[time_format(language).as_str(), ISO_TIME]
|
||||
.into_iter()
|
||||
.find_map(|format| NaiveTime::parse_from_str(text, format).ok())
|
||||
.map(Some)
|
||||
.ok_or_else(|| DateInputError::InvalidTime {
|
||||
hint: time_hint(language),
|
||||
})
|
||||
}
|
||||
|
||||
// Lee una fecha y hora local de `tz`, con el formato del idioma o en ISO 8601, y la convierte a
|
||||
// UTC. En blanco devuelve `None`.
|
||||
//
|
||||
// En el cambio al horario de verano hay horas que no existen en `tz` (p. ej. las 02:30 del último
|
||||
// domingo de marzo en Madrid): se rechazan, porque cualquier corrección inventaría una hora que el
|
||||
// usuario no ha escrito. En el cambio al horario de invierno hay horas que existen dos veces: se
|
||||
// toma la primera porque el usuario no tiene forma de indicar cuál de las dos quería.
|
||||
pub(crate) fn parse_datetime(
|
||||
text: &str,
|
||||
language: &impl LangId,
|
||||
tz: Tz,
|
||||
) -> Result<Option<DateTime<Utc>>, DateInputError> {
|
||||
let text = text.trim();
|
||||
if text.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
let format = datetime_format(language);
|
||||
let local = std::iter::once(format.as_str())
|
||||
.chain(ISO_DATETIME)
|
||||
.find_map(|format| NaiveDateTime::parse_from_str(text, format).ok())
|
||||
.filter(|local| YEARS.contains(&chrono::Datelike::year(local)))
|
||||
.ok_or_else(|| DateInputError::InvalidDateTime {
|
||||
hint: datetime_hint(language),
|
||||
})?;
|
||||
match tz.from_local_datetime(&local) {
|
||||
LocalResult::Single(dt) | LocalResult::Ambiguous(dt, _) => Ok(Some(dt.with_timezone(&Utc))),
|
||||
LocalResult::None => Err(DateInputError::NonexistentTime),
|
||||
}
|
||||
}
|
||||
|
||||
// Muestra una fecha con el formato del idioma, tal como se lee después.
|
||||
pub(crate) fn format_date(date: NaiveDate, language: &impl LangId) -> String {
|
||||
date.format(&date_format(language)).to_string()
|
||||
}
|
||||
|
||||
// Muestra una hora con el formato del idioma, tal como se lee después.
|
||||
pub(crate) fn format_time(time: NaiveTime, language: &impl LangId) -> String {
|
||||
time.format(&time_format(language)).to_string()
|
||||
}
|
||||
|
||||
// Muestra un instante en `tz` con el formato del idioma, tal como se lee después.
|
||||
pub(crate) fn format_datetime(dt: DateTime<Utc>, language: &impl LangId, tz: Tz) -> String {
|
||||
dt.with_timezone(&tz)
|
||||
.format(&datetime_format(language))
|
||||
.to_string()
|
||||
}
|
||||
15
src/locale/en-GB/datetime.ftl
Normal file
15
src/locale/en-GB/datetime.ftl
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
# British English writes the day before the month. Only these keys differ from en-US; the rest
|
||||
# fall back to en-US.
|
||||
|
||||
# Date formats.
|
||||
date_format_short = { $day }/{ $month }/{ $year_short }
|
||||
date_format_medium = { $day }/{ $month }/{ $year }
|
||||
date_format_long = { $day } { $month } { $year }
|
||||
|
||||
# Date input (strftime pattern, see en-US).
|
||||
date_input_format = %d/%m/%Y
|
||||
date_input_hint = dd/mm/yyyy
|
||||
|
||||
# Start/end date precision.
|
||||
since_long = since { $day } { $month } { $year }
|
||||
until_long = until { $day } { $month } { $year }
|
||||
|
|
@ -8,6 +8,19 @@ time_format_short = { $hour }:{ $minute }
|
|||
time_format_long = { $hour }:{ $minute }:{ $second }
|
||||
datetime_join = { $date }, { $time }
|
||||
|
||||
# Date and time input. `date_input_format` and `time_input_format` are strftime patterns (%d day,
|
||||
# %m month, %Y four-digit year, %H hour, %M minute), not text: they are used both to show a value
|
||||
# and to read what the user types. Keep the date one in the same order as `date_format_medium`.
|
||||
date_input_format = %m/%d/%Y
|
||||
date_input_hint = mm/dd/yyyy
|
||||
time_input_format = %H:%M
|
||||
time_input_hint = hh:mm
|
||||
input_format_help = Format: { $format }
|
||||
date_input_invalid = Invalid date: use the format { $format }.
|
||||
time_input_invalid = Invalid time: use the format { $format }.
|
||||
datetime_input_invalid = Invalid date and time: use the format { $format }.
|
||||
datetime_input_nonexistent = That time does not exist in your time zone: the clock moves forward for daylight saving time.
|
||||
|
||||
# Relative dates.
|
||||
relative_today = today
|
||||
relative_years = { $n ->
|
||||
|
|
|
|||
|
|
@ -8,6 +8,19 @@ time_format_short = { $hour }:{ $minute }
|
|||
time_format_long = { $hour }:{ $minute }:{ $second }
|
||||
datetime_join = { $date }, { $time }
|
||||
|
||||
# Date and time input. `date_input_format` and `time_input_format` are strftime patterns (%d day,
|
||||
# %m month, %Y four-digit year, %H hour, %M minute), not text: they are used both to show a value
|
||||
# and to read what the user types. Keep the date one in the same order as `date_format_medium`.
|
||||
date_input_format = %d/%m/%Y
|
||||
date_input_hint = dd/mm/aaaa
|
||||
time_input_format = %H:%M
|
||||
time_input_hint = hh:mm
|
||||
input_format_help = Formato: { $format }
|
||||
date_input_invalid = Fecha no válida: usa el formato { $format }.
|
||||
time_input_invalid = Hora no válida: usa el formato { $format }.
|
||||
datetime_input_invalid = Fecha y hora no válidas: usa el formato { $format }.
|
||||
datetime_input_nonexistent = Esa hora no existe en tu zona horaria: coincide con el adelanto del reloj al horario de verano.
|
||||
|
||||
# Relative dates.
|
||||
relative_today = hoy
|
||||
relative_years = { $n ->
|
||||
|
|
|
|||
|
|
@ -213,6 +213,20 @@ impl Lc {
|
|||
|
||||
// **< Lc GETTERS >*****************************************************************************
|
||||
|
||||
/// Indica si la instancia está **sin contenido** ([`Lc::none()`]).
|
||||
///
|
||||
/// Que no lo esté no garantiza que haya traducción: una clave sin traducir también devuelve
|
||||
/// `None` con [`lookup()`](Self::lookup).
|
||||
///
|
||||
/// ```rust
|
||||
/// # use pagetop::prelude::*;
|
||||
/// assert!(Lc::none().is_none());
|
||||
/// assert!(!Lc::n("Hello").is_none());
|
||||
/// ```
|
||||
pub fn is_none(&self) -> bool {
|
||||
matches!(self.op, LcKind::None)
|
||||
}
|
||||
|
||||
/// Resuelve la traducción usando el idioma por defecto o, si no procede, el de respaldo de la
|
||||
/// aplicación.
|
||||
///
|
||||
|
|
|
|||
117
tests/component_form_date.rs
Normal file
117
tests/component_form_date.rs
Normal file
|
|
@ -0,0 +1,117 @@
|
|||
use pagetop::prelude::*;
|
||||
|
||||
fn cx(language: &str, timezone: &str) -> Context {
|
||||
Context::default()
|
||||
.with_langid(&Locale::resolve(language))
|
||||
.with_timezone(timezone.parse().unwrap())
|
||||
}
|
||||
|
||||
#[pagetop::test]
|
||||
async fn dates_are_shown_in_the_format_of_the_language() {
|
||||
let date = NaiveDate::from_ymd_opt(2026, 10, 6).unwrap();
|
||||
|
||||
let mut field = form::date::Field::date()
|
||||
.with_name("expires")
|
||||
.with_date(date);
|
||||
let html = field.render(&mut cx("es-ES", "UTC")).await.into_string();
|
||||
assert!(html.contains(r#"value="06/10/2026""#));
|
||||
assert!(html.contains(r#"placeholder="dd/mm/aaaa""#));
|
||||
assert!(html.contains("form-field form-field-date"));
|
||||
|
||||
let html = field.render(&mut cx("en-US", "UTC")).await.into_string();
|
||||
assert!(html.contains(r#"value="10/06/2026""#));
|
||||
assert!(html.contains(r#"placeholder="mm/dd/yyyy""#));
|
||||
}
|
||||
|
||||
#[pagetop::test]
|
||||
async fn datetimes_are_shown_in_the_local_time_of_the_user() {
|
||||
let dt = Utc.with_ymd_and_hms(2026, 10, 6, 12, 30, 0).unwrap();
|
||||
|
||||
let mut field = form::date::Field::datetime()
|
||||
.with_name("at")
|
||||
.with_datetime(dt);
|
||||
let html = field
|
||||
.render(&mut cx("es-ES", "Europe/Madrid"))
|
||||
.await
|
||||
.into_string();
|
||||
assert!(html.contains(r#"value="06/10/2026 14:30""#));
|
||||
assert!(html.contains(r#"placeholder="dd/mm/aaaa hh:mm""#));
|
||||
}
|
||||
|
||||
#[pagetop::test]
|
||||
async fn shown_values_are_read_back_unchanged() {
|
||||
let dt = Utc.with_ymd_and_hms(2026, 10, 6, 12, 30, 0).unwrap();
|
||||
let mut cx = cx("en-US", "America/New_York");
|
||||
|
||||
let mut field = form::date::Field::datetime()
|
||||
.with_name("at")
|
||||
.with_datetime(dt);
|
||||
let html = field.render(&mut cx).await.into_string();
|
||||
let value = html
|
||||
.split(r#"value=""#)
|
||||
.nth(1)
|
||||
.unwrap()
|
||||
.split('"')
|
||||
.next()
|
||||
.unwrap();
|
||||
assert_eq!(cx.parse_datetime(value), Ok(Some(dt)));
|
||||
}
|
||||
|
||||
#[pagetop::test]
|
||||
async fn text_is_shown_as_written_and_empty_fields_have_no_value() {
|
||||
let mut field = form::date::Field::time().with_name("at").with_text("25:99");
|
||||
let html = field.render(&mut cx("es-ES", "UTC")).await.into_string();
|
||||
assert!(html.contains(r#"value="25:99""#));
|
||||
assert!(html.contains("form-field form-field-time"));
|
||||
|
||||
let mut empty = form::date::Field::date().with_name("expires");
|
||||
let html = empty.render(&mut cx("es-ES", "UTC")).await.into_string();
|
||||
assert!(!html.contains("value="));
|
||||
}
|
||||
|
||||
#[pagetop::test]
|
||||
async fn a_value_of_another_kind_is_ignored() {
|
||||
let date = NaiveDate::from_ymd_opt(2026, 10, 6).unwrap();
|
||||
let mut field = form::date::Field::time().with_name("at").with_date(date);
|
||||
let html = field.render(&mut cx("es-ES", "UTC")).await.into_string();
|
||||
assert!(!html.contains("value="));
|
||||
}
|
||||
|
||||
// The format stays visible (and is announced by screen readers) once the placeholder is gone.
|
||||
#[pagetop::test]
|
||||
async fn the_format_is_also_a_help_text_linked_to_the_input() {
|
||||
let mut field = form::date::Field::date().with_name("expires");
|
||||
let html = field.render(&mut cx("es-ES", "UTC")).await.into_string();
|
||||
assert!(html.contains(r#"aria-describedby="edit-expires-input-format""#));
|
||||
assert!(html.contains(
|
||||
r#"<div id="edit-expires-input-format" class="form-text">Formato: dd/mm/aaaa</div>"#
|
||||
));
|
||||
}
|
||||
|
||||
#[pagetop::test]
|
||||
async fn autocomplete_is_off_unless_set() {
|
||||
let mut field = form::date::Field::date().with_name("born");
|
||||
let html = field.render(&mut cx("es-ES", "UTC")).await.into_string();
|
||||
assert!(html.contains(r#"autocomplete="off""#));
|
||||
|
||||
let mut field = form::date::Field::date()
|
||||
.with_name("born")
|
||||
.with_autocomplete(form::Autocomplete::token(form::AutofillField::Bday));
|
||||
let html = field.render(&mut cx("es-ES", "UTC")).await.into_string();
|
||||
assert!(html.contains(r#"autocomplete="bday""#));
|
||||
}
|
||||
|
||||
#[pagetop::test]
|
||||
async fn required_readonly_and_disabled_are_rendered() {
|
||||
let mut field = form::date::Field::date()
|
||||
.with_name("expires")
|
||||
.with_label(Lc::n("Expires"))
|
||||
.with_required(true)
|
||||
.with_readonly(true)
|
||||
.with_disabled(true);
|
||||
let html = field.render(&mut cx("es-ES", "UTC")).await.into_string();
|
||||
assert!(html.contains(r#"class="form-required""#));
|
||||
assert!(html.contains(" readonly"));
|
||||
assert!(html.contains(" required"));
|
||||
assert!(html.contains(" disabled"));
|
||||
}
|
||||
176
tests/component_form_help_text.rs
Normal file
176
tests/component_form_help_text.rs
Normal file
|
|
@ -0,0 +1,176 @@
|
|||
use pagetop::prelude::*;
|
||||
|
||||
// The help text of a field gets an id and the control points to it with `aria-describedby`, so
|
||||
// screen readers announce it when the control gets the focus.
|
||||
|
||||
async fn render(component: &mut impl Component) -> String {
|
||||
component
|
||||
.render(&mut Context::default())
|
||||
.await
|
||||
.into_string()
|
||||
}
|
||||
|
||||
fn help() -> Lc {
|
||||
Lc::n("Help")
|
||||
}
|
||||
|
||||
// **< Form fields >********************************************************************************
|
||||
|
||||
#[pagetop::test]
|
||||
async fn single_controls_point_to_their_help_text() {
|
||||
let cases: [(String, &str); 5] = [
|
||||
(
|
||||
render(
|
||||
&mut form::input::Field::text()
|
||||
.with_name("a")
|
||||
.with_help_text(help()),
|
||||
)
|
||||
.await,
|
||||
"edit-a-input-help",
|
||||
),
|
||||
(
|
||||
render(&mut form::Number::new().with_name("b").with_help_text(help())).await,
|
||||
"edit-b-input-help",
|
||||
),
|
||||
(
|
||||
render(&mut form::Range::new().with_name("c").with_help_text(help())).await,
|
||||
"edit-c-range-help",
|
||||
),
|
||||
(
|
||||
render(&mut form::Textarea::new().with_name("d").with_help_text(help())).await,
|
||||
"edit-d-textarea-help",
|
||||
),
|
||||
(
|
||||
render(
|
||||
&mut form::select::Field::new()
|
||||
.with_name("e")
|
||||
.with_help_text(help()),
|
||||
)
|
||||
.await,
|
||||
"edit-e-select-help",
|
||||
),
|
||||
];
|
||||
for (html, id) in cases {
|
||||
assert!(
|
||||
html.contains(&format!(r#"aria-describedby="{id}""#)),
|
||||
"{html}"
|
||||
);
|
||||
assert!(
|
||||
html.contains(&format!(r#"<div id="{id}" class="form-text">Help</div>"#)),
|
||||
"{html}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[pagetop::test]
|
||||
async fn without_help_text_there_is_no_aria_describedby() {
|
||||
let html = render(&mut form::input::Field::text().with_name("a")).await;
|
||||
assert!(!html.contains("aria-describedby"), "{html}");
|
||||
}
|
||||
|
||||
#[pagetop::test]
|
||||
async fn date_fields_point_to_their_format_and_their_help_text() {
|
||||
let html = render(
|
||||
&mut form::date::Field::date()
|
||||
.with_name("f")
|
||||
.with_help_text(help()),
|
||||
)
|
||||
.await;
|
||||
assert!(html.contains(r#"aria-describedby="edit-f-input-format edit-f-input-help""#));
|
||||
assert!(html.contains(r#"<div id="edit-f-input-help" class="form-text">Help</div>"#));
|
||||
}
|
||||
|
||||
#[pagetop::test]
|
||||
async fn checks_and_radios_are_labelled_groups_with_help_text() {
|
||||
let check = render(
|
||||
&mut form::check::Field::new()
|
||||
.with_name("g")
|
||||
.with_label(Lc::n("Options"))
|
||||
.with_help_text(help())
|
||||
.with_item(form::check::Item::new("1", Lc::n("One"))),
|
||||
)
|
||||
.await;
|
||||
let radio = render(
|
||||
&mut form::radio::Field::new()
|
||||
.with_name("h")
|
||||
.with_label(Lc::n("Choice"))
|
||||
.with_help_text(help())
|
||||
.with_item(form::radio::Item::new("1", Lc::n("One"))),
|
||||
)
|
||||
.await;
|
||||
for (html, id) in [(check, "edit-g"), (radio, "edit-h")] {
|
||||
assert!(html.contains(r#"role="group""#), "{html}");
|
||||
assert!(
|
||||
html.contains(&format!(r#"aria-labelledby="{id}-label""#)),
|
||||
"{html}"
|
||||
);
|
||||
assert!(
|
||||
html.contains(&format!(r#"aria-describedby="{id}-help""#)),
|
||||
"{html}"
|
||||
);
|
||||
assert!(
|
||||
html.contains(&format!(r#"<label id="{id}-label" class="form-label">"#)),
|
||||
"{html}"
|
||||
);
|
||||
assert!(
|
||||
html.contains(&format!(r#"<div id="{id}-help" class="form-text">"#)),
|
||||
"{html}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// **< form::parts::Help >**************************************************************************
|
||||
|
||||
#[pagetop::test]
|
||||
async fn help_links_only_when_there_is_text_and_an_anchor() {
|
||||
let cx = Context::default();
|
||||
let text = help();
|
||||
let none = Lc::none();
|
||||
|
||||
let field = form::parts::Help::new(&text, Some("edit-x-input"));
|
||||
assert_eq!(field.id(), Some("edit-x-input-help"));
|
||||
assert_eq!(
|
||||
field.render(&cx).into_string(),
|
||||
r#"<div id="edit-x-input-help" class="form-text">Help</div>"#
|
||||
);
|
||||
|
||||
// Without an anchor the text is still shown, but there is no id to point to.
|
||||
let field = form::parts::Help::new(&text, None);
|
||||
assert_eq!(field.id(), None);
|
||||
assert_eq!(
|
||||
field.render(&cx).into_string(),
|
||||
r#"<div class="form-text">Help</div>"#
|
||||
);
|
||||
|
||||
// Without text there is nothing to show nor to link.
|
||||
let field = form::parts::Help::new(&none, Some("edit-x-input"));
|
||||
assert_eq!(field.id(), None);
|
||||
assert_eq!(field.render(&cx).into_string(), "");
|
||||
|
||||
let format = form::parts::Help::suffixed(&text, Some("edit-x-input"), "-format");
|
||||
assert_eq!(format.id(), Some("edit-x-input-format"));
|
||||
}
|
||||
|
||||
#[pagetop::test]
|
||||
async fn help_class_can_be_replaced() {
|
||||
let cx = Context::default();
|
||||
let text = help();
|
||||
let field = form::parts::Help::new(&text, Some("edit-x-input")).with_class("hint small");
|
||||
assert_eq!(
|
||||
field.render(&cx).into_string(),
|
||||
r#"<div id="edit-x-input-help" class="hint small">Help</div>"#
|
||||
);
|
||||
}
|
||||
|
||||
#[pagetop::test]
|
||||
async fn help_without_translation_keeps_the_linked_element() {
|
||||
let cx = Context::default();
|
||||
// A missing translation still renders the element, so `aria-describedby` never dangles.
|
||||
let missing = Lc::l("no_such_key_for_help");
|
||||
let field = form::parts::Help::new(&missing, Some("edit-x-input"));
|
||||
assert_eq!(field.id(), Some("edit-x-input-help"));
|
||||
assert_eq!(
|
||||
field.render(&cx).into_string(),
|
||||
r#"<div id="edit-x-input-help" class="form-text"></div>"#
|
||||
);
|
||||
}
|
||||
92
tests/component_form_label.rs
Normal file
92
tests/component_form_label.rs
Normal file
|
|
@ -0,0 +1,92 @@
|
|||
use pagetop::prelude::*;
|
||||
|
||||
// `form::parts::Label` renders the label of a form field with the required mark, in the three
|
||||
// shapes used by the fields: linked to a control, next to a checkbox, or naming a group.
|
||||
|
||||
fn label() -> Lc {
|
||||
Lc::n("Name")
|
||||
}
|
||||
|
||||
#[pagetop::test]
|
||||
async fn a_control_label_points_to_the_control() {
|
||||
let cx = Context::default();
|
||||
let text = label();
|
||||
let field = form::parts::Label::new(&text, Some("edit-a-input"));
|
||||
assert_eq!(field.id(), None);
|
||||
assert_eq!(
|
||||
field.render(&cx).into_string(),
|
||||
r#"<label for="edit-a-input" class="form-label">Name</label>"#
|
||||
);
|
||||
}
|
||||
|
||||
#[pagetop::test]
|
||||
async fn required_fields_get_the_translated_mark() {
|
||||
let cx = Context::default().with_langid(&Locale::resolve("en-US"));
|
||||
let html = form::parts::Label::new(&label(), Some("edit-a-input"))
|
||||
.with_required(true)
|
||||
.render(&cx)
|
||||
.into_string();
|
||||
let title = Lc::l("field_required").lookup(&cx).unwrap();
|
||||
assert!(html.contains(&format!(
|
||||
r#"<span class="form-required" title="{title}">*</span>"#
|
||||
)));
|
||||
}
|
||||
|
||||
#[pagetop::test]
|
||||
async fn a_checkbox_label_uses_its_own_class() {
|
||||
let cx = Context::default();
|
||||
let html = form::parts::Label::check(&label(), Some("edit-b-checkbox"))
|
||||
.render(&cx)
|
||||
.into_string();
|
||||
assert_eq!(
|
||||
html,
|
||||
r#"<label for="edit-b-checkbox" class="form-check-label">Name</label>"#
|
||||
);
|
||||
}
|
||||
|
||||
#[pagetop::test]
|
||||
async fn a_group_label_has_an_id_and_no_for() {
|
||||
let cx = Context::default();
|
||||
let text = label();
|
||||
let field = form::parts::Label::group(&text, "edit-c");
|
||||
assert_eq!(field.id(), Some("edit-c-label"));
|
||||
assert_eq!(
|
||||
field.render(&cx).into_string(),
|
||||
r#"<label id="edit-c-label" class="form-label">Name</label>"#
|
||||
);
|
||||
}
|
||||
|
||||
#[pagetop::test]
|
||||
async fn without_text_there_is_no_label_nor_id() {
|
||||
let cx = Context::default();
|
||||
let none = Lc::none();
|
||||
let field = form::parts::Label::group(&none, "edit-c").with_required(true);
|
||||
assert_eq!(field.id(), None);
|
||||
assert_eq!(field.render(&cx).into_string(), "");
|
||||
}
|
||||
|
||||
#[pagetop::test]
|
||||
async fn the_class_can_be_replaced() {
|
||||
let cx = Context::default();
|
||||
let html = form::parts::Label::check(&label(), Some("edit-b-checkbox"))
|
||||
.with_class("control-label")
|
||||
.render(&cx)
|
||||
.into_string();
|
||||
assert_eq!(
|
||||
html,
|
||||
r#"<label for="edit-b-checkbox" class="control-label">Name</label>"#
|
||||
);
|
||||
}
|
||||
|
||||
#[pagetop::test]
|
||||
async fn a_group_label_without_translation_keeps_the_linked_element() {
|
||||
let cx = Context::default();
|
||||
// A missing translation still renders the element, so `aria-labelledby` never dangles.
|
||||
let missing = Lc::l("no_such_key_for_label");
|
||||
let field = form::parts::Label::group(&missing, "edit-c");
|
||||
assert_eq!(field.id(), Some("edit-c-label"));
|
||||
assert_eq!(
|
||||
field.render(&cx).into_string(),
|
||||
r#"<label id="edit-c-label" class="form-label"></label>"#
|
||||
);
|
||||
}
|
||||
151
tests/datetime_input.rs
Normal file
151
tests/datetime_input.rs
Normal file
|
|
@ -0,0 +1,151 @@
|
|||
use pagetop::prelude::*;
|
||||
|
||||
async fn setup() {
|
||||
Application::new().await;
|
||||
}
|
||||
|
||||
fn cx(language: &str, timezone: &str) -> Context {
|
||||
Context::default()
|
||||
.with_langid(&Locale::resolve(language))
|
||||
.with_timezone(timezone.parse().unwrap())
|
||||
}
|
||||
|
||||
fn date(y: i32, m: u32, d: u32) -> NaiveDate {
|
||||
NaiveDate::from_ymd_opt(y, m, d).unwrap()
|
||||
}
|
||||
|
||||
fn utc(y: i32, m: u32, d: u32, h: u32, min: u32) -> DateTime<Utc> {
|
||||
Utc.with_ymd_and_hms(y, m, d, h, min, 0).unwrap()
|
||||
}
|
||||
|
||||
// **< Contextual::parse_date() >*******************************************************************
|
||||
|
||||
#[pagetop::test]
|
||||
async fn dates_are_read_in_the_format_of_the_language() {
|
||||
setup().await;
|
||||
|
||||
let es = cx("es-ES", "UTC");
|
||||
assert_eq!(es.parse_date("06/10/2026"), Ok(Some(date(2026, 10, 6))));
|
||||
assert_eq!(es.parse_date(" 6/1/2026 "), Ok(Some(date(2026, 1, 6))));
|
||||
|
||||
let en = cx("en-US", "UTC");
|
||||
assert_eq!(en.parse_date("10/06/2026"), Ok(Some(date(2026, 10, 6))));
|
||||
}
|
||||
|
||||
// British English has no translations of its own except the day-first date formats; the rest falls
|
||||
// back to en-US. Reading 06/10/2026 month first would silently store 10 June instead of 6 October.
|
||||
#[pagetop::test]
|
||||
async fn british_english_reads_and_shows_the_day_first() {
|
||||
setup().await;
|
||||
|
||||
let gb = cx("en-GB", "UTC");
|
||||
assert_eq!(gb.parse_date("06/10/2026"), Ok(Some(date(2026, 10, 6))));
|
||||
assert_eq!(
|
||||
gb.parse_date("10/31/2026"),
|
||||
Err(DateInputError::InvalidDate {
|
||||
hint: "dd/mm/yyyy".to_string()
|
||||
})
|
||||
);
|
||||
assert_eq!(
|
||||
gb.format_date(date(2026, 10, 6), DateFormat::Medium),
|
||||
"06/10/2026"
|
||||
);
|
||||
assert_eq!(
|
||||
gb.format_date(date(2026, 10, 6), DateFormat::Long),
|
||||
"6 October 2026"
|
||||
);
|
||||
assert_eq!(
|
||||
Lc::l("relative_today").lookup(&gb).as_deref(),
|
||||
Some("today")
|
||||
);
|
||||
}
|
||||
|
||||
#[pagetop::test]
|
||||
async fn dates_also_accept_iso_and_blank_is_none() {
|
||||
setup().await;
|
||||
|
||||
let es = cx("es-ES", "UTC");
|
||||
assert_eq!(es.parse_date("2026-10-06"), Ok(Some(date(2026, 10, 6))));
|
||||
assert_eq!(es.parse_date(" "), Ok(None));
|
||||
}
|
||||
|
||||
#[pagetop::test]
|
||||
async fn invalid_dates_report_the_expected_format() {
|
||||
setup().await;
|
||||
|
||||
let es = cx("es-ES", "UTC");
|
||||
let expected = Err(DateInputError::InvalidDate {
|
||||
hint: "dd/mm/aaaa".to_string(),
|
||||
});
|
||||
// A two-digit year would otherwise be read as year 26.
|
||||
assert_eq!(es.parse_date("06/10/26"), expected);
|
||||
assert_eq!(es.parse_date("31/02/2026"), expected);
|
||||
assert_eq!(es.parse_date("10/31/2026"), expected);
|
||||
|
||||
let message = es.parse_date("x").unwrap_err().message();
|
||||
assert_eq!(
|
||||
message.lookup(&es).as_deref(),
|
||||
Some("Fecha no válida: usa el formato dd/mm/aaaa.")
|
||||
);
|
||||
}
|
||||
|
||||
// **< Contextual::parse_time() >*******************************************************************
|
||||
|
||||
#[pagetop::test]
|
||||
async fn times_are_read_with_one_or_two_digit_hours_and_minutes() {
|
||||
setup().await;
|
||||
|
||||
let es = cx("es-ES", "UTC");
|
||||
assert_eq!(es.parse_time("9:05"), Ok(NaiveTime::from_hms_opt(9, 5, 0)));
|
||||
assert_eq!(es.parse_time("9:5"), Ok(NaiveTime::from_hms_opt(9, 5, 0)));
|
||||
assert_eq!(
|
||||
es.parse_time("14:30"),
|
||||
Ok(NaiveTime::from_hms_opt(14, 30, 0))
|
||||
);
|
||||
assert!(matches!(
|
||||
es.parse_time("25:00"),
|
||||
Err(DateInputError::InvalidTime { .. })
|
||||
));
|
||||
}
|
||||
|
||||
// **< Contextual::parse_datetime() >***************************************************************
|
||||
|
||||
#[pagetop::test]
|
||||
async fn datetimes_are_read_in_the_local_time_of_the_user() {
|
||||
setup().await;
|
||||
|
||||
// Madrid is UTC+2 in October (summer time).
|
||||
let es = cx("es-ES", "Europe/Madrid");
|
||||
let expected = Ok(Some(utc(2026, 10, 6, 12, 30)));
|
||||
assert_eq!(es.parse_datetime("06/10/2026 14:30"), expected);
|
||||
assert_eq!(es.parse_datetime("2026-10-06T14:30"), expected);
|
||||
assert_eq!(es.parse_datetime("2026-10-06 14:30"), expected);
|
||||
|
||||
let en = cx("en-US", "Europe/Madrid");
|
||||
assert_eq!(en.parse_datetime("10/06/2026 14:30"), expected);
|
||||
}
|
||||
|
||||
#[pagetop::test]
|
||||
async fn nonexistent_local_times_are_rejected() {
|
||||
setup().await;
|
||||
|
||||
// On 2026-03-29 Madrid clocks jump from 02:00 to 03:00.
|
||||
let es = cx("es-ES", "Europe/Madrid");
|
||||
assert_eq!(
|
||||
es.parse_datetime("29/03/2026 02:30"),
|
||||
Err(DateInputError::NonexistentTime)
|
||||
);
|
||||
}
|
||||
|
||||
#[pagetop::test]
|
||||
async fn ambiguous_local_times_take_the_first_occurrence() {
|
||||
setup().await;
|
||||
|
||||
// On 2026-10-25 Madrid clocks go back from 03:00 to 02:00, so 02:30 happens twice: first at
|
||||
// UTC+2 (00:30 UTC), then at UTC+1 (01:30 UTC).
|
||||
let es = cx("es-ES", "Europe/Madrid");
|
||||
assert_eq!(
|
||||
es.parse_datetime("25/10/2026 02:30"),
|
||||
Ok(Some(utc(2026, 10, 25, 0, 30)))
|
||||
);
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue