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::checkbox::checkbox;
62use crate::primitives::icon_button::{self, icon_button};
63use crate::primitives::input::{Shortcuts, input};
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    /// Reads a time typed as "9:40", "09:40", "940" or "0940". `None`
126    /// for anything else or a time outside the day.
127    pub fn parse(text: &str) -> Option<TimeOfDay> {
128        let text = text.trim();
129        if text.is_empty() || !text.chars().all(|c| c.is_ascii_digit() || c == ':') {
130            return None;
131        }
132        let (hours, minutes) = match text.split_once(':') {
133            Some(parts) => parts,
134            None if (3..=4).contains(&text.len()) => text.split_at(text.len() - 2),
135            None => return None,
136        };
137        if !(1..=2).contains(&hours.len()) || minutes.len() != 2 {
138            return None;
139        }
140        let (hours, minutes) = (hours.parse::<u16>().ok()?, minutes.parse::<u16>().ok()?);
141        (hours < 24 && minutes < 60).then_some(TimeOfDay(hours * 60 + minutes))
142    }
143}
144
145impl std::fmt::Display for TimeOfDay {
146    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
147        write!(f, "{:02}:{:02}", self.0 / 60, self.0 % 60)
148    }
149}
150
151/// Whether the entry repeats and in what unit, as the menu offers it.
152#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
153pub enum Repeats {
154    #[default]
155    Never,
156    Daily,
157    Weekly,
158    Monthly,
159    Yearly,
160}
161
162impl Repeats {
163    /// The choices in the menu.
164    pub const ALL: [Repeats; 5] = [
165        Repeats::Never,
166        Repeats::Daily,
167        Repeats::Weekly,
168        Repeats::Monthly,
169        Repeats::Yearly,
170    ];
171
172    /// The choice that stands for `frequency`.
173    pub fn of(frequency: Option<Frequency>) -> Self {
174        match frequency {
175            None => Repeats::Never,
176            Some(Frequency::Daily) => Repeats::Daily,
177            Some(Frequency::Weekly) => Repeats::Weekly,
178            Some(Frequency::Monthly) => Repeats::Monthly,
179            Some(Frequency::Yearly) => Repeats::Yearly,
180        }
181    }
182
183    /// The unit the entry repeats in, or `None` when it does not.
184    pub fn frequency(self) -> Option<Frequency> {
185        match self {
186            Repeats::Never => None,
187            Repeats::Daily => Some(Frequency::Daily),
188            Repeats::Weekly => Some(Frequency::Weekly),
189            Repeats::Monthly => Some(Frequency::Monthly),
190            Repeats::Yearly => Some(Frequency::Yearly),
191        }
192    }
193
194    /// The name of the unit after a number: "week" after 1, "weeks" after
195    /// any other.
196    pub fn unit(self, interval: u32) -> &'static str {
197        let one = interval == 1;
198        match self {
199            Repeats::Never => "",
200            Repeats::Daily if one => "day",
201            Repeats::Daily => "days",
202            Repeats::Weekly if one => "week",
203            Repeats::Weekly => "weeks",
204            Repeats::Monthly if one => "month",
205            Repeats::Monthly => "months",
206            Repeats::Yearly if one => "year",
207            Repeats::Yearly => "years",
208        }
209    }
210}
211
212impl std::fmt::Display for Repeats {
213    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
214        f.write_str(match self {
215            Repeats::Never => "Does not repeat",
216            Repeats::Daily => "Daily",
217            Repeats::Weekly => "Weekly",
218            Repeats::Monthly => "Monthly",
219            Repeats::Yearly => "Yearly",
220        })
221    }
222}
223
224/// How a repeating entry stops, as the menu offers it.
225#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
226pub enum Stops {
227    #[default]
228    Never,
229    /// On a date picked beside the menu.
230    On,
231    /// After a number of occurrences typed beside the menu.
232    After,
233}
234
235impl Stops {
236    /// The choices in the menu.
237    pub const ALL: [Stops; 3] = [Stops::Never, Stops::On, Stops::After];
238}
239
240impl std::fmt::Display for Stops {
241    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
242        f.write_str(match self {
243            Stops::Never => "Never",
244            Stops::On => "On a date",
245            Stops::After => "After",
246        })
247    }
248}
249
250/// A [`Tone`] with a name for the colour menu.
251#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
252pub struct Colour(pub Tone);
253
254impl std::fmt::Display for Colour {
255    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
256        f.write_str(match self.0 {
257            Tone::Primary => "Default",
258            Tone::Neutral => "Neutral",
259            Tone::Success => "Green",
260            Tone::Warning => "Amber",
261            Tone::Destructive => "Red",
262        })
263    }
264}
265
266/// Changes to the form.
267#[derive(Debug, Clone, PartialEq)]
268pub enum Event {
269    Title(String),
270    AllDay(bool),
271    /// Sets the start or end date, and closes the date picker.
272    Date(Field, Date),
273    /// Sets the start or end time, in minutes from midnight.
274    Time(Field, u16),
275    Repeats(Repeats),
276    /// The text of the "every" field. Only its digits are kept.
277    Interval(String),
278    Stops(Stops),
279    /// Sets the last date of the repeat, and closes the date picker.
280    Until(Date),
281    /// The text of the "after" field. Only its digits are kept.
282    Count(String),
283    Tone(Tone),
284    Location(String),
285    /// An edit to the notes.
286    Notes(Action),
287    /// Opens the date picker for a field, or closes whichever is open
288    /// with `None`.
289    Picker(Option<Field>),
290    /// Opens or closes the date picker for the last date of the repeat.
291    UntilPicker(bool),
292    /// Moves the date picker by this many months.
293    PickerMonth(i32),
294}
295
296/// A date the form picks from a month.
297#[derive(Debug, Clone, Copy, PartialEq, Eq)]
298enum Target {
299    Field(Field),
300    Until,
301}
302
303/// A date picker that is open: whose it is, and the month it shows.
304#[derive(Debug, Clone, Copy, PartialEq, Eq)]
305struct Picker {
306    target: Target,
307    month: Date,
308}
309
310/// What the form holds. The end is kept at or after the start: moving the
311/// start moves the end with it, so the entry keeps its length. The last
312/// date of a repeat is kept on or after the start.
313#[derive(Debug, Clone)]
314pub struct State {
315    id: Option<EntryId>,
316    title: String,
317    all_day: bool,
318    start: (Date, u16),
319    end: (Date, u16),
320    repeats: Repeats,
321    interval: String,
322    stops: Stops,
323    until: Date,
324    count: String,
325    tone: Tone,
326    tag: Option<String>,
327    location: String,
328    notes: Content,
329    time_zone: TimeZone,
330    week_start: Weekday,
331    picker: Option<Picker>,
332}
333
334/// The digits of `text`, up to [`NUMBER_DIGITS`] of them.
335fn digits(text: &str) -> String {
336    text.chars()
337        .filter(char::is_ascii_digit)
338        .take(NUMBER_DIGITS)
339        .collect()
340}
341
342/// The number a field holds, at least 1. An empty field counts as 1.
343fn number(text: &str) -> u32 {
344    text.parse::<u32>().unwrap_or(1).max(1)
345}
346
347impl State {
348    /// A form for a new entry over the span the calendar asked for.
349    pub fn new(draft: &Draft, time_zone: &TimeZone) -> Self {
350        Self::over(draft.when, time_zone)
351    }
352
353    /// A form for changing `entry`.
354    pub fn edit(entry: &Entry, time_zone: &TimeZone) -> Self {
355        let mut form = Self {
356            id: Some(entry.id()),
357            title: entry.title().to_owned(),
358            tone: entry.tone_of(),
359            tag: entry.tag_of().map(str::to_owned),
360            location: entry.location_of().unwrap_or_default().to_owned(),
361            notes: Content::with_text(entry.notes_of().unwrap_or_default()),
362            ..Self::over(entry.when(), time_zone)
363        };
364        let Some(repeat) = entry.repeat_of() else {
365            return form;
366        };
367        form.repeats = Repeats::of(Some(repeat.frequency()));
368        form.interval = repeat.every().to_string();
369        match repeat.ends() {
370            Ends::Never => {}
371            Ends::On(date) => {
372                form.stops = Stops::On;
373                form.until = date;
374            }
375            Ends::After(count) => {
376                form.stops = Stops::After;
377                form.count = count.to_string();
378            }
379        }
380        form
381    }
382
383    fn over(when: When, time_zone: &TimeZone) -> Self {
384        let nine = 9 * 60;
385        let (all_day, start, end) = match when {
386            When::AllDay { first, last } => (true, (first, nine), (last, nine + DEFAULT_MINUTES)),
387            When::Timed { start, end } => (
388                false,
389                local(start, time_zone),
390                local(end.max(start), time_zone),
391            ),
392        };
393        Self {
394            id: None,
395            title: String::new(),
396            all_day,
397            start,
398            end,
399            repeats: Repeats::Never,
400            interval: String::from("1"),
401            stops: Stops::Never,
402            until: start.0.checked_add(1.month()).unwrap_or(start.0),
403            count: DEFAULT_COUNT.to_string(),
404            tone: Tone::default(),
405            tag: None,
406            location: String::new(),
407            notes: Content::new(),
408            time_zone: time_zone.clone(),
409            week_start: Weekday::Monday,
410            picker: None,
411        }
412    }
413
414    /// The day weeks start on in the date picker. Defaults to Monday.
415    pub fn with_week_start(mut self, week_start: Weekday) -> Self {
416        self.week_start = week_start;
417        self
418    }
419
420    /// The day weeks start on in the date picker.
421    pub fn week_start(&self) -> Weekday {
422        self.week_start
423    }
424
425    /// The entry being changed, or `None` for a new one.
426    pub fn id(&self) -> Option<EntryId> {
427        self.id
428    }
429
430    pub fn is_new(&self) -> bool {
431        self.id.is_none()
432    }
433
434    pub fn title(&self) -> &str {
435        &self.title
436    }
437
438    pub fn is_all_day(&self) -> bool {
439        self.all_day
440    }
441
442    pub fn repeats(&self) -> Repeats {
443        self.repeats
444    }
445
446    /// How many units pass between repeats, at least 1.
447    pub fn interval(&self) -> u32 {
448        number(&self.interval)
449    }
450
451    pub fn stops(&self) -> Stops {
452        self.stops
453    }
454
455    /// The last date of the repeat, used when it stops on a date.
456    pub fn until(&self) -> Date {
457        self.until
458    }
459
460    /// How many occurrences there are, used when the repeat stops after
461    /// a number of them. At least 1.
462    pub fn count(&self) -> u32 {
463        number(&self.count)
464    }
465
466    /// The repeat rule the form describes, or `None` when the entry does
467    /// not repeat.
468    pub fn repeat(&self) -> Option<Repeat> {
469        let rule = Repeat::new(self.repeats.frequency()?).interval(self.interval());
470        Some(match self.stops {
471            Stops::Never => rule,
472            Stops::On => rule.until(self.until),
473            Stops::After => rule.count(self.count()),
474        })
475    }
476
477    pub fn tone(&self) -> Tone {
478        self.tone
479    }
480
481    pub fn location(&self) -> &str {
482        &self.location
483    }
484
485    /// The notes as text, without the space around them.
486    pub fn notes(&self) -> String {
487        self.notes.text().trim().to_owned()
488    }
489
490    /// The notes buffer, for drawing the notes in a text area of the
491    /// app's own.
492    pub fn notes_content(&self) -> &Content {
493        &self.notes
494    }
495
496    /// The month the open date picker shows, as its first day, or `None`
497    /// when no picker is open.
498    pub fn picker_month(&self) -> Option<Date> {
499        self.picker.map(|picker| picker.month)
500    }
501
502    /// The text of the "every" field as typed, which may be blank.
503    pub fn interval_text(&self) -> &str {
504        &self.interval
505    }
506
507    /// The text of the "after" field as typed, which may be blank.
508    pub fn count_text(&self) -> &str {
509        &self.count
510    }
511
512    /// Whether the date picker for the last date of the repeat is open.
513    pub fn is_picking_until(&self) -> bool {
514        self.picker
515            .is_some_and(|picker| picker.target == Target::Until)
516    }
517
518    /// The date of a field.
519    pub fn date(&self, field: Field) -> Date {
520        self.at(field).0
521    }
522
523    /// The time of a field, in minutes from midnight.
524    pub fn time(&self, field: Field) -> u16 {
525        self.at(field).1
526    }
527
528    /// The times a field's menu lists. The start's is the whole day in
529    /// order. The end's begins just after the start when both are on the
530    /// same day and carries on round midnight, so the times before the
531    /// start, which would end the entry the next day, come last. The menu
532    /// opens with the field's time in the middle, filters as you type and
533    /// takes a typed time off the [`TIME_STEP`] grid.
534    pub fn times(&self, field: Field) -> Vec<TimeOfDay> {
535        match field {
536            Field::End if self.end.0 == self.start.0 => {
537                TimeOfDay::from((self.start.1 + TIME_STEP) % DAY_MINUTES)
538            }
539            _ => TimeOfDay::all(),
540        }
541    }
542
543    /// The start or end whose date picker is open.
544    pub fn picker(&self) -> Option<Field> {
545        match self.picker?.target {
546            Target::Field(field) => Some(field),
547            Target::Until => None,
548        }
549    }
550
551    /// The span the form describes.
552    pub fn when(&self) -> When {
553        if self.all_day {
554            return When::all_day(self.start.0, self.end.0);
555        }
556        When::timed(
557            instant_at(self.start.0, self.start.1, &self.time_zone),
558            instant_at(self.end.0, self.end.1, &self.time_zone),
559        )
560    }
561
562    /// The entry the form describes. A new entry takes `new_id`; a changed
563    /// one keeps its own. A blank title becomes [`UNTITLED`].
564    pub fn entry(&self, new_id: EntryId) -> Entry {
565        let title = match self.title.trim() {
566            "" => UNTITLED,
567            title => title,
568        };
569        let mut entry = Entry::at(self.id.unwrap_or(new_id), title, self.when())
570            .tone(self.tone)
571            .location(self.location.clone())
572            .notes(self.notes());
573        if let Some(tag) = &self.tag {
574            entry = entry.tag(tag.clone());
575        }
576        if let Some(rule) = self.repeat() {
577            entry = entry.repeat(rule);
578        }
579        entry
580    }
581
582    pub fn update(&mut self, event: Event) {
583        match event {
584            Event::Title(title) => self.title = title,
585            Event::AllDay(all_day) => {
586                self.all_day = all_day;
587                self.settle(Field::End);
588            }
589            Event::Date(field, date) => {
590                self.picker = None;
591                self.set(field, (date, self.time(field)));
592            }
593            Event::Time(field, minute) => {
594                self.set(field, (self.date(field), minute.min(DAY_MINUTES - 1)));
595            }
596            Event::Repeats(repeats) => {
597                self.repeats = repeats;
598                if repeats == Repeats::Never && self.is_picking_until() {
599                    self.picker = None;
600                }
601            }
602            Event::Interval(text) => self.interval = digits(&text),
603            Event::Stops(stops) => {
604                self.stops = stops;
605                if stops != Stops::On && self.is_picking_until() {
606                    self.picker = None;
607                }
608            }
609            Event::Until(date) => {
610                self.picker = None;
611                self.until = date.max(self.start.0);
612            }
613            Event::Count(text) => self.count = digits(&text),
614            Event::Tone(tone) => self.tone = tone,
615            Event::Location(location) => self.location = location,
616            Event::Notes(action) => self.notes.perform(action),
617            Event::Picker(field) => {
618                self.picker = field.map(|field| Picker {
619                    target: Target::Field(field),
620                    month: self.date(field).first_of_month(),
621                });
622            }
623            Event::UntilPicker(open) => {
624                self.picker = open.then(|| Picker {
625                    target: Target::Until,
626                    month: self.until.first_of_month(),
627                });
628            }
629            Event::PickerMonth(months) => {
630                if let Some(picker) = &mut self.picker {
631                    picker.month = picker
632                        .month
633                        .checked_add(i64::from(months.clamp(-1200, 1200)).months())
634                        .unwrap_or(picker.month);
635                }
636            }
637        }
638    }
639
640    fn at(&self, field: Field) -> (Date, u16) {
641        match field {
642            Field::Start => self.start,
643            Field::End => self.end,
644        }
645    }
646
647    /// Sets a field. A new start carries the end along, keeping the
648    /// length; a new end is kept from going before the start.
649    fn set(&mut self, field: Field, to: (Date, u16)) {
650        match field {
651            Field::Start => {
652                let days = days_between(self.start.0, self.end.0);
653                let minutes = i32::from(self.end.1) - i32::from(self.start.1);
654                self.start = to;
655                let end = i32::from(to.1) + minutes;
656                self.end = (
657                    add_days(to.0, days + end.div_euclid(i32::from(DAY_MINUTES))),
658                    u16::try_from(end.rem_euclid(i32::from(DAY_MINUTES))).unwrap_or(0),
659                );
660            }
661            Field::End => self.end = to,
662        }
663        self.until = self.until.max(self.start.0);
664        self.settle(field);
665    }
666
667    /// The date a picker is for.
668    fn target_date(&self, target: Target) -> Date {
669        match target {
670            Target::Field(field) => self.date(field),
671            Target::Until => self.until,
672        }
673    }
674
675    /// Puts the end back at or after the start. Whole days may start and
676    /// end on the same day; a timed entry is at least one step long.
677    fn settle(&mut self, changed: Field) {
678        if self.all_day {
679            if self.end.0 < self.start.0 {
680                self.end.0 = self.start.0;
681            }
682            return;
683        }
684        if self.end > self.start {
685            return;
686        }
687        // An end time picked earlier than the start on the same day means
688        // the next day, as in "22:00 to 01:00".
689        if changed == Field::End && self.end.0 == self.start.0 && self.end.1 < self.start.1 {
690            self.end.0 = add_days(self.start.0, 1);
691            return;
692        }
693        let end = self.start.1 + TIME_STEP;
694        self.end = if end >= DAY_MINUTES {
695            (add_days(self.start.0, 1), end - DAY_MINUTES)
696        } else {
697            (self.start.0, end)
698        };
699    }
700}
701
702/// The date and minute of `instant` in `time_zone`.
703fn local(instant: Timestamp, time_zone: &TimeZone) -> (Date, u16) {
704    let date = date_of(instant, time_zone);
705    (date, minute_on(date, instant, time_zone))
706}
707
708fn days_between(from: Date, to: Date) -> i32 {
709    i32::try_from(to.duration_since(from).as_hours() / 24).unwrap_or(0)
710}
711
712/// A part of the form, for leaving it out with [`Editor::without`].
713#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
714pub enum Part {
715    Title,
716    AllDay,
717    Starts,
718    Ends,
719    /// The repeat menu, and the "every" and "stops" rows under it.
720    Repeat,
721    Colour,
722    Location,
723    Notes,
724}
725
726impl Part {
727    pub const ALL: [Part; 8] = [
728        Part::Title,
729        Part::AllDay,
730        Part::Starts,
731        Part::Ends,
732        Part::Repeat,
733        Part::Colour,
734        Part::Location,
735        Part::Notes,
736    ];
737}
738
739/// An entry form builder. Convert it into an [`Element`] to render the
740/// whole form, or call [`fields`](Editor::fields) to lay out its parts.
741pub struct Editor<'a, Message> {
742    state: &'a State,
743    on_event: Option<Box<dyn Fn(Event) -> Message + 'a>>,
744    on_submit: Option<Message>,
745    shortcuts: Shortcuts,
746    without: Vec<Part>,
747}
748
749/// Renders the form for `state`. Without [`on_event`](Editor::on_event)
750/// every control renders disabled.
751pub fn editor<Message>(state: &State) -> Editor<'_, Message> {
752    Editor {
753        state,
754        on_event: None,
755        on_submit: None,
756        shortcuts: Shortcuts::all(),
757        without: Vec::new(),
758    }
759}
760
761impl<Message> std::fmt::Debug for Editor<'_, Message> {
762    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
763        f.debug_struct("Editor")
764            .field("state", self.state)
765            .field("enabled", &self.on_event.is_some())
766            .field("submits", &self.on_submit.is_some())
767            .field("shortcuts", &self.shortcuts)
768            .field("without", &self.without)
769            .finish()
770    }
771}
772
773/// The form's parts as separate elements, for an app that lays them out
774/// itself. A part left out with [`Editor::without`] is `None`, and so are
775/// `every` and `stops` while the entry does not repeat.
776pub struct Fields<'a, Message> {
777    pub title: Option<Element<'a, Message>>,
778    pub all_day: Option<Element<'a, Message>>,
779    pub starts: Option<Element<'a, Message>>,
780    pub ends: Option<Element<'a, Message>>,
781    pub repeat: Option<Element<'a, Message>>,
782    /// "Every 2 weeks".
783    pub every: Option<Element<'a, Message>>,
784    /// "Stops on a date" or "after 6 times".
785    pub stops: Option<Element<'a, Message>>,
786    pub colour: Option<Element<'a, Message>>,
787    pub location: Option<Element<'a, Message>>,
788    pub notes: Option<Element<'a, Message>>,
789}
790
791impl<Message> std::fmt::Debug for Fields<'_, Message> {
792    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
793        f.debug_struct("Fields")
794            .field("title", &self.title.is_some())
795            .field("all_day", &self.all_day.is_some())
796            .field("starts", &self.starts.is_some())
797            .field("ends", &self.ends.is_some())
798            .field("repeat", &self.repeat.is_some())
799            .field("every", &self.every.is_some())
800            .field("stops", &self.stops.is_some())
801            .field("colour", &self.colour.is_some())
802            .field("location", &self.location.is_some())
803            .field("notes", &self.notes.is_some())
804            .finish()
805    }
806}
807
808impl<'a, Message> Editor<'a, Message> {
809    pub fn on_event(mut self, on_event: impl Fn(Event) -> Message + 'a) -> Self {
810        self.on_event = Some(Box::new(on_event));
811        self
812    }
813
814    /// Sent when Enter is pressed in the title or the location, usually
815    /// the same message as the Save button.
816    pub fn on_submit(mut self, message: Message) -> Self {
817        self.on_submit = Some(message);
818        self
819    }
820
821    /// The editing shortcuts of the form's text fields. Defaults to all
822    /// of them.
823    pub fn shortcuts(mut self, shortcuts: Shortcuts) -> Self {
824        self.shortcuts = shortcuts;
825        self
826    }
827
828    /// Leaves a part out of the form. What the entry holds for it is kept.
829    pub fn without(mut self, part: Part) -> Self {
830        if !self.without.contains(&part) {
831            self.without.push(part);
832        }
833        self
834    }
835
836    /// Whether the form draws `part`.
837    pub fn shows(&self, part: Part) -> bool {
838        !self.without.contains(&part)
839    }
840}
841
842impl<'a, Message: Clone + 'a> Editor<'a, Message> {
843    /// The form's parts as separate elements.
844    pub fn fields(self) -> Fields<'a, Message> {
845        let shows = |part| !self.without.contains(&part);
846        let Editor {
847            state,
848            on_event,
849            on_submit,
850            shortcuts,
851            ..
852        } = self;
853        let on_event: Handler<'a, Message> = on_event.map(std::rc::Rc::from);
854        let repeating = state.repeats() != Repeats::Never;
855
856        let title = shows(Part::Title).then(|| {
857            input("Add a title", state.title())
858                .shortcuts(shortcuts)
859                .on_input_maybe(
860                    on_event
861                        .clone()
862                        .map(|handler| move |title| handler(Event::Title(title))),
863                )
864                .on_submit_maybe(on_submit.clone())
865                .into()
866        });
867        // A check box, since the form only applies on save.
868        let all_day = shows(Part::AllDay).then(|| {
869            checkbox(state.is_all_day())
870                .label("All day")
871                .on_toggle_maybe(
872                    on_event
873                        .clone()
874                        .map(|handler| move |on| handler(Event::AllDay(on))),
875                )
876                .into()
877        });
878        let repeat = shows(Part::Repeat).then(|| {
879            select(&Repeats::ALL[..], Some(state.repeats()))
880                .width(Length::Fill)
881                .on_select_maybe(
882                    on_event
883                        .clone()
884                        .map(|handler| move |repeats| handler(Event::Repeats(repeats))),
885                )
886                .into()
887        });
888        let colour = shows(Part::Colour).then(|| colour_menu(state, &on_event));
889        let location = shows(Part::Location).then(|| {
890            input("Add a location", state.location())
891                .icon(lucide!(MapPin))
892                .shortcuts(shortcuts)
893                .on_input_maybe(
894                    on_event
895                        .clone()
896                        .map(|handler| move |location| handler(Event::Location(location))),
897                )
898                .on_submit_maybe(on_submit)
899                .into()
900        });
901        let notes = shows(Part::Notes).then(|| {
902            textarea(&state.notes)
903                .id(notes_id())
904                .placeholder("Add notes")
905                .min_height(NOTES_HEIGHT)
906                .shortcuts(shortcuts)
907                .on_action_maybe(
908                    on_event
909                        .clone()
910                        .map(|handler| move |action| handler(Event::Notes(action))),
911                )
912                .into()
913        });
914
915        Fields {
916            title,
917            all_day,
918            starts: shows(Part::Starts).then(|| moment(state, Field::Start, "Starts", &on_event)),
919            ends: shows(Part::Ends).then(|| moment(state, Field::End, "Ends", &on_event)),
920            repeat,
921            every: (shows(Part::Repeat) && repeating).then(|| every(state, shortcuts, &on_event)),
922            stops: (shows(Part::Repeat) && repeating).then(|| stops(state, shortcuts, &on_event)),
923            colour,
924            location,
925            notes,
926        }
927    }
928}
929
930/// The colour menu, each colour with a swatch before its name.
931fn colour_menu<'a, Message: Clone + 'a>(
932    state: &State,
933    on_event: &Handler<'a, Message>,
934) -> Element<'a, Message> {
935    let colours: Vec<Colour> = Tone::ALL.into_iter().map(Colour).collect();
936    select(colours, Some(Colour(state.tone())))
937        .width(Length::Fill)
938        .leading(|colour: &Colour| {
939            let tone = colour.0;
940            Some(theme::swatch(move |theme: &Theme| style::tone(&Tokens::of(theme), tone)).into())
941        })
942        .on_select_maybe(
943            on_event
944                .clone()
945                .map(|handler| move |colour: Colour| handler(Event::Tone(colour.0))),
946        )
947        .into()
948}
949
950type Handler<'a, Message> = Option<std::rc::Rc<dyn Fn(Event) -> Message + 'a>>;
951
952fn send<Message>(handler: &Handler<'_, Message>, event: Event) -> Option<Message> {
953    handler.as_ref().map(|handler| handler(event))
954}
955
956impl<'a, Message: Clone + 'a> From<Editor<'a, Message>> for Element<'a, Message> {
957    fn from(editor: Editor<'a, Message>) -> Self {
958        let Fields {
959            title,
960            all_day,
961            starts,
962            ends,
963            repeat,
964            every,
965            stops,
966            colour,
967            location,
968            notes,
969        } = editor.fields();
970
971        let menus: Vec<Element<'a, Message>> = [
972            repeat.map(|menu| container(menu).width(Length::FillPortion(3)).into()),
973            colour.map(|menu| container(menu).width(Length::FillPortion(2)).into()),
974        ]
975        .into_iter()
976        .flatten()
977        .collect();
978        let menus =
979            (!menus.is_empty()).then(|| Row::with_children(menus).spacing(space::SM).into());
980
981        Column::with_children(
982            [
983                title, all_day, starts, ends, menus, every, stops, location, notes,
984            ]
985            .into_iter()
986            .flatten(),
987        )
988        .spacing(space::MD)
989        .width(Length::Fill)
990        .into()
991    }
992}
993
994/// The name beside a field.
995fn name<'a, Message: 'a>(name: &'a str) -> Element<'a, Message> {
996    let label = text(name)
997        .size(text_size::SM)
998        .wrapping(text::Wrapping::None)
999        .style(|theme: &Theme| text::Style {
1000            color: Some(Tokens::of(theme).muted_foreground),
1001        });
1002    container(label).width(Length::Fixed(NAME_WIDTH)).into()
1003}
1004
1005/// A field for a small whole number.
1006fn number_field<'a, Message: Clone + 'a>(
1007    value: &str,
1008    shortcuts: Shortcuts,
1009    on_event: &Handler<'a, Message>,
1010    event: fn(String) -> Event,
1011) -> Element<'a, Message> {
1012    input("1", value)
1013        .width(NUMBER_WIDTH)
1014        .shortcuts(shortcuts)
1015        .on_input_maybe(
1016            on_event
1017                .clone()
1018                .map(|handler| move |text| handler(event(text))),
1019        )
1020        .into()
1021}
1022
1023/// How many units pass between repeats: "Every 2 weeks".
1024fn every<'a, Message: Clone + 'a>(
1025    state: &'a State,
1026    shortcuts: Shortcuts,
1027    on_event: &Handler<'a, Message>,
1028) -> Element<'a, Message> {
1029    let unit = text(state.repeats().unit(state.interval()))
1030        .size(text_size::SM)
1031        .wrapping(text::Wrapping::None);
1032    row![
1033        name("Every"),
1034        number_field(&state.interval, shortcuts, on_event, Event::Interval),
1035        unit,
1036    ]
1037    .spacing(space::SM)
1038    .align_y(Alignment::Center)
1039    .into()
1040}
1041
1042/// How the repeat stops: never, on a date or after a number of times.
1043fn stops<'a, Message: Clone + 'a>(
1044    state: &'a State,
1045    shortcuts: Shortcuts,
1046    on_event: &Handler<'a, Message>,
1047) -> Element<'a, Message> {
1048    let handler = on_event.clone();
1049    let choice = select(&Stops::ALL[..], Some(state.stops()))
1050        .width(Length::Fill)
1051        .on_select_maybe(handler.map(|handler| move |stops| handler(Event::Stops(stops))));
1052    let mut controls = Row::new()
1053        .spacing(space::SM)
1054        .align_y(Alignment::Center)
1055        .push(name("Stops"))
1056        .push(choice);
1057    match state.stops() {
1058        Stops::Never => {}
1059        Stops::On => controls = controls.push(date_field(state, Target::Until, on_event)),
1060        Stops::After => {
1061            let times = text(if state.count() == 1 { "time" } else { "times" })
1062                .size(text_size::SM)
1063                .wrapping(text::Wrapping::None);
1064            controls = controls
1065                .push(number_field(
1066                    &state.count,
1067                    shortcuts,
1068                    on_event,
1069                    Event::Count,
1070                ))
1071                .push(times);
1072        }
1073    }
1074    controls.into()
1075}
1076
1077/// One end of the entry: its name, its date and, unless it lasts all day,
1078/// its time.
1079fn moment<'a, Message: Clone + 'a>(
1080    state: &'a State,
1081    field: Field,
1082    label: &'a str,
1083    on_event: &Handler<'a, Message>,
1084) -> Element<'a, Message> {
1085    let mut controls = Row::new()
1086        .spacing(space::SM)
1087        .align_y(Alignment::Center)
1088        .push(name(label))
1089        .push(date_field(state, Target::Field(field), on_event));
1090    if !state.is_all_day() {
1091        let handler = on_event.clone();
1092        controls = controls.push(
1093            select(state.times(field), Some(TimeOfDay(state.time(field))))
1094                .width(TIME_WIDTH)
1095                .searchable(true)
1096                .search_placeholder("hh:mm")
1097                .on_custom({
1098                    let handler = handler.clone();
1099                    move |text| {
1100                        let handler = handler.as_ref()?;
1101                        let time = TimeOfDay::parse(&text)?;
1102                        Some(handler(Event::Time(field, time.0)))
1103                    }
1104                })
1105                .on_select_maybe(
1106                    handler
1107                        .map(|handler| move |time: TimeOfDay| handler(Event::Time(field, time.0))),
1108                ),
1109        );
1110    }
1111    controls.into()
1112}
1113
1114/// A date as a button that opens a month to pick another from.
1115fn date_field<'a, Message: Clone + 'a>(
1116    state: &'a State,
1117    target: Target,
1118    on_event: &Handler<'a, Message>,
1119) -> Element<'a, Message> {
1120    let open = state.picker.filter(|picker| picker.target == target);
1121    let toggle = match target {
1122        Target::Field(field) => Event::Picker(open.is_none().then_some(field)),
1123        Target::Until => Event::UntilPicker(open.is_none()),
1124    };
1125    let date = state.target_date(target);
1126    let trigger = button(date.strftime("%a %-d %b %Y").to_string())
1127        .variant(button::Variant::Outline)
1128        .icon(lucide!(Calendar))
1129        .align_x(Alignment::Start)
1130        .width(Length::Fill)
1131        .on_press_maybe(send(on_event, toggle));
1132
1133    let content: Element<'a, Message> = match open {
1134        Some(picker) => month_picker(state, picker, on_event),
1135        None => Space::new().into(),
1136    };
1137    let mut date = popover(trigger, content)
1138        .open(open.is_some())
1139        .align(Align::Start)
1140        .width(Length::Shrink)
1141        .padding(space::MD);
1142    if let Some(close) = send(on_event, Event::Picker(None)) {
1143        date = date.on_dismiss(close);
1144    }
1145    // A narrow column cuts the date short rather than letting it run
1146    // under the time beside it.
1147    container(date).width(Length::Fill).clip(true).into()
1148}
1149
1150/// A month of days to pick from, with arrows to the months either side.
1151fn month_picker<'a, Message: Clone + 'a>(
1152    state: &State,
1153    picker: Picker,
1154    on_event: &Handler<'a, Message>,
1155) -> Element<'a, Message> {
1156    let step = |glyph, label: &'static str, months: i32| {
1157        icon_button(glyph)
1158            .label(label)
1159            .variant(icon_button::Variant::Ghost)
1160            .size(Size::Sm)
1161            .on_press_maybe(send(on_event, Event::PickerMonth(months)))
1162    };
1163    let name = text(picker.month.strftime("%B %Y").to_string())
1164        .size(text_size::SM)
1165        .font(theme::semibold())
1166        .wrapping(text::Wrapping::None);
1167    let header = row![
1168        step(lucide!(ChevronLeft), "Previous month", -1),
1169        container(name).center_x(Length::Fill),
1170        step(lucide!(ChevronRight), "Next month", 1),
1171    ]
1172    .align_y(Alignment::Center);
1173
1174    let chosen = state.target_date(picker.target);
1175    let target = picker.target;
1176    let pick = on_event.clone().map(|handler| {
1177        move |date: Date| match target {
1178            Target::Field(field) => handler(Event::Date(field, date)),
1179            Target::Until => handler(Event::Until(date)),
1180        }
1181    });
1182    let grid = month_grid(picker.month, state.week_start, Some(chosen), pick);
1183    column![header, grid]
1184        .spacing(space::SM)
1185        .width(Length::Fixed(7.0 * CELL))
1186        .into()
1187}
1188
1189/// The days of `month` under their weekday names, as the form's date
1190/// picker draws them, with `chosen` marked. Pressing a day sends
1191/// `on_pick` with it; without `on_pick` the days are disabled. Days of the
1192/// neighbouring months are left blank.
1193pub fn month_grid<'a, Message: Clone + 'a>(
1194    month: Date,
1195    week_start: Weekday,
1196    chosen: Option<Date>,
1197    on_pick: Option<impl Fn(Date) -> Message + 'a>,
1198) -> Element<'a, Message> {
1199    let weeks = month_weeks(month, week_start);
1200    let on_pick = on_pick.map(std::rc::Rc::new);
1201    let mut grid = Column::new().spacing(2.0);
1202    if let Some(week) = weeks.first() {
1203        grid = grid.push(Row::with_children(week.iter().map(|date| {
1204            container(text(weekday_label(*date, true)).size(text_size::XS).style(
1205                |theme: &Theme| text::Style {
1206                    color: Some(Tokens::of(theme).muted_foreground),
1207                },
1208            ))
1209            .center(Length::Fixed(CELL))
1210            .into()
1211        })));
1212    }
1213    for week in &weeks {
1214        grid = grid.push(Row::with_children(week.iter().map(|date| {
1215            if date.month() != month.month() {
1216                return Space::new()
1217                    .width(Length::Fixed(CELL))
1218                    .height(Length::Fixed(CELL))
1219                    .into();
1220            }
1221            let day = style::Day {
1222                today: false,
1223                selected: Some(*date) == chosen,
1224                in_month: true,
1225            };
1226            let number = text(date.day().to_string())
1227                .size(text_size::XS)
1228                .wrapping(text::Wrapping::None);
1229            widget::button(container(number).center(Length::Fill))
1230                .width(Length::Fixed(CELL))
1231                .height(Length::Fixed(CELL))
1232                .padding(0)
1233                .on_press_maybe(on_pick.as_ref().map(|pick| pick(*date)))
1234                .style(move |theme, status: Status| {
1235                    style::year_day(&Tokens::of(theme), day, status)
1236                })
1237                .into()
1238        })));
1239    }
1240    grid.into()
1241}
1242
1243#[cfg(test)]
1244mod tests {
1245    use super::*;
1246    use jiff::civil::date;
1247
1248    const UTC: TimeZone = TimeZone::UTC;
1249
1250    /// A time on 19 June 2026.
1251    fn at(hour: u16, minute: u16) -> Timestamp {
1252        instant_at(date(2026, 6, 19), hour * 60 + minute, &UTC)
1253    }
1254
1255    fn timed() -> State {
1256        State::new(
1257            &Draft {
1258                when: When::timed(at(11, 0), at(12, 30)),
1259            },
1260            &UTC,
1261        )
1262    }
1263
1264    fn whole_day() -> State {
1265        State::new(
1266            &Draft {
1267                when: When::day(date(2026, 6, 19)),
1268            },
1269            &UTC,
1270        )
1271    }
1272
1273    #[test]
1274    fn a_new_form_starts_from_the_draft() {
1275        let form = timed();
1276        assert!(form.is_new());
1277        assert_eq!(form.id(), None);
1278        assert_eq!(form.title(), "");
1279        assert!(!form.is_all_day());
1280        assert_eq!(form.date(Field::Start), date(2026, 6, 19));
1281        assert_eq!((form.time(Field::Start), form.time(Field::End)), (660, 750));
1282        assert_eq!(form.repeats(), Repeats::Never);
1283        assert_eq!(form.tone(), Tone::Primary);
1284        assert_eq!(form.picker(), None);
1285        assert_eq!(form.when(), When::timed(at(11, 0), at(12, 30)));
1286
1287        let form = whole_day();
1288        assert!(form.is_all_day());
1289        assert_eq!(form.when(), When::day(date(2026, 6, 19)));
1290    }
1291
1292    #[test]
1293    fn editing_starts_from_the_entry_and_keeps_what_the_form_does_not_show() {
1294        let rule = Repeat::weekly().interval(2);
1295        let entry = Entry::new(EntryId(4), "Review", at(15, 0), at(16, 0))
1296            .tone(Tone::Success)
1297            .tag("work")
1298            .repeat(rule)
1299            .location("Room 4")
1300            .notes("Bring the plan\nand the figures");
1301        let mut form = State::edit(&entry, &UTC);
1302        assert_eq!(form.id(), Some(EntryId(4)));
1303        assert!(!form.is_new());
1304        assert_eq!(form.title(), "Review");
1305        assert_eq!(form.tone(), Tone::Success);
1306        assert_eq!(form.repeats(), Repeats::Weekly);
1307        assert_eq!(form.interval(), 2);
1308        assert_eq!(form.stops(), Stops::Never);
1309        assert_eq!(form.location(), "Room 4");
1310        assert_eq!(form.notes(), "Bring the plan\nand the figures");
1311        assert_eq!(form.entry(EntryId(99)), entry, "unchanged, with its own id");
1312
1313        form.update(Event::Title(String::from("Retro")));
1314        let saved = form.entry(EntryId(99));
1315        assert_eq!(saved.id(), EntryId(4));
1316        assert_eq!(saved.title(), "Retro");
1317        assert_eq!(saved.tag_of(), Some("work"));
1318        assert_eq!(saved.repeat_of(), Some(rule));
1319        assert_eq!(saved.location_of(), Some("Room 4"));
1320    }
1321
1322    #[test]
1323    fn a_blank_title_is_saved_as_untitled_and_a_new_entry_takes_the_id_given() {
1324        let mut form = timed();
1325        form.update(Event::Title(String::from("   ")));
1326        let entry = form.entry(EntryId(7));
1327        assert_eq!(entry.id(), EntryId(7));
1328        assert_eq!(entry.title(), UNTITLED);
1329        form.update(Event::Title(String::from("  Retro ")));
1330        assert_eq!(form.entry(EntryId(7)).title(), "Retro");
1331    }
1332
1333    #[test]
1334    fn moving_the_start_keeps_the_length() {
1335        let mut form = timed();
1336        form.update(Event::Time(Field::Start, 14 * 60));
1337        assert_eq!((form.time(Field::Start), form.time(Field::End)), (840, 930));
1338
1339        form.update(Event::Date(Field::Start, date(2026, 6, 22)));
1340        assert_eq!(form.date(Field::End), date(2026, 6, 22));
1341        assert_eq!(
1342            form.when(),
1343            When::timed(
1344                instant_at(date(2026, 6, 22), 840, &UTC),
1345                instant_at(date(2026, 6, 22), 930, &UTC)
1346            )
1347        );
1348
1349        // Late enough, the end rolls into the next day.
1350        form.update(Event::Time(Field::Start, 23 * 60));
1351        assert_eq!(form.date(Field::End), date(2026, 6, 23));
1352        assert_eq!(form.time(Field::End), 30);
1353    }
1354
1355    #[test]
1356    fn the_end_never_goes_before_the_start() {
1357        let mut form = timed();
1358        // An earlier time on the same day means the next day.
1359        form.update(Event::Time(Field::End, 9 * 60));
1360        assert_eq!(form.date(Field::End), date(2026, 6, 20));
1361        assert_eq!(form.time(Field::End), 540);
1362
1363        // An end date before the start comes back to just after it.
1364        form.update(Event::Date(Field::End, date(2026, 6, 1)));
1365        assert_eq!(form.date(Field::End), date(2026, 6, 19));
1366        assert_eq!(form.time(Field::End), 660 + TIME_STEP);
1367
1368        // The same time as the start is one step long.
1369        let mut form = timed();
1370        form.update(Event::Time(Field::End, 660));
1371        assert_eq!(form.time(Field::End), 660 + TIME_STEP);
1372
1373        // At the last step of the day, the shortest entry ends at midnight.
1374        let late = at(23, 45);
1375        let mut form = State::new(
1376            &Draft {
1377                when: When::timed(late, late),
1378            },
1379            &UTC,
1380        );
1381        form.update(Event::Time(Field::End, 23 * 60 + 45));
1382        assert_eq!(
1383            (form.date(Field::End), form.time(Field::End)),
1384            (date(2026, 6, 20), 0)
1385        );
1386    }
1387
1388    #[test]
1389    fn times_out_of_range_are_kept_within_the_day() {
1390        let mut form = timed();
1391        form.update(Event::Time(Field::Start, 5000));
1392        assert_eq!(form.time(Field::Start), DAY_MINUTES - 1);
1393    }
1394
1395    #[test]
1396    fn all_day_keeps_the_dates_and_brings_the_times_back() {
1397        let mut form = timed();
1398        form.update(Event::AllDay(true));
1399        assert_eq!(form.when(), When::day(date(2026, 6, 19)));
1400        form.update(Event::Date(Field::End, date(2026, 6, 21)));
1401        assert_eq!(
1402            form.when(),
1403            When::all_day(date(2026, 6, 19), date(2026, 6, 21))
1404        );
1405        form.update(Event::Date(Field::End, date(2026, 6, 1)));
1406        assert_eq!(form.date(Field::End), date(2026, 6, 19), "same day is fine");
1407        form.update(Event::AllDay(false));
1408        assert_eq!((form.time(Field::Start), form.time(Field::End)), (660, 750));
1409
1410        // A draft for a whole day has a morning hour ready.
1411        let mut form = whole_day();
1412        form.update(Event::AllDay(false));
1413        assert_eq!((form.time(Field::Start), form.time(Field::End)), (540, 600));
1414    }
1415
1416    #[test]
1417    fn repeat_and_colour_reach_the_entry() {
1418        let mut form = timed();
1419        form.update(Event::Repeats(Repeats::Weekly));
1420        form.update(Event::Tone(Tone::Warning));
1421        let entry = form.entry(EntryId(1));
1422        assert_eq!(entry.repeat_of(), Some(Repeat::weekly()));
1423        assert_eq!(entry.tone_of(), Tone::Warning);
1424        form.update(Event::Repeats(Repeats::Never));
1425        assert_eq!(form.entry(EntryId(1)).repeat_of(), None);
1426    }
1427
1428    #[test]
1429    fn every_repeat_choice_has_a_name_and_round_trips() {
1430        for choice in Repeats::ALL {
1431            assert!(!choice.to_string().is_empty());
1432            assert_eq!(Repeats::of(choice.frequency()), choice);
1433        }
1434        assert_eq!(Repeats::default(), Repeats::Never);
1435        assert_eq!(Repeats::Never.frequency(), None);
1436        let units: Vec<_> = Repeats::ALL
1437            .iter()
1438            .map(|choice| (choice.unit(1), choice.unit(2)))
1439            .collect();
1440        assert_eq!(
1441            units,
1442            vec![
1443                ("", ""),
1444                ("day", "days"),
1445                ("week", "weeks"),
1446                ("month", "months"),
1447                ("year", "years")
1448            ]
1449        );
1450        let names: Vec<_> = Stops::ALL.iter().map(Stops::to_string).collect();
1451        assert_eq!(names, vec!["Never", "On a date", "After"]);
1452        assert_eq!(Stops::default(), Stops::Never);
1453    }
1454
1455    #[test]
1456    fn a_repeat_takes_its_interval_and_its_end_from_the_form() {
1457        let mut form = timed();
1458        assert_eq!(form.repeat(), None);
1459        assert_eq!((form.interval(), form.count()), (1, DEFAULT_COUNT));
1460        assert_eq!(form.until(), date(2026, 7, 19), "a month after the start");
1461
1462        form.update(Event::Repeats(Repeats::Weekly));
1463        assert_eq!(form.repeat(), Some(Repeat::weekly()));
1464        form.update(Event::Interval(String::from("2")));
1465        assert_eq!(form.repeat(), Some(Repeat::weekly().interval(2)));
1466
1467        form.update(Event::Stops(Stops::After));
1468        form.update(Event::Count(String::from("6")));
1469        assert_eq!(form.repeat(), Some(Repeat::weekly().interval(2).count(6)));
1470
1471        form.update(Event::Stops(Stops::On));
1472        form.update(Event::Until(date(2026, 9, 1)));
1473        let rule = Repeat::weekly().interval(2).until(date(2026, 9, 1));
1474        assert_eq!(form.repeat(), Some(rule));
1475        assert_eq!(form.entry(EntryId(1)).repeat_of(), Some(rule));
1476
1477        // The interval and the end wait while the entry does not repeat.
1478        form.update(Event::Repeats(Repeats::Never));
1479        assert_eq!(form.repeat(), None);
1480        form.update(Event::Repeats(Repeats::Monthly));
1481        assert_eq!(
1482            form.repeat(),
1483            Some(Repeat::monthly().interval(2).until(date(2026, 9, 1)))
1484        );
1485    }
1486
1487    #[test]
1488    fn number_fields_keep_digits_and_count_blank_as_one() {
1489        let mut form = timed();
1490        form.update(Event::Repeats(Repeats::Daily));
1491        form.update(Event::Interval(String::from("a1b2c3d4")));
1492        assert_eq!(form.interval(), 123, "three digits at most");
1493        form.update(Event::Interval(String::new()));
1494        assert_eq!(form.interval(), 1, "blank while typing");
1495        form.update(Event::Interval(String::from("0")));
1496        assert_eq!(form.interval(), 1);
1497        assert_eq!(form.repeat(), Some(Repeat::daily()));
1498
1499        form.update(Event::Stops(Stops::After));
1500        form.update(Event::Count(String::from("-5 times")));
1501        assert_eq!(form.count(), 5);
1502        form.update(Event::Count(String::from("0")));
1503        assert_eq!(form.count(), 1);
1504    }
1505
1506    #[test]
1507    fn an_entry_ending_on_a_date_or_after_a_count_fills_the_form() {
1508        let base = Entry::new(EntryId(4), "Review", at(15, 0), at(16, 0));
1509        let on = base
1510            .clone()
1511            .repeat(Repeat::monthly().until(date(2026, 12, 19)));
1512        let form = State::edit(&on, &UTC);
1513        assert_eq!(form.repeats(), Repeats::Monthly);
1514        assert_eq!(form.stops(), Stops::On);
1515        assert_eq!(form.until(), date(2026, 12, 19));
1516        assert_eq!(form.entry(EntryId(9)), on);
1517
1518        let after = base.repeat(Repeat::yearly().interval(4).count(3));
1519        let form = State::edit(&after, &UTC);
1520        assert_eq!(form.repeats(), Repeats::Yearly);
1521        assert_eq!(form.stops(), Stops::After);
1522        assert_eq!((form.interval(), form.count()), (4, 3));
1523        assert_eq!(form.entry(EntryId(9)), after);
1524    }
1525
1526    #[test]
1527    fn the_last_date_of_a_repeat_stays_on_or_after_the_start() {
1528        let mut form = timed();
1529        form.update(Event::Repeats(Repeats::Daily));
1530        form.update(Event::Stops(Stops::On));
1531        form.update(Event::Until(date(2026, 6, 1)));
1532        assert_eq!(form.until(), date(2026, 6, 19), "not before the start");
1533
1534        form.update(Event::Until(date(2026, 6, 25)));
1535        form.update(Event::Date(Field::Start, date(2026, 8, 3)));
1536        assert_eq!(form.until(), date(2026, 8, 3), "carried by the start");
1537    }
1538
1539    #[test]
1540    fn the_picker_for_the_last_date_opens_turns_and_closes() {
1541        let mut form = timed();
1542        form.update(Event::Repeats(Repeats::Daily));
1543        form.update(Event::Stops(Stops::On));
1544        form.update(Event::UntilPicker(true));
1545        assert!(form.is_picking_until());
1546        assert_eq!(form.picker(), None, "not the start's or the end's");
1547        assert_eq!(form.picker.map(|p| p.month), Some(date(2026, 7, 1)));
1548        form.update(Event::PickerMonth(2));
1549        assert_eq!(form.picker.map(|p| p.month), Some(date(2026, 9, 1)));
1550        form.update(Event::Until(date(2026, 9, 14)));
1551        assert!(!form.is_picking_until());
1552        assert_eq!(form.until(), date(2026, 9, 14));
1553
1554        // One picker at a time, and it closes with the field it is for.
1555        form.update(Event::UntilPicker(true));
1556        form.update(Event::Picker(Some(Field::Start)));
1557        assert!(!form.is_picking_until());
1558        assert_eq!(form.picker(), Some(Field::Start));
1559        form.update(Event::UntilPicker(true));
1560        form.update(Event::UntilPicker(false));
1561        assert!(!form.is_picking_until());
1562        form.update(Event::UntilPicker(true));
1563        form.update(Event::Stops(Stops::Never));
1564        assert!(!form.is_picking_until());
1565        form.update(Event::Stops(Stops::On));
1566        form.update(Event::UntilPicker(true));
1567        form.update(Event::Repeats(Repeats::Never));
1568        assert!(!form.is_picking_until());
1569        form.update(Event::UntilPicker(true));
1570        form.update(Event::Picker(None));
1571        assert!(!form.is_picking_until());
1572    }
1573
1574    #[test]
1575    fn location_and_notes_reach_the_entry() {
1576        let mut form = timed();
1577        assert_eq!(form.location(), "");
1578        assert_eq!(form.notes(), "");
1579        let blank = form.entry(EntryId(1));
1580        assert_eq!((blank.location_of(), blank.notes_of()), (None, None));
1581
1582        form.update(Event::Location(String::from(" Room 4 ")));
1583        for letter in "Agenda".chars() {
1584            form.update(Event::Notes(Action::Edit(
1585                iced::widget::text_editor::Edit::Insert(letter),
1586            )));
1587        }
1588        form.update(Event::Notes(Action::Edit(
1589            iced::widget::text_editor::Edit::Enter,
1590        )));
1591        assert_eq!(form.notes(), "Agenda", "space at the ends is dropped");
1592        let entry = form.entry(EntryId(1));
1593        assert_eq!(entry.location_of(), Some("Room 4"));
1594        assert_eq!(entry.notes_of(), Some("Agenda"));
1595    }
1596
1597    #[test]
1598    fn typed_times_are_read_with_or_without_a_colon() {
1599        assert_eq!(TimeOfDay::parse("09:40"), Some(TimeOfDay(580)));
1600        assert_eq!(TimeOfDay::parse(" 9:40 "), Some(TimeOfDay(580)));
1601        assert_eq!(TimeOfDay::parse("940"), Some(TimeOfDay(580)));
1602        assert_eq!(TimeOfDay::parse("2359"), Some(TimeOfDay(1439)));
1603        assert_eq!(TimeOfDay::parse("0:00"), Some(TimeOfDay(0)));
1604        for bad in [
1605            "", "9", "24:00", "12:60", "9:4", "123:00", "ab:cd", "€12", "12:3x", ":30",
1606        ] {
1607            assert_eq!(TimeOfDay::parse(bad), None, "{bad:?}");
1608        }
1609    }
1610
1611    #[test]
1612    fn times_and_colours_have_names() {
1613        assert_eq!(TimeOfDay(0).to_string(), "00:00");
1614        assert_eq!(TimeOfDay(570).to_string(), "09:30");
1615        let all = TimeOfDay::all();
1616        assert_eq!(all.len(), 96);
1617        assert_eq!(all.last(), Some(&TimeOfDay(1425)));
1618
1619        // A menu can start anywhere and still lists the whole day.
1620        let from_ten = TimeOfDay::from(607);
1621        assert_eq!(from_ten.len(), 96);
1622        assert_eq!(from_ten.first(), Some(&TimeOfDay(600)));
1623        assert_eq!(from_ten.last(), Some(&TimeOfDay(585)));
1624        assert_eq!(TimeOfDay::from(0), all);
1625        assert_eq!(TimeOfDay::from(9999).first(), Some(&TimeOfDay(1425)));
1626
1627        // The start's menu lists the day in order; the end's begins after
1628        // the start on the same day, and lists the day on another.
1629        let form = timed();
1630        assert_eq!(form.times(Field::Start), all);
1631        assert_eq!(form.times(Field::End).first(), Some(&TimeOfDay(675)));
1632        assert_eq!(form.times(Field::End).len(), 96);
1633        let mut overnight = timed();
1634        overnight.update(Event::Date(Field::End, date(2026, 6, 20)));
1635        assert_eq!(overnight.times(Field::End), all);
1636        let names: Vec<_> = Tone::ALL
1637            .iter()
1638            .map(|tone| Colour(*tone).to_string())
1639            .collect();
1640        assert_eq!(names, vec!["Default", "Neutral", "Green", "Amber", "Red"]);
1641    }
1642
1643    #[test]
1644    fn the_date_picker_opens_on_the_field_month_and_closes_on_a_choice() {
1645        let mut form = timed().with_week_start(Weekday::Sunday);
1646        form.update(Event::Picker(Some(Field::End)));
1647        assert_eq!(form.picker(), Some(Field::End));
1648        assert_eq!(form.picker.map(|p| p.month), Some(date(2026, 6, 1)));
1649
1650        form.update(Event::PickerMonth(1));
1651        form.update(Event::PickerMonth(1));
1652        assert_eq!(form.picker.map(|p| p.month), Some(date(2026, 8, 1)));
1653        form.update(Event::PickerMonth(-3));
1654        assert_eq!(form.picker.map(|p| p.month), Some(date(2026, 5, 1)));
1655
1656        form.update(Event::Date(Field::End, date(2026, 6, 20)));
1657        assert_eq!(form.picker(), None);
1658        assert_eq!(form.date(Field::End), date(2026, 6, 20));
1659
1660        form.update(Event::Picker(Some(Field::Start)));
1661        form.update(Event::Picker(None));
1662        assert_eq!(form.picker(), None);
1663        form.update(Event::PickerMonth(1));
1664        assert_eq!(form.picker(), None, "nothing to move");
1665    }
1666
1667    #[test]
1668    fn builder_defaults_and_options() {
1669        let form = timed();
1670        let built: Editor<'_, Event> = editor(&form);
1671        assert!(built.on_event.is_none());
1672        assert!(built.on_submit.is_none());
1673        assert_eq!(built.shortcuts, Shortcuts::all());
1674
1675        let built = built
1676            .on_event(|event| event)
1677            .on_submit(Event::Picker(None))
1678            .shortcuts(Shortcuts::none());
1679        assert!(built.on_event.is_some());
1680        assert!(built.on_submit.is_some());
1681        assert_eq!(built.shortcuts, Shortcuts::none());
1682        assert!(format!("{built:?}").contains("enabled: true"));
1683    }
1684
1685    #[test]
1686    fn parts_can_be_left_out_and_laid_out_by_the_app() {
1687        let mut form = timed();
1688        {
1689            let built: Editor<'_, Event> = editor(&form);
1690            assert!(Part::ALL.iter().all(|part| built.shows(*part)));
1691            let fields = built.fields();
1692            assert!(fields.title.is_some() && fields.notes.is_some() && fields.colour.is_some());
1693            assert!(
1694                fields.every.is_none() && fields.stops.is_none(),
1695                "it does not repeat"
1696            );
1697        }
1698        {
1699            let built: Editor<'_, Event> = editor(&form)
1700                .without(Part::Colour)
1701                .without(Part::Location)
1702                .without(Part::Colour);
1703            assert!(!built.shows(Part::Colour));
1704            assert!(format!("{built:?}").contains("Location"));
1705            let fields = built.fields();
1706            assert!(fields.colour.is_none() && fields.location.is_none());
1707            assert!(fields.title.is_some() && fields.starts.is_some() && fields.ends.is_some());
1708        }
1709
1710        form.update(Event::Repeats(Repeats::Weekly));
1711        let fields = editor::<Event>(&form).fields();
1712        assert!(fields.every.is_some() && fields.stops.is_some());
1713        let fields = editor::<Event>(&form).without(Part::Repeat).fields();
1714        assert!(fields.repeat.is_none() && fields.every.is_none() && fields.stops.is_none());
1715    }
1716
1717    #[test]
1718    fn the_raw_field_text_the_picker_month_and_the_notes_can_be_read() {
1719        let mut form = timed().with_week_start(Weekday::Sunday);
1720        assert_eq!(form.week_start(), Weekday::Sunday);
1721        form.update(Event::Interval(String::new()));
1722        assert_eq!(form.interval_text(), "");
1723        assert_eq!(form.interval(), 1, "blank counts as one");
1724        form.update(Event::Count(String::from("2a")));
1725        assert_eq!(form.count_text(), "2");
1726
1727        assert_eq!(form.picker_month(), None);
1728        form.update(Event::Picker(Some(Field::Start)));
1729        let month = form.date(Field::Start).first_of_month();
1730        assert_eq!(form.picker_month(), Some(month));
1731        form.update(Event::PickerMonth(2));
1732        assert_eq!(form.picker_month(), month.checked_add(2.months()).ok());
1733
1734        form.update(Event::Notes(Action::Edit(
1735            iced::widget::text_editor::Edit::Paste(std::sync::Arc::new(String::from("Bring cake"))),
1736        )));
1737        assert_eq!(form.notes_content().text().trim(), "Bring cake");
1738    }
1739}