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 iced::time::Duration;
5
6pub use super::gesture::DOUBLE_CLICK;
7use jiff::civil::{Date, Weekday};
8use jiff::tz::TimeZone;
9use jiff::{SignedDuration, Timestamp, ToSpan};
10
11use super::entry::{Change, Changed, Draft, Entries, Entry, EntryId, When, add_days};
12use super::layout::{self, DAY_MINUTES, instant_at};
13use crate::keys::{self, Chord, Keymap};
14
15/// How long an entry asked for by pressing a time slot is.
16pub const SLOT_MINUTES: u16 = 60;
17
18/// How many days [`View::FourDays`] shows.
19pub const FOUR_DAYS: i32 = 4;
20
21/// How the entries are laid out.
22#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
23pub enum View {
24    /// One day against the hours.
25    Day,
26    /// Seven days side by side against the hours.
27    Week,
28    /// A grid of weeks with entries across the days.
29    #[default]
30    Month,
31    /// The twelve months of a year, small.
32    Year,
33    /// The month's entries as a list, day by day.
34    Agenda,
35    /// Four days against the hours, starting on the day on show.
36    FourDays,
37}
38
39impl View {
40    /// Every view, in the order the header's menu lists them.
41    pub const ALL: [View; 6] = [
42        View::Day,
43        View::Week,
44        View::Month,
45        View::Year,
46        View::Agenda,
47        View::FourDays,
48    ];
49
50    pub fn label(self) -> &'static str {
51        match self {
52            View::Day => "Day",
53            View::Week => "Week",
54            View::Month => "Month",
55            View::Year => "Year",
56            View::Agenda => "Schedule",
57            View::FourDays => "4 days",
58        }
59    }
60}
61
62impl std::fmt::Display for View {
63    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
64        f.write_str(self.label())
65    }
66}
67
68/// What the user may change through the calendar's own gestures and
69/// shortcuts. Everything is allowed by default.
70///
71/// This only limits what the calendar offers. [`Event::Insert`] and
72/// [`Event::Remove`] always apply, so the app, or controls of its own, can
73/// still add, change and remove entries on a calendar that is read-only
74/// to the pointer and the keyboard.
75#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
76pub struct Allow {
77    /// Asking for a new entry: a second press on a day or a time, a drag
78    /// across empty space, or [`Action::Activate`] on a day.
79    pub create: bool,
80    /// Dragging an entry to move it or to change when it ends.
81    pub reschedule: bool,
82    /// Removing the selected entry with [`Action::Remove`].
83    pub remove: bool,
84}
85
86impl Allow {
87    /// Everything: the default.
88    pub const ALL: Allow = Allow {
89        create: true,
90        reschedule: true,
91        remove: true,
92    };
93
94    /// Nothing: a read-only calendar. Days and entries can still be
95    /// selected, entries opened and the period and view changed.
96    pub const NONE: Allow = Allow {
97        create: false,
98        reschedule: false,
99        remove: false,
100    };
101}
102
103impl Default for Allow {
104    fn default() -> Self {
105        Self::ALL
106    }
107}
108
109/// What is selected: at most one thing at a time.
110#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
111pub enum Selection {
112    Day(Date),
113    /// A time on a day in the week and day views, in minutes from
114    /// midnight.
115    Slot {
116        date: Date,
117        minute: u16,
118    },
119    /// One occurrence of an entry, told apart by when it starts.
120    Entry {
121        entry: EntryId,
122        start: Timestamp,
123    },
124}
125
126/// Everything that changes the calendar.
127#[derive(Debug, Clone, PartialEq, Eq)]
128pub enum Event {
129    Show(View),
130    /// Moves on by a month, a week or a day, whichever the view shows.
131    Next,
132    Previous,
133    /// Goes to today and selects it.
134    Today,
135    /// Shows the period holding this date, without selecting anything.
136    GoTo(Date),
137    /// A single press on a day, a time slot or an entry, which selects it.
138    /// A press on what is already selected activates it, as
139    /// [`Event::Activate`] does, unless
140    /// [`with_activate_on_second_press`](State::with_activate_on_second_press)
141    /// turned that off.
142    Press(Selection),
143    /// A double click or double tap: selects what was pressed and
144    /// activates it, opening an entry or asking for a new one on a day or
145    /// a time.
146    DoublePress(Selection),
147    /// Activates the selection: an entry is opened, and a day or a time
148    /// slot asks for a new entry there. With nothing selected it asks for
149    /// one on the day on show.
150    Activate,
151    /// Clears the selection.
152    Clear,
153    /// Moves the selected day by this many days and follows it when it
154    /// leaves the period on show.
155    MoveDay(i32),
156    /// Selects the next entry on the selected day, wrapping.
157    NextEntry,
158    PreviousEntry,
159    /// Shows one day, as the "more" count of a crowded day does.
160    OpenDay(Date),
161    /// A span dragged out on empty space.
162    Request(Draft),
163    /// An occurrence dragged or resized to a new time. `start` says which
164    /// occurrence; every occurrence of a repeating entry starts as far from
165    /// where it did as this one, and takes this one's new length, so
166    /// resizing one edge resizes the series. A whole-day entry moves by the
167    /// days between the two starts.
168    Reschedule {
169        entry: EntryId,
170        start: Timestamp,
171        to: (Timestamp, Timestamp),
172    },
173    /// An occurrence dragged by whole days, as in the month view and the
174    /// strip of whole-day entries. A timed entry keeps its time of day and
175    /// a whole-day entry its length in days. A repeating entry moves as a
176    /// whole. Like [`Reschedule`](Event::Reschedule), it is limited by
177    /// [`Allow`] and by entries that are locked or not
178    /// [`movable`](Entry::movable).
179    MoveDays {
180        entry: EntryId,
181        start: Timestamp,
182        days: i32,
183    },
184    /// The user asked to remove an entry, such as with the Delete key.
185    /// It is limited by [`Allow`] and by entries that are locked or not
186    /// [`removable`](Entry::removable), and only proposed when
187    /// [`with_proposals`](State::with_proposals) is on.
188    Delete(EntryId),
189    /// Applies the change waiting in [`State::pending`].
190    Confirm,
191    /// Drops the change waiting in [`State::pending`], leaving the entry
192    /// where it was.
193    Discard,
194    /// Adds an entry, or replaces the one with the same id. Always
195    /// applies, and clears a pending change to the same entry.
196    Insert(Entry),
197    /// Removes an entry. Always applies, and clears a pending change to
198    /// it.
199    Remove(EntryId),
200    /// The current time, for "today" and the now line.
201    Tick(Timestamp),
202}
203
204/// What the app may want to act on after an [`Event`].
205#[derive(Debug, Clone, PartialEq, Eq)]
206pub enum Output {
207    Selected(Option<Selection>),
208    /// An entry was activated: show or edit it.
209    Opened {
210        entry: EntryId,
211        start: Timestamp,
212    },
213    /// The user asked for a new entry here. Nothing is added until the app
214    /// sends [`Event::Insert`].
215    Requested(Draft),
216    /// An entry was created, updated or removed. Pass it to
217    /// [`Scheduler::observe`](super::schedule::Scheduler::observe) for
218    /// triggers on changes.
219    Changed(Box<Changed>),
220    /// With [`with_proposals`](State::with_proposals) on, a drag or the
221    /// Delete key asks for this change without making it. The entries are
222    /// untouched and the change is drawn as a preview until the app sends
223    /// [`Event::Confirm`] or [`Event::Discard`].
224    Proposed(Box<Changed>),
225    /// A different period or view is on show, such as after
226    /// [`Event::Next`], and once for the first period on the first
227    /// [`Event::Tick`]. Useful for loading the entries of that period.
228    Viewed {
229        view: View,
230        first: Date,
231        last: Date,
232    },
233}
234
235/// The entries, the view, the period on show and the selection.
236#[derive(Debug, Clone, PartialEq)]
237pub struct State {
238    entries: Entries,
239    view: View,
240    /// A date in the period on show.
241    cursor: Date,
242    today: Date,
243    now: Option<Timestamp>,
244    selection: Option<Selection>,
245    week_start: Weekday,
246    allow: Allow,
247    proposals: bool,
248    pending: Option<Pending>,
249    /// The entries with the pending change applied, drawn while it waits.
250    shown: Option<Entries>,
251    second_press: bool,
252    double_click: Duration,
253    /// Whether the period on show has been reported with
254    /// [`Output::Viewed`].
255    announced: bool,
256    /// Counts the times the hours should scroll back to the start hour.
257    scrolls: u32,
258}
259
260/// A change waiting for [`Event::Confirm`], and the new start a selection
261/// on the moved entry follows to.
262#[derive(Debug, Clone, PartialEq)]
263struct Pending {
264    changed: Changed,
265    follow: Option<Timestamp>,
266}
267
268impl State {
269    /// An empty calendar in UTC showing the month of `today`.
270    ///
271    /// The calendar never reads the clock. Pass today's date here, and
272    /// keep it current with [`Event::Tick`] if the app stays open.
273    pub fn new(today: Date) -> Self {
274        Self {
275            entries: Entries::utc(),
276            view: View::default(),
277            cursor: today,
278            today,
279            now: None,
280            selection: None,
281            week_start: Weekday::Monday,
282            allow: Allow::ALL,
283            proposals: false,
284            pending: None,
285            shown: None,
286            second_press: true,
287            double_click: DOUBLE_CLICK,
288            announced: false,
289            scrolls: 0,
290        }
291    }
292
293    /// How soon a second press must follow the first to make a double
294    /// click or double tap. Defaults to [`DOUBLE_CLICK`].
295    pub fn with_double_click(mut self, interval: Duration) -> Self {
296        self.double_click = interval;
297        self
298    }
299
300    pub fn double_click(&self) -> Duration {
301        self.double_click
302    }
303
304    /// Makes drags and the Delete key propose their change with
305    /// [`Output::Proposed`] instead of making it, so the app can ask
306    /// first. Off by default: changes apply at once.
307    pub fn with_proposals(mut self, proposals: bool) -> Self {
308        self.proposals = proposals;
309        self
310    }
311
312    /// Whether a press on what is already selected activates it. On by
313    /// default, which suits touch screens; turn it off where a double
314    /// click opens things, so only [`Event::DoublePress`] activates.
315    pub fn with_activate_on_second_press(mut self, activates: bool) -> Self {
316        self.second_press = activates;
317        self
318    }
319
320    pub fn proposes(&self) -> bool {
321        self.proposals
322    }
323
324    pub fn activates_on_second_press(&self) -> bool {
325        self.second_press
326    }
327
328    /// The change waiting for [`Event::Confirm`] or [`Event::Discard`].
329    pub fn pending(&self) -> Option<&Changed> {
330        self.pending.as_ref().map(|pending| &pending.changed)
331    }
332
333    /// The entries as drawn: [`entries`](State::entries) with any pending
334    /// change applied.
335    pub fn shown(&self) -> &Entries {
336        self.shown.as_ref().unwrap_or(&self.entries)
337    }
338
339    /// Whether `entry` is drawn as a preview of a pending change.
340    pub fn is_preview(&self, entry: EntryId) -> bool {
341        self.pending
342            .as_ref()
343            .is_some_and(|pending| pending.changed.entry.id() == entry)
344    }
345
346    pub(super) fn scrolls(&self) -> u32 {
347        self.scrolls
348    }
349
350    /// A calendar showing the month of `now` in the time zone of
351    /// `entries`, with the now line drawn.
352    pub fn at(now: Timestamp, entries: Entries) -> Self {
353        let mut state = Self::new(entries.date_of(now)).with_entries(entries);
354        state.now = Some(now);
355        state
356    }
357
358    /// Replaces the entries and their time zone.
359    pub fn with_entries(mut self, entries: Entries) -> Self {
360        self.entries = entries;
361        self
362    }
363
364    pub fn with_view(mut self, view: View) -> Self {
365        self.set_view(view);
366        self
367    }
368
369    /// The day weeks start on. Defaults to Monday.
370    pub fn with_week_start(mut self, week_start: Weekday) -> Self {
371        self.week_start = week_start;
372        self
373    }
374
375    /// Shows the period holding `date`.
376    pub fn with_cursor(mut self, date: Date) -> Self {
377        self.cursor = date;
378        self
379    }
380
381    pub fn with_selection(mut self, selection: Selection) -> Self {
382        self.selection = Some(selection);
383        self
384    }
385
386    /// Limits what the user may change through the calendar itself.
387    pub fn with_allow(mut self, allow: Allow) -> Self {
388        self.allow = allow;
389        self
390    }
391
392    /// A calendar the user can look through but not change: nothing can
393    /// be created, dragged or removed from it. The same as
394    /// [`with_allow`](State::with_allow) with [`Allow::NONE`].
395    pub fn read_only(self) -> Self {
396        self.with_allow(Allow::NONE)
397    }
398
399    /// Changes what the user may do, such as when they sign in or a
400    /// calendar they cannot edit comes on show.
401    pub fn set_allow(&mut self, allow: Allow) {
402        self.allow = allow;
403    }
404
405    pub fn allow(&self) -> Allow {
406        self.allow
407    }
408
409    /// Whether the calendar's own drags and shortcuts may move or resize
410    /// `entry`: the calendar allows rescheduling and the entry is
411    /// [`movable`](Entry::is_movable).
412    pub fn can_move(&self, entry: &Entry) -> bool {
413        self.allow.reschedule && entry.is_movable()
414    }
415
416    /// Whether the calendar's own Delete shortcut may remove `entry`: the
417    /// calendar allows removing and the entry is
418    /// [`removable`](Entry::is_removable).
419    pub fn can_remove(&self, entry: &Entry) -> bool {
420        self.allow.remove && entry.is_removable()
421    }
422
423    pub fn entries(&self) -> &Entries {
424        &self.entries
425    }
426
427    pub fn time_zone(&self) -> &TimeZone {
428        self.entries.time_zone()
429    }
430
431    pub fn view(&self) -> View {
432        self.view
433    }
434
435    /// A date in the period on show.
436    pub fn cursor(&self) -> Date {
437        self.cursor
438    }
439
440    pub fn today(&self) -> Date {
441        self.today
442    }
443
444    /// The time of the last [`Event::Tick`], which is where the now line
445    /// is drawn.
446    pub fn now(&self) -> Option<Timestamp> {
447        self.now
448    }
449
450    pub fn week_start(&self) -> Weekday {
451        self.week_start
452    }
453
454    pub fn selection(&self) -> Option<Selection> {
455        self.selection
456    }
457
458    /// The selected entry, if an entry is selected.
459    pub fn selected_entry(&self) -> Option<&Entry> {
460        match self.selection? {
461            Selection::Entry { entry, .. } => self.entries.get(entry),
462            _ => None,
463        }
464    }
465
466    /// The day the selection is on, if anything is selected.
467    pub fn selected_day(&self) -> Option<Date> {
468        Some(match self.selection? {
469            Selection::Day(date) | Selection::Slot { date, .. } => date,
470            Selection::Entry { start, .. } => self.entries.date_of(start),
471        })
472    }
473
474    pub fn is_selected(&self, selection: Selection) -> bool {
475        self.selection == Some(selection)
476    }
477
478    /// The first and last date on show. The month view includes the days
479    /// of neighbouring months that fill its first and last weeks.
480    pub fn range(&self) -> (Date, Date) {
481        match self.view {
482            View::Month => {
483                let weeks = layout::month_weeks(self.cursor, self.week_start);
484                let first = weeks.first().map_or(self.cursor, |week| week[0]);
485                let last = weeks.last().map_or(self.cursor, |week| week[6]);
486                (first, last)
487            }
488            View::Week => {
489                let week = layout::week_of(self.cursor, self.week_start);
490                (week[0], week[6])
491            }
492            View::Day => (self.cursor, self.cursor),
493            View::FourDays => (self.cursor, add_days(self.cursor, FOUR_DAYS - 1)),
494            View::Year => (self.cursor.first_of_year(), self.cursor.last_of_year()),
495            View::Agenda => (self.cursor.first_of_month(), self.cursor.last_of_month()),
496        }
497    }
498
499    /// The period on show in words, such as "November 2026".
500    pub fn title(&self) -> String {
501        let format = |date: Date, format: &str| date.strftime(format).to_string();
502        match self.view {
503            View::Month | View::Agenda => format(self.cursor, "%B %Y"),
504            View::Year => format(self.cursor, "%Y"),
505            View::Day => format(self.cursor, "%A %-d %B %Y"),
506            View::Week | View::FourDays => {
507                let (first, last) = self.range();
508                let start = if first.year() != last.year() {
509                    "%-d %b %Y"
510                } else if first.month() != last.month() {
511                    "%-d %b"
512                } else {
513                    "%-d"
514                };
515                format!("{} - {}", format(first, start), format(last, "%-d %b %Y"))
516            }
517        }
518    }
519
520    /// A shorter [`title`](State::title) for narrow screens, such as
521    /// "Thu 19 Nov 2026" for a day and "30 Nov - 6 Dec" for a week that
522    /// crosses months.
523    pub fn short_title(&self) -> String {
524        let format = |date: Date, format: &str| date.strftime(format).to_string();
525        match self.view {
526            View::Month | View::Agenda | View::Year => self.title(),
527            View::Day => format(self.cursor, "%a %-d %b %Y"),
528            View::Week | View::FourDays => {
529                let (first, last) = self.range();
530                if (first.year(), first.month()) == (last.year(), last.month()) {
531                    return self.title();
532                }
533                format!("{} - {}", format(first, "%-d %b"), format(last, "%-d %b"))
534            }
535        }
536    }
537
538    /// Applies an event and returns what the app may want to act on.
539    pub fn update(&mut self, event: Event) -> Option<Output> {
540        let output = self.apply(event);
541        if matches!(output, Some(Output::Viewed { .. })) {
542            self.announced = true;
543        }
544        output
545    }
546
547    fn apply(&mut self, event: Event) -> Option<Output> {
548        match event {
549            Event::Show(view) => {
550                if view == self.view {
551                    return None;
552                }
553                if let Some(day) = self.selected_day() {
554                    self.cursor = day;
555                }
556                self.set_view(view);
557                Some(self.viewed())
558            }
559            Event::Next => self.step(1),
560            Event::Previous => self.step(-1),
561            Event::Today => {
562                let before = (self.range(), self.selection);
563                self.cursor = self.today;
564                self.selection = Some(Selection::Day(self.today));
565                self.scrolls = self.scrolls.wrapping_add(1);
566                if before.0 != self.range() {
567                    return Some(self.viewed());
568                }
569                (before.1 != self.selection).then_some(Output::Selected(self.selection))
570            }
571            Event::GoTo(date) => self.show(date),
572            Event::Press(selection) => {
573                if self.selection == Some(selection) {
574                    return if self.second_press {
575                        self.activate()
576                    } else {
577                        None
578                    };
579                }
580                self.selection = Some(selection);
581                Some(Output::Selected(self.selection))
582            }
583            Event::DoublePress(selection) => {
584                let changed = self.selection != Some(selection);
585                self.selection = Some(selection);
586                self.activate()
587                    .or_else(|| changed.then_some(Output::Selected(self.selection)))
588            }
589            Event::Activate => self.activate(),
590            Event::Clear => {
591                self.selection.take()?;
592                Some(Output::Selected(None))
593            }
594            Event::MoveDay(days) => {
595                let from = self.selected_day().unwrap_or(self.cursor);
596                let date = add_days(from, days);
597                self.selection = Some(Selection::Day(date));
598                let (first, last) = self.range();
599                // The month view also shows days of its neighbours, and
600                // moving onto one of those turns the page.
601                let leaves_the_month = self.view == View::Month
602                    && (date.year(), date.month()) != (self.cursor.year(), self.cursor.month());
603                if date < first || date > last || leaves_the_month {
604                    self.cursor = date;
605                    return Some(self.viewed());
606                }
607                Some(Output::Selected(self.selection))
608            }
609            Event::NextEntry => self.cycle(1),
610            Event::PreviousEntry => self.cycle(-1),
611            Event::OpenDay(date) => {
612                if self.view == View::Day && self.cursor == date {
613                    return None;
614                }
615                self.cursor = date;
616                self.set_view(View::Day);
617                Some(self.viewed())
618            }
619            Event::Request(draft) => self.allow.create.then_some(Output::Requested(draft)),
620            Event::Reschedule { entry, start, to } => {
621                let (moved, new_start) = self.rescheduled(entry, start, to)?;
622                self.change(moved, Some(new_start))
623            }
624            Event::MoveDays { entry, start, days } => {
625                if days == 0 {
626                    return None;
627                }
628                let moved = self.moved_by_days(entry, days)?;
629                let new_start = shift_days(start, days, self.entries.time_zone());
630                self.change(moved, Some(new_start))
631            }
632            Event::Delete(id) => {
633                let entry = self.entries.get(id)?;
634                if !self.can_remove(entry) {
635                    return None;
636                }
637                if !self.proposals {
638                    return self.remove(id);
639                }
640                let changed = Changed {
641                    change: Change::Removed,
642                    entry: entry.clone(),
643                    before: None,
644                };
645                self.propose(Pending {
646                    changed,
647                    follow: None,
648                })
649            }
650            Event::Confirm => {
651                let pending = self.pending.take()?;
652                self.shown = None;
653                match pending.changed.change {
654                    Change::Removed => self.remove(pending.changed.entry.id()),
655                    Change::Created | Change::Updated => {
656                        self.insert(pending.changed.entry, pending.follow)
657                    }
658                }
659            }
660            Event::Discard => {
661                self.pending.take()?;
662                self.shown = None;
663                None
664            }
665            Event::Insert(entry) => {
666                // Inserting the proposed entry confirms it, selection and all.
667                let follow = self
668                    .pending
669                    .as_ref()
670                    .filter(|pending| pending.changed.entry == entry)
671                    .and_then(|pending| pending.follow);
672                self.clear_pending(entry.id());
673                self.insert(entry, follow)
674            }
675            Event::Remove(id) => {
676                self.clear_pending(id);
677                self.remove(id)
678            }
679            Event::Tick(now) => {
680                self.now = Some(now);
681                self.today = self.entries.date_of(now);
682                (!self.announced).then(|| self.viewed())
683            }
684        }
685    }
686
687    /// Makes a change from a gesture, or proposes it when proposals are
688    /// on. A selection on the entry follows to the start in `follow`.
689    fn change(&mut self, moved: Entry, follow: Option<Timestamp>) -> Option<Output> {
690        let before = self.entries.get(moved.id())?;
691        if !self.can_move(before) || *before == moved {
692            return None;
693        }
694        if !self.proposals {
695            return self.insert(moved, follow);
696        }
697        let changed = Changed {
698            change: Change::Updated,
699            entry: moved,
700            before: Some(before.clone()),
701        };
702        self.propose(Pending { changed, follow })
703    }
704
705    fn propose(&mut self, pending: Pending) -> Option<Output> {
706        let output = Output::Proposed(Box::new(pending.changed.clone()));
707        self.shown = match pending.changed.change {
708            Change::Removed => None,
709            Change::Created | Change::Updated => {
710                let mut shown = self.entries.clone();
711                let _ = shown.insert(pending.changed.entry.clone());
712                Some(shown)
713            }
714        };
715        self.pending = Some(pending);
716        Some(output)
717    }
718
719    fn clear_pending(&mut self, id: EntryId) {
720        if self.is_preview(id) {
721            self.pending = None;
722            self.shown = None;
723        }
724    }
725
726    fn insert(&mut self, entry: Entry, follow: Option<Timestamp>) -> Option<Output> {
727        let id = entry.id();
728        let changed = self.entries.insert(entry)?;
729        if let Some(to) = follow
730            && matches!(self.selection, Some(Selection::Entry { entry, .. }) if entry == id)
731        {
732            self.selection = Some(Selection::Entry {
733                entry: id,
734                start: to,
735            });
736        }
737        Some(report(changed))
738    }
739
740    fn remove(&mut self, id: EntryId) -> Option<Output> {
741        let changed = self.entries.remove(id)?;
742        if matches!(self.selection, Some(Selection::Entry { entry, .. }) if entry == id) {
743            self.selection = None;
744        }
745        Some(report(changed))
746    }
747
748    fn set_view(&mut self, view: View) {
749        let timed = |view: View| matches!(view, View::Day | View::Week | View::FourDays);
750        if timed(view) && !timed(self.view) {
751            self.scrolls = self.scrolls.wrapping_add(1);
752        }
753        self.view = view;
754    }
755
756    fn viewed(&self) -> Output {
757        let (first, last) = self.range();
758        Output::Viewed {
759            view: self.view,
760            first,
761            last,
762        }
763    }
764
765    fn show(&mut self, date: Date) -> Option<Output> {
766        let before = self.range();
767        self.cursor = date;
768        (before != self.range()).then(|| self.viewed())
769    }
770
771    fn step(&mut self, direction: i32) -> Option<Output> {
772        let months = |count: i32| {
773            self.cursor
774                .checked_add(i64::from(count).months())
775                .unwrap_or(self.cursor)
776        };
777        let target = match self.view {
778            View::Month | View::Agenda => months(direction),
779            View::Year => months(12 * direction),
780            View::Week => add_days(self.cursor, 7 * direction),
781            View::FourDays => add_days(self.cursor, FOUR_DAYS * direction),
782            View::Day => add_days(self.cursor, direction),
783        };
784        self.show(target)
785    }
786
787    fn activate(&mut self) -> Option<Output> {
788        let time_zone = self.entries.time_zone();
789        if let Some(Selection::Entry { entry, start }) = self.selection {
790            self.entries.get(entry)?;
791            return Some(Output::Opened { entry, start });
792        }
793        if !self.allow.create {
794            return None;
795        }
796        Some(match self.selection {
797            Some(Selection::Entry { entry, start }) => Output::Opened { entry, start },
798            Some(Selection::Slot { date, minute }) => {
799                let end = minute.saturating_add(SLOT_MINUTES).min(DAY_MINUTES);
800                Output::Requested(Draft {
801                    when: When::timed(
802                        instant_at(date, minute, time_zone),
803                        instant_at(date, end, time_zone),
804                    ),
805                })
806            }
807            Some(Selection::Day(date)) => Output::Requested(Draft {
808                when: When::day(date),
809            }),
810            None => Output::Requested(Draft {
811                when: When::day(self.cursor),
812            }),
813        })
814    }
815
816    /// Moves the selection through the entries of the selected day, or in
817    /// the schedule through every entry it lists.
818    fn cycle(&mut self, direction: i32) -> Option<Output> {
819        let occurrences = if self.view == View::Agenda {
820            let (first, last) = self.range();
821            self.entries.between(first, last)
822        } else {
823            let day = self.selected_day().unwrap_or(self.cursor);
824            self.entries.on(day)
825        };
826        let count = i32::try_from(occurrences.len()).ok().filter(|n| *n > 0)?;
827        let current = occurrences.iter().position(|occurrence| {
828            self.is_selected(Selection::Entry {
829                entry: occurrence.entry,
830                start: occurrence.start,
831            })
832        });
833        let next = match current {
834            Some(index) => (i32::try_from(index).ok()? + direction).rem_euclid(count),
835            None if direction < 0 => count - 1,
836            None => 0,
837        };
838        let occurrence = occurrences.get(usize::try_from(next).ok()?)?;
839        let selection = Selection::Entry {
840            entry: occurrence.entry,
841            start: occurrence.start,
842        };
843        if self.selection == Some(selection) {
844            return None;
845        }
846        self.selection = Some(selection);
847        Some(Output::Selected(self.selection))
848    }
849
850    /// `entry` with the occurrence starting at `start` moved to `to`, and
851    /// where that occurrence now starts. A whole-day entry moves by the
852    /// days between `start` and the new start.
853    fn rescheduled(
854        &self,
855        id: EntryId,
856        start: Timestamp,
857        to: (Timestamp, Timestamp),
858    ) -> Option<(Entry, Timestamp)> {
859        let entry = self.entries.get(id)?;
860        let (new_start, new_end) = (to.0.min(to.1), to.0.max(to.1));
861        let When::Timed {
862            start: first_start, ..
863        } = entry.when()
864        else {
865            let days = days_between(self.entries.date_of(start), self.entries.date_of(new_start));
866            let moved = self.moved_by_days(id, days)?;
867            return Some((moved, shift_days(start, days, self.entries.time_zone())));
868        };
869        let shift: SignedDuration = new_start.duration_since(start);
870        let first = first_start.checked_add(shift).ok()?;
871        let end = first.checked_add(new_end.duration_since(new_start)).ok()?;
872        Some((
873            entry.clone().rescheduled(When::timed(first, end)),
874            new_start,
875        ))
876    }
877
878    /// `entry` moved by whole days, keeping a timed entry's time of day
879    /// and a whole-day entry's length.
880    fn moved_by_days(&self, id: EntryId, days: i32) -> Option<Entry> {
881        let entry = self.entries.get(id)?;
882        let when = match entry.when() {
883            When::AllDay { first, last } => {
884                When::all_day(add_days(first, days), add_days(last, days))
885            }
886            When::Timed { start, end } => {
887                let moved = shift_days(start, days, self.entries.time_zone());
888                When::timed(moved, moved.checked_add(end.duration_since(start)).ok()?)
889            }
890        };
891        Some(entry.clone().rescheduled(when))
892    }
893}
894
895/// `instant` moved by whole days at the same local time in `time_zone`.
896fn shift_days(instant: Timestamp, days: i32, time_zone: &TimeZone) -> Timestamp {
897    instant
898        .to_zoned_datetime(time_zone.clone())
899        .checked_add(i64::from(days).days())
900        .map(|zoned| zoned.timestamp())
901        .unwrap_or(instant)
902}
903
904/// How many days `to` is after `from`, negative when before.
905pub(super) fn days_between(from: Date, to: Date) -> i32 {
906    from.until(to).ok().map(|span| span.get_days()).unwrap_or(0)
907}
908
909fn report(changed: Changed) -> Output {
910    Output::Changed(Box::new(changed))
911}
912
913/// What a calendar keyboard shortcut does.
914#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
915pub enum Action {
916    Next,
917    Previous,
918    Today,
919    PreviousDay,
920    NextDay,
921    PreviousWeek,
922    NextWeek,
923    PreviousEntry,
924    NextEntry,
925    Month,
926    Week,
927    Day,
928    Agenda,
929    Year,
930    FourDays,
931    Activate,
932    Remove,
933    Close,
934}
935
936impl Action {
937    /// The [`Event`] this action sends to `state`, or `None` when it would
938    /// do nothing: removing with no entry selected, closing with nothing
939    /// selected, or switching to the view already on show.
940    pub fn event(self, state: &State) -> Option<Event> {
941        let show = |view: View| (state.view() != view).then_some(Event::Show(view));
942        match self {
943            Action::Next => Some(Event::Next),
944            Action::Previous => Some(Event::Previous),
945            Action::Today => Some(Event::Today),
946            // The schedule lists entries, not days, so there the arrows
947            // step through the entries.
948            Action::PreviousDay | Action::PreviousWeek if state.view() == View::Agenda => {
949                Some(Event::PreviousEntry)
950            }
951            Action::NextDay | Action::NextWeek if state.view() == View::Agenda => {
952                Some(Event::NextEntry)
953            }
954            Action::PreviousDay => Some(Event::MoveDay(-1)),
955            Action::NextDay => Some(Event::MoveDay(1)),
956            Action::PreviousWeek => Some(Event::MoveDay(-7)),
957            Action::NextWeek => Some(Event::MoveDay(7)),
958            Action::PreviousEntry => Some(Event::PreviousEntry),
959            Action::NextEntry => Some(Event::NextEntry),
960            Action::Month => show(View::Month),
961            Action::Week => show(View::Week),
962            Action::Day => show(View::Day),
963            Action::Agenda => show(View::Agenda),
964            Action::Year => show(View::Year),
965            Action::FourDays => show(View::FourDays),
966            Action::Activate => (state.selected_entry().is_some() || state.allow().create)
967                .then_some(Event::Activate),
968            Action::Remove => state
969                .selected_entry()
970                .filter(|entry| state.can_remove(entry))
971                .map(|entry| Event::Delete(entry.id())),
972            Action::Close => state.selection().map(|_| Event::Clear),
973        }
974    }
975}
976
977impl keys::Action for Action {
978    const ALL: &'static [Self] = &[
979        Action::Previous,
980        Action::Next,
981        Action::Today,
982        Action::PreviousDay,
983        Action::NextDay,
984        Action::PreviousWeek,
985        Action::NextWeek,
986        Action::PreviousEntry,
987        Action::NextEntry,
988        Action::Month,
989        Action::Week,
990        Action::Day,
991        Action::Agenda,
992        Action::Year,
993        Action::FourDays,
994        Action::Activate,
995        Action::Remove,
996        Action::Close,
997    ];
998
999    fn defaults() -> Keymap<Self> {
1000        default_keymap()
1001    }
1002
1003    fn name(self) -> &'static str {
1004        match self {
1005            Action::Next => "Next",
1006            Action::Previous => "Previous",
1007            Action::Today => "Today",
1008            Action::PreviousDay => "Previous day",
1009            Action::NextDay => "Next day",
1010            Action::PreviousWeek => "Previous week",
1011            Action::NextWeek => "Next week",
1012            Action::PreviousEntry => "Previous entry",
1013            Action::NextEntry => "Next entry",
1014            Action::Month => "Month",
1015            Action::Week => "Week",
1016            Action::Day => "Day",
1017            Action::Agenda => "Schedule",
1018            Action::Year => "Year",
1019            Action::FourDays => "4 days",
1020            Action::Activate => "Activate",
1021            Action::Remove => "Remove",
1022            Action::Close => "Close",
1023        }
1024    }
1025
1026    fn description(self) -> &'static str {
1027        match self {
1028            Action::Next => "Shows the next period: a day, a week, four days, a month or a year.",
1029            Action::Previous => "Shows the previous period.",
1030            Action::Today => "Goes to today and selects it.",
1031            Action::PreviousDay => "Selects the day before.",
1032            Action::NextDay => "Selects the day after.",
1033            Action::PreviousWeek => "Selects the same day a week earlier.",
1034            Action::NextWeek => "Selects the same day a week later.",
1035            Action::PreviousEntry => "Selects the previous entry on the selected day.",
1036            Action::NextEntry => "Selects the next entry on the selected day.",
1037            Action::Month => "Switches to the month view.",
1038            Action::Week => "Switches to the week view.",
1039            Action::Day => "Switches to the day view.",
1040            Action::Agenda => "Switches to the schedule, a list of the month's entries.",
1041            Action::Year => "Switches to the year view.",
1042            Action::FourDays => "Switches to the four day view.",
1043            Action::Activate => {
1044                "Opens the selected entry, or asks for a new one on the selected day."
1045            }
1046            Action::Remove => "Removes the selected entry.",
1047            Action::Close => "Clears the selection.",
1048        }
1049    }
1050}
1051
1052/// The default calendar shortcuts:
1053///
1054/// | Keys | Action |
1055/// | --- | --- |
1056/// | `PageUp` | [`Action::Previous`] |
1057/// | `PageDown` | [`Action::Next`] |
1058/// | `T` | [`Action::Today`] |
1059/// | `ArrowLeft` | [`Action::PreviousDay`] |
1060/// | `ArrowRight` | [`Action::NextDay`] |
1061/// | `ArrowUp` | [`Action::PreviousWeek`] |
1062/// | `ArrowDown` | [`Action::NextWeek`] |
1063/// | `Alt+ArrowUp` | [`Action::PreviousEntry`] |
1064/// | `Alt+ArrowDown` | [`Action::NextEntry`] |
1065/// | `M` | [`Action::Month`] |
1066/// | `W` | [`Action::Week`] |
1067/// | `D` | [`Action::Day`] |
1068/// | `A` | [`Action::Agenda`] |
1069/// | `Y` | [`Action::Year`] |
1070/// | `X` | [`Action::FourDays`] |
1071/// | `Enter` | [`Action::Activate`] |
1072/// | `Delete`, `Backspace` | [`Action::Remove`] |
1073/// | `Escape` | [`Action::Close`] |
1074///
1075/// The arrow and page keys are shared with tabs, sliders and pagination,
1076/// so on a screen with several of those resolve the calendar's keymap only
1077/// while the calendar is what the user is working in.
1078pub fn default_keymap() -> Keymap<Action> {
1079    Keymap::new()
1080        .bind(Chord::named(Named::PageUp), Action::Previous)
1081        .bind(Chord::named(Named::PageDown), Action::Next)
1082        .bind(Chord::character('t'), Action::Today)
1083        .bind(Chord::named(Named::ArrowLeft), Action::PreviousDay)
1084        .bind(Chord::named(Named::ArrowRight), Action::NextDay)
1085        .bind(Chord::named(Named::ArrowUp), Action::PreviousWeek)
1086        .bind(Chord::named(Named::ArrowDown), Action::NextWeek)
1087        .bind(Chord::named(Named::ArrowUp).alt(), Action::PreviousEntry)
1088        .bind(Chord::named(Named::ArrowDown).alt(), Action::NextEntry)
1089        .bind(Chord::character('m'), Action::Month)
1090        .bind(Chord::character('w'), Action::Week)
1091        .bind(Chord::character('d'), Action::Day)
1092        .bind(Chord::character('a'), Action::Agenda)
1093        .bind(Chord::character('y'), Action::Year)
1094        .bind(Chord::character('x'), Action::FourDays)
1095        .bind(Chord::named(Named::Enter), Action::Activate)
1096        .bind(Chord::named(Named::Delete), Action::Remove)
1097        .bind(Chord::named(Named::Backspace), Action::Remove)
1098        .bind(Chord::named(Named::Escape), Action::Close)
1099}
1100
1101#[cfg(test)]
1102mod tests {
1103    use super::*;
1104    use crate::data::calendar::entry::Change;
1105    use crate::data::calendar::repeat::Repeat;
1106    use jiff::civil::date;
1107
1108    /// Thursday 19 November 2026.
1109    fn today() -> Date {
1110        date(2026, 11, 19)
1111    }
1112
1113    fn at(day: i8, hour: i8) -> Timestamp {
1114        instant_at(
1115            date(2026, 11, day),
1116            u16::try_from(hour).unwrap_or(0) * 60,
1117            &TimeZone::UTC,
1118        )
1119    }
1120
1121    fn meeting(id: u64, day: i8, hour: i8) -> Entry {
1122        Entry::new(EntryId(id), "Meeting", at(day, hour), at(day, hour + 1))
1123    }
1124
1125    fn state() -> State {
1126        State::new(today()).with_entries(Entries::utc().with([
1127            meeting(1, 19, 9),
1128            meeting(2, 19, 14),
1129            meeting(3, 20, 9),
1130        ]))
1131    }
1132
1133    fn entry(id: u64, day: i8, hour: i8) -> Selection {
1134        Selection::Entry {
1135            entry: EntryId(id),
1136            start: at(day, hour),
1137        }
1138    }
1139
1140    #[test]
1141    fn a_new_calendar_shows_the_month_of_today_with_nothing_selected() {
1142        let state = State::new(today());
1143        assert_eq!(state.view(), View::Month);
1144        assert_eq!(state.cursor(), today());
1145        assert_eq!(state.today(), today());
1146        assert_eq!(state.now(), None);
1147        assert_eq!(state.selection(), None);
1148        assert_eq!(state.selected_day(), None);
1149        assert_eq!(state.week_start(), Weekday::Monday);
1150        assert!(state.entries().is_empty());
1151        assert_eq!(state.time_zone(), &TimeZone::UTC);
1152    }
1153
1154    #[test]
1155    fn at_takes_today_from_the_time_and_the_time_zone() {
1156        let Ok(tokyo) = TimeZone::get("Asia/Tokyo") else {
1157            panic!("the time zone database is bundled for tests");
1158        };
1159        let state = State::at(at(19, 20), Entries::new(tokyo));
1160        assert_eq!(state.today(), date(2026, 11, 20));
1161        assert_eq!(state.now(), Some(at(19, 20)));
1162    }
1163
1164    #[test]
1165    fn builder_options() {
1166        let state = State::new(today())
1167            .with_view(View::Week)
1168            .with_week_start(Weekday::Sunday)
1169            .with_cursor(date(2026, 12, 1))
1170            .with_selection(Selection::Day(date(2026, 12, 2)));
1171        assert_eq!(state.view(), View::Week);
1172        assert_eq!(state.week_start(), Weekday::Sunday);
1173        assert_eq!(state.cursor(), date(2026, 12, 1));
1174        assert_eq!(state.selected_day(), Some(date(2026, 12, 2)));
1175    }
1176
1177    #[test]
1178    fn every_view_has_a_label_a_range_and_a_title() {
1179        let mut state = state();
1180        let expected = [
1181            (
1182                View::Month,
1183                (date(2026, 10, 26), date(2026, 12, 6)),
1184                "November 2026",
1185            ),
1186            (
1187                View::Week,
1188                (date(2026, 11, 16), date(2026, 11, 22)),
1189                "16 - 22 Nov 2026",
1190            ),
1191            (View::Day, (today(), today()), "Thursday 19 November 2026"),
1192            (
1193                View::Agenda,
1194                (date(2026, 11, 1), date(2026, 11, 30)),
1195                "November 2026",
1196            ),
1197            (View::Year, (date(2026, 1, 1), date(2026, 12, 31)), "2026"),
1198            (
1199                View::FourDays,
1200                (today(), date(2026, 11, 22)),
1201                "19 - 22 Nov 2026",
1202            ),
1203        ];
1204        assert_eq!(View::ALL.len(), expected.len());
1205        for (view, range, title) in expected {
1206            let _ = state.update(Event::Show(view));
1207            assert_eq!(state.view(), view);
1208            assert_eq!(state.range(), range, "{view:?}");
1209            assert_eq!(state.title(), title, "{view:?}");
1210            assert_eq!(view.to_string(), view.label());
1211        }
1212        let labels: Vec<_> = View::ALL.iter().map(|view| view.label()).collect();
1213        assert_eq!(
1214            labels,
1215            vec!["Day", "Week", "Month", "Year", "Schedule", "4 days"]
1216        );
1217    }
1218
1219    #[test]
1220    fn a_year_steps_by_years_and_four_days_by_four() {
1221        let mut year = State::new(today()).with_view(View::Year);
1222        let _ = year.update(Event::Next);
1223        assert_eq!(year.cursor(), date(2027, 11, 19));
1224        assert_eq!(year.short_title(), "2027");
1225        let _ = year.update(Event::Previous);
1226        let _ = year.update(Event::Previous);
1227        assert_eq!(year.cursor(), date(2025, 11, 19));
1228
1229        let mut days = State::new(date(2026, 11, 29)).with_view(View::FourDays);
1230        assert_eq!(days.short_title(), "29 Nov - 2 Dec");
1231        let _ = days.update(Event::Next);
1232        assert_eq!(days.range(), (date(2026, 12, 3), date(2026, 12, 6)));
1233        let _ = days.update(Event::Previous);
1234        let _ = days.update(Event::Previous);
1235        assert_eq!(days.cursor(), date(2026, 11, 25));
1236
1237        // A day moved out of the four starts the next four.
1238        let mut days = State::new(today()).with_view(View::FourDays);
1239        let _ = days.update(Event::MoveDay(3));
1240        assert_eq!(days.cursor(), today());
1241        let _ = days.update(Event::MoveDay(1));
1242        assert_eq!(days.cursor(), date(2026, 11, 23));
1243    }
1244
1245    #[test]
1246    fn week_titles_name_both_months_or_years_when_they_differ() {
1247        let state = State::new(date(2026, 12, 1)).with_view(View::Week);
1248        assert_eq!(state.title(), "30 Nov - 6 Dec 2026");
1249        let state = State::new(date(2026, 12, 31)).with_view(View::Week);
1250        assert_eq!(state.title(), "28 Dec 2026 - 3 Jan 2027");
1251    }
1252
1253    #[test]
1254    fn short_titles_fit_a_phone() {
1255        let mut state = State::new(today());
1256        assert_eq!(state.short_title(), "November 2026");
1257        let _ = state.update(Event::Show(View::Agenda));
1258        assert_eq!(state.short_title(), "November 2026");
1259        let _ = state.update(Event::Show(View::Day));
1260        assert_eq!(state.short_title(), "Thu 19 Nov 2026");
1261        let _ = state.update(Event::Show(View::Week));
1262        assert_eq!(state.short_title(), "16 - 22 Nov 2026");
1263
1264        let across_months = State::new(date(2026, 12, 1)).with_view(View::Week);
1265        assert_eq!(across_months.short_title(), "30 Nov - 6 Dec");
1266        let across_years = State::new(date(2026, 12, 31)).with_view(View::Week);
1267        assert_eq!(across_years.short_title(), "28 Dec - 3 Jan");
1268    }
1269
1270    #[test]
1271    fn the_week_follows_the_day_weeks_start_on() {
1272        let state = State::new(today())
1273            .with_view(View::Week)
1274            .with_week_start(Weekday::Sunday);
1275        assert_eq!(state.range(), (date(2026, 11, 15), date(2026, 11, 21)));
1276    }
1277
1278    #[test]
1279    fn next_and_previous_step_by_what_the_view_shows() {
1280        let mut state = state();
1281        assert_eq!(
1282            state.update(Event::Next),
1283            Some(Output::Viewed {
1284                view: View::Month,
1285                first: date(2026, 11, 30),
1286                last: date(2027, 1, 3)
1287            })
1288        );
1289        assert_eq!(state.cursor(), date(2026, 12, 19));
1290        let _ = state.update(Event::Previous);
1291        assert_eq!(state.cursor(), today());
1292
1293        let _ = state.update(Event::Show(View::Week));
1294        let _ = state.update(Event::Next);
1295        assert_eq!(state.cursor(), date(2026, 11, 26));
1296        let _ = state.update(Event::Show(View::Day));
1297        let _ = state.update(Event::Previous);
1298        assert_eq!(state.cursor(), date(2026, 11, 25));
1299        let _ = state.update(Event::Show(View::Agenda));
1300        let _ = state.update(Event::Next);
1301        assert_eq!(state.cursor(), date(2026, 12, 25));
1302    }
1303
1304    #[test]
1305    fn stepping_a_month_from_the_31st_lands_on_the_last_day() {
1306        let mut state = State::new(date(2027, 1, 31));
1307        let _ = state.update(Event::Next);
1308        assert_eq!(state.cursor(), date(2027, 2, 28));
1309    }
1310
1311    #[test]
1312    fn showing_the_view_already_on_show_does_nothing() {
1313        let mut state = state();
1314        assert_eq!(state.update(Event::Show(View::Month)), None);
1315        assert!(state.update(Event::Show(View::Week)).is_some());
1316    }
1317
1318    #[test]
1319    fn switching_view_goes_to_the_selected_day() {
1320        let mut state = state();
1321        let _ = state.update(Event::Press(Selection::Day(date(2026, 11, 3))));
1322        let _ = state.update(Event::Show(View::Day));
1323        assert_eq!(state.cursor(), date(2026, 11, 3));
1324    }
1325
1326    #[test]
1327    fn go_to_reports_only_when_the_period_changes() {
1328        let mut state = state();
1329        assert_eq!(state.update(Event::GoTo(date(2026, 11, 2))), None);
1330        assert_eq!(state.cursor(), date(2026, 11, 2));
1331        assert!(matches!(
1332            state.update(Event::GoTo(date(2027, 3, 1))),
1333            Some(Output::Viewed { .. })
1334        ));
1335        assert_eq!(state.selection(), None);
1336    }
1337
1338    #[test]
1339    fn today_comes_back_and_selects_today() {
1340        let mut state = state();
1341        assert_eq!(
1342            state.update(Event::Today),
1343            Some(Output::Selected(Some(Selection::Day(today()))))
1344        );
1345        assert_eq!(state.update(Event::Today), None);
1346        let _ = state.update(Event::Next);
1347        assert!(matches!(
1348            state.update(Event::Today),
1349            Some(Output::Viewed { .. })
1350        ));
1351        assert_eq!(state.cursor(), today());
1352    }
1353
1354    #[test]
1355    fn the_first_press_selects_and_the_second_activates() {
1356        let mut state = state();
1357        let day = Selection::Day(date(2026, 11, 3));
1358        assert_eq!(
1359            state.update(Event::Press(day)),
1360            Some(Output::Selected(Some(day)))
1361        );
1362        assert!(state.is_selected(day));
1363        assert_eq!(
1364            state.update(Event::Press(day)),
1365            Some(Output::Requested(Draft {
1366                when: When::day(date(2026, 11, 3))
1367            }))
1368        );
1369
1370        let picked = entry(1, 19, 9);
1371        assert_eq!(
1372            state.update(Event::Press(picked)),
1373            Some(Output::Selected(Some(picked)))
1374        );
1375        assert_eq!(state.selected_entry().map(Entry::id), Some(EntryId(1)));
1376        assert_eq!(state.selected_day(), Some(today()));
1377        assert_eq!(
1378            state.update(Event::Press(picked)),
1379            Some(Output::Opened {
1380                entry: EntryId(1),
1381                start: at(19, 9)
1382            })
1383        );
1384    }
1385
1386    #[test]
1387    fn a_slot_asks_for_an_hour_and_stops_at_midnight() {
1388        let mut state = state();
1389        let slot = Selection::Slot {
1390            date: today(),
1391            minute: 600,
1392        };
1393        let _ = state.update(Event::Press(slot));
1394        assert_eq!(
1395            state.update(Event::Activate),
1396            Some(Output::Requested(Draft {
1397                when: When::timed(at(19, 10), at(19, 11))
1398            }))
1399        );
1400        let late = Selection::Slot {
1401            date: today(),
1402            minute: 1410,
1403        };
1404        let _ = state.update(Event::Press(late));
1405        assert_eq!(
1406            state.update(Event::Activate),
1407            Some(Output::Requested(Draft {
1408                when: When::timed(instant_at(today(), 1410, &TimeZone::UTC), at(20, 0))
1409            }))
1410        );
1411    }
1412
1413    #[test]
1414    fn activating_with_nothing_selected_asks_for_the_day_on_show() {
1415        let mut state = state();
1416        assert_eq!(
1417            state.update(Event::Activate),
1418            Some(Output::Requested(Draft {
1419                when: When::day(today())
1420            }))
1421        );
1422    }
1423
1424    #[test]
1425    fn activating_an_entry_that_is_gone_does_nothing() {
1426        let mut state = state().with_selection(entry(9, 19, 9));
1427        assert_eq!(state.update(Event::Activate), None);
1428        assert_eq!(state.selected_entry(), None);
1429    }
1430
1431    #[test]
1432    fn everything_is_allowed_unless_set() {
1433        assert_eq!(Allow::default(), Allow::ALL);
1434        assert_eq!(state().allow(), Allow::ALL);
1435        assert_eq!(state().read_only().allow(), Allow::NONE);
1436        let mut state = state();
1437        state.set_allow(Allow {
1438            remove: false,
1439            ..Allow::ALL
1440        });
1441        assert!(state.allow().create && !state.allow().remove);
1442    }
1443
1444    #[test]
1445    fn a_read_only_calendar_can_be_looked_through_but_not_changed() {
1446        let mut state = state().read_only();
1447        let day = Selection::Day(date(2026, 11, 3));
1448        let slot = Selection::Slot {
1449            date: today(),
1450            minute: 600,
1451        };
1452
1453        // Selecting and moving about still work.
1454        assert_eq!(
1455            state.update(Event::Press(day)),
1456            Some(Output::Selected(Some(day)))
1457        );
1458        assert!(state.update(Event::Next).is_some());
1459        assert!(state.update(Event::Show(View::Week)).is_some());
1460
1461        // A second press, Enter or a drag asks for nothing.
1462        let _ = state.update(Event::Press(day));
1463        assert_eq!(state.update(Event::Press(day)), None);
1464        assert_eq!(state.update(Event::Activate), None);
1465        let _ = state.update(Event::Press(slot));
1466        assert_eq!(state.update(Event::Press(slot)), None);
1467        let draft = Draft {
1468            when: When::day(today()),
1469        };
1470        assert_eq!(state.update(Event::Request(draft)), None);
1471        let _ = state.update(Event::Clear);
1472        assert_eq!(state.update(Event::Activate), None);
1473        assert_eq!(Action::Activate.event(&state), None);
1474
1475        // An entry can still be opened, but not dragged or removed by key.
1476        let picked = entry(1, 19, 9);
1477        let _ = state.update(Event::Press(picked));
1478        assert_eq!(
1479            state.update(Event::Press(picked)),
1480            Some(Output::Opened {
1481                entry: EntryId(1),
1482                start: at(19, 9)
1483            })
1484        );
1485        assert_eq!(Action::Activate.event(&state), Some(Event::Activate));
1486        assert_eq!(Action::Remove.event(&state), None);
1487        let drag = Event::Reschedule {
1488            entry: EntryId(1),
1489            start: at(19, 9),
1490            to: (at(20, 9), at(20, 10)),
1491        };
1492        assert_eq!(state.update(drag), None);
1493        assert_eq!(
1494            state.entries().get(EntryId(1)).map(Entry::when),
1495            Some(meeting(1, 19, 9).when())
1496        );
1497    }
1498
1499    #[test]
1500    fn the_app_can_still_change_a_read_only_calendar() {
1501        let mut state = state().read_only();
1502        assert!(state.update(Event::Insert(meeting(7, 21, 9))).is_some());
1503        assert!(state.update(Event::Insert(meeting(7, 22, 9))).is_some());
1504        assert!(state.update(Event::Remove(EntryId(7))).is_some());
1505        assert_eq!(state.entries().len(), 3);
1506    }
1507
1508    #[test]
1509    fn each_permission_stands_alone() {
1510        let mut state = state().with_allow(Allow {
1511            create: false,
1512            ..Allow::ALL
1513        });
1514        let _ = state.update(Event::Press(entry(1, 19, 9)));
1515        assert_eq!(
1516            Action::Remove.event(&state),
1517            Some(Event::Delete(EntryId(1)))
1518        );
1519        let drag = Event::Reschedule {
1520            entry: EntryId(1),
1521            start: at(19, 9),
1522            to: (at(20, 9), at(20, 10)),
1523        };
1524        assert!(state.update(drag).is_some());
1525        let _ = state.update(Event::Clear);
1526        assert_eq!(state.update(Event::Activate), None);
1527    }
1528
1529    #[test]
1530    fn clear_reports_only_when_something_was_selected() {
1531        let mut state = state();
1532        assert_eq!(state.update(Event::Clear), None);
1533        let _ = state.update(Event::Press(Selection::Day(today())));
1534        assert_eq!(state.update(Event::Clear), Some(Output::Selected(None)));
1535        assert_eq!(state.selection(), None);
1536    }
1537
1538    #[test]
1539    fn moving_the_day_starts_from_the_period_on_show_and_turns_the_page() {
1540        let mut state = state();
1541        assert_eq!(
1542            state.update(Event::MoveDay(1)),
1543            Some(Output::Selected(Some(Selection::Day(date(2026, 11, 20)))))
1544        );
1545        let _ = state.update(Event::MoveDay(7));
1546        assert_eq!(state.selected_day(), Some(date(2026, 11, 27)));
1547        assert_eq!(state.cursor(), today(), "still in November");
1548
1549        // 4 December is in the month grid, but belongs to the next month.
1550        assert!(matches!(
1551            state.update(Event::MoveDay(7)),
1552            Some(Output::Viewed { .. })
1553        ));
1554        assert_eq!(state.cursor(), date(2026, 12, 4));
1555
1556        let mut week = State::new(today()).with_view(View::Week);
1557        let _ = week.update(Event::MoveDay(3));
1558        assert_eq!(week.cursor(), today());
1559        assert!(matches!(
1560            week.update(Event::MoveDay(1)),
1561            Some(Output::Viewed { .. })
1562        ));
1563        assert_eq!(week.cursor(), date(2026, 11, 23));
1564    }
1565
1566    #[test]
1567    fn entries_of_the_selected_day_cycle_and_wrap() {
1568        let mut state = state();
1569        assert_eq!(
1570            state.update(Event::NextEntry),
1571            Some(Output::Selected(Some(entry(1, 19, 9))))
1572        );
1573        let _ = state.update(Event::NextEntry);
1574        assert!(state.is_selected(entry(2, 19, 14)));
1575        let _ = state.update(Event::NextEntry);
1576        assert!(state.is_selected(entry(1, 19, 9)), "wraps");
1577        let _ = state.update(Event::PreviousEntry);
1578        assert!(state.is_selected(entry(2, 19, 14)));
1579
1580        let mut from_the_end = self::state();
1581        let _ = from_the_end.update(Event::PreviousEntry);
1582        assert!(from_the_end.is_selected(entry(2, 19, 14)));
1583
1584        let mut one = self::state().with_selection(Selection::Day(date(2026, 11, 20)));
1585        let _ = one.update(Event::NextEntry);
1586        assert_eq!(one.update(Event::NextEntry), None, "the only entry");
1587
1588        let mut none = self::state().with_selection(Selection::Day(date(2026, 11, 1)));
1589        assert_eq!(none.update(Event::NextEntry), None);
1590    }
1591
1592    #[test]
1593    fn the_schedule_steps_through_all_its_entries_with_the_arrows() {
1594        let mut state = state().with_view(View::Agenda);
1595        for action in [Action::NextDay, Action::NextWeek] {
1596            assert_eq!(action.event(&state), Some(Event::NextEntry), "{action:?}");
1597        }
1598        for action in [Action::PreviousDay, Action::PreviousWeek] {
1599            assert_eq!(
1600                action.event(&state),
1601                Some(Event::PreviousEntry),
1602                "{action:?}"
1603            );
1604        }
1605        let _ = state.update(Event::NextEntry);
1606        let _ = state.update(Event::NextEntry);
1607        let _ = state.update(Event::NextEntry);
1608        assert!(state.is_selected(entry(3, 20, 9)), "on to the next day");
1609        let _ = state.update(Event::NextEntry);
1610        assert!(state.is_selected(entry(1, 19, 9)), "and round again");
1611    }
1612
1613    #[test]
1614    fn open_day_switches_to_the_day_view() {
1615        let mut state = state();
1616        assert_eq!(
1617            state.update(Event::OpenDay(date(2026, 11, 3))),
1618            Some(Output::Viewed {
1619                view: View::Day,
1620                first: date(2026, 11, 3),
1621                last: date(2026, 11, 3)
1622            })
1623        );
1624        assert_eq!(state.view(), View::Day);
1625        assert_eq!(state.update(Event::OpenDay(date(2026, 11, 3))), None);
1626    }
1627
1628    #[test]
1629    fn a_request_is_passed_on_and_adds_nothing() {
1630        let mut state = state();
1631        let draft = Draft {
1632            when: When::timed(at(19, 11), at(19, 12)),
1633        };
1634        assert_eq!(
1635            state.update(Event::Request(draft)),
1636            Some(Output::Requested(draft))
1637        );
1638        assert_eq!(state.entries().len(), 3);
1639    }
1640
1641    #[test]
1642    fn insert_and_remove_report_the_change() {
1643        let mut state = state();
1644        let change = |output: Option<Output>| match output {
1645            Some(Output::Changed(changed)) => Some(changed.change),
1646            _ => None,
1647        };
1648        let created = state.update(Event::Insert(meeting(4, 21, 9)));
1649        assert_eq!(change(created), Some(Change::Created));
1650        let updated = state.update(Event::Insert(meeting(4, 22, 9)));
1651        assert_eq!(change(updated), Some(Change::Updated));
1652        assert_eq!(state.update(Event::Insert(meeting(4, 22, 9))), None);
1653
1654        let _ = state.update(Event::Press(entry(4, 22, 9)));
1655        let removed = state.update(Event::Remove(EntryId(4)));
1656        assert_eq!(change(removed), Some(Change::Removed));
1657        assert_eq!(state.selection(), None, "the selection goes with it");
1658        assert_eq!(state.update(Event::Remove(EntryId(4))), None);
1659    }
1660
1661    #[test]
1662    fn removing_another_entry_keeps_the_selection() {
1663        let mut state = state().with_selection(entry(1, 19, 9));
1664        let _ = state.update(Event::Remove(EntryId(2)));
1665        assert!(state.is_selected(entry(1, 19, 9)));
1666    }
1667
1668    #[test]
1669    fn rescheduling_moves_the_entry_and_the_selection() {
1670        let mut state = state().with_selection(entry(1, 19, 9));
1671        let output = state.update(Event::Reschedule {
1672            entry: EntryId(1),
1673            start: at(19, 9),
1674            to: (at(20, 15), at(20, 17)),
1675        });
1676        let Some(Output::Changed(changed)) = output else {
1677            panic!("an update");
1678        };
1679        assert_eq!(changed.change, Change::Updated);
1680        assert_eq!(changed.entry.when(), When::timed(at(20, 15), at(20, 17)));
1681        assert_eq!(changed.before, Some(meeting(1, 19, 9)));
1682        assert!(state.is_selected(entry(1, 20, 15)));
1683    }
1684
1685    #[test]
1686    fn rescheduling_one_occurrence_moves_the_whole_series() {
1687        let mut state = State::new(today())
1688            .with_entries(Entries::utc().with([meeting(1, 16, 9).repeat(Repeat::daily())]));
1689        // The occurrence on the 19th is dragged two hours later.
1690        let _ = state.update(Event::Reschedule {
1691            entry: EntryId(1),
1692            start: at(19, 9),
1693            to: (at(19, 11), at(19, 12)),
1694        });
1695        let moved = state.entries().get(EntryId(1)).map(Entry::when);
1696        assert_eq!(moved, Some(When::timed(at(16, 11), at(16, 12))));
1697    }
1698
1699    #[test]
1700    fn resizing_one_occurrence_changes_the_length_of_the_whole_series() {
1701        let series = || {
1702            State::new(today())
1703                .with_entries(Entries::utc().with([meeting(1, 16, 9).repeat(Repeat::daily())]))
1704        };
1705        // The top edge of the 19th is dragged an hour earlier: every
1706        // occurrence starts an hour earlier and still ends at 10:00.
1707        let mut state = series();
1708        let _ = state.update(Event::Reschedule {
1709            entry: EntryId(1),
1710            start: at(19, 9),
1711            to: (at(19, 8), at(19, 10)),
1712        });
1713        let longer = state.entries().get(EntryId(1)).map(Entry::when);
1714        assert_eq!(longer, Some(When::timed(at(16, 8), at(16, 10))));
1715
1716        // The lower edge of the 19th is dragged an hour later: every
1717        // occurrence still starts at 09:00 and ends at 11:00.
1718        let mut state = series();
1719        let _ = state.update(Event::Reschedule {
1720            entry: EntryId(1),
1721            start: at(19, 9),
1722            to: (at(19, 9), at(19, 11)),
1723        });
1724        let longer = state.entries().get(EntryId(1)).map(Entry::when);
1725        assert_eq!(longer, Some(When::timed(at(16, 9), at(16, 11))));
1726    }
1727
1728    #[test]
1729    fn rescheduling_ignores_unknown_and_unmoved_entries() {
1730        let mut state = state();
1731        let unknown = Event::Reschedule {
1732            entry: EntryId(99),
1733            start: at(19, 0),
1734            to: (at(20, 9), at(20, 10)),
1735        };
1736        assert_eq!(state.update(unknown), None);
1737        let unmoved = Event::Reschedule {
1738            entry: EntryId(1),
1739            start: at(19, 9),
1740            to: (at(19, 9), at(19, 10)),
1741        };
1742        assert_eq!(state.update(unmoved), None);
1743    }
1744
1745    #[test]
1746    fn a_tick_moves_today_and_the_now_line() {
1747        let mut state = state();
1748        let _ = state.update(Event::Tick(at(19, 0)));
1749        assert_eq!(state.update(Event::Tick(at(20, 0))), None);
1750        assert_eq!(state.now(), Some(at(20, 0)));
1751        assert_eq!(state.today(), date(2026, 11, 20));
1752        assert_eq!(state.cursor(), today(), "the period on show stays");
1753    }
1754
1755    fn press(keymap: &Keymap<Action>, chord: &str) -> Option<Action> {
1756        let Ok(chord) = chord.parse::<Chord>() else {
1757            panic!("{chord} is a chord");
1758        };
1759        keymap.resolve(chord.key(), chord.modifiers())
1760    }
1761
1762    #[test]
1763    fn default_keymap_covers_every_action() {
1764        let keymap = default_keymap();
1765        let expected = [
1766            ("PageUp", Action::Previous),
1767            ("PageDown", Action::Next),
1768            ("T", Action::Today),
1769            ("ArrowLeft", Action::PreviousDay),
1770            ("ArrowRight", Action::NextDay),
1771            ("ArrowUp", Action::PreviousWeek),
1772            ("ArrowDown", Action::NextWeek),
1773            ("Alt+ArrowUp", Action::PreviousEntry),
1774            ("Alt+ArrowDown", Action::NextEntry),
1775            ("M", Action::Month),
1776            ("W", Action::Week),
1777            ("D", Action::Day),
1778            ("A", Action::Agenda),
1779            ("Y", Action::Year),
1780            ("X", Action::FourDays),
1781            ("Enter", Action::Activate),
1782            ("Delete", Action::Remove),
1783            ("Backspace", Action::Remove),
1784            ("Escape", Action::Close),
1785        ];
1786        for (chord, action) in expected {
1787            assert_eq!(press(&keymap, chord), Some(action), "{chord}");
1788        }
1789        assert_eq!(press(&keymap, "Ctrl+T"), None);
1790        for action in <Action as keys::Action>::ALL {
1791            assert!(!keymap.chords(action).is_empty(), "{action:?}");
1792            assert!(!keys::Action::name(*action).is_empty());
1793            assert!(!keys::Action::description(*action).is_empty());
1794        }
1795        assert_eq!(Keymap::<Action>::defaults(), keymap);
1796    }
1797
1798    #[test]
1799    fn keymap_overrides_and_unbinding() {
1800        let Ok(chord) = "Ctrl+G".parse::<Chord>() else {
1801            panic!("a chord");
1802        };
1803        let keymap = default_keymap()
1804            .unbind(&Chord::character('t'))
1805            .bind(chord, Action::Today);
1806        assert_eq!(press(&keymap, "T"), None);
1807        assert_eq!(press(&keymap, "Ctrl+G"), Some(Action::Today));
1808        assert_eq!(press(&keymap, "M"), Some(Action::Month));
1809        assert!(
1810            default_keymap()
1811                .unbind_action(&Action::Remove)
1812                .chords(&Action::Remove)
1813                .is_empty()
1814        );
1815    }
1816
1817    #[test]
1818    fn actions_map_to_events() {
1819        let state = state();
1820        assert_eq!(Action::Next.event(&state), Some(Event::Next));
1821        assert_eq!(Action::Previous.event(&state), Some(Event::Previous));
1822        assert_eq!(Action::Today.event(&state), Some(Event::Today));
1823        assert_eq!(Action::PreviousDay.event(&state), Some(Event::MoveDay(-1)));
1824        assert_eq!(Action::NextDay.event(&state), Some(Event::MoveDay(1)));
1825        assert_eq!(Action::PreviousWeek.event(&state), Some(Event::MoveDay(-7)));
1826        assert_eq!(Action::NextWeek.event(&state), Some(Event::MoveDay(7)));
1827        assert_eq!(Action::NextEntry.event(&state), Some(Event::NextEntry));
1828        assert_eq!(
1829            Action::PreviousEntry.event(&state),
1830            Some(Event::PreviousEntry)
1831        );
1832        assert_eq!(Action::Activate.event(&state), Some(Event::Activate));
1833        assert_eq!(Action::Month.event(&state), None, "already on show");
1834        assert_eq!(Action::Week.event(&state), Some(Event::Show(View::Week)));
1835        assert_eq!(Action::Day.event(&state), Some(Event::Show(View::Day)));
1836        assert_eq!(
1837            Action::Agenda.event(&state),
1838            Some(Event::Show(View::Agenda))
1839        );
1840        assert_eq!(Action::Year.event(&state), Some(Event::Show(View::Year)));
1841        assert_eq!(
1842            Action::FourDays.event(&state),
1843            Some(Event::Show(View::FourDays))
1844        );
1845    }
1846
1847    #[test]
1848    fn remove_and_close_need_a_selection() {
1849        let mut state = state();
1850        assert_eq!(Action::Remove.event(&state), None);
1851        assert_eq!(Action::Close.event(&state), None);
1852
1853        let _ = state.update(Event::Press(Selection::Day(today())));
1854        assert_eq!(Action::Remove.event(&state), None, "a day is not an entry");
1855        assert_eq!(Action::Close.event(&state), Some(Event::Clear));
1856
1857        let _ = state.update(Event::Press(entry(2, 19, 14)));
1858        let Some(event) = Action::Remove.event(&state) else {
1859            panic!("an entry is selected");
1860        };
1861        assert_eq!(event, Event::Delete(EntryId(2)));
1862        assert!(state.update(event).is_some());
1863        assert_eq!(state.entries().len(), 2);
1864    }
1865
1866    fn when_of(state: &State, id: u64) -> Option<When> {
1867        state.entries().get(EntryId(id)).map(Entry::when)
1868    }
1869
1870    #[test]
1871    fn moving_by_days_keeps_the_time_of_day_and_follows_the_selection() {
1872        let mut state = state();
1873        let _ = state.update(Event::Press(entry(1, 19, 9)));
1874        let output = state.update(Event::MoveDays {
1875            entry: EntryId(1),
1876            start: at(19, 9),
1877            days: 3,
1878        });
1879        assert!(matches!(output, Some(Output::Changed(_))));
1880        assert_eq!(when_of(&state, 1), Some(When::timed(at(22, 9), at(22, 10))));
1881        assert_eq!(state.selection(), Some(entry(1, 22, 9)));
1882        let back = Event::MoveDays {
1883            entry: EntryId(1),
1884            start: at(22, 9),
1885            days: -5,
1886        };
1887        assert!(state.update(back).is_some());
1888        assert_eq!(when_of(&state, 1), Some(When::timed(at(17, 9), at(17, 10))));
1889        let nowhere = Event::MoveDays {
1890            entry: EntryId(1),
1891            start: at(17, 9),
1892            days: 0,
1893        };
1894        assert_eq!(state.update(nowhere), None);
1895    }
1896
1897    #[test]
1898    fn whole_day_entries_move_by_days_and_keep_their_length() {
1899        let mut state = state();
1900        let trip = Entry::all_day(EntryId(8), "Trip", date(2026, 11, 19), date(2026, 11, 21));
1901        let _ = state.update(Event::Insert(trip));
1902        let _ = state.update(Event::MoveDays {
1903            entry: EntryId(8),
1904            start: at(19, 0),
1905            days: 7,
1906        });
1907        assert_eq!(
1908            when_of(&state, 8),
1909            Some(When::all_day(date(2026, 11, 26), date(2026, 11, 28)))
1910        );
1911        // A reschedule of a whole-day entry moves it by the days between.
1912        let _ = state.update(Event::Reschedule {
1913            entry: EntryId(8),
1914            start: at(26, 0),
1915            to: (at(24, 0), at(25, 0)),
1916        });
1917        assert_eq!(
1918            when_of(&state, 8),
1919            Some(When::all_day(date(2026, 11, 24), date(2026, 11, 26)))
1920        );
1921    }
1922
1923    #[test]
1924    fn moving_one_occurrence_by_days_moves_the_whole_series() {
1925        let mut state = State::new(today()).with_entries(
1926            Entries::utc().with([Entry::all_day(
1927                EntryId(1),
1928                "Bins",
1929                date(2026, 11, 2),
1930                date(2026, 11, 2),
1931            )
1932            .repeat(Repeat::weekly())]),
1933        );
1934        let _ = state.update(Event::MoveDays {
1935            entry: EntryId(1),
1936            start: at(16, 0),
1937            days: 1,
1938        });
1939        assert_eq!(when_of(&state, 1), Some(When::day(date(2026, 11, 3))));
1940    }
1941
1942    #[test]
1943    fn drags_by_days_follow_the_permission_to_reschedule() {
1944        let mut state = state().with_allow(Allow {
1945            reschedule: false,
1946            ..Allow::ALL
1947        });
1948        let event = Event::MoveDays {
1949            entry: EntryId(1),
1950            start: at(19, 9),
1951            days: 1,
1952        };
1953        assert_eq!(state.update(event), None);
1954        assert_eq!(when_of(&state, 1), Some(When::timed(at(19, 9), at(19, 10))));
1955    }
1956
1957    #[test]
1958    fn a_locked_entry_is_never_moved_or_deleted_by_the_calendar() {
1959        let mut state = state();
1960        let _ = state.update(Event::Insert(meeting(5, 19, 16).locked(true)));
1961        let _ = state.update(Event::Press(entry(5, 19, 16)));
1962        assert_eq!(Action::Remove.event(&state), None);
1963        for event in [
1964            Event::Delete(EntryId(5)),
1965            Event::MoveDays {
1966                entry: EntryId(5),
1967                start: at(19, 16),
1968                days: 1,
1969            },
1970            Event::Reschedule {
1971                entry: EntryId(5),
1972                start: at(19, 16),
1973                to: (at(19, 17), at(19, 18)),
1974            },
1975        ] {
1976            assert_eq!(state.update(event.clone()), None, "{event:?}");
1977        }
1978        assert_eq!(
1979            when_of(&state, 5),
1980            Some(When::timed(at(19, 16), at(19, 17)))
1981        );
1982        // It can still be opened, and the app can still change it.
1983        assert!(matches!(
1984            state.update(Event::Activate),
1985            Some(Output::Opened { .. })
1986        ));
1987        assert!(state.update(Event::Remove(EntryId(5))).is_some());
1988    }
1989
1990    #[test]
1991    fn moving_and_removing_are_allowed_one_by_one_for_each_entry() {
1992        for locked in [false, true] {
1993            for movable in [false, true] {
1994                for removable in [false, true] {
1995                    for allow in [
1996                        Allow::ALL,
1997                        Allow::NONE,
1998                        Allow {
1999                            reschedule: false,
2000                            ..Allow::ALL
2001                        },
2002                        Allow {
2003                            remove: false,
2004                            ..Allow::ALL
2005                        },
2006                    ] {
2007                        let case = format!(
2008                            "locked {locked} movable {movable} removable {removable} {allow:?}"
2009                        );
2010                        let made = meeting(5, 19, 16)
2011                            .locked(locked)
2012                            .movable(movable)
2013                            .removable(removable);
2014                        let moves = !locked && movable && allow.reschedule;
2015                        let removes = !locked && removable && allow.remove;
2016                        assert_eq!(made.is_movable(), !locked && movable, "{case}");
2017                        assert_eq!(made.is_removable(), !locked && removable, "{case}");
2018
2019                        let mut state = state().with_allow(allow);
2020                        let _ = state.update(Event::Insert(made));
2021                        let _ = state.update(Event::Press(entry(5, 19, 16)));
2022                        let Some(shown) = state.selected_entry().cloned() else {
2023                            panic!("{case}: not selected");
2024                        };
2025                        assert_eq!(state.can_move(&shown), moves, "{case}");
2026                        assert_eq!(state.can_remove(&shown), removes, "{case}");
2027                        assert_eq!(
2028                            Action::Remove.event(&state),
2029                            removes.then_some(Event::Delete(EntryId(5))),
2030                            "{case}"
2031                        );
2032
2033                        let dragged = state.update(Event::MoveDays {
2034                            entry: EntryId(5),
2035                            start: at(19, 16),
2036                            days: 1,
2037                        });
2038                        assert_eq!(dragged.is_some(), moves, "{case}: by days");
2039                        let resized = state.update(Event::Reschedule {
2040                            entry: EntryId(5),
2041                            start: if moves { at(20, 16) } else { at(19, 16) },
2042                            to: (at(21, 16), at(21, 18)),
2043                        });
2044                        assert_eq!(resized.is_some(), moves, "{case}: rescheduled");
2045                        let expected = if moves {
2046                            When::timed(at(21, 16), at(21, 18))
2047                        } else {
2048                            When::timed(at(19, 16), at(19, 17))
2049                        };
2050                        assert_eq!(when_of(&state, 5), Some(expected), "{case}");
2051
2052                        let deleted = state.update(Event::Delete(EntryId(5)));
2053                        assert_eq!(deleted.is_some(), removes, "{case}: deleted");
2054                        assert_eq!(when_of(&state, 5).is_none(), removes, "{case}");
2055
2056                        // The app's own events always apply.
2057                        let _ = state.update(Event::Insert(meeting(5, 19, 16).locked(true)));
2058                        assert!(state.update(Event::Remove(EntryId(5))).is_some(), "{case}");
2059                    }
2060                }
2061            }
2062        }
2063    }
2064
2065    #[test]
2066    fn with_proposals_a_drag_is_proposed_and_drawn_until_confirmed() {
2067        let mut state = state().with_proposals(true);
2068        assert!(state.proposes());
2069        let _ = state.update(Event::Press(entry(1, 19, 9)));
2070        let output = state.update(Event::MoveDays {
2071            entry: EntryId(1),
2072            start: at(19, 9),
2073            days: 1,
2074        });
2075        let Some(Output::Proposed(proposed)) = output else {
2076            panic!("a proposal, not {output:?}");
2077        };
2078        assert_eq!(proposed.change, Change::Updated);
2079        assert_eq!(proposed.entry.when(), When::timed(at(20, 9), at(20, 10)));
2080        assert_eq!(
2081            proposed.before.map(|before| before.when()),
2082            Some(When::timed(at(19, 9), at(19, 10)))
2083        );
2084        // Nothing has changed yet, but the move is drawn.
2085        assert_eq!(when_of(&state, 1), Some(When::timed(at(19, 9), at(19, 10))));
2086        assert_eq!(
2087            state.shown().get(EntryId(1)).map(Entry::when),
2088            Some(When::timed(at(20, 9), at(20, 10)))
2089        );
2090        assert!(state.is_preview(EntryId(1)));
2091        assert!(!state.is_preview(EntryId(2)));
2092
2093        assert!(matches!(
2094            state.update(Event::Confirm),
2095            Some(Output::Changed(_))
2096        ));
2097        assert_eq!(when_of(&state, 1), Some(When::timed(at(20, 9), at(20, 10))));
2098        assert_eq!(state.pending(), None);
2099        assert_eq!(state.selection(), Some(entry(1, 20, 9)));
2100        assert_eq!(state.update(Event::Confirm), None, "nothing is pending");
2101    }
2102
2103    #[test]
2104    fn a_discarded_proposal_leaves_the_entry_where_it_was() {
2105        let mut state = state().with_proposals(true);
2106        let _ = state.update(Event::Reschedule {
2107            entry: EntryId(1),
2108            start: at(19, 9),
2109            to: (at(19, 11), at(19, 12)),
2110        });
2111        assert!(state.pending().is_some());
2112        assert_eq!(state.update(Event::Discard), None);
2113        assert_eq!(state.pending(), None);
2114        assert_eq!(state.shown(), state.entries());
2115        assert_eq!(when_of(&state, 1), Some(When::timed(at(19, 9), at(19, 10))));
2116    }
2117
2118    #[test]
2119    fn inserting_the_proposed_entry_confirms_it_and_others_clear_it() {
2120        let mut state = state().with_proposals(true);
2121        let _ = state.update(Event::MoveDays {
2122            entry: EntryId(1),
2123            start: at(19, 9),
2124            days: 1,
2125        });
2126        let Some(proposed) = state.pending().map(|pending| pending.entry.clone()) else {
2127            panic!("a proposal");
2128        };
2129        assert!(state.update(Event::Insert(proposed)).is_some());
2130        assert_eq!(state.pending(), None);
2131        assert_eq!(when_of(&state, 1), Some(When::timed(at(20, 9), at(20, 10))));
2132
2133        let _ = state.update(Event::MoveDays {
2134            entry: EntryId(2),
2135            start: at(19, 14),
2136            days: 1,
2137        });
2138        let _ = state.update(Event::Remove(EntryId(2)));
2139        assert_eq!(state.pending(), None);
2140    }
2141
2142    #[test]
2143    fn with_proposals_the_delete_key_proposes_a_removal() {
2144        let mut state = state().with_proposals(true);
2145        let _ = state.update(Event::Press(entry(2, 19, 14)));
2146        let Some(event) = Action::Remove.event(&state) else {
2147            panic!("an entry is selected");
2148        };
2149        let Some(Output::Proposed(proposed)) = state.update(event) else {
2150            panic!("a proposal");
2151        };
2152        assert_eq!(proposed.change, Change::Removed);
2153        assert_eq!(state.entries().len(), 3, "still there");
2154        assert!(
2155            state.shown().get(EntryId(2)).is_some(),
2156            "drawn as a preview"
2157        );
2158        assert!(state.is_preview(EntryId(2)));
2159        assert!(matches!(
2160            state.update(Event::Confirm),
2161            Some(Output::Changed(_))
2162        ));
2163        assert_eq!(state.entries().len(), 2);
2164        assert_eq!(state.selection(), None);
2165    }
2166
2167    #[test]
2168    fn a_double_press_selects_and_activates_at_once() {
2169        let mut state = state();
2170        assert_eq!(
2171            state.update(Event::DoublePress(entry(1, 19, 9))),
2172            Some(Output::Opened {
2173                entry: EntryId(1),
2174                start: at(19, 9)
2175            })
2176        );
2177        assert_eq!(state.selection(), Some(entry(1, 19, 9)));
2178        let slot = Selection::Slot {
2179            date: today(),
2180            minute: 600,
2181        };
2182        assert!(matches!(
2183            state.update(Event::DoublePress(slot)),
2184            Some(Output::Requested(_))
2185        ));
2186        // Without leave to create, a double press on a day only selects it.
2187        let mut read_only = State::new(today()).read_only();
2188        assert_eq!(
2189            read_only.update(Event::DoublePress(Selection::Day(today()))),
2190            Some(Output::Selected(Some(Selection::Day(today()))))
2191        );
2192    }
2193
2194    #[test]
2195    fn a_second_press_can_be_left_to_select_only() {
2196        let mut state = state().with_activate_on_second_press(false);
2197        assert!(!state.activates_on_second_press());
2198        let _ = state.update(Event::Press(entry(1, 19, 9)));
2199        assert_eq!(state.update(Event::Press(entry(1, 19, 9))), None);
2200        assert!(matches!(
2201            state.update(Event::DoublePress(entry(1, 19, 9))),
2202            Some(Output::Opened { .. })
2203        ));
2204        // By default a second press activates, for touch screens.
2205        let mut touch = self::state();
2206        assert!(touch.activates_on_second_press());
2207        let _ = touch.update(Event::Press(entry(1, 19, 9)));
2208        assert!(matches!(
2209            touch.update(Event::Press(entry(1, 19, 9))),
2210            Some(Output::Opened { .. })
2211        ));
2212    }
2213
2214    #[test]
2215    fn the_double_click_interval_can_be_set() {
2216        let state = state();
2217        assert_eq!(state.double_click(), DOUBLE_CLICK);
2218        let state = state.with_double_click(Duration::from_secs(3600));
2219        assert_eq!(state.double_click(), Duration::from_secs(3600));
2220    }
2221
2222    #[test]
2223    fn the_first_tick_reports_the_period_on_show_once() {
2224        let mut state = state();
2225        let (first, last) = state.range();
2226        assert_eq!(
2227            state.update(Event::Tick(at(19, 8))),
2228            Some(Output::Viewed {
2229                view: View::Month,
2230                first,
2231                last
2232            })
2233        );
2234        assert_eq!(state.update(Event::Tick(at(19, 9))), None);
2235
2236        // Once a period has been reported another way, the tick says nothing.
2237        let mut moved = self::state();
2238        assert!(matches!(
2239            moved.update(Event::Next),
2240            Some(Output::Viewed { .. })
2241        ));
2242        assert_eq!(moved.update(Event::Tick(at(19, 8))), None);
2243    }
2244
2245    #[test]
2246    fn today_and_timed_views_ask_the_hours_to_scroll_to_the_start() {
2247        let mut state = state();
2248        let start = state.scrolls();
2249        let _ = state.update(Event::Show(View::Week));
2250        assert_eq!(state.scrolls(), start + 1);
2251        let _ = state.update(Event::Show(View::Day));
2252        assert_eq!(state.scrolls(), start + 1, "already in a timed view");
2253        let _ = state.update(Event::Today);
2254        assert_eq!(state.scrolls(), start + 2);
2255        let _ = state.update(Event::Show(View::Month));
2256        assert_eq!(state.scrolls(), start + 2);
2257    }
2258}