Skip to main content

hypersig_ui/
date.rs

1//! Date fields with a label, a description, and an error message.
2
3use hypersig::html::{Bindable, El, attr, input};
4use hypersig::style::value::rem;
5use hypersig::{CalendarDate, Form, IntoExpr, Sig, Validate};
6
7use crate::field::{Frame, field_style};
8
9/// A date type a [`DateField`] can be bound to: `CalendarDate` or `Option<CalendarDate>`.
10///
11/// An `Option` field starts empty for `None`, and emptying it sets `None`.
12/// A plain `CalendarDate` keeps its date when the visitor empties the field.
13#[diagnostic::on_unimplemented(
14    message = "a date field cannot be bound to a `{Self}` signal",
15    note = "bind a `CalendarDate` or `Option<CalendarDate>` signal; text goes in a `TextField`"
16)]
17pub trait Dated: Bindable + sealed::Sealed {}
18
19impl Dated for CalendarDate {}
20impl Dated for Option<CalendarDate> {}
21
22mod sealed {
23    use hypersig::CalendarDate;
24
25    pub trait Sealed {}
26    impl Sealed for CalendarDate {}
27    impl Sealed for Option<CalendarDate> {}
28}
29
30/// A date field bound to a `CalendarDate` or `Option<CalendarDate>` signal, with its label.
31///
32/// Where given, a description and an error message are tied to it.
33///
34/// It is an `<input type="date">` with the ids, `aria-describedby`, and
35/// `aria-invalid` of a [`TextField`](crate::TextField). The browser draws
36/// its own date picker. `min` and
37/// `max` take a `CalendarDate`, so a bound cannot be text.
38///
39/// ```
40/// use hypersig::{CalendarDate, Signals};
41/// use hypersig_ui::DateField;
42/// use serde::{Deserialize, Serialize};
43///
44/// #[derive(Signals, Serialize, Deserialize)]
45/// struct Booking {
46///     arrival: Option<CalendarDate>,
47/// }
48///
49/// let arrival = DateField::new("Arrival", Booking::arrival())
50///     .min(CalendarDate::new(2026, 1, 1))
51///     .max(CalendarDate::new(2026, 12, 31));
52/// let html = arrival.render().render();
53/// assert!(html.contains(r#"type="date""#));
54/// assert!(html.contains(r#"min="2026-01-01""#));
55/// assert!(html.contains(r#"for="ui-arrival-input""#));
56/// ```
57#[derive(Debug)]
58pub struct DateField<S, T> {
59    value: Sig<S, T>,
60    min: Option<CalendarDate>,
61    max: Option<CalendarDate>,
62    frame: Frame<S>,
63}
64
65impl<S, T: Dated> DateField<S, T> {
66    /// A date field labeled `label`, bound to `value`.
67    #[must_use]
68    pub fn new(label: impl Into<String>, value: Sig<S, T>) -> Self {
69        Self {
70            value,
71            min: None,
72            max: None,
73            frame: Frame::new(label.into()),
74        }
75    }
76
77    /// A date field labeled `label`, bound to `field` of `form`.
78    ///
79    /// It shows [`error`](Sig::error) of the form for `field` and marks the
80    /// field touched when the visitor leaves it, as
81    /// [`TextField::in_form`](crate::TextField::in_form) does.
82    #[must_use]
83    pub fn in_form<V: Validate>(
84        label: impl Into<String>,
85        form: Sig<S, Form<V>>,
86        field: Sig<V, T>,
87    ) -> Self {
88        let mut out = Self::new(label, form.field(field));
89        out.frame = out.frame.in_form(form, field);
90        out
91    }
92
93    /// Sets the earliest date the browser accepts.
94    ///
95    /// # Panics
96    ///
97    /// Panics if `min` is after a maximum set before.
98    #[must_use]
99    pub fn min(mut self, min: CalendarDate) -> Self {
100        if let Some(max) = self.max {
101            assert!(
102                min <= max,
103                "a date field's earliest date is not after its latest, but {min} is after {max}"
104            );
105        }
106        self.min = Some(min);
107        self
108    }
109
110    /// Sets the latest date the browser accepts.
111    ///
112    /// # Panics
113    ///
114    /// Panics if `max` is before a minimum set before.
115    #[must_use]
116    pub fn max(mut self, max: CalendarDate) -> Self {
117        if let Some(min) = self.min {
118            assert!(
119                min <= max,
120                "a date field's latest date is not before its earliest, but {max} is before {min}"
121            );
122        }
123        self.max = Some(max);
124        self
125    }
126
127    /// Adds a line under the field that `aria-describedby` points at.
128    #[must_use]
129    pub fn description(mut self, text: impl Into<String>) -> Self {
130        self.frame.description = Some(text.into());
131        self
132    }
133
134    /// Shows `message` under the field.
135    ///
136    /// It marks the field invalid while `message` is not empty.
137    #[must_use]
138    pub fn error(mut self, message: impl IntoExpr<S, String>) -> Self {
139        self.frame.error = Some(message.into_expr());
140        self
141    }
142
143    /// Marks the field `required`.
144    ///
145    /// The label shows it with an asterisk that a screen reader skips.
146    #[must_use]
147    pub fn required(mut self) -> Self {
148        self.frame.required = true;
149        self
150    }
151
152    /// Disables the field while `when` is true.
153    #[must_use]
154    pub fn disabled(mut self, when: impl IntoExpr<S, bool>) -> Self {
155        self.frame.disabled = Some(when.into_expr());
156        self
157    }
158
159    /// The label, the field, the description, and the error, in a `<div>`.
160    #[must_use]
161    pub fn render(self) -> El<S> {
162        let mut control = input()
163            .attr(attr::TYPE, "date")
164            .css(field_style().height(rem(2.25)))
165            .bind(self.value);
166        if let Some(min) = self.min {
167            control = control.attr(attr::MIN, min.to_string());
168        }
169        if let Some(max) = self.max {
170            control = control.attr(attr::MAX, max.to_string());
171        }
172        self.frame.render(&crate::id::base(self.value), control)
173    }
174}
175
176impl<S, T: Dated> From<DateField<S, T>> for El<S> {
177    fn from(field: DateField<S, T>) -> Self {
178        field.render()
179    }
180}
181
182impl<S, T: Dated> From<DateField<S, T>> for hypersig::html::Node<S> {
183    fn from(field: DateField<S, T>) -> Self {
184        field.render().into()
185    }
186}