1use 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
66pub const TIME_STEP: u16 = 15;
68pub const UNTITLED: &str = "(No title)";
70pub const DEFAULT_MINUTES: u16 = 60;
72
73pub const DEFAULT_COUNT: u32 = 10;
75pub const NUMBER_DIGITS: usize = 3;
77
78const CELL: f32 = 32.0;
80const TIME_WIDTH: f32 = 96.0;
82const NAME_WIDTH: f32 = 48.0;
84const NUMBER_WIDTH: f32 = 64.0;
86const NOTES_HEIGHT: f32 = 64.0;
88
89pub fn notes_id() -> widget::Id {
91 widget::Id::new("iced-cube-calendar-notes")
92}
93
94#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
96pub enum Field {
97 Start,
98 End,
99}
100
101#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
103pub struct TimeOfDay(pub u16);
104
105impl TimeOfDay {
106 pub fn all() -> Vec<TimeOfDay> {
108 (0..DAY_MINUTES)
109 .step_by(usize::from(TIME_STEP))
110 .map(TimeOfDay)
111 .collect()
112 }
113
114 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#[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 pub const ALL: [Repeats; 5] = [
146 Repeats::Never,
147 Repeats::Daily,
148 Repeats::Weekly,
149 Repeats::Monthly,
150 Repeats::Yearly,
151 ];
152
153 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 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 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
207pub enum Stops {
208 #[default]
209 Never,
210 On,
212 After,
214}
215
216impl Stops {
217 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#[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#[derive(Debug, Clone, PartialEq)]
249pub enum Event {
250 Title(String),
251 AllDay(bool),
252 Date(Field, Date),
254 Time(Field, u16),
256 Repeats(Repeats),
257 Interval(String),
259 Stops(Stops),
260 Until(Date),
262 Count(String),
264 Tone(Tone),
265 Location(String),
266 Notes(Action),
268 Picker(Option<Field>),
271 UntilPicker(bool),
273 PickerMonth(i32),
275}
276
277#[derive(Debug, Clone, Copy, PartialEq, Eq)]
279enum Target {
280 Field(Field),
281 Until,
282}
283
284#[derive(Debug, Clone, Copy, PartialEq, Eq)]
286struct Picker {
287 target: Target,
288 month: Date,
289}
290
291#[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
315fn digits(text: &str) -> String {
317 text.chars()
318 .filter(char::is_ascii_digit)
319 .take(NUMBER_DIGITS)
320 .collect()
321}
322
323fn number(text: &str) -> u32 {
325 text.parse::<u32>().unwrap_or(1).max(1)
326}
327
328impl State {
329 pub fn new(draft: &Draft, time_zone: &TimeZone) -> Self {
331 Self::over(draft.when, time_zone)
332 }
333
334 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 pub fn with_week_start(mut self, week_start: Weekday) -> Self {
397 self.week_start = week_start;
398 self
399 }
400
401 pub fn week_start(&self) -> Weekday {
403 self.week_start
404 }
405
406 pub fn id(&self) -> Option<EntryId> {
408 self.id
409 }
410
411 pub fn is_new(&self) -> bool {
412 self.id.is_none()
413 }
414
415 pub fn title(&self) -> &str {
416 &self.title
417 }
418
419 pub fn is_all_day(&self) -> bool {
420 self.all_day
421 }
422
423 pub fn repeats(&self) -> Repeats {
424 self.repeats
425 }
426
427 pub fn interval(&self) -> u32 {
429 number(&self.interval)
430 }
431
432 pub fn stops(&self) -> Stops {
433 self.stops
434 }
435
436 pub fn until(&self) -> Date {
438 self.until
439 }
440
441 pub fn count(&self) -> u32 {
444 number(&self.count)
445 }
446
447 pub fn repeat(&self) -> Option<Repeat> {
450 let rule = Repeat::new(self.repeats.frequency()?).interval(self.interval());
451 Some(match self.stops {
452 Stops::Never => rule,
453 Stops::On => rule.until(self.until),
454 Stops::After => rule.count(self.count()),
455 })
456 }
457
458 pub fn tone(&self) -> Tone {
459 self.tone
460 }
461
462 pub fn location(&self) -> &str {
463 &self.location
464 }
465
466 pub fn notes(&self) -> String {
468 self.notes.text().trim().to_owned()
469 }
470
471 pub fn notes_content(&self) -> &Content {
474 &self.notes
475 }
476
477 pub fn picker_month(&self) -> Option<Date> {
480 self.picker.map(|picker| picker.month)
481 }
482
483 pub fn interval_text(&self) -> &str {
485 &self.interval
486 }
487
488 pub fn count_text(&self) -> &str {
490 &self.count
491 }
492
493 pub fn is_picking_until(&self) -> bool {
495 self.picker
496 .is_some_and(|picker| picker.target == Target::Until)
497 }
498
499 pub fn date(&self, field: Field) -> Date {
501 self.at(field).0
502 }
503
504 pub fn time(&self, field: Field) -> u16 {
506 self.at(field).1
507 }
508
509 pub fn times(&self, field: Field) -> Vec<TimeOfDay> {
513 let first = match field {
514 Field::End if self.end.0 == self.start.0 => self.start.1 + TIME_STEP,
515 _ => self.time(field).saturating_sub(60),
516 };
517 TimeOfDay::from(first % DAY_MINUTES)
518 }
519
520 pub fn picker(&self) -> Option<Field> {
522 match self.picker?.target {
523 Target::Field(field) => Some(field),
524 Target::Until => None,
525 }
526 }
527
528 pub fn when(&self) -> When {
530 if self.all_day {
531 return When::all_day(self.start.0, self.end.0);
532 }
533 When::timed(
534 instant_at(self.start.0, self.start.1, &self.time_zone),
535 instant_at(self.end.0, self.end.1, &self.time_zone),
536 )
537 }
538
539 pub fn entry(&self, new_id: EntryId) -> Entry {
542 let title = match self.title.trim() {
543 "" => UNTITLED,
544 title => title,
545 };
546 let mut entry = Entry::at(self.id.unwrap_or(new_id), title, self.when())
547 .tone(self.tone)
548 .location(self.location.clone())
549 .notes(self.notes());
550 if let Some(tag) = &self.tag {
551 entry = entry.tag(tag.clone());
552 }
553 if let Some(rule) = self.repeat() {
554 entry = entry.repeat(rule);
555 }
556 entry
557 }
558
559 pub fn update(&mut self, event: Event) {
560 match event {
561 Event::Title(title) => self.title = title,
562 Event::AllDay(all_day) => {
563 self.all_day = all_day;
564 self.settle(Field::End);
565 }
566 Event::Date(field, date) => {
567 self.picker = None;
568 self.set(field, (date, self.time(field)));
569 }
570 Event::Time(field, minute) => {
571 self.set(field, (self.date(field), minute.min(DAY_MINUTES - 1)));
572 }
573 Event::Repeats(repeats) => {
574 self.repeats = repeats;
575 if repeats == Repeats::Never && self.is_picking_until() {
576 self.picker = None;
577 }
578 }
579 Event::Interval(text) => self.interval = digits(&text),
580 Event::Stops(stops) => {
581 self.stops = stops;
582 if stops != Stops::On && self.is_picking_until() {
583 self.picker = None;
584 }
585 }
586 Event::Until(date) => {
587 self.picker = None;
588 self.until = date.max(self.start.0);
589 }
590 Event::Count(text) => self.count = digits(&text),
591 Event::Tone(tone) => self.tone = tone,
592 Event::Location(location) => self.location = location,
593 Event::Notes(action) => self.notes.perform(action),
594 Event::Picker(field) => {
595 self.picker = field.map(|field| Picker {
596 target: Target::Field(field),
597 month: self.date(field).first_of_month(),
598 });
599 }
600 Event::UntilPicker(open) => {
601 self.picker = open.then(|| Picker {
602 target: Target::Until,
603 month: self.until.first_of_month(),
604 });
605 }
606 Event::PickerMonth(months) => {
607 if let Some(picker) = &mut self.picker {
608 picker.month = picker
609 .month
610 .checked_add(i64::from(months.clamp(-1200, 1200)).months())
611 .unwrap_or(picker.month);
612 }
613 }
614 }
615 }
616
617 fn at(&self, field: Field) -> (Date, u16) {
618 match field {
619 Field::Start => self.start,
620 Field::End => self.end,
621 }
622 }
623
624 fn set(&mut self, field: Field, to: (Date, u16)) {
627 match field {
628 Field::Start => {
629 let days = days_between(self.start.0, self.end.0);
630 let minutes = i32::from(self.end.1) - i32::from(self.start.1);
631 self.start = to;
632 let end = i32::from(to.1) + minutes;
633 self.end = (
634 add_days(to.0, days + end.div_euclid(i32::from(DAY_MINUTES))),
635 u16::try_from(end.rem_euclid(i32::from(DAY_MINUTES))).unwrap_or(0),
636 );
637 }
638 Field::End => self.end = to,
639 }
640 self.until = self.until.max(self.start.0);
641 self.settle(field);
642 }
643
644 fn target_date(&self, target: Target) -> Date {
646 match target {
647 Target::Field(field) => self.date(field),
648 Target::Until => self.until,
649 }
650 }
651
652 fn settle(&mut self, changed: Field) {
655 if self.all_day {
656 if self.end.0 < self.start.0 {
657 self.end.0 = self.start.0;
658 }
659 return;
660 }
661 if self.end > self.start {
662 return;
663 }
664 if changed == Field::End && self.end.0 == self.start.0 && self.end.1 < self.start.1 {
667 self.end.0 = add_days(self.start.0, 1);
668 return;
669 }
670 let end = self.start.1 + TIME_STEP;
671 self.end = if end >= DAY_MINUTES {
672 (add_days(self.start.0, 1), end - DAY_MINUTES)
673 } else {
674 (self.start.0, end)
675 };
676 }
677}
678
679fn local(instant: Timestamp, time_zone: &TimeZone) -> (Date, u16) {
681 let date = date_of(instant, time_zone);
682 (date, minute_on(date, instant, time_zone))
683}
684
685fn days_between(from: Date, to: Date) -> i32 {
686 i32::try_from(to.duration_since(from).as_hours() / 24).unwrap_or(0)
687}
688
689#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
691pub enum Part {
692 Title,
693 AllDay,
694 Starts,
695 Ends,
696 Repeat,
698 Colour,
699 Location,
700 Notes,
701}
702
703impl Part {
704 pub const ALL: [Part; 8] = [
705 Part::Title,
706 Part::AllDay,
707 Part::Starts,
708 Part::Ends,
709 Part::Repeat,
710 Part::Colour,
711 Part::Location,
712 Part::Notes,
713 ];
714}
715
716pub struct Editor<'a, Message> {
719 state: &'a State,
720 on_event: Option<Box<dyn Fn(Event) -> Message + 'a>>,
721 on_submit: Option<Message>,
722 shortcuts: Shortcuts,
723 without: Vec<Part>,
724}
725
726pub fn editor<Message>(state: &State) -> Editor<'_, Message> {
729 Editor {
730 state,
731 on_event: None,
732 on_submit: None,
733 shortcuts: Shortcuts::all(),
734 without: Vec::new(),
735 }
736}
737
738impl<Message> std::fmt::Debug for Editor<'_, Message> {
739 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
740 f.debug_struct("Editor")
741 .field("state", self.state)
742 .field("enabled", &self.on_event.is_some())
743 .field("submits", &self.on_submit.is_some())
744 .field("shortcuts", &self.shortcuts)
745 .field("without", &self.without)
746 .finish()
747 }
748}
749
750pub struct Fields<'a, Message> {
754 pub title: Option<Element<'a, Message>>,
755 pub all_day: Option<Element<'a, Message>>,
756 pub starts: Option<Element<'a, Message>>,
757 pub ends: Option<Element<'a, Message>>,
758 pub repeat: Option<Element<'a, Message>>,
759 pub every: Option<Element<'a, Message>>,
761 pub stops: Option<Element<'a, Message>>,
763 pub colour: Option<Element<'a, Message>>,
764 pub location: Option<Element<'a, Message>>,
765 pub notes: Option<Element<'a, Message>>,
766}
767
768impl<Message> std::fmt::Debug for Fields<'_, Message> {
769 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
770 f.debug_struct("Fields")
771 .field("title", &self.title.is_some())
772 .field("all_day", &self.all_day.is_some())
773 .field("starts", &self.starts.is_some())
774 .field("ends", &self.ends.is_some())
775 .field("repeat", &self.repeat.is_some())
776 .field("every", &self.every.is_some())
777 .field("stops", &self.stops.is_some())
778 .field("colour", &self.colour.is_some())
779 .field("location", &self.location.is_some())
780 .field("notes", &self.notes.is_some())
781 .finish()
782 }
783}
784
785impl<'a, Message> Editor<'a, Message> {
786 pub fn on_event(mut self, on_event: impl Fn(Event) -> Message + 'a) -> Self {
787 self.on_event = Some(Box::new(on_event));
788 self
789 }
790
791 pub fn on_submit(mut self, message: Message) -> Self {
794 self.on_submit = Some(message);
795 self
796 }
797
798 pub fn shortcuts(mut self, shortcuts: Shortcuts) -> Self {
801 self.shortcuts = shortcuts;
802 self
803 }
804
805 pub fn without(mut self, part: Part) -> Self {
807 if !self.without.contains(&part) {
808 self.without.push(part);
809 }
810 self
811 }
812
813 pub fn shows(&self, part: Part) -> bool {
815 !self.without.contains(&part)
816 }
817}
818
819impl<'a, Message: Clone + 'a> Editor<'a, Message> {
820 pub fn fields(self) -> Fields<'a, Message> {
822 let shows = |part| !self.without.contains(&part);
823 let Editor {
824 state,
825 on_event,
826 on_submit,
827 shortcuts,
828 ..
829 } = self;
830 let on_event: Handler<'a, Message> = on_event.map(std::rc::Rc::from);
831 let repeating = state.repeats() != Repeats::Never;
832
833 let title = shows(Part::Title).then(|| {
834 input("Add a title", state.title())
835 .shortcuts(shortcuts)
836 .on_input_maybe(
837 on_event
838 .clone()
839 .map(|handler| move |title| handler(Event::Title(title))),
840 )
841 .on_submit_maybe(on_submit.clone())
842 .into()
843 });
844 let all_day = shows(Part::AllDay).then(|| {
846 checkbox(state.is_all_day())
847 .label("All day")
848 .on_toggle_maybe(
849 on_event
850 .clone()
851 .map(|handler| move |on| handler(Event::AllDay(on))),
852 )
853 .into()
854 });
855 let repeat = shows(Part::Repeat).then(|| {
856 select(&Repeats::ALL[..], Some(state.repeats()))
857 .width(Length::Fill)
858 .on_select_maybe(
859 on_event
860 .clone()
861 .map(|handler| move |repeats| handler(Event::Repeats(repeats))),
862 )
863 .into()
864 });
865 let colour = shows(Part::Colour).then(|| colour_menu(state, &on_event));
866 let location = shows(Part::Location).then(|| {
867 input("Add a location", state.location())
868 .icon(lucide!(MapPin))
869 .shortcuts(shortcuts)
870 .on_input_maybe(
871 on_event
872 .clone()
873 .map(|handler| move |location| handler(Event::Location(location))),
874 )
875 .on_submit_maybe(on_submit)
876 .into()
877 });
878 let notes = shows(Part::Notes).then(|| {
879 textarea(&state.notes)
880 .id(notes_id())
881 .placeholder("Add notes")
882 .min_height(NOTES_HEIGHT)
883 .shortcuts(shortcuts)
884 .on_action_maybe(
885 on_event
886 .clone()
887 .map(|handler| move |action| handler(Event::Notes(action))),
888 )
889 .into()
890 });
891
892 Fields {
893 title,
894 all_day,
895 starts: shows(Part::Starts).then(|| moment(state, Field::Start, "Starts", &on_event)),
896 ends: shows(Part::Ends).then(|| moment(state, Field::End, "Ends", &on_event)),
897 repeat,
898 every: (shows(Part::Repeat) && repeating).then(|| every(state, shortcuts, &on_event)),
899 stops: (shows(Part::Repeat) && repeating).then(|| stops(state, shortcuts, &on_event)),
900 colour,
901 location,
902 notes,
903 }
904 }
905}
906
907fn colour_menu<'a, Message: Clone + 'a>(
909 state: &State,
910 on_event: &Handler<'a, Message>,
911) -> Element<'a, Message> {
912 let colours: Vec<Colour> = Tone::ALL.into_iter().map(Colour).collect();
913 select(colours, Some(Colour(state.tone())))
914 .width(Length::Fill)
915 .leading(|colour: &Colour| {
916 let tone = colour.0;
917 Some(theme::swatch(move |theme: &Theme| style::tone(&Tokens::of(theme), tone)).into())
918 })
919 .on_select_maybe(
920 on_event
921 .clone()
922 .map(|handler| move |colour: Colour| handler(Event::Tone(colour.0))),
923 )
924 .into()
925}
926
927type Handler<'a, Message> = Option<std::rc::Rc<dyn Fn(Event) -> Message + 'a>>;
928
929fn send<Message>(handler: &Handler<'_, Message>, event: Event) -> Option<Message> {
930 handler.as_ref().map(|handler| handler(event))
931}
932
933impl<'a, Message: Clone + 'a> From<Editor<'a, Message>> for Element<'a, Message> {
934 fn from(editor: Editor<'a, Message>) -> Self {
935 let Fields {
936 title,
937 all_day,
938 starts,
939 ends,
940 repeat,
941 every,
942 stops,
943 colour,
944 location,
945 notes,
946 } = editor.fields();
947
948 let menus: Vec<Element<'a, Message>> = [
949 repeat.map(|menu| container(menu).width(Length::FillPortion(3)).into()),
950 colour.map(|menu| container(menu).width(Length::FillPortion(2)).into()),
951 ]
952 .into_iter()
953 .flatten()
954 .collect();
955 let menus =
956 (!menus.is_empty()).then(|| Row::with_children(menus).spacing(space::SM).into());
957
958 Column::with_children(
959 [
960 title, all_day, starts, ends, menus, every, stops, location, notes,
961 ]
962 .into_iter()
963 .flatten(),
964 )
965 .spacing(space::MD)
966 .width(Length::Fill)
967 .into()
968 }
969}
970
971fn name<'a, Message: 'a>(name: &'a str) -> Element<'a, Message> {
973 let label = text(name)
974 .size(text_size::SM)
975 .wrapping(text::Wrapping::None)
976 .style(|theme: &Theme| text::Style {
977 color: Some(Tokens::of(theme).muted_foreground),
978 });
979 container(label).width(Length::Fixed(NAME_WIDTH)).into()
980}
981
982fn number_field<'a, Message: Clone + 'a>(
984 value: &str,
985 shortcuts: Shortcuts,
986 on_event: &Handler<'a, Message>,
987 event: fn(String) -> Event,
988) -> Element<'a, Message> {
989 input("1", value)
990 .width(NUMBER_WIDTH)
991 .shortcuts(shortcuts)
992 .on_input_maybe(
993 on_event
994 .clone()
995 .map(|handler| move |text| handler(event(text))),
996 )
997 .into()
998}
999
1000fn every<'a, Message: Clone + 'a>(
1002 state: &'a State,
1003 shortcuts: Shortcuts,
1004 on_event: &Handler<'a, Message>,
1005) -> Element<'a, Message> {
1006 let unit = text(state.repeats().unit(state.interval()))
1007 .size(text_size::SM)
1008 .wrapping(text::Wrapping::None);
1009 row![
1010 name("Every"),
1011 number_field(&state.interval, shortcuts, on_event, Event::Interval),
1012 unit,
1013 ]
1014 .spacing(space::SM)
1015 .align_y(Alignment::Center)
1016 .into()
1017}
1018
1019fn stops<'a, Message: Clone + 'a>(
1021 state: &'a State,
1022 shortcuts: Shortcuts,
1023 on_event: &Handler<'a, Message>,
1024) -> Element<'a, Message> {
1025 let handler = on_event.clone();
1026 let choice = select(&Stops::ALL[..], Some(state.stops()))
1027 .width(Length::Fill)
1028 .on_select_maybe(handler.map(|handler| move |stops| handler(Event::Stops(stops))));
1029 let mut controls = Row::new()
1030 .spacing(space::SM)
1031 .align_y(Alignment::Center)
1032 .push(name("Stops"))
1033 .push(choice);
1034 match state.stops() {
1035 Stops::Never => {}
1036 Stops::On => controls = controls.push(date_field(state, Target::Until, on_event)),
1037 Stops::After => {
1038 let times = text(if state.count() == 1 { "time" } else { "times" })
1039 .size(text_size::SM)
1040 .wrapping(text::Wrapping::None);
1041 controls = controls
1042 .push(number_field(
1043 &state.count,
1044 shortcuts,
1045 on_event,
1046 Event::Count,
1047 ))
1048 .push(times);
1049 }
1050 }
1051 controls.into()
1052}
1053
1054fn moment<'a, Message: Clone + 'a>(
1057 state: &'a State,
1058 field: Field,
1059 label: &'a str,
1060 on_event: &Handler<'a, Message>,
1061) -> Element<'a, Message> {
1062 let mut controls = Row::new()
1063 .spacing(space::SM)
1064 .align_y(Alignment::Center)
1065 .push(name(label))
1066 .push(date_field(state, Target::Field(field), on_event));
1067 if !state.is_all_day() {
1068 let handler = on_event.clone();
1069 controls = controls.push(
1070 select(state.times(field), Some(TimeOfDay(state.time(field))))
1071 .width(TIME_WIDTH)
1072 .on_select_maybe(
1073 handler
1074 .map(|handler| move |time: TimeOfDay| handler(Event::Time(field, time.0))),
1075 ),
1076 );
1077 }
1078 controls.into()
1079}
1080
1081fn date_field<'a, Message: Clone + 'a>(
1083 state: &'a State,
1084 target: Target,
1085 on_event: &Handler<'a, Message>,
1086) -> Element<'a, Message> {
1087 let open = state.picker.filter(|picker| picker.target == target);
1088 let toggle = match target {
1089 Target::Field(field) => Event::Picker(open.is_none().then_some(field)),
1090 Target::Until => Event::UntilPicker(open.is_none()),
1091 };
1092 let date = state.target_date(target);
1093 let trigger = button(date.strftime("%a %-d %b %Y").to_string())
1094 .variant(button::Variant::Outline)
1095 .icon(lucide!(Calendar))
1096 .align_x(Alignment::Start)
1097 .width(Length::Fill)
1098 .on_press_maybe(send(on_event, toggle));
1099
1100 let content: Element<'a, Message> = match open {
1101 Some(picker) => month_picker(state, picker, on_event),
1102 None => Space::new().into(),
1103 };
1104 let mut date = popover(trigger, content)
1105 .open(open.is_some())
1106 .align(Align::Start)
1107 .width(Length::Shrink)
1108 .padding(space::MD);
1109 if let Some(close) = send(on_event, Event::Picker(None)) {
1110 date = date.on_dismiss(close);
1111 }
1112 container(date).width(Length::Fill).clip(true).into()
1115}
1116
1117fn month_picker<'a, Message: Clone + 'a>(
1119 state: &State,
1120 picker: Picker,
1121 on_event: &Handler<'a, Message>,
1122) -> Element<'a, Message> {
1123 let step = |glyph, label: &'static str, months: i32| {
1124 icon_button(glyph)
1125 .label(label)
1126 .variant(icon_button::Variant::Ghost)
1127 .size(Size::Sm)
1128 .on_press_maybe(send(on_event, Event::PickerMonth(months)))
1129 };
1130 let name = text(picker.month.strftime("%B %Y").to_string())
1131 .size(text_size::SM)
1132 .font(theme::semibold())
1133 .wrapping(text::Wrapping::None);
1134 let header = row![
1135 step(lucide!(ChevronLeft), "Previous month", -1),
1136 container(name).center_x(Length::Fill),
1137 step(lucide!(ChevronRight), "Next month", 1),
1138 ]
1139 .align_y(Alignment::Center);
1140
1141 let chosen = state.target_date(picker.target);
1142 let target = picker.target;
1143 let pick = on_event.clone().map(|handler| {
1144 move |date: Date| match target {
1145 Target::Field(field) => handler(Event::Date(field, date)),
1146 Target::Until => handler(Event::Until(date)),
1147 }
1148 });
1149 let grid = month_grid(picker.month, state.week_start, Some(chosen), pick);
1150 column![header, grid]
1151 .spacing(space::SM)
1152 .width(Length::Fixed(7.0 * CELL))
1153 .into()
1154}
1155
1156pub fn month_grid<'a, Message: Clone + 'a>(
1161 month: Date,
1162 week_start: Weekday,
1163 chosen: Option<Date>,
1164 on_pick: Option<impl Fn(Date) -> Message + 'a>,
1165) -> Element<'a, Message> {
1166 let weeks = month_weeks(month, week_start);
1167 let on_pick = on_pick.map(std::rc::Rc::new);
1168 let mut grid = Column::new().spacing(2.0);
1169 if let Some(week) = weeks.first() {
1170 grid = grid.push(Row::with_children(week.iter().map(|date| {
1171 container(text(weekday_label(*date, true)).size(text_size::XS).style(
1172 |theme: &Theme| text::Style {
1173 color: Some(Tokens::of(theme).muted_foreground),
1174 },
1175 ))
1176 .center(Length::Fixed(CELL))
1177 .into()
1178 })));
1179 }
1180 for week in &weeks {
1181 grid = grid.push(Row::with_children(week.iter().map(|date| {
1182 if date.month() != month.month() {
1183 return Space::new()
1184 .width(Length::Fixed(CELL))
1185 .height(Length::Fixed(CELL))
1186 .into();
1187 }
1188 let day = style::Day {
1189 today: false,
1190 selected: Some(*date) == chosen,
1191 in_month: true,
1192 };
1193 let number = text(date.day().to_string())
1194 .size(text_size::XS)
1195 .wrapping(text::Wrapping::None);
1196 widget::button(container(number).center(Length::Fill))
1197 .width(Length::Fixed(CELL))
1198 .height(Length::Fixed(CELL))
1199 .padding(0)
1200 .on_press_maybe(on_pick.as_ref().map(|pick| pick(*date)))
1201 .style(move |theme, status: Status| {
1202 style::year_day(&Tokens::of(theme), day, status)
1203 })
1204 .into()
1205 })));
1206 }
1207 grid.into()
1208}
1209
1210#[cfg(test)]
1211mod tests {
1212 use super::*;
1213 use jiff::civil::date;
1214
1215 const UTC: TimeZone = TimeZone::UTC;
1216
1217 fn at(hour: u16, minute: u16) -> Timestamp {
1219 instant_at(date(2026, 6, 19), hour * 60 + minute, &UTC)
1220 }
1221
1222 fn timed() -> State {
1223 State::new(
1224 &Draft {
1225 when: When::timed(at(11, 0), at(12, 30)),
1226 },
1227 &UTC,
1228 )
1229 }
1230
1231 fn whole_day() -> State {
1232 State::new(
1233 &Draft {
1234 when: When::day(date(2026, 6, 19)),
1235 },
1236 &UTC,
1237 )
1238 }
1239
1240 #[test]
1241 fn a_new_form_starts_from_the_draft() {
1242 let form = timed();
1243 assert!(form.is_new());
1244 assert_eq!(form.id(), None);
1245 assert_eq!(form.title(), "");
1246 assert!(!form.is_all_day());
1247 assert_eq!(form.date(Field::Start), date(2026, 6, 19));
1248 assert_eq!((form.time(Field::Start), form.time(Field::End)), (660, 750));
1249 assert_eq!(form.repeats(), Repeats::Never);
1250 assert_eq!(form.tone(), Tone::Primary);
1251 assert_eq!(form.picker(), None);
1252 assert_eq!(form.when(), When::timed(at(11, 0), at(12, 30)));
1253
1254 let form = whole_day();
1255 assert!(form.is_all_day());
1256 assert_eq!(form.when(), When::day(date(2026, 6, 19)));
1257 }
1258
1259 #[test]
1260 fn editing_starts_from_the_entry_and_keeps_what_the_form_does_not_show() {
1261 let rule = Repeat::weekly().interval(2);
1262 let entry = Entry::new(EntryId(4), "Review", at(15, 0), at(16, 0))
1263 .tone(Tone::Success)
1264 .tag("work")
1265 .repeat(rule)
1266 .location("Room 4")
1267 .notes("Bring the plan\nand the figures");
1268 let mut form = State::edit(&entry, &UTC);
1269 assert_eq!(form.id(), Some(EntryId(4)));
1270 assert!(!form.is_new());
1271 assert_eq!(form.title(), "Review");
1272 assert_eq!(form.tone(), Tone::Success);
1273 assert_eq!(form.repeats(), Repeats::Weekly);
1274 assert_eq!(form.interval(), 2);
1275 assert_eq!(form.stops(), Stops::Never);
1276 assert_eq!(form.location(), "Room 4");
1277 assert_eq!(form.notes(), "Bring the plan\nand the figures");
1278 assert_eq!(form.entry(EntryId(99)), entry, "unchanged, with its own id");
1279
1280 form.update(Event::Title(String::from("Retro")));
1281 let saved = form.entry(EntryId(99));
1282 assert_eq!(saved.id(), EntryId(4));
1283 assert_eq!(saved.title(), "Retro");
1284 assert_eq!(saved.tag_of(), Some("work"));
1285 assert_eq!(saved.repeat_of(), Some(rule));
1286 assert_eq!(saved.location_of(), Some("Room 4"));
1287 }
1288
1289 #[test]
1290 fn a_blank_title_is_saved_as_untitled_and_a_new_entry_takes_the_id_given() {
1291 let mut form = timed();
1292 form.update(Event::Title(String::from(" ")));
1293 let entry = form.entry(EntryId(7));
1294 assert_eq!(entry.id(), EntryId(7));
1295 assert_eq!(entry.title(), UNTITLED);
1296 form.update(Event::Title(String::from(" Retro ")));
1297 assert_eq!(form.entry(EntryId(7)).title(), "Retro");
1298 }
1299
1300 #[test]
1301 fn moving_the_start_keeps_the_length() {
1302 let mut form = timed();
1303 form.update(Event::Time(Field::Start, 14 * 60));
1304 assert_eq!((form.time(Field::Start), form.time(Field::End)), (840, 930));
1305
1306 form.update(Event::Date(Field::Start, date(2026, 6, 22)));
1307 assert_eq!(form.date(Field::End), date(2026, 6, 22));
1308 assert_eq!(
1309 form.when(),
1310 When::timed(
1311 instant_at(date(2026, 6, 22), 840, &UTC),
1312 instant_at(date(2026, 6, 22), 930, &UTC)
1313 )
1314 );
1315
1316 form.update(Event::Time(Field::Start, 23 * 60));
1318 assert_eq!(form.date(Field::End), date(2026, 6, 23));
1319 assert_eq!(form.time(Field::End), 30);
1320 }
1321
1322 #[test]
1323 fn the_end_never_goes_before_the_start() {
1324 let mut form = timed();
1325 form.update(Event::Time(Field::End, 9 * 60));
1327 assert_eq!(form.date(Field::End), date(2026, 6, 20));
1328 assert_eq!(form.time(Field::End), 540);
1329
1330 form.update(Event::Date(Field::End, date(2026, 6, 1)));
1332 assert_eq!(form.date(Field::End), date(2026, 6, 19));
1333 assert_eq!(form.time(Field::End), 660 + TIME_STEP);
1334
1335 let mut form = timed();
1337 form.update(Event::Time(Field::End, 660));
1338 assert_eq!(form.time(Field::End), 660 + TIME_STEP);
1339
1340 let late = at(23, 45);
1342 let mut form = State::new(
1343 &Draft {
1344 when: When::timed(late, late),
1345 },
1346 &UTC,
1347 );
1348 form.update(Event::Time(Field::End, 23 * 60 + 45));
1349 assert_eq!(
1350 (form.date(Field::End), form.time(Field::End)),
1351 (date(2026, 6, 20), 0)
1352 );
1353 }
1354
1355 #[test]
1356 fn times_out_of_range_are_kept_within_the_day() {
1357 let mut form = timed();
1358 form.update(Event::Time(Field::Start, 5000));
1359 assert_eq!(form.time(Field::Start), DAY_MINUTES - 1);
1360 }
1361
1362 #[test]
1363 fn all_day_keeps_the_dates_and_brings_the_times_back() {
1364 let mut form = timed();
1365 form.update(Event::AllDay(true));
1366 assert_eq!(form.when(), When::day(date(2026, 6, 19)));
1367 form.update(Event::Date(Field::End, date(2026, 6, 21)));
1368 assert_eq!(
1369 form.when(),
1370 When::all_day(date(2026, 6, 19), date(2026, 6, 21))
1371 );
1372 form.update(Event::Date(Field::End, date(2026, 6, 1)));
1373 assert_eq!(form.date(Field::End), date(2026, 6, 19), "same day is fine");
1374 form.update(Event::AllDay(false));
1375 assert_eq!((form.time(Field::Start), form.time(Field::End)), (660, 750));
1376
1377 let mut form = whole_day();
1379 form.update(Event::AllDay(false));
1380 assert_eq!((form.time(Field::Start), form.time(Field::End)), (540, 600));
1381 }
1382
1383 #[test]
1384 fn repeat_and_colour_reach_the_entry() {
1385 let mut form = timed();
1386 form.update(Event::Repeats(Repeats::Weekly));
1387 form.update(Event::Tone(Tone::Warning));
1388 let entry = form.entry(EntryId(1));
1389 assert_eq!(entry.repeat_of(), Some(Repeat::weekly()));
1390 assert_eq!(entry.tone_of(), Tone::Warning);
1391 form.update(Event::Repeats(Repeats::Never));
1392 assert_eq!(form.entry(EntryId(1)).repeat_of(), None);
1393 }
1394
1395 #[test]
1396 fn every_repeat_choice_has_a_name_and_round_trips() {
1397 for choice in Repeats::ALL {
1398 assert!(!choice.to_string().is_empty());
1399 assert_eq!(Repeats::of(choice.frequency()), choice);
1400 }
1401 assert_eq!(Repeats::default(), Repeats::Never);
1402 assert_eq!(Repeats::Never.frequency(), None);
1403 let units: Vec<_> = Repeats::ALL
1404 .iter()
1405 .map(|choice| (choice.unit(1), choice.unit(2)))
1406 .collect();
1407 assert_eq!(
1408 units,
1409 vec![
1410 ("", ""),
1411 ("day", "days"),
1412 ("week", "weeks"),
1413 ("month", "months"),
1414 ("year", "years")
1415 ]
1416 );
1417 let names: Vec<_> = Stops::ALL.iter().map(Stops::to_string).collect();
1418 assert_eq!(names, vec!["Never", "On a date", "After"]);
1419 assert_eq!(Stops::default(), Stops::Never);
1420 }
1421
1422 #[test]
1423 fn a_repeat_takes_its_interval_and_its_end_from_the_form() {
1424 let mut form = timed();
1425 assert_eq!(form.repeat(), None);
1426 assert_eq!((form.interval(), form.count()), (1, DEFAULT_COUNT));
1427 assert_eq!(form.until(), date(2026, 7, 19), "a month after the start");
1428
1429 form.update(Event::Repeats(Repeats::Weekly));
1430 assert_eq!(form.repeat(), Some(Repeat::weekly()));
1431 form.update(Event::Interval(String::from("2")));
1432 assert_eq!(form.repeat(), Some(Repeat::weekly().interval(2)));
1433
1434 form.update(Event::Stops(Stops::After));
1435 form.update(Event::Count(String::from("6")));
1436 assert_eq!(form.repeat(), Some(Repeat::weekly().interval(2).count(6)));
1437
1438 form.update(Event::Stops(Stops::On));
1439 form.update(Event::Until(date(2026, 9, 1)));
1440 let rule = Repeat::weekly().interval(2).until(date(2026, 9, 1));
1441 assert_eq!(form.repeat(), Some(rule));
1442 assert_eq!(form.entry(EntryId(1)).repeat_of(), Some(rule));
1443
1444 form.update(Event::Repeats(Repeats::Never));
1446 assert_eq!(form.repeat(), None);
1447 form.update(Event::Repeats(Repeats::Monthly));
1448 assert_eq!(
1449 form.repeat(),
1450 Some(Repeat::monthly().interval(2).until(date(2026, 9, 1)))
1451 );
1452 }
1453
1454 #[test]
1455 fn number_fields_keep_digits_and_count_blank_as_one() {
1456 let mut form = timed();
1457 form.update(Event::Repeats(Repeats::Daily));
1458 form.update(Event::Interval(String::from("a1b2c3d4")));
1459 assert_eq!(form.interval(), 123, "three digits at most");
1460 form.update(Event::Interval(String::new()));
1461 assert_eq!(form.interval(), 1, "blank while typing");
1462 form.update(Event::Interval(String::from("0")));
1463 assert_eq!(form.interval(), 1);
1464 assert_eq!(form.repeat(), Some(Repeat::daily()));
1465
1466 form.update(Event::Stops(Stops::After));
1467 form.update(Event::Count(String::from("-5 times")));
1468 assert_eq!(form.count(), 5);
1469 form.update(Event::Count(String::from("0")));
1470 assert_eq!(form.count(), 1);
1471 }
1472
1473 #[test]
1474 fn an_entry_ending_on_a_date_or_after_a_count_fills_the_form() {
1475 let base = Entry::new(EntryId(4), "Review", at(15, 0), at(16, 0));
1476 let on = base
1477 .clone()
1478 .repeat(Repeat::monthly().until(date(2026, 12, 19)));
1479 let form = State::edit(&on, &UTC);
1480 assert_eq!(form.repeats(), Repeats::Monthly);
1481 assert_eq!(form.stops(), Stops::On);
1482 assert_eq!(form.until(), date(2026, 12, 19));
1483 assert_eq!(form.entry(EntryId(9)), on);
1484
1485 let after = base.repeat(Repeat::yearly().interval(4).count(3));
1486 let form = State::edit(&after, &UTC);
1487 assert_eq!(form.repeats(), Repeats::Yearly);
1488 assert_eq!(form.stops(), Stops::After);
1489 assert_eq!((form.interval(), form.count()), (4, 3));
1490 assert_eq!(form.entry(EntryId(9)), after);
1491 }
1492
1493 #[test]
1494 fn the_last_date_of_a_repeat_stays_on_or_after_the_start() {
1495 let mut form = timed();
1496 form.update(Event::Repeats(Repeats::Daily));
1497 form.update(Event::Stops(Stops::On));
1498 form.update(Event::Until(date(2026, 6, 1)));
1499 assert_eq!(form.until(), date(2026, 6, 19), "not before the start");
1500
1501 form.update(Event::Until(date(2026, 6, 25)));
1502 form.update(Event::Date(Field::Start, date(2026, 8, 3)));
1503 assert_eq!(form.until(), date(2026, 8, 3), "carried by the start");
1504 }
1505
1506 #[test]
1507 fn the_picker_for_the_last_date_opens_turns_and_closes() {
1508 let mut form = timed();
1509 form.update(Event::Repeats(Repeats::Daily));
1510 form.update(Event::Stops(Stops::On));
1511 form.update(Event::UntilPicker(true));
1512 assert!(form.is_picking_until());
1513 assert_eq!(form.picker(), None, "not the start's or the end's");
1514 assert_eq!(form.picker.map(|p| p.month), Some(date(2026, 7, 1)));
1515 form.update(Event::PickerMonth(2));
1516 assert_eq!(form.picker.map(|p| p.month), Some(date(2026, 9, 1)));
1517 form.update(Event::Until(date(2026, 9, 14)));
1518 assert!(!form.is_picking_until());
1519 assert_eq!(form.until(), date(2026, 9, 14));
1520
1521 form.update(Event::UntilPicker(true));
1523 form.update(Event::Picker(Some(Field::Start)));
1524 assert!(!form.is_picking_until());
1525 assert_eq!(form.picker(), Some(Field::Start));
1526 form.update(Event::UntilPicker(true));
1527 form.update(Event::UntilPicker(false));
1528 assert!(!form.is_picking_until());
1529 form.update(Event::UntilPicker(true));
1530 form.update(Event::Stops(Stops::Never));
1531 assert!(!form.is_picking_until());
1532 form.update(Event::Stops(Stops::On));
1533 form.update(Event::UntilPicker(true));
1534 form.update(Event::Repeats(Repeats::Never));
1535 assert!(!form.is_picking_until());
1536 form.update(Event::UntilPicker(true));
1537 form.update(Event::Picker(None));
1538 assert!(!form.is_picking_until());
1539 }
1540
1541 #[test]
1542 fn location_and_notes_reach_the_entry() {
1543 let mut form = timed();
1544 assert_eq!(form.location(), "");
1545 assert_eq!(form.notes(), "");
1546 let blank = form.entry(EntryId(1));
1547 assert_eq!((blank.location_of(), blank.notes_of()), (None, None));
1548
1549 form.update(Event::Location(String::from(" Room 4 ")));
1550 for letter in "Agenda".chars() {
1551 form.update(Event::Notes(Action::Edit(
1552 iced::widget::text_editor::Edit::Insert(letter),
1553 )));
1554 }
1555 form.update(Event::Notes(Action::Edit(
1556 iced::widget::text_editor::Edit::Enter,
1557 )));
1558 assert_eq!(form.notes(), "Agenda", "space at the ends is dropped");
1559 let entry = form.entry(EntryId(1));
1560 assert_eq!(entry.location_of(), Some("Room 4"));
1561 assert_eq!(entry.notes_of(), Some("Agenda"));
1562 }
1563
1564 #[test]
1565 fn times_and_colours_have_names() {
1566 assert_eq!(TimeOfDay(0).to_string(), "00:00");
1567 assert_eq!(TimeOfDay(570).to_string(), "09:30");
1568 let all = TimeOfDay::all();
1569 assert_eq!(all.len(), 96);
1570 assert_eq!(all.last(), Some(&TimeOfDay(1425)));
1571
1572 let from_ten = TimeOfDay::from(607);
1574 assert_eq!(from_ten.len(), 96);
1575 assert_eq!(from_ten.first(), Some(&TimeOfDay(600)));
1576 assert_eq!(from_ten.last(), Some(&TimeOfDay(585)));
1577 assert_eq!(TimeOfDay::from(0), all);
1578 assert_eq!(TimeOfDay::from(9999).first(), Some(&TimeOfDay(1425)));
1579
1580 let form = timed();
1582 assert_eq!(form.times(Field::Start).first(), Some(&TimeOfDay(600)));
1583 assert_eq!(form.times(Field::End).first(), Some(&TimeOfDay(675)));
1584 let mut overnight = timed();
1585 overnight.update(Event::Date(Field::End, date(2026, 6, 20)));
1586 assert_eq!(
1587 overnight.times(Field::End).first(),
1588 Some(&TimeOfDay(750 - 60))
1589 );
1590 let names: Vec<_> = Tone::ALL
1591 .iter()
1592 .map(|tone| Colour(*tone).to_string())
1593 .collect();
1594 assert_eq!(names, vec!["Default", "Neutral", "Green", "Amber", "Red"]);
1595 }
1596
1597 #[test]
1598 fn the_date_picker_opens_on_the_field_month_and_closes_on_a_choice() {
1599 let mut form = timed().with_week_start(Weekday::Sunday);
1600 form.update(Event::Picker(Some(Field::End)));
1601 assert_eq!(form.picker(), Some(Field::End));
1602 assert_eq!(form.picker.map(|p| p.month), Some(date(2026, 6, 1)));
1603
1604 form.update(Event::PickerMonth(1));
1605 form.update(Event::PickerMonth(1));
1606 assert_eq!(form.picker.map(|p| p.month), Some(date(2026, 8, 1)));
1607 form.update(Event::PickerMonth(-3));
1608 assert_eq!(form.picker.map(|p| p.month), Some(date(2026, 5, 1)));
1609
1610 form.update(Event::Date(Field::End, date(2026, 6, 20)));
1611 assert_eq!(form.picker(), None);
1612 assert_eq!(form.date(Field::End), date(2026, 6, 20));
1613
1614 form.update(Event::Picker(Some(Field::Start)));
1615 form.update(Event::Picker(None));
1616 assert_eq!(form.picker(), None);
1617 form.update(Event::PickerMonth(1));
1618 assert_eq!(form.picker(), None, "nothing to move");
1619 }
1620
1621 #[test]
1622 fn builder_defaults_and_options() {
1623 let form = timed();
1624 let built: Editor<'_, Event> = editor(&form);
1625 assert!(built.on_event.is_none());
1626 assert!(built.on_submit.is_none());
1627 assert_eq!(built.shortcuts, Shortcuts::all());
1628
1629 let built = built
1630 .on_event(|event| event)
1631 .on_submit(Event::Picker(None))
1632 .shortcuts(Shortcuts::none());
1633 assert!(built.on_event.is_some());
1634 assert!(built.on_submit.is_some());
1635 assert_eq!(built.shortcuts, Shortcuts::none());
1636 assert!(format!("{built:?}").contains("enabled: true"));
1637 }
1638
1639 #[test]
1640 fn parts_can_be_left_out_and_laid_out_by_the_app() {
1641 let mut form = timed();
1642 {
1643 let built: Editor<'_, Event> = editor(&form);
1644 assert!(Part::ALL.iter().all(|part| built.shows(*part)));
1645 let fields = built.fields();
1646 assert!(fields.title.is_some() && fields.notes.is_some() && fields.colour.is_some());
1647 assert!(
1648 fields.every.is_none() && fields.stops.is_none(),
1649 "it does not repeat"
1650 );
1651 }
1652 {
1653 let built: Editor<'_, Event> = editor(&form)
1654 .without(Part::Colour)
1655 .without(Part::Location)
1656 .without(Part::Colour);
1657 assert!(!built.shows(Part::Colour));
1658 assert!(format!("{built:?}").contains("Location"));
1659 let fields = built.fields();
1660 assert!(fields.colour.is_none() && fields.location.is_none());
1661 assert!(fields.title.is_some() && fields.starts.is_some() && fields.ends.is_some());
1662 }
1663
1664 form.update(Event::Repeats(Repeats::Weekly));
1665 let fields = editor::<Event>(&form).fields();
1666 assert!(fields.every.is_some() && fields.stops.is_some());
1667 let fields = editor::<Event>(&form).without(Part::Repeat).fields();
1668 assert!(fields.repeat.is_none() && fields.every.is_none() && fields.stops.is_none());
1669 }
1670
1671 #[test]
1672 fn the_raw_field_text_the_picker_month_and_the_notes_can_be_read() {
1673 let mut form = timed().with_week_start(Weekday::Sunday);
1674 assert_eq!(form.week_start(), Weekday::Sunday);
1675 form.update(Event::Interval(String::new()));
1676 assert_eq!(form.interval_text(), "");
1677 assert_eq!(form.interval(), 1, "blank counts as one");
1678 form.update(Event::Count(String::from("2a")));
1679 assert_eq!(form.count_text(), "2");
1680
1681 assert_eq!(form.picker_month(), None);
1682 form.update(Event::Picker(Some(Field::Start)));
1683 let month = form.date(Field::Start).first_of_month();
1684 assert_eq!(form.picker_month(), Some(month));
1685 form.update(Event::PickerMonth(2));
1686 assert_eq!(form.picker_month(), month.checked_add(2.months()).ok());
1687
1688 form.update(Event::Notes(Action::Edit(
1689 iced::widget::text_editor::Edit::Paste(std::sync::Arc::new(String::from("Bring cake"))),
1690 )));
1691 assert_eq!(form.notes_content().text().trim(), "Bring cake");
1692 }
1693}