day_spec/controls/datetime.rs
1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4pub const DATE_KIND: &str = "day.piece.datepicker";
5pub const TIME_KIND: &str = "day.piece.timepicker";
6
7// ---------------------------------------------------------------------------
8// Values: proleptic-Gregorian civil date + wall-clock time. No chrono dependency: ISO-8601
9// strings and epoch days / seconds-of-day are the interchange forms across native boundaries.
10// ---------------------------------------------------------------------------
11
12/// A civil (zoneless) calendar date, proleptic Gregorian. Ordered chronologically; `Display` and
13/// [`DayDate::parse_iso`] speak ISO-8601 (`YYYY-MM-DD`).
14#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
15pub struct DayDate {
16 pub year: i32,
17 pub month: u8,
18 pub day: u8,
19}
20
21impl Default for DayDate {
22 fn default() -> Self {
23 DayDate {
24 year: 1970,
25 month: 1,
26 day: 1,
27 }
28 }
29}
30
31/// Milliseconds since the Unix epoch, from the wall clock of whatever target this is. Use it (or
32/// [`now_epoch_secs`]) for timestamps in app code: it is the one wall clock that works on every
33/// Day target.
34///
35/// `SystemTime::now()` traps on `wasm32-unknown-unknown`: the target has no clock, and the trap
36/// is not a panic that can be caught, it aborts the module. So a clock read anywhere on the
37/// startup path takes the whole web app down with `RuntimeError: Unreachable code`. The web
38/// build reads the browser's `Date.now()` through the same JS shim day-toolkit-dom imports
39/// everything else from; every other target reads `SystemTime`.
40///
41/// This is wall-clock time: the user or the network can set it backwards. Measure elapsed time
42/// with the monotonic `day_core::frame::now_secs()` instead.
43#[must_use]
44pub fn now_epoch_millis() -> i64 {
45 #[cfg(target_arch = "wasm32")]
46 {
47 // SAFETY: the shim exports this for every web-dom app; a build that links this crate and
48 // an older shim fails at instantiation with a LinkError naming the missing import, which
49 // is the loud failure rather than the silent one.
50 (unsafe { day_datetime_now_secs() } * 1000.0) as i64
51 }
52 #[cfg(not(target_arch = "wasm32"))]
53 {
54 std::time::SystemTime::now()
55 .duration_since(std::time::UNIX_EPOCH)
56 .map_or(0, |d| d.as_millis() as i64)
57 }
58}
59
60/// Seconds since the Unix epoch, from the same clock as [`now_epoch_millis`].
61#[must_use]
62pub fn now_epoch_secs() -> i64 {
63 now_epoch_millis().div_euclid(1000)
64}
65
66// The attribute makes this a wasm import from the instantiation's `env` object (shim.js supplies
67// it) rather than a link-time-resolved symbol; without it rust-lld reports it undefined.
68#[cfg(target_arch = "wasm32")]
69#[link(wasm_import_module = "env")]
70unsafe extern "C" {
71 /// Seconds since the Unix epoch (fractional), from the browser's clock.
72 fn day_datetime_now_secs() -> f64;
73}
74
75impl DayDate {
76 /// A validated date (`month` 1–12, `day` within the month, leap-aware); `None` otherwise.
77 #[must_use]
78 pub fn new(year: i32, month: u8, day: u8) -> Option<Self> {
79 if (1..=12).contains(&month) && day >= 1 && day <= days_in_month(year, month) {
80 Some(DayDate { year, month, day })
81 } else {
82 None
83 }
84 }
85
86 /// Today's date derived from the system clock in UTC (Day carries no time-zone database; an
87 /// app that must roll the date at local midnight should compute it with its own zone source).
88 pub fn today() -> Self {
89 Self::from_epoch_days(now_epoch_secs().div_euclid(86_400))
90 }
91
92 /// Days since 1970-01-01 (negative before). The numeric interchange form across native
93 /// boundaries (`Event::Custom.num`).
94 #[must_use]
95 pub fn to_epoch_days(self) -> i64 {
96 // Howard Hinnant's days_from_civil.
97 let y = i64::from(self.year) - i64::from(self.month <= 2);
98 let era = if y >= 0 { y } else { y - 399 } / 400;
99 let yoe = y - era * 400;
100 let m = i64::from(self.month);
101 let doy = (153 * (m + if m > 2 { -3 } else { 9 }) + 2) / 5 + i64::from(self.day) - 1;
102 let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
103 era * 146_097 + doe - 719_468
104 }
105
106 /// The date `days` after 1970-01-01 (inverse of [`DayDate::to_epoch_days`]).
107 pub fn from_epoch_days(days: i64) -> Self {
108 // Howard Hinnant's civil_from_days.
109 let z = days + 719_468;
110 let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
111 let doe = z - era * 146_097;
112 let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
113 let y = yoe + era * 400;
114 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
115 let mp = (5 * doy + 2) / 153;
116 let day = (doy - (153 * mp + 2) / 5 + 1) as u8;
117 let month = (if mp < 10 { mp + 3 } else { mp - 9 }) as u8;
118 DayDate {
119 year: (y + i64::from(month <= 2)) as i32,
120 month,
121 day,
122 }
123 }
124
125 /// Parse strict ISO-8601 `YYYY-MM-DD` (the form `Display` writes). `None` on anything else.
126 #[must_use]
127 pub fn parse_iso(s: &str) -> Option<Self> {
128 let mut it = s.split('-');
129 let (y, m, d) = (it.next()?, it.next()?, it.next()?);
130 if it.next().is_some() || y.len() != 4 || m.len() != 2 || d.len() != 2 {
131 return None;
132 }
133 if [y, m, d]
134 .iter()
135 .any(|p| !p.bytes().all(|b| b.is_ascii_digit()))
136 {
137 return None;
138 }
139 Self::new(y.parse().ok()?, m.parse().ok()?, d.parse().ok()?)
140 }
141
142 /// This date limited to the inclusive `[min, max]` range (either bound optional).
143 #[must_use]
144 pub fn clamped(self, min: Option<DayDate>, max: Option<DayDate>) -> Self {
145 let mut d = self;
146 if let Some(min) = min
147 && d < min
148 {
149 d = min;
150 }
151 if let Some(max) = max
152 && d > max
153 {
154 d = max;
155 }
156 d
157 }
158}
159
160impl std::fmt::Display for DayDate {
161 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
162 write!(f, "{:04}-{:02}-{:02}", self.year, self.month, self.day)
163 }
164}
165
166#[must_use]
167pub fn is_leap(year: i32) -> bool {
168 (year % 4 == 0 && year % 100 != 0) || year % 400 == 0
169}
170
171#[must_use]
172pub fn days_in_month(year: i32, month: u8) -> u8 {
173 match month {
174 1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
175 4 | 6 | 9 | 11 => 30,
176 2 if is_leap(year) => 29,
177 2 => 28,
178 _ => 0,
179 }
180}
181
182/// A civil (zoneless) wall-clock time. `Display` and [`DayTime::parse_iso`] speak ISO-8601
183/// (`HH:MM`, or `HH:MM:SS` when seconds are nonzero).
184#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
185pub struct DayTime {
186 pub hour: u8,
187 pub minute: u8,
188 pub second: u8,
189}
190
191impl DayTime {
192 /// A validated time (`hour` 0–23, `minute`/`second` 0–59); `None` otherwise.
193 #[must_use]
194 pub fn new(hour: u8, minute: u8, second: u8) -> Option<Self> {
195 if hour < 24 && minute < 60 && second < 60 {
196 Some(DayTime {
197 hour,
198 minute,
199 second,
200 })
201 } else {
202 None
203 }
204 }
205
206 /// The current time of day from the system clock in UTC, the twin of [`DayDate::today`],
207 /// and carrying the same caveat: Day ships no time-zone database, so an app that needs local
208 /// wall-clock time should apply its own offset. Pair the two for a timestamp
209 /// (`Day-Showcase-2026-08-12-14-23-05.png`).
210 #[must_use]
211 pub fn now() -> Self {
212 Self::from_seconds_of_day(now_epoch_secs().rem_euclid(86_400))
213 }
214
215 /// Seconds since midnight, the numeric interchange form across native boundaries.
216 #[must_use]
217 pub fn seconds_of_day(self) -> i64 {
218 i64::from(self.hour) * 3600 + i64::from(self.minute) * 60 + i64::from(self.second)
219 }
220
221 /// The time `secs` after midnight (inverse of [`DayTime::seconds_of_day`]; out-of-range wraps
222 /// into the day).
223 #[must_use]
224 pub fn from_seconds_of_day(secs: i64) -> Self {
225 let s = secs.rem_euclid(86_400);
226 DayTime {
227 hour: (s / 3600) as u8,
228 minute: (s / 60 % 60) as u8,
229 second: (s % 60) as u8,
230 }
231 }
232
233 /// Parse ISO-8601 `HH:MM` or `HH:MM:SS`. `None` on anything else.
234 #[must_use]
235 pub fn parse_iso(s: &str) -> Option<Self> {
236 let mut it = s.split(':');
237 let (h, m) = (it.next()?, it.next()?);
238 let sec = it.next();
239 if it.next().is_some() || h.len() != 2 || m.len() != 2 {
240 return None;
241 }
242 if let Some(sec) = sec
243 && sec.len() != 2
244 {
245 return None;
246 }
247 if [Some(h), Some(m), sec]
248 .iter()
249 .flatten()
250 .any(|p| !p.bytes().all(|b| b.is_ascii_digit()))
251 {
252 return None;
253 }
254 Self::new(
255 h.parse().ok()?,
256 m.parse().ok()?,
257 sec.map_or(Some(0), |s| s.parse().ok())?,
258 )
259 }
260}
261
262impl std::fmt::Display for DayTime {
263 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
264 if self.second == 0 {
265 write!(f, "{:02}:{:02}", self.hour, self.minute)
266 } else {
267 write!(f, "{:02}:{:02}:{:02}", self.hour, self.minute, self.second)
268 }
269 }
270}
271
272// ---------------------------------------------------------------------------
273// The pieces
274// ---------------------------------------------------------------------------
275
276/// How the picker presents (docs/datepicker.md has the per-toolkit table). Like `PickerStyle`,
277/// each intent maps to the platform's closest idiomatic control, so chrome differs per platform.
278#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
279pub enum Style {
280 /// The platform default: [`Style::Compact`] everywhere today.
281 #[default]
282 Automatic,
283 /// A field/button showing the value that summons a transient chooser (`NSDatePicker`
284 /// textFieldAndStepper / `UIDatePicker` .compact / a Material dialog launcher / `QDateEdit` with
285 /// calendar popup / `CalendarDatePicker` flyout / GtkMenuButton+calendar popover /
286 /// ArkUI `CalendarPicker`).
287 Compact,
288 /// An embedded calendar / clock / wheels (`NSDatePicker` graphical / `UIDatePicker` .inline /
289 /// framework DatePicker+TimePicker widgets / `QCalendarWidget` / `CalendarView` / `GtkCalendar` /
290 /// ArkUI `DatePicker` wheels).
291 Inline,
292}
293
294/// Full props (realize) for the date picker. `style`/`min`/`max` are set once at build; only the
295/// value patches.
296#[derive(Clone, Copy, Debug, Default, PartialEq)]
297pub struct DateProps {
298 pub date: DayDate,
299 pub style: Style,
300 pub min: Option<DayDate>,
301 pub max: Option<DayDate>,
302}
303
304#[derive(Clone, Copy, Debug, PartialEq)]
305pub enum DatePatch {
306 SetDate(DayDate),
307}
308
309/// Full props (realize) for the time picker. `style`/`seconds` are set once at build; only the
310/// value patches.
311#[derive(Clone, Copy, Debug, Default, PartialEq)]
312pub struct TimeProps {
313 pub time: DayTime,
314 pub style: Style,
315 /// Show/edit seconds; honored on AppKit and Qt (the toolkits whose controls have a seconds
316 /// field), a documented no-op elsewhere.
317 pub seconds: bool,
318}
319
320#[derive(Clone, Copy, Debug, PartialEq)]
321pub enum TimePatch {
322 SetTime(DayTime),
323}