1use iced::Color;
4use jiff::civil::Date;
5use jiff::tz::TimeZone;
6use jiff::{SignedDuration, Timestamp};
7
8use super::repeat::{self, Repeat};
9use crate::icon::Glyph;
10
11#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
14pub struct EntryId(pub u64);
15
16pub use crate::theme::Tone;
18
19#[derive(Debug, Clone, Copy, PartialEq)]
23pub enum Paint {
24 Tone(Tone),
25 Colour(Color),
27}
28
29impl Default for Paint {
30 fn default() -> Self {
31 Paint::Tone(Tone::default())
32 }
33}
34
35impl From<Tone> for Paint {
36 fn from(tone: Tone) -> Self {
37 Paint::Tone(tone)
38 }
39}
40
41impl From<Color> for Paint {
42 fn from(colour: Color) -> Self {
43 Paint::Colour(colour)
44 }
45}
46
47#[derive(Debug, Clone, Copy)]
49struct Custom(Color);
50
51impl PartialEq for Custom {
52 fn eq(&self, other: &Self) -> bool {
53 let bits = |colour: Color| [colour.r, colour.g, colour.b, colour.a].map(f32::to_bits);
54 bits(self.0) == bits(other.0)
55 }
56}
57
58impl Eq for Custom {}
59
60pub use super::rules::{When, add_days, date_of, instant, midnight, next_day};
61
62#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
64pub enum Emphasis {
65 #[default]
67 Solid,
68 Outlined,
71 Struck,
73 Faded,
75 Hatched,
77}
78
79impl Emphasis {
80 pub const ALL: [Emphasis; 5] = [
81 Emphasis::Solid,
82 Emphasis::Outlined,
83 Emphasis::Struck,
84 Emphasis::Faded,
85 Emphasis::Hatched,
86 ];
87}
88
89#[derive(Debug, Clone, PartialEq, Eq, Default)]
91struct Marker {
92 glyph: Option<Glyph>,
93 label: Option<String>,
94}
95
96#[derive(Debug, Clone, PartialEq, Eq)]
98pub struct Entry {
99 id: EntryId,
100 title: String,
101 when: When,
102 tone: Tone,
103 colour: Option<Custom>,
104 tag: Option<String>,
105 repeat: Option<Repeat>,
106 location: Option<String>,
107 notes: Option<String>,
108 marker: Option<Box<Marker>>,
110 emphasis: Emphasis,
111 locked: bool,
112 movable: bool,
113 removable: bool,
114}
115
116fn filled(text: String) -> Option<String> {
118 let trimmed = text.trim();
119 if trimmed.is_empty() {
120 return None;
121 }
122 Some(trimmed.to_owned())
123}
124
125impl Entry {
126 pub fn new(id: EntryId, title: impl Into<String>, start: Timestamp, end: Timestamp) -> Self {
128 Self::at(id, title, When::timed(start, end))
129 }
130
131 pub fn all_day(id: EntryId, title: impl Into<String>, first: Date, last: Date) -> Self {
133 Self::at(id, title, When::all_day(first, last))
134 }
135
136 pub fn at(id: EntryId, title: impl Into<String>, when: When) -> Self {
138 Self {
139 id,
140 title: title.into(),
141 when,
142 tone: Tone::default(),
143 colour: None,
144 tag: None,
145 repeat: None,
146 location: None,
147 notes: None,
148 marker: None,
149 emphasis: Emphasis::Solid,
150 locked: false,
151 movable: true,
152 removable: true,
153 }
154 }
155
156 pub fn icon(mut self, glyph: Glyph) -> Self {
160 self.marker.get_or_insert_default().glyph = Some(glyph);
161 self
162 }
163
164 pub fn icon_label(mut self, label: impl Into<String>) -> Self {
167 self.marker.get_or_insert_default().label = filled(label.into());
168 self
169 }
170
171 pub fn icon_label_of(&self) -> Option<&str> {
172 self.marker.as_ref()?.label.as_deref()
173 }
174
175 pub fn emphasis(mut self, emphasis: Emphasis) -> Self {
176 self.emphasis = emphasis;
177 self
178 }
179
180 pub fn locked(mut self, locked: bool) -> Self {
186 self.locked = locked;
187 self
188 }
189
190 pub fn movable(mut self, movable: bool) -> Self {
197 self.movable = movable;
198 self
199 }
200
201 pub fn removable(mut self, removable: bool) -> Self {
206 self.removable = removable;
207 self
208 }
209
210 pub fn location(mut self, location: impl Into<String>) -> Self {
212 self.location = filled(location.into());
213 self
214 }
215
216 pub fn notes(mut self, notes: impl Into<String>) -> Self {
219 let notes = notes.into();
220 self.notes = (!notes.trim().is_empty()).then_some(notes);
221 self
222 }
223
224 pub fn tone(mut self, tone: Tone) -> Self {
225 self.tone = tone;
226 self
227 }
228
229 pub fn colour(mut self, colour: impl Into<Option<Color>>) -> Self {
236 self.colour = colour.into().map(Custom);
237 self
238 }
239
240 pub fn tag(mut self, tag: impl Into<String>) -> Self {
243 self.tag = Some(tag.into());
244 self
245 }
246
247 pub fn repeat(mut self, repeat: Repeat) -> Self {
250 self.repeat = Some(repeat);
251 self
252 }
253
254 pub(super) fn repeating(mut self, repeat: Option<Repeat>) -> Self {
256 self.repeat = repeat;
257 self
258 }
259
260 pub fn titled(mut self, title: impl Into<String>) -> Self {
262 self.title = title.into();
263 self
264 }
265
266 pub fn rescheduled(mut self, when: When) -> Self {
269 self.when = when;
270 self
271 }
272
273 pub fn id(&self) -> EntryId {
274 self.id
275 }
276
277 pub fn title(&self) -> &str {
278 &self.title
279 }
280
281 pub fn when(&self) -> When {
283 self.when
284 }
285
286 pub fn tone_of(&self) -> Tone {
287 self.tone
288 }
289
290 pub fn colour_of(&self) -> Option<Color> {
292 self.colour.map(|custom| custom.0)
293 }
294
295 pub fn paint_of(&self) -> Paint {
298 self.colour_of()
299 .map_or(Paint::Tone(self.tone), Paint::Colour)
300 }
301
302 pub fn tag_of(&self) -> Option<&str> {
303 self.tag.as_deref()
304 }
305
306 pub fn repeat_of(&self) -> Option<Repeat> {
307 self.repeat
308 }
309
310 pub fn location_of(&self) -> Option<&str> {
311 self.location.as_deref()
312 }
313
314 pub fn notes_of(&self) -> Option<&str> {
315 self.notes.as_deref()
316 }
317
318 pub fn is_all_day(&self) -> bool {
319 self.when.is_all_day()
320 }
321
322 pub fn icon_of(&self) -> Option<Glyph> {
323 self.marker.as_ref()?.glyph
324 }
325
326 pub fn emphasis_of(&self) -> Emphasis {
327 self.emphasis
328 }
329
330 pub fn is_locked(&self) -> bool {
331 self.locked
332 }
333
334 pub fn is_movable(&self) -> bool {
337 self.movable && !self.locked
338 }
339
340 pub fn is_removable(&self) -> bool {
343 self.removable && !self.locked
344 }
345}
346
347#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
350pub struct Occurrence {
351 pub entry: EntryId,
352 pub index: u32,
354 pub start: Timestamp,
355 pub end: Timestamp,
357 pub all_day: bool,
358}
359
360impl Occurrence {
361 pub fn duration(&self) -> SignedDuration {
362 self.end.duration_since(self.start)
363 }
364
365 pub fn dates(&self, time_zone: &TimeZone) -> (Date, Date) {
367 let first = date_of(self.start, time_zone);
368 if self.end <= self.start {
369 return (first, first);
370 }
371 let last_instant = self
372 .end
373 .saturating_sub(SignedDuration::from_nanos(1))
374 .unwrap_or(self.end);
375 (first, date_of(last_instant, time_zone).max(first))
376 }
377}
378
379#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
382pub struct Draft {
383 pub when: When,
384}
385
386#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
388pub enum Change {
389 Created,
390 Updated,
391 Removed,
392}
393
394impl Change {
395 pub const ALL: [Change; 3] = [Change::Created, Change::Updated, Change::Removed];
396}
397
398#[derive(Debug, Clone, PartialEq, Eq)]
400pub struct Changed {
401 pub change: Change,
402 pub entry: Entry,
404 pub before: Option<Entry>,
406}
407
408#[derive(Debug, Clone)]
413pub struct Entries {
414 items: Vec<Entry>,
415 time_zone: TimeZone,
416 next: u64,
418}
419
420impl PartialEq for Entries {
421 fn eq(&self, other: &Self) -> bool {
422 self.items == other.items && self.time_zone == other.time_zone
423 }
424}
425
426impl Eq for Entries {}
427
428impl Default for Entries {
429 fn default() -> Self {
430 Self::utc()
431 }
432}
433
434impl Entries {
435 pub fn new(time_zone: TimeZone) -> Self {
437 Self {
438 items: Vec::new(),
439 time_zone,
440 next: 0,
441 }
442 }
443
444 pub fn utc() -> Self {
446 Self::new(TimeZone::UTC)
447 }
448
449 pub fn system() -> Self {
452 Self::new(TimeZone::system())
453 }
454
455 pub fn with(mut self, entries: impl IntoIterator<Item = Entry>) -> Self {
458 for entry in entries {
459 let _ = self.insert(entry);
460 }
461 self
462 }
463
464 pub fn time_zone(&self) -> &TimeZone {
465 &self.time_zone
466 }
467
468 pub fn len(&self) -> usize {
469 self.items.len()
470 }
471
472 pub fn is_empty(&self) -> bool {
473 self.items.is_empty()
474 }
475
476 pub fn iter(&self) -> impl Iterator<Item = &Entry> {
477 self.items.iter()
478 }
479
480 pub fn get(&self, id: EntryId) -> Option<&Entry> {
481 self.items.iter().find(|entry| entry.id == id)
482 }
483
484 pub fn next_id(&self) -> EntryId {
488 EntryId(self.next)
489 }
490
491 pub fn insert(&mut self, entry: Entry) -> Option<Changed> {
494 self.next = self.next.max(entry.id.0.saturating_add(1));
495 let Some(existing) = self.items.iter_mut().find(|item| item.id == entry.id) else {
496 self.items.push(entry.clone());
497 return Some(Changed {
498 change: Change::Created,
499 entry,
500 before: None,
501 });
502 };
503 if *existing == entry {
504 return None;
505 }
506 let before = std::mem::replace(existing, entry.clone());
507 Some(Changed {
508 change: Change::Updated,
509 entry,
510 before: Some(before),
511 })
512 }
513
514 pub fn remove(&mut self, id: EntryId) -> Option<Changed> {
516 let index = self.items.iter().position(|entry| entry.id == id)?;
517 Some(Changed {
518 change: Change::Removed,
519 entry: self.items.remove(index),
520 before: None,
521 })
522 }
523
524 pub fn date_of(&self, instant: Timestamp) -> Date {
526 date_of(instant, &self.time_zone)
527 }
528
529 pub fn midnight(&self, date: Date) -> Timestamp {
531 midnight(date, &self.time_zone)
532 }
533
534 pub fn occurrences(&self, from: Timestamp, to: Timestamp) -> Vec<Occurrence> {
537 let mut found: Vec<Occurrence> = self
538 .items
539 .iter()
540 .flat_map(|entry| repeat::occurrences(entry, &self.time_zone, from, to))
541 .collect();
542 found.sort_by_key(|occurrence| (occurrence.start, occurrence.entry));
543 found
544 }
545
546 pub fn between(&self, first: Date, last: Date) -> Vec<Occurrence> {
549 self.occurrences(self.midnight(first), self.midnight(next_day(last)))
550 }
551
552 pub fn on(&self, date: Date) -> Vec<Occurrence> {
554 self.between(date, date)
555 }
556}
557
558#[cfg(test)]
559mod tests {
560 use super::*;
561 use jiff::civil::date;
562
563 fn at(day: i8, hour: i8) -> Timestamp {
564 date(2026, 11, day)
565 .at(hour, 0, 0, 0)
566 .to_zoned_datetime(TimeZone::UTC)
567 .map(|zoned| zoned.timestamp())
568 .unwrap_or_default()
569 }
570
571 fn meeting(id: u64, day: i8, hour: i8) -> Entry {
572 Entry::new(EntryId(id), "Meeting", at(day, hour), at(day, hour + 1))
573 }
574
575 #[test]
576 fn days_are_added_and_stop_at_the_ends_of_time() {
577 let day = date(2026, 11, 3);
578 assert_eq!(add_days(day, 1), date(2026, 11, 4));
579 assert_eq!(add_days(day, -3), date(2026, 10, 31));
580 assert_eq!(add_days(day, 0), day);
581 assert_eq!(add_days(day, i32::MAX), Date::MAX);
582 assert_eq!(add_days(day, i32::MIN), Date::MIN);
583 assert_eq!(add_days(Date::MAX, 1), Date::MAX);
584 assert_eq!(next_day(date(2026, 12, 31)), date(2027, 1, 1));
585 }
586
587 #[test]
588 fn spans_are_put_in_order() {
589 assert_eq!(
590 When::timed(at(3, 10), at(3, 9)),
591 When::Timed {
592 start: at(3, 9),
593 end: at(3, 10)
594 }
595 );
596 assert_eq!(
597 When::all_day(date(2026, 11, 5), date(2026, 11, 3)),
598 When::AllDay {
599 first: date(2026, 11, 3),
600 last: date(2026, 11, 5)
601 }
602 );
603 }
604
605 #[test]
606 fn whole_days_run_from_midnight_to_the_midnight_after_the_last_day() {
607 let when = When::all_day(date(2026, 11, 3), date(2026, 11, 4));
608 assert!(when.is_all_day());
609 assert_eq!(when.start(&TimeZone::UTC), at(3, 0));
610 assert_eq!(when.end(&TimeZone::UTC), at(5, 0));
611 assert_eq!(When::day(date(2026, 11, 3)).end(&TimeZone::UTC), at(4, 0));
612 }
613
614 #[test]
615 fn whole_days_follow_the_time_zone() {
616 let Ok(tokyo) = TimeZone::get("Asia/Tokyo") else {
617 panic!("the time zone database is bundled for tests");
618 };
619 let when = When::day(date(2026, 11, 3));
620 assert_eq!(when.start(&tokyo), at(2, 15));
622 assert_eq!(date_of(at(2, 15), &tokyo), date(2026, 11, 3));
623 assert_eq!(date_of(at(2, 14), &tokyo), date(2026, 11, 2));
624 }
625
626 #[test]
627 fn entry_builder_defaults_and_options() {
628 let entry = meeting(1, 3, 9);
629 assert_eq!(entry.id(), EntryId(1));
630 assert_eq!(entry.title(), "Meeting");
631 assert_eq!(entry.tone_of(), Tone::Primary);
632 assert_eq!(entry.tag_of(), None);
633 assert_eq!(entry.repeat_of(), None);
634 assert!(!entry.is_all_day());
635
636 let entry = entry
637 .tone(Tone::Warning)
638 .tag("work")
639 .repeat(Repeat::daily())
640 .titled("Review")
641 .rescheduled(When::day(date(2026, 11, 9)));
642 assert_eq!(entry.tone_of(), Tone::Warning);
643 assert_eq!(entry.tag_of(), Some("work"));
644 assert_eq!(entry.repeat_of(), Some(Repeat::daily()));
645 assert_eq!(entry.title(), "Review");
646 assert!(entry.is_all_day());
647 }
648
649 #[test]
650 fn the_location_is_trimmed_the_notes_kept_and_blank_clears_them() {
651 let entry = meeting(1, 3, 9);
652 assert_eq!(entry.location_of(), None);
653 assert_eq!(entry.notes_of(), None);
654
655 let entry = entry
656 .location(" Room 4 ")
657 .notes(" Bring the plan\nand the figures\n");
658 assert_eq!(entry.location_of(), Some("Room 4"));
659 assert_eq!(
660 entry.notes_of(),
661 Some(" Bring the plan\nand the figures\n")
662 );
663
664 let entry = entry.location(" ").notes(" \n ");
665 assert_eq!(entry.location_of(), None);
666 assert_eq!(entry.notes_of(), None);
667 }
668
669 #[test]
670 fn insert_reports_created_updated_and_unchanged() {
671 let mut entries = Entries::utc();
672 let created = entries.insert(meeting(1, 3, 9));
673 assert_eq!(created.map(|changed| changed.change), Some(Change::Created));
674
675 assert_eq!(entries.insert(meeting(1, 3, 9)), None);
676
677 let updated = entries.insert(meeting(1, 4, 9));
678 let Some(updated) = updated else {
679 panic!("a moved entry is an update");
680 };
681 assert_eq!(updated.change, Change::Updated);
682 assert_eq!(updated.before, Some(meeting(1, 3, 9)));
683 assert_eq!(updated.entry, meeting(1, 4, 9));
684 assert_eq!(entries.len(), 1);
685 }
686
687 #[test]
688 fn remove_hands_back_the_entry() {
689 let mut entries = Entries::utc().with([meeting(1, 3, 9), meeting(2, 4, 9)]);
690 let removed = entries.remove(EntryId(1));
691 assert_eq!(
692 removed.map(|changed| (changed.change, changed.entry)),
693 Some((Change::Removed, meeting(1, 3, 9)))
694 );
695 assert_eq!(entries.remove(EntryId(1)), None);
696 assert_eq!(entries.len(), 1);
697 assert!(entries.get(EntryId(2)).is_some());
698 }
699
700 #[test]
701 fn next_id_is_unused() {
702 let mut entries = Entries::utc();
703 assert!(entries.is_empty());
704 assert_eq!(entries.next_id(), EntryId(0));
705 let _ = entries.insert(meeting(7, 3, 9));
706 assert_eq!(entries.next_id(), EntryId(8));
707 let _ = entries.insert(meeting(u64::MAX, 3, 9));
708 assert_eq!(entries.next_id(), EntryId(u64::MAX));
709 }
710
711 #[test]
712 fn a_removed_entry_never_gives_its_id_back() {
713 let mut entries = Entries::utc().with([meeting(1, 3, 9), meeting(2, 3, 10)]);
714 assert_eq!(entries.next_id(), EntryId(3));
715 let _ = entries.remove(EntryId(2));
716 assert_eq!(entries.next_id(), EntryId(3), "2 was used");
717 let _ = entries.remove(EntryId(1));
718 assert_eq!(entries.next_id(), EntryId(3));
719 assert_eq!(entries, Entries::utc());
721 }
722
723 #[test]
724 fn icon_emphasis_and_lock_default_off_and_can_be_set() {
725 let entry = meeting(1, 3, 9);
726 assert_eq!(entry.icon_of(), None);
727 assert_eq!(entry.icon_label_of(), None);
728 assert_eq!(entry.emphasis_of(), Emphasis::Solid);
729 assert!(!entry.is_locked());
730 let entry = entry
731 .icon(crate::lucide!(Users))
732 .icon_label(" Team entry ")
733 .emphasis(Emphasis::Outlined)
734 .locked(true);
735 assert_eq!(entry.icon_of().map(Glyph::name), Some("users"));
736 assert_eq!(entry.icon_label_of(), Some("Team entry"));
737 assert_eq!(entry.emphasis_of(), Emphasis::Outlined);
738 assert!(entry.is_locked());
739 assert_eq!(entry.icon_label("").icon_label_of(), None);
740 assert_eq!(Emphasis::ALL.len(), 5);
741 }
742
743 #[test]
744 fn moving_and_removing_default_on_and_a_lock_turns_both_off() {
745 let entry = meeting(1, 3, 9);
746 assert!(entry.is_movable() && entry.is_removable());
747 let fixed = entry.clone().movable(false);
748 assert!(!fixed.is_movable() && fixed.is_removable());
749 let kept = entry.clone().removable(false);
750 assert!(kept.is_movable() && !kept.is_removable());
751 let locked = entry.clone().locked(true);
752 assert!(!locked.is_movable() && !locked.is_removable());
753 assert_ne!(fixed, entry);
754 assert_ne!(kept, entry);
755 assert_eq!(fixed.movable(true), entry);
756 }
757
758 #[test]
759 fn a_colour_of_its_own_paints_the_entry_instead_of_its_tone() {
760 let teal = Color::from_rgb8(0x0f, 0x76, 0x6e);
761 let entry = meeting(1, 3, 9).tone(Tone::Success);
762 assert_eq!(entry.colour_of(), None);
763 assert_eq!(entry.paint_of(), Paint::Tone(Tone::Success));
764
765 let coloured = entry.clone().colour(teal);
766 assert_eq!(coloured.colour_of(), Some(teal));
767 assert_eq!(coloured.paint_of(), Paint::Colour(teal));
768 assert_eq!(coloured.tone_of(), Tone::Success);
769 assert_ne!(coloured, entry);
770 assert_eq!(coloured.clone(), coloured);
771 assert_eq!(coloured.colour(None), entry);
772
773 assert_eq!(Paint::default(), Paint::Tone(Tone::Primary));
774 assert_eq!(Paint::from(Tone::Warning), Paint::Tone(Tone::Warning));
775 assert_eq!(Paint::from(teal), Paint::Colour(teal));
776 }
777
778 #[test]
779 fn occurrences_overlap_the_range_and_come_in_order() {
780 let entries = Entries::utc().with([
781 meeting(1, 5, 9),
782 meeting(2, 3, 14),
783 meeting(3, 3, 9),
784 Entry::all_day(EntryId(4), "Trip", date(2026, 11, 2), date(2026, 11, 3)),
785 ]);
786 let found = entries.on(date(2026, 11, 3));
787 let ids: Vec<_> = found.iter().map(|occurrence| occurrence.entry.0).collect();
788 assert_eq!(ids, vec![4, 3, 2]);
789 assert!(found[0].all_day);
790 assert!(!found[1].all_day);
791
792 let week = entries.between(date(2026, 11, 2), date(2026, 11, 8));
793 assert_eq!(week.len(), 4);
794 assert!(entries.on(date(2026, 11, 4)).is_empty());
795 }
796
797 #[test]
798 fn an_entry_ending_at_midnight_does_not_touch_the_next_day() {
799 let entries = Entries::utc().with([Entry::new(EntryId(1), "Late", at(3, 22), at(4, 0))]);
800 assert_eq!(entries.on(date(2026, 11, 3)).len(), 1);
801 assert!(entries.on(date(2026, 11, 4)).is_empty());
802 let occurrence = entries.on(date(2026, 11, 3))[0];
803 assert_eq!(
804 occurrence.dates(&TimeZone::UTC),
805 (date(2026, 11, 3), date(2026, 11, 3))
806 );
807 assert_eq!(occurrence.duration(), SignedDuration::from_hours(2));
808 }
809
810 #[test]
811 fn an_entry_with_no_length_sits_on_its_day() {
812 let entries =
813 Entries::utc().with([Entry::new(EntryId(1), "Deadline", at(3, 17), at(3, 17))]);
814 let found = entries.on(date(2026, 11, 3));
815 assert_eq!(found.len(), 1);
816 assert_eq!(
817 found[0].dates(&TimeZone::UTC),
818 (date(2026, 11, 3), date(2026, 11, 3))
819 );
820 }
821}