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