Skip to main content

day_pieces/
datetime.rs

1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! `day_pieces::datetime`: core date and time pickers with native toolkit renderers and a composed DOM fallback
5//! (docs/datepicker.md; DESIGN.md §15).
6//!
7//! ```ignore
8//! let date = Signal::new(DayDate::new(2026, 7, 18).unwrap());
9//! let time = Signal::new(DayTime::new(9, 30, 0).unwrap());
10//! column((
11//!     date_picker(date),                      // Compact: field/button → platform chooser
12//!     date_picker(date).inline(),             // Inline: embedded calendar / wheels
13//!     time_picker(time),
14//!     row((date_picker(date), time_picker(time))),  // combined date+time = composition
15//! ))
16//! ```
17//!
18//! Two pieces, [`date_picker`] and [`time_picker`], rather than one combined date-time piece: a
19//! single combined control exists on only 3 of the 7 toolkits (`NSDatePicker`,
20//! `UIDatePicker.dateAndTime`, `QDateTimeEdit`), while separate date and time controls realize
21//! natively on all of them. Each piece maps a small style intent ([`Style::Compact`] /
22//! [`Style::Inline`]) to the platform's closest idiomatic control, never promising identical
23//! chrome (Android's Material chooser is a modal dialog, iOS's a popover, Qt's a calendar popup;
24//! that difference is the platform, docs/datepicker.md has the full table).
25//!
26//! The bound signal is two-way: a user pick sets it; the app setting it updates the native
27//! control. Values are civil (zoneless) [`DayDate`]/[`DayTime`]; time zones are the app's
28//! business. The piece's node also accepts `Event::TextChanged` carrying an ISO value
29//! (`"2026-07-18"` / `"09:30"`) as a synthetic set, so dayscript's existing `input:` step drives
30//! any picker on any backend.
31
32use crate::Decorated;
33use day_core::{BuildCx, Flex, Piece, RNode, with_tree};
34use day_reactive::{Binding, bind_seeded};
35use day_spec::Event;
36
37pub use day_spec::controls::datetime::*;
38
39/// How the pickers are realized on the compiled backend: `Native` (a platform picker
40/// control) or `Emulated` (GTK, where GTK4/libadwaita have no stock date/time picker, so the
41/// renderer composes native primitives: `GtkCalendar` in a popover, linked spin buttons; also mock).
42#[must_use]
43pub fn support() -> day_spec::Support {
44    let support = day_core::capability(day_spec::Cap::DateTimePicker);
45    if support == day_spec::Support::Unsupported {
46        day_spec::Support::Emulated
47    } else {
48        support
49    }
50}
51
52/// A native date picker bound two-way to a [`DayDate`] signal. Build with [`date_picker`].
53#[must_use]
54pub struct DatePicker<S: Binding<DayDate>> {
55    date: S,
56    style: Style,
57    min: Option<DayDate>,
58    max: Option<DayDate>,
59}
60
61/// `date_picker(date)`: a field summoning the platform's chooser; `.inline()` embeds it.
62/// `date` is a `Signal<DayDate>` or any other two-way binding (a day-model `Field`, mapped).
63pub fn date_picker<S: Binding<DayDate>>(date: S) -> DatePicker<S> {
64    // web-dom's registry is populated at runtime (no `linkme` on wasm), and a constructor always
65    // runs before the node it returns is realized, so this is where the arm registers itself.
66    DatePicker {
67        date,
68        style: Style::Automatic,
69        min: None,
70        max: None,
71    }
72}
73
74#[crate::builder(DatePickerBuilder)]
75#[crate::builder(TimePickerBuilder)]
76impl<S: Binding<DayDate>> DatePicker<S> {
77    pub fn compact(mut self) -> Self {
78        self.style = Style::Compact;
79        self
80    }
81    pub fn inline(mut self) -> Self {
82        self.style = Style::Inline;
83        self
84    }
85    pub fn style(mut self, style: Style) -> Self {
86        self.style = style;
87        self
88    }
89    /// Earliest selectable date (inclusive). Native where the control supports it; picks are
90    /// clamped in the piece regardless.
91    pub fn min(mut self, min: DayDate) -> Self {
92        self.min = Some(min);
93        self
94    }
95    /// Latest selectable date (inclusive).
96    pub fn max(mut self, max: DayDate) -> Self {
97        self.max = Some(max);
98        self
99    }
100}
101
102impl<S: Binding<DayDate>> Piece for DatePicker<S> {
103    fn build(self, cx: &mut BuildCx) -> RNode {
104        let DatePicker {
105            date,
106            style,
107            min,
108            max,
109        } = self;
110        // Seed with the signal's value clamped into range; reflect a build-time clamp back.
111        let initial = date.peek().clamped(min, max);
112        if initial != date.peek() {
113            date.write(initial);
114        }
115        let node = cx.leaf(
116            DATE_KIND,
117            &DateProps {
118                date: initial,
119                style,
120                min,
121                max,
122            },
123            Flex::default(),
124        );
125        // App writes → native (renderers no-op on an unchanged value, so a pick echoing through
126        // the signal never loops).
127        let dt = date.clone();
128        bind_seeded(
129            initial,
130            move || dt.read(),
131            move |d: &DayDate| {
132                with_tree(|t| t.patch(node, Box::new(DatePatch::SetDate(*d)), false));
133            },
134        );
135        // Native picks (`Custom`: ISO text in-process, epoch days across JNI/C-ABI) and
136        // dayscript's `input:` step (`TextChanged` with ISO text) → signal.
137        cx.on(node, move |ev| {
138            let picked = match ev {
139                Event::Custom { num, text, .. } => {
140                    if text.is_empty() {
141                        Some(DayDate::from_epoch_days(*num as i64))
142                    } else {
143                        DayDate::parse_iso(text)
144                    }
145                }
146                Event::TextChanged(s) => DayDate::parse_iso(s),
147                _ => None,
148            };
149            if let Some(d) = picked {
150                date.write(d.clamped(min, max));
151            }
152        });
153        node
154    }
155}
156
157/// A native time picker bound two-way to a [`DayTime`] signal. Build with [`time_picker`].
158#[must_use]
159pub struct TimePicker<S: Binding<DayTime>> {
160    time: S,
161    style: Style,
162    seconds: bool,
163}
164
165/// `time_picker(time)`: a field summoning the platform's chooser; `.inline()` embeds it.
166pub fn time_picker<S: Binding<DayTime>>(time: S) -> TimePicker<S> {
167    TimePicker {
168        time,
169        style: Style::Automatic,
170        seconds: false,
171    }
172}
173
174impl<S: Binding<DayTime>> TimePicker<S> {
175    pub fn compact(mut self) -> Self {
176        self.style = Style::Compact;
177        self
178    }
179    pub fn inline(mut self) -> Self {
180        self.style = Style::Inline;
181        self
182    }
183    pub fn style(mut self, style: Style) -> Self {
184        self.style = style;
185        self
186    }
187    /// Show/edit seconds; honored on AppKit and Qt, a documented no-op elsewhere
188    /// (docs/datepicker.md).
189    pub fn seconds(mut self) -> Self {
190        self.seconds = true;
191        self
192    }
193}
194
195impl<S: Binding<DayTime>> Piece for TimePicker<S> {
196    fn build(self, cx: &mut BuildCx) -> RNode {
197        let TimePicker {
198            time,
199            style,
200            seconds,
201        } = self;
202        let initial = time.peek();
203        let node = cx.leaf(
204            TIME_KIND,
205            &TimeProps {
206                time: initial,
207                style,
208                seconds,
209            },
210            Flex::default(),
211        );
212        let tm = time.clone();
213        bind_seeded(
214            initial,
215            move || tm.read(),
216            move |t: &DayTime| {
217                with_tree(|tr| tr.patch(node, Box::new(TimePatch::SetTime(*t)), false));
218            },
219        );
220        cx.on(node, move |ev| {
221            let picked = match ev {
222                Event::Custom { num, text, .. } => {
223                    if text.is_empty() {
224                        Some(DayTime::from_seconds_of_day(*num as i64))
225                    } else {
226                        DayTime::parse_iso(text)
227                    }
228                }
229                Event::TextChanged(s) => DayTime::parse_iso(s),
230                _ => None,
231            };
232            if let Some(t) = picked {
233                time.write(t);
234            }
235        });
236        node
237    }
238}
239
240// ---------------------------------------------------------------------------
241// Per-toolkit native renderers, one file per backend (the day-piece-picker convention). Every
242// module registers `Renderer`s link-time into its backend's `RENDERERS` slice; the `#[cfg]` gates
243// each to its feature + target.
244// ---------------------------------------------------------------------------
245
246// ---------------------------------------------------------------------------
247// Unit tests: the calendar math every backend leans on.
248// ---------------------------------------------------------------------------
249
250// --- Typed builders, forwarded through `Decorated` (docs/api-style.md) ---
251
252/// The date and time pickers' conformance cases (docs/testing.md). Every picker takes a
253/// synthetic ISO `input`, on every backend.
254#[cfg(feature = "conformance")]
255pub mod conformance {
256    use crate::*;
257    use day_core::conformance::{Case, Drive};
258    use day_reactive::Signal;
259
260    use super::{DATE_KIND, DayDate, DayTime, TIME_KIND, date_picker, time_picker};
261
262    /// A picked date reaches the bound date.
263    #[day_macros::test(day_core)]
264    fn date_picker_sets_date() -> Case {
265        Case::new()
266            .proves(DATE_KIND)
267            .page(|| {
268                let date = Signal::new(DayDate::new(2026, 1, 15).unwrap_or(DayDate::today()));
269                column((
270                    label(move || format!("date {}", date.get()))
271                        .id(day_core::id!(datetime::value)),
272                    date_picker(date)
273                        .compact()
274                        .id(day_core::id!(datetime::date)),
275                ))
276            })
277            .drive(|d: Drive| async move {
278                d.input("datetime::date", "2026-11-05").await?;
279                d.assert_text("datetime::value", "date 2026-11-05").await
280            })
281    }
282
283    /// A date past the picker's bounds lands on the bound.
284    #[day_macros::test(day_core)]
285    fn date_picker_clamps() -> Case {
286        Case::new()
287            .proves(DATE_KIND)
288            .page(|| {
289                let date = Signal::new(DayDate::new(2026, 6, 1).unwrap_or(DayDate::today()));
290                let (lo, hi) = (DayDate::new(2026, 1, 1), DayDate::new(2026, 12, 31));
291                let mut picker = date_picker(date).compact();
292                if let (Some(lo), Some(hi)) = (lo, hi) {
293                    picker = picker.min(lo).max(hi);
294                }
295                column((
296                    label(move || format!("date {}", date.get()))
297                        .id(day_core::id!(datetime::value)),
298                    picker.id(day_core::id!(datetime::date)),
299                ))
300            })
301            .drive(|d: Drive| async move {
302                d.input("datetime::date", "2027-06-15").await?;
303                d.assert_text("datetime::value", "date 2026-12-31").await
304            })
305    }
306
307    /// A picked time reaches the bound time.
308    #[day_macros::test(day_core)]
309    fn time_picker_sets_time() -> Case {
310        Case::new()
311            .proves(TIME_KIND)
312            .page(|| {
313                let time = Signal::new(DayTime::new(9, 0, 0).unwrap_or(DayTime::now()));
314                column((
315                    label(move || format!("time {}", time.get()))
316                        .id(day_core::id!(datetime::value)),
317                    time_picker(time)
318                        .compact()
319                        .id(day_core::id!(datetime::time)),
320                ))
321            })
322            .drive(|d: Drive| async move {
323                d.input("datetime::time", "14:45").await?;
324                d.assert_text("datetime::value", "time 14:45").await
325            })
326    }
327}
328
329#[cfg(test)]
330mod tests {
331    use super::*;
332
333    #[test]
334    fn date_validation() {
335        assert!(DayDate::new(2026, 7, 18).is_some());
336        assert!(DayDate::new(2024, 2, 29).is_some(), "leap day");
337        assert!(DayDate::new(2023, 2, 29).is_none(), "not a leap year");
338        assert!(DayDate::new(2000, 2, 29).is_some(), "400-rule leap");
339        assert!(DayDate::new(1900, 2, 29).is_none(), "100-rule non-leap");
340        assert!(DayDate::new(2026, 4, 31).is_none());
341        assert!(DayDate::new(2026, 0, 1).is_none());
342        assert!(DayDate::new(2026, 13, 1).is_none());
343        assert!(DayDate::new(2026, 1, 0).is_none());
344    }
345
346    #[test]
347    fn epoch_days_anchors() {
348        let d = |y, m, dd| DayDate::new(y, m, dd).unwrap();
349        assert_eq!(d(1970, 1, 1).to_epoch_days(), 0);
350        assert_eq!(d(1970, 1, 2).to_epoch_days(), 1);
351        assert_eq!(d(1969, 12, 31).to_epoch_days(), -1);
352        assert_eq!(d(2000, 1, 1).to_epoch_days(), 10957);
353        assert_eq!(d(2026, 7, 18).to_epoch_days(), 20652);
354    }
355
356    #[test]
357    fn epoch_days_round_trip() {
358        // A wide swath incl. leap boundaries and negative epochs.
359        for days in (-200_000..200_000).step_by(97) {
360            let d = DayDate::from_epoch_days(days);
361            assert_eq!(d.to_epoch_days(), days, "{d}");
362            assert!(
363                DayDate::new(d.year, d.month, d.day).is_some(),
364                "{d} is valid"
365            );
366        }
367    }
368
369    #[test]
370    fn date_iso_round_trip() {
371        for s in ["1970-01-01", "2026-07-18", "2024-02-29", "0001-12-31"] {
372            let d = DayDate::parse_iso(s).unwrap();
373            assert_eq!(d.to_string(), s);
374        }
375        for bad in [
376            "2026-7-18",
377            "18-07-2026",
378            "2026-02-30",
379            "2026-07-18T00:00",
380            "hello",
381            "",
382        ] {
383            assert!(DayDate::parse_iso(bad).is_none(), "{bad:?} rejected");
384        }
385    }
386
387    #[test]
388    fn date_clamp() {
389        let d = |y, m, dd| DayDate::new(y, m, dd).unwrap();
390        let (min, max) = (Some(d(2026, 1, 1)), Some(d(2026, 12, 31)));
391        assert_eq!(d(2025, 6, 1).clamped(min, max), d(2026, 1, 1));
392        assert_eq!(d(2027, 6, 1).clamped(min, max), d(2026, 12, 31));
393        assert_eq!(d(2026, 6, 1).clamped(min, max), d(2026, 6, 1));
394        assert_eq!(d(2027, 6, 1).clamped(None, None), d(2027, 6, 1));
395    }
396
397    #[test]
398    fn time_validation_and_seconds() {
399        assert!(DayTime::new(23, 59, 59).is_some());
400        assert!(DayTime::new(24, 0, 0).is_none());
401        assert!(DayTime::new(0, 60, 0).is_none());
402        assert!(DayTime::new(0, 0, 60).is_none());
403        let t = DayTime::new(9, 30, 15).unwrap();
404        assert_eq!(t.seconds_of_day(), 34_215);
405        assert_eq!(DayTime::from_seconds_of_day(34_215), t);
406        assert_eq!(
407            DayTime::from_seconds_of_day(-1),
408            DayTime::new(23, 59, 59).unwrap(),
409            "wraps into the day"
410        );
411    }
412
413    #[test]
414    fn time_iso_round_trip() {
415        assert_eq!(
416            DayTime::parse_iso("09:30").unwrap(),
417            DayTime::new(9, 30, 0).unwrap()
418        );
419        assert_eq!(
420            DayTime::parse_iso("23:59:59").unwrap(),
421            DayTime::new(23, 59, 59).unwrap()
422        );
423        // Display shows seconds exactly when nonzero.
424        assert_eq!(DayTime::new(9, 30, 0).unwrap().to_string(), "09:30");
425        assert_eq!(DayTime::new(9, 30, 7).unwrap().to_string(), "09:30:07");
426        for bad in ["24:00", "9:30", "09:3", "09:30:5", "09-30", ""] {
427            assert!(DayTime::parse_iso(bad).is_none(), "{bad:?} rejected");
428        }
429    }
430
431    #[test]
432    fn today_is_valid() {
433        let t = DayDate::today();
434        assert!(DayDate::new(t.year, t.month, t.day).is_some());
435        assert!(t.year >= 2026);
436    }
437}