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, Color, Element, Length, Theme};
46use jiff::civil::{Date, Weekday};
47use jiff::tz::TimeZone;
48use jiff::{Timestamp, ToSpan};
49
50use super::entry::{Draft, Entry, EntryId, Paint, 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
269pub const CUSTOM_COLOUR: &str = "Custom";
272
273#[derive(Debug, Clone, PartialEq)]
276enum Choice {
277 Tone(Tone),
278 Custom(Color, Option<String>),
279}
280
281impl std::fmt::Display for Choice {
282 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
283 match self {
284 Choice::Tone(tone) => Colour(*tone).fmt(f),
285 Choice::Custom(_, Some(label)) => f.write_str(label),
286 Choice::Custom(_, None) => f.write_str(CUSTOM_COLOUR),
287 }
288 }
289}
290
291#[derive(Debug, Clone, PartialEq)]
293pub enum Event {
294 Title(String),
295 AllDay(bool),
296 Date(Field, Date),
298 Time(Field, u16),
300 Repeats(Repeats),
301 Interval(String),
303 Stops(Stops),
304 Until(Date),
306 Count(String),
308 Tone(Tone),
310 Colour(Option<Color>),
313 Location(String),
314 Notes(Action),
316 Picker(Option<Field>),
319 UntilPicker(bool),
321 PickerMonth(i32),
323}
324
325#[derive(Debug, Clone, Copy, PartialEq, Eq)]
327enum Target {
328 Field(Field),
329 Until,
330}
331
332#[derive(Debug, Clone, Copy, PartialEq, Eq)]
334struct Picker {
335 target: Target,
336 month: Date,
337}
338
339#[derive(Debug, Clone)]
343pub struct State {
344 id: Option<EntryId>,
345 title: String,
346 all_day: bool,
347 start: (Date, u16),
348 end: (Date, u16),
349 opened: Option<(Timestamp, Timestamp)>,
352 rolled: bool,
355 repeats: Repeats,
356 interval: String,
357 stops: Stops,
358 until: Date,
359 count: String,
360 tone: Tone,
361 colour: Option<Color>,
362 source: Option<Box<Entry>>,
366 colour_label: Option<String>,
367 location: String,
368 notes: Content,
369 opened_notes: Option<String>,
372 time_zone: TimeZone,
373 week_start: Weekday,
374 picker: Option<Picker>,
375}
376
377fn digits(text: &str) -> String {
380 text.chars()
381 .filter(char::is_ascii_digit)
382 .skip_while(|c| *c == '0')
383 .take(NUMBER_DIGITS)
384 .collect()
385}
386
387fn number(text: &str) -> u32 {
389 text.parse::<u32>().unwrap_or(1).max(1)
390}
391
392impl State {
393 pub fn new(draft: &Draft, time_zone: &TimeZone) -> Self {
395 Self::over(draft.when, time_zone)
396 }
397
398 pub fn edit(entry: &Entry, time_zone: &TimeZone) -> Self {
400 let mut form = Self {
401 id: Some(entry.id()),
402 title: entry.title().to_owned(),
403 tone: entry.tone_of(),
404 colour: entry.colour_of(),
405 source: Some(Box::new(entry.clone())),
406 location: entry.location_of().unwrap_or_default().to_owned(),
407 notes: Content::with_text(entry.notes_of().unwrap_or_default()),
408 opened_notes: entry.notes_of().map(str::to_owned),
409 ..Self::over(entry.when(), time_zone)
410 };
411 let Some(repeat) = entry.repeat_of() else {
412 return form;
413 };
414 form.repeats = Repeats::of(Some(repeat.frequency()));
415 form.interval = repeat.every().to_string();
416 match repeat.ends() {
417 Ends::Never => {}
418 Ends::On(date) => {
419 form.stops = Stops::On;
420 form.until = date;
421 }
422 Ends::After(count) => {
423 form.stops = Stops::After;
424 form.count = count.to_string();
425 }
426 }
427 form
428 }
429
430 fn over(when: When, time_zone: &TimeZone) -> Self {
431 let nine = 9 * 60;
432 let (all_day, start, end, opened) = match when {
433 When::AllDay { first, last } => {
434 (true, (first, nine), (last, nine + DEFAULT_MINUTES), None)
435 }
436 When::Timed { start, end } => (
437 false,
438 local(start, time_zone),
439 local(end.max(start), time_zone),
440 Some((start, end.max(start))),
441 ),
442 };
443 Self {
444 id: None,
445 title: String::new(),
446 all_day,
447 start,
448 end,
449 opened,
450 rolled: false,
451 repeats: Repeats::Never,
452 interval: String::from("1"),
453 stops: Stops::Never,
454 until: start.0.checked_add(1.month()).unwrap_or(start.0),
455 count: DEFAULT_COUNT.to_string(),
456 tone: Tone::default(),
457 colour: None,
458 source: None,
459 colour_label: None,
460 location: String::new(),
461 notes: Content::new(),
462 opened_notes: None,
463 time_zone: time_zone.clone(),
464 week_start: Weekday::Monday,
465 picker: None,
466 }
467 }
468
469 pub fn with_week_start(mut self, week_start: Weekday) -> Self {
471 self.week_start = week_start;
472 self
473 }
474
475 pub fn week_start(&self) -> Weekday {
477 self.week_start
478 }
479
480 pub fn id(&self) -> Option<EntryId> {
482 self.id
483 }
484
485 pub fn is_new(&self) -> bool {
486 self.id.is_none()
487 }
488
489 pub fn title(&self) -> &str {
490 &self.title
491 }
492
493 pub fn is_all_day(&self) -> bool {
494 self.all_day
495 }
496
497 pub fn repeats(&self) -> Repeats {
498 self.repeats
499 }
500
501 pub fn interval(&self) -> u32 {
503 number(&self.interval)
504 }
505
506 pub fn stops(&self) -> Stops {
507 self.stops
508 }
509
510 pub fn until(&self) -> Date {
512 self.until
513 }
514
515 pub fn count(&self) -> u32 {
518 number(&self.count)
519 }
520
521 pub fn repeat(&self) -> Option<Repeat> {
524 let rule = Repeat::new(self.repeats.frequency()?).interval(self.interval());
525 Some(match self.stops {
526 Stops::Never => rule,
527 Stops::On => rule.until(self.until),
528 Stops::After => rule.count(self.count()),
529 })
530 }
531
532 pub fn tone(&self) -> Tone {
533 self.tone
534 }
535
536 pub fn colour(&self) -> Option<Color> {
539 self.colour
540 }
541
542 pub fn with_colour_label(mut self, label: impl Into<String>) -> Self {
546 let label = label.into();
547 self.colour_label = (!label.trim().is_empty()).then(|| label.trim().to_owned());
548 self
549 }
550
551 pub fn colour_label(&self) -> Option<&str> {
552 self.colour_label.as_deref()
553 }
554
555 fn own_colour(&self) -> Option<Color> {
558 self.colour
559 .or_else(|| self.source.as_ref().and_then(|source| source.colour_of()))
560 }
561
562 pub fn location(&self) -> &str {
563 &self.location
564 }
565
566 pub fn notes(&self) -> String {
570 if let Some(notes) = &self.opened_notes {
571 return notes.clone();
572 }
573 self.notes.text().trim().to_owned()
574 }
575
576 pub fn notes_content(&self) -> &Content {
579 &self.notes
580 }
581
582 pub fn picker_month(&self) -> Option<Date> {
585 self.picker.map(|picker| picker.month)
586 }
587
588 pub fn interval_text(&self) -> &str {
590 &self.interval
591 }
592
593 pub fn count_text(&self) -> &str {
595 &self.count
596 }
597
598 pub fn is_picking_until(&self) -> bool {
600 self.picker
601 .is_some_and(|picker| picker.target == Target::Until)
602 }
603
604 pub fn date(&self, field: Field) -> Date {
606 self.at(field).0
607 }
608
609 pub fn time(&self, field: Field) -> u16 {
611 self.at(field).1
612 }
613
614 pub fn times(&self, field: Field) -> Vec<TimeOfDay> {
621 match field {
622 Field::End if self.end.0 == self.start.0 || self.rolled => {
623 TimeOfDay::from((self.start.1 + TIME_STEP) % DAY_MINUTES)
624 }
625 _ => TimeOfDay::all(),
626 }
627 }
628
629 pub fn picker(&self) -> Option<Field> {
631 match self.picker?.target {
632 Target::Field(field) => Some(field),
633 Target::Until => None,
634 }
635 }
636
637 pub fn when(&self) -> When {
639 if self.all_day {
640 return When::all_day(self.start.0, self.end.0);
641 }
642 let (opened_start, opened_end) = self.opened.unzip();
643 When::timed(
644 self.instant(self.start, opened_start),
645 self.instant(self.end, opened_end),
646 )
647 }
648
649 fn instant(&self, field: (Date, u16), opened: Option<Timestamp>) -> Timestamp {
652 match opened {
653 Some(instant) if local(instant, &self.time_zone) == field => instant,
654 _ => instant_at(field.0, field.1, &self.time_zone),
655 }
656 }
657
658 pub fn entry(&self, new_id: EntryId) -> Entry {
663 let title = match self.title.trim() {
664 "" => UNTITLED,
665 title => title,
666 };
667 let entry = match &self.source {
668 Some(source) => (**source).clone().titled(title).rescheduled(self.when()),
669 None => Entry::at(new_id, title, self.when()),
670 };
671 entry
672 .tone(self.tone)
673 .colour(self.colour)
674 .location(self.location.clone())
675 .notes(self.notes())
676 .repeating(self.repeat())
677 }
678
679 pub fn update(&mut self, event: Event) {
680 match event {
681 Event::Title(title) => self.title = title,
682 Event::AllDay(all_day) => self.set_all_day(all_day),
683 Event::Date(field, date) => {
684 self.picker = None;
685 if field == Field::End {
686 self.rolled = false;
687 }
688 self.set(field, (date, self.time(field)));
689 }
690 Event::Time(field, minute) => {
691 let mut date = self.date(field);
692 if field == Field::End && self.rolled {
695 date = self.start.0;
696 self.rolled = false;
697 }
698 self.set(field, (date, minute.min(DAY_MINUTES - 1)));
699 }
700 Event::Repeats(repeats) => {
701 self.repeats = repeats;
702 if repeats == Repeats::Never && self.is_picking_until() {
703 self.picker = None;
704 }
705 }
706 Event::Interval(text) => self.interval = digits(&text),
707 Event::Stops(stops) => {
708 self.stops = stops;
709 if stops != Stops::On && self.is_picking_until() {
710 self.picker = None;
711 }
712 }
713 Event::Until(date) => {
714 self.picker = None;
715 self.until = date.max(self.start.0);
716 }
717 Event::Count(text) => self.count = digits(&text),
718 Event::Tone(tone) => {
719 self.tone = tone;
720 self.colour = None;
721 }
722 Event::Colour(colour) => self.colour = colour,
723 Event::Location(location) => self.location = location,
724 Event::Notes(action) => {
725 if action.is_edit() {
726 self.opened_notes = None;
727 }
728 self.notes.perform(action);
729 }
730 Event::Picker(field) => {
731 self.picker = field.map(|field| Picker {
732 target: Target::Field(field),
733 month: self.date(field).first_of_month(),
734 });
735 }
736 Event::UntilPicker(open) => {
737 self.picker = open.then(|| Picker {
738 target: Target::Until,
739 month: self.until.first_of_month(),
740 });
741 }
742 Event::PickerMonth(months) => {
743 if let Some(picker) = &mut self.picker {
744 picker.month = picker
745 .month
746 .checked_add(i64::from(months.clamp(-1200, 1200)).months())
747 .unwrap_or(picker.month);
748 }
749 }
750 }
751 }
752
753 fn at(&self, field: Field) -> (Date, u16) {
754 match field {
755 Field::Start => self.start,
756 Field::End => self.end,
757 }
758 }
759
760 fn set(&mut self, field: Field, to: (Date, u16)) {
763 match field {
764 Field::Start => {
765 let days = days_between(self.start.0, self.end.0);
766 let minutes = i32::from(self.end.1) - i32::from(self.start.1);
767 self.start = to;
768 let end = i32::from(to.1) + minutes;
769 self.end = (
770 add_days(to.0, days + end.div_euclid(i32::from(DAY_MINUTES))),
771 u16::try_from(end.rem_euclid(i32::from(DAY_MINUTES))).unwrap_or(0),
772 );
773 }
774 Field::End => self.end = to,
775 }
776 self.until = self.until.max(self.start.0);
777 self.settle(field);
778 }
779
780 fn target_date(&self, target: Target) -> Date {
782 match target {
783 Target::Field(field) => self.date(field),
784 Target::Until => self.until,
785 }
786 }
787
788 fn set_all_day(&mut self, all_day: bool) {
792 if self.all_day == all_day {
793 return;
794 }
795 self.all_day = all_day;
796 let midnight_end = self.end.1 == 0;
797 match all_day {
798 true if midnight_end && self.end.0 > self.start.0 => {
799 self.end.0 = add_days(self.end.0, -1);
800 }
801 false if midnight_end => self.end.0 = add_days(self.end.0, 1),
802 _ => {}
803 }
804 self.rolled = false;
805 self.settle(Field::End);
806 }
807
808 fn settle(&mut self, changed: Field) {
811 if self.all_day {
812 if self.end.0 < self.start.0 {
813 self.end.0 = self.start.0;
814 }
815 return;
816 }
817 if self.end > self.start {
818 return;
819 }
820 if changed == Field::End && self.end.0 == self.start.0 {
823 self.end.0 = add_days(self.start.0, 1);
824 self.rolled = true;
825 return;
826 }
827 let end = self.start.1 + TIME_STEP;
828 self.end = if end >= DAY_MINUTES {
829 (add_days(self.start.0, 1), end - DAY_MINUTES)
830 } else {
831 (self.start.0, end)
832 };
833 }
834}
835
836fn local(instant: Timestamp, time_zone: &TimeZone) -> (Date, u16) {
838 let date = date_of(instant, time_zone);
839 (date, minute_on(date, instant, time_zone))
840}
841
842fn days_between(from: Date, to: Date) -> i32 {
843 i32::try_from(to.duration_since(from).as_hours() / 24).unwrap_or(0)
844}
845
846#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
848pub enum Part {
849 Title,
850 AllDay,
851 Starts,
852 Ends,
853 Repeat,
855 Colour,
856 Location,
857 Notes,
858}
859
860impl Part {
861 pub const ALL: [Part; 8] = [
862 Part::Title,
863 Part::AllDay,
864 Part::Starts,
865 Part::Ends,
866 Part::Repeat,
867 Part::Colour,
868 Part::Location,
869 Part::Notes,
870 ];
871}
872
873pub struct Editor<'a, Message> {
876 state: &'a State,
877 on_event: Option<Box<dyn Fn(Event) -> Message + 'a>>,
878 on_submit: Option<Message>,
879 shortcuts: Shortcuts,
880 without: Vec<Part>,
881 read_only: bool,
882}
883
884pub fn editor<Message>(state: &State) -> Editor<'_, Message> {
888 Editor {
889 state,
890 on_event: None,
891 on_submit: None,
892 shortcuts: Shortcuts::all(),
893 without: Vec::new(),
894 read_only: false,
895 }
896}
897
898impl<Message> std::fmt::Debug for Editor<'_, Message> {
899 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
900 f.debug_struct("Editor")
901 .field("state", self.state)
902 .field("enabled", &self.on_event.is_some())
903 .field("submits", &self.on_submit.is_some())
904 .field("shortcuts", &self.shortcuts)
905 .field("without", &self.without)
906 .field("read_only", &self.read_only)
907 .finish()
908 }
909}
910
911pub struct Fields<'a, Message> {
920 pub title: Option<Element<'a, Message>>,
921 pub all_day: Option<Element<'a, Message>>,
922 pub starts: Option<Element<'a, Message>>,
923 pub ends: Option<Element<'a, Message>>,
924 pub repeat: Option<Element<'a, Message>>,
925 pub every: Option<Element<'a, Message>>,
927 pub stops: Option<Element<'a, Message>>,
929 pub colour: Option<Element<'a, Message>>,
930 pub location: Option<Element<'a, Message>>,
931 pub notes: Option<Element<'a, Message>>,
932}
933
934impl<Message> std::fmt::Debug for Fields<'_, Message> {
935 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
936 f.debug_struct("Fields")
937 .field("title", &self.title.is_some())
938 .field("all_day", &self.all_day.is_some())
939 .field("starts", &self.starts.is_some())
940 .field("ends", &self.ends.is_some())
941 .field("repeat", &self.repeat.is_some())
942 .field("every", &self.every.is_some())
943 .field("stops", &self.stops.is_some())
944 .field("colour", &self.colour.is_some())
945 .field("location", &self.location.is_some())
946 .field("notes", &self.notes.is_some())
947 .finish()
948 }
949}
950
951impl<'a, Message> Editor<'a, Message> {
952 pub fn on_event(mut self, on_event: impl Fn(Event) -> Message + 'a) -> Self {
953 self.on_event = Some(Box::new(on_event));
954 self
955 }
956
957 pub fn on_submit(mut self, message: Message) -> Self {
960 self.on_submit = Some(message);
961 self
962 }
963
964 pub fn shortcuts(mut self, shortcuts: Shortcuts) -> Self {
967 self.shortcuts = shortcuts;
968 self
969 }
970
971 pub fn without(mut self, part: Part) -> Self {
973 if !self.without.contains(&part) {
974 self.without.push(part);
975 }
976 self
977 }
978
979 pub fn shows(&self, part: Part) -> bool {
981 !self.without.contains(&part)
982 }
983
984 pub fn read_only(mut self, read_only: bool) -> Self {
990 self.read_only = read_only;
991 self
992 }
993
994 pub fn is_read_only(&self) -> bool {
995 self.read_only
996 }
997}
998
999impl<'a, Message: Clone + 'a> Editor<'a, Message> {
1000 pub fn fields(self) -> Fields<'a, Message> {
1002 if self.read_only {
1003 return shown(self.state, &self.without);
1004 }
1005 let shows = |part| !self.without.contains(&part);
1006 let Editor {
1007 state,
1008 on_event,
1009 on_submit,
1010 shortcuts,
1011 ..
1012 } = self;
1013 let on_event: Handler<'a, Message> = on_event.map(std::rc::Rc::from);
1014 let repeating = state.repeats() != Repeats::Never;
1015
1016 let title = shows(Part::Title).then(|| {
1017 input("Add a title", state.title())
1018 .shortcuts(shortcuts)
1019 .on_input_maybe(
1020 on_event
1021 .clone()
1022 .map(|handler| move |title| handler(Event::Title(title))),
1023 )
1024 .on_submit_maybe(on_submit.clone())
1025 .into()
1026 });
1027 let all_day = shows(Part::AllDay).then(|| {
1029 checkbox(state.is_all_day())
1030 .label("All day")
1031 .on_toggle_maybe(
1032 on_event
1033 .clone()
1034 .map(|handler| move |on| handler(Event::AllDay(on))),
1035 )
1036 .into()
1037 });
1038 let repeat = shows(Part::Repeat).then(|| {
1039 let menu = select(&Repeats::ALL[..], Some(state.repeats()))
1040 .width(Length::Fill)
1041 .on_select_maybe(
1042 on_event
1043 .clone()
1044 .map(|handler| move |repeats| handler(Event::Repeats(repeats))),
1045 );
1046 named_menu(menu, "Repeats")
1047 });
1048 let colour = shows(Part::Colour).then(|| colour_menu(state, &on_event));
1049 let location = shows(Part::Location).then(|| {
1050 input("Add a location", state.location())
1051 .icon(lucide!(MapPin))
1052 .shortcuts(shortcuts)
1053 .on_input_maybe(
1054 on_event
1055 .clone()
1056 .map(|handler| move |location| handler(Event::Location(location))),
1057 )
1058 .on_submit_maybe(on_submit)
1059 .into()
1060 });
1061 let notes = shows(Part::Notes).then(|| {
1062 textarea(&state.notes)
1063 .id(notes_id())
1064 .placeholder("Add notes")
1065 .min_height(NOTES_HEIGHT)
1066 .shortcuts(shortcuts)
1067 .on_action_maybe(
1068 on_event
1069 .clone()
1070 .map(|handler| move |action| handler(Event::Notes(action))),
1071 )
1072 .into()
1073 });
1074
1075 Fields {
1076 title,
1077 all_day,
1078 starts: shows(Part::Starts).then(|| moment(state, Field::Start, "Starts", &on_event)),
1079 ends: shows(Part::Ends).then(|| moment(state, Field::End, "Ends", &on_event)),
1080 repeat,
1081 every: (shows(Part::Repeat) && repeating).then(|| every(state, shortcuts, &on_event)),
1082 stops: (shows(Part::Repeat) && repeating).then(|| stops(state, shortcuts, &on_event)),
1083 colour,
1084 location,
1085 notes,
1086 }
1087 }
1088}
1089
1090const READ_NAME_WIDTH: f32 = 64.0;
1092
1093fn value<'a, Message: 'a>(content: String) -> Element<'a, Message> {
1096 text(content)
1097 .size(text_size::SM)
1098 .width(Length::Fill)
1099 .style(|theme: &Theme| text::Style {
1100 color: Some(Tokens::of(theme).foreground),
1101 })
1102 .into()
1103}
1104
1105fn named<'a, Message: 'a>(
1108 label: &'a str,
1109 content: impl Into<Element<'a, Message>>,
1110) -> Element<'a, Message> {
1111 read_row(label, content, None)
1112}
1113
1114fn read_row<'a, Message: 'a>(
1117 label: &'a str,
1118 content: impl Into<Element<'a, Message>>,
1119 colour: Option<Color>,
1120) -> Element<'a, Message> {
1121 let name = text(label)
1122 .size(text_size::SM)
1123 .wrapping(text::Wrapping::None)
1124 .style(|theme: &Theme| text::Style {
1125 color: Some(Tokens::of(theme).muted_foreground),
1126 });
1127 let row: Element<'a, Message> = row![
1128 container(name).width(Length::Fixed(READ_NAME_WIDTH)),
1129 content.into()
1130 ]
1131 .spacing(space::SM)
1132 .into();
1133 #[cfg(feature = "icedwright")]
1134 let row = {
1135 let mut annotated = icedwright_probe::semantic(row)
1136 .role(icedwright_probe::role::Group)
1137 .name(label)
1138 .readonly(true)
1139 .component("iced_cube::calendar");
1140 if let Some(colour) = colour {
1141 annotated = annotated.prop("colour", super::parts::hex(colour));
1142 }
1143 annotated.into()
1144 };
1145 #[cfg(not(feature = "icedwright"))]
1146 let _ = colour;
1147 row
1148}
1149
1150fn day_text(date: Date) -> String {
1152 date.strftime("%a %-d %b %Y").to_string()
1153}
1154
1155fn span_text(state: &State) -> (String, Option<String>) {
1160 let (first, last) = (state.date(Field::Start), state.date(Field::End));
1161 let time = |field| TimeOfDay(state.time(field));
1162 match (state.is_all_day(), first == last) {
1163 (true, true) => (format!("{}, all day", day_text(first)), None),
1164 (true, false) => (
1165 format!("{}, all day", day_text(first)),
1166 Some(day_text(last)),
1167 ),
1168 (false, true) => (
1169 format!(
1170 "{}, {} to {}",
1171 day_text(first),
1172 time(Field::Start),
1173 time(Field::End)
1174 ),
1175 None,
1176 ),
1177 (false, false) => (
1178 format!("{}, {}", day_text(first), time(Field::Start)),
1179 Some(format!("{}, {}", day_text(last), time(Field::End))),
1180 ),
1181 }
1182}
1183
1184fn repeat_text(state: &State) -> Option<String> {
1187 let repeats = state.repeats();
1188 repeats.frequency()?;
1189 let interval = state.interval();
1190 let every = match interval {
1191 1 => repeats.to_string(),
1192 _ => format!("Every {interval} {}", repeats.unit(interval)),
1193 };
1194 Some(match state.stops() {
1195 Stops::Never => every,
1196 Stops::On => format!("{every}, until {}", day_text(state.until())),
1197 Stops::After if state.count() == 1 => format!("{every}, once"),
1198 Stops::After => format!("{every}, {} times", state.count()),
1199 })
1200}
1201
1202fn shown<'a, Message: 'a>(state: &'a State, without: &[Part]) -> Fields<'a, Message> {
1209 let shows = |part| !without.contains(&part);
1210 let title = read_title(state);
1211 let heading = || -> Element<'a, Message> {
1212 let heading = text(title)
1213 .size(text_size::LG)
1214 .font(theme::semibold())
1215 .width(Length::Fill)
1216 .style(|theme: &Theme| text::Style {
1217 color: Some(Tokens::of(theme).foreground),
1218 });
1219 #[cfg(feature = "icedwright")]
1220 let heading = icedwright_probe::semantic(heading)
1221 .role(icedwright_probe::role::Heading)
1222 .name(title)
1223 .component("iced_cube::calendar");
1224 heading.into()
1225 };
1226 let (start, end) = span_text(state);
1227 let (starts, ends) = match (shows(Part::Starts), shows(Part::Ends), end) {
1228 (true, false, _) | (true, true, None) => {
1230 let label = if shows(Part::Ends) { "When" } else { "Starts" };
1231 (Some(named(label, value(start))), None)
1232 }
1233 (true, true, Some(end)) => (
1234 Some(named("Starts", value(start))),
1235 Some(named("Ends", value(end))),
1236 ),
1237 (false, true, Some(end)) => (None, Some(named("Ends", value(end)))),
1238 (false, true, None) => (None, Some(named("When", value(start)))),
1239 (false, false, _) => (None, None),
1240 };
1241 let colour = chosen(state);
1242 let location = state.location().trim().to_owned();
1243 let notes = state.notes();
1244 Fields {
1245 title: shows(Part::Title).then(heading),
1246 all_day: None,
1247 starts,
1248 ends,
1249 repeat: repeat_text(state)
1250 .filter(|_| shows(Part::Repeat))
1251 .map(|repeat| named("Repeats", value(repeat))),
1252 every: None,
1253 stops: None,
1254 colour: shows(Part::Colour).then(|| {
1255 let shown = row![swatch(&colour), value(colour.to_string())]
1256 .spacing(space::SM)
1257 .align_y(Alignment::Center);
1258 read_row("Colour", shown, state.colour())
1259 }),
1260 location: (shows(Part::Location) && !location.is_empty())
1261 .then(|| named("Where", value(location))),
1262 notes: (shows(Part::Notes) && !notes.trim().is_empty())
1263 .then(|| named("Notes", value(notes))),
1264 }
1265}
1266
1267fn read_title(state: &State) -> &str {
1269 match state.title().trim() {
1270 "" => UNTITLED,
1271 title => title,
1272 }
1273}
1274
1275fn chosen(state: &State) -> Choice {
1277 match state.colour() {
1278 Some(colour) => custom(state, colour),
1279 None => Choice::Tone(state.tone()),
1280 }
1281}
1282
1283fn custom(state: &State, colour: Color) -> Choice {
1285 Choice::Custom(colour, state.colour_label().map(str::to_owned))
1286}
1287
1288fn swatch<'a, Message: 'a>(choice: &Choice) -> Element<'a, Message> {
1290 let paint = match choice {
1291 Choice::Tone(tone) => Paint::Tone(*tone),
1292 Choice::Custom(colour, _) => Paint::Colour(*colour),
1293 };
1294 theme::swatch(move |theme: &Theme| style::paint(&Tokens::of(theme), paint)).into()
1295}
1296
1297fn colour_menu<'a, Message: Clone + 'a>(
1301 state: &State,
1302 on_event: &Handler<'a, Message>,
1303) -> Element<'a, Message> {
1304 let colours: Vec<Choice> = state
1305 .own_colour()
1306 .map(|colour| custom(state, colour))
1307 .into_iter()
1308 .chain(Tone::ALL.into_iter().map(Choice::Tone))
1309 .collect();
1310 let menu = select(colours, Some(chosen(state)))
1311 .width(Length::Fill)
1312 .leading(|choice: &Choice| Some(swatch(choice)))
1313 .on_select_maybe(on_event.clone().map(|handler| {
1314 move |choice: Choice| {
1315 handler(match choice {
1316 Choice::Tone(tone) => Event::Tone(tone),
1317 Choice::Custom(colour, _) => Event::Colour(Some(colour)),
1318 })
1319 }
1320 }));
1321 named_menu(menu, "Colour")
1322}
1323
1324fn named_menu<'a, Message: 'a>(
1326 menu: impl Into<Element<'a, Message>>,
1327 name: &'static str,
1328) -> Element<'a, Message> {
1329 #[cfg(feature = "icedwright")]
1330 return icedwright_probe::semantic(menu)
1331 .name(name)
1332 .component("iced_cube::calendar")
1333 .into();
1334 #[cfg(not(feature = "icedwright"))]
1335 {
1336 let _ = name;
1337 menu.into()
1338 }
1339}
1340
1341type Handler<'a, Message> = Option<std::rc::Rc<dyn Fn(Event) -> Message + 'a>>;
1342
1343fn send<Message>(handler: &Handler<'_, Message>, event: Event) -> Option<Message> {
1344 handler.as_ref().map(|handler| handler(event))
1345}
1346
1347impl<'a, Message: Clone + 'a> From<Editor<'a, Message>> for Element<'a, Message> {
1348 fn from(editor: Editor<'a, Message>) -> Self {
1349 if editor.read_only {
1350 #[cfg(feature = "icedwright")]
1351 let title = read_title(editor.state);
1352 let Fields {
1353 title: heading,
1354 starts,
1355 ends,
1356 repeat,
1357 colour,
1358 location,
1359 notes,
1360 ..
1361 } = editor.fields();
1362 let form = Column::with_children(
1363 [heading, starts, ends, repeat, colour, location, notes]
1364 .into_iter()
1365 .flatten(),
1366 )
1367 .spacing(space::MD)
1368 .width(Length::Fill);
1369 #[cfg(feature = "icedwright")]
1371 let form = icedwright_probe::semantic(form)
1372 .role(icedwright_probe::role::Group)
1373 .name(title)
1374 .readonly(true)
1375 .component("iced_cube::calendar");
1376 return form.into();
1377 }
1378 let Fields {
1379 title,
1380 all_day,
1381 starts,
1382 ends,
1383 repeat,
1384 every,
1385 stops,
1386 colour,
1387 location,
1388 notes,
1389 } = editor.fields();
1390
1391 let menus: Vec<Element<'a, Message>> = [
1392 repeat.map(|menu| container(menu).width(Length::FillPortion(3)).into()),
1393 colour.map(|menu| container(menu).width(Length::FillPortion(2)).into()),
1394 ]
1395 .into_iter()
1396 .flatten()
1397 .collect();
1398 let menus =
1399 (!menus.is_empty()).then(|| Row::with_children(menus).spacing(space::SM).into());
1400
1401 Column::with_children(
1402 [
1403 title, all_day, starts, ends, menus, every, stops, location, notes,
1404 ]
1405 .into_iter()
1406 .flatten(),
1407 )
1408 .spacing(space::MD)
1409 .width(Length::Fill)
1410 .into()
1411 }
1412}
1413
1414fn name<'a, Message: 'a>(name: &'a str) -> Element<'a, Message> {
1416 let label = text(name)
1417 .size(text_size::SM)
1418 .wrapping(text::Wrapping::None)
1419 .style(|theme: &Theme| text::Style {
1420 color: Some(Tokens::of(theme).muted_foreground),
1421 });
1422 container(label).width(Length::Fixed(NAME_WIDTH)).into()
1423}
1424
1425fn number_field<'a, Message: Clone + 'a>(
1427 value: &str,
1428 shortcuts: Shortcuts,
1429 on_event: &Handler<'a, Message>,
1430 event: fn(String) -> Event,
1431) -> Element<'a, Message> {
1432 input("1", value)
1433 .width(NUMBER_WIDTH)
1434 .shortcuts(shortcuts)
1435 .on_input_maybe(
1436 on_event
1437 .clone()
1438 .map(|handler| move |text| handler(event(text))),
1439 )
1440 .into()
1441}
1442
1443fn every<'a, Message: Clone + 'a>(
1445 state: &'a State,
1446 shortcuts: Shortcuts,
1447 on_event: &Handler<'a, Message>,
1448) -> Element<'a, Message> {
1449 let unit = text(state.repeats().unit(state.interval()))
1450 .size(text_size::SM)
1451 .wrapping(text::Wrapping::None);
1452 row![
1453 name("Every"),
1454 number_field(&state.interval, shortcuts, on_event, Event::Interval),
1455 unit,
1456 ]
1457 .spacing(space::SM)
1458 .align_y(Alignment::Center)
1459 .into()
1460}
1461
1462fn stops<'a, Message: Clone + 'a>(
1464 state: &'a State,
1465 shortcuts: Shortcuts,
1466 on_event: &Handler<'a, Message>,
1467) -> Element<'a, Message> {
1468 let handler = on_event.clone();
1469 let choice = select(&Stops::ALL[..], Some(state.stops()))
1470 .width(Length::Fill)
1471 .on_select_maybe(handler.map(|handler| move |stops| handler(Event::Stops(stops))));
1472 let mut controls = Row::new()
1473 .spacing(space::SM)
1474 .align_y(Alignment::Center)
1475 .push(name("Stops"))
1476 .push(choice);
1477 match state.stops() {
1478 Stops::Never => {}
1479 Stops::On => controls = controls.push(date_field(state, Target::Until, on_event)),
1480 Stops::After => {
1481 let times = text(if state.count() == 1 { "time" } else { "times" })
1482 .size(text_size::SM)
1483 .wrapping(text::Wrapping::None);
1484 controls = controls
1485 .push(number_field(
1486 &state.count,
1487 shortcuts,
1488 on_event,
1489 Event::Count,
1490 ))
1491 .push(times);
1492 }
1493 }
1494 controls.into()
1495}
1496
1497fn moment<'a, Message: Clone + 'a>(
1500 state: &'a State,
1501 field: Field,
1502 label: &'a str,
1503 on_event: &Handler<'a, Message>,
1504) -> Element<'a, Message> {
1505 let mut controls = Row::new()
1506 .spacing(space::SM)
1507 .align_y(Alignment::Center)
1508 .push(name(label))
1509 .push(date_field(state, Target::Field(field), on_event));
1510 if !state.is_all_day() {
1511 let handler = on_event.clone();
1512 controls = controls.push(
1513 select(state.times(field), Some(TimeOfDay(state.time(field))))
1514 .width(TIME_WIDTH)
1515 .searchable(true)
1516 .search_placeholder("hh:mm")
1517 .on_custom({
1518 let handler = handler.clone();
1519 move |text| {
1520 let handler = handler.as_ref()?;
1521 let time = TimeOfDay::parse(&text)?;
1522 Some(handler(Event::Time(field, time.0)))
1523 }
1524 })
1525 .on_select_maybe(
1526 handler
1527 .map(|handler| move |time: TimeOfDay| handler(Event::Time(field, time.0))),
1528 ),
1529 );
1530 }
1531 controls.into()
1532}
1533
1534fn date_field<'a, Message: Clone + 'a>(
1536 state: &'a State,
1537 target: Target,
1538 on_event: &Handler<'a, Message>,
1539) -> Element<'a, Message> {
1540 let open = state.picker.filter(|picker| picker.target == target);
1541 let toggle = match target {
1542 Target::Field(field) => Event::Picker(open.is_none().then_some(field)),
1543 Target::Until => Event::UntilPicker(open.is_none()),
1544 };
1545 let date = state.target_date(target);
1546 let trigger = button(date.strftime("%a %-d %b %Y").to_string())
1547 .variant(button::Variant::Outline)
1548 .icon(lucide!(Calendar))
1549 .align_x(Alignment::Start)
1550 .width(Length::Fill)
1551 .on_press_maybe(send(on_event, toggle));
1552
1553 let content: Element<'a, Message> = match open {
1554 Some(picker) => month_picker(state, picker, on_event),
1555 None => Space::new().into(),
1556 };
1557 let mut date = popover(trigger, content)
1558 .open(open.is_some())
1559 .align(Align::Start)
1560 .width(Length::Shrink)
1561 .padding(space::MD);
1562 if let Some(close) = send(on_event, Event::Picker(None)) {
1563 date = date.on_dismiss(close);
1564 }
1565 container(date).width(Length::Fill).clip(true).into()
1568}
1569
1570fn month_picker<'a, Message: Clone + 'a>(
1572 state: &State,
1573 picker: Picker,
1574 on_event: &Handler<'a, Message>,
1575) -> Element<'a, Message> {
1576 let step = |glyph, label: &'static str, months: i32| {
1577 icon_button(glyph)
1578 .label(label)
1579 .variant(icon_button::Variant::Ghost)
1580 .size(Size::Sm)
1581 .on_press_maybe(send(on_event, Event::PickerMonth(months)))
1582 };
1583 let name = text(picker.month.strftime("%B %Y").to_string())
1584 .size(text_size::SM)
1585 .font(theme::semibold())
1586 .wrapping(text::Wrapping::None);
1587 let header = row![
1588 step(lucide!(ChevronLeft), "Previous month", -1),
1589 container(name).center_x(Length::Fill),
1590 step(lucide!(ChevronRight), "Next month", 1),
1591 ]
1592 .align_y(Alignment::Center);
1593
1594 let chosen = state.target_date(picker.target);
1595 let target = picker.target;
1596 let pick = on_event.clone().map(|handler| {
1597 move |date: Date| match target {
1598 Target::Field(field) => handler(Event::Date(field, date)),
1599 Target::Until => handler(Event::Until(date)),
1600 }
1601 });
1602 let grid = month_grid(picker.month, state.week_start, Some(chosen), pick);
1603 column![header, grid]
1604 .spacing(space::SM)
1605 .width(Length::Fixed(7.0 * CELL))
1606 .into()
1607}
1608
1609pub fn month_grid<'a, Message: Clone + 'a>(
1614 month: Date,
1615 week_start: Weekday,
1616 chosen: Option<Date>,
1617 on_pick: Option<impl Fn(Date) -> Message + 'a>,
1618) -> Element<'a, Message> {
1619 let weeks = month_weeks(month, week_start);
1620 let on_pick = on_pick.map(std::rc::Rc::new);
1621 let mut grid = Column::new().spacing(2.0);
1622 if let Some(week) = weeks.first() {
1623 grid = grid.push(Row::with_children(week.iter().map(|date| {
1624 container(text(weekday_label(*date, true)).size(text_size::XS).style(
1625 |theme: &Theme| text::Style {
1626 color: Some(Tokens::of(theme).muted_foreground),
1627 },
1628 ))
1629 .center(Length::Fixed(CELL))
1630 .into()
1631 })));
1632 }
1633 for week in &weeks {
1634 grid = grid.push(Row::with_children(week.iter().map(|date| {
1635 if date.month() != month.month() {
1636 return Space::new()
1637 .width(Length::Fixed(CELL))
1638 .height(Length::Fixed(CELL))
1639 .into();
1640 }
1641 let day = style::Day {
1642 today: false,
1643 selected: Some(*date) == chosen,
1644 in_month: true,
1645 };
1646 let number = text(date.day().to_string())
1647 .size(text_size::XS)
1648 .wrapping(text::Wrapping::None);
1649 widget::button(container(number).center(Length::Fill))
1650 .width(Length::Fixed(CELL))
1651 .height(Length::Fixed(CELL))
1652 .padding(0)
1653 .on_press_maybe(on_pick.as_ref().map(|pick| pick(*date)))
1654 .style(move |theme, status: Status| {
1655 style::year_day(&Tokens::of(theme), day, status)
1656 })
1657 .into()
1658 })));
1659 }
1660 grid.into()
1661}
1662
1663#[cfg(test)]
1664mod tests {
1665 use super::*;
1666 use jiff::civil::date;
1667
1668 const UTC: TimeZone = TimeZone::UTC;
1669
1670 fn at(hour: u16, minute: u16) -> Timestamp {
1672 instant_at(date(2026, 6, 19), hour * 60 + minute, &UTC)
1673 }
1674
1675 fn timed() -> State {
1676 State::new(
1677 &Draft {
1678 when: When::timed(at(11, 0), at(12, 30)),
1679 },
1680 &UTC,
1681 )
1682 }
1683
1684 fn whole_day() -> State {
1685 State::new(
1686 &Draft {
1687 when: When::day(date(2026, 6, 19)),
1688 },
1689 &UTC,
1690 )
1691 }
1692
1693 #[test]
1694 fn a_new_form_starts_from_the_draft() {
1695 let form = timed();
1696 assert!(form.is_new());
1697 assert_eq!(form.id(), None);
1698 assert_eq!(form.title(), "");
1699 assert!(!form.is_all_day());
1700 assert_eq!(form.date(Field::Start), date(2026, 6, 19));
1701 assert_eq!((form.time(Field::Start), form.time(Field::End)), (660, 750));
1702 assert_eq!(form.repeats(), Repeats::Never);
1703 assert_eq!(form.tone(), Tone::Primary);
1704 assert_eq!(form.picker(), None);
1705 assert_eq!(form.when(), When::timed(at(11, 0), at(12, 30)));
1706
1707 let form = whole_day();
1708 assert!(form.is_all_day());
1709 assert_eq!(form.when(), When::day(date(2026, 6, 19)));
1710 }
1711
1712 #[test]
1713 fn editing_starts_from_the_entry_and_keeps_what_the_form_does_not_show() {
1714 let rule = Repeat::weekly().interval(2);
1715 let entry = Entry::new(EntryId(4), "Review", at(15, 0), at(16, 0))
1716 .tone(Tone::Success)
1717 .tag("work")
1718 .repeat(rule)
1719 .location("Room 4")
1720 .notes("Bring the plan\nand the figures");
1721 let mut form = State::edit(&entry, &UTC);
1722 assert_eq!(form.id(), Some(EntryId(4)));
1723 assert!(!form.is_new());
1724 assert_eq!(form.title(), "Review");
1725 assert_eq!(form.tone(), Tone::Success);
1726 assert_eq!(form.repeats(), Repeats::Weekly);
1727 assert_eq!(form.interval(), 2);
1728 assert_eq!(form.stops(), Stops::Never);
1729 assert_eq!(form.location(), "Room 4");
1730 assert_eq!(form.notes(), "Bring the plan\nand the figures");
1731 assert_eq!(form.entry(EntryId(99)), entry, "unchanged, with its own id");
1732
1733 form.update(Event::Title(String::from("Retro")));
1734 let saved = form.entry(EntryId(99));
1735 assert_eq!(saved.id(), EntryId(4));
1736 assert_eq!(saved.title(), "Retro");
1737 assert_eq!(saved.tag_of(), Some("work"));
1738 assert_eq!(saved.repeat_of(), Some(rule));
1739 assert_eq!(saved.location_of(), Some("Room 4"));
1740 }
1741
1742 #[test]
1743 fn saving_keeps_the_icon_emphasis_and_permissions_the_form_does_not_show() {
1744 let entry = Entry::new(EntryId(4), "Invitation", at(15, 0), at(16, 0))
1745 .repeat(Repeat::daily())
1746 .icon(crate::lucide!(Mail))
1747 .icon_label("Invitation")
1748 .emphasis(crate::data::calendar::Emphasis::Outlined)
1749 .movable(false)
1750 .removable(false);
1751 let mut form = State::edit(&entry, &UTC);
1752 form.update(Event::Title(String::from("Accepted")));
1753 form.update(Event::Repeats(Repeats::Never));
1754 let saved = form.entry(EntryId(99));
1755 assert_eq!(saved.title(), "Accepted");
1756 assert_eq!(saved.repeat_of(), None, "the form's choice wins");
1757 assert_eq!(saved.icon_of(), entry.icon_of());
1758 assert_eq!(saved.icon_label_of(), Some("Invitation"));
1759 assert_eq!(saved.emphasis_of(), entry.emphasis_of());
1760 assert!(!saved.is_movable() && !saved.is_removable());
1761
1762 let locked = State::edit(&entry.clone().locked(true), &UTC).entry(EntryId(99));
1763 assert!(locked.is_locked());
1764 }
1765
1766 #[test]
1767 fn a_blank_title_is_saved_as_untitled_and_a_new_entry_takes_the_id_given() {
1768 let mut form = timed();
1769 form.update(Event::Title(String::from(" ")));
1770 let entry = form.entry(EntryId(7));
1771 assert_eq!(entry.id(), EntryId(7));
1772 assert_eq!(entry.title(), UNTITLED);
1773 form.update(Event::Title(String::from(" Retro ")));
1774 assert_eq!(form.entry(EntryId(7)).title(), "Retro");
1775 }
1776
1777 #[test]
1778 fn moving_the_start_keeps_the_length() {
1779 let mut form = timed();
1780 form.update(Event::Time(Field::Start, 14 * 60));
1781 assert_eq!((form.time(Field::Start), form.time(Field::End)), (840, 930));
1782
1783 form.update(Event::Date(Field::Start, date(2026, 6, 22)));
1784 assert_eq!(form.date(Field::End), date(2026, 6, 22));
1785 assert_eq!(
1786 form.when(),
1787 When::timed(
1788 instant_at(date(2026, 6, 22), 840, &UTC),
1789 instant_at(date(2026, 6, 22), 930, &UTC)
1790 )
1791 );
1792
1793 form.update(Event::Time(Field::Start, 23 * 60));
1795 assert_eq!(form.date(Field::End), date(2026, 6, 23));
1796 assert_eq!(form.time(Field::End), 30);
1797 }
1798
1799 #[test]
1800 fn the_end_never_goes_before_the_start() {
1801 let mut form = timed();
1802 form.update(Event::Time(Field::End, 9 * 60));
1804 assert_eq!(form.date(Field::End), date(2026, 6, 20));
1805 assert_eq!(form.time(Field::End), 540);
1806
1807 form.update(Event::Date(Field::End, date(2026, 6, 1)));
1809 assert_eq!(form.date(Field::End), date(2026, 6, 19));
1810 assert_eq!(form.time(Field::End), 660 + TIME_STEP);
1811
1812 let mut form = timed();
1815 form.update(Event::Time(Field::End, 660));
1816 assert_eq!(
1817 (form.date(Field::End), form.time(Field::End)),
1818 (date(2026, 6, 20), 660)
1819 );
1820
1821 let late = at(23, 45);
1823 let mut form = State::new(
1824 &Draft {
1825 when: When::timed(late, late),
1826 },
1827 &UTC,
1828 );
1829 form.update(Event::Time(Field::Start, 23 * 60 + 45));
1830 assert_eq!(
1831 (form.date(Field::End), form.time(Field::End)),
1832 (date(2026, 6, 20), 0)
1833 );
1834 }
1835
1836 #[test]
1837 fn an_end_put_on_the_next_day_comes_back_when_a_later_time_is_typed() {
1838 let mut form = State::new(
1839 &Draft {
1840 when: When::timed(at(9, 0), at(10, 0)),
1841 },
1842 &UTC,
1843 );
1844 form.update(Event::Time(Field::End, 8 * 60));
1845 assert_eq!(
1846 form.date(Field::End),
1847 date(2026, 6, 20),
1848 "08:00 is overnight"
1849 );
1850 assert_eq!(form.times(Field::End)[0], TimeOfDay(9 * 60 + TIME_STEP));
1851 form.update(Event::Time(Field::End, 11 * 60));
1852 assert_eq!(
1853 form.when(),
1854 When::timed(at(9, 0), at(11, 0)),
1855 "not 26 hours"
1856 );
1857
1858 form.update(Event::Date(Field::End, date(2026, 6, 20)));
1860 form.update(Event::Time(Field::End, 12 * 60));
1861 assert_eq!(form.date(Field::End), date(2026, 6, 20));
1862
1863 let mut form = timed();
1865 form.update(Event::Time(Field::End, 9 * 60));
1866 form.update(Event::Time(Field::Start, 10 * 60));
1867 form.update(Event::Time(Field::End, 12 * 60));
1868 assert_eq!(
1869 (form.date(Field::End), form.time(Field::End)),
1870 (date(2026, 6, 19), 720)
1871 );
1872 }
1873
1874 #[test]
1875 fn whole_days_end_on_the_day_a_midnight_end_closes() {
1876 let mut form = State::new(
1877 &Draft {
1878 when: When::timed(at(23, 0), at(23, 0) + jiff::SignedDuration::from_hours(1)),
1879 },
1880 &UTC,
1881 );
1882 form.update(Event::AllDay(true));
1883 assert_eq!(
1884 form.when(),
1885 When::day(date(2026, 6, 19)),
1886 "one day, not two"
1887 );
1888 form.update(Event::AllDay(false));
1889 assert_eq!(
1890 form.when(),
1891 When::timed(at(23, 0), at(23, 0) + jiff::SignedDuration::from_hours(1)),
1892 "and back"
1893 );
1894 form.update(Event::AllDay(false));
1895 assert_eq!(form.date(Field::End), date(2026, 6, 20), "no change twice");
1896 }
1897
1898 #[test]
1899 fn editing_the_title_alone_keeps_the_notes_and_the_seconds() {
1900 let start = at(9, 0) + jiff::SignedDuration::from_secs(30);
1901 let end = at(10, 0) + jiff::SignedDuration::from_secs(15);
1902 let notes = " Agenda first\nthen figures\n";
1903 let entry = Entry::new(EntryId(2), "Review", start, end).notes(notes);
1904 let mut form = State::edit(&entry, &UTC);
1905 form.update(Event::Title(String::from("Review two")));
1906 assert_eq!(form.notes(), notes);
1907 let saved = form.entry(EntryId(9));
1908 assert_eq!(saved.when(), When::timed(start, end));
1909 assert_eq!(saved.notes_of(), Some(notes));
1910
1911 form.update(Event::Time(Field::End, 11 * 60));
1913 assert_eq!(form.when(), When::timed(start, at(11, 0)));
1914
1915 form.update(Event::Notes(Action::Edit(
1917 iced::widget::text_editor::Edit::Insert('x'),
1918 )));
1919 assert!(!form.notes().starts_with(' '));
1920 let mut form = State::edit(&entry, &UTC);
1922 form.update(Event::Notes(Action::Move(
1923 iced::widget::text_editor::Motion::Down,
1924 )));
1925 assert_eq!(form.notes(), notes);
1926 }
1927
1928 #[test]
1929 fn times_out_of_range_are_kept_within_the_day() {
1930 let mut form = timed();
1931 form.update(Event::Time(Field::Start, 5000));
1932 assert_eq!(form.time(Field::Start), DAY_MINUTES - 1);
1933 }
1934
1935 #[test]
1936 fn all_day_keeps_the_dates_and_brings_the_times_back() {
1937 let mut form = timed();
1938 form.update(Event::AllDay(true));
1939 assert_eq!(form.when(), When::day(date(2026, 6, 19)));
1940 form.update(Event::Date(Field::End, date(2026, 6, 21)));
1941 assert_eq!(
1942 form.when(),
1943 When::all_day(date(2026, 6, 19), date(2026, 6, 21))
1944 );
1945 form.update(Event::Date(Field::End, date(2026, 6, 1)));
1946 assert_eq!(form.date(Field::End), date(2026, 6, 19), "same day is fine");
1947 form.update(Event::AllDay(false));
1948 assert_eq!((form.time(Field::Start), form.time(Field::End)), (660, 750));
1949
1950 let mut form = whole_day();
1952 form.update(Event::AllDay(false));
1953 assert_eq!((form.time(Field::Start), form.time(Field::End)), (540, 600));
1954 }
1955
1956 #[test]
1957 fn repeat_and_colour_reach_the_entry() {
1958 let mut form = timed();
1959 form.update(Event::Repeats(Repeats::Weekly));
1960 form.update(Event::Tone(Tone::Warning));
1961 let entry = form.entry(EntryId(1));
1962 assert_eq!(entry.repeat_of(), Some(Repeat::weekly()));
1963 assert_eq!(entry.tone_of(), Tone::Warning);
1964 form.update(Event::Repeats(Repeats::Never));
1965 assert_eq!(form.entry(EntryId(1)).repeat_of(), None);
1966 }
1967
1968 #[test]
1969 fn a_colour_of_the_entry_own_is_kept_until_a_tone_is_picked() {
1970 let teal = Color::from_rgb8(0x0f, 0x76, 0x6e);
1971 let entry = Entry::new(EntryId(3), "Shared", at(9, 0), at(10, 0))
1972 .tone(Tone::Success)
1973 .colour(teal);
1974 let mut form = State::edit(&entry, &UTC);
1975 assert_eq!(form.colour(), Some(teal));
1976 assert_eq!(chosen(&form), Choice::Custom(teal, None));
1977 assert_eq!(chosen(&form).to_string(), CUSTOM_COLOUR);
1978 assert_eq!(form.entry(EntryId(9)), entry);
1979
1980 form.update(Event::Colour(Some(teal)));
1981 assert_eq!(form.colour(), Some(teal));
1982 form.update(Event::Tone(Tone::Warning));
1983 assert_eq!(form.colour(), None);
1984 assert_eq!(chosen(&form), Choice::Tone(Tone::Warning));
1985 assert_eq!(form.own_colour(), Some(teal), "still offered in the menu");
1986 let saved = form.entry(EntryId(9));
1987 assert_eq!((saved.colour_of(), saved.tone_of()), (None, Tone::Warning));
1988
1989 let named = State::edit(&entry, &UTC).with_colour_label(" Team ");
1991 assert_eq!(named.colour_label(), Some("Team"));
1992 assert_eq!(chosen(&named).to_string(), "Team");
1993 assert_eq!(named.with_colour_label(" ").colour_label(), None);
1994
1995 form.update(Event::Colour(Some(teal)));
1996 assert_eq!(form.entry(EntryId(9)).colour_of(), Some(teal));
1997 form.update(Event::Colour(None));
1998 assert_eq!(form.entry(EntryId(9)).colour_of(), None);
1999 assert_eq!(
2000 State::new(&Draft { when: entry.when() }, &UTC).colour(),
2001 None
2002 );
2003 }
2004
2005 #[test]
2006 fn every_repeat_choice_has_a_name_and_round_trips() {
2007 for choice in Repeats::ALL {
2008 assert!(!choice.to_string().is_empty());
2009 assert_eq!(Repeats::of(choice.frequency()), choice);
2010 }
2011 assert_eq!(Repeats::default(), Repeats::Never);
2012 assert_eq!(Repeats::Never.frequency(), None);
2013 let units: Vec<_> = Repeats::ALL
2014 .iter()
2015 .map(|choice| (choice.unit(1), choice.unit(2)))
2016 .collect();
2017 assert_eq!(
2018 units,
2019 vec![
2020 ("", ""),
2021 ("day", "days"),
2022 ("week", "weeks"),
2023 ("month", "months"),
2024 ("year", "years")
2025 ]
2026 );
2027 let names: Vec<_> = Stops::ALL.iter().map(Stops::to_string).collect();
2028 assert_eq!(names, vec!["Never", "On a date", "After"]);
2029 assert_eq!(Stops::default(), Stops::Never);
2030 }
2031
2032 #[test]
2033 fn a_repeat_takes_its_interval_and_its_end_from_the_form() {
2034 let mut form = timed();
2035 assert_eq!(form.repeat(), None);
2036 assert_eq!((form.interval(), form.count()), (1, DEFAULT_COUNT));
2037 assert_eq!(form.until(), date(2026, 7, 19), "a month after the start");
2038
2039 form.update(Event::Repeats(Repeats::Weekly));
2040 assert_eq!(form.repeat(), Some(Repeat::weekly()));
2041 form.update(Event::Interval(String::from("2")));
2042 assert_eq!(form.repeat(), Some(Repeat::weekly().interval(2)));
2043
2044 form.update(Event::Stops(Stops::After));
2045 form.update(Event::Count(String::from("6")));
2046 assert_eq!(form.repeat(), Some(Repeat::weekly().interval(2).count(6)));
2047
2048 form.update(Event::Stops(Stops::On));
2049 form.update(Event::Until(date(2026, 9, 1)));
2050 let rule = Repeat::weekly().interval(2).until(date(2026, 9, 1));
2051 assert_eq!(form.repeat(), Some(rule));
2052 assert_eq!(form.entry(EntryId(1)).repeat_of(), Some(rule));
2053
2054 form.update(Event::Repeats(Repeats::Never));
2056 assert_eq!(form.repeat(), None);
2057 form.update(Event::Repeats(Repeats::Monthly));
2058 assert_eq!(
2059 form.repeat(),
2060 Some(Repeat::monthly().interval(2).until(date(2026, 9, 1)))
2061 );
2062 }
2063
2064 #[test]
2065 fn number_fields_keep_digits_and_count_blank_as_one() {
2066 let mut form = timed();
2067 form.update(Event::Repeats(Repeats::Daily));
2068 form.update(Event::Interval(String::from("a1b2c3d4")));
2069 assert_eq!(form.interval(), 123, "three digits at most");
2070 form.update(Event::Interval(String::new()));
2071 assert_eq!(form.interval(), 1, "blank while typing");
2072 form.update(Event::Interval(String::from("0")));
2073 assert_eq!(form.interval_text(), "", "a 0 is never shown");
2074 assert_eq!(form.interval(), 1);
2075 assert_eq!(form.repeat(), Some(Repeat::daily()));
2076 form.update(Event::Interval(String::from("05")));
2077 assert_eq!(form.interval_text(), "5");
2078 form.update(Event::Interval(String::from("10")));
2079 assert_eq!(form.interval(), 10);
2080
2081 form.update(Event::Stops(Stops::After));
2082 form.update(Event::Count(String::from("-5 times")));
2083 assert_eq!(form.count(), 5);
2084 form.update(Event::Count(String::from("0")));
2085 assert_eq!(form.count(), 1);
2086 }
2087
2088 #[test]
2089 fn an_entry_ending_on_a_date_or_after_a_count_fills_the_form() {
2090 let base = Entry::new(EntryId(4), "Review", at(15, 0), at(16, 0));
2091 let on = base
2092 .clone()
2093 .repeat(Repeat::monthly().until(date(2026, 12, 19)));
2094 let form = State::edit(&on, &UTC);
2095 assert_eq!(form.repeats(), Repeats::Monthly);
2096 assert_eq!(form.stops(), Stops::On);
2097 assert_eq!(form.until(), date(2026, 12, 19));
2098 assert_eq!(form.entry(EntryId(9)), on);
2099
2100 let after = base.repeat(Repeat::yearly().interval(4).count(3));
2101 let form = State::edit(&after, &UTC);
2102 assert_eq!(form.repeats(), Repeats::Yearly);
2103 assert_eq!(form.stops(), Stops::After);
2104 assert_eq!((form.interval(), form.count()), (4, 3));
2105 assert_eq!(form.entry(EntryId(9)), after);
2106 }
2107
2108 #[test]
2109 fn the_last_date_of_a_repeat_stays_on_or_after_the_start() {
2110 let mut form = timed();
2111 form.update(Event::Repeats(Repeats::Daily));
2112 form.update(Event::Stops(Stops::On));
2113 form.update(Event::Until(date(2026, 6, 1)));
2114 assert_eq!(form.until(), date(2026, 6, 19), "not before the start");
2115
2116 form.update(Event::Until(date(2026, 6, 25)));
2117 form.update(Event::Date(Field::Start, date(2026, 8, 3)));
2118 assert_eq!(form.until(), date(2026, 8, 3), "carried by the start");
2119 }
2120
2121 #[test]
2122 fn the_picker_for_the_last_date_opens_turns_and_closes() {
2123 let mut form = timed();
2124 form.update(Event::Repeats(Repeats::Daily));
2125 form.update(Event::Stops(Stops::On));
2126 form.update(Event::UntilPicker(true));
2127 assert!(form.is_picking_until());
2128 assert_eq!(form.picker(), None, "not the start's or the end's");
2129 assert_eq!(form.picker.map(|p| p.month), Some(date(2026, 7, 1)));
2130 form.update(Event::PickerMonth(2));
2131 assert_eq!(form.picker.map(|p| p.month), Some(date(2026, 9, 1)));
2132 form.update(Event::Until(date(2026, 9, 14)));
2133 assert!(!form.is_picking_until());
2134 assert_eq!(form.until(), date(2026, 9, 14));
2135
2136 form.update(Event::UntilPicker(true));
2138 form.update(Event::Picker(Some(Field::Start)));
2139 assert!(!form.is_picking_until());
2140 assert_eq!(form.picker(), Some(Field::Start));
2141 form.update(Event::UntilPicker(true));
2142 form.update(Event::UntilPicker(false));
2143 assert!(!form.is_picking_until());
2144 form.update(Event::UntilPicker(true));
2145 form.update(Event::Stops(Stops::Never));
2146 assert!(!form.is_picking_until());
2147 form.update(Event::Stops(Stops::On));
2148 form.update(Event::UntilPicker(true));
2149 form.update(Event::Repeats(Repeats::Never));
2150 assert!(!form.is_picking_until());
2151 form.update(Event::UntilPicker(true));
2152 form.update(Event::Picker(None));
2153 assert!(!form.is_picking_until());
2154 }
2155
2156 #[test]
2157 fn location_and_notes_reach_the_entry() {
2158 let mut form = timed();
2159 assert_eq!(form.location(), "");
2160 assert_eq!(form.notes(), "");
2161 let blank = form.entry(EntryId(1));
2162 assert_eq!((blank.location_of(), blank.notes_of()), (None, None));
2163
2164 form.update(Event::Location(String::from(" Room 4 ")));
2165 for letter in "Agenda".chars() {
2166 form.update(Event::Notes(Action::Edit(
2167 iced::widget::text_editor::Edit::Insert(letter),
2168 )));
2169 }
2170 form.update(Event::Notes(Action::Edit(
2171 iced::widget::text_editor::Edit::Enter,
2172 )));
2173 assert_eq!(form.notes(), "Agenda", "space at the ends is dropped");
2174 let entry = form.entry(EntryId(1));
2175 assert_eq!(entry.location_of(), Some("Room 4"));
2176 assert_eq!(entry.notes_of(), Some("Agenda"));
2177 }
2178
2179 #[test]
2180 fn typed_times_are_read_with_or_without_a_colon() {
2181 assert_eq!(TimeOfDay::parse("09:40"), Some(TimeOfDay(580)));
2182 assert_eq!(TimeOfDay::parse(" 9:40 "), Some(TimeOfDay(580)));
2183 assert_eq!(TimeOfDay::parse("940"), Some(TimeOfDay(580)));
2184 assert_eq!(TimeOfDay::parse("2359"), Some(TimeOfDay(1439)));
2185 assert_eq!(TimeOfDay::parse("0:00"), Some(TimeOfDay(0)));
2186 assert_eq!(TimeOfDay::parse("9"), Some(TimeOfDay(540)), "a bare hour");
2187 assert_eq!(TimeOfDay::parse("17"), Some(TimeOfDay(1020)));
2188 assert_eq!(TimeOfDay::parse("09.05"), Some(TimeOfDay(545)));
2189 assert_eq!(TimeOfDay::parse("9.05"), Some(TimeOfDay(545)));
2190 for bad in [
2191 "", "24", "24:00", "12:60", "9:4", "123:00", "ab:cd", "€12", "12:3x", ":30", "9:",
2192 "9.", "9:30.5", ".",
2193 ] {
2194 assert_eq!(TimeOfDay::parse(bad), None, "{bad:?}");
2195 }
2196 }
2197
2198 #[test]
2199 fn times_and_colours_have_names() {
2200 assert_eq!(TimeOfDay(0).to_string(), "00:00");
2201 assert_eq!(TimeOfDay(570).to_string(), "09:30");
2202 let all = TimeOfDay::all();
2203 assert_eq!(all.len(), 96);
2204 assert_eq!(all.last(), Some(&TimeOfDay(1425)));
2205
2206 let from_ten = TimeOfDay::from(607);
2208 assert_eq!(from_ten.len(), 96);
2209 assert_eq!(from_ten.first(), Some(&TimeOfDay(600)));
2210 assert_eq!(from_ten.last(), Some(&TimeOfDay(585)));
2211 assert_eq!(TimeOfDay::from(0), all);
2212 assert_eq!(TimeOfDay::from(9999).first(), Some(&TimeOfDay(1425)));
2213
2214 let form = timed();
2217 assert_eq!(form.times(Field::Start), all);
2218 assert_eq!(form.times(Field::End).first(), Some(&TimeOfDay(675)));
2219 assert_eq!(form.times(Field::End).len(), 96);
2220 let mut overnight = timed();
2221 overnight.update(Event::Date(Field::End, date(2026, 6, 20)));
2222 assert_eq!(overnight.times(Field::End), all);
2223 let names: Vec<_> = Tone::ALL
2224 .iter()
2225 .map(|tone| Colour(*tone).to_string())
2226 .collect();
2227 assert_eq!(names, vec!["Default", "Neutral", "Green", "Amber", "Red"]);
2228 }
2229
2230 #[test]
2231 fn the_date_picker_opens_on_the_field_month_and_closes_on_a_choice() {
2232 let mut form = timed().with_week_start(Weekday::Sunday);
2233 form.update(Event::Picker(Some(Field::End)));
2234 assert_eq!(form.picker(), Some(Field::End));
2235 assert_eq!(form.picker.map(|p| p.month), Some(date(2026, 6, 1)));
2236
2237 form.update(Event::PickerMonth(1));
2238 form.update(Event::PickerMonth(1));
2239 assert_eq!(form.picker.map(|p| p.month), Some(date(2026, 8, 1)));
2240 form.update(Event::PickerMonth(-3));
2241 assert_eq!(form.picker.map(|p| p.month), Some(date(2026, 5, 1)));
2242
2243 form.update(Event::Date(Field::End, date(2026, 6, 20)));
2244 assert_eq!(form.picker(), None);
2245 assert_eq!(form.date(Field::End), date(2026, 6, 20));
2246
2247 form.update(Event::Picker(Some(Field::Start)));
2248 form.update(Event::Picker(None));
2249 assert_eq!(form.picker(), None);
2250 form.update(Event::PickerMonth(1));
2251 assert_eq!(form.picker(), None, "nothing to move");
2252 }
2253
2254 #[test]
2255 fn builder_defaults_and_options() {
2256 let form = timed();
2257 let built: Editor<'_, Event> = editor(&form);
2258 assert!(built.on_event.is_none());
2259 assert!(built.on_submit.is_none());
2260 assert_eq!(built.shortcuts, Shortcuts::all());
2261 assert!(!built.is_read_only());
2262 let built = built.read_only(true);
2263 assert!(built.is_read_only());
2264 assert!(format!("{built:?}").contains("read_only: true"));
2265 let built = built.read_only(false);
2266
2267 let built = built
2268 .on_event(|event| event)
2269 .on_submit(Event::Picker(None))
2270 .shortcuts(Shortcuts::none());
2271 assert!(built.on_event.is_some());
2272 assert!(built.on_submit.is_some());
2273 assert_eq!(built.shortcuts, Shortcuts::none());
2274 assert!(format!("{built:?}").contains("enabled: true"));
2275 }
2276
2277 #[test]
2278 fn parts_can_be_left_out_and_laid_out_by_the_app() {
2279 let mut form = timed();
2280 {
2281 let built: Editor<'_, Event> = editor(&form);
2282 assert!(Part::ALL.iter().all(|part| built.shows(*part)));
2283 let fields = built.fields();
2284 assert!(fields.title.is_some() && fields.notes.is_some() && fields.colour.is_some());
2285 assert!(
2286 fields.every.is_none() && fields.stops.is_none(),
2287 "it does not repeat"
2288 );
2289 }
2290 {
2291 let built: Editor<'_, Event> = editor(&form)
2292 .without(Part::Colour)
2293 .without(Part::Location)
2294 .without(Part::Colour);
2295 assert!(!built.shows(Part::Colour));
2296 assert!(format!("{built:?}").contains("Location"));
2297 let fields = built.fields();
2298 assert!(fields.colour.is_none() && fields.location.is_none());
2299 assert!(fields.title.is_some() && fields.starts.is_some() && fields.ends.is_some());
2300 }
2301
2302 form.update(Event::Repeats(Repeats::Weekly));
2303 let fields = editor::<Event>(&form).fields();
2304 assert!(fields.every.is_some() && fields.stops.is_some());
2305 let fields = editor::<Event>(&form).without(Part::Repeat).fields();
2306 assert!(fields.repeat.is_none() && fields.every.is_none() && fields.stops.is_none());
2307 }
2308
2309 #[test]
2310 fn a_read_only_form_keeps_its_parts_but_leaves_out_what_says_nothing() {
2311 let mut form = timed();
2312 {
2313 let fields = editor::<Event>(&form).read_only(true).fields();
2314 assert!(fields.title.is_some() && fields.starts.is_some() && fields.colour.is_some());
2315 assert!(fields.ends.is_none(), "on the same day as the start");
2316 assert!(fields.repeat.is_none(), "it does not repeat");
2317 assert!(
2318 fields.location.is_none() && fields.notes.is_none(),
2319 "both blank"
2320 );
2321 assert!(fields.all_day.is_none() && fields.every.is_none() && fields.stops.is_none());
2322 }
2323
2324 form.update(Event::Date(Field::End, date(2026, 6, 20)));
2325 form.update(Event::Repeats(Repeats::Weekly));
2326 form.update(Event::Location(String::from(" Room 4 ")));
2327 form.update(Event::Notes(Action::Edit(
2328 iced::widget::text_editor::Edit::Insert('x'),
2329 )));
2330 let fields = editor::<Event>(&form).read_only(true).fields();
2331 assert!(fields.ends.is_some() && fields.repeat.is_some());
2332 assert!(fields.all_day.is_none() && fields.every.is_none() && fields.stops.is_none());
2333 assert!(fields.location.is_some() && fields.notes.is_some());
2334
2335 let fields = editor::<Event>(&form)
2336 .read_only(true)
2337 .without(Part::Location)
2338 .without(Part::Title)
2339 .fields();
2340 assert!(fields.location.is_none() && fields.title.is_none());
2341 }
2342
2343 #[test]
2344 fn read_only_text_says_when_and_how_often_in_a_line_each() {
2345 let mut form = timed();
2346 assert_eq!(
2347 span_text(&form),
2348 (String::from("Fri 19 Jun 2026, 11:00 to 12:30"), None)
2349 );
2350 form.update(Event::Date(Field::End, date(2026, 6, 20)));
2351 assert_eq!(
2352 span_text(&form),
2353 (
2354 String::from("Fri 19 Jun 2026, 11:00"),
2355 Some(String::from("Sat 20 Jun 2026, 12:30"))
2356 )
2357 );
2358 form.update(Event::AllDay(true));
2359 assert_eq!(
2360 span_text(&form),
2361 (
2362 String::from("Fri 19 Jun 2026, all day"),
2363 Some(String::from("Sat 20 Jun 2026"))
2364 )
2365 );
2366 form.update(Event::Date(Field::End, date(2026, 6, 19)));
2367 assert_eq!(
2368 span_text(&form),
2369 (String::from("Fri 19 Jun 2026, all day"), None)
2370 );
2371
2372 assert_eq!(repeat_text(&form), None);
2373 form.update(Event::Repeats(Repeats::Weekly));
2374 assert_eq!(repeat_text(&form).as_deref(), Some("Weekly"));
2375 form.update(Event::Interval(String::from("2")));
2376 assert_eq!(repeat_text(&form).as_deref(), Some("Every 2 weeks"));
2377 form.update(Event::Stops(Stops::After));
2378 form.update(Event::Count(String::from("6")));
2379 assert_eq!(
2380 repeat_text(&form).as_deref(),
2381 Some("Every 2 weeks, 6 times")
2382 );
2383 form.update(Event::Count(String::from("1")));
2384 assert_eq!(repeat_text(&form).as_deref(), Some("Every 2 weeks, once"));
2385 form.update(Event::Stops(Stops::On));
2386 form.update(Event::Until(date(2026, 7, 1)));
2387 assert_eq!(
2388 repeat_text(&form).as_deref(),
2389 Some("Every 2 weeks, until Wed 1 Jul 2026")
2390 );
2391 }
2392
2393 #[test]
2394 fn the_raw_field_text_the_picker_month_and_the_notes_can_be_read() {
2395 let mut form = timed().with_week_start(Weekday::Sunday);
2396 assert_eq!(form.week_start(), Weekday::Sunday);
2397 form.update(Event::Interval(String::new()));
2398 assert_eq!(form.interval_text(), "");
2399 assert_eq!(form.interval(), 1, "blank counts as one");
2400 form.update(Event::Count(String::from("2a")));
2401 assert_eq!(form.count_text(), "2");
2402
2403 assert_eq!(form.picker_month(), None);
2404 form.update(Event::Picker(Some(Field::Start)));
2405 let month = form.date(Field::Start).first_of_month();
2406 assert_eq!(form.picker_month(), Some(month));
2407 form.update(Event::PickerMonth(2));
2408 assert_eq!(form.picker_month(), month.checked_add(2.months()).ok());
2409
2410 form.update(Event::Notes(Action::Edit(
2411 iced::widget::text_editor::Edit::Paste(std::sync::Arc::new(String::from("Bring cake"))),
2412 )));
2413 assert_eq!(form.notes_content().text().trim(), "Bring cake");
2414 }
2415}