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