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 self.notes = filled(notes.into());
168 self
169 }
170
171 pub fn tone(mut self, tone: Tone) -> Self {
172 self.tone = tone;
173 self
174 }
175
176 pub fn tag(mut self, tag: impl Into<String>) -> Self {
179 self.tag = Some(tag.into());
180 self
181 }
182
183 pub fn repeat(mut self, repeat: Repeat) -> Self {
186 self.repeat = Some(repeat);
187 self
188 }
189
190 pub fn titled(mut self, title: impl Into<String>) -> Self {
192 self.title = title.into();
193 self
194 }
195
196 pub fn rescheduled(mut self, when: When) -> Self {
199 self.when = when;
200 self
201 }
202
203 pub fn id(&self) -> EntryId {
204 self.id
205 }
206
207 pub fn title(&self) -> &str {
208 &self.title
209 }
210
211 pub fn when(&self) -> When {
213 self.when
214 }
215
216 pub fn tone_of(&self) -> Tone {
217 self.tone
218 }
219
220 pub fn tag_of(&self) -> Option<&str> {
221 self.tag.as_deref()
222 }
223
224 pub fn repeat_of(&self) -> Option<Repeat> {
225 self.repeat
226 }
227
228 pub fn location_of(&self) -> Option<&str> {
229 self.location.as_deref()
230 }
231
232 pub fn notes_of(&self) -> Option<&str> {
233 self.notes.as_deref()
234 }
235
236 pub fn is_all_day(&self) -> bool {
237 self.when.is_all_day()
238 }
239
240 pub fn icon_of(&self) -> Option<Glyph> {
241 self.marker.as_ref()?.glyph
242 }
243
244 pub fn emphasis_of(&self) -> Emphasis {
245 self.emphasis
246 }
247
248 pub fn is_locked(&self) -> bool {
249 self.locked
250 }
251}
252
253#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
256pub struct Occurrence {
257 pub entry: EntryId,
258 pub index: u32,
260 pub start: Timestamp,
261 pub end: Timestamp,
263 pub all_day: bool,
264}
265
266impl Occurrence {
267 pub fn duration(&self) -> SignedDuration {
268 self.end.duration_since(self.start)
269 }
270
271 pub fn dates(&self, time_zone: &TimeZone) -> (Date, Date) {
273 let first = date_of(self.start, time_zone);
274 if self.end <= self.start {
275 return (first, first);
276 }
277 let last_instant = self
278 .end
279 .saturating_sub(SignedDuration::from_nanos(1))
280 .unwrap_or(self.end);
281 (first, date_of(last_instant, time_zone).max(first))
282 }
283}
284
285#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
288pub struct Draft {
289 pub when: When,
290}
291
292#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
294pub enum Change {
295 Created,
296 Updated,
297 Removed,
298}
299
300impl Change {
301 pub const ALL: [Change; 3] = [Change::Created, Change::Updated, Change::Removed];
302}
303
304#[derive(Debug, Clone, PartialEq, Eq)]
306pub struct Changed {
307 pub change: Change,
308 pub entry: Entry,
310 pub before: Option<Entry>,
312}
313
314#[derive(Debug, Clone)]
319pub struct Entries {
320 items: Vec<Entry>,
321 time_zone: TimeZone,
322 next: u64,
324}
325
326impl PartialEq for Entries {
327 fn eq(&self, other: &Self) -> bool {
328 self.items == other.items && self.time_zone == other.time_zone
329 }
330}
331
332impl Eq for Entries {}
333
334impl Default for Entries {
335 fn default() -> Self {
336 Self::utc()
337 }
338}
339
340impl Entries {
341 pub fn new(time_zone: TimeZone) -> Self {
343 Self {
344 items: Vec::new(),
345 time_zone,
346 next: 0,
347 }
348 }
349
350 pub fn utc() -> Self {
352 Self::new(TimeZone::UTC)
353 }
354
355 pub fn system() -> Self {
358 Self::new(TimeZone::system())
359 }
360
361 pub fn with(mut self, entries: impl IntoIterator<Item = Entry>) -> Self {
364 for entry in entries {
365 let _ = self.insert(entry);
366 }
367 self
368 }
369
370 pub fn time_zone(&self) -> &TimeZone {
371 &self.time_zone
372 }
373
374 pub fn len(&self) -> usize {
375 self.items.len()
376 }
377
378 pub fn is_empty(&self) -> bool {
379 self.items.is_empty()
380 }
381
382 pub fn iter(&self) -> impl Iterator<Item = &Entry> {
383 self.items.iter()
384 }
385
386 pub fn get(&self, id: EntryId) -> Option<&Entry> {
387 self.items.iter().find(|entry| entry.id == id)
388 }
389
390 pub fn next_id(&self) -> EntryId {
394 EntryId(self.next)
395 }
396
397 pub fn insert(&mut self, entry: Entry) -> Option<Changed> {
400 self.next = self.next.max(entry.id.0.saturating_add(1));
401 let Some(existing) = self.items.iter_mut().find(|item| item.id == entry.id) else {
402 self.items.push(entry.clone());
403 return Some(Changed {
404 change: Change::Created,
405 entry,
406 before: None,
407 });
408 };
409 if *existing == entry {
410 return None;
411 }
412 let before = std::mem::replace(existing, entry.clone());
413 Some(Changed {
414 change: Change::Updated,
415 entry,
416 before: Some(before),
417 })
418 }
419
420 pub fn remove(&mut self, id: EntryId) -> Option<Changed> {
422 let index = self.items.iter().position(|entry| entry.id == id)?;
423 Some(Changed {
424 change: Change::Removed,
425 entry: self.items.remove(index),
426 before: None,
427 })
428 }
429
430 pub fn date_of(&self, instant: Timestamp) -> Date {
432 date_of(instant, &self.time_zone)
433 }
434
435 pub fn midnight(&self, date: Date) -> Timestamp {
437 midnight(date, &self.time_zone)
438 }
439
440 pub fn occurrences(&self, from: Timestamp, to: Timestamp) -> Vec<Occurrence> {
443 let mut found: Vec<Occurrence> = self
444 .items
445 .iter()
446 .flat_map(|entry| repeat::occurrences(entry, &self.time_zone, from, to))
447 .collect();
448 found.sort_by_key(|occurrence| (occurrence.start, occurrence.entry));
449 found
450 }
451
452 pub fn between(&self, first: Date, last: Date) -> Vec<Occurrence> {
455 self.occurrences(self.midnight(first), self.midnight(next_day(last)))
456 }
457
458 pub fn on(&self, date: Date) -> Vec<Occurrence> {
460 self.between(date, date)
461 }
462}
463
464#[cfg(test)]
465mod tests {
466 use super::*;
467 use jiff::civil::date;
468
469 fn at(day: i8, hour: i8) -> Timestamp {
470 date(2026, 11, day)
471 .at(hour, 0, 0, 0)
472 .to_zoned_datetime(TimeZone::UTC)
473 .map(|zoned| zoned.timestamp())
474 .unwrap_or_default()
475 }
476
477 fn meeting(id: u64, day: i8, hour: i8) -> Entry {
478 Entry::new(EntryId(id), "Meeting", at(day, hour), at(day, hour + 1))
479 }
480
481 #[test]
482 fn days_are_added_and_stop_at_the_ends_of_time() {
483 let day = date(2026, 11, 3);
484 assert_eq!(add_days(day, 1), date(2026, 11, 4));
485 assert_eq!(add_days(day, -3), date(2026, 10, 31));
486 assert_eq!(add_days(day, 0), day);
487 assert_eq!(add_days(day, i32::MAX), Date::MAX);
488 assert_eq!(add_days(day, i32::MIN), Date::MIN);
489 assert_eq!(add_days(Date::MAX, 1), Date::MAX);
490 assert_eq!(next_day(date(2026, 12, 31)), date(2027, 1, 1));
491 }
492
493 #[test]
494 fn spans_are_put_in_order() {
495 assert_eq!(
496 When::timed(at(3, 10), at(3, 9)),
497 When::Timed {
498 start: at(3, 9),
499 end: at(3, 10)
500 }
501 );
502 assert_eq!(
503 When::all_day(date(2026, 11, 5), date(2026, 11, 3)),
504 When::AllDay {
505 first: date(2026, 11, 3),
506 last: date(2026, 11, 5)
507 }
508 );
509 }
510
511 #[test]
512 fn whole_days_run_from_midnight_to_the_midnight_after_the_last_day() {
513 let when = When::all_day(date(2026, 11, 3), date(2026, 11, 4));
514 assert!(when.is_all_day());
515 assert_eq!(when.start(&TimeZone::UTC), at(3, 0));
516 assert_eq!(when.end(&TimeZone::UTC), at(5, 0));
517 assert_eq!(When::day(date(2026, 11, 3)).end(&TimeZone::UTC), at(4, 0));
518 }
519
520 #[test]
521 fn whole_days_follow_the_time_zone() {
522 let Ok(tokyo) = TimeZone::get("Asia/Tokyo") else {
523 panic!("the time zone database is bundled for tests");
524 };
525 let when = When::day(date(2026, 11, 3));
526 assert_eq!(when.start(&tokyo), at(2, 15));
528 assert_eq!(date_of(at(2, 15), &tokyo), date(2026, 11, 3));
529 assert_eq!(date_of(at(2, 14), &tokyo), date(2026, 11, 2));
530 }
531
532 #[test]
533 fn entry_builder_defaults_and_options() {
534 let entry = meeting(1, 3, 9);
535 assert_eq!(entry.id(), EntryId(1));
536 assert_eq!(entry.title(), "Meeting");
537 assert_eq!(entry.tone_of(), Tone::Primary);
538 assert_eq!(entry.tag_of(), None);
539 assert_eq!(entry.repeat_of(), None);
540 assert!(!entry.is_all_day());
541
542 let entry = entry
543 .tone(Tone::Warning)
544 .tag("work")
545 .repeat(Repeat::daily())
546 .titled("Review")
547 .rescheduled(When::day(date(2026, 11, 9)));
548 assert_eq!(entry.tone_of(), Tone::Warning);
549 assert_eq!(entry.tag_of(), Some("work"));
550 assert_eq!(entry.repeat_of(), Some(Repeat::daily()));
551 assert_eq!(entry.title(), "Review");
552 assert!(entry.is_all_day());
553 }
554
555 #[test]
556 fn location_and_notes_are_trimmed_and_blank_clears_them() {
557 let entry = meeting(1, 3, 9);
558 assert_eq!(entry.location_of(), None);
559 assert_eq!(entry.notes_of(), None);
560
561 let entry = entry
562 .location(" Room 4 ")
563 .notes("Bring the plan\nand the figures\n");
564 assert_eq!(entry.location_of(), Some("Room 4"));
565 assert_eq!(entry.notes_of(), Some("Bring the plan\nand the figures"));
566
567 let entry = entry.location(" ").notes("");
568 assert_eq!(entry.location_of(), None);
569 assert_eq!(entry.notes_of(), None);
570 }
571
572 #[test]
573 fn insert_reports_created_updated_and_unchanged() {
574 let mut entries = Entries::utc();
575 let created = entries.insert(meeting(1, 3, 9));
576 assert_eq!(created.map(|changed| changed.change), Some(Change::Created));
577
578 assert_eq!(entries.insert(meeting(1, 3, 9)), None);
579
580 let updated = entries.insert(meeting(1, 4, 9));
581 let Some(updated) = updated else {
582 panic!("a moved entry is an update");
583 };
584 assert_eq!(updated.change, Change::Updated);
585 assert_eq!(updated.before, Some(meeting(1, 3, 9)));
586 assert_eq!(updated.entry, meeting(1, 4, 9));
587 assert_eq!(entries.len(), 1);
588 }
589
590 #[test]
591 fn remove_hands_back_the_entry() {
592 let mut entries = Entries::utc().with([meeting(1, 3, 9), meeting(2, 4, 9)]);
593 let removed = entries.remove(EntryId(1));
594 assert_eq!(
595 removed.map(|changed| (changed.change, changed.entry)),
596 Some((Change::Removed, meeting(1, 3, 9)))
597 );
598 assert_eq!(entries.remove(EntryId(1)), None);
599 assert_eq!(entries.len(), 1);
600 assert!(entries.get(EntryId(2)).is_some());
601 }
602
603 #[test]
604 fn next_id_is_unused() {
605 let mut entries = Entries::utc();
606 assert!(entries.is_empty());
607 assert_eq!(entries.next_id(), EntryId(0));
608 let _ = entries.insert(meeting(7, 3, 9));
609 assert_eq!(entries.next_id(), EntryId(8));
610 let _ = entries.insert(meeting(u64::MAX, 3, 9));
611 assert_eq!(entries.next_id(), EntryId(u64::MAX));
612 }
613
614 #[test]
615 fn a_removed_entry_never_gives_its_id_back() {
616 let mut entries = Entries::utc().with([meeting(1, 3, 9), meeting(2, 3, 10)]);
617 assert_eq!(entries.next_id(), EntryId(3));
618 let _ = entries.remove(EntryId(2));
619 assert_eq!(entries.next_id(), EntryId(3), "2 was used");
620 let _ = entries.remove(EntryId(1));
621 assert_eq!(entries.next_id(), EntryId(3));
622 assert_eq!(entries, Entries::utc());
624 }
625
626 #[test]
627 fn icon_emphasis_and_lock_default_off_and_can_be_set() {
628 let entry = meeting(1, 3, 9);
629 assert_eq!(entry.icon_of(), None);
630 assert_eq!(entry.icon_label_of(), None);
631 assert_eq!(entry.emphasis_of(), Emphasis::Solid);
632 assert!(!entry.is_locked());
633 let entry = entry
634 .icon(crate::lucide!(Users))
635 .icon_label(" Team entry ")
636 .emphasis(Emphasis::Outlined)
637 .locked(true);
638 assert_eq!(entry.icon_of().map(Glyph::name), Some("users"));
639 assert_eq!(entry.icon_label_of(), Some("Team entry"));
640 assert_eq!(entry.emphasis_of(), Emphasis::Outlined);
641 assert!(entry.is_locked());
642 assert_eq!(entry.icon_label("").icon_label_of(), None);
643 assert_eq!(Emphasis::ALL.len(), 5);
644 }
645
646 #[test]
647 fn occurrences_overlap_the_range_and_come_in_order() {
648 let entries = Entries::utc().with([
649 meeting(1, 5, 9),
650 meeting(2, 3, 14),
651 meeting(3, 3, 9),
652 Entry::all_day(EntryId(4), "Trip", date(2026, 11, 2), date(2026, 11, 3)),
653 ]);
654 let found = entries.on(date(2026, 11, 3));
655 let ids: Vec<_> = found.iter().map(|occurrence| occurrence.entry.0).collect();
656 assert_eq!(ids, vec![4, 3, 2]);
657 assert!(found[0].all_day);
658 assert!(!found[1].all_day);
659
660 let week = entries.between(date(2026, 11, 2), date(2026, 11, 8));
661 assert_eq!(week.len(), 4);
662 assert!(entries.on(date(2026, 11, 4)).is_empty());
663 }
664
665 #[test]
666 fn an_entry_ending_at_midnight_does_not_touch_the_next_day() {
667 let entries = Entries::utc().with([Entry::new(EntryId(1), "Late", at(3, 22), at(4, 0))]);
668 assert_eq!(entries.on(date(2026, 11, 3)).len(), 1);
669 assert!(entries.on(date(2026, 11, 4)).is_empty());
670 let occurrence = entries.on(date(2026, 11, 3))[0];
671 assert_eq!(
672 occurrence.dates(&TimeZone::UTC),
673 (date(2026, 11, 3), date(2026, 11, 3))
674 );
675 assert_eq!(occurrence.duration(), SignedDuration::from_hours(2));
676 }
677
678 #[test]
679 fn an_entry_with_no_length_sits_on_its_day() {
680 let entries =
681 Entries::utc().with([Entry::new(EntryId(1), "Deadline", at(3, 17), at(3, 17))]);
682 let found = entries.on(date(2026, 11, 3));
683 assert_eq!(found.len(), 1);
684 assert_eq!(
685 found[0].dates(&TimeZone::UTC),
686 (date(2026, 11, 3), date(2026, 11, 3))
687 );
688 }
689}