Skip to main content

iced_cube/data/calendar/
editor.rs

1//! A form for creating or changing an entry: its title, whether it lasts
2//! all day, when it starts and ends, how it repeats and when the repeats
3//! stop, its colour, where it is and any notes.
4//!
5//! The form is as tall as its fields, and grows when a repeat is chosen.
6//! Where room is short, put it in a scroll area.
7//!
8//! The form has no buttons of its own. Put it in a dialog, a popover or a
9//! side panel with whatever actions the app wants, start it from the
10//! [`Draft`] the calendar asked for or from an existing [`Entry`], and
11//! turn it back into an entry with [`State::entry`]:
12//!
13//! ```
14//! use iced_cube::data::calendar::editor;
15//! use iced_cube::data::calendar::{Draft, EntryId, Repeat, When, instant};
16//! use jiff::civil::{date, time};
17//! use jiff::tz::TimeZone;
18//!
19//! let utc = TimeZone::UTC;
20//! let at = |hour| instant(date(2026, 6, 19), time(hour, 0, 0, 0), &utc);
21//! let draft = Draft { when: When::timed(at(11), at(12)) };
22//!
23//! let mut form = editor::State::new(&draft, &utc);
24//! form.update(editor::Event::Title(String::from("Retrospective")));
25//! // Starting an hour later keeps the entry an hour long.
26//! form.update(editor::Event::Time(editor::Field::Start, 12 * 60));
27//!
28//! // Every two weeks, six times in all.
29//! form.update(editor::Event::Repeats(editor::Repeats::Weekly));
30//! form.update(editor::Event::Interval(String::from("2")));
31//! form.update(editor::Event::Stops(editor::Stops::After));
32//! form.update(editor::Event::Count(String::from("6")));
33//! form.update(editor::Event::Location(String::from("Room 4")));
34//!
35//! let entry = form.entry(EntryId(7));
36//! assert_eq!(entry.title(), "Retrospective");
37//! assert_eq!(entry.when(), When::timed(at(12), at(13)));
38//! assert_eq!(entry.repeat_of(), Some(Repeat::weekly().interval(2).count(6)));
39//! assert_eq!(entry.location_of(), Some("Room 4"));
40//! ```
41
42use iced::widget::button::Status;
43use iced::widget::text_editor::{Action, Content};
44use iced::widget::{self, Column, Row, Space, column, container, row, text};
45use iced::{Alignment, Element, Length, Theme};
46use jiff::civil::{Date, Weekday};
47use jiff::tz::TimeZone;
48use jiff::{Timestamp, ToSpan};
49
50use super::entry::{Draft, Entry, EntryId, Tone, When, add_days, date_of};
51use super::layout::{DAY_MINUTES, instant_at, minute_on, month_weeks};
52use super::parts::weekday_label;
53use super::repeat::{Ends, Frequency, Repeat};
54use super::style;
55use crate::forms::select::select;
56use crate::forms::textarea::textarea;
57use crate::lucide;
58use crate::overlay::anchored::Align;
59use crate::overlay::popover::popover;
60use crate::primitives::button::{self, Size, button};
61use crate::primitives::icon_button::{self, icon_button};
62use crate::primitives::input::{Shortcuts, input};
63use crate::primitives::switch::switch;
64use crate::theme::{self, Tokens, space, text_size};
65
66/// The step between the times offered, in minutes.
67pub const TIME_STEP: u16 = 15;
68/// The title given to an entry saved without one.
69pub const UNTITLED: &str = "(No title)";
70/// How long a new timed entry is when the draft was for whole days.
71pub const DEFAULT_MINUTES: u16 = 60;
72
73/// How many occurrences a new "after" ending starts at.
74pub const DEFAULT_COUNT: u32 = 10;
75/// The most digits the interval and the count take.
76pub const NUMBER_DIGITS: usize = 3;
77
78/// The side of a day in the date picker.
79const CELL: f32 = 32.0;
80/// The width of a time's menu.
81const TIME_WIDTH: f32 = 96.0;
82/// The width of the names beside the fields.
83const NAME_WIDTH: f32 = 48.0;
84/// The width of a field for a small number.
85const NUMBER_WIDTH: f32 = 64.0;
86/// The height the notes start at, about two lines.
87const NOTES_HEIGHT: f32 = 64.0;
88
89/// The id of the notes field, for focusing it.
90pub fn notes_id() -> widget::Id {
91    widget::Id::new("iced-cube-calendar-notes")
92}
93
94/// The start or the end of the entry.
95#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
96pub enum Field {
97    Start,
98    End,
99}
100
101/// A time of day in minutes from midnight, shown as "09:30".
102#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
103pub struct TimeOfDay(pub u16);
104
105impl TimeOfDay {
106    /// Every time offered, a day's worth at [`TIME_STEP`] apart.
107    pub fn all() -> Vec<TimeOfDay> {
108        (0..DAY_MINUTES)
109            .step_by(usize::from(TIME_STEP))
110            .map(TimeOfDay)
111            .collect()
112    }
113
114    /// Every time offered, starting the list at `first` and carrying on
115    /// round midnight, so a menu opens near the time it is about rather
116    /// than at the start of the day.
117    pub fn from(first: u16) -> Vec<TimeOfDay> {
118        let mut times = Self::all();
119        let first = (first.min(DAY_MINUTES - 1) / TIME_STEP) * TIME_STEP;
120        let split = times.iter().position(|time| time.0 >= first).unwrap_or(0);
121        times.rotate_left(split);
122        times
123    }
124}
125
126impl std::fmt::Display for TimeOfDay {
127    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
128        write!(f, "{:02}:{:02}", self.0 / 60, self.0 % 60)
129    }
130}
131
132/// Whether the entry repeats and in what unit, as the menu offers it.
133#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
134pub enum Repeats {
135    #[default]
136    Never,
137    Daily,
138    Weekly,
139    Monthly,
140    Yearly,
141}
142
143impl Repeats {
144    /// The choices in the menu.
145    pub const ALL: [Repeats; 5] = [
146        Repeats::Never,
147        Repeats::Daily,
148        Repeats::Weekly,
149        Repeats::Monthly,
150        Repeats::Yearly,
151    ];
152
153    /// The choice that stands for `frequency`.
154    pub fn of(frequency: Option<Frequency>) -> Self {
155        match frequency {
156            None => Repeats::Never,
157            Some(Frequency::Daily) => Repeats::Daily,
158            Some(Frequency::Weekly) => Repeats::Weekly,
159            Some(Frequency::Monthly) => Repeats::Monthly,
160            Some(Frequency::Yearly) => Repeats::Yearly,
161        }
162    }
163
164    /// The unit the entry repeats in, or `None` when it does not.
165    pub fn frequency(self) -> Option<Frequency> {
166        match self {
167            Repeats::Never => None,
168            Repeats::Daily => Some(Frequency::Daily),
169            Repeats::Weekly => Some(Frequency::Weekly),
170            Repeats::Monthly => Some(Frequency::Monthly),
171            Repeats::Yearly => Some(Frequency::Yearly),
172        }
173    }
174
175    /// The name of the unit after a number: "week" after 1, "weeks" after
176    /// any other.
177    pub fn unit(self, interval: u32) -> &'static str {
178        let one = interval == 1;
179        match self {
180            Repeats::Never => "",
181            Repeats::Daily if one => "day",
182            Repeats::Daily => "days",
183            Repeats::Weekly if one => "week",
184            Repeats::Weekly => "weeks",
185            Repeats::Monthly if one => "month",
186            Repeats::Monthly => "months",
187            Repeats::Yearly if one => "year",
188            Repeats::Yearly => "years",
189        }
190    }
191}
192
193impl std::fmt::Display for Repeats {
194    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
195        f.write_str(match self {
196            Repeats::Never => "Does not repeat",
197            Repeats::Daily => "Daily",
198            Repeats::Weekly => "Weekly",
199            Repeats::Monthly => "Monthly",
200            Repeats::Yearly => "Yearly",
201        })
202    }
203}
204
205/// How a repeating entry stops, as the menu offers it.
206#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
207pub enum Stops {
208    #[default]
209    Never,
210    /// On a date picked beside the menu.
211    On,
212    /// After a number of occurrences typed beside the menu.
213    After,
214}
215
216impl Stops {
217    /// The choices in the menu.
218    pub const ALL: [Stops; 3] = [Stops::Never, Stops::On, Stops::After];
219}
220
221impl std::fmt::Display for Stops {
222    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
223        f.write_str(match self {
224            Stops::Never => "Never",
225            Stops::On => "On a date",
226            Stops::After => "After",
227        })
228    }
229}
230
231/// A [`Tone`] with a name for the colour menu.
232#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
233pub struct Colour(pub Tone);
234
235impl std::fmt::Display for Colour {
236    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
237        f.write_str(match self.0 {
238            Tone::Primary => "Default",
239            Tone::Neutral => "Neutral",
240            Tone::Success => "Green",
241            Tone::Warning => "Amber",
242            Tone::Destructive => "Red",
243        })
244    }
245}
246
247/// Changes to the form.
248#[derive(Debug, Clone, PartialEq)]
249pub enum Event {
250    Title(String),
251    AllDay(bool),
252    /// Sets the start or end date, and closes the date picker.
253    Date(Field, Date),
254    /// Sets the start or end time, in minutes from midnight.
255    Time(Field, u16),
256    Repeats(Repeats),
257    /// The text of the "every" field. Only its digits are kept.
258    Interval(String),
259    Stops(Stops),
260    /// Sets the last date of the repeat, and closes the date picker.
261    Until(Date),
262    /// The text of the "after" field. Only its digits are kept.
263    Count(String),
264    Tone(Tone),
265    Location(String),
266    /// An edit to the notes.
267    Notes(Action),
268    /// Opens the date picker for a field, or closes whichever is open
269    /// with `None`.
270    Picker(Option<Field>),
271    /// Opens or closes the date picker for the last date of the repeat.
272    UntilPicker(bool),
273    /// Moves the date picker by this many months.
274    PickerMonth(i32),
275}
276
277/// A date the form picks from a month.
278#[derive(Debug, Clone, Copy, PartialEq, Eq)]
279enum Target {
280    Field(Field),
281    Until,
282}
283
284/// A date picker that is open: whose it is, and the month it shows.
285#[derive(Debug, Clone, Copy, PartialEq, Eq)]
286struct Picker {
287    target: Target,
288    month: Date,
289}
290
291/// What the form holds. The end is kept at or after the start: moving the
292/// start moves the end with it, so the entry keeps its length. The last
293/// date of a repeat is kept on or after the start.
294#[derive(Debug, Clone)]
295pub struct State {
296    id: Option<EntryId>,
297    title: String,
298    all_day: bool,
299    start: (Date, u16),
300    end: (Date, u16),
301    repeats: Repeats,
302    interval: String,
303    stops: Stops,
304    until: Date,
305    count: String,
306    tone: Tone,
307    tag: Option<String>,
308    location: String,
309    notes: Content,
310    time_zone: TimeZone,
311    week_start: Weekday,
312    picker: Option<Picker>,
313}
314
315/// The digits of `text`, up to [`NUMBER_DIGITS`] of them.
316fn digits(text: &str) -> String {
317    text.chars()
318        .filter(char::is_ascii_digit)
319        .take(NUMBER_DIGITS)
320        .collect()
321}
322
323/// The number a field holds, at least 1. An empty field counts as 1.
324fn number(text: &str) -> u32 {
325    text.parse::<u32>().unwrap_or(1).max(1)
326}
327
328impl State {
329    /// A form for a new entry over the span the calendar asked for.
330    pub fn new(draft: &Draft, time_zone: &TimeZone) -> Self {
331        Self::over(draft.when, time_zone)
332    }
333
334    /// A form for changing `entry`.
335    pub fn edit(entry: &Entry, time_zone: &TimeZone) -> Self {
336        let mut form = Self {
337            id: Some(entry.id()),
338            title: entry.title().to_owned(),
339            tone: entry.tone_of(),
340            tag: entry.tag_of().map(str::to_owned),
341            location: entry.location_of().unwrap_or_default().to_owned(),
342            notes: Content::with_text(entry.notes_of().unwrap_or_default()),
343            ..Self::over(entry.when(), time_zone)
344        };
345        let Some(repeat) = entry.repeat_of() else {
346            return form;
347        };
348        form.repeats = Repeats::of(Some(repeat.frequency()));
349        form.interval = repeat.every().to_string();
350        match repeat.ends() {
351            Ends::Never => {}
352            Ends::On(date) => {
353                form.stops = Stops::On;
354                form.until = date;
355            }
356            Ends::After(count) => {
357                form.stops = Stops::After;
358                form.count = count.to_string();
359            }
360        }
361        form
362    }
363
364    fn over(when: When, time_zone: &TimeZone) -> Self {
365        let nine = 9 * 60;
366        let (all_day, start, end) = match when {
367            When::AllDay { first, last } => (true, (first, nine), (last, nine + DEFAULT_MINUTES)),
368            When::Timed { start, end } => (
369                false,
370                local(start, time_zone),
371                local(end.max(start), time_zone),
372            ),
373        };
374        Self {
375            id: None,
376            title: String::new(),
377            all_day,
378            start,
379            end,
380            repeats: Repeats::Never,
381            interval: String::from("1"),
382            stops: Stops::Never,
383            until: start.0.checked_add(1.month()).unwrap_or(start.0),
384            count: DEFAULT_COUNT.to_string(),
385            tone: Tone::default(),
386            tag: None,
387            location: String::new(),
388            notes: Content::new(),
389            time_zone: time_zone.clone(),
390            week_start: Weekday::Monday,
391            picker: None,
392        }
393    }
394
395    /// The day weeks start on in the date picker. Defaults to Monday.
396    pub fn with_week_start(mut self, week_start: Weekday) -> Self {
397        self.week_start = week_start;
398        self
399    }
400
401    /// The entry being changed, or `None` for a new one.
402    pub fn id(&self) -> Option<EntryId> {
403        self.id
404    }
405
406    pub fn is_new(&self) -> bool {
407        self.id.is_none()
408    }
409
410    pub fn title(&self) -> &str {
411        &self.title
412    }
413
414    pub fn is_all_day(&self) -> bool {
415        self.all_day
416    }
417
418    pub fn repeats(&self) -> Repeats {
419        self.repeats
420    }
421
422    /// How many units pass between repeats, at least 1.
423    pub fn interval(&self) -> u32 {
424        number(&self.interval)
425    }
426
427    pub fn stops(&self) -> Stops {
428        self.stops
429    }
430
431    /// The last date of the repeat, used when it stops on a date.
432    pub fn until(&self) -> Date {
433        self.until
434    }
435
436    /// How many occurrences there are, used when the repeat stops after
437    /// a number of them. At least 1.
438    pub fn count(&self) -> u32 {
439        number(&self.count)
440    }
441
442    /// The repeat rule the form describes, or `None` when the entry does
443    /// not repeat.
444    pub fn repeat(&self) -> Option<Repeat> {
445        let rule = Repeat::new(self.repeats.frequency()?).interval(self.interval());
446        Some(match self.stops {
447            Stops::Never => rule,
448            Stops::On => rule.until(self.until),
449            Stops::After => rule.count(self.count()),
450        })
451    }
452
453    pub fn tone(&self) -> Tone {
454        self.tone
455    }
456
457    pub fn location(&self) -> &str {
458        &self.location
459    }
460
461    /// The notes as text, without the space around them.
462    pub fn notes(&self) -> String {
463        self.notes.text().trim().to_owned()
464    }
465
466    /// Whether the date picker for the last date of the repeat is open.
467    pub fn is_picking_until(&self) -> bool {
468        self.picker
469            .is_some_and(|picker| picker.target == Target::Until)
470    }
471
472    /// The date of a field.
473    pub fn date(&self, field: Field) -> Date {
474        self.at(field).0
475    }
476
477    /// The time of a field, in minutes from midnight.
478    pub fn time(&self, field: Field) -> u16 {
479        self.at(field).1
480    }
481
482    /// The times a field's menu lists. The start's begins an hour before
483    /// the time chosen; the end's begins just after the start when both
484    /// are on the same day, since nothing earlier would be on that day.
485    pub fn times(&self, field: Field) -> Vec<TimeOfDay> {
486        let first = match field {
487            Field::End if self.end.0 == self.start.0 => self.start.1 + TIME_STEP,
488            _ => self.time(field).saturating_sub(60),
489        };
490        TimeOfDay::from(first % DAY_MINUTES)
491    }
492
493    /// The start or end whose date picker is open.
494    pub fn picker(&self) -> Option<Field> {
495        match self.picker?.target {
496            Target::Field(field) => Some(field),
497            Target::Until => None,
498        }
499    }
500
501    /// The span the form describes.
502    pub fn when(&self) -> When {
503        if self.all_day {
504            return When::all_day(self.start.0, self.end.0);
505        }
506        When::timed(
507            instant_at(self.start.0, self.start.1, &self.time_zone),
508            instant_at(self.end.0, self.end.1, &self.time_zone),
509        )
510    }
511
512    /// The entry the form describes. A new entry takes `new_id`; a changed
513    /// one keeps its own. A blank title becomes [`UNTITLED`].
514    pub fn entry(&self, new_id: EntryId) -> Entry {
515        let title = match self.title.trim() {
516            "" => UNTITLED,
517            title => title,
518        };
519        let mut entry = Entry::at(self.id.unwrap_or(new_id), title, self.when())
520            .tone(self.tone)
521            .location(self.location.clone())
522            .notes(self.notes());
523        if let Some(tag) = &self.tag {
524            entry = entry.tag(tag.clone());
525        }
526        if let Some(rule) = self.repeat() {
527            entry = entry.repeat(rule);
528        }
529        entry
530    }
531
532    pub fn update(&mut self, event: Event) {
533        match event {
534            Event::Title(title) => self.title = title,
535            Event::AllDay(all_day) => {
536                self.all_day = all_day;
537                self.settle(Field::End);
538            }
539            Event::Date(field, date) => {
540                self.picker = None;
541                self.set(field, (date, self.time(field)));
542            }
543            Event::Time(field, minute) => {
544                self.set(field, (self.date(field), minute.min(DAY_MINUTES - 1)));
545            }
546            Event::Repeats(repeats) => {
547                self.repeats = repeats;
548                if repeats == Repeats::Never && self.is_picking_until() {
549                    self.picker = None;
550                }
551            }
552            Event::Interval(text) => self.interval = digits(&text),
553            Event::Stops(stops) => {
554                self.stops = stops;
555                if stops != Stops::On && self.is_picking_until() {
556                    self.picker = None;
557                }
558            }
559            Event::Until(date) => {
560                self.picker = None;
561                self.until = date.max(self.start.0);
562            }
563            Event::Count(text) => self.count = digits(&text),
564            Event::Tone(tone) => self.tone = tone,
565            Event::Location(location) => self.location = location,
566            Event::Notes(action) => self.notes.perform(action),
567            Event::Picker(field) => {
568                self.picker = field.map(|field| Picker {
569                    target: Target::Field(field),
570                    month: self.date(field).first_of_month(),
571                });
572            }
573            Event::UntilPicker(open) => {
574                self.picker = open.then(|| Picker {
575                    target: Target::Until,
576                    month: self.until.first_of_month(),
577                });
578            }
579            Event::PickerMonth(months) => {
580                if let Some(picker) = &mut self.picker {
581                    picker.month = picker
582                        .month
583                        .checked_add(i64::from(months.clamp(-1200, 1200)).months())
584                        .unwrap_or(picker.month);
585                }
586            }
587        }
588    }
589
590    fn at(&self, field: Field) -> (Date, u16) {
591        match field {
592            Field::Start => self.start,
593            Field::End => self.end,
594        }
595    }
596
597    /// Sets a field. A new start carries the end along, keeping the
598    /// length; a new end is kept from going before the start.
599    fn set(&mut self, field: Field, to: (Date, u16)) {
600        match field {
601            Field::Start => {
602                let days = days_between(self.start.0, self.end.0);
603                let minutes = i32::from(self.end.1) - i32::from(self.start.1);
604                self.start = to;
605                let end = i32::from(to.1) + minutes;
606                self.end = (
607                    add_days(to.0, days + end.div_euclid(i32::from(DAY_MINUTES))),
608                    u16::try_from(end.rem_euclid(i32::from(DAY_MINUTES))).unwrap_or(0),
609                );
610            }
611            Field::End => self.end = to,
612        }
613        self.until = self.until.max(self.start.0);
614        self.settle(field);
615    }
616
617    /// The date a picker is for.
618    fn target_date(&self, target: Target) -> Date {
619        match target {
620            Target::Field(field) => self.date(field),
621            Target::Until => self.until,
622        }
623    }
624
625    /// Puts the end back at or after the start. Whole days may start and
626    /// end on the same day; a timed entry is at least one step long.
627    fn settle(&mut self, changed: Field) {
628        if self.all_day {
629            if self.end.0 < self.start.0 {
630                self.end.0 = self.start.0;
631            }
632            return;
633        }
634        if self.end > self.start {
635            return;
636        }
637        // An end time picked earlier than the start on the same day means
638        // the next day, as in "22:00 to 01:00".
639        if changed == Field::End && self.end.0 == self.start.0 && self.end.1 < self.start.1 {
640            self.end.0 = add_days(self.start.0, 1);
641            return;
642        }
643        let end = self.start.1 + TIME_STEP;
644        self.end = if end >= DAY_MINUTES {
645            (add_days(self.start.0, 1), end - DAY_MINUTES)
646        } else {
647            (self.start.0, end)
648        };
649    }
650}
651
652/// The date and minute of `instant` in `time_zone`.
653fn local(instant: Timestamp, time_zone: &TimeZone) -> (Date, u16) {
654    let date = date_of(instant, time_zone);
655    (date, minute_on(date, instant, time_zone))
656}
657
658fn days_between(from: Date, to: Date) -> i32 {
659    i32::try_from(to.duration_since(from).as_hours() / 24).unwrap_or(0)
660}
661
662/// An entry form builder. Convert it into an [`Element`] to render.
663pub struct Editor<'a, Message> {
664    state: &'a State,
665    on_event: Option<Box<dyn Fn(Event) -> Message + 'a>>,
666    on_submit: Option<Message>,
667    shortcuts: Shortcuts,
668}
669
670/// Renders the form for `state`. Without [`on_event`](Editor::on_event)
671/// every control renders disabled.
672pub fn editor<Message>(state: &State) -> Editor<'_, Message> {
673    Editor {
674        state,
675        on_event: None,
676        on_submit: None,
677        shortcuts: Shortcuts::all(),
678    }
679}
680
681impl<Message> std::fmt::Debug for Editor<'_, Message> {
682    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
683        f.debug_struct("Editor")
684            .field("state", self.state)
685            .field("enabled", &self.on_event.is_some())
686            .field("submits", &self.on_submit.is_some())
687            .field("shortcuts", &self.shortcuts)
688            .finish()
689    }
690}
691
692impl<'a, Message> Editor<'a, Message> {
693    pub fn on_event(mut self, on_event: impl Fn(Event) -> Message + 'a) -> Self {
694        self.on_event = Some(Box::new(on_event));
695        self
696    }
697
698    /// Sent when Enter is pressed in the title or the location, usually
699    /// the same message as the Save button.
700    pub fn on_submit(mut self, message: Message) -> Self {
701        self.on_submit = Some(message);
702        self
703    }
704
705    /// The editing shortcuts of the form's text fields. Defaults to all
706    /// of them.
707    pub fn shortcuts(mut self, shortcuts: Shortcuts) -> Self {
708        self.shortcuts = shortcuts;
709        self
710    }
711}
712
713type Handler<'a, Message> = Option<std::rc::Rc<dyn Fn(Event) -> Message + 'a>>;
714
715fn send<Message>(handler: &Handler<'_, Message>, event: Event) -> Option<Message> {
716    handler.as_ref().map(|handler| handler(event))
717}
718
719impl<'a, Message: Clone + 'a> From<Editor<'a, Message>> for Element<'a, Message> {
720    fn from(editor: Editor<'a, Message>) -> Self {
721        let Editor {
722            state,
723            on_event,
724            on_submit,
725            shortcuts,
726        } = editor;
727        let on_event: Handler<'a, Message> = on_event.map(std::rc::Rc::from);
728
729        let title = input("Add a title", state.title())
730            .shortcuts(shortcuts)
731            .on_input_maybe(
732                on_event
733                    .clone()
734                    .map(|handler| move |title| handler(Event::Title(title))),
735            )
736            .on_submit_maybe(on_submit.clone());
737        let all_day = switch(state.is_all_day()).label("All day").on_toggle_maybe(
738            on_event
739                .clone()
740                .map(|handler| move |on| handler(Event::AllDay(on))),
741        );
742
743        let repeats = select(&Repeats::ALL[..], Some(state.repeats()))
744            .width(Length::FillPortion(3))
745            .on_select_maybe(
746                on_event
747                    .clone()
748                    .map(|handler| move |repeats| handler(Event::Repeats(repeats))),
749            );
750        let colours: Vec<Colour> = Tone::ALL.into_iter().map(Colour).collect();
751        let colour = select(colours, Some(Colour(state.tone())))
752            .width(Length::FillPortion(2))
753            .on_select_maybe(
754                on_event
755                    .clone()
756                    .map(|handler| move |colour: Colour| handler(Event::Tone(colour.0))),
757            );
758
759        let location = input("Add a location", state.location())
760            .icon(lucide!(MapPin))
761            .shortcuts(shortcuts)
762            .on_input_maybe(
763                on_event
764                    .clone()
765                    .map(|handler| move |location| handler(Event::Location(location))),
766            )
767            .on_submit_maybe(on_submit);
768        let notes = textarea(&state.notes)
769            .id(notes_id())
770            .placeholder("Add notes")
771            .min_height(NOTES_HEIGHT)
772            .shortcuts(shortcuts)
773            .on_action_maybe(
774                on_event
775                    .clone()
776                    .map(|handler| move |action| handler(Event::Notes(action))),
777            );
778
779        let mut form = column![
780            title,
781            all_day,
782            moment(state, Field::Start, "Starts", &on_event),
783            moment(state, Field::End, "Ends", &on_event),
784            row![repeats, colour].spacing(space::SM),
785        ]
786        .spacing(space::MD)
787        .width(Length::Fill);
788        if state.repeats() != Repeats::Never {
789            form = form
790                .push(every(state, shortcuts, &on_event))
791                .push(stops(state, shortcuts, &on_event));
792        }
793        form.push(location).push(notes).into()
794    }
795}
796
797/// The name beside a field.
798fn name<'a, Message: 'a>(name: &'a str) -> Element<'a, Message> {
799    let label = text(name)
800        .size(text_size::SM)
801        .wrapping(text::Wrapping::None)
802        .style(|theme: &Theme| text::Style {
803            color: Some(Tokens::of(theme).muted_foreground),
804        });
805    container(label).width(Length::Fixed(NAME_WIDTH)).into()
806}
807
808/// A field for a small whole number.
809fn number_field<'a, Message: Clone + 'a>(
810    value: &str,
811    shortcuts: Shortcuts,
812    on_event: &Handler<'a, Message>,
813    event: fn(String) -> Event,
814) -> Element<'a, Message> {
815    input("1", value)
816        .width(NUMBER_WIDTH)
817        .shortcuts(shortcuts)
818        .on_input_maybe(
819            on_event
820                .clone()
821                .map(|handler| move |text| handler(event(text))),
822        )
823        .into()
824}
825
826/// How many units pass between repeats: "Every 2 weeks".
827fn every<'a, Message: Clone + 'a>(
828    state: &'a State,
829    shortcuts: Shortcuts,
830    on_event: &Handler<'a, Message>,
831) -> Element<'a, Message> {
832    let unit = text(state.repeats().unit(state.interval()))
833        .size(text_size::SM)
834        .wrapping(text::Wrapping::None);
835    row![
836        name("Every"),
837        number_field(&state.interval, shortcuts, on_event, Event::Interval),
838        unit,
839    ]
840    .spacing(space::SM)
841    .align_y(Alignment::Center)
842    .into()
843}
844
845/// How the repeat stops: never, on a date or after a number of times.
846fn stops<'a, Message: Clone + 'a>(
847    state: &'a State,
848    shortcuts: Shortcuts,
849    on_event: &Handler<'a, Message>,
850) -> Element<'a, Message> {
851    let handler = on_event.clone();
852    let choice = select(&Stops::ALL[..], Some(state.stops()))
853        .width(Length::Fill)
854        .on_select_maybe(handler.map(|handler| move |stops| handler(Event::Stops(stops))));
855    let mut controls = Row::new()
856        .spacing(space::SM)
857        .align_y(Alignment::Center)
858        .push(name("Stops"))
859        .push(choice);
860    match state.stops() {
861        Stops::Never => {}
862        Stops::On => controls = controls.push(date_field(state, Target::Until, on_event)),
863        Stops::After => {
864            let times = text(if state.count() == 1 { "time" } else { "times" })
865                .size(text_size::SM)
866                .wrapping(text::Wrapping::None);
867            controls = controls
868                .push(number_field(
869                    &state.count,
870                    shortcuts,
871                    on_event,
872                    Event::Count,
873                ))
874                .push(times);
875        }
876    }
877    controls.into()
878}
879
880/// One end of the entry: its name, its date and, unless it lasts all day,
881/// its time.
882fn moment<'a, Message: Clone + 'a>(
883    state: &'a State,
884    field: Field,
885    label: &'a str,
886    on_event: &Handler<'a, Message>,
887) -> Element<'a, Message> {
888    let mut controls = Row::new()
889        .spacing(space::SM)
890        .align_y(Alignment::Center)
891        .push(name(label))
892        .push(date_field(state, Target::Field(field), on_event));
893    if !state.is_all_day() {
894        let handler = on_event.clone();
895        controls = controls.push(
896            select(state.times(field), Some(TimeOfDay(state.time(field))))
897                .width(TIME_WIDTH)
898                .on_select_maybe(
899                    handler
900                        .map(|handler| move |time: TimeOfDay| handler(Event::Time(field, time.0))),
901                ),
902        );
903    }
904    controls.into()
905}
906
907/// A date as a button that opens a month to pick another from.
908fn date_field<'a, Message: Clone + 'a>(
909    state: &'a State,
910    target: Target,
911    on_event: &Handler<'a, Message>,
912) -> Element<'a, Message> {
913    let open = state.picker.filter(|picker| picker.target == target);
914    let toggle = match target {
915        Target::Field(field) => Event::Picker(open.is_none().then_some(field)),
916        Target::Until => Event::UntilPicker(open.is_none()),
917    };
918    let date = state.target_date(target);
919    let trigger = button(date.strftime("%a %-d %b %Y").to_string())
920        .variant(button::Variant::Outline)
921        .width(Length::Fill)
922        .on_press_maybe(send(on_event, toggle));
923
924    let content: Element<'a, Message> = match open {
925        Some(picker) => month_picker(state, picker, on_event),
926        None => Space::new().into(),
927    };
928    let mut date = popover(trigger, content)
929        .open(open.is_some())
930        .align(Align::Start)
931        .width(Length::Shrink)
932        .padding(space::MD);
933    if let Some(close) = send(on_event, Event::Picker(None)) {
934        date = date.on_dismiss(close);
935    }
936    container(date).width(Length::Fill).into()
937}
938
939/// A month of days to pick from, with arrows to the months either side.
940fn month_picker<'a, Message: Clone + 'a>(
941    state: &State,
942    picker: Picker,
943    on_event: &Handler<'a, Message>,
944) -> Element<'a, Message> {
945    let step = |glyph, label: &'static str, months: i32| {
946        icon_button(glyph)
947            .label(label)
948            .variant(icon_button::Variant::Ghost)
949            .size(Size::Sm)
950            .on_press_maybe(send(on_event, Event::PickerMonth(months)))
951    };
952    let name = text(picker.month.strftime("%B %Y").to_string())
953        .size(text_size::SM)
954        .font(theme::semibold())
955        .wrapping(text::Wrapping::None);
956    let header = row![
957        step(lucide!(ChevronLeft), "Previous month", -1),
958        container(name).center_x(Length::Fill),
959        step(lucide!(ChevronRight), "Next month", 1),
960    ]
961    .align_y(Alignment::Center);
962
963    let weeks = month_weeks(picker.month, state.week_start);
964    let mut grid = Column::new().spacing(2.0);
965    if let Some(week) = weeks.first() {
966        grid = grid.push(Row::with_children(week.iter().map(|date| {
967            container(text(weekday_label(*date, true)).size(text_size::XS).style(
968                |theme: &Theme| text::Style {
969                    color: Some(Tokens::of(theme).muted_foreground),
970                },
971            ))
972            .center(Length::Fixed(CELL))
973            .into()
974        })));
975    }
976    let chosen = state.target_date(picker.target);
977    let pick = move |date: Date| match picker.target {
978        Target::Field(field) => Event::Date(field, date),
979        Target::Until => Event::Until(date),
980    };
981    for week in &weeks {
982        grid = grid.push(Row::with_children(week.iter().map(|date| {
983            if date.month() != picker.month.month() {
984                return Space::new()
985                    .width(Length::Fixed(CELL))
986                    .height(Length::Fixed(CELL))
987                    .into();
988            }
989            let day = style::Day {
990                today: false,
991                selected: *date == chosen,
992                in_month: true,
993            };
994            let number = text(date.day().to_string())
995                .size(text_size::XS)
996                .wrapping(text::Wrapping::None);
997            widget::button(container(number).center(Length::Fill))
998                .width(Length::Fixed(CELL))
999                .height(Length::Fixed(CELL))
1000                .padding(0)
1001                .on_press_maybe(send(on_event, pick(*date)))
1002                .style(move |theme, status: Status| {
1003                    style::year_day(&Tokens::of(theme), day, status)
1004                })
1005                .into()
1006        })));
1007    }
1008    column![header, grid]
1009        .spacing(space::SM)
1010        .width(Length::Fixed(7.0 * CELL))
1011        .into()
1012}
1013
1014#[cfg(test)]
1015mod tests {
1016    use super::*;
1017    use jiff::civil::date;
1018
1019    const UTC: TimeZone = TimeZone::UTC;
1020
1021    /// A time on 19 June 2026.
1022    fn at(hour: u16, minute: u16) -> Timestamp {
1023        instant_at(date(2026, 6, 19), hour * 60 + minute, &UTC)
1024    }
1025
1026    fn timed() -> State {
1027        State::new(
1028            &Draft {
1029                when: When::timed(at(11, 0), at(12, 30)),
1030            },
1031            &UTC,
1032        )
1033    }
1034
1035    fn whole_day() -> State {
1036        State::new(
1037            &Draft {
1038                when: When::day(date(2026, 6, 19)),
1039            },
1040            &UTC,
1041        )
1042    }
1043
1044    #[test]
1045    fn a_new_form_starts_from_the_draft() {
1046        let form = timed();
1047        assert!(form.is_new());
1048        assert_eq!(form.id(), None);
1049        assert_eq!(form.title(), "");
1050        assert!(!form.is_all_day());
1051        assert_eq!(form.date(Field::Start), date(2026, 6, 19));
1052        assert_eq!((form.time(Field::Start), form.time(Field::End)), (660, 750));
1053        assert_eq!(form.repeats(), Repeats::Never);
1054        assert_eq!(form.tone(), Tone::Primary);
1055        assert_eq!(form.picker(), None);
1056        assert_eq!(form.when(), When::timed(at(11, 0), at(12, 30)));
1057
1058        let form = whole_day();
1059        assert!(form.is_all_day());
1060        assert_eq!(form.when(), When::day(date(2026, 6, 19)));
1061    }
1062
1063    #[test]
1064    fn editing_starts_from_the_entry_and_keeps_what_the_form_does_not_show() {
1065        let rule = Repeat::weekly().interval(2);
1066        let entry = Entry::new(EntryId(4), "Review", at(15, 0), at(16, 0))
1067            .tone(Tone::Success)
1068            .tag("work")
1069            .repeat(rule)
1070            .location("Room 4")
1071            .notes("Bring the plan\nand the figures");
1072        let mut form = State::edit(&entry, &UTC);
1073        assert_eq!(form.id(), Some(EntryId(4)));
1074        assert!(!form.is_new());
1075        assert_eq!(form.title(), "Review");
1076        assert_eq!(form.tone(), Tone::Success);
1077        assert_eq!(form.repeats(), Repeats::Weekly);
1078        assert_eq!(form.interval(), 2);
1079        assert_eq!(form.stops(), Stops::Never);
1080        assert_eq!(form.location(), "Room 4");
1081        assert_eq!(form.notes(), "Bring the plan\nand the figures");
1082        assert_eq!(form.entry(EntryId(99)), entry, "unchanged, with its own id");
1083
1084        form.update(Event::Title(String::from("Retro")));
1085        let saved = form.entry(EntryId(99));
1086        assert_eq!(saved.id(), EntryId(4));
1087        assert_eq!(saved.title(), "Retro");
1088        assert_eq!(saved.tag_of(), Some("work"));
1089        assert_eq!(saved.repeat_of(), Some(rule));
1090        assert_eq!(saved.location_of(), Some("Room 4"));
1091    }
1092
1093    #[test]
1094    fn a_blank_title_is_saved_as_untitled_and_a_new_entry_takes_the_id_given() {
1095        let mut form = timed();
1096        form.update(Event::Title(String::from("   ")));
1097        let entry = form.entry(EntryId(7));
1098        assert_eq!(entry.id(), EntryId(7));
1099        assert_eq!(entry.title(), UNTITLED);
1100        form.update(Event::Title(String::from("  Retro ")));
1101        assert_eq!(form.entry(EntryId(7)).title(), "Retro");
1102    }
1103
1104    #[test]
1105    fn moving_the_start_keeps_the_length() {
1106        let mut form = timed();
1107        form.update(Event::Time(Field::Start, 14 * 60));
1108        assert_eq!((form.time(Field::Start), form.time(Field::End)), (840, 930));
1109
1110        form.update(Event::Date(Field::Start, date(2026, 6, 22)));
1111        assert_eq!(form.date(Field::End), date(2026, 6, 22));
1112        assert_eq!(
1113            form.when(),
1114            When::timed(
1115                instant_at(date(2026, 6, 22), 840, &UTC),
1116                instant_at(date(2026, 6, 22), 930, &UTC)
1117            )
1118        );
1119
1120        // Late enough, the end rolls into the next day.
1121        form.update(Event::Time(Field::Start, 23 * 60));
1122        assert_eq!(form.date(Field::End), date(2026, 6, 23));
1123        assert_eq!(form.time(Field::End), 30);
1124    }
1125
1126    #[test]
1127    fn the_end_never_goes_before_the_start() {
1128        let mut form = timed();
1129        // An earlier time on the same day means the next day.
1130        form.update(Event::Time(Field::End, 9 * 60));
1131        assert_eq!(form.date(Field::End), date(2026, 6, 20));
1132        assert_eq!(form.time(Field::End), 540);
1133
1134        // An end date before the start comes back to just after it.
1135        form.update(Event::Date(Field::End, date(2026, 6, 1)));
1136        assert_eq!(form.date(Field::End), date(2026, 6, 19));
1137        assert_eq!(form.time(Field::End), 660 + TIME_STEP);
1138
1139        // The same time as the start is one step long.
1140        let mut form = timed();
1141        form.update(Event::Time(Field::End, 660));
1142        assert_eq!(form.time(Field::End), 660 + TIME_STEP);
1143
1144        // At the last step of the day, the shortest entry ends at midnight.
1145        let late = at(23, 45);
1146        let mut form = State::new(
1147            &Draft {
1148                when: When::timed(late, late),
1149            },
1150            &UTC,
1151        );
1152        form.update(Event::Time(Field::End, 23 * 60 + 45));
1153        assert_eq!(
1154            (form.date(Field::End), form.time(Field::End)),
1155            (date(2026, 6, 20), 0)
1156        );
1157    }
1158
1159    #[test]
1160    fn times_out_of_range_are_kept_within_the_day() {
1161        let mut form = timed();
1162        form.update(Event::Time(Field::Start, 5000));
1163        assert_eq!(form.time(Field::Start), DAY_MINUTES - 1);
1164    }
1165
1166    #[test]
1167    fn all_day_keeps_the_dates_and_brings_the_times_back() {
1168        let mut form = timed();
1169        form.update(Event::AllDay(true));
1170        assert_eq!(form.when(), When::day(date(2026, 6, 19)));
1171        form.update(Event::Date(Field::End, date(2026, 6, 21)));
1172        assert_eq!(
1173            form.when(),
1174            When::all_day(date(2026, 6, 19), date(2026, 6, 21))
1175        );
1176        form.update(Event::Date(Field::End, date(2026, 6, 1)));
1177        assert_eq!(form.date(Field::End), date(2026, 6, 19), "same day is fine");
1178        form.update(Event::AllDay(false));
1179        assert_eq!((form.time(Field::Start), form.time(Field::End)), (660, 750));
1180
1181        // A draft for a whole day has a morning hour ready.
1182        let mut form = whole_day();
1183        form.update(Event::AllDay(false));
1184        assert_eq!((form.time(Field::Start), form.time(Field::End)), (540, 600));
1185    }
1186
1187    #[test]
1188    fn repeat_and_colour_reach_the_entry() {
1189        let mut form = timed();
1190        form.update(Event::Repeats(Repeats::Weekly));
1191        form.update(Event::Tone(Tone::Warning));
1192        let entry = form.entry(EntryId(1));
1193        assert_eq!(entry.repeat_of(), Some(Repeat::weekly()));
1194        assert_eq!(entry.tone_of(), Tone::Warning);
1195        form.update(Event::Repeats(Repeats::Never));
1196        assert_eq!(form.entry(EntryId(1)).repeat_of(), None);
1197    }
1198
1199    #[test]
1200    fn every_repeat_choice_has_a_name_and_round_trips() {
1201        for choice in Repeats::ALL {
1202            assert!(!choice.to_string().is_empty());
1203            assert_eq!(Repeats::of(choice.frequency()), choice);
1204        }
1205        assert_eq!(Repeats::default(), Repeats::Never);
1206        assert_eq!(Repeats::Never.frequency(), None);
1207        let units: Vec<_> = Repeats::ALL
1208            .iter()
1209            .map(|choice| (choice.unit(1), choice.unit(2)))
1210            .collect();
1211        assert_eq!(
1212            units,
1213            vec![
1214                ("", ""),
1215                ("day", "days"),
1216                ("week", "weeks"),
1217                ("month", "months"),
1218                ("year", "years")
1219            ]
1220        );
1221        let names: Vec<_> = Stops::ALL.iter().map(Stops::to_string).collect();
1222        assert_eq!(names, vec!["Never", "On a date", "After"]);
1223        assert_eq!(Stops::default(), Stops::Never);
1224    }
1225
1226    #[test]
1227    fn a_repeat_takes_its_interval_and_its_end_from_the_form() {
1228        let mut form = timed();
1229        assert_eq!(form.repeat(), None);
1230        assert_eq!((form.interval(), form.count()), (1, DEFAULT_COUNT));
1231        assert_eq!(form.until(), date(2026, 7, 19), "a month after the start");
1232
1233        form.update(Event::Repeats(Repeats::Weekly));
1234        assert_eq!(form.repeat(), Some(Repeat::weekly()));
1235        form.update(Event::Interval(String::from("2")));
1236        assert_eq!(form.repeat(), Some(Repeat::weekly().interval(2)));
1237
1238        form.update(Event::Stops(Stops::After));
1239        form.update(Event::Count(String::from("6")));
1240        assert_eq!(form.repeat(), Some(Repeat::weekly().interval(2).count(6)));
1241
1242        form.update(Event::Stops(Stops::On));
1243        form.update(Event::Until(date(2026, 9, 1)));
1244        let rule = Repeat::weekly().interval(2).until(date(2026, 9, 1));
1245        assert_eq!(form.repeat(), Some(rule));
1246        assert_eq!(form.entry(EntryId(1)).repeat_of(), Some(rule));
1247
1248        // The interval and the end wait while the entry does not repeat.
1249        form.update(Event::Repeats(Repeats::Never));
1250        assert_eq!(form.repeat(), None);
1251        form.update(Event::Repeats(Repeats::Monthly));
1252        assert_eq!(
1253            form.repeat(),
1254            Some(Repeat::monthly().interval(2).until(date(2026, 9, 1)))
1255        );
1256    }
1257
1258    #[test]
1259    fn number_fields_keep_digits_and_count_blank_as_one() {
1260        let mut form = timed();
1261        form.update(Event::Repeats(Repeats::Daily));
1262        form.update(Event::Interval(String::from("a1b2c3d4")));
1263        assert_eq!(form.interval(), 123, "three digits at most");
1264        form.update(Event::Interval(String::new()));
1265        assert_eq!(form.interval(), 1, "blank while typing");
1266        form.update(Event::Interval(String::from("0")));
1267        assert_eq!(form.interval(), 1);
1268        assert_eq!(form.repeat(), Some(Repeat::daily()));
1269
1270        form.update(Event::Stops(Stops::After));
1271        form.update(Event::Count(String::from("-5 times")));
1272        assert_eq!(form.count(), 5);
1273        form.update(Event::Count(String::from("0")));
1274        assert_eq!(form.count(), 1);
1275    }
1276
1277    #[test]
1278    fn an_entry_ending_on_a_date_or_after_a_count_fills_the_form() {
1279        let base = Entry::new(EntryId(4), "Review", at(15, 0), at(16, 0));
1280        let on = base
1281            .clone()
1282            .repeat(Repeat::monthly().until(date(2026, 12, 19)));
1283        let form = State::edit(&on, &UTC);
1284        assert_eq!(form.repeats(), Repeats::Monthly);
1285        assert_eq!(form.stops(), Stops::On);
1286        assert_eq!(form.until(), date(2026, 12, 19));
1287        assert_eq!(form.entry(EntryId(9)), on);
1288
1289        let after = base.repeat(Repeat::yearly().interval(4).count(3));
1290        let form = State::edit(&after, &UTC);
1291        assert_eq!(form.repeats(), Repeats::Yearly);
1292        assert_eq!(form.stops(), Stops::After);
1293        assert_eq!((form.interval(), form.count()), (4, 3));
1294        assert_eq!(form.entry(EntryId(9)), after);
1295    }
1296
1297    #[test]
1298    fn the_last_date_of_a_repeat_stays_on_or_after_the_start() {
1299        let mut form = timed();
1300        form.update(Event::Repeats(Repeats::Daily));
1301        form.update(Event::Stops(Stops::On));
1302        form.update(Event::Until(date(2026, 6, 1)));
1303        assert_eq!(form.until(), date(2026, 6, 19), "not before the start");
1304
1305        form.update(Event::Until(date(2026, 6, 25)));
1306        form.update(Event::Date(Field::Start, date(2026, 8, 3)));
1307        assert_eq!(form.until(), date(2026, 8, 3), "carried by the start");
1308    }
1309
1310    #[test]
1311    fn the_picker_for_the_last_date_opens_turns_and_closes() {
1312        let mut form = timed();
1313        form.update(Event::Repeats(Repeats::Daily));
1314        form.update(Event::Stops(Stops::On));
1315        form.update(Event::UntilPicker(true));
1316        assert!(form.is_picking_until());
1317        assert_eq!(form.picker(), None, "not the start's or the end's");
1318        assert_eq!(form.picker.map(|p| p.month), Some(date(2026, 7, 1)));
1319        form.update(Event::PickerMonth(2));
1320        assert_eq!(form.picker.map(|p| p.month), Some(date(2026, 9, 1)));
1321        form.update(Event::Until(date(2026, 9, 14)));
1322        assert!(!form.is_picking_until());
1323        assert_eq!(form.until(), date(2026, 9, 14));
1324
1325        // One picker at a time, and it closes with the field it is for.
1326        form.update(Event::UntilPicker(true));
1327        form.update(Event::Picker(Some(Field::Start)));
1328        assert!(!form.is_picking_until());
1329        assert_eq!(form.picker(), Some(Field::Start));
1330        form.update(Event::UntilPicker(true));
1331        form.update(Event::UntilPicker(false));
1332        assert!(!form.is_picking_until());
1333        form.update(Event::UntilPicker(true));
1334        form.update(Event::Stops(Stops::Never));
1335        assert!(!form.is_picking_until());
1336        form.update(Event::Stops(Stops::On));
1337        form.update(Event::UntilPicker(true));
1338        form.update(Event::Repeats(Repeats::Never));
1339        assert!(!form.is_picking_until());
1340        form.update(Event::UntilPicker(true));
1341        form.update(Event::Picker(None));
1342        assert!(!form.is_picking_until());
1343    }
1344
1345    #[test]
1346    fn location_and_notes_reach_the_entry() {
1347        let mut form = timed();
1348        assert_eq!(form.location(), "");
1349        assert_eq!(form.notes(), "");
1350        let blank = form.entry(EntryId(1));
1351        assert_eq!((blank.location_of(), blank.notes_of()), (None, None));
1352
1353        form.update(Event::Location(String::from(" Room 4 ")));
1354        for letter in "Agenda".chars() {
1355            form.update(Event::Notes(Action::Edit(
1356                iced::widget::text_editor::Edit::Insert(letter),
1357            )));
1358        }
1359        form.update(Event::Notes(Action::Edit(
1360            iced::widget::text_editor::Edit::Enter,
1361        )));
1362        assert_eq!(form.notes(), "Agenda", "space at the ends is dropped");
1363        let entry = form.entry(EntryId(1));
1364        assert_eq!(entry.location_of(), Some("Room 4"));
1365        assert_eq!(entry.notes_of(), Some("Agenda"));
1366    }
1367
1368    #[test]
1369    fn times_and_colours_have_names() {
1370        assert_eq!(TimeOfDay(0).to_string(), "00:00");
1371        assert_eq!(TimeOfDay(570).to_string(), "09:30");
1372        let all = TimeOfDay::all();
1373        assert_eq!(all.len(), 96);
1374        assert_eq!(all.last(), Some(&TimeOfDay(1425)));
1375
1376        // A menu can start anywhere and still lists the whole day.
1377        let from_ten = TimeOfDay::from(607);
1378        assert_eq!(from_ten.len(), 96);
1379        assert_eq!(from_ten.first(), Some(&TimeOfDay(600)));
1380        assert_eq!(from_ten.last(), Some(&TimeOfDay(585)));
1381        assert_eq!(TimeOfDay::from(0), all);
1382        assert_eq!(TimeOfDay::from(9999).first(), Some(&TimeOfDay(1425)));
1383
1384        // The start's menu opens an hour early, the end's after the start.
1385        let form = timed();
1386        assert_eq!(form.times(Field::Start).first(), Some(&TimeOfDay(600)));
1387        assert_eq!(form.times(Field::End).first(), Some(&TimeOfDay(675)));
1388        let mut overnight = timed();
1389        overnight.update(Event::Date(Field::End, date(2026, 6, 20)));
1390        assert_eq!(
1391            overnight.times(Field::End).first(),
1392            Some(&TimeOfDay(750 - 60))
1393        );
1394        let names: Vec<_> = Tone::ALL
1395            .iter()
1396            .map(|tone| Colour(*tone).to_string())
1397            .collect();
1398        assert_eq!(names, vec!["Default", "Neutral", "Green", "Amber", "Red"]);
1399    }
1400
1401    #[test]
1402    fn the_date_picker_opens_on_the_field_month_and_closes_on_a_choice() {
1403        let mut form = timed().with_week_start(Weekday::Sunday);
1404        form.update(Event::Picker(Some(Field::End)));
1405        assert_eq!(form.picker(), Some(Field::End));
1406        assert_eq!(form.picker.map(|p| p.month), Some(date(2026, 6, 1)));
1407
1408        form.update(Event::PickerMonth(1));
1409        form.update(Event::PickerMonth(1));
1410        assert_eq!(form.picker.map(|p| p.month), Some(date(2026, 8, 1)));
1411        form.update(Event::PickerMonth(-3));
1412        assert_eq!(form.picker.map(|p| p.month), Some(date(2026, 5, 1)));
1413
1414        form.update(Event::Date(Field::End, date(2026, 6, 20)));
1415        assert_eq!(form.picker(), None);
1416        assert_eq!(form.date(Field::End), date(2026, 6, 20));
1417
1418        form.update(Event::Picker(Some(Field::Start)));
1419        form.update(Event::Picker(None));
1420        assert_eq!(form.picker(), None);
1421        form.update(Event::PickerMonth(1));
1422        assert_eq!(form.picker(), None, "nothing to move");
1423    }
1424
1425    #[test]
1426    fn builder_defaults_and_options() {
1427        let form = timed();
1428        let built: Editor<'_, Event> = editor(&form);
1429        assert!(built.on_event.is_none());
1430        assert!(built.on_submit.is_none());
1431        assert_eq!(built.shortcuts, Shortcuts::all());
1432
1433        let built = built
1434            .on_event(|event| event)
1435            .on_submit(Event::Picker(None))
1436            .shortcuts(Shortcuts::none());
1437        assert!(built.on_event.is_some());
1438        assert!(built.on_submit.is_some());
1439        assert_eq!(built.shortcuts, Shortcuts::none());
1440        assert!(format!("{built:?}").contains("enabled: true"));
1441    }
1442}