♿️ (form): Enlaza ayuda de los campos a su control

This commit is contained in:
Manuel Cillero 2026-10-09 00:59:43 +02:00
parent fc71a077ee
commit 8690f994c3
15 changed files with 341 additions and 44 deletions

View file

@ -142,11 +142,20 @@ 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 = 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);
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.as_deref()]
aria-describedby=[help.id()]
{
@if let Some(label) = label {
label id=[label_id.as_deref()] class="form-label" { (label) }
}
@let item_classes = if *self.inline() {
"form-check form-check-inline"
@ -170,9 +179,7 @@ impl Component for Field {
}
}
}
@if let Some(description) = self.help_text().lookup(cx) {
div class="form-text" { (description) }
}
(help)
}
})
}

View file

@ -148,7 +148,6 @@ 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 format_id = input_id.as_deref().map(|id| util::join!(id, "-format"));
let tz = cx.timezone();
let value = match (self.kind(), &self.value) {
(_, Value::Text(text)) => Some(text.clone()),
@ -163,6 +162,14 @@ 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);
// 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);
@ -188,18 +195,14 @@ impl Component for Field {
name=[self.name().as_deref()]
value=[value]
placeholder=(hint)
aria-describedby=[format_id.as_deref()]
aria-describedby=[util::non_blank(&described_by)]
autocomplete=(autocomplete)
autofocus[*self.autofocus()]
readonly[*self.readonly()]
required[*self.required()]
disabled[*self.disabled()];
@if let Some(format) = format.lookup(cx) {
div id=[format_id.as_deref()] class="form-text" { (format) }
}
@if let Some(description) = self.help_text().lookup(cx) {
div class="form-text" { (description) }
}
(format)
(help)
}
})
}

View file

@ -0,0 +1,70 @@
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) }
}
}
}
}

View file

@ -220,6 +220,7 @@ 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 input_class = if *self.plaintext() {
"form-control-plaintext"
} else {
@ -251,6 +252,7 @@ impl Component for Field {
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 +269,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)
}
})
}

View file

@ -85,6 +85,7 @@ 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);
Ok(html! {
div (self.props().unpack(cx)) {
@if let Some(label) = self.label().lookup(cx) {
@ -103,6 +104,7 @@ impl Component for Number {
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 +115,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)
}
})
}

View file

@ -142,11 +142,20 @@ 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 = 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);
Ok(html! {
div (self.props().unpack(cx)) {
@if let Some(label) = self.label().lookup(cx) {
label class="form-label" {
div
(self.props().unpack(cx))
role="group"
aria-labelledby=[label_id.as_deref()]
aria-describedby=[help.id()]
{
@if let Some(label) = label {
label id=[label_id.as_deref()] class="form-label" {
(label)
@if *self.required() {
span
@ -187,9 +196,7 @@ impl Component for Field {
}
}
}
@if let Some(description) = self.help_text().lookup(cx) {
div class="form-text" { (description) }
}
(help)
}
})
}

View file

@ -82,6 +82,7 @@ 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);
Ok(html! {
div (self.props().unpack(cx)) {
@if let Some(label) = self.label().lookup(cx) {
@ -90,6 +91,7 @@ impl Component for Range {
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 +100,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)
}
})
}

View file

@ -240,6 +240,7 @@ 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);
Ok(html! {
div (self.props().unpack(cx)) {
@ -258,6 +259,7 @@ impl Component for Field {
}
select
id=[select_id.as_deref()]
aria-describedby=[help.id()]
class="form-select"
name=[self.name().as_deref()]
multiple[*self.multiple()]
@ -297,9 +299,7 @@ impl Component for Field {
}
}
}
@if let Some(description) = self.help_text().lookup(cx) {
div class="form-text" { (description) }
}
(help)
}
})
}

View file

@ -93,6 +93,7 @@ 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);
Ok(html! {
div (self.props().unpack(cx)) {
@ -111,6 +112,7 @@ impl Component for Textarea {
}
textarea
id=[textarea_id.as_deref()]
aria-describedby=[help.id()]
class="form-control"
name=[self.name().as_deref()]
rows=[self.rows()]
@ -127,9 +129,7 @@ impl Component for Textarea {
(value)
}
}
@if let Some(description) = self.help_text().lookup(cx) {
div class="form-text" { (description) }
}
(help)
}
})
}