✨ (form): Añade campos de fecha y hora por idioma

Nuevo `form:📅:Field` (fecha, hora y fecha y hora) que muestra el
valor en el formato del idioma efectivo (dd/mm/aaaa, mm/dd/yyyy...) y no
con el selector nativo, que sigue el formato del navegador. Contextual
añade `parse_date()`, `parse_time()` y `parse_datetime()` para leer lo
escrito.
This commit is contained in:
Manuel Cillero 2026-10-09 00:47:26 +02:00
parent 144127776d
commit fc71a077ee
11 changed files with 940 additions and 2 deletions

View file

@ -16,6 +16,12 @@ pub mod select;
#[doc(inline)]
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::InputBsExt;
@ -25,6 +31,8 @@ pub use textarea::Textarea;
#[doc(inline)]
pub use textarea::TextareaBsExt;
pub use pagetop::base::component::form::date;
pub use pagetop::base::component::form::Number;
pub use pagetop::base::component::form::Range;

View file

@ -29,6 +29,8 @@ pub use select_timezone::SelectTimezone;
pub mod input;
pub mod date;
mod number;
pub use number::Number;

View file

@ -0,0 +1,329 @@
//! 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 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()),
(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());
// 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)) {
@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)]
{
"*"
}
}
}
}
input
type="text"
id=[input_id.as_deref()]
class="form-control"
name=[self.name().as_deref()]
value=[value]
placeholder=(hint)
aria-describedby=[format_id.as_deref()]
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) }
}
}
})
}
}
#[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
}
}

View file

@ -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

View file

@ -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
View 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()
}

View 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 }

View file

@ -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 ->

View file

@ -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 ->

View 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"));
}

151
tests/datetime_input.rs Normal file
View 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)))
);
}