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