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 toggle groups, accordions and
1076/// pagination, which apps also resolve from anywhere, so on a screen with
1077/// several of those resolve the calendar's keymap only while the calendar
1078/// is what the user is working in.
1079pub fn default_keymap() -> Keymap<Action> {
1080    Keymap::new()
1081        .bind(Chord::named(Named::PageUp), Action::Previous)
1082        .bind(Chord::named(Named::PageDown), Action::Next)
1083        .bind(Chord::character('t'), Action::Today)
1084        .bind(Chord::named(Named::ArrowLeft), Action::PreviousDay)
1085        .bind(Chord::named(Named::ArrowRight), Action::NextDay)
1086        .bind(Chord::named(Named::ArrowUp), Action::PreviousWeek)
1087        .bind(Chord::named(Named::ArrowDown), Action::NextWeek)
1088        .bind(Chord::named(Named::ArrowUp).alt(), Action::PreviousEntry)
1089        .bind(Chord::named(Named::ArrowDown).alt(), Action::NextEntry)
1090        .bind(Chord::character('m'), Action::Month)
1091        .bind(Chord::character('w'), Action::Week)
1092        .bind(Chord::character('d'), Action::Day)
1093        .bind(Chord::character('a'), Action::Agenda)
1094        .bind(Chord::character('y'), Action::Year)
1095        .bind(Chord::character('x'), Action::FourDays)
1096        .bind(Chord::named(Named::Enter), Action::Activate)
1097        .bind(Chord::named(Named::Delete), Action::Remove)
1098        .bind(Chord::named(Named::Backspace), Action::Remove)
1099        .bind(Chord::named(Named::Escape), Action::Close)
1100}
1101
1102#[cfg(test)]
1103mod tests {
1104    use super::*;
1105    use crate::data::calendar::entry::Change;
1106    use crate::data::calendar::repeat::Repeat;
1107    use jiff::civil::date;
1108
1109    /// Thursday 19 November 2026.
1110    fn today() -> Date {
1111        date(2026, 11, 19)
1112    }
1113
1114    fn at(day: i8, hour: i8) -> Timestamp {
1115        instant_at(
1116            date(2026, 11, day),
1117            u16::try_from(hour).unwrap_or(0) * 60,
1118            &TimeZone::UTC,
1119        )
1120    }
1121
1122    fn meeting(id: u64, day: i8, hour: i8) -> Entry {
1123        Entry::new(EntryId(id), "Meeting", at(day, hour), at(day, hour + 1))
1124    }
1125
1126    fn state() -> State {
1127        State::new(today()).with_entries(Entries::utc().with([
1128            meeting(1, 19, 9),
1129            meeting(2, 19, 14),
1130            meeting(3, 20, 9),
1131        ]))
1132    }
1133
1134    fn entry(id: u64, day: i8, hour: i8) -> Selection {
1135        Selection::Entry {
1136            entry: EntryId(id),
1137            start: at(day, hour),
1138        }
1139    }
1140
1141    #[test]
1142    fn a_new_calendar_shows_the_month_of_today_with_nothing_selected() {
1143        let state = State::new(today());
1144        assert_eq!(state.view(), View::Month);
1145        assert_eq!(state.cursor(), today());
1146        assert_eq!(state.today(), today());
1147        assert_eq!(state.now(), None);
1148        assert_eq!(state.selection(), None);
1149        assert_eq!(state.selected_day(), None);
1150        assert_eq!(state.week_start(), Weekday::Monday);
1151        assert!(state.entries().is_empty());
1152        assert_eq!(state.time_zone(), &TimeZone::UTC);
1153    }
1154
1155    #[test]
1156    fn at_takes_today_from_the_time_and_the_time_zone() {
1157        let Ok(tokyo) = TimeZone::get("Asia/Tokyo") else {
1158            panic!("the time zone database is bundled for tests");
1159        };
1160        let state = State::at(at(19, 20), Entries::new(tokyo));
1161        assert_eq!(state.today(), date(2026, 11, 20));
1162        assert_eq!(state.now(), Some(at(19, 20)));
1163    }
1164
1165    #[test]
1166    fn builder_options() {
1167        let state = State::new(today())
1168            .with_view(View::Week)
1169            .with_week_start(Weekday::Sunday)
1170            .with_cursor(date(2026, 12, 1))
1171            .with_selection(Selection::Day(date(2026, 12, 2)));
1172        assert_eq!(state.view(), View::Week);
1173        assert_eq!(state.week_start(), Weekday::Sunday);
1174        assert_eq!(state.cursor(), date(2026, 12, 1));
1175        assert_eq!(state.selected_day(), Some(date(2026, 12, 2)));
1176    }
1177
1178    #[test]
1179    fn every_view_has_a_label_a_range_and_a_title() {
1180        let mut state = state();
1181        let expected = [
1182            (
1183                View::Month,
1184                (date(2026, 10, 26), date(2026, 12, 6)),
1185                "November 2026",
1186            ),
1187            (
1188                View::Week,
1189                (date(2026, 11, 16), date(2026, 11, 22)),
1190                "16 - 22 Nov 2026",
1191            ),
1192            (View::Day, (today(), today()), "Thursday 19 November 2026"),
1193            (
1194                View::Agenda,
1195                (date(2026, 11, 1), date(2026, 11, 30)),
1196                "November 2026",
1197            ),
1198            (View::Year, (date(2026, 1, 1), date(2026, 12, 31)), "2026"),
1199            (
1200                View::FourDays,
1201                (today(), date(2026, 11, 22)),
1202                "19 - 22 Nov 2026",
1203            ),
1204        ];
1205        assert_eq!(View::ALL.len(), expected.len());
1206        for (view, range, title) in expected {
1207            let _ = state.update(Event::Show(view));
1208            assert_eq!(state.view(), view);
1209            assert_eq!(state.range(), range, "{view:?}");
1210            assert_eq!(state.title(), title, "{view:?}");
1211            assert_eq!(view.to_string(), view.label());
1212        }
1213        let labels: Vec<_> = View::ALL.iter().map(|view| view.label()).collect();
1214        assert_eq!(
1215            labels,
1216            vec!["Day", "Week", "Month", "Year", "Schedule", "4 days"]
1217        );
1218    }
1219
1220    #[test]
1221    fn a_year_steps_by_years_and_four_days_by_four() {
1222        let mut year = State::new(today()).with_view(View::Year);
1223        let _ = year.update(Event::Next);
1224        assert_eq!(year.cursor(), date(2027, 11, 19));
1225        assert_eq!(year.short_title(), "2027");
1226        let _ = year.update(Event::Previous);
1227        let _ = year.update(Event::Previous);
1228        assert_eq!(year.cursor(), date(2025, 11, 19));
1229
1230        let mut days = State::new(date(2026, 11, 29)).with_view(View::FourDays);
1231        assert_eq!(days.short_title(), "29 Nov - 2 Dec");
1232        let _ = days.update(Event::Next);
1233        assert_eq!(days.range(), (date(2026, 12, 3), date(2026, 12, 6)));
1234        let _ = days.update(Event::Previous);
1235        let _ = days.update(Event::Previous);
1236        assert_eq!(days.cursor(), date(2026, 11, 25));
1237
1238        // A day moved out of the four starts the next four.
1239        let mut days = State::new(today()).with_view(View::FourDays);
1240        let _ = days.update(Event::MoveDay(3));
1241        assert_eq!(days.cursor(), today());
1242        let _ = days.update(Event::MoveDay(1));
1243        assert_eq!(days.cursor(), date(2026, 11, 23));
1244    }
1245
1246    #[test]
1247    fn week_titles_name_both_months_or_years_when_they_differ() {
1248        let state = State::new(date(2026, 12, 1)).with_view(View::Week);
1249        assert_eq!(state.title(), "30 Nov - 6 Dec 2026");
1250        let state = State::new(date(2026, 12, 31)).with_view(View::Week);
1251        assert_eq!(state.title(), "28 Dec 2026 - 3 Jan 2027");
1252    }
1253
1254    #[test]
1255    fn short_titles_fit_a_phone() {
1256        let mut state = State::new(today());
1257        assert_eq!(state.short_title(), "November 2026");
1258        let _ = state.update(Event::Show(View::Agenda));
1259        assert_eq!(state.short_title(), "November 2026");
1260        let _ = state.update(Event::Show(View::Day));
1261        assert_eq!(state.short_title(), "Thu 19 Nov 2026");
1262        let _ = state.update(Event::Show(View::Week));
1263        assert_eq!(state.short_title(), "16 - 22 Nov 2026");
1264
1265        let across_months = State::new(date(2026, 12, 1)).with_view(View::Week);
1266        assert_eq!(across_months.short_title(), "30 Nov - 6 Dec");
1267        let across_years = State::new(date(2026, 12, 31)).with_view(View::Week);
1268        assert_eq!(across_years.short_title(), "28 Dec - 3 Jan");
1269    }
1270
1271    #[test]
1272    fn the_week_follows_the_day_weeks_start_on() {
1273        let state = State::new(today())
1274            .with_view(View::Week)
1275            .with_week_start(Weekday::Sunday);
1276        assert_eq!(state.range(), (date(2026, 11, 15), date(2026, 11, 21)));
1277    }
1278
1279    #[test]
1280    fn next_and_previous_step_by_what_the_view_shows() {
1281        let mut state = state();
1282        assert_eq!(
1283            state.update(Event::Next),
1284            Some(Output::Viewed {
1285                view: View::Month,
1286                first: date(2026, 11, 30),
1287                last: date(2027, 1, 3)
1288            })
1289        );
1290        assert_eq!(state.cursor(), date(2026, 12, 19));
1291        let _ = state.update(Event::Previous);
1292        assert_eq!(state.cursor(), today());
1293
1294        let _ = state.update(Event::Show(View::Week));
1295        let _ = state.update(Event::Next);
1296        assert_eq!(state.cursor(), date(2026, 11, 26));
1297        let _ = state.update(Event::Show(View::Day));
1298        let _ = state.update(Event::Previous);
1299        assert_eq!(state.cursor(), date(2026, 11, 25));
1300        let _ = state.update(Event::Show(View::Agenda));
1301        let _ = state.update(Event::Next);
1302        assert_eq!(state.cursor(), date(2026, 12, 25));
1303    }
1304
1305    #[test]
1306    fn stepping_a_month_from_the_31st_lands_on_the_last_day() {
1307        let mut state = State::new(date(2027, 1, 31));
1308        let _ = state.update(Event::Next);
1309        assert_eq!(state.cursor(), date(2027, 2, 28));
1310    }
1311
1312    #[test]
1313    fn showing_the_view_already_on_show_does_nothing() {
1314        let mut state = state();
1315        assert_eq!(state.update(Event::Show(View::Month)), None);
1316        assert!(state.update(Event::Show(View::Week)).is_some());
1317    }
1318
1319    #[test]
1320    fn switching_view_goes_to_the_selected_day() {
1321        let mut state = state();
1322        let _ = state.update(Event::Press(Selection::Day(date(2026, 11, 3))));
1323        let _ = state.update(Event::Show(View::Day));
1324        assert_eq!(state.cursor(), date(2026, 11, 3));
1325    }
1326
1327    #[test]
1328    fn go_to_reports_only_when_the_period_changes() {
1329        let mut state = state();
1330        assert_eq!(state.update(Event::GoTo(date(2026, 11, 2))), None);
1331        assert_eq!(state.cursor(), date(2026, 11, 2));
1332        assert!(matches!(
1333            state.update(Event::GoTo(date(2027, 3, 1))),
1334            Some(Output::Viewed { .. })
1335        ));
1336        assert_eq!(state.selection(), None);
1337    }
1338
1339    #[test]
1340    fn today_comes_back_and_selects_today() {
1341        let mut state = state();
1342        assert_eq!(
1343            state.update(Event::Today),
1344            Some(Output::Selected(Some(Selection::Day(today()))))
1345        );
1346        assert_eq!(state.update(Event::Today), None);
1347        let _ = state.update(Event::Next);
1348        assert!(matches!(
1349            state.update(Event::Today),
1350            Some(Output::Viewed { .. })
1351        ));
1352        assert_eq!(state.cursor(), today());
1353    }
1354
1355    #[test]
1356    fn the_first_press_selects_and_the_second_activates() {
1357        let mut state = state();
1358        let day = Selection::Day(date(2026, 11, 3));
1359        assert_eq!(
1360            state.update(Event::Press(day)),
1361            Some(Output::Selected(Some(day)))
1362        );
1363        assert!(state.is_selected(day));
1364        assert_eq!(
1365            state.update(Event::Press(day)),
1366            Some(Output::Requested(Draft {
1367                when: When::day(date(2026, 11, 3))
1368            }))
1369        );
1370
1371        let picked = entry(1, 19, 9);
1372        assert_eq!(
1373            state.update(Event::Press(picked)),
1374            Some(Output::Selected(Some(picked)))
1375        );
1376        assert_eq!(state.selected_entry().map(Entry::id), Some(EntryId(1)));
1377        assert_eq!(state.selected_day(), Some(today()));
1378        assert_eq!(
1379            state.update(Event::Press(picked)),
1380            Some(Output::Opened {
1381                entry: EntryId(1),
1382                start: at(19, 9)
1383            })
1384        );
1385    }
1386
1387    #[test]
1388    fn a_slot_asks_for_an_hour_and_stops_at_midnight() {
1389        let mut state = state();
1390        let slot = Selection::Slot {
1391            date: today(),
1392            minute: 600,
1393        };
1394        let _ = state.update(Event::Press(slot));
1395        assert_eq!(
1396            state.update(Event::Activate),
1397            Some(Output::Requested(Draft {
1398                when: When::timed(at(19, 10), at(19, 11))
1399            }))
1400        );
1401        let late = Selection::Slot {
1402            date: today(),
1403            minute: 1410,
1404        };
1405        let _ = state.update(Event::Press(late));
1406        assert_eq!(
1407            state.update(Event::Activate),
1408            Some(Output::Requested(Draft {
1409                when: When::timed(instant_at(today(), 1410, &TimeZone::UTC), at(20, 0))
1410            }))
1411        );
1412    }
1413
1414    #[test]
1415    fn activating_with_nothing_selected_asks_for_the_day_on_show() {
1416        let mut state = state();
1417        assert_eq!(
1418            state.update(Event::Activate),
1419            Some(Output::Requested(Draft {
1420                when: When::day(today())
1421            }))
1422        );
1423    }
1424
1425    #[test]
1426    fn activating_an_entry_that_is_gone_does_nothing() {
1427        let mut state = state().with_selection(entry(9, 19, 9));
1428        assert_eq!(state.update(Event::Activate), None);
1429        assert_eq!(state.selected_entry(), None);
1430    }
1431
1432    #[test]
1433    fn everything_is_allowed_unless_set() {
1434        assert_eq!(Allow::default(), Allow::ALL);
1435        assert_eq!(state().allow(), Allow::ALL);
1436        assert_eq!(state().read_only().allow(), Allow::NONE);
1437        let mut state = state();
1438        state.set_allow(Allow {
1439            remove: false,
1440            ..Allow::ALL
1441        });
1442        assert!(state.allow().create && !state.allow().remove);
1443    }
1444
1445    #[test]
1446    fn a_read_only_calendar_can_be_looked_through_but_not_changed() {
1447        let mut state = state().read_only();
1448        let day = Selection::Day(date(2026, 11, 3));
1449        let slot = Selection::Slot {
1450            date: today(),
1451            minute: 600,
1452        };
1453
1454        // Selecting and moving about still work.
1455        assert_eq!(
1456            state.update(Event::Press(day)),
1457            Some(Output::Selected(Some(day)))
1458        );
1459        assert!(state.update(Event::Next).is_some());
1460        assert!(state.update(Event::Show(View::Week)).is_some());
1461
1462        // A second press, Enter or a drag asks for nothing.
1463        let _ = state.update(Event::Press(day));
1464        assert_eq!(state.update(Event::Press(day)), None);
1465        assert_eq!(state.update(Event::Activate), None);
1466        let _ = state.update(Event::Press(slot));
1467        assert_eq!(state.update(Event::Press(slot)), None);
1468        let draft = Draft {
1469            when: When::day(today()),
1470        };
1471        assert_eq!(state.update(Event::Request(draft)), None);
1472        let _ = state.update(Event::Clear);
1473        assert_eq!(state.update(Event::Activate), None);
1474        assert_eq!(Action::Activate.event(&state), None);
1475
1476        // An entry can still be opened, but not dragged or removed by key.
1477        let picked = entry(1, 19, 9);
1478        let _ = state.update(Event::Press(picked));
1479        assert_eq!(
1480            state.update(Event::Press(picked)),
1481            Some(Output::Opened {
1482                entry: EntryId(1),
1483                start: at(19, 9)
1484            })
1485        );
1486        assert_eq!(Action::Activate.event(&state), Some(Event::Activate));
1487        assert_eq!(Action::Remove.event(&state), None);
1488        let drag = Event::Reschedule {
1489            entry: EntryId(1),
1490            start: at(19, 9),
1491            to: (at(20, 9), at(20, 10)),
1492        };
1493        assert_eq!(state.update(drag), None);
1494        assert_eq!(
1495            state.entries().get(EntryId(1)).map(Entry::when),
1496            Some(meeting(1, 19, 9).when())
1497        );
1498    }
1499
1500    #[test]
1501    fn the_app_can_still_change_a_read_only_calendar() {
1502        let mut state = state().read_only();
1503        assert!(state.update(Event::Insert(meeting(7, 21, 9))).is_some());
1504        assert!(state.update(Event::Insert(meeting(7, 22, 9))).is_some());
1505        assert!(state.update(Event::Remove(EntryId(7))).is_some());
1506        assert_eq!(state.entries().len(), 3);
1507    }
1508
1509    #[test]
1510    fn each_permission_stands_alone() {
1511        let mut state = state().with_allow(Allow {
1512            create: false,
1513            ..Allow::ALL
1514        });
1515        let _ = state.update(Event::Press(entry(1, 19, 9)));
1516        assert_eq!(
1517            Action::Remove.event(&state),
1518            Some(Event::Delete(EntryId(1)))
1519        );
1520        let drag = Event::Reschedule {
1521            entry: EntryId(1),
1522            start: at(19, 9),
1523            to: (at(20, 9), at(20, 10)),
1524        };
1525        assert!(state.update(drag).is_some());
1526        let _ = state.update(Event::Clear);
1527        assert_eq!(state.update(Event::Activate), None);
1528    }
1529
1530    #[test]
1531    fn clear_reports_only_when_something_was_selected() {
1532        let mut state = state();
1533        assert_eq!(state.update(Event::Clear), None);
1534        let _ = state.update(Event::Press(Selection::Day(today())));
1535        assert_eq!(state.update(Event::Clear), Some(Output::Selected(None)));
1536        assert_eq!(state.selection(), None);
1537    }
1538
1539    #[test]
1540    fn moving_the_day_starts_from_the_period_on_show_and_turns_the_page() {
1541        let mut state = state();
1542        assert_eq!(
1543            state.update(Event::MoveDay(1)),
1544            Some(Output::Selected(Some(Selection::Day(date(2026, 11, 20)))))
1545        );
1546        let _ = state.update(Event::MoveDay(7));
1547        assert_eq!(state.selected_day(), Some(date(2026, 11, 27)));
1548        assert_eq!(state.cursor(), today(), "still in November");
1549
1550        // 4 December is in the month grid, but belongs to the next month.
1551        assert!(matches!(
1552            state.update(Event::MoveDay(7)),
1553            Some(Output::Viewed { .. })
1554        ));
1555        assert_eq!(state.cursor(), date(2026, 12, 4));
1556
1557        let mut week = State::new(today()).with_view(View::Week);
1558        let _ = week.update(Event::MoveDay(3));
1559        assert_eq!(week.cursor(), today());
1560        assert!(matches!(
1561            week.update(Event::MoveDay(1)),
1562            Some(Output::Viewed { .. })
1563        ));
1564        assert_eq!(week.cursor(), date(2026, 11, 23));
1565    }
1566
1567    #[test]
1568    fn entries_of_the_selected_day_cycle_and_wrap() {
1569        let mut state = state();
1570        assert_eq!(
1571            state.update(Event::NextEntry),
1572            Some(Output::Selected(Some(entry(1, 19, 9))))
1573        );
1574        let _ = state.update(Event::NextEntry);
1575        assert!(state.is_selected(entry(2, 19, 14)));
1576        let _ = state.update(Event::NextEntry);
1577        assert!(state.is_selected(entry(1, 19, 9)), "wraps");
1578        let _ = state.update(Event::PreviousEntry);
1579        assert!(state.is_selected(entry(2, 19, 14)));
1580
1581        let mut from_the_end = self::state();
1582        let _ = from_the_end.update(Event::PreviousEntry);
1583        assert!(from_the_end.is_selected(entry(2, 19, 14)));
1584
1585        let mut one = self::state().with_selection(Selection::Day(date(2026, 11, 20)));
1586        let _ = one.update(Event::NextEntry);
1587        assert_eq!(one.update(Event::NextEntry), None, "the only entry");
1588
1589        let mut none = self::state().with_selection(Selection::Day(date(2026, 11, 1)));
1590        assert_eq!(none.update(Event::NextEntry), None);
1591    }
1592
1593    #[test]
1594    fn the_schedule_steps_through_all_its_entries_with_the_arrows() {
1595        let mut state = state().with_view(View::Agenda);
1596        for action in [Action::NextDay, Action::NextWeek] {
1597            assert_eq!(action.event(&state), Some(Event::NextEntry), "{action:?}");
1598        }
1599        for action in [Action::PreviousDay, Action::PreviousWeek] {
1600            assert_eq!(
1601                action.event(&state),
1602                Some(Event::PreviousEntry),
1603                "{action:?}"
1604            );
1605        }
1606        let _ = state.update(Event::NextEntry);
1607        let _ = state.update(Event::NextEntry);
1608        let _ = state.update(Event::NextEntry);
1609        assert!(state.is_selected(entry(3, 20, 9)), "on to the next day");
1610        let _ = state.update(Event::NextEntry);
1611        assert!(state.is_selected(entry(1, 19, 9)), "and round again");
1612    }
1613
1614    #[test]
1615    fn open_day_switches_to_the_day_view() {
1616        let mut state = state();
1617        assert_eq!(
1618            state.update(Event::OpenDay(date(2026, 11, 3))),
1619            Some(Output::Viewed {
1620                view: View::Day,
1621                first: date(2026, 11, 3),
1622                last: date(2026, 11, 3)
1623            })
1624        );
1625        assert_eq!(state.view(), View::Day);
1626        assert_eq!(state.update(Event::OpenDay(date(2026, 11, 3))), None);
1627    }
1628
1629    #[test]
1630    fn a_request_is_passed_on_and_adds_nothing() {
1631        let mut state = state();
1632        let draft = Draft {
1633            when: When::timed(at(19, 11), at(19, 12)),
1634        };
1635        assert_eq!(
1636            state.update(Event::Request(draft)),
1637            Some(Output::Requested(draft))
1638        );
1639        assert_eq!(state.entries().len(), 3);
1640    }
1641
1642    #[test]
1643    fn insert_and_remove_report_the_change() {
1644        let mut state = state();
1645        let change = |output: Option<Output>| match output {
1646            Some(Output::Changed(changed)) => Some(changed.change),
1647            _ => None,
1648        };
1649        let created = state.update(Event::Insert(meeting(4, 21, 9)));
1650        assert_eq!(change(created), Some(Change::Created));
1651        let updated = state.update(Event::Insert(meeting(4, 22, 9)));
1652        assert_eq!(change(updated), Some(Change::Updated));
1653        assert_eq!(state.update(Event::Insert(meeting(4, 22, 9))), None);
1654
1655        let _ = state.update(Event::Press(entry(4, 22, 9)));
1656        let removed = state.update(Event::Remove(EntryId(4)));
1657        assert_eq!(change(removed), Some(Change::Removed));
1658        assert_eq!(state.selection(), None, "the selection goes with it");
1659        assert_eq!(state.update(Event::Remove(EntryId(4))), None);
1660    }
1661
1662    #[test]
1663    fn removing_another_entry_keeps_the_selection() {
1664        let mut state = state().with_selection(entry(1, 19, 9));
1665        let _ = state.update(Event::Remove(EntryId(2)));
1666        assert!(state.is_selected(entry(1, 19, 9)));
1667    }
1668
1669    #[test]
1670    fn rescheduling_moves_the_entry_and_the_selection() {
1671        let mut state = state().with_selection(entry(1, 19, 9));
1672        let output = state.update(Event::Reschedule {
1673            entry: EntryId(1),
1674            start: at(19, 9),
1675            to: (at(20, 15), at(20, 17)),
1676        });
1677        let Some(Output::Changed(changed)) = output else {
1678            panic!("an update");
1679        };
1680        assert_eq!(changed.change, Change::Updated);
1681        assert_eq!(changed.entry.when(), When::timed(at(20, 15), at(20, 17)));
1682        assert_eq!(changed.before, Some(meeting(1, 19, 9)));
1683        assert!(state.is_selected(entry(1, 20, 15)));
1684    }
1685
1686    #[test]
1687    fn rescheduling_one_occurrence_moves_the_whole_series() {
1688        let mut state = State::new(today())
1689            .with_entries(Entries::utc().with([meeting(1, 16, 9).repeat(Repeat::daily())]));
1690        // The occurrence on the 19th is dragged two hours later.
1691        let _ = state.update(Event::Reschedule {
1692            entry: EntryId(1),
1693            start: at(19, 9),
1694            to: (at(19, 11), at(19, 12)),
1695        });
1696        let moved = state.entries().get(EntryId(1)).map(Entry::when);
1697        assert_eq!(moved, Some(When::timed(at(16, 11), at(16, 12))));
1698    }
1699
1700    #[test]
1701    fn resizing_one_occurrence_changes_the_length_of_the_whole_series() {
1702        let series = || {
1703            State::new(today())
1704                .with_entries(Entries::utc().with([meeting(1, 16, 9).repeat(Repeat::daily())]))
1705        };
1706        // The top edge of the 19th is dragged an hour earlier: every
1707        // occurrence starts an hour earlier and still ends at 10:00.
1708        let mut state = series();
1709        let _ = state.update(Event::Reschedule {
1710            entry: EntryId(1),
1711            start: at(19, 9),
1712            to: (at(19, 8), at(19, 10)),
1713        });
1714        let longer = state.entries().get(EntryId(1)).map(Entry::when);
1715        assert_eq!(longer, Some(When::timed(at(16, 8), at(16, 10))));
1716
1717        // The lower edge of the 19th is dragged an hour later: every
1718        // occurrence still starts at 09:00 and ends at 11:00.
1719        let mut state = series();
1720        let _ = state.update(Event::Reschedule {
1721            entry: EntryId(1),
1722            start: at(19, 9),
1723            to: (at(19, 9), at(19, 11)),
1724        });
1725        let longer = state.entries().get(EntryId(1)).map(Entry::when);
1726        assert_eq!(longer, Some(When::timed(at(16, 9), at(16, 11))));
1727    }
1728
1729    #[test]
1730    fn rescheduling_ignores_unknown_and_unmoved_entries() {
1731        let mut state = state();
1732        let unknown = Event::Reschedule {
1733            entry: EntryId(99),
1734            start: at(19, 0),
1735            to: (at(20, 9), at(20, 10)),
1736        };
1737        assert_eq!(state.update(unknown), None);
1738        let unmoved = Event::Reschedule {
1739            entry: EntryId(1),
1740            start: at(19, 9),
1741            to: (at(19, 9), at(19, 10)),
1742        };
1743        assert_eq!(state.update(unmoved), None);
1744    }
1745
1746    #[test]
1747    fn a_tick_moves_today_and_the_now_line() {
1748        let mut state = state();
1749        let _ = state.update(Event::Tick(at(19, 0)));
1750        assert_eq!(state.update(Event::Tick(at(20, 0))), None);
1751        assert_eq!(state.now(), Some(at(20, 0)));
1752        assert_eq!(state.today(), date(2026, 11, 20));
1753        assert_eq!(state.cursor(), today(), "the period on show stays");
1754    }
1755
1756    fn press(keymap: &Keymap<Action>, chord: &str) -> Option<Action> {
1757        let Ok(chord) = chord.parse::<Chord>() else {
1758            panic!("{chord} is a chord");
1759        };
1760        keymap.resolve(chord.key(), chord.modifiers())
1761    }
1762
1763    #[test]
1764    fn default_keymap_covers_every_action() {
1765        let keymap = default_keymap();
1766        let expected = [
1767            ("PageUp", Action::Previous),
1768            ("PageDown", Action::Next),
1769            ("T", Action::Today),
1770            ("ArrowLeft", Action::PreviousDay),
1771            ("ArrowRight", Action::NextDay),
1772            ("ArrowUp", Action::PreviousWeek),
1773            ("ArrowDown", Action::NextWeek),
1774            ("Alt+ArrowUp", Action::PreviousEntry),
1775            ("Alt+ArrowDown", Action::NextEntry),
1776            ("M", Action::Month),
1777            ("W", Action::Week),
1778            ("D", Action::Day),
1779            ("A", Action::Agenda),
1780            ("Y", Action::Year),
1781            ("X", Action::FourDays),
1782            ("Enter", Action::Activate),
1783            ("Delete", Action::Remove),
1784            ("Backspace", Action::Remove),
1785            ("Escape", Action::Close),
1786        ];
1787        for (chord, action) in expected {
1788            assert_eq!(press(&keymap, chord), Some(action), "{chord}");
1789        }
1790        assert_eq!(press(&keymap, "Ctrl+T"), None);
1791        for action in <Action as keys::Action>::ALL {
1792            assert!(!keymap.chords(action).is_empty(), "{action:?}");
1793            assert!(!keys::Action::name(*action).is_empty());
1794            assert!(!keys::Action::description(*action).is_empty());
1795        }
1796        assert_eq!(Keymap::<Action>::defaults(), keymap);
1797    }
1798
1799    #[test]
1800    fn keymap_overrides_and_unbinding() {
1801        let Ok(chord) = "Ctrl+G".parse::<Chord>() else {
1802            panic!("a chord");
1803        };
1804        let keymap = default_keymap()
1805            .unbind(&Chord::character('t'))
1806            .bind(chord, Action::Today);
1807        assert_eq!(press(&keymap, "T"), None);
1808        assert_eq!(press(&keymap, "Ctrl+G"), Some(Action::Today));
1809        assert_eq!(press(&keymap, "M"), Some(Action::Month));
1810        assert!(
1811            default_keymap()
1812                .unbind_action(&Action::Remove)
1813                .chords(&Action::Remove)
1814                .is_empty()
1815        );
1816    }
1817
1818    #[test]
1819    fn actions_map_to_events() {
1820        let state = state();
1821        assert_eq!(Action::Next.event(&state), Some(Event::Next));
1822        assert_eq!(Action::Previous.event(&state), Some(Event::Previous));
1823        assert_eq!(Action::Today.event(&state), Some(Event::Today));
1824        assert_eq!(Action::PreviousDay.event(&state), Some(Event::MoveDay(-1)));
1825        assert_eq!(Action::NextDay.event(&state), Some(Event::MoveDay(1)));
1826        assert_eq!(Action::PreviousWeek.event(&state), Some(Event::MoveDay(-7)));
1827        assert_eq!(Action::NextWeek.event(&state), Some(Event::MoveDay(7)));
1828        assert_eq!(Action::NextEntry.event(&state), Some(Event::NextEntry));
1829        assert_eq!(
1830            Action::PreviousEntry.event(&state),
1831            Some(Event::PreviousEntry)
1832        );
1833        assert_eq!(Action::Activate.event(&state), Some(Event::Activate));
1834        assert_eq!(Action::Month.event(&state), None, "already on show");
1835        assert_eq!(Action::Week.event(&state), Some(Event::Show(View::Week)));
1836        assert_eq!(Action::Day.event(&state), Some(Event::Show(View::Day)));
1837        assert_eq!(
1838            Action::Agenda.event(&state),
1839            Some(Event::Show(View::Agenda))
1840        );
1841        assert_eq!(Action::Year.event(&state), Some(Event::Show(View::Year)));
1842        assert_eq!(
1843            Action::FourDays.event(&state),
1844            Some(Event::Show(View::FourDays))
1845        );
1846    }
1847
1848    #[test]
1849    fn remove_and_close_need_a_selection() {
1850        let mut state = state();
1851        assert_eq!(Action::Remove.event(&state), None);
1852        assert_eq!(Action::Close.event(&state), None);
1853
1854        let _ = state.update(Event::Press(Selection::Day(today())));
1855        assert_eq!(Action::Remove.event(&state), None, "a day is not an entry");
1856        assert_eq!(Action::Close.event(&state), Some(Event::Clear));
1857
1858        let _ = state.update(Event::Press(entry(2, 19, 14)));
1859        let Some(event) = Action::Remove.event(&state) else {
1860            panic!("an entry is selected");
1861        };
1862        assert_eq!(event, Event::Delete(EntryId(2)));
1863        assert!(state.update(event).is_some());
1864        assert_eq!(state.entries().len(), 2);
1865    }
1866
1867    fn when_of(state: &State, id: u64) -> Option<When> {
1868        state.entries().get(EntryId(id)).map(Entry::when)
1869    }
1870
1871    #[test]
1872    fn moving_by_days_keeps_the_time_of_day_and_follows_the_selection() {
1873        let mut state = state();
1874        let _ = state.update(Event::Press(entry(1, 19, 9)));
1875        let output = state.update(Event::MoveDays {
1876            entry: EntryId(1),
1877            start: at(19, 9),
1878            days: 3,
1879        });
1880        assert!(matches!(output, Some(Output::Changed(_))));
1881        assert_eq!(when_of(&state, 1), Some(When::timed(at(22, 9), at(22, 10))));
1882        assert_eq!(state.selection(), Some(entry(1, 22, 9)));
1883        let back = Event::MoveDays {
1884            entry: EntryId(1),
1885            start: at(22, 9),
1886            days: -5,
1887        };
1888        assert!(state.update(back).is_some());
1889        assert_eq!(when_of(&state, 1), Some(When::timed(at(17, 9), at(17, 10))));
1890        let nowhere = Event::MoveDays {
1891            entry: EntryId(1),
1892            start: at(17, 9),
1893            days: 0,
1894        };
1895        assert_eq!(state.update(nowhere), None);
1896    }
1897
1898    #[test]
1899    fn whole_day_entries_move_by_days_and_keep_their_length() {
1900        let mut state = state();
1901        let trip = Entry::all_day(EntryId(8), "Trip", date(2026, 11, 19), date(2026, 11, 21));
1902        let _ = state.update(Event::Insert(trip));
1903        let _ = state.update(Event::MoveDays {
1904            entry: EntryId(8),
1905            start: at(19, 0),
1906            days: 7,
1907        });
1908        assert_eq!(
1909            when_of(&state, 8),
1910            Some(When::all_day(date(2026, 11, 26), date(2026, 11, 28)))
1911        );
1912        // A reschedule of a whole-day entry moves it by the days between.
1913        let _ = state.update(Event::Reschedule {
1914            entry: EntryId(8),
1915            start: at(26, 0),
1916            to: (at(24, 0), at(25, 0)),
1917        });
1918        assert_eq!(
1919            when_of(&state, 8),
1920            Some(When::all_day(date(2026, 11, 24), date(2026, 11, 26)))
1921        );
1922    }
1923
1924    #[test]
1925    fn moving_one_occurrence_by_days_moves_the_whole_series() {
1926        let mut state = State::new(today()).with_entries(
1927            Entries::utc().with([Entry::all_day(
1928                EntryId(1),
1929                "Bins",
1930                date(2026, 11, 2),
1931                date(2026, 11, 2),
1932            )
1933            .repeat(Repeat::weekly())]),
1934        );
1935        let _ = state.update(Event::MoveDays {
1936            entry: EntryId(1),
1937            start: at(16, 0),
1938            days: 1,
1939        });
1940        assert_eq!(when_of(&state, 1), Some(When::day(date(2026, 11, 3))));
1941    }
1942
1943    #[test]
1944    fn drags_by_days_follow_the_permission_to_reschedule() {
1945        let mut state = state().with_allow(Allow {
1946            reschedule: false,
1947            ..Allow::ALL
1948        });
1949        let event = Event::MoveDays {
1950            entry: EntryId(1),
1951            start: at(19, 9),
1952            days: 1,
1953        };
1954        assert_eq!(state.update(event), None);
1955        assert_eq!(when_of(&state, 1), Some(When::timed(at(19, 9), at(19, 10))));
1956    }
1957
1958    #[test]
1959    fn a_locked_entry_is_never_moved_or_deleted_by_the_calendar() {
1960        let mut state = state();
1961        let _ = state.update(Event::Insert(meeting(5, 19, 16).locked(true)));
1962        let _ = state.update(Event::Press(entry(5, 19, 16)));
1963        assert_eq!(Action::Remove.event(&state), None);
1964        for event in [
1965            Event::Delete(EntryId(5)),
1966            Event::MoveDays {
1967                entry: EntryId(5),
1968                start: at(19, 16),
1969                days: 1,
1970            },
1971            Event::Reschedule {
1972                entry: EntryId(5),
1973                start: at(19, 16),
1974                to: (at(19, 17), at(19, 18)),
1975            },
1976        ] {
1977            assert_eq!(state.update(event.clone()), None, "{event:?}");
1978        }
1979        assert_eq!(
1980            when_of(&state, 5),
1981            Some(When::timed(at(19, 16), at(19, 17)))
1982        );
1983        // It can still be opened, and the app can still change it.
1984        assert!(matches!(
1985            state.update(Event::Activate),
1986            Some(Output::Opened { .. })
1987        ));
1988        assert!(state.update(Event::Remove(EntryId(5))).is_some());
1989    }
1990
1991    #[test]
1992    fn moving_and_removing_are_allowed_one_by_one_for_each_entry() {
1993        for locked in [false, true] {
1994            for movable in [false, true] {
1995                for removable in [false, true] {
1996                    for allow in [
1997                        Allow::ALL,
1998                        Allow::NONE,
1999                        Allow {
2000                            reschedule: false,
2001                            ..Allow::ALL
2002                        },
2003                        Allow {
2004                            remove: false,
2005                            ..Allow::ALL
2006                        },
2007                    ] {
2008                        let case = format!(
2009                            "locked {locked} movable {movable} removable {removable} {allow:?}"
2010                        );
2011                        let made = meeting(5, 19, 16)
2012                            .locked(locked)
2013                            .movable(movable)
2014                            .removable(removable);
2015                        let moves = !locked && movable && allow.reschedule;
2016                        let removes = !locked && removable && allow.remove;
2017                        assert_eq!(made.is_movable(), !locked && movable, "{case}");
2018                        assert_eq!(made.is_removable(), !locked && removable, "{case}");
2019
2020                        let mut state = state().with_allow(allow);
2021                        let _ = state.update(Event::Insert(made));
2022                        let _ = state.update(Event::Press(entry(5, 19, 16)));
2023                        let Some(shown) = state.selected_entry().cloned() else {
2024                            panic!("{case}: not selected");
2025                        };
2026                        assert_eq!(state.can_move(&shown), moves, "{case}");
2027                        assert_eq!(state.can_remove(&shown), removes, "{case}");
2028                        assert_eq!(
2029                            Action::Remove.event(&state),
2030                            removes.then_some(Event::Delete(EntryId(5))),
2031                            "{case}"
2032                        );
2033
2034                        let dragged = state.update(Event::MoveDays {
2035                            entry: EntryId(5),
2036                            start: at(19, 16),
2037                            days: 1,
2038                        });
2039                        assert_eq!(dragged.is_some(), moves, "{case}: by days");
2040                        let resized = state.update(Event::Reschedule {
2041                            entry: EntryId(5),
2042                            start: if moves { at(20, 16) } else { at(19, 16) },
2043                            to: (at(21, 16), at(21, 18)),
2044                        });
2045                        assert_eq!(resized.is_some(), moves, "{case}: rescheduled");
2046                        let expected = if moves {
2047                            When::timed(at(21, 16), at(21, 18))
2048                        } else {
2049                            When::timed(at(19, 16), at(19, 17))
2050                        };
2051                        assert_eq!(when_of(&state, 5), Some(expected), "{case}");
2052
2053                        let deleted = state.update(Event::Delete(EntryId(5)));
2054                        assert_eq!(deleted.is_some(), removes, "{case}: deleted");
2055                        assert_eq!(when_of(&state, 5).is_none(), removes, "{case}");
2056
2057                        // The app's own events always apply.
2058                        let _ = state.update(Event::Insert(meeting(5, 19, 16).locked(true)));
2059                        assert!(state.update(Event::Remove(EntryId(5))).is_some(), "{case}");
2060                    }
2061                }
2062            }
2063        }
2064    }
2065
2066    #[test]
2067    fn with_proposals_a_drag_is_proposed_and_drawn_until_confirmed() {
2068        let mut state = state().with_proposals(true);
2069        assert!(state.proposes());
2070        let _ = state.update(Event::Press(entry(1, 19, 9)));
2071        let output = state.update(Event::MoveDays {
2072            entry: EntryId(1),
2073            start: at(19, 9),
2074            days: 1,
2075        });
2076        let Some(Output::Proposed(proposed)) = output else {
2077            panic!("a proposal, not {output:?}");
2078        };
2079        assert_eq!(proposed.change, Change::Updated);
2080        assert_eq!(proposed.entry.when(), When::timed(at(20, 9), at(20, 10)));
2081        assert_eq!(
2082            proposed.before.map(|before| before.when()),
2083            Some(When::timed(at(19, 9), at(19, 10)))
2084        );
2085        // Nothing has changed yet, but the move is drawn.
2086        assert_eq!(when_of(&state, 1), Some(When::timed(at(19, 9), at(19, 10))));
2087        assert_eq!(
2088            state.shown().get(EntryId(1)).map(Entry::when),
2089            Some(When::timed(at(20, 9), at(20, 10)))
2090        );
2091        assert!(state.is_preview(EntryId(1)));
2092        assert!(!state.is_preview(EntryId(2)));
2093
2094        assert!(matches!(
2095            state.update(Event::Confirm),
2096            Some(Output::Changed(_))
2097        ));
2098        assert_eq!(when_of(&state, 1), Some(When::timed(at(20, 9), at(20, 10))));
2099        assert_eq!(state.pending(), None);
2100        assert_eq!(state.selection(), Some(entry(1, 20, 9)));
2101        assert_eq!(state.update(Event::Confirm), None, "nothing is pending");
2102    }
2103
2104    #[test]
2105    fn a_discarded_proposal_leaves_the_entry_where_it_was() {
2106        let mut state = state().with_proposals(true);
2107        let _ = state.update(Event::Reschedule {
2108            entry: EntryId(1),
2109            start: at(19, 9),
2110            to: (at(19, 11), at(19, 12)),
2111        });
2112        assert!(state.pending().is_some());
2113        assert_eq!(state.update(Event::Discard), None);
2114        assert_eq!(state.pending(), None);
2115        assert_eq!(state.shown(), state.entries());
2116        assert_eq!(when_of(&state, 1), Some(When::timed(at(19, 9), at(19, 10))));
2117    }
2118
2119    #[test]
2120    fn inserting_the_proposed_entry_confirms_it_and_others_clear_it() {
2121        let mut state = state().with_proposals(true);
2122        let _ = state.update(Event::MoveDays {
2123            entry: EntryId(1),
2124            start: at(19, 9),
2125            days: 1,
2126        });
2127        let Some(proposed) = state.pending().map(|pending| pending.entry.clone()) else {
2128            panic!("a proposal");
2129        };
2130        assert!(state.update(Event::Insert(proposed)).is_some());
2131        assert_eq!(state.pending(), None);
2132        assert_eq!(when_of(&state, 1), Some(When::timed(at(20, 9), at(20, 10))));
2133
2134        let _ = state.update(Event::MoveDays {
2135            entry: EntryId(2),
2136            start: at(19, 14),
2137            days: 1,
2138        });
2139        let _ = state.update(Event::Remove(EntryId(2)));
2140        assert_eq!(state.pending(), None);
2141    }
2142
2143    #[test]
2144    fn with_proposals_the_delete_key_proposes_a_removal() {
2145        let mut state = state().with_proposals(true);
2146        let _ = state.update(Event::Press(entry(2, 19, 14)));
2147        let Some(event) = Action::Remove.event(&state) else {
2148            panic!("an entry is selected");
2149        };
2150        let Some(Output::Proposed(proposed)) = state.update(event) else {
2151            panic!("a proposal");
2152        };
2153        assert_eq!(proposed.change, Change::Removed);
2154        assert_eq!(state.entries().len(), 3, "still there");
2155        assert!(
2156            state.shown().get(EntryId(2)).is_some(),
2157            "drawn as a preview"
2158        );
2159        assert!(state.is_preview(EntryId(2)));
2160        assert!(matches!(
2161            state.update(Event::Confirm),
2162            Some(Output::Changed(_))
2163        ));
2164        assert_eq!(state.entries().len(), 2);
2165        assert_eq!(state.selection(), None);
2166    }
2167
2168    #[test]
2169    fn a_double_press_selects_and_activates_at_once() {
2170        let mut state = state();
2171        assert_eq!(
2172            state.update(Event::DoublePress(entry(1, 19, 9))),
2173            Some(Output::Opened {
2174                entry: EntryId(1),
2175                start: at(19, 9)
2176            })
2177        );
2178        assert_eq!(state.selection(), Some(entry(1, 19, 9)));
2179        let slot = Selection::Slot {
2180            date: today(),
2181            minute: 600,
2182        };
2183        assert!(matches!(
2184            state.update(Event::DoublePress(slot)),
2185            Some(Output::Requested(_))
2186        ));
2187        // Without leave to create, a double press on a day only selects it.
2188        let mut read_only = State::new(today()).read_only();
2189        assert_eq!(
2190            read_only.update(Event::DoublePress(Selection::Day(today()))),
2191            Some(Output::Selected(Some(Selection::Day(today()))))
2192        );
2193    }
2194
2195    #[test]
2196    fn a_second_press_can_be_left_to_select_only() {
2197        let mut state = state().with_activate_on_second_press(false);
2198        assert!(!state.activates_on_second_press());
2199        let _ = state.update(Event::Press(entry(1, 19, 9)));
2200        assert_eq!(state.update(Event::Press(entry(1, 19, 9))), None);
2201        assert!(matches!(
2202            state.update(Event::DoublePress(entry(1, 19, 9))),
2203            Some(Output::Opened { .. })
2204        ));
2205        // By default a second press activates, for touch screens.
2206        let mut touch = self::state();
2207        assert!(touch.activates_on_second_press());
2208        let _ = touch.update(Event::Press(entry(1, 19, 9)));
2209        assert!(matches!(
2210            touch.update(Event::Press(entry(1, 19, 9))),
2211            Some(Output::Opened { .. })
2212        ));
2213    }
2214
2215    #[test]
2216    fn the_double_click_interval_can_be_set() {
2217        let state = state();
2218        assert_eq!(state.double_click(), DOUBLE_CLICK);
2219        let state = state.with_double_click(Duration::from_secs(3600));
2220        assert_eq!(state.double_click(), Duration::from_secs(3600));
2221    }
2222
2223    #[test]
2224    fn the_first_tick_reports_the_period_on_show_once() {
2225        let mut state = state();
2226        let (first, last) = state.range();
2227        assert_eq!(
2228            state.update(Event::Tick(at(19, 8))),
2229            Some(Output::Viewed {
2230                view: View::Month,
2231                first,
2232                last
2233            })
2234        );
2235        assert_eq!(state.update(Event::Tick(at(19, 9))), None);
2236
2237        // Once a period has been reported another way, the tick says nothing.
2238        let mut moved = self::state();
2239        assert!(matches!(
2240            moved.update(Event::Next),
2241            Some(Output::Viewed { .. })
2242        ));
2243        assert_eq!(moved.update(Event::Tick(at(19, 8))), None);
2244    }
2245
2246    #[test]
2247    fn today_and_timed_views_ask_the_hours_to_scroll_to_the_start() {
2248        let mut state = state();
2249        let start = state.scrolls();
2250        let _ = state.update(Event::Show(View::Week));
2251        assert_eq!(state.scrolls(), start + 1);
2252        let _ = state.update(Event::Show(View::Day));
2253        assert_eq!(state.scrolls(), start + 1, "already in a timed view");
2254        let _ = state.update(Event::Today);
2255        assert_eq!(state.scrolls(), start + 2);
2256        let _ = state.update(Event::Show(View::Month));
2257        assert_eq!(state.scrolls(), start + 2);
2258    }
2259}