Skip to main content

iced_cube/data/calendar/
state.rs

1//! What the calendar shows and what is selected in it.
2
3use iced::keyboard::key::Named;
4use jiff::civil::{Date, Weekday};
5use jiff::tz::TimeZone;
6use jiff::{SignedDuration, Timestamp, ToSpan};
7
8use super::entry::{Changed, Draft, Entries, Entry, EntryId, When, add_days};
9use super::layout::{self, DAY_MINUTES, instant_at};
10use crate::keys::{self, Chord, Keymap};
11
12/// How long an entry asked for by pressing a time slot is.
13pub const SLOT_MINUTES: u16 = 60;
14
15/// How many days [`View::FourDays`] shows.
16pub const FOUR_DAYS: i32 = 4;
17
18/// How the entries are laid out.
19#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
20pub enum View {
21    /// One day against the hours.
22    Day,
23    /// Seven days side by side against the hours.
24    Week,
25    /// A grid of weeks with entries across the days.
26    #[default]
27    Month,
28    /// The twelve months of a year, small.
29    Year,
30    /// The month's entries as a list, day by day.
31    Agenda,
32    /// Four days against the hours, starting on the day on show.
33    FourDays,
34}
35
36impl View {
37    /// Every view, in the order the header's menu lists them.
38    pub const ALL: [View; 6] = [
39        View::Day,
40        View::Week,
41        View::Month,
42        View::Year,
43        View::Agenda,
44        View::FourDays,
45    ];
46
47    pub fn label(self) -> &'static str {
48        match self {
49            View::Day => "Day",
50            View::Week => "Week",
51            View::Month => "Month",
52            View::Year => "Year",
53            View::Agenda => "Schedule",
54            View::FourDays => "4 days",
55        }
56    }
57}
58
59impl std::fmt::Display for View {
60    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
61        f.write_str(self.label())
62    }
63}
64
65/// What the user may change through the calendar's own gestures and
66/// shortcuts. Everything is allowed by default.
67///
68/// This only limits what the calendar offers. [`Event::Insert`] and
69/// [`Event::Remove`] always apply, so the app, or controls of its own, can
70/// still add, change and remove entries on a calendar that is read-only
71/// to the pointer and the keyboard.
72#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
73pub struct Allow {
74    /// Asking for a new entry: a second press on a day or a time, a drag
75    /// across empty space, or [`Action::Activate`] on a day.
76    pub create: bool,
77    /// Dragging an entry to move it or to change when it ends.
78    pub reschedule: bool,
79    /// Removing the selected entry with [`Action::Remove`].
80    pub remove: bool,
81}
82
83impl Allow {
84    /// Everything: the default.
85    pub const ALL: Allow = Allow {
86        create: true,
87        reschedule: true,
88        remove: true,
89    };
90
91    /// Nothing: a read-only calendar. Days and entries can still be
92    /// selected, entries opened and the period and view changed.
93    pub const NONE: Allow = Allow {
94        create: false,
95        reschedule: false,
96        remove: false,
97    };
98}
99
100impl Default for Allow {
101    fn default() -> Self {
102        Self::ALL
103    }
104}
105
106/// What is selected: at most one thing at a time.
107#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
108pub enum Selection {
109    Day(Date),
110    /// A time on a day in the week and day views, in minutes from
111    /// midnight.
112    Slot {
113        date: Date,
114        minute: u16,
115    },
116    /// One occurrence of an entry, told apart by when it starts.
117    Entry {
118        entry: EntryId,
119        start: Timestamp,
120    },
121}
122
123/// Everything that changes the calendar.
124#[derive(Debug, Clone, PartialEq, Eq)]
125pub enum Event {
126    Show(View),
127    /// Moves on by a month, a week or a day, whichever the view shows.
128    Next,
129    Previous,
130    /// Goes to today and selects it.
131    Today,
132    /// Shows the period holding this date, without selecting anything.
133    GoTo(Date),
134    /// A press on a day, a time slot or an entry. The first press selects
135    /// it; a press on what is already selected activates it, as
136    /// [`Event::Activate`] does.
137    Press(Selection),
138    /// Activates the selection: an entry is opened, and a day or a time
139    /// slot asks for a new entry there. With nothing selected it asks for
140    /// one on the day on show.
141    Activate,
142    /// Clears the selection.
143    Clear,
144    /// Moves the selected day by this many days and follows it when it
145    /// leaves the period on show.
146    MoveDay(i32),
147    /// Selects the next entry on the selected day, wrapping.
148    NextEntry,
149    PreviousEntry,
150    /// Shows one day, as the "more" count of a crowded day does.
151    OpenDay(Date),
152    /// A span dragged out on empty space.
153    Request(Draft),
154    /// An occurrence dragged to a new time. `start` says which occurrence;
155    /// a repeating entry moves as a whole by the same amount.
156    Reschedule {
157        entry: EntryId,
158        start: Timestamp,
159        to: (Timestamp, Timestamp),
160    },
161    /// Adds an entry, or replaces the one with the same id.
162    Insert(Entry),
163    Remove(EntryId),
164    /// The current time, for "today" and the now line.
165    Tick(Timestamp),
166}
167
168/// What the app may want to act on after an [`Event`].
169#[derive(Debug, Clone, PartialEq, Eq)]
170pub enum Output {
171    Selected(Option<Selection>),
172    /// An entry was activated: show or edit it.
173    Opened {
174        entry: EntryId,
175        start: Timestamp,
176    },
177    /// The user asked for a new entry here. Nothing is added until the app
178    /// sends [`Event::Insert`].
179    Requested(Draft),
180    /// An entry was created, updated or removed. Pass it to
181    /// [`Scheduler::observe`](super::schedule::Scheduler::observe) for
182    /// triggers on changes.
183    Changed(Box<Changed>),
184    /// A different period or view is on show, such as after
185    /// [`Event::Next`]. Useful for loading the entries of that period.
186    Viewed {
187        view: View,
188        first: Date,
189        last: Date,
190    },
191}
192
193/// The entries, the view, the period on show and the selection.
194#[derive(Debug, Clone, PartialEq)]
195pub struct State {
196    entries: Entries,
197    view: View,
198    /// A date in the period on show.
199    cursor: Date,
200    today: Date,
201    now: Option<Timestamp>,
202    selection: Option<Selection>,
203    week_start: Weekday,
204    allow: Allow,
205}
206
207impl State {
208    /// An empty calendar in UTC showing the month of `today`.
209    ///
210    /// The calendar never reads the clock. Pass today's date here, and
211    /// keep it current with [`Event::Tick`] if the app stays open.
212    pub fn new(today: Date) -> Self {
213        Self {
214            entries: Entries::utc(),
215            view: View::default(),
216            cursor: today,
217            today,
218            now: None,
219            selection: None,
220            week_start: Weekday::Monday,
221            allow: Allow::ALL,
222        }
223    }
224
225    /// A calendar showing the month of `now` in the time zone of
226    /// `entries`, with the now line drawn.
227    pub fn at(now: Timestamp, entries: Entries) -> Self {
228        let mut state = Self::new(entries.date_of(now)).with_entries(entries);
229        state.now = Some(now);
230        state
231    }
232
233    /// Replaces the entries and their time zone.
234    pub fn with_entries(mut self, entries: Entries) -> Self {
235        self.entries = entries;
236        self
237    }
238
239    pub fn with_view(mut self, view: View) -> Self {
240        self.set_view(view);
241        self
242    }
243
244    /// The day weeks start on. Defaults to Monday.
245    pub fn with_week_start(mut self, week_start: Weekday) -> Self {
246        self.week_start = week_start;
247        self
248    }
249
250    /// Shows the period holding `date`.
251    pub fn with_cursor(mut self, date: Date) -> Self {
252        self.cursor = date;
253        self
254    }
255
256    pub fn with_selection(mut self, selection: Selection) -> Self {
257        self.selection = Some(selection);
258        self
259    }
260
261    /// Limits what the user may change through the calendar itself.
262    pub fn with_allow(mut self, allow: Allow) -> Self {
263        self.allow = allow;
264        self
265    }
266
267    /// A calendar the user can look through but not change: nothing can
268    /// be created, dragged or removed from it. The same as
269    /// [`with_allow`](State::with_allow) with [`Allow::NONE`].
270    pub fn read_only(self) -> Self {
271        self.with_allow(Allow::NONE)
272    }
273
274    /// Changes what the user may do, such as when they sign in or a
275    /// calendar they cannot edit comes on show.
276    pub fn set_allow(&mut self, allow: Allow) {
277        self.allow = allow;
278    }
279
280    pub fn allow(&self) -> Allow {
281        self.allow
282    }
283
284    pub fn entries(&self) -> &Entries {
285        &self.entries
286    }
287
288    pub fn time_zone(&self) -> &TimeZone {
289        self.entries.time_zone()
290    }
291
292    pub fn view(&self) -> View {
293        self.view
294    }
295
296    /// A date in the period on show.
297    pub fn cursor(&self) -> Date {
298        self.cursor
299    }
300
301    pub fn today(&self) -> Date {
302        self.today
303    }
304
305    /// The time of the last [`Event::Tick`], which is where the now line
306    /// is drawn.
307    pub fn now(&self) -> Option<Timestamp> {
308        self.now
309    }
310
311    pub fn week_start(&self) -> Weekday {
312        self.week_start
313    }
314
315    pub fn selection(&self) -> Option<Selection> {
316        self.selection
317    }
318
319    /// The selected entry, if an entry is selected.
320    pub fn selected_entry(&self) -> Option<&Entry> {
321        match self.selection? {
322            Selection::Entry { entry, .. } => self.entries.get(entry),
323            _ => None,
324        }
325    }
326
327    /// The day the selection is on, if anything is selected.
328    pub fn selected_day(&self) -> Option<Date> {
329        Some(match self.selection? {
330            Selection::Day(date) | Selection::Slot { date, .. } => date,
331            Selection::Entry { start, .. } => self.entries.date_of(start),
332        })
333    }
334
335    pub fn is_selected(&self, selection: Selection) -> bool {
336        self.selection == Some(selection)
337    }
338
339    /// The first and last date on show. The month view includes the days
340    /// of neighbouring months that fill its first and last weeks.
341    pub fn range(&self) -> (Date, Date) {
342        match self.view {
343            View::Month => {
344                let weeks = layout::month_weeks(self.cursor, self.week_start);
345                let first = weeks.first().map_or(self.cursor, |week| week[0]);
346                let last = weeks.last().map_or(self.cursor, |week| week[6]);
347                (first, last)
348            }
349            View::Week => {
350                let week = layout::week_of(self.cursor, self.week_start);
351                (week[0], week[6])
352            }
353            View::Day => (self.cursor, self.cursor),
354            View::FourDays => (self.cursor, add_days(self.cursor, FOUR_DAYS - 1)),
355            View::Year => (self.cursor.first_of_year(), self.cursor.last_of_year()),
356            View::Agenda => (self.cursor.first_of_month(), self.cursor.last_of_month()),
357        }
358    }
359
360    /// The period on show in words, such as "November 2026".
361    pub fn title(&self) -> String {
362        let format = |date: Date, format: &str| date.strftime(format).to_string();
363        match self.view {
364            View::Month | View::Agenda => format(self.cursor, "%B %Y"),
365            View::Year => format(self.cursor, "%Y"),
366            View::Day => format(self.cursor, "%A %-d %B %Y"),
367            View::Week | View::FourDays => {
368                let (first, last) = self.range();
369                let start = if first.year() != last.year() {
370                    "%-d %b %Y"
371                } else if first.month() != last.month() {
372                    "%-d %b"
373                } else {
374                    "%-d"
375                };
376                format!("{} - {}", format(first, start), format(last, "%-d %b %Y"))
377            }
378        }
379    }
380
381    /// A shorter [`title`](State::title) for narrow screens, such as
382    /// "Thu 19 Nov 2026" for a day and "30 Nov - 6 Dec" for a week that
383    /// crosses months.
384    pub fn short_title(&self) -> String {
385        let format = |date: Date, format: &str| date.strftime(format).to_string();
386        match self.view {
387            View::Month | View::Agenda | View::Year => self.title(),
388            View::Day => format(self.cursor, "%a %-d %b %Y"),
389            View::Week | View::FourDays => {
390                let (first, last) = self.range();
391                if (first.year(), first.month()) == (last.year(), last.month()) {
392                    return self.title();
393                }
394                format!("{} - {}", format(first, "%-d %b"), format(last, "%-d %b"))
395            }
396        }
397    }
398
399    /// Applies an event and returns what the app may want to act on.
400    pub fn update(&mut self, event: Event) -> Option<Output> {
401        match event {
402            Event::Show(view) => {
403                if view == self.view {
404                    return None;
405                }
406                if let Some(day) = self.selected_day() {
407                    self.cursor = day;
408                }
409                self.set_view(view);
410                Some(self.viewed())
411            }
412            Event::Next => self.step(1),
413            Event::Previous => self.step(-1),
414            Event::Today => {
415                let before = (self.range(), self.selection);
416                self.cursor = self.today;
417                self.selection = Some(Selection::Day(self.today));
418                if before.0 != self.range() {
419                    return Some(self.viewed());
420                }
421                (before.1 != self.selection).then_some(Output::Selected(self.selection))
422            }
423            Event::GoTo(date) => self.show(date),
424            Event::Press(selection) => {
425                if self.selection == Some(selection) {
426                    return self.activate();
427                }
428                self.selection = Some(selection);
429                Some(Output::Selected(self.selection))
430            }
431            Event::Activate => self.activate(),
432            Event::Clear => {
433                self.selection.take()?;
434                Some(Output::Selected(None))
435            }
436            Event::MoveDay(days) => {
437                let from = self.selected_day().unwrap_or(self.cursor);
438                let date = add_days(from, days);
439                self.selection = Some(Selection::Day(date));
440                let (first, last) = self.range();
441                // The month view also shows days of its neighbours, and
442                // moving onto one of those turns the page.
443                let leaves_the_month = self.view == View::Month
444                    && (date.year(), date.month()) != (self.cursor.year(), self.cursor.month());
445                if date < first || date > last || leaves_the_month {
446                    self.cursor = date;
447                    return Some(self.viewed());
448                }
449                Some(Output::Selected(self.selection))
450            }
451            Event::NextEntry => self.cycle(1),
452            Event::PreviousEntry => self.cycle(-1),
453            Event::OpenDay(date) => {
454                if self.view == View::Day && self.cursor == date {
455                    return None;
456                }
457                self.cursor = date;
458                self.set_view(View::Day);
459                Some(self.viewed())
460            }
461            Event::Request(draft) => self.allow.create.then_some(Output::Requested(draft)),
462            Event::Reschedule { entry, start, to } => {
463                if !self.allow.reschedule {
464                    return None;
465                }
466                let moved = self.rescheduled(entry, start, to)?;
467                let changed = self.entries.insert(moved)?;
468                if let Some(Selection::Entry {
469                    entry: selected, ..
470                }) = self.selection
471                    && selected == entry
472                {
473                    self.selection = Some(Selection::Entry {
474                        entry,
475                        start: to.0.min(to.1),
476                    });
477                }
478                Some(report(changed))
479            }
480            Event::Insert(entry) => self.entries.insert(entry).map(report),
481            Event::Remove(id) => {
482                let changed = self.entries.remove(id)?;
483                if matches!(self.selection, Some(Selection::Entry { entry, .. }) if entry == id) {
484                    self.selection = None;
485                }
486                Some(report(changed))
487            }
488            Event::Tick(now) => {
489                self.now = Some(now);
490                self.today = self.entries.date_of(now);
491                None
492            }
493        }
494    }
495
496    fn set_view(&mut self, view: View) {
497        self.view = view;
498    }
499
500    fn viewed(&self) -> Output {
501        let (first, last) = self.range();
502        Output::Viewed {
503            view: self.view,
504            first,
505            last,
506        }
507    }
508
509    fn show(&mut self, date: Date) -> Option<Output> {
510        let before = self.range();
511        self.cursor = date;
512        (before != self.range()).then(|| self.viewed())
513    }
514
515    fn step(&mut self, direction: i32) -> Option<Output> {
516        let months = |count: i32| {
517            self.cursor
518                .checked_add(i64::from(count).months())
519                .unwrap_or(self.cursor)
520        };
521        let target = match self.view {
522            View::Month | View::Agenda => months(direction),
523            View::Year => months(12 * direction),
524            View::Week => add_days(self.cursor, 7 * direction),
525            View::FourDays => add_days(self.cursor, FOUR_DAYS * direction),
526            View::Day => add_days(self.cursor, direction),
527        };
528        self.show(target)
529    }
530
531    fn activate(&mut self) -> Option<Output> {
532        let time_zone = self.entries.time_zone();
533        if let Some(Selection::Entry { entry, start }) = self.selection {
534            self.entries.get(entry)?;
535            return Some(Output::Opened { entry, start });
536        }
537        if !self.allow.create {
538            return None;
539        }
540        Some(match self.selection {
541            Some(Selection::Entry { entry, start }) => Output::Opened { entry, start },
542            Some(Selection::Slot { date, minute }) => {
543                let end = minute.saturating_add(SLOT_MINUTES).min(DAY_MINUTES);
544                Output::Requested(Draft {
545                    when: When::timed(
546                        instant_at(date, minute, time_zone),
547                        instant_at(date, end, time_zone),
548                    ),
549                })
550            }
551            Some(Selection::Day(date)) => Output::Requested(Draft {
552                when: When::day(date),
553            }),
554            None => Output::Requested(Draft {
555                when: When::day(self.cursor),
556            }),
557        })
558    }
559
560    /// Moves the selection through the entries of the selected day, or in
561    /// the schedule through every entry it lists.
562    fn cycle(&mut self, direction: i32) -> Option<Output> {
563        let occurrences = if self.view == View::Agenda {
564            let (first, last) = self.range();
565            self.entries.between(first, last)
566        } else {
567            let day = self.selected_day().unwrap_or(self.cursor);
568            self.entries.on(day)
569        };
570        let count = i32::try_from(occurrences.len()).ok().filter(|n| *n > 0)?;
571        let current = occurrences.iter().position(|occurrence| {
572            self.is_selected(Selection::Entry {
573                entry: occurrence.entry,
574                start: occurrence.start,
575            })
576        });
577        let next = match current {
578            Some(index) => (i32::try_from(index).ok()? + direction).rem_euclid(count),
579            None if direction < 0 => count - 1,
580            None => 0,
581        };
582        let occurrence = occurrences.get(usize::try_from(next).ok()?)?;
583        let selection = Selection::Entry {
584            entry: occurrence.entry,
585            start: occurrence.start,
586        };
587        if self.selection == Some(selection) {
588            return None;
589        }
590        self.selection = Some(selection);
591        Some(Output::Selected(self.selection))
592    }
593
594    /// `entry` with the occurrence starting at `start` moved to `to`.
595    fn rescheduled(
596        &self,
597        entry: EntryId,
598        start: Timestamp,
599        to: (Timestamp, Timestamp),
600    ) -> Option<Entry> {
601        let entry = self.entries.get(entry)?;
602        let When::Timed {
603            start: first_start, ..
604        } = entry.when()
605        else {
606            return None;
607        };
608        let (new_start, new_end) = (to.0.min(to.1), to.0.max(to.1));
609        let shift: SignedDuration = new_start.duration_since(start);
610        let first = first_start.checked_add(shift).ok()?;
611        let end = first.checked_add(new_end.duration_since(new_start)).ok()?;
612        Some(entry.clone().rescheduled(When::timed(first, end)))
613    }
614}
615
616fn report(changed: Changed) -> Output {
617    Output::Changed(Box::new(changed))
618}
619
620/// What a calendar keyboard shortcut does.
621#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
622pub enum Action {
623    Next,
624    Previous,
625    Today,
626    PreviousDay,
627    NextDay,
628    PreviousWeek,
629    NextWeek,
630    PreviousEntry,
631    NextEntry,
632    Month,
633    Week,
634    Day,
635    Agenda,
636    Year,
637    FourDays,
638    Activate,
639    Remove,
640    Close,
641}
642
643impl Action {
644    /// The [`Event`] this action sends to `state`, or `None` when it would
645    /// do nothing: removing with no entry selected, closing with nothing
646    /// selected, or switching to the view already on show.
647    pub fn event(self, state: &State) -> Option<Event> {
648        let show = |view: View| (state.view() != view).then_some(Event::Show(view));
649        match self {
650            Action::Next => Some(Event::Next),
651            Action::Previous => Some(Event::Previous),
652            Action::Today => Some(Event::Today),
653            // The schedule lists entries, not days, so there the arrows
654            // step through the entries.
655            Action::PreviousDay | Action::PreviousWeek if state.view() == View::Agenda => {
656                Some(Event::PreviousEntry)
657            }
658            Action::NextDay | Action::NextWeek if state.view() == View::Agenda => {
659                Some(Event::NextEntry)
660            }
661            Action::PreviousDay => Some(Event::MoveDay(-1)),
662            Action::NextDay => Some(Event::MoveDay(1)),
663            Action::PreviousWeek => Some(Event::MoveDay(-7)),
664            Action::NextWeek => Some(Event::MoveDay(7)),
665            Action::PreviousEntry => Some(Event::PreviousEntry),
666            Action::NextEntry => Some(Event::NextEntry),
667            Action::Month => show(View::Month),
668            Action::Week => show(View::Week),
669            Action::Day => show(View::Day),
670            Action::Agenda => show(View::Agenda),
671            Action::Year => show(View::Year),
672            Action::FourDays => show(View::FourDays),
673            Action::Activate => (state.selected_entry().is_some() || state.allow().create)
674                .then_some(Event::Activate),
675            Action::Remove => state
676                .selected_entry()
677                .filter(|_| state.allow().remove)
678                .map(|entry| Event::Remove(entry.id())),
679            Action::Close => state.selection().map(|_| Event::Clear),
680        }
681    }
682}
683
684impl keys::Action for Action {
685    const ALL: &'static [Self] = &[
686        Action::Previous,
687        Action::Next,
688        Action::Today,
689        Action::PreviousDay,
690        Action::NextDay,
691        Action::PreviousWeek,
692        Action::NextWeek,
693        Action::PreviousEntry,
694        Action::NextEntry,
695        Action::Month,
696        Action::Week,
697        Action::Day,
698        Action::Agenda,
699        Action::Year,
700        Action::FourDays,
701        Action::Activate,
702        Action::Remove,
703        Action::Close,
704    ];
705
706    fn defaults() -> Keymap<Self> {
707        default_keymap()
708    }
709
710    fn name(self) -> &'static str {
711        match self {
712            Action::Next => "Next",
713            Action::Previous => "Previous",
714            Action::Today => "Today",
715            Action::PreviousDay => "Previous day",
716            Action::NextDay => "Next day",
717            Action::PreviousWeek => "Previous week",
718            Action::NextWeek => "Next week",
719            Action::PreviousEntry => "Previous entry",
720            Action::NextEntry => "Next entry",
721            Action::Month => "Month",
722            Action::Week => "Week",
723            Action::Day => "Day",
724            Action::Agenda => "Schedule",
725            Action::Year => "Year",
726            Action::FourDays => "4 days",
727            Action::Activate => "Activate",
728            Action::Remove => "Remove",
729            Action::Close => "Close",
730        }
731    }
732
733    fn description(self) -> &'static str {
734        match self {
735            Action::Next => "Shows the next period: a day, a week, four days, a month or a year.",
736            Action::Previous => "Shows the previous period.",
737            Action::Today => "Goes to today and selects it.",
738            Action::PreviousDay => "Selects the day before.",
739            Action::NextDay => "Selects the day after.",
740            Action::PreviousWeek => "Selects the same day a week earlier.",
741            Action::NextWeek => "Selects the same day a week later.",
742            Action::PreviousEntry => "Selects the previous entry on the selected day.",
743            Action::NextEntry => "Selects the next entry on the selected day.",
744            Action::Month => "Switches to the month view.",
745            Action::Week => "Switches to the week view.",
746            Action::Day => "Switches to the day view.",
747            Action::Agenda => "Switches to the schedule, a list of the month's entries.",
748            Action::Year => "Switches to the year view.",
749            Action::FourDays => "Switches to the four day view.",
750            Action::Activate => {
751                "Opens the selected entry, or asks for a new one on the selected day."
752            }
753            Action::Remove => "Removes the selected entry.",
754            Action::Close => "Clears the selection.",
755        }
756    }
757}
758
759/// The default calendar shortcuts:
760///
761/// | Keys | Action |
762/// | --- | --- |
763/// | `PageUp` | [`Action::Previous`] |
764/// | `PageDown` | [`Action::Next`] |
765/// | `T` | [`Action::Today`] |
766/// | `ArrowLeft` | [`Action::PreviousDay`] |
767/// | `ArrowRight` | [`Action::NextDay`] |
768/// | `ArrowUp` | [`Action::PreviousWeek`] |
769/// | `ArrowDown` | [`Action::NextWeek`] |
770/// | `Alt+ArrowUp` | [`Action::PreviousEntry`] |
771/// | `Alt+ArrowDown` | [`Action::NextEntry`] |
772/// | `M` | [`Action::Month`] |
773/// | `W` | [`Action::Week`] |
774/// | `D` | [`Action::Day`] |
775/// | `A` | [`Action::Agenda`] |
776/// | `Y` | [`Action::Year`] |
777/// | `X` | [`Action::FourDays`] |
778/// | `Enter` | [`Action::Activate`] |
779/// | `Delete`, `Backspace` | [`Action::Remove`] |
780/// | `Escape` | [`Action::Close`] |
781///
782/// The arrow and page keys are shared with tabs, sliders and pagination,
783/// so on a screen with several of those resolve the calendar's keymap only
784/// while the calendar is what the user is working in.
785pub fn default_keymap() -> Keymap<Action> {
786    Keymap::new()
787        .bind(Chord::named(Named::PageUp), Action::Previous)
788        .bind(Chord::named(Named::PageDown), Action::Next)
789        .bind(Chord::character('t'), Action::Today)
790        .bind(Chord::named(Named::ArrowLeft), Action::PreviousDay)
791        .bind(Chord::named(Named::ArrowRight), Action::NextDay)
792        .bind(Chord::named(Named::ArrowUp), Action::PreviousWeek)
793        .bind(Chord::named(Named::ArrowDown), Action::NextWeek)
794        .bind(Chord::named(Named::ArrowUp).alt(), Action::PreviousEntry)
795        .bind(Chord::named(Named::ArrowDown).alt(), Action::NextEntry)
796        .bind(Chord::character('m'), Action::Month)
797        .bind(Chord::character('w'), Action::Week)
798        .bind(Chord::character('d'), Action::Day)
799        .bind(Chord::character('a'), Action::Agenda)
800        .bind(Chord::character('y'), Action::Year)
801        .bind(Chord::character('x'), Action::FourDays)
802        .bind(Chord::named(Named::Enter), Action::Activate)
803        .bind(Chord::named(Named::Delete), Action::Remove)
804        .bind(Chord::named(Named::Backspace), Action::Remove)
805        .bind(Chord::named(Named::Escape), Action::Close)
806}
807
808#[cfg(test)]
809mod tests {
810    use super::*;
811    use crate::data::calendar::entry::Change;
812    use crate::data::calendar::repeat::Repeat;
813    use jiff::civil::date;
814
815    /// Thursday 19 November 2026.
816    fn today() -> Date {
817        date(2026, 11, 19)
818    }
819
820    fn at(day: i8, hour: i8) -> Timestamp {
821        instant_at(
822            date(2026, 11, day),
823            u16::try_from(hour).unwrap_or(0) * 60,
824            &TimeZone::UTC,
825        )
826    }
827
828    fn meeting(id: u64, day: i8, hour: i8) -> Entry {
829        Entry::new(EntryId(id), "Meeting", at(day, hour), at(day, hour + 1))
830    }
831
832    fn state() -> State {
833        State::new(today()).with_entries(Entries::utc().with([
834            meeting(1, 19, 9),
835            meeting(2, 19, 14),
836            meeting(3, 20, 9),
837        ]))
838    }
839
840    fn entry(id: u64, day: i8, hour: i8) -> Selection {
841        Selection::Entry {
842            entry: EntryId(id),
843            start: at(day, hour),
844        }
845    }
846
847    #[test]
848    fn a_new_calendar_shows_the_month_of_today_with_nothing_selected() {
849        let state = State::new(today());
850        assert_eq!(state.view(), View::Month);
851        assert_eq!(state.cursor(), today());
852        assert_eq!(state.today(), today());
853        assert_eq!(state.now(), None);
854        assert_eq!(state.selection(), None);
855        assert_eq!(state.selected_day(), None);
856        assert_eq!(state.week_start(), Weekday::Monday);
857        assert!(state.entries().is_empty());
858        assert_eq!(state.time_zone(), &TimeZone::UTC);
859    }
860
861    #[test]
862    fn at_takes_today_from_the_time_and_the_time_zone() {
863        let Ok(tokyo) = TimeZone::get("Asia/Tokyo") else {
864            panic!("the time zone database is bundled for tests");
865        };
866        let state = State::at(at(19, 20), Entries::new(tokyo));
867        assert_eq!(state.today(), date(2026, 11, 20));
868        assert_eq!(state.now(), Some(at(19, 20)));
869    }
870
871    #[test]
872    fn builder_options() {
873        let state = State::new(today())
874            .with_view(View::Week)
875            .with_week_start(Weekday::Sunday)
876            .with_cursor(date(2026, 12, 1))
877            .with_selection(Selection::Day(date(2026, 12, 2)));
878        assert_eq!(state.view(), View::Week);
879        assert_eq!(state.week_start(), Weekday::Sunday);
880        assert_eq!(state.cursor(), date(2026, 12, 1));
881        assert_eq!(state.selected_day(), Some(date(2026, 12, 2)));
882    }
883
884    #[test]
885    fn every_view_has_a_label_a_range_and_a_title() {
886        let mut state = state();
887        let expected = [
888            (
889                View::Month,
890                (date(2026, 10, 26), date(2026, 12, 6)),
891                "November 2026",
892            ),
893            (
894                View::Week,
895                (date(2026, 11, 16), date(2026, 11, 22)),
896                "16 - 22 Nov 2026",
897            ),
898            (View::Day, (today(), today()), "Thursday 19 November 2026"),
899            (
900                View::Agenda,
901                (date(2026, 11, 1), date(2026, 11, 30)),
902                "November 2026",
903            ),
904            (View::Year, (date(2026, 1, 1), date(2026, 12, 31)), "2026"),
905            (
906                View::FourDays,
907                (today(), date(2026, 11, 22)),
908                "19 - 22 Nov 2026",
909            ),
910        ];
911        assert_eq!(View::ALL.len(), expected.len());
912        for (view, range, title) in expected {
913            let _ = state.update(Event::Show(view));
914            assert_eq!(state.view(), view);
915            assert_eq!(state.range(), range, "{view:?}");
916            assert_eq!(state.title(), title, "{view:?}");
917            assert_eq!(view.to_string(), view.label());
918        }
919        let labels: Vec<_> = View::ALL.iter().map(|view| view.label()).collect();
920        assert_eq!(
921            labels,
922            vec!["Day", "Week", "Month", "Year", "Schedule", "4 days"]
923        );
924    }
925
926    #[test]
927    fn a_year_steps_by_years_and_four_days_by_four() {
928        let mut year = State::new(today()).with_view(View::Year);
929        let _ = year.update(Event::Next);
930        assert_eq!(year.cursor(), date(2027, 11, 19));
931        assert_eq!(year.short_title(), "2027");
932        let _ = year.update(Event::Previous);
933        let _ = year.update(Event::Previous);
934        assert_eq!(year.cursor(), date(2025, 11, 19));
935
936        let mut days = State::new(date(2026, 11, 29)).with_view(View::FourDays);
937        assert_eq!(days.short_title(), "29 Nov - 2 Dec");
938        let _ = days.update(Event::Next);
939        assert_eq!(days.range(), (date(2026, 12, 3), date(2026, 12, 6)));
940        let _ = days.update(Event::Previous);
941        let _ = days.update(Event::Previous);
942        assert_eq!(days.cursor(), date(2026, 11, 25));
943
944        // A day moved out of the four starts the next four.
945        let mut days = State::new(today()).with_view(View::FourDays);
946        let _ = days.update(Event::MoveDay(3));
947        assert_eq!(days.cursor(), today());
948        let _ = days.update(Event::MoveDay(1));
949        assert_eq!(days.cursor(), date(2026, 11, 23));
950    }
951
952    #[test]
953    fn week_titles_name_both_months_or_years_when_they_differ() {
954        let state = State::new(date(2026, 12, 1)).with_view(View::Week);
955        assert_eq!(state.title(), "30 Nov - 6 Dec 2026");
956        let state = State::new(date(2026, 12, 31)).with_view(View::Week);
957        assert_eq!(state.title(), "28 Dec 2026 - 3 Jan 2027");
958    }
959
960    #[test]
961    fn short_titles_fit_a_phone() {
962        let mut state = State::new(today());
963        assert_eq!(state.short_title(), "November 2026");
964        let _ = state.update(Event::Show(View::Agenda));
965        assert_eq!(state.short_title(), "November 2026");
966        let _ = state.update(Event::Show(View::Day));
967        assert_eq!(state.short_title(), "Thu 19 Nov 2026");
968        let _ = state.update(Event::Show(View::Week));
969        assert_eq!(state.short_title(), "16 - 22 Nov 2026");
970
971        let across_months = State::new(date(2026, 12, 1)).with_view(View::Week);
972        assert_eq!(across_months.short_title(), "30 Nov - 6 Dec");
973        let across_years = State::new(date(2026, 12, 31)).with_view(View::Week);
974        assert_eq!(across_years.short_title(), "28 Dec - 3 Jan");
975    }
976
977    #[test]
978    fn the_week_follows_the_day_weeks_start_on() {
979        let state = State::new(today())
980            .with_view(View::Week)
981            .with_week_start(Weekday::Sunday);
982        assert_eq!(state.range(), (date(2026, 11, 15), date(2026, 11, 21)));
983    }
984
985    #[test]
986    fn next_and_previous_step_by_what_the_view_shows() {
987        let mut state = state();
988        assert_eq!(
989            state.update(Event::Next),
990            Some(Output::Viewed {
991                view: View::Month,
992                first: date(2026, 11, 30),
993                last: date(2027, 1, 3)
994            })
995        );
996        assert_eq!(state.cursor(), date(2026, 12, 19));
997        let _ = state.update(Event::Previous);
998        assert_eq!(state.cursor(), today());
999
1000        let _ = state.update(Event::Show(View::Week));
1001        let _ = state.update(Event::Next);
1002        assert_eq!(state.cursor(), date(2026, 11, 26));
1003        let _ = state.update(Event::Show(View::Day));
1004        let _ = state.update(Event::Previous);
1005        assert_eq!(state.cursor(), date(2026, 11, 25));
1006        let _ = state.update(Event::Show(View::Agenda));
1007        let _ = state.update(Event::Next);
1008        assert_eq!(state.cursor(), date(2026, 12, 25));
1009    }
1010
1011    #[test]
1012    fn stepping_a_month_from_the_31st_lands_on_the_last_day() {
1013        let mut state = State::new(date(2027, 1, 31));
1014        let _ = state.update(Event::Next);
1015        assert_eq!(state.cursor(), date(2027, 2, 28));
1016    }
1017
1018    #[test]
1019    fn showing_the_view_already_on_show_does_nothing() {
1020        let mut state = state();
1021        assert_eq!(state.update(Event::Show(View::Month)), None);
1022        assert!(state.update(Event::Show(View::Week)).is_some());
1023    }
1024
1025    #[test]
1026    fn switching_view_goes_to_the_selected_day() {
1027        let mut state = state();
1028        let _ = state.update(Event::Press(Selection::Day(date(2026, 11, 3))));
1029        let _ = state.update(Event::Show(View::Day));
1030        assert_eq!(state.cursor(), date(2026, 11, 3));
1031    }
1032
1033    #[test]
1034    fn go_to_reports_only_when_the_period_changes() {
1035        let mut state = state();
1036        assert_eq!(state.update(Event::GoTo(date(2026, 11, 2))), None);
1037        assert_eq!(state.cursor(), date(2026, 11, 2));
1038        assert!(matches!(
1039            state.update(Event::GoTo(date(2027, 3, 1))),
1040            Some(Output::Viewed { .. })
1041        ));
1042        assert_eq!(state.selection(), None);
1043    }
1044
1045    #[test]
1046    fn today_comes_back_and_selects_today() {
1047        let mut state = state();
1048        assert_eq!(
1049            state.update(Event::Today),
1050            Some(Output::Selected(Some(Selection::Day(today()))))
1051        );
1052        assert_eq!(state.update(Event::Today), None);
1053        let _ = state.update(Event::Next);
1054        assert!(matches!(
1055            state.update(Event::Today),
1056            Some(Output::Viewed { .. })
1057        ));
1058        assert_eq!(state.cursor(), today());
1059    }
1060
1061    #[test]
1062    fn the_first_press_selects_and_the_second_activates() {
1063        let mut state = state();
1064        let day = Selection::Day(date(2026, 11, 3));
1065        assert_eq!(
1066            state.update(Event::Press(day)),
1067            Some(Output::Selected(Some(day)))
1068        );
1069        assert!(state.is_selected(day));
1070        assert_eq!(
1071            state.update(Event::Press(day)),
1072            Some(Output::Requested(Draft {
1073                when: When::day(date(2026, 11, 3))
1074            }))
1075        );
1076
1077        let picked = entry(1, 19, 9);
1078        assert_eq!(
1079            state.update(Event::Press(picked)),
1080            Some(Output::Selected(Some(picked)))
1081        );
1082        assert_eq!(state.selected_entry().map(Entry::id), Some(EntryId(1)));
1083        assert_eq!(state.selected_day(), Some(today()));
1084        assert_eq!(
1085            state.update(Event::Press(picked)),
1086            Some(Output::Opened {
1087                entry: EntryId(1),
1088                start: at(19, 9)
1089            })
1090        );
1091    }
1092
1093    #[test]
1094    fn a_slot_asks_for_an_hour_and_stops_at_midnight() {
1095        let mut state = state();
1096        let slot = Selection::Slot {
1097            date: today(),
1098            minute: 600,
1099        };
1100        let _ = state.update(Event::Press(slot));
1101        assert_eq!(
1102            state.update(Event::Activate),
1103            Some(Output::Requested(Draft {
1104                when: When::timed(at(19, 10), at(19, 11))
1105            }))
1106        );
1107        let late = Selection::Slot {
1108            date: today(),
1109            minute: 1410,
1110        };
1111        let _ = state.update(Event::Press(late));
1112        assert_eq!(
1113            state.update(Event::Activate),
1114            Some(Output::Requested(Draft {
1115                when: When::timed(instant_at(today(), 1410, &TimeZone::UTC), at(20, 0))
1116            }))
1117        );
1118    }
1119
1120    #[test]
1121    fn activating_with_nothing_selected_asks_for_the_day_on_show() {
1122        let mut state = state();
1123        assert_eq!(
1124            state.update(Event::Activate),
1125            Some(Output::Requested(Draft {
1126                when: When::day(today())
1127            }))
1128        );
1129    }
1130
1131    #[test]
1132    fn activating_an_entry_that_is_gone_does_nothing() {
1133        let mut state = state().with_selection(entry(9, 19, 9));
1134        assert_eq!(state.update(Event::Activate), None);
1135        assert_eq!(state.selected_entry(), None);
1136    }
1137
1138    #[test]
1139    fn everything_is_allowed_unless_set() {
1140        assert_eq!(Allow::default(), Allow::ALL);
1141        assert_eq!(state().allow(), Allow::ALL);
1142        assert_eq!(state().read_only().allow(), Allow::NONE);
1143        let mut state = state();
1144        state.set_allow(Allow {
1145            remove: false,
1146            ..Allow::ALL
1147        });
1148        assert!(state.allow().create && !state.allow().remove);
1149    }
1150
1151    #[test]
1152    fn a_read_only_calendar_can_be_looked_through_but_not_changed() {
1153        let mut state = state().read_only();
1154        let day = Selection::Day(date(2026, 11, 3));
1155        let slot = Selection::Slot {
1156            date: today(),
1157            minute: 600,
1158        };
1159
1160        // Selecting and moving about still work.
1161        assert_eq!(
1162            state.update(Event::Press(day)),
1163            Some(Output::Selected(Some(day)))
1164        );
1165        assert!(state.update(Event::Next).is_some());
1166        assert!(state.update(Event::Show(View::Week)).is_some());
1167
1168        // A second press, Enter or a drag asks for nothing.
1169        let _ = state.update(Event::Press(day));
1170        assert_eq!(state.update(Event::Press(day)), None);
1171        assert_eq!(state.update(Event::Activate), None);
1172        let _ = state.update(Event::Press(slot));
1173        assert_eq!(state.update(Event::Press(slot)), None);
1174        let draft = Draft {
1175            when: When::day(today()),
1176        };
1177        assert_eq!(state.update(Event::Request(draft)), None);
1178        let _ = state.update(Event::Clear);
1179        assert_eq!(state.update(Event::Activate), None);
1180        assert_eq!(Action::Activate.event(&state), None);
1181
1182        // An entry can still be opened, but not dragged or removed by key.
1183        let picked = entry(1, 19, 9);
1184        let _ = state.update(Event::Press(picked));
1185        assert_eq!(
1186            state.update(Event::Press(picked)),
1187            Some(Output::Opened {
1188                entry: EntryId(1),
1189                start: at(19, 9)
1190            })
1191        );
1192        assert_eq!(Action::Activate.event(&state), Some(Event::Activate));
1193        assert_eq!(Action::Remove.event(&state), None);
1194        let drag = Event::Reschedule {
1195            entry: EntryId(1),
1196            start: at(19, 9),
1197            to: (at(20, 9), at(20, 10)),
1198        };
1199        assert_eq!(state.update(drag), None);
1200        assert_eq!(
1201            state.entries().get(EntryId(1)).map(Entry::when),
1202            Some(meeting(1, 19, 9).when())
1203        );
1204    }
1205
1206    #[test]
1207    fn the_app_can_still_change_a_read_only_calendar() {
1208        let mut state = state().read_only();
1209        assert!(state.update(Event::Insert(meeting(7, 21, 9))).is_some());
1210        assert!(state.update(Event::Insert(meeting(7, 22, 9))).is_some());
1211        assert!(state.update(Event::Remove(EntryId(7))).is_some());
1212        assert_eq!(state.entries().len(), 3);
1213    }
1214
1215    #[test]
1216    fn each_permission_stands_alone() {
1217        let mut state = state().with_allow(Allow {
1218            create: false,
1219            ..Allow::ALL
1220        });
1221        let _ = state.update(Event::Press(entry(1, 19, 9)));
1222        assert_eq!(
1223            Action::Remove.event(&state),
1224            Some(Event::Remove(EntryId(1)))
1225        );
1226        let drag = Event::Reschedule {
1227            entry: EntryId(1),
1228            start: at(19, 9),
1229            to: (at(20, 9), at(20, 10)),
1230        };
1231        assert!(state.update(drag).is_some());
1232        let _ = state.update(Event::Clear);
1233        assert_eq!(state.update(Event::Activate), None);
1234    }
1235
1236    #[test]
1237    fn clear_reports_only_when_something_was_selected() {
1238        let mut state = state();
1239        assert_eq!(state.update(Event::Clear), None);
1240        let _ = state.update(Event::Press(Selection::Day(today())));
1241        assert_eq!(state.update(Event::Clear), Some(Output::Selected(None)));
1242        assert_eq!(state.selection(), None);
1243    }
1244
1245    #[test]
1246    fn moving_the_day_starts_from_the_period_on_show_and_turns_the_page() {
1247        let mut state = state();
1248        assert_eq!(
1249            state.update(Event::MoveDay(1)),
1250            Some(Output::Selected(Some(Selection::Day(date(2026, 11, 20)))))
1251        );
1252        let _ = state.update(Event::MoveDay(7));
1253        assert_eq!(state.selected_day(), Some(date(2026, 11, 27)));
1254        assert_eq!(state.cursor(), today(), "still in November");
1255
1256        // 4 December is in the month grid, but belongs to the next month.
1257        assert!(matches!(
1258            state.update(Event::MoveDay(7)),
1259            Some(Output::Viewed { .. })
1260        ));
1261        assert_eq!(state.cursor(), date(2026, 12, 4));
1262
1263        let mut week = State::new(today()).with_view(View::Week);
1264        let _ = week.update(Event::MoveDay(3));
1265        assert_eq!(week.cursor(), today());
1266        assert!(matches!(
1267            week.update(Event::MoveDay(1)),
1268            Some(Output::Viewed { .. })
1269        ));
1270        assert_eq!(week.cursor(), date(2026, 11, 23));
1271    }
1272
1273    #[test]
1274    fn entries_of_the_selected_day_cycle_and_wrap() {
1275        let mut state = state();
1276        assert_eq!(
1277            state.update(Event::NextEntry),
1278            Some(Output::Selected(Some(entry(1, 19, 9))))
1279        );
1280        let _ = state.update(Event::NextEntry);
1281        assert!(state.is_selected(entry(2, 19, 14)));
1282        let _ = state.update(Event::NextEntry);
1283        assert!(state.is_selected(entry(1, 19, 9)), "wraps");
1284        let _ = state.update(Event::PreviousEntry);
1285        assert!(state.is_selected(entry(2, 19, 14)));
1286
1287        let mut from_the_end = self::state();
1288        let _ = from_the_end.update(Event::PreviousEntry);
1289        assert!(from_the_end.is_selected(entry(2, 19, 14)));
1290
1291        let mut one = self::state().with_selection(Selection::Day(date(2026, 11, 20)));
1292        let _ = one.update(Event::NextEntry);
1293        assert_eq!(one.update(Event::NextEntry), None, "the only entry");
1294
1295        let mut none = self::state().with_selection(Selection::Day(date(2026, 11, 1)));
1296        assert_eq!(none.update(Event::NextEntry), None);
1297    }
1298
1299    #[test]
1300    fn the_schedule_steps_through_all_its_entries_with_the_arrows() {
1301        let mut state = state().with_view(View::Agenda);
1302        for action in [Action::NextDay, Action::NextWeek] {
1303            assert_eq!(action.event(&state), Some(Event::NextEntry), "{action:?}");
1304        }
1305        for action in [Action::PreviousDay, Action::PreviousWeek] {
1306            assert_eq!(
1307                action.event(&state),
1308                Some(Event::PreviousEntry),
1309                "{action:?}"
1310            );
1311        }
1312        let _ = state.update(Event::NextEntry);
1313        let _ = state.update(Event::NextEntry);
1314        let _ = state.update(Event::NextEntry);
1315        assert!(state.is_selected(entry(3, 20, 9)), "on to the next day");
1316        let _ = state.update(Event::NextEntry);
1317        assert!(state.is_selected(entry(1, 19, 9)), "and round again");
1318    }
1319
1320    #[test]
1321    fn open_day_switches_to_the_day_view() {
1322        let mut state = state();
1323        assert_eq!(
1324            state.update(Event::OpenDay(date(2026, 11, 3))),
1325            Some(Output::Viewed {
1326                view: View::Day,
1327                first: date(2026, 11, 3),
1328                last: date(2026, 11, 3)
1329            })
1330        );
1331        assert_eq!(state.view(), View::Day);
1332        assert_eq!(state.update(Event::OpenDay(date(2026, 11, 3))), None);
1333    }
1334
1335    #[test]
1336    fn a_request_is_passed_on_and_adds_nothing() {
1337        let mut state = state();
1338        let draft = Draft {
1339            when: When::timed(at(19, 11), at(19, 12)),
1340        };
1341        assert_eq!(
1342            state.update(Event::Request(draft)),
1343            Some(Output::Requested(draft))
1344        );
1345        assert_eq!(state.entries().len(), 3);
1346    }
1347
1348    #[test]
1349    fn insert_and_remove_report_the_change() {
1350        let mut state = state();
1351        let change = |output: Option<Output>| match output {
1352            Some(Output::Changed(changed)) => Some(changed.change),
1353            _ => None,
1354        };
1355        let created = state.update(Event::Insert(meeting(4, 21, 9)));
1356        assert_eq!(change(created), Some(Change::Created));
1357        let updated = state.update(Event::Insert(meeting(4, 22, 9)));
1358        assert_eq!(change(updated), Some(Change::Updated));
1359        assert_eq!(state.update(Event::Insert(meeting(4, 22, 9))), None);
1360
1361        let _ = state.update(Event::Press(entry(4, 22, 9)));
1362        let removed = state.update(Event::Remove(EntryId(4)));
1363        assert_eq!(change(removed), Some(Change::Removed));
1364        assert_eq!(state.selection(), None, "the selection goes with it");
1365        assert_eq!(state.update(Event::Remove(EntryId(4))), None);
1366    }
1367
1368    #[test]
1369    fn removing_another_entry_keeps_the_selection() {
1370        let mut state = state().with_selection(entry(1, 19, 9));
1371        let _ = state.update(Event::Remove(EntryId(2)));
1372        assert!(state.is_selected(entry(1, 19, 9)));
1373    }
1374
1375    #[test]
1376    fn rescheduling_moves_the_entry_and_the_selection() {
1377        let mut state = state().with_selection(entry(1, 19, 9));
1378        let output = state.update(Event::Reschedule {
1379            entry: EntryId(1),
1380            start: at(19, 9),
1381            to: (at(20, 15), at(20, 17)),
1382        });
1383        let Some(Output::Changed(changed)) = output else {
1384            panic!("an update");
1385        };
1386        assert_eq!(changed.change, Change::Updated);
1387        assert_eq!(changed.entry.when(), When::timed(at(20, 15), at(20, 17)));
1388        assert_eq!(changed.before, Some(meeting(1, 19, 9)));
1389        assert!(state.is_selected(entry(1, 20, 15)));
1390    }
1391
1392    #[test]
1393    fn rescheduling_one_occurrence_moves_the_whole_series() {
1394        let mut state = State::new(today())
1395            .with_entries(Entries::utc().with([meeting(1, 16, 9).repeat(Repeat::daily())]));
1396        // The occurrence on the 19th is dragged two hours later.
1397        let _ = state.update(Event::Reschedule {
1398            entry: EntryId(1),
1399            start: at(19, 9),
1400            to: (at(19, 11), at(19, 12)),
1401        });
1402        let moved = state.entries().get(EntryId(1)).map(Entry::when);
1403        assert_eq!(moved, Some(When::timed(at(16, 11), at(16, 12))));
1404    }
1405
1406    #[test]
1407    fn rescheduling_ignores_unknown_whole_day_and_unmoved_entries() {
1408        let mut state = state();
1409        let day = date(2026, 11, 19);
1410        let _ = state.update(Event::Insert(Entry::all_day(EntryId(8), "Trip", day, day)));
1411        let to = (at(20, 9), at(20, 10));
1412        for id in [8, 99] {
1413            let event = Event::Reschedule {
1414                entry: EntryId(id),
1415                start: at(19, 0),
1416                to,
1417            };
1418            assert_eq!(state.update(event), None, "{id}");
1419        }
1420        let unmoved = Event::Reschedule {
1421            entry: EntryId(1),
1422            start: at(19, 9),
1423            to: (at(19, 9), at(19, 10)),
1424        };
1425        assert_eq!(state.update(unmoved), None);
1426    }
1427
1428    #[test]
1429    fn a_tick_moves_today_and_the_now_line() {
1430        let mut state = state();
1431        assert_eq!(state.update(Event::Tick(at(20, 0))), None);
1432        assert_eq!(state.now(), Some(at(20, 0)));
1433        assert_eq!(state.today(), date(2026, 11, 20));
1434        assert_eq!(state.cursor(), today(), "the period on show stays");
1435    }
1436
1437    fn press(keymap: &Keymap<Action>, chord: &str) -> Option<Action> {
1438        let Ok(chord) = chord.parse::<Chord>() else {
1439            panic!("{chord} is a chord");
1440        };
1441        keymap.resolve(chord.key(), chord.modifiers())
1442    }
1443
1444    #[test]
1445    fn default_keymap_covers_every_action() {
1446        let keymap = default_keymap();
1447        let expected = [
1448            ("PageUp", Action::Previous),
1449            ("PageDown", Action::Next),
1450            ("T", Action::Today),
1451            ("ArrowLeft", Action::PreviousDay),
1452            ("ArrowRight", Action::NextDay),
1453            ("ArrowUp", Action::PreviousWeek),
1454            ("ArrowDown", Action::NextWeek),
1455            ("Alt+ArrowUp", Action::PreviousEntry),
1456            ("Alt+ArrowDown", Action::NextEntry),
1457            ("M", Action::Month),
1458            ("W", Action::Week),
1459            ("D", Action::Day),
1460            ("A", Action::Agenda),
1461            ("Y", Action::Year),
1462            ("X", Action::FourDays),
1463            ("Enter", Action::Activate),
1464            ("Delete", Action::Remove),
1465            ("Backspace", Action::Remove),
1466            ("Escape", Action::Close),
1467        ];
1468        for (chord, action) in expected {
1469            assert_eq!(press(&keymap, chord), Some(action), "{chord}");
1470        }
1471        assert_eq!(press(&keymap, "Ctrl+T"), None);
1472        for action in <Action as keys::Action>::ALL {
1473            assert!(!keymap.chords(action).is_empty(), "{action:?}");
1474            assert!(!keys::Action::name(*action).is_empty());
1475            assert!(!keys::Action::description(*action).is_empty());
1476        }
1477        assert_eq!(Keymap::<Action>::defaults(), keymap);
1478    }
1479
1480    #[test]
1481    fn keymap_overrides_and_unbinding() {
1482        let Ok(chord) = "Ctrl+G".parse::<Chord>() else {
1483            panic!("a chord");
1484        };
1485        let keymap = default_keymap()
1486            .unbind(&Chord::character('t'))
1487            .bind(chord, Action::Today);
1488        assert_eq!(press(&keymap, "T"), None);
1489        assert_eq!(press(&keymap, "Ctrl+G"), Some(Action::Today));
1490        assert_eq!(press(&keymap, "M"), Some(Action::Month));
1491        assert!(
1492            default_keymap()
1493                .unbind_action(&Action::Remove)
1494                .chords(&Action::Remove)
1495                .is_empty()
1496        );
1497    }
1498
1499    #[test]
1500    fn actions_map_to_events() {
1501        let state = state();
1502        assert_eq!(Action::Next.event(&state), Some(Event::Next));
1503        assert_eq!(Action::Previous.event(&state), Some(Event::Previous));
1504        assert_eq!(Action::Today.event(&state), Some(Event::Today));
1505        assert_eq!(Action::PreviousDay.event(&state), Some(Event::MoveDay(-1)));
1506        assert_eq!(Action::NextDay.event(&state), Some(Event::MoveDay(1)));
1507        assert_eq!(Action::PreviousWeek.event(&state), Some(Event::MoveDay(-7)));
1508        assert_eq!(Action::NextWeek.event(&state), Some(Event::MoveDay(7)));
1509        assert_eq!(Action::NextEntry.event(&state), Some(Event::NextEntry));
1510        assert_eq!(
1511            Action::PreviousEntry.event(&state),
1512            Some(Event::PreviousEntry)
1513        );
1514        assert_eq!(Action::Activate.event(&state), Some(Event::Activate));
1515        assert_eq!(Action::Month.event(&state), None, "already on show");
1516        assert_eq!(Action::Week.event(&state), Some(Event::Show(View::Week)));
1517        assert_eq!(Action::Day.event(&state), Some(Event::Show(View::Day)));
1518        assert_eq!(
1519            Action::Agenda.event(&state),
1520            Some(Event::Show(View::Agenda))
1521        );
1522        assert_eq!(Action::Year.event(&state), Some(Event::Show(View::Year)));
1523        assert_eq!(
1524            Action::FourDays.event(&state),
1525            Some(Event::Show(View::FourDays))
1526        );
1527    }
1528
1529    #[test]
1530    fn remove_and_close_need_a_selection() {
1531        let mut state = state();
1532        assert_eq!(Action::Remove.event(&state), None);
1533        assert_eq!(Action::Close.event(&state), None);
1534
1535        let _ = state.update(Event::Press(Selection::Day(today())));
1536        assert_eq!(Action::Remove.event(&state), None, "a day is not an entry");
1537        assert_eq!(Action::Close.event(&state), Some(Event::Clear));
1538
1539        let _ = state.update(Event::Press(entry(2, 19, 14)));
1540        let Some(event) = Action::Remove.event(&state) else {
1541            panic!("an entry is selected");
1542        };
1543        assert_eq!(event, Event::Remove(EntryId(2)));
1544        assert!(state.update(event).is_some());
1545        assert_eq!(state.entries().len(), 2);
1546    }
1547}