Skip to main content

taut/
date.rs

1//! Dates: a `Date` value, a date picker, and a date range picker.
2//!
3//! ```ignore
4//! // in the app's state:  due: Date::today()
5//! if ui.date(&mut app.due).changed {
6//!     plan_again();
7//! }
8//! ui.date_range(&mut app.away, &mut app.back); // the first day pressed, then the last
9//! ```
10//!
11//! Dates are written in the user's format ([`ui.locale`](Ui::locale)), and weeks start on the
12//! user's first day. In the calendar, focus starts on the picked day: arrows move a day or a
13//! week, Page Up/Down a month (with Shift, a year), Home/End to the week's start and end, Enter
14//! picks.
15use crate::accessibility::Role;
16use crate::color::Color;
17use crate::event::{Key, Mods};
18use crate::geom::Rect;
19use crate::id::Id;
20use crate::layout::Align;
21use crate::ui::{Icon, Response, Ui};
22use crate::widgets::{Before, DOWN, RIGHT};
23#[cfg(unix)]
24use std::ffi::{c_int, c_long};
25use std::fmt::Write;
26
27const LEFT: Icon = Icon::line("M9.5 4 5.5 8 9.5 12");
28/// Day numbers, written out once.
29const NUMBERS: [&str; 31] =
30    ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31"];
31/// Minimum width and height of a calendar day (more with larger text).
32const DAY: [f32; 2] = [30.0, 26.0];
33
34/// A calendar day.
35#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
36pub struct Date {
37    /// The year.
38    pub year: i32,
39    /// 1 to 12.
40    pub month: u8,
41    /// Day of the month, from 1.
42    pub day: u8,
43}
44
45impl Date {
46    /// A date from year, month (1 to 12) and day (from 1).
47    pub const fn new(year: i32, month: u8, day: u8) -> Self {
48        Date { year, month, day }
49    }
50
51    /// Days since 1970-01-01; negative before it.
52    pub fn days(self) -> i64 {
53        // Years counted from March, so the leap day comes last, in 400-year cycles after which
54        // the calendar repeats. (Howard Hinnant's algorithm.)
55        let year = self.year as i64 - (self.month <= 2) as i64;
56        let (era, month) = (year.div_euclid(400), (self.month as i64 + 9) % 12);
57        let of_year = (153 * month + 2) / 5 + self.day as i64 - 1;
58        let of_era = year.rem_euclid(400) * 365 + year.rem_euclid(400) / 4 - year.rem_euclid(400) / 100 + of_year;
59        era * 146_097 + of_era - 719_468
60    }
61    /// The date `days` after 1970-01-01. Beyond the representable years, the first or last.
62    pub fn from_days(days: i64) -> Self {
63        let shifted = days.saturating_add(719_468);
64        let (era, of_era) = (shifted.div_euclid(146_097), shifted.rem_euclid(146_097));
65        let year_of_era = (of_era - of_era / 1460 + of_era / 36_524 - of_era / 146_096) / 365;
66        let of_year = of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100);
67        let month = (5 * of_year + 2) / 153;
68        let (day, month) = (of_year - (153 * month + 2) / 5 + 1, (month + 2) % 12 + 1);
69        let year = (year_of_era + era * 400 + (month <= 2) as i64).clamp(i32::MIN as i64, i32::MAX as i64) as i32;
70        Date { year, month: month as u8, day: day as u8 }
71    }
72    /// Day of the week: 0 Monday to 6 Sunday.
73    pub fn weekday(self) -> u8 {
74        (self.days() + 3).rem_euclid(7) as u8
75    }
76    /// Days in its month.
77    pub fn month_length(self) -> u8 {
78        let leap = self.year % 4 == 0 && (self.year % 100 != 0 || self.year % 400 == 0);
79        match self.month {
80            2 if leap => 29,
81            2 => 28,
82            4 | 6 | 9 | 11 => 30,
83            _ => 31,
84        }
85    }
86    /// The same day `months` later (earlier, if negative); the month's last day if it has
87    /// fewer.
88    pub fn add_months(self, months: i32) -> Self {
89        let counted = self.year as i64 * 12 + self.month as i64 - 1 + months as i64;
90        let year = counted.div_euclid(12).clamp(i32::MIN as i64, i32::MAX as i64) as i32;
91        let first = Date::new(year, counted.rem_euclid(12) as u8 + 1, 1);
92        Date { day: self.day.min(first.month_length()), ..first }
93    }
94    /// Today, in local time.
95    pub fn today() -> Self {
96        let [year, month, day, ..] = local_now();
97        Date::new(year, month as u8, day as u8)
98    }
99}
100
101/// 1970-01-01.
102impl Default for Date {
103    fn default() -> Self {
104        Date::new(1970, 1, 1)
105    }
106}
107
108/// ISO 8601, which sorts: `2026-11-30`. For the user's format, see
109/// [`ui.format_date(date)`](Ui::format_date).
110impl std::fmt::Display for Date {
111    fn fmt(&self, to: &mut std::fmt::Formatter) -> std::fmt::Result {
112        write!(to, "{:04}-{:02}-{:02}", self.year, self.month, self.day)
113    }
114}
115
116/// Local time now: year, month, day, hour, minute, second.
117#[cfg(windows)]
118pub(crate) fn local_now() -> [i32; 6] {
119    crate::windows::local_time().map(i32::from)
120}
121
122/// C's `struct tm` on every Unix: `int` fields, and the UTC offset as a `long`.
123#[cfg(unix)]
124#[repr(C)]
125struct Moment {
126    second: c_int,
127    minute: c_int,
128    hour: c_int,
129    day: c_int,
130    month: c_int,
131    year: c_int,
132    rest: [c_int; 3],
133    ahead: c_long,
134    zone: *const u8,
135}
136
137/// C's `time_t`: seconds since 1970, a `long`, as these functions take it on 32 and 64 bits.
138#[cfg(unix)]
139type Seconds = c_long;
140
141#[cfg(unix)]
142unsafe extern "C" {
143    fn time(into: *mut Seconds) -> Seconds;
144    fn localtime_r(time: *const Seconds, into: *mut Moment) -> *mut Moment;
145}
146
147#[cfg(unix)]
148pub(crate) fn local_now() -> [i32; 6] {
149    let mut moment = Moment { second: 0, minute: 0, hour: 0, day: 1, month: 0, year: 70, rest: [0; 3], ahead: 0, zone: std::ptr::null() };
150    // SAFETY: the C library fills in the struct it is given; both pointers outlive the calls.
151    unsafe { localtime_r(&time(std::ptr::null_mut()), &mut moment) };
152    [moment.year + 1900, moment.month + 1, moment.day, moment.hour, moment.minute, moment.second]
153}
154
155/// Without a system to ask, UTC. (A page asks the browser's clock and time zone.)
156#[cfg(not(any(windows, unix)))]
157pub(crate) fn local_now() -> [i32; 6] {
158    #[cfg(target_family = "wasm")]
159    let since = (crate::web_host::unix_seconds() as i64 + crate::web_host::zone_ahead()).max(0) as u64;
160    #[cfg(not(target_family = "wasm"))]
161    let since = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |since| since.as_secs());
162    let (day, of_day) = (Date::from_days((since / 86_400) as i64), (since % 86_400) as i32);
163    [day.year, day.month as i32, day.day as i32, of_day / 3600, of_day / 60 % 60, of_day % 60]
164}
165
166/// The local UTC offset at `at` (seconds since 1970, UTC), in seconds: added to a UTC time to
167/// get local time.
168pub(crate) fn ahead_of_greenwich(at: i64) -> i64 {
169    ahead(at)
170}
171
172#[cfg(unix)]
173fn ahead(at: i64) -> i64 {
174    let mut moment = Moment { second: 0, minute: 0, hour: 0, day: 1, month: 0, year: 70, rest: [0; 3], ahead: 0, zone: std::ptr::null() };
175    // SAFETY: the C library fills in the struct it is given; both pointers outlive the call.
176    unsafe { localtime_r(&at, &mut moment) };
177    moment.ahead
178}
179
180#[cfg(windows)]
181#[link(name = "kernel32")]
182unsafe extern "system" {
183    fn GetLocalTime(time: *mut [u16; 8]);
184}
185
186/// From Windows' local and UTC time now; taken to hold at any moment.
187#[cfg(windows)]
188fn ahead(_at: i64) -> i64 {
189    let mut time = [0u16; 8];
190    // SAFETY: the system fills in the struct it is given.
191    unsafe { GetLocalTime(&mut time) };
192    let here = Date::new(time[0] as i32, time[1] as u8, time[3] as u8).days() * 86_400 + time[4] as i64 * 3600 + time[5] as i64 * 60 + time[6] as i64;
193    let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |since| since.as_secs() as i64);
194    // The two clocks were read a moment apart: zones differ by whole quarter hours.
195    ((here - now) as f64 / 900.0).round() as i64 * 900
196}
197
198#[cfg(not(any(windows, unix)))]
199fn ahead(_at: i64) -> i64 {
200    #[cfg(target_family = "wasm")]
201    return crate::web_host::zone_ahead();
202    #[allow(unreachable_code)]
203    0
204}
205
206/// Calendar and clock words: English until the app sets its own in `ui.calendar_words`, but for
207/// month and day names and AM/PM, which are the system's while `ui.locale` is `None`
208/// ([`CalendarWords::of_the_system`]). (Date and time formats and the week's first day: see
209/// [`ui.locale`](Ui::locale).)
210#[derive(Clone, Copy, Debug, PartialEq)]
211pub struct CalendarWords {
212    /// The names of the twelve months.
213    pub months: [&'static str; 12],
214    /// Short weekday names, Monday first.
215    pub days: [&'static str; 7],
216    /// AM and PM.
217    pub halves: [&'static str; 2],
218    /// Screen reader names of a time's fields: hours, minutes, seconds, AM/PM.
219    pub clock: [&'static str; 4],
220    /// Screen reader names of the previous and next month arrows.
221    pub arrows: [&'static str; 2],
222}
223
224impl Default for CalendarWords {
225    fn default() -> Self {
226        CalendarWords {
227            months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
228            days: ["Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"],
229            halves: ["AM", "PM"],
230            clock: ["Hours", "Minutes", "Seconds", "AM or PM"],
231            arrows: ["The month before", "The month after"],
232        }
233    }
234}
235
236/// The open calendar: its box, the month shown, the first end of a range being picked, and the
237/// day under the pointer or focus last run, to which a half-picked range is shown.
238#[derive(Clone, Copy, Default)]
239pub(crate) struct Shown {
240    of: Id,
241    month: (i32, u8),
242    first: Option<Date>,
243    pointed: Option<Date>,
244}
245
246/// Date and date range pickers.
247impl Ui {
248    /// A date box that opens a calendar to pick another. `changed` is set when the user picks.
249    pub fn date(&mut self, date: &mut Date) -> Response {
250        let mut written = std::mem::take(&mut self.scratch);
251        written.clear();
252        self.formats().write_date(&mut written, *date);
253        let mut state = self.opens_calendar(&written);
254        self.scratch = written;
255        if let Some(day) = self.calendar(state.id, [*date; 2]) {
256            (state.changed, *date) = (day != *date, day);
257            self.close_popup();
258        }
259        state
260    }
261
262    /// A date range box, `from` to `to`, that opens a calendar: the first day pressed is one
263    /// end, the second the other (the earlier is `from`). Until the second, the range is shown
264    /// up to the day under the pointer or focus, and nothing changes. `changed` is set when a
265    /// range is picked.
266    pub fn date_range(&mut self, from: &mut Date, to: &mut Date) -> Response {
267        let (mut written, locale) = (std::mem::take(&mut self.scratch), self.formats());
268        written.clear();
269        locale.write_date(&mut written, *from);
270        written.push_str(" \u{2013} ");
271        locale.write_date(&mut written, *to);
272        let mut state = self.opens_calendar(&written);
273        self.scratch = written;
274        let Some(day) = self.calendar(state.id, [*from, *to]) else { return state };
275        let Some(first) = self.calendar_open.first else {
276            self.calendar_open.first = Some(day);
277            return state;
278        };
279        state.changed = (first.min(day), first.max(day)) != (*from, *to);
280        (*from, *to) = (first.min(day), first.max(day));
281        self.close_popup();
282        state
283    }
284
285    /// The box showing the pick, `written`; pressed, it opens the calendar. Screen readers get
286    /// a button named by its text, with a popup, expanded or not.
287    fn opens_calendar(&mut self, written: &str) -> Response {
288        let state = self.button_like(Before::None, written, Some(DOWN), false);
289        if state.clicked {
290            self.open_calendar(state.id, state.rect);
291        }
292        let open = self.popups.iter().any(|popup| popup.id == state.id);
293        self.tell(&state, Role::Fold, Some(open), "");
294        state
295    }
296
297    /// Opens the calendar of box `of`, below `under`: at the picked month, nothing half picked.
298    pub(crate) fn open_calendar(&mut self, of: Id, under: Rect) {
299        self.open_popup(of, under);
300        self.calendar_open.of = 0;
301    }
302
303    /// The calendar under a box while open: month name, previous and next arrows, and the days
304    /// in week rows from the user's first weekday. `picked` are the first and last picked days
305    /// (the same, for one). Returns the day pressed, if any.
306    pub(crate) fn calendar(&mut self, of: Id, picked: [Date; 2]) -> Option<Date> {
307        if !self.popup(of) {
308            return None;
309        }
310        let t = self.theme;
311        let fresh = self.calendar_open.of != of;
312        if fresh {
313            self.calendar_open = Shown { of, month: (picked[0].year, picked[0].month), ..Shown::default() };
314        }
315        // Never larger than the window, either way: what doesn't fit scrolls.
316        let [wide, high] = self.popup_most();
317        self.column().pad(8.0).gap(6.0).max(wide, high).scroll().scroll_x().fill(t.raised).border(t.line_strong, 1.0).radius(8.0).shadow(16.0).sense().open();
318        let first = self.calendar_month_row();
319        self.grid(7).gap(2.0).open();
320        // On opening, focus goes to the picked day, and keys move between days. Handled here,
321        // where the days' ids are known and before them, so no other box gets the keys first.
322        if fresh {
323            self.set_focus(self.id(picked[0].days()));
324        }
325        self.calendar_keys(first);
326        let size = self.day_size();
327        self.calendar_weekdays(first, size);
328        let pressed = self.calendar_days(first, picked, size);
329        self.close();
330        self.close();
331        pressed
332    }
333
334    /// The calendar's top row: the previous-month arrow, the month and year, the next-month
335    /// arrow. Returns the first day of the month shown, after the arrows.
336    fn calendar_month_row(&mut self) -> Date {
337        let (t, words, (year, month)) = (self.theme, self.calendar_words_in_use(), self.calendar_open.month);
338        self.row().gap(6.0).open();
339        let back = self.button_like(Before::Icon(LEFT), "", None, false);
340        self.tell(&back, Role::Button, None, words.arrows[0]);
341        self.spacer();
342        self.text(words.months[(month as usize + 11) % 12], t.font.bold(), t.text);
343        self.year_label(year);
344        self.spacer();
345        let on = self.button_like(Before::Icon(RIGHT), "", None, false);
346        self.tell(&on, Role::Button, None, words.arrows[1]);
347        self.close();
348        let (back, on) = (back.clicked, on.clicked);
349        let first = Date::new(year, month, 1).add_months(on as i32 - back as i32);
350        self.calendar_open.month = (first.year, first.month);
351        self.again |= on || back;
352        first
353    }
354
355    /// The weekday names, from the user's first weekday; then blanks for the weekdays before
356    /// the 1st of `first`'s month.
357    fn calendar_weekdays(&mut self, first: Date, size: [f32; 2]) {
358        let (t, words, first_day) = (self.theme, self.calendar_words_in_use(), self.locale_in_use().first_weekday);
359        let heading = 18f32.max(self.text.metrics(t.small_font, self.scale).height().ceil() + 2.0);
360        for day in 0..7 {
361            self.el().size(size[0], heading).text(words.days[(day + first_day as usize) % 7], t.small_font, t.text_faint).text_align(Align::Center).show();
362        }
363        for _ in 0..(first.weekday() + 7 - first_day % 7) % 7 {
364            self.el().size(size[0], size[1]).show();
365        }
366    }
367
368    /// The days of `first`'s month, `picked` marked. Returns the day pressed, if any.
369    fn calendar_days(&mut self, first: Date, picked: [Date; 2], size: [f32; 2]) -> Option<Date> {
370        // A half-picked range shows up to the day pointed at.
371        let shown = match (self.calendar_open.first, self.calendar_open.pointed) {
372            (Some(start), Some(end)) => [start.min(end), start.max(end)],
373            (Some(start), None) => [start; 2],
374            (None, _) => picked,
375        };
376        let (today, mut pressed, mut hovered, mut keyed) = (Date::today(), None, None, None);
377        for day in (1..=first.month_length()).map(|day| Date::new(first.year, first.month, day)) {
378            let state = self.calendar_day(day, shown, today, size);
379            pressed = pressed.or(state.clicked.then_some(day));
380            (hovered, keyed) = (hovered.or(state.hovered.then_some(day)), keyed.or(state.focused.then_some(day)));
381        }
382        // The pointer's day if over one; else focus. A half-picked range is redrawn up to it.
383        let pointed = hovered.or(keyed);
384        let half_picked = self.calendar_open.first.is_some();
385        self.again |= half_picked && std::mem::replace(&mut self.calendar_open.pointed, pointed) != pointed;
386        pressed
387    }
388
389    /// Calendar keys while focus is on a day of the month starting `first`: move focus, and the
390    /// month shown.
391    fn calendar_keys(&mut self, first: Date) {
392        let mut days = (0..first.month_length() as i64).map(|day| Date::from_days(first.days() + day));
393        let Some(on) = days.find(|day| self.id(day.days()) == self.focus) else { return };
394        // Home and End go to the user's week start and end.
395        let into_week = (on.weekday() as i64 - self.locale_in_use().first_weekday as i64).rem_euclid(7);
396        let mut key = |key: Key, mods: Mods| self.key(key, mods) as i64;
397        let along = key(Key::Right, Mods::NONE) - key(Key::Left, Mods::NONE) + 7 * (key(Key::Down, Mods::NONE) - key(Key::Up, Mods::NONE));
398        let months = key(Key::PageDown, Mods::NONE) - key(Key::PageUp, Mods::NONE) + 12 * (key(Key::PageDown, Mods::SHIFT) - key(Key::PageUp, Mods::SHIFT));
399        let ends = (6 - into_week) * key(Key::End, Mods::NONE) - into_week * key(Key::Home, Mods::NONE);
400        let to = Date::from_days(on.add_months(months as i32).days() + along + ends);
401        if to != on {
402            self.calendar_open.month = (to.year, to.month);
403            self.set_focus(self.id(to.days()));
404        }
405    }
406
407    /// The height of a one-line part: the theme's, or the text's, if larger text needs more.
408    pub(crate) fn line_part(&mut self) -> f32 {
409        self.theme.control_height.max(self.text.metrics(self.theme.font, self.scale).height().ceil() + 8.0)
410    }
411    /// A calendar day's size: room for "30".
412    fn day_size(&mut self) -> [f32; 2] {
413        let (font, wide) = (self.theme.font, self.text_width("30", self.theme.font));
414        [DAY[0].max(wide.ceil() + 10.0), DAY[1].max(self.text.metrics(font, self.scale).height().ceil() + 6.0)]
415    }
416
417    /// The year, beside the month's name.
418    fn year_label(&mut self, year: i32) {
419        let (t, mut written) = (self.theme, std::mem::take(&mut self.scratch));
420        written.clear();
421        let _ = write!(written, "{year}");
422        self.text(&written, t.font.bold(), t.text_dim);
423        self.scratch = written;
424    }
425
426    /// One calendar day: filled at the ends of the pick, tinted between them, ringed if today.
427    /// Screen readers get a selectable row named in full ("11 November 2026"), its day number,
428    /// and whether it is picked.
429    fn calendar_day(&mut self, day: Date, [start, end]: [Date; 2], today: Date, [wide, high]: [f32; 2]) -> Response {
430        let t = self.theme;
431        let state = self.press(self.id(day.days()));
432        let (ends, within) = (day == start || day == end, start < day && day < end);
433        let (fill, ink) = match (ends, within, state.hovered || state.focused) {
434            (true, ..) => (t.accent, t.on_accent),
435            (false, _, true) => (t.hover, t.text),
436            (false, true, false) => (t.selected, t.text),
437            (false, false, false) => (Color::NONE, t.text),
438        };
439        // On a day filled with the accent, the focus ring takes the number's colour, which
440        // shows on it.
441        let edge = match (ends && state.focused, day == today) {
442            (true, _) => t.on_accent,
443            (false, true) => t.accent,
444            (false, false) => Color::NONE,
445        };
446        let cell = self.el().key(day.days()).size(wide, high).text(NUMBERS[day.day as usize - 1], t.font, ink).text_align(Align::Center);
447        cell.fill(fill).border(edge, 1.0).radius(5.0).sense().focusable().show();
448        if self.listening {
449            let name = format!("{} {} {}", day.day, self.calendar_words_in_use().months[day.month as usize - 1], day.year);
450            self.tell(&state, Role::Row, Some(ends || within), &name);
451            self.tell_position(day.day as usize, day.month_length() as usize);
452        }
453        state
454    }
455}
456
457#[cfg(test)]
458mod tests {
459    use super::*;
460
461    #[test]
462    fn days_are_counted_and_named_right() {
463        assert_eq!(Date::new(1970, 1, 1).days(), 0);
464        assert_eq!(Date::new(1970, 1, 1).weekday(), 3, "a Thursday");
465        assert_eq!(Date::new(2026, 11, 11).weekday(), 2, "a Wednesday");
466        assert_eq!(Date::new(2000, 2, 29).days() + 1, Date::new(2000, 3, 1).days(), "2000 was a leap year");
467        assert_eq!([Date::new(2024, 2, 1).month_length(), Date::new(2023, 2, 1).month_length(), Date::new(1900, 2, 1).month_length()], [29, 28, 28]);
468        assert_eq!([Date::new(2026, 12, 5).month_length(), Date::new(2026, 4, 30).month_length()], [31, 30]);
469        assert_eq!(Date::new(2026, 3, 7).to_string(), "2026-03-07");
470        assert!(Date::new(2026, 3, 7) < Date::new(2026, 11, 1));
471    }
472
473    #[test]
474    fn a_month_on_or_back_keeps_the_day_where_the_month_has_it() {
475        let last = Date::new(2026, 1, 31);
476        assert_eq!(
477            [last.add_months(1), last.add_months(2), last.add_months(-2), last.add_months(13)],
478            [Date::new(2026, 2, 28), Date::new(2026, 3, 31), Date::new(2025, 11, 30), Date::new(2027, 2, 28)]
479        );
480        assert_eq!(Date::new(2024, 2, 29).add_months(-12), Date::new(2023, 2, 28));
481        assert_eq!(Date::new(2026, 11, 13).add_months(0), Date::new(2026, 11, 13));
482    }
483
484    #[test]
485    fn every_day_for_eight_hundred_years_comes_back_as_itself() {
486        let mut day = Date::new(1600, 1, 1);
487        for days in day.days()..Date::new(2400, 1, 1).days() {
488            assert_eq!(Date::from_days(days), day);
489            assert_eq!(day.days(), days);
490            let last = day.day == day.month_length();
491            day = match (last, day.month) {
492                (false, _) => Date::new(day.year, day.month, day.day + 1),
493                (true, 12) => Date::new(day.year + 1, 1, 1),
494                (true, _) => Date::new(day.year, day.month + 1, 1),
495            };
496        }
497    }
498}