Skip to main content

qframe/widgets/
date_picker.rs

1//! Date picker: a field that opens a month calendar as a layer.
2
3use std::time::Duration;
4
5use super::cells;
6use super::layer::PointerGate;
7use super::placement::{self, Placement};
8use crate::date::{Date, Weekday};
9use crate::event::{Event, KeyEvent, MouseButton, MouseKind};
10use crate::geometry::{Rect, Size};
11use crate::keymap::{Key, Modifiers};
12use crate::motion::Easing;
13use crate::style::CellStyle;
14use crate::text;
15use crate::theme::State;
16use crate::widget::{EventCx, MeasureCx, PaintCx, Widget};
17
18/// Width of one day column.
19const CELL: u16 = 4;
20
21/// Rows of weeks; always six so the calendar keeps its height from month to month.
22const WEEKS: u16 = 6;
23
24/// Title row, a spare row and the weekday row above the weeks.
25const HEADER_ROWS: u16 = 3;
26
27/// Cells of a month arrow beside the title: the glyph with a cell on each side, all of them the
28/// press target.
29const ARROW: u16 = 3;
30
31/// A field showing a chosen date that opens a calendar to choose another.
32///
33/// Closed: Enter, Space, ↓ or a click opens it. Open: ←/→ move a day, ↑/↓ a week, PgUp/PgDn a
34/// month, Shift+PgUp/PgDn a year, Home/End go to the ends of the week, Enter or Space chooses,
35/// Esc or a click elsewhere closes; that click still reaches what it landed on, and a click on
36/// the field while open only closes it. The arrows beside the title and the mouse wheel change the
37/// month (each arrow is three cells that light up under the pointer). One day is highlighted:
38/// the keyboard moves it and so does the pointer once it moves. Whatever the pointer is over, the
39/// field, an arrow or a day, shows the pillar `▌` in its leftmost cell, a column that is always
40/// blank, so nothing in the date picker slides whatever [`Env::slide`](crate::env::Env::slide)
41/// says. The highlighted day's pillar breathes only while the keyboard moved it last. Month and
42/// weekday names, the first day of the week and the field format come from the `quvyta.date`
43/// locale keys.
44///
45/// The field uses the `select` styles. The calendar uses `calendar` (`bg`, `padding`),
46/// `calendar-title`, `calendar-arrow` with `hover` (`bg` over its three cells, `pillar`),
47/// `calendar-weekday`, and `calendar-day` with `hover` (the highlighted day, `pillar`), `focus` (added
48/// to `hover` while the keyboard moved the highlight), `selected`, variants `outside` and `today`.
49pub struct DatePicker<Msg> {
50    value: Option<Date>,
51    today: Option<Date>,
52    placeholder: String,
53    disabled: bool,
54    on_change: Option<Box<dyn Fn(Date) -> Msg>>,
55}
56
57#[derive(Debug, Default)]
58struct DatePickerMemory {
59    open: bool,
60    opened_at: Duration,
61    cursor: Option<Date>,
62    popup: Rect,
63    /// The pointer moves the one highlighted day only when it moves.
64    pointer: PointerGate,
65    /// A day of a neighbouring month under the pointer: it is the highlighted day without
66    /// turning the calendar to its month.
67    pointed: Option<Date>,
68    /// The pointer, not the keyboard, put the highlight where it is: its pillar stays calm.
69    by_pointer: bool,
70}
71
72impl<Msg: 'static> DatePicker<Msg> {
73    /// A date picker showing `value`.
74    #[must_use]
75    pub fn new(value: Option<Date>) -> Self {
76        Self { value, today: None, placeholder: String::new(), disabled: false, on_change: None }
77    }
78
79    /// Faint text shown while no date is chosen.
80    #[must_use]
81    pub fn placeholder(mut self, text: impl Into<String>) -> Self {
82        self.placeholder = text.into();
83        self
84    }
85
86    /// The day marked as today; by default [`Date::today_local`], the day on the machine's own
87    /// clock and time zone, so the mark does not jump a day early or late around midnight.
88    #[must_use]
89    pub fn today(mut self, today: Date) -> Self {
90        self.today = Some(today);
91        self
92    }
93
94    /// Greys the field out; it cannot be opened.
95    #[must_use]
96    pub fn disabled(mut self, disabled: bool) -> Self {
97        self.disabled = disabled;
98        self
99    }
100
101    /// Message for choosing a different date.
102    #[must_use]
103    pub fn on_change(mut self, message: impl Fn(Date) -> Msg + 'static) -> Self {
104        self.on_change = Some(Box::new(message));
105        self
106    }
107
108    fn today_or_clock(&self) -> Date {
109        self.today.unwrap_or_else(Date::today_local)
110    }
111
112    fn open(&self, cx: &mut EventCx<'_, Msg>) {
113        let now = cx.now();
114        let cursor = self.value.unwrap_or_else(|| self.today_or_clock());
115        let pointer = cx.interaction.pointer;
116        let memory = cx.memory::<DatePickerMemory>();
117        memory.open = true;
118        memory.opened_at = now;
119        memory.cursor = Some(cursor);
120        memory.pointer = PointerGate::new(pointer);
121        memory.pointed = None;
122        memory.by_pointer = false;
123        cx.capture_keys(true);
124    }
125
126    fn close(cx: &mut EventCx<'_, Msg>) {
127        cx.memory::<DatePickerMemory>().open = false;
128        cx.capture_keys(false);
129    }
130
131    fn choose(&self, cx: &mut EventCx<'_, Msg>, date: Date) {
132        Self::close(cx);
133        cx.flash();
134        if Some(date) != self.value
135            && let Some(message) = &self.on_change
136        {
137            cx.emit(message(date));
138        }
139    }
140
141    fn cursor(&self, cx: &mut EventCx<'_, Msg>) -> Date {
142        let fallback = self.value.unwrap_or_else(|| self.today_or_clock());
143        *cx.memory::<DatePickerMemory>().cursor.get_or_insert(fallback)
144    }
145
146    fn key(&self, cx: &mut EventCx<'_, Msg>, key: &KeyEvent) -> bool {
147        // Keys move on from the day the keyboard or the pointer last put the highlight on.
148        let memory = cx.memory::<DatePickerMemory>();
149        memory.pointed = None;
150        memory.by_pointer = false;
151        let cursor = self.cursor(cx);
152        let shift = Modifiers { shift: true, ..Modifiers::default() };
153        let first = first_weekday(cx.env().i18n());
154        let moved = if key.is_plain(Key::Left) {
155            Some(cursor.add_days(-1))
156        } else if key.is_plain(Key::Right) {
157            Some(cursor.add_days(1))
158        } else if key.is_plain(Key::Up) {
159            Some(cursor.add_days(-7))
160        } else if key.is_plain(Key::Down) {
161            Some(cursor.add_days(7))
162        } else if key.is_plain(Key::PageUp) {
163            Some(cursor.add_months(-1))
164        } else if key.is_plain(Key::PageDown) {
165            Some(cursor.add_months(1))
166        } else if key.chord.mods == shift && key.chord.key == Key::PageUp {
167            Some(cursor.add_months(-12))
168        } else if key.chord.mods == shift && key.chord.key == Key::PageDown {
169            Some(cursor.add_months(12))
170        } else if key.is_plain(Key::Home) {
171            Some(cursor.start_of_week(first))
172        } else if key.is_plain(Key::End) {
173            Some(cursor.start_of_week(first).add_days(6))
174        } else {
175            None
176        };
177        if let Some(date) = moved {
178            cx.memory::<DatePickerMemory>().cursor = Some(date);
179        } else if key.is_plain(Key::Enter) || key.is_plain(Key::Space) {
180            self.choose(cx, cursor);
181        } else if key.is_plain(Key::Esc) {
182            Self::close(cx);
183        } else if key.is_plain(Key::Tab) {
184            Self::close(cx);
185            return false;
186        }
187        true
188    }
189
190    fn click_calendar(&self, cx: &mut EventCx<'_, Msg>, popup: Rect, x: i32, y: i32) {
191        let cursor = self.cursor(cx);
192        let inner = popup.inset(calendar_padding(cx.env()));
193        if y == inner.y {
194            if x < inner.x + i32::from(ARROW) {
195                cx.memory::<DatePickerMemory>().cursor = Some(cursor.add_months(-1));
196            } else if x >= inner.right() - i32::from(ARROW) {
197                cx.memory::<DatePickerMemory>().cursor = Some(cursor.add_months(1));
198            }
199            return;
200        }
201        let row = y - inner.y - i32::from(HEADER_ROWS);
202        let column = (x - inner.x) / i32::from(CELL);
203        if !(0..i32::from(WEEKS)).contains(&row) || !(0..7).contains(&column) || x < inner.x {
204            return;
205        }
206        let date = grid_start(cursor, first_weekday(cx.env().i18n())).add_days(i64::from(row * 7 + column));
207        self.choose(cx, date);
208    }
209}
210
211/// The first day of the week for the active language. Reads the environment's translator
212/// directly because events are handled outside the translation scope of painting.
213fn first_weekday(i18n: &crate::i18n::I18n) -> Weekday {
214    let number = i18n.translate("quvyta.date.first-weekday", &[]);
215    number.trim().parse::<u8>().ok().and_then(Weekday::from_number).unwrap_or(Weekday::Monday)
216}
217
218/// The first day shown for the month of `cursor`.
219fn grid_start(cursor: Date, first: Weekday) -> Date {
220    cursor.first_of_month().start_of_week(first)
221}
222
223fn month_name(month: u8) -> String {
224    crate::t!(&format!("quvyta.date.month-{month}"))
225}
226
227/// `date` written the way the active language writes dates.
228fn format_date(date: Date) -> String {
229    crate::t!("quvyta.date.format", day = u32::from(date.day()), month = month_name(date.month()), year = date.year())
230}
231
232fn calendar_padding(env: &crate::env::Env) -> crate::geometry::Padding {
233    crate::style::WidgetStyle::new(env.theme().style("calendar", None, &[]), 0.0).padding()
234}
235
236impl<Msg: 'static> Widget<Msg> for DatePicker<Msg> {
237    fn measure(&self, cx: &mut MeasureCx<'_>, available: Size) -> Size {
238        let style = cx.env().theme().style("select", None, &[]);
239        let (vertical, horizontal) = style.pair("padding").unwrap_or((0, 1));
240        let sample = self.value.map_or(0, |date| text::width(&format_date(date)));
241        let longest = sample.max(text::width(&self.placeholder)).max(12);
242        Size::new(cells::sum([longest, 3, horizontal.saturating_mul(2)]), vertical.saturating_mul(2).saturating_add(1))
243            .min(available)
244    }
245
246    fn paint(&self, cx: &mut PaintCx<'_>, area: Rect) {
247        let open = cx.memory::<DatePickerMemory>().open;
248        let mut states = if self.disabled { vec![State::Disabled] } else { cx.pressable_states() };
249        if open {
250            states.push(State::Active);
251        }
252        let label = self.value.map(format_date);
253        super::select::paint_field(cx, area, &states, label.as_deref(), &self.placeholder);
254        if !self.disabled {
255            cx.register_hit(area);
256        }
257        if open && !self.disabled {
258            cx.request_overlay(area);
259        }
260    }
261
262    fn paint_overlay(&self, cx: &mut PaintCx<'_>, anchor: Rect) {
263        let style = cx.style("calendar", None, &[]);
264        let padding = style.padding();
265        let background = style.text().bg.unwrap_or_else(|| cx.color("overlay"));
266        let size = Size::new(
267            (CELL * 7).saturating_add(padding.horizontal()),
268            (HEADER_ROWS + WEEKS).saturating_add(padding.vertical()),
269        );
270        let (full, side) = placement::place(anchor, size, cx.clip(), Placement::Below);
271        let (opened_at, remembered) = {
272            let memory = cx.memory::<DatePickerMemory>();
273            memory.popup = full;
274            (memory.opened_at, memory.cursor)
275        };
276        let enter = cx.env().theme().motion().enter;
277        let progress = cx.progress_since(opened_at, enter, Easing::EaseOut);
278        let shown = placement::unfold(full, side, progress);
279        cx.clear(shown, background);
280        cx.register_hit(shown);
281        let mut cursor = remembered.or(self.value).unwrap_or_else(|| self.today_or_clock());
282        let today = self.today_or_clock();
283        let first = first_weekday(cx.env().i18n());
284        let inner = full.inset(padding);
285        let pointer = cx.pointer();
286        let weekday_row = inner.y + 2;
287        let day_rect = |index: i64| {
288            let (row, column) = (u16::try_from(index / 7).unwrap_or(0), u16::try_from(index % 7).unwrap_or(0));
289            Rect::new(inner.x + i32::from(column * CELL), weekday_row + 1 + i32::from(row), CELL, 1)
290        };
291        let start = grid_start(cursor, first);
292        let under_pointer = pointer
293            .and_then(|(x, y)| (0..i64::from(WEEKS * 7)).find(|index| day_rect(*index).contains(x, y)))
294            .map(|index| start.add_days(index));
295        let anywhere = cx.pointer_anywhere();
296        let highlighted = {
297            let memory = cx.memory::<DatePickerMemory>();
298            if memory.pointer.moved(anywhere) {
299                memory.pointed = None;
300                memory.by_pointer |= under_pointer.is_some();
301                match under_pointer {
302                    Some(date) if date.month() == cursor.month() => {
303                        cursor = date;
304                        memory.cursor = Some(date);
305                    }
306                    other => memory.pointed = other,
307                }
308            }
309            (memory.pointed.unwrap_or(cursor), memory.by_pointer)
310        };
311        let (highlighted, by_pointer) = highlighted;
312        // Only a highlight the keyboard moved counts as visible focus, so its pillar breathes.
313        let keyboard_focus = !by_pointer && cx.is_focus_visible();
314        cx.with_clip(shown, |cx| {
315            // Title with the month arrows at both ends.
316            let title = crate::t!("quvyta.date.title", month = month_name(cursor.month()), year = cursor.year());
317            let title_style = cx.style("calendar-title", None, &[]).text();
318            let title_width = text::width(&title);
319            let title_x = inner.x + i32::from(inner.width.saturating_sub(title_width) / 2);
320            cx.text(title_x, inner.y, &title, title_style, title_width);
321            for (glyph, x) in [("chevron-left", inner.x), ("chevron-right", inner.right() - i32::from(ARROW))] {
322                let area = Rect::new(x, inner.y, ARROW, 1);
323                let arrow = cx.env().icons().glyph(glyph).into_owned();
324                let hovered = pointer.is_some_and(|(px, py)| area.contains(px, py));
325                let states = if hovered { vec![State::Hover] } else { Vec::new() };
326                let arrow_style = cx.style("calendar-arrow", None, &states);
327                let pillar = arrow_style.color("pillar");
328                let arrow_style = arrow_style.text();
329                if let Some(bg) = arrow_style.bg {
330                    cx.fill(area, bg);
331                }
332                // The arrow's leftmost cell is blank padding around the glyph, so the pillar fits.
333                if let Some(color) = pillar {
334                    cx.pillar(x, inner.y, color);
335                }
336                cx.text(x + 1, inner.y, &arrow, CellStyle { bg: None, ..arrow_style }, text::width(&arrow));
337            }
338
339            let weekday_style = cx.style("calendar-weekday", None, &[]).text();
340            for column in 0..7u8 {
341                let weekday = Weekday::from_number((first.number() - 1 + column) % 7 + 1).unwrap_or(Weekday::Monday);
342                let name = crate::t!(&format!("quvyta.date.weekday-{}", weekday.number()));
343                let x = inner.x + i32::from(u16::from(column) * CELL) + 1;
344                cx.text(x, weekday_row, &name, weekday_style, CELL - 1);
345            }
346
347            let start = grid_start(cursor, first);
348            for index in 0..i64::from(WEEKS * 7) {
349                let date = start.add_days(index);
350                let cell = day_rect(index);
351                let mut states = Vec::new();
352                if date == highlighted {
353                    states.push(State::Hover);
354                    if keyboard_focus {
355                        states.push(State::Focus);
356                    }
357                }
358                if Some(date) == self.value {
359                    states.push(State::Selected);
360                }
361                let variant = if date.month() != cursor.month() {
362                    Some("outside")
363                } else if date == today {
364                    Some("today")
365                } else {
366                    None
367                };
368                let day_style = cx.style("calendar-day", variant, &states);
369                let pillar = day_style.color("pillar");
370                let day_style = day_style.text();
371                if let Some(bg) = day_style.bg {
372                    cx.fill(cell, bg);
373                }
374                // Every day cell keeps its first column blank for the pillar: the number never moves.
375                if let Some(color) = pillar {
376                    cx.pillar(cell.x, cell.y, color);
377                }
378                let label = format!("{:>2}", date.day());
379                cx.text(cell.x + 1, cell.y, &label, CellStyle { bg: None, ..day_style }, 2);
380            }
381        });
382    }
383
384    fn event(&self, cx: &mut EventCx<'_, Msg>, event: &Event) -> bool {
385        if self.disabled {
386            return false;
387        }
388        let open = cx.memory::<DatePickerMemory>().open;
389        match event {
390            Event::PointerOutside => {
391                Self::close(cx);
392                true
393            }
394            Event::Key(key) if !open => {
395                let opens = key.is_plain(Key::Enter) || key.is_plain(Key::Space) || key.is_plain(Key::Down);
396                if opens {
397                    self.open(cx);
398                }
399                opens
400            }
401            Event::Key(key) => self.key(cx, key),
402            Event::Mouse(mouse) => {
403                let popup = cx.memory::<DatePickerMemory>().popup;
404                let in_popup = open && popup.contains(mouse.x, mouse.y);
405                match mouse.kind {
406                    MouseKind::Down(MouseButton::Left) if in_popup => {
407                        self.click_calendar(cx, popup, mouse.x, mouse.y);
408                        true
409                    }
410                    MouseKind::Down(MouseButton::Left) => {
411                        if open {
412                            Self::close(cx);
413                        } else {
414                            self.open(cx);
415                        }
416                        true
417                    }
418                    MouseKind::ScrollUp | MouseKind::ScrollDown if in_popup => {
419                        let months = if mouse.kind == MouseKind::ScrollUp { -1 } else { 1 };
420                        let cursor = self.cursor(cx);
421                        cx.memory::<DatePickerMemory>().cursor = Some(cursor.add_months(months));
422                        true
423                    }
424                    _ => false,
425                }
426            }
427            Event::Paste(_) => false,
428        }
429    }
430
431    fn focusable(&self) -> bool {
432        !self.disabled
433    }
434}
435
436#[cfg(test)]
437mod tests {
438    use super::*;
439    use crate::runtime::{App, Command, Harness};
440    use crate::widget::{Length, View};
441
442    struct Demo {
443        date: Option<Date>,
444    }
445
446    impl App for Demo {
447        type Msg = Date;
448        fn update(&mut self, date: Date) -> Command<Date> {
449            self.date = Some(date);
450            Command::none()
451        }
452        fn view(&self, ui: &mut View<'_, Date>) {
453            let today = Date::new(2026, 9, 16).expect("valid");
454            ui.add(DatePicker::new(self.date).today(today).placeholder("Release date").on_change(|date| date))
455                .width(Length::Cells(24))
456                .id("date");
457        }
458    }
459
460    fn date(year: i32, month: u8, day: u8) -> Date {
461        Date::new(year, month, day).expect("valid")
462    }
463
464    #[test]
465    fn opens_a_calendar_with_weeks_from_the_locale() {
466        let mut h = Harness::new(Demo { date: Some(date(2026, 9, 3)) }, 40, 14);
467        h.set_reduced_motion(true);
468        assert!(h.screen().starts_with("  September 3, 2026"), "{}", h.screen());
469        h.press("tab").press("enter");
470        let screen = h.screen();
471        let lines: Vec<&str> = screen.lines().collect();
472        assert_eq!(lines[2], "   ◀     September 2026     ▶", "{screen}");
473        assert_eq!(lines[4], "   Su  Mo  Tu  We  Th  Fr  Sa");
474        // The highlighted day (the chosen 3rd) shows the pillar in its blank first column.
475        assert_eq!(lines[5], "   30  31   1   2 ▌ 3   4   5");
476        assert_eq!(lines[10], "    4   5   6   7   8   9  10");
477        let theme = h.env().theme();
478        // The chosen day is filled with the accent; days of other months are faint.
479        assert_eq!(h.bg(18, 5), theme.color("accent"));
480        assert_eq!(h.fg(20, 5), theme.color("ink"));
481        assert_eq!(h.fg(4, 5), theme.color("muted"));
482    }
483
484    #[test]
485    fn today_is_marked_and_turkish_weeks_start_on_monday_with_names() {
486        let mut h = Harness::new(Demo { date: None }, 40, 14);
487        h.set_reduced_motion(true).set_locale("tr").press("tab").press("enter");
488        let screen = h.screen();
489        assert!(screen.contains("Eylül 2026"), "{screen}");
490        assert!(screen.contains("Pt  Sa  Ça  Pe  Cu  Ct  Pz"), "{screen}");
491        let (x, y) = h.find("16").expect("today shown");
492        let theme = h.env().theme();
493        assert_eq!(h.fg(u16::try_from(x).unwrap_or(0), u16::try_from(y).unwrap_or(0)), theme.color("accent"));
494    }
495
496    #[test]
497    fn today_is_the_local_day_unless_given() {
498        // Read the local day on both sides, so a midnight passing in between cannot fail the test.
499        let before = Date::today_local();
500        let marked = DatePicker::<Date>::new(None).today_or_clock();
501        let after = Date::today_local();
502        assert!(marked == before || marked == after, "{marked} is not the local day {before}");
503        let given = date(2026, 9, 16);
504        assert_eq!(DatePicker::<Date>::new(None).today(given).today_or_clock(), given);
505    }
506
507    #[test]
508    fn english_weeks_start_on_sunday() {
509        let mut h = Harness::new(Demo { date: None }, 40, 14);
510        h.set_reduced_motion(true).press("tab").press("enter");
511        assert!(h.screen().contains("Su  Mo  Tu"), "{}", h.screen());
512    }
513
514    #[test]
515    fn keyboard_moves_by_day_week_month_and_week_ends() {
516        let mut h = Harness::new(Demo { date: Some(date(2026, 1, 31)) }, 40, 14);
517        h.set_reduced_motion(true).press("tab").press("enter");
518        h.press("pgdn").press("enter");
519        assert_eq!(h.app().date, Some(date(2026, 2, 28)));
520        h.press("enter").press("right").press("down").press("enter");
521        assert_eq!(h.app().date, Some(date(2026, 3, 8)));
522        h.press("enter").press("right").press("right").press("home").press("enter");
523        assert_eq!(h.app().date, Some(date(2026, 3, 8)), "English weeks start on Sunday");
524        h.press("enter").press("end").press("left").press("up").press("enter");
525        assert_eq!(h.app().date, Some(date(2026, 3, 6)));
526        h.press("enter").press("shift+pgup").press("enter");
527        assert_eq!(h.app().date, Some(date(2025, 3, 6)));
528        h.press("enter").press("esc");
529        assert!(!h.screen().contains("Mo  Tu"));
530    }
531
532    #[test]
533    fn clicks_choose_days_and_arrows_change_the_month() {
534        let mut h = Harness::new(Demo { date: Some(date(2026, 9, 3)) }, 40, 14);
535        h.set_reduced_motion(true);
536        h.click(3, 0);
537        let (x, y) = h.find("▶").expect("next month arrow");
538        h.click(x, y);
539        assert!(h.screen().contains("October 2026"), "{}", h.screen());
540        h.click_text("15");
541        assert_eq!(h.app().date, Some(date(2026, 10, 15)));
542        assert!(h.screen().contains("October 15, 2026"), "{}", h.screen());
543    }
544
545    #[test]
546    fn unfolds_over_motion_enter() {
547        let mut h = Harness::new(Demo { date: None }, 40, 14);
548        h.press("tab").press("enter");
549        assert!(!h.screen().contains("Mo"));
550        h.advance(Duration::from_millis(300));
551        assert!(h.screen().contains("Mo"));
552    }
553
554    // One highlight, and the mouse does what the keys do.
555
556    /// Days whose cell carries the highlight surface.
557    fn lit_days(h: &Harness<Demo>) -> Vec<String> {
558        let active = h.env().theme().color("active");
559        let screen = h.screen();
560        let mut days = Vec::new();
561        for (y, line) in screen.lines().enumerate().skip(5) {
562            // Day cells are four wide from the calendar's inner edge, two cells in.
563            for (column, day) in line.chars().skip(2).collect::<Vec<_>>().chunks(4).enumerate() {
564                let x = u16::try_from(column * 4 + 3).unwrap_or(0);
565                if u16::try_from(y).is_ok_and(|y| h.bg(x, y) == active) {
566                    days.push(day.iter().filter(|c| **c != '▌').collect::<String>().trim().to_owned());
567                }
568            }
569        }
570        days
571    }
572
573    #[test]
574    fn the_pointer_moves_the_one_highlighted_day() {
575        let mut h = Harness::new(Demo { date: None }, 40, 14);
576        h.set_reduced_motion(true).press("tab").press("enter");
577        assert_eq!(lit_days(&h), ["16"], "today has the keyboard highlight:\n{}", h.screen());
578        let (x, y) = h.find("22").expect("a day");
579        h.hover(x, y);
580        assert_eq!(lit_days(&h), ["22"], "only the hovered day is lit:\n{}", h.screen());
581        h.press("right");
582        assert_eq!(lit_days(&h), ["23"], "the keyboard goes on from it and the resting pointer waits");
583        h.press("enter");
584        assert_eq!(h.app().date, Some(date(2026, 9, 23)));
585    }
586
587    #[test]
588    fn a_neighbouring_months_day_under_the_pointer_is_lit_without_turning_the_month() {
589        let mut h = Harness::new(Demo { date: Some(date(2026, 9, 3)) }, 40, 14);
590        h.set_reduced_motion(true).press("tab").press("enter");
591        let (x, y) = h.find("30").expect("August 30");
592        h.hover(x, y);
593        assert!(h.screen().contains("September 2026"), "{}", h.screen());
594        assert_eq!(lit_days(&h), ["30"], "{}", h.screen());
595        h.press("right");
596        assert_eq!(lit_days(&h), ["4"], "keys continue from the September day");
597    }
598
599    #[test]
600    fn month_arrows_are_three_cell_buttons_and_the_wheel_turns_the_month() {
601        let mut h = Harness::new(Demo { date: Some(date(2026, 9, 3)) }, 40, 14);
602        h.set_reduced_motion(true).press("tab").press("enter");
603        let (x, y) = h.find("▶").expect("next month arrow");
604        let (column, row) = (u16::try_from(x).expect("x"), u16::try_from(y).expect("y"));
605        let resting = h.bg(column, row);
606        h.hover(x + 1, y);
607        let lit = h.env().theme().color("active");
608        assert_ne!(resting, lit);
609        assert_eq!([h.bg(column - 1, row), h.bg(column, row), h.bg(column + 1, row)], [lit, lit, lit]);
610        h.click(x - 1, y);
611        assert!(h.screen().contains("October 2026"), "{}", h.screen());
612        let (x, y) = h.find("◀").expect("previous month arrow");
613        h.click(x + 1, y);
614        assert!(h.screen().contains("September 2026"), "{}", h.screen());
615        let (x, y) = h.find("15").expect("a day");
616        h.mouse(MouseKind::ScrollDown, x, y);
617        assert!(h.screen().contains("October 2026"), "{}", h.screen());
618        h.mouse(MouseKind::ScrollUp, x, y).mouse(MouseKind::ScrollUp, x, y);
619        assert!(h.screen().contains("August 2026"), "{}", h.screen());
620        h.set_glyph_mode(crate::icons::GlyphMode::Ascii);
621        assert!(!h.screen().contains('▶'), "{}", h.screen());
622    }
623
624    // Every hovered part shows the pillar in its leftmost cell and nothing slides, whether the
625    // slide setting is on or off.
626
627    /// A harness with the slide setting forced `on` or off, reduced motion so layers open at once.
628    fn harness(value: Option<Date>, slide: bool, width: u16) -> Harness<Demo> {
629        let mut env = crate::env::Env::builtin();
630        env.set_slide(slide);
631        let mut h = Harness::with_env(Demo { date: value }, env, width, 14);
632        h.set_reduced_motion(true);
633        h
634    }
635
636    /// The pillar colour a calendar style gives in `states` at pulse phase zero.
637    fn pillar_of(h: &Harness<Demo>, widget: &str, states: &[State]) -> Option<crate::color::Rgb> {
638        crate::style::WidgetStyle::new(h.env().theme().style(widget, None, states), 0.0).color("pillar")
639    }
640
641    fn cell(x: i32, y: i32) -> (u16, u16) {
642        (u16::try_from(x).expect("x"), u16::try_from(y).expect("y"))
643    }
644
645    /// The open calendar of September 2026 as the tests below see it, with `pillars` drawn over
646    /// the resting screen at `(column, row)`.
647    fn calendar_with(pillars: &[(usize, usize)]) -> String {
648        let mut lines: Vec<Vec<char>> = [
649            "▌ September 3, 2026  ▾",
650            "",
651            "   ◀     September 2026     ▶",
652            "",
653            "   Su  Mo  Tu  We  Th  Fr  Sa",
654            "   30  31   1   2   3   4   5",
655            "    6   7   8   9  10  11  12",
656            "   13  14  15  16  17  18  19",
657            "   20  21  22  23  24  25  26",
658            "   27  28  29  30   1   2   3",
659            "    4   5   6   7   8   9  10",
660            "",
661            "",
662            "",
663        ]
664        .iter()
665        .map(|line| line.chars().collect())
666        .collect();
667        for &(column, row) in pillars {
668            let line = &mut lines[row];
669            assert_eq!(line.get(column), Some(&' '), "a pillar only takes a blank cell");
670            line[column] = '▌';
671        }
672        lines.iter().map(|line| line.iter().collect::<String>()).collect::<Vec<_>>().join("\n") + "\n"
673    }
674
675    #[test]
676    fn a_hovered_day_shows_the_pillar_in_its_blank_first_column_and_never_slides() {
677        for slide in [false, true] {
678            let mut h = harness(Some(date(2026, 9, 3)), slide, 40);
679            h.click(3, 0);
680            // Opened with a click: the chosen day carries the one highlight and its calm pillar.
681            assert_eq!(h.screen(), calendar_with(&[(18, 5)]), "slide {slide}");
682            let (x, y) = h.find("22").expect("a day");
683            h.hover(x + 1, y);
684            // The pillar moves to the hovered day's first column; every number stays in place.
685            assert_eq!(h.screen(), calendar_with(&[(10, 8)]), "slide {slide}");
686            let soft = pillar_of(&h, "calendar-day", &[State::Hover]);
687            assert!(soft.is_some());
688            assert_eq!(h.fg(10, 8), soft, "a pointer highlight has the soft pillar");
689            assert_eq!(h.bg(10, 8), h.bg(11, 8), "the pillar sits on the day's lit surface");
690            // Hovering the chosen day keeps its accent fill and adds an ink pillar.
691            h.hover(20, 5);
692            assert_eq!(h.screen(), calendar_with(&[(18, 5)]), "slide {slide}");
693            assert_eq!(h.bg(19, 5), h.env().theme().color("accent"));
694            assert_eq!(h.fg(18, 5), pillar_of(&h, "calendar-day", &[State::Hover, State::Selected]));
695        }
696    }
697
698    #[test]
699    fn a_hovered_month_arrow_shows_the_pillar_in_its_first_cell() {
700        for slide in [false, true] {
701            let mut h = harness(Some(date(2026, 9, 3)), slide, 40);
702            h.click(3, 0);
703            let (x, y) = h.find("◀").expect("previous month arrow");
704            h.hover(x, y);
705            assert_eq!(h.screen(), calendar_with(&[(2, 2), (18, 5)]), "slide {slide}");
706            let soft = pillar_of(&h, "calendar-arrow", &[State::Hover]);
707            assert!(soft.is_some());
708            assert_eq!(h.fg(2, 2), soft);
709            let (x, y) = h.find("▶").expect("next month arrow");
710            h.hover(x + 1, y);
711            assert_eq!(h.screen(), calendar_with(&[(27, 2), (18, 5)]), "slide {slide}");
712            assert_eq!(h.fg(27, 2), soft);
713        }
714    }
715
716    #[test]
717    fn a_hovered_field_shows_the_pillar_and_its_label_stays() {
718        for slide in [false, true] {
719            let mut h = harness(Some(date(2026, 9, 3)), slide, 40);
720            assert_eq!(h.screen().lines().next(), Some("  September 3, 2026  ▾"), "slide {slide}");
721            h.hover(10, 0);
722            assert_eq!(h.screen().lines().next(), Some("▌ September 3, 2026  ▾"), "slide {slide}");
723        }
724    }
725
726    #[test]
727    fn only_a_highlight_the_keyboard_moved_breathes() {
728        let mut h = harness(Some(date(2026, 9, 3)), true, 40);
729        h.press("tab").press("enter").press("right");
730        assert_eq!(h.screen(), calendar_with(&[(22, 5)]));
731        let breathing = pillar_of(&h, "calendar-day", &[State::Hover, State::Focus]);
732        let soft = pillar_of(&h, "calendar-day", &[State::Hover]);
733        assert_ne!(breathing, soft);
734        assert_eq!(h.fg(22, 5), breathing, "keyboard focus breathes");
735        let breathes = h.env().theme().style("calendar-day", None, &[State::Hover, State::Focus]);
736        assert!(crate::style::WidgetStyle::new(breathes, 0.0).is_animated());
737        // The pointer takes the highlight over: its day stays calm although focus came from keys.
738        let (x, y) = h.find("22").expect("a day");
739        h.hover(x, y);
740        assert_eq!(h.screen(), calendar_with(&[(10, 8)]));
741        assert_eq!(h.fg(10, 8), soft);
742        h.press("left");
743        assert_eq!(h.screen(), calendar_with(&[(6, 8)]));
744        assert_eq!(h.fg(6, 8), breathing);
745    }
746
747    #[test]
748    fn narrow_screens_keep_the_pillar_in_the_first_column() {
749        let mut h = harness(Some(date(2026, 9, 3)), true, 26);
750        h.click(3, 0);
751        let (x, y) = h.find("22").expect("a day");
752        h.hover(x, y);
753        let screen = h.screen();
754        let lines: Vec<&str> = screen.lines().collect();
755        assert_eq!(lines[0], "▌ September 3, 2026  ▾", "{screen}");
756        assert_eq!(lines[7], "   13  14  15  16  17  18", "{screen}");
757        assert_eq!(lines[8], "   20  21 ▌22  23  24  25", "{screen}");
758        let (x, y) = h.find("◀").expect("previous month arrow");
759        h.hover(x, y);
760        assert_eq!(h.screen().lines().nth(2), Some("  ▌◀  September 2026  ▶"), "{}", h.screen());
761    }
762
763    #[test]
764    fn ascii_mode_draws_the_pillar_as_a_filled_cell() {
765        let mut h = harness(Some(date(2026, 9, 3)), false, 40);
766        h.set_glyph_mode(crate::icons::GlyphMode::Ascii).click(3, 0);
767        let (x, y) = h.find("22").expect("a day");
768        h.hover(x, y);
769        let (column, row) = cell(x - 1, y);
770        assert_eq!(h.bg(column, row), pillar_of(&h, "calendar-day", &[State::Hover]));
771        assert_eq!(h.screen().lines().nth(8), Some("   20  21  22  23  24  25  26"), "{}", h.screen());
772    }
773}