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