♻️ (form): Reúne etiqueta y ayuda en form::parts
Label y Help generan el marcado común de los campos de formulario. La etiqueta con la marca opcional de obligatorio y el texto de ayuda, con sus enlaces de accesibilidad.
This commit is contained in:
parent
8690f994c3
commit
d80a6787c7
20 changed files with 534 additions and 262 deletions
|
|
@ -55,7 +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::FieldHelp::new(field.help_text(), input_id.as_deref(), cx);
|
||||
let help = form::parts::Help::new(field.help_text(), input_id.as_deref());
|
||||
let input_class = if *field.plaintext() {
|
||||
"form-control-plaintext"
|
||||
} else {
|
||||
|
|
@ -77,26 +77,12 @@ 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()]
|
||||
|
|
@ -117,8 +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) }
|
||||
(help)
|
||||
@if floating { (label.render(cx)) }
|
||||
(help.render(cx))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
|
|
|||
|
|
@ -62,27 +62,13 @@ 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::FieldHelp::new(field.help_text(), select_id.as_deref(), cx);
|
||||
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()]
|
||||
|
|
@ -125,8 +111,8 @@ pub(crate) fn render(field: &Field, cx: &mut Context) -> Result<Markup, Componen
|
|||
}
|
||||
}
|
||||
}
|
||||
@if floating { (label) }
|
||||
(help)
|
||||
@if floating { (label.render(cx)) }
|
||||
(help.render(cx))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
|
|
|||
|
|
@ -61,7 +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::FieldHelp::new(field.help_text(), textarea_id.as_deref(), cx);
|
||||
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=""`.
|
||||
|
|
@ -70,25 +70,11 @@ 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()]
|
||||
|
|
@ -106,8 +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) }
|
||||
(help)
|
||||
@if floating { (label.render(cx)) }
|
||||
(help.render(cx))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
|
|
|||
|
|
@ -6,8 +6,7 @@ pub use props::{Autocomplete, AutofillField, CheckboxKind, Method};
|
|||
mod component;
|
||||
pub use component::Form;
|
||||
|
||||
mod field_help;
|
||||
pub use field_help::FieldHelp;
|
||||
pub mod parts;
|
||||
|
||||
mod fieldset;
|
||||
pub use fieldset::Fieldset;
|
||||
|
|
|
|||
|
|
@ -143,20 +143,17 @@ impl Component for Field {
|
|||
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 = self.label().lookup(cx);
|
||||
let label_id = label.as_ref().map(|_| util::join!(&container_id, "-label"));
|
||||
let help = form::FieldHelp::new(self.help_text(), Some(&container_id), cx);
|
||||
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))
|
||||
role="group"
|
||||
aria-labelledby=[label_id.as_deref()]
|
||||
aria-labelledby=[label.id()]
|
||||
aria-describedby=[help.id()]
|
||||
{
|
||||
@if let Some(label) = label {
|
||||
label id=[label_id.as_deref()] class="form-label" { (label) }
|
||||
}
|
||||
(label.render(cx))
|
||||
@let item_classes = if *self.inline() {
|
||||
"form-check form-check-inline"
|
||||
} else {
|
||||
|
|
@ -179,7 +176,7 @@ impl Component for Field {
|
|||
}
|
||||
}
|
||||
}
|
||||
(help)
|
||||
(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))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
|
|
|||
|
|
@ -162,8 +162,10 @@ impl Component for Field {
|
|||
Kind::DateTime => input::datetime_hint(cx),
|
||||
};
|
||||
let format = Lc::l("input_format_help").with_arg("format", hint.clone());
|
||||
let format = form::FieldHelp::suffixed(&format, input_id.as_deref(), "-format", cx);
|
||||
let help = form::FieldHelp::new(self.help_text(), input_id.as_deref(), cx);
|
||||
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(),
|
||||
|
|
@ -175,19 +177,7 @@ impl Component for Field {
|
|||
let autocomplete = self.autocomplete().unwrap_or(&form::Autocomplete::Off);
|
||||
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="text"
|
||||
id=[input_id.as_deref()]
|
||||
|
|
@ -201,8 +191,8 @@ impl Component for Field {
|
|||
readonly[*self.readonly()]
|
||||
required[*self.required()]
|
||||
disabled[*self.disabled()];
|
||||
(format)
|
||||
(help)
|
||||
(format.render(cx))
|
||||
(help.render(cx))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,70 +0,0 @@
|
|||
use crate::prelude::*;
|
||||
|
||||
/// Texto de ayuda de un campo de formulario, ya traducido, con el identificador que lo enlaza a su
|
||||
/// control.
|
||||
///
|
||||
/// Lo usan los campos de formulario (y los temas que pintan su propio marcado) para mostrar el
|
||||
/// texto de ayuda bajo el control y enlazarlo con `aria-describedby`, de modo que los lectores de
|
||||
/// pantalla lo anuncien al entrar en el campo. Se inserta en [`html!`] como cualquier otro valor:
|
||||
/// genera `<div id="..." class="form-text">...</div>`, o nada si no hay texto.
|
||||
///
|
||||
/// # Ejemplo
|
||||
///
|
||||
/// ```rust,no_run
|
||||
/// # use pagetop::prelude::*;
|
||||
/// # fn render(help_text: &Lc, input_id: Option<&str>, cx: &Context) -> Markup {
|
||||
/// let help = form::FieldHelp::new(help_text, input_id, cx);
|
||||
/// html! {
|
||||
/// input type="text" id=[input_id] aria-describedby=[help.id()];
|
||||
/// (help)
|
||||
/// }
|
||||
/// # }
|
||||
/// ```
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct FieldHelp {
|
||||
text: Option<String>,
|
||||
id: Option<String>,
|
||||
}
|
||||
|
||||
impl FieldHelp {
|
||||
/// Traduce `help_text` y, si hay texto, le asigna 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: &Lc, anchor_id: Option<&str>, language: &impl LangId) -> Self {
|
||||
Self::suffixed(help_text, anchor_id, "-help", language)
|
||||
}
|
||||
|
||||
/// Igual que [`new()`](Self::new), pero con otro sufijo para el identificador; útil cuando un
|
||||
/// mismo control tiene más de un texto que lo describe.
|
||||
pub fn suffixed(
|
||||
help_text: &Lc,
|
||||
anchor_id: Option<&str>,
|
||||
suffix: &str,
|
||||
language: &impl LangId,
|
||||
) -> Self {
|
||||
let text = help_text.lookup(language);
|
||||
// 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 = text
|
||||
.as_ref()
|
||||
.and(anchor_id)
|
||||
.map(|anchor_id| util::join!(anchor_id, suffix));
|
||||
Self { text, id }
|
||||
}
|
||||
|
||||
/// Devuelve el identificador para `aria-describedby`, o `None` si no hay texto o si el control
|
||||
/// no tiene identificador.
|
||||
pub fn id(&self) -> Option<&str> {
|
||||
self.id.as_deref()
|
||||
}
|
||||
}
|
||||
|
||||
impl Render for FieldHelp {
|
||||
fn render(&self) -> Markup {
|
||||
html! {
|
||||
@if let Some(text) = &self.text {
|
||||
div id=[self.id()] class="form-text" { (text) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -220,7 +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::FieldHelp::new(self.help_text(), input_id.as_deref(), cx);
|
||||
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 {
|
||||
|
|
@ -236,19 +238,7 @@ 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()]
|
||||
|
|
@ -269,7 +259,7 @@ impl Component for Field {
|
|||
onfocus=[strict.then_some("this.removeAttribute('readonly')")]
|
||||
required[*self.required()]
|
||||
disabled[*self.disabled()];
|
||||
(help)
|
||||
(help.render(cx))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
|
|
|||
|
|
@ -85,22 +85,12 @@ 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::FieldHelp::new(self.help_text(), input_id.as_deref(), cx);
|
||||
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()]
|
||||
|
|
@ -115,7 +105,7 @@ impl Component for Number {
|
|||
readonly[*self.readonly()]
|
||||
required[*self.required()]
|
||||
disabled[*self.disabled()];
|
||||
(help)
|
||||
(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
|
||||
}
|
||||
}
|
||||
|
|
@ -143,30 +143,18 @@ impl Component for Field {
|
|||
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 = self.label().lookup(cx);
|
||||
let label_id = label.as_ref().map(|_| util::join!(&container_id, "-label"));
|
||||
let help = form::FieldHelp::new(self.help_text(), Some(&container_id), cx);
|
||||
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))
|
||||
role="group"
|
||||
aria-labelledby=[label_id.as_deref()]
|
||||
aria-labelledby=[label.id()]
|
||||
aria-describedby=[help.id()]
|
||||
{
|
||||
@if let Some(label) = label {
|
||||
label id=[label_id.as_deref()] class="form-label" {
|
||||
(label)
|
||||
@if *self.required() {
|
||||
span
|
||||
class="form-required"
|
||||
title=[Lc::l("field_required").lookup(cx)]
|
||||
{
|
||||
"*"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
(label.render(cx))
|
||||
@let item_classes = if *self.inline() {
|
||||
"form-check form-check-inline"
|
||||
} else {
|
||||
|
|
@ -196,7 +184,7 @@ impl Component for Field {
|
|||
}
|
||||
}
|
||||
}
|
||||
(help)
|
||||
(help.render(cx))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
|
|
|||
|
|
@ -82,12 +82,11 @@ 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::FieldHelp::new(self.help_text(), range_id.as_deref(), cx);
|
||||
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()]
|
||||
|
|
@ -100,7 +99,7 @@ impl Component for Range {
|
|||
value=[self.value()]
|
||||
autofocus[*self.autofocus()]
|
||||
disabled[*self.disabled()];
|
||||
(help)
|
||||
(help.render(cx))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
|
|
|||
|
|
@ -240,23 +240,13 @@ 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::FieldHelp::new(self.help_text(), select_id.as_deref(), cx);
|
||||
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()]
|
||||
|
|
@ -299,7 +289,7 @@ impl Component for Field {
|
|||
}
|
||||
}
|
||||
}
|
||||
(help)
|
||||
(help.render(cx))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
|
|
|||
|
|
@ -93,23 +93,13 @@ impl Component for Textarea {
|
|||
let textarea_id = container_id
|
||||
.as_deref()
|
||||
.map(|id| util::join!(id, "-textarea"));
|
||||
let help = form::FieldHelp::new(self.help_text(), textarea_id.as_deref(), cx);
|
||||
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()]
|
||||
|
|
@ -129,7 +119,7 @@ impl Component for Textarea {
|
|||
(value)
|
||||
}
|
||||
}
|
||||
(help)
|
||||
(help.render(cx))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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.
|
||||
///
|
||||
|
|
|
|||
|
|
@ -119,32 +119,58 @@ async fn checks_and_radios_are_labelled_groups_with_help_text() {
|
|||
}
|
||||
}
|
||||
|
||||
// **< form::FieldHelp >****************************************************************************
|
||||
// **< form::parts::Help >**************************************************************************
|
||||
|
||||
#[pagetop::test]
|
||||
async fn field_help_links_only_when_there_is_text_and_an_anchor() {
|
||||
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::FieldHelp::new(&help(), Some("edit-x-input"), &cx);
|
||||
let field = form::parts::Help::new(&text, Some("edit-x-input"));
|
||||
assert_eq!(field.id(), Some("edit-x-input-help"));
|
||||
assert_eq!(
|
||||
field.render().into_string(),
|
||||
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::FieldHelp::new(&help(), None, &cx);
|
||||
let field = form::parts::Help::new(&text, None);
|
||||
assert_eq!(field.id(), None);
|
||||
assert_eq!(
|
||||
field.render().into_string(),
|
||||
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::FieldHelp::new(&Lc::none(), Some("edit-x-input"), &cx);
|
||||
let field = form::parts::Help::new(&none, Some("edit-x-input"));
|
||||
assert_eq!(field.id(), None);
|
||||
assert_eq!(field.render().into_string(), "");
|
||||
assert_eq!(field.render(&cx).into_string(), "");
|
||||
|
||||
let format = form::FieldHelp::suffixed(&help(), Some("edit-x-input"), "-format", &cx);
|
||||
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>"#
|
||||
);
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue