1use jiff::civil::Date;
4use jiff::tz::TimeZone;
5use jiff::{SignedDuration, Timestamp};
6
7use super::repeat::{self, Repeat};
8use crate::icon::Glyph;
9
10#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
13pub struct EntryId(pub u64);
14
15#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
17pub enum Tone {
18 #[default]
19 Primary,
20 Neutral,
21 Success,
22 Warning,
23 Destructive,
24}
25
26impl Tone {
27 pub const ALL: [Tone; 5] = [
28 Tone::Primary,
29 Tone::Neutral,
30 Tone::Success,
31 Tone::Warning,
32 Tone::Destructive,
33 ];
34}
35
36pub use super::rules::{When, add_days, date_of, instant, midnight, next_day};
37
38#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
40pub enum Emphasis {
41 #[default]
43 Solid,
44 Outlined,
47 Struck,
49 Faded,
51 Hatched,
53}
54
55impl Emphasis {
56 pub const ALL: [Emphasis; 5] = [
57 Emphasis::Solid,
58 Emphasis::Outlined,
59 Emphasis::Struck,
60 Emphasis::Faded,
61 Emphasis::Hatched,
62 ];
63}
64
65#[derive(Debug, Clone, PartialEq, Eq, Default)]
67struct Marker {
68 glyph: Option<Glyph>,
69 label: Option<String>,
70}
71
72#[derive(Debug, Clone, PartialEq, Eq)]
74pub struct Entry {
75 id: EntryId,
76 title: String,
77 when: When,
78 tone: Tone,
79 tag: Option<String>,
80 repeat: Option<Repeat>,
81 location: Option<String>,
82 notes: Option<String>,
83 marker: Option<Box<Marker>>,
85 emphasis: Emphasis,
86 locked: bool,
87}
88
89fn filled(text: String) -> Option<String> {
91 let trimmed = text.trim();
92 if trimmed.is_empty() {
93 return None;
94 }
95 Some(trimmed.to_owned())
96}
97
98impl Entry {
99 pub fn new(id: EntryId, title: impl Into<String>, start: Timestamp, end: Timestamp) -> Self {
101 Self::at(id, title, When::timed(start, end))
102 }
103
104 pub fn all_day(id: EntryId, title: impl Into<String>, first: Date, last: Date) -> Self {
106 Self::at(id, title, When::all_day(first, last))
107 }
108
109 pub fn at(id: EntryId, title: impl Into<String>, when: When) -> Self {
111 Self {
112 id,
113 title: title.into(),
114 when,
115 tone: Tone::default(),
116 tag: None,
117 repeat: None,
118 location: None,
119 notes: None,
120 marker: None,
121 emphasis: Emphasis::Solid,
122 locked: false,
123 }
124 }
125
126 pub fn icon(mut self, glyph: Glyph) -> Self {
130 self.marker.get_or_insert_default().glyph = Some(glyph);
131 self
132 }
133
134 pub fn icon_label(mut self, label: impl Into<String>) -> Self {
137 self.marker.get_or_insert_default().label = filled(label.into());
138 self
139 }
140
141 pub fn icon_label_of(&self) -> Option<&str> {
142 self.marker.as_ref()?.label.as_deref()
143 }
144
145 pub fn emphasis(mut self, emphasis: Emphasis) -> Self {
146 self.emphasis = emphasis;
147 self
148 }
149
150 pub fn locked(mut self, locked: bool) -> Self {
154 self.locked = locked;
155 self
156 }
157
158 pub fn location(mut self, location: impl Into<String>) -> Self {
160 self.location = filled(location.into());
161 self
162 }
163
164 pub fn notes(mut self, notes: impl Into<String>) -> Self {
167 let notes = notes.into();
168 self.notes = (!notes.trim().is_empty()).then_some(notes);
169 self
170 }
171
172 pub fn tone(mut self, tone: Tone) -> Self {
173 self.tone = tone;
174 self
175 }
176
177 pub fn tag(mut self, tag: impl Into<String>) -> Self {
180 self.tag = Some(tag.into());
181 self
182 }
183
184 pub fn repeat(mut self, repeat: Repeat) -> Self {
187 self.repeat = Some(repeat);
188 self
189 }
190
191 pub fn titled(mut self, title: impl Into<String>) -> Self {
193 self.title = title.into();
194 self
195 }
196
197 pub fn rescheduled(mut self, when: When) -> Self {
200 self.when = when;
201 self
202 }
203
204 pub fn id(&self) -> EntryId {
205 self.id
206 }
207
208 pub fn title(&self) -> &str {
209 &self.title
210 }
211
212 pub fn when(&self) -> When {
214 self.when
215 }
216
217 pub fn tone_of(&self) -> Tone {
218 self.tone
219 }
220
221 pub fn tag_of(&self) -> Option<&str> {
222 self.tag.as_deref()
223 }
224
225 pub fn repeat_of(&self) -> Option<Repeat> {
226 self.repeat
227 }
228
229 pub fn location_of(&self) -> Option<&str> {
230 self.location.as_deref()
231 }
232
233 pub fn notes_of(&self) -> Option<&str> {
234 self.notes.as_deref()
235 }
236
237 pub fn is_all_day(&self) -> bool {
238 self.when.is_all_day()
239 }
240
241 pub fn icon_of(&self) -> Option<Glyph> {
242 self.marker.as_ref()?.glyph
243 }
244
245 pub fn emphasis_of(&self) -> Emphasis {
246 self.emphasis
247 }
248
249 pub fn is_locked(&self) -> bool {
250 self.locked
251 }
252}
253
254#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
257pub struct Occurrence {
258 pub entry: EntryId,
259 pub index: u32,
261 pub start: Timestamp,
262 pub end: Timestamp,
264 pub all_day: bool,
265}
266
267impl Occurrence {
268 pub fn duration(&self) -> SignedDuration {
269 self.end.duration_since(self.start)
270 }
271
272 pub fn dates(&self, time_zone: &TimeZone) -> (Date, Date) {
274 let first = date_of(self.start, time_zone);
275 if self.end <= self.start {
276 return (first, first);
277 }
278 let last_instant = self
279 .end
280 .saturating_sub(SignedDuration::from_nanos(1))
281 .unwrap_or(self.end);
282 (first, date_of(last_instant, time_zone).max(first))
283 }
284}
285
286#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
289pub struct Draft {
290 pub when: When,
291}
292
293#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
295pub enum Change {
296 Created,
297 Updated,
298 Removed,
299}
300
301impl Change {
302 pub const ALL: [Change; 3] = [Change::Created, Change::Updated, Change::Removed];
303}
304
305#[derive(Debug, Clone, PartialEq, Eq)]
307pub struct Changed {
308 pub change: Change,
309 pub entry: Entry,
311 pub before: Option<Entry>,
313}
314
315#[derive(Debug, Clone)]
320pub struct Entries {
321 items: Vec<Entry>,
322 time_zone: TimeZone,
323 next: u64,
325}
326
327impl PartialEq for Entries {
328 fn eq(&self, other: &Self) -> bool {
329 self.items == other.items && self.time_zone == other.time_zone
330 }
331}
332
333impl Eq for Entries {}
334
335impl Default for Entries {
336 fn default() -> Self {
337 Self::utc()
338 }
339}
340
341impl Entries {
342 pub fn new(time_zone: TimeZone) -> Self {
344 Self {
345 items: Vec::new(),
346 time_zone,
347 next: 0,
348 }
349 }
350
351 pub fn utc() -> Self {
353 Self::new(TimeZone::UTC)
354 }
355
356 pub fn system() -> Self {
359 Self::new(TimeZone::system())
360 }
361
362 pub fn with(mut self, entries: impl IntoIterator<Item = Entry>) -> Self {
365 for entry in entries {
366 let _ = self.insert(entry);
367 }
368 self
369 }
370
371 pub fn time_zone(&self) -> &TimeZone {
372 &self.time_zone
373 }
374
375 pub fn len(&self) -> usize {
376 self.items.len()
377 }
378
379 pub fn is_empty(&self) -> bool {
380 self.items.is_empty()
381 }
382
383 pub fn iter(&self) -> impl Iterator<Item = &Entry> {
384 self.items.iter()
385 }
386
387 pub fn get(&self, id: EntryId) -> Option<&Entry> {
388 self.items.iter().find(|entry| entry.id == id)
389 }
390
391 pub fn next_id(&self) -> EntryId {
395 EntryId(self.next)
396 }
397
398 pub fn insert(&mut self, entry: Entry) -> Option<Changed> {
401 self.next = self.next.max(entry.id.0.saturating_add(1));
402 let Some(existing) = self.items.iter_mut().find(|item| item.id == entry.id) else {
403 self.items.push(entry.clone());
404 return Some(Changed {
405 change: Change::Created,
406 entry,
407 before: None,
408 });
409 };
410 if *existing == entry {
411 return None;
412 }
413 let before = std::mem::replace(existing, entry.clone());
414 Some(Changed {
415 change: Change::Updated,
416 entry,
417 before: Some(before),
418 })
419 }
420
421 pub fn remove(&mut self, id: EntryId) -> Option<Changed> {
423 let index = self.items.iter().position(|entry| entry.id == id)?;
424 Some(Changed {
425 change: Change::Removed,
426 entry: self.items.remove(index),
427 before: None,
428 })
429 }
430
431 pub fn date_of(&self, instant: Timestamp) -> Date {
433 date_of(instant, &self.time_zone)
434 }
435
436 pub fn midnight(&self, date: Date) -> Timestamp {
438 midnight(date, &self.time_zone)
439 }
440
441 pub fn occurrences(&self, from: Timestamp, to: Timestamp) -> Vec<Occurrence> {
444 let mut found: Vec<Occurrence> = self
445 .items
446 .iter()
447 .flat_map(|entry| repeat::occurrences(entry, &self.time_zone, from, to))
448 .collect();
449 found.sort_by_key(|occurrence| (occurrence.start, occurrence.entry));
450 found
451 }
452
453 pub fn between(&self, first: Date, last: Date) -> Vec<Occurrence> {
456 self.occurrences(self.midnight(first), self.midnight(next_day(last)))
457 }
458
459 pub fn on(&self, date: Date) -> Vec<Occurrence> {
461 self.between(date, date)
462 }
463}
464
465#[cfg(test)]
466mod tests {
467 use super::*;
468 use jiff::civil::date;
469
470 fn at(day: i8, hour: i8) -> Timestamp {
471 date(2026, 11, day)
472 .at(hour, 0, 0, 0)
473 .to_zoned_datetime(TimeZone::UTC)
474 .map(|zoned| zoned.timestamp())
475 .unwrap_or_default()
476 }
477
478 fn meeting(id: u64, day: i8, hour: i8) -> Entry {
479 Entry::new(EntryId(id), "Meeting", at(day, hour), at(day, hour + 1))
480 }
481
482 #[test]
483 fn days_are_added_and_stop_at_the_ends_of_time() {
484 let day = date(2026, 11, 3);
485 assert_eq!(add_days(day, 1), date(2026, 11, 4));
486 assert_eq!(add_days(day, -3), date(2026, 10, 31));
487 assert_eq!(add_days(day, 0), day);
488 assert_eq!(add_days(day, i32::MAX), Date::MAX);
489 assert_eq!(add_days(day, i32::MIN), Date::MIN);
490 assert_eq!(add_days(Date::MAX, 1), Date::MAX);
491 assert_eq!(next_day(date(2026, 12, 31)), date(2027, 1, 1));
492 }
493
494 #[test]
495 fn spans_are_put_in_order() {
496 assert_eq!(
497 When::timed(at(3, 10), at(3, 9)),
498 When::Timed {
499 start: at(3, 9),
500 end: at(3, 10)
501 }
502 );
503 assert_eq!(
504 When::all_day(date(2026, 11, 5), date(2026, 11, 3)),
505 When::AllDay {
506 first: date(2026, 11, 3),
507 last: date(2026, 11, 5)
508 }
509 );
510 }
511
512 #[test]
513 fn whole_days_run_from_midnight_to_the_midnight_after_the_last_day() {
514 let when = When::all_day(date(2026, 11, 3), date(2026, 11, 4));
515 assert!(when.is_all_day());
516 assert_eq!(when.start(&TimeZone::UTC), at(3, 0));
517 assert_eq!(when.end(&TimeZone::UTC), at(5, 0));
518 assert_eq!(When::day(date(2026, 11, 3)).end(&TimeZone::UTC), at(4, 0));
519 }
520
521 #[test]
522 fn whole_days_follow_the_time_zone() {
523 let Ok(tokyo) = TimeZone::get("Asia/Tokyo") else {
524 panic!("the time zone database is bundled for tests");
525 };
526 let when = When::day(date(2026, 11, 3));
527 assert_eq!(when.start(&tokyo), at(2, 15));
529 assert_eq!(date_of(at(2, 15), &tokyo), date(2026, 11, 3));
530 assert_eq!(date_of(at(2, 14), &tokyo), date(2026, 11, 2));
531 }
532
533 #[test]
534 fn entry_builder_defaults_and_options() {
535 let entry = meeting(1, 3, 9);
536 assert_eq!(entry.id(), EntryId(1));
537 assert_eq!(entry.title(), "Meeting");
538 assert_eq!(entry.tone_of(), Tone::Primary);
539 assert_eq!(entry.tag_of(), None);
540 assert_eq!(entry.repeat_of(), None);
541 assert!(!entry.is_all_day());
542
543 let entry = entry
544 .tone(Tone::Warning)
545 .tag("work")
546 .repeat(Repeat::daily())
547 .titled("Review")
548 .rescheduled(When::day(date(2026, 11, 9)));
549 assert_eq!(entry.tone_of(), Tone::Warning);
550 assert_eq!(entry.tag_of(), Some("work"));
551 assert_eq!(entry.repeat_of(), Some(Repeat::daily()));
552 assert_eq!(entry.title(), "Review");
553 assert!(entry.is_all_day());
554 }
555
556 #[test]
557 fn the_location_is_trimmed_the_notes_kept_and_blank_clears_them() {
558 let entry = meeting(1, 3, 9);
559 assert_eq!(entry.location_of(), None);
560 assert_eq!(entry.notes_of(), None);
561
562 let entry = entry
563 .location(" Room 4 ")
564 .notes(" Bring the plan\nand the figures\n");
565 assert_eq!(entry.location_of(), Some("Room 4"));
566 assert_eq!(
567 entry.notes_of(),
568 Some(" Bring the plan\nand the figures\n")
569 );
570
571 let entry = entry.location(" ").notes(" \n ");
572 assert_eq!(entry.location_of(), None);
573 assert_eq!(entry.notes_of(), None);
574 }
575
576 #[test]
577 fn insert_reports_created_updated_and_unchanged() {
578 let mut entries = Entries::utc();
579 let created = entries.insert(meeting(1, 3, 9));
580 assert_eq!(created.map(|changed| changed.change), Some(Change::Created));
581
582 assert_eq!(entries.insert(meeting(1, 3, 9)), None);
583
584 let updated = entries.insert(meeting(1, 4, 9));
585 let Some(updated) = updated else {
586 panic!("a moved entry is an update");
587 };
588 assert_eq!(updated.change, Change::Updated);
589 assert_eq!(updated.before, Some(meeting(1, 3, 9)));
590 assert_eq!(updated.entry, meeting(1, 4, 9));
591 assert_eq!(entries.len(), 1);
592 }
593
594 #[test]
595 fn remove_hands_back_the_entry() {
596 let mut entries = Entries::utc().with([meeting(1, 3, 9), meeting(2, 4, 9)]);
597 let removed = entries.remove(EntryId(1));
598 assert_eq!(
599 removed.map(|changed| (changed.change, changed.entry)),
600 Some((Change::Removed, meeting(1, 3, 9)))
601 );
602 assert_eq!(entries.remove(EntryId(1)), None);
603 assert_eq!(entries.len(), 1);
604 assert!(entries.get(EntryId(2)).is_some());
605 }
606
607 #[test]
608 fn next_id_is_unused() {
609 let mut entries = Entries::utc();
610 assert!(entries.is_empty());
611 assert_eq!(entries.next_id(), EntryId(0));
612 let _ = entries.insert(meeting(7, 3, 9));
613 assert_eq!(entries.next_id(), EntryId(8));
614 let _ = entries.insert(meeting(u64::MAX, 3, 9));
615 assert_eq!(entries.next_id(), EntryId(u64::MAX));
616 }
617
618 #[test]
619 fn a_removed_entry_never_gives_its_id_back() {
620 let mut entries = Entries::utc().with([meeting(1, 3, 9), meeting(2, 3, 10)]);
621 assert_eq!(entries.next_id(), EntryId(3));
622 let _ = entries.remove(EntryId(2));
623 assert_eq!(entries.next_id(), EntryId(3), "2 was used");
624 let _ = entries.remove(EntryId(1));
625 assert_eq!(entries.next_id(), EntryId(3));
626 assert_eq!(entries, Entries::utc());
628 }
629
630 #[test]
631 fn icon_emphasis_and_lock_default_off_and_can_be_set() {
632 let entry = meeting(1, 3, 9);
633 assert_eq!(entry.icon_of(), None);
634 assert_eq!(entry.icon_label_of(), None);
635 assert_eq!(entry.emphasis_of(), Emphasis::Solid);
636 assert!(!entry.is_locked());
637 let entry = entry
638 .icon(crate::lucide!(Users))
639 .icon_label(" Team entry ")
640 .emphasis(Emphasis::Outlined)
641 .locked(true);
642 assert_eq!(entry.icon_of().map(Glyph::name), Some("users"));
643 assert_eq!(entry.icon_label_of(), Some("Team entry"));
644 assert_eq!(entry.emphasis_of(), Emphasis::Outlined);
645 assert!(entry.is_locked());
646 assert_eq!(entry.icon_label("").icon_label_of(), None);
647 assert_eq!(Emphasis::ALL.len(), 5);
648 }
649
650 #[test]
651 fn occurrences_overlap_the_range_and_come_in_order() {
652 let entries = Entries::utc().with([
653 meeting(1, 5, 9),
654 meeting(2, 3, 14),
655 meeting(3, 3, 9),
656 Entry::all_day(EntryId(4), "Trip", date(2026, 11, 2), date(2026, 11, 3)),
657 ]);
658 let found = entries.on(date(2026, 11, 3));
659 let ids: Vec<_> = found.iter().map(|occurrence| occurrence.entry.0).collect();
660 assert_eq!(ids, vec![4, 3, 2]);
661 assert!(found[0].all_day);
662 assert!(!found[1].all_day);
663
664 let week = entries.between(date(2026, 11, 2), date(2026, 11, 8));
665 assert_eq!(week.len(), 4);
666 assert!(entries.on(date(2026, 11, 4)).is_empty());
667 }
668
669 #[test]
670 fn an_entry_ending_at_midnight_does_not_touch_the_next_day() {
671 let entries = Entries::utc().with([Entry::new(EntryId(1), "Late", at(3, 22), at(4, 0))]);
672 assert_eq!(entries.on(date(2026, 11, 3)).len(), 1);
673 assert!(entries.on(date(2026, 11, 4)).is_empty());
674 let occurrence = entries.on(date(2026, 11, 3))[0];
675 assert_eq!(
676 occurrence.dates(&TimeZone::UTC),
677 (date(2026, 11, 3), date(2026, 11, 3))
678 );
679 assert_eq!(occurrence.duration(), SignedDuration::from_hours(2));
680 }
681
682 #[test]
683 fn an_entry_with_no_length_sits_on_its_day() {
684 let entries =
685 Entries::utc().with([Entry::new(EntryId(1), "Deadline", at(3, 17), at(3, 17))]);
686 let found = entries.on(date(2026, 11, 3));
687 assert_eq!(found.len(), 1);
688 assert_eq!(
689 found[0].dates(&TimeZone::UTC),
690 (date(2026, 11, 3), date(2026, 11, 3))
691 );
692 }
693}