Skip to main content

iced_cube/data/calendar/
entry.rs

1//! Calendar entries and the collection that holds them.
2
3use jiff::civil::{Date, Time};
4use jiff::tz::TimeZone;
5use jiff::{SignedDuration, Span, Timestamp};
6
7use super::repeat::{self, Repeat};
8
9/// Identifies an entry. The app chooses the number, usually its own
10/// record id, or takes a free one from [`Entries::next_id`].
11#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
12pub struct EntryId(pub u64);
13
14/// The colour of an entry, taken from the theme's tokens.
15#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
16pub enum Tone {
17    #[default]
18    Primary,
19    Neutral,
20    Success,
21    Warning,
22    Destructive,
23}
24
25impl Tone {
26    pub const ALL: [Tone; 5] = [
27        Tone::Primary,
28        Tone::Neutral,
29        Tone::Success,
30        Tone::Warning,
31        Tone::Destructive,
32    ];
33}
34
35/// When an entry happens.
36#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
37pub enum When {
38    /// From one instant to another. `end` is not part of the entry, so an
39    /// entry ending at 10:00 does not overlap one starting at 10:00.
40    Timed { start: Timestamp, end: Timestamp },
41    /// Whole days, from `first` to `last` inclusive, in whatever time zone
42    /// the calendar shows.
43    AllDay { first: Date, last: Date },
44}
45
46impl When {
47    /// A timed span. The two instants are put in order.
48    pub fn timed(start: Timestamp, end: Timestamp) -> Self {
49        When::Timed {
50            start: start.min(end),
51            end: start.max(end),
52        }
53    }
54
55    /// Whole days. The two dates are put in order.
56    pub fn all_day(first: Date, last: Date) -> Self {
57        When::AllDay {
58            first: first.min(last),
59            last: first.max(last),
60        }
61    }
62
63    /// A single whole day.
64    pub fn day(date: Date) -> Self {
65        When::AllDay {
66            first: date,
67            last: date,
68        }
69    }
70
71    pub fn is_all_day(&self) -> bool {
72        matches!(self, When::AllDay { .. })
73    }
74
75    /// The first instant of the span in `time_zone`.
76    pub fn start(&self, time_zone: &TimeZone) -> Timestamp {
77        match *self {
78            When::Timed { start, .. } => start,
79            When::AllDay { first, .. } => midnight(first, time_zone),
80        }
81    }
82
83    /// The instant the span stops at in `time_zone`. For whole days this
84    /// is midnight after the last day.
85    pub fn end(&self, time_zone: &TimeZone) -> Timestamp {
86        match *self {
87            When::Timed { end, .. } => end,
88            When::AllDay { last, .. } => midnight(next_day(last), time_zone),
89        }
90    }
91}
92
93/// Midnight at the start of `date` in `time_zone`, or the first instant of
94/// the day when a clock change skips midnight.
95pub fn midnight(date: Date, time_zone: &TimeZone) -> Timestamp {
96    date.to_zoned_datetime(time_zone.clone())
97        .map(|zoned| zoned.timestamp())
98        .unwrap_or(Timestamp::MAX)
99}
100
101/// The instant it is `time` on `date` in `time_zone`. A time a clock
102/// change skips moves forward by the gap, and one that happens twice
103/// takes the first.
104///
105/// ```
106/// use iced_cube::data::calendar::instant;
107/// use jiff::civil::{date, time};
108/// use jiff::tz::TimeZone;
109///
110/// let nine = instant(date(2026, 11, 19), time(9, 0, 0, 0), &TimeZone::UTC);
111/// assert_eq!(nine.to_string(), "2026-11-19T09:00:00Z");
112/// ```
113pub fn instant(date: Date, time: Time, time_zone: &TimeZone) -> Timestamp {
114    date.to_datetime(time)
115        .to_zoned_datetime(time_zone.clone())
116        .map(|zoned| zoned.timestamp())
117        .unwrap_or_else(|_| midnight(date, time_zone))
118}
119
120/// The calendar date of `instant` in `time_zone`.
121pub fn date_of(instant: Timestamp, time_zone: &TimeZone) -> Date {
122    instant.to_zoned_datetime(time_zone.clone()).date()
123}
124
125/// `date` moved by `days`, stopping at the first or last date there is.
126pub fn add_days(date: Date, days: i32) -> Date {
127    match Span::new().try_days(i64::from(days)) {
128        Ok(span) => date.saturating_add(span),
129        Err(_) if days < 0 => Date::MIN,
130        Err(_) => Date::MAX,
131    }
132}
133
134pub(super) fn next_day(date: Date) -> Date {
135    add_days(date, 1)
136}
137
138/// Something on the calendar: a meeting, a deadline, a holiday.
139#[derive(Debug, Clone, PartialEq, Eq)]
140pub struct Entry {
141    id: EntryId,
142    title: String,
143    when: When,
144    tone: Tone,
145    tag: Option<String>,
146    repeat: Option<Repeat>,
147    location: Option<String>,
148    notes: Option<String>,
149}
150
151/// `text` without the space around it, or `None` when nothing is left.
152fn filled(text: String) -> Option<String> {
153    let trimmed = text.trim();
154    if trimmed.is_empty() {
155        return None;
156    }
157    Some(trimmed.to_owned())
158}
159
160impl Entry {
161    /// A timed entry from `start` up to `end`.
162    pub fn new(id: EntryId, title: impl Into<String>, start: Timestamp, end: Timestamp) -> Self {
163        Self::at(id, title, When::timed(start, end))
164    }
165
166    /// An entry covering whole days, `first` to `last` inclusive.
167    pub fn all_day(id: EntryId, title: impl Into<String>, first: Date, last: Date) -> Self {
168        Self::at(id, title, When::all_day(first, last))
169    }
170
171    /// An entry covering `when`.
172    pub fn at(id: EntryId, title: impl Into<String>, when: When) -> Self {
173        Self {
174            id,
175            title: title.into(),
176            when,
177            tone: Tone::default(),
178            tag: None,
179            repeat: None,
180            location: None,
181            notes: None,
182        }
183    }
184
185    /// Where the entry takes place. Blank text clears it.
186    pub fn location(mut self, location: impl Into<String>) -> Self {
187        self.location = filled(location.into());
188        self
189    }
190
191    /// Free text kept with the entry, which may run over several lines.
192    /// Blank text clears it.
193    pub fn notes(mut self, notes: impl Into<String>) -> Self {
194        self.notes = filled(notes.into());
195        self
196    }
197
198    pub fn tone(mut self, tone: Tone) -> Self {
199        self.tone = tone;
200        self
201    }
202
203    /// A label that triggers can be limited to, such as `"work"`. See
204    /// [`Scope::Tagged`](super::schedule::Scope::Tagged).
205    pub fn tag(mut self, tag: impl Into<String>) -> Self {
206        self.tag = Some(tag.into());
207        self
208    }
209
210    /// Makes the entry repeat. Every occurrence keeps the length of the
211    /// first.
212    pub fn repeat(mut self, repeat: Repeat) -> Self {
213        self.repeat = Some(repeat);
214        self
215    }
216
217    /// Replaces the title.
218    pub fn titled(mut self, title: impl Into<String>) -> Self {
219        self.title = title.into();
220        self
221    }
222
223    /// Moves the entry. A repeating entry moves as a whole, since `when` is
224    /// its first occurrence.
225    pub fn rescheduled(mut self, when: When) -> Self {
226        self.when = when;
227        self
228    }
229
230    pub fn id(&self) -> EntryId {
231        self.id
232    }
233
234    pub fn title(&self) -> &str {
235        &self.title
236    }
237
238    /// When the entry, or its first occurrence, happens.
239    pub fn when(&self) -> When {
240        self.when
241    }
242
243    pub fn tone_of(&self) -> Tone {
244        self.tone
245    }
246
247    pub fn tag_of(&self) -> Option<&str> {
248        self.tag.as_deref()
249    }
250
251    pub fn repeat_of(&self) -> Option<Repeat> {
252        self.repeat
253    }
254
255    pub fn location_of(&self) -> Option<&str> {
256        self.location.as_deref()
257    }
258
259    pub fn notes_of(&self) -> Option<&str> {
260        self.notes.as_deref()
261    }
262
263    pub fn is_all_day(&self) -> bool {
264        self.when.is_all_day()
265    }
266}
267
268/// One time an entry happens. An entry that does not repeat has a single
269/// occurrence with index 0.
270#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
271pub struct Occurrence {
272    pub entry: EntryId,
273    /// Which repetition this is, counted from 0.
274    pub index: u32,
275    pub start: Timestamp,
276    /// The instant the occurrence stops at, which is not part of it.
277    pub end: Timestamp,
278    pub all_day: bool,
279}
280
281impl Occurrence {
282    pub fn duration(&self) -> SignedDuration {
283        self.end.duration_since(self.start)
284    }
285
286    /// The first and last calendar dates the occurrence touches.
287    pub fn dates(&self, time_zone: &TimeZone) -> (Date, Date) {
288        let first = date_of(self.start, time_zone);
289        if self.end <= self.start {
290            return (first, first);
291        }
292        let last_instant = self
293            .end
294            .saturating_sub(SignedDuration::from_nanos(1))
295            .unwrap_or(self.end);
296        (first, date_of(last_instant, time_zone).max(first))
297    }
298}
299
300/// A span the user asked for by clicking or dragging on empty space. The
301/// app turns it into an [`Entry`], usually after asking for a title.
302#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
303pub struct Draft {
304    pub when: When,
305}
306
307/// What happened to an entry.
308#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
309pub enum Change {
310    Created,
311    Updated,
312    Removed,
313}
314
315impl Change {
316    pub const ALL: [Change; 3] = [Change::Created, Change::Updated, Change::Removed];
317}
318
319/// A change made to [`Entries`].
320#[derive(Debug, Clone, PartialEq, Eq)]
321pub struct Changed {
322    pub change: Change,
323    /// The entry as it is now, or as it was when removed.
324    pub entry: Entry,
325    /// The entry before an update.
326    pub before: Option<Entry>,
327}
328
329/// The entries of a calendar and the time zone they are shown in.
330#[derive(Debug, Clone, PartialEq, Eq)]
331pub struct Entries {
332    items: Vec<Entry>,
333    time_zone: TimeZone,
334}
335
336impl Default for Entries {
337    fn default() -> Self {
338        Self::utc()
339    }
340}
341
342impl Entries {
343    /// An empty collection shown in `time_zone`.
344    pub fn new(time_zone: TimeZone) -> Self {
345        Self {
346            items: Vec::new(),
347            time_zone,
348        }
349    }
350
351    /// An empty collection shown in UTC.
352    pub fn utc() -> Self {
353        Self::new(TimeZone::UTC)
354    }
355
356    /// An empty collection shown in the system's time zone, or UTC when
357    /// the system does not say.
358    pub fn system() -> Self {
359        Self::new(TimeZone::system())
360    }
361
362    /// Adds entries while building. An entry with an id already present
363    /// replaces the earlier one.
364    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    /// An id no entry uses yet.
392    pub fn next_id(&self) -> EntryId {
393        let highest = self.items.iter().map(|entry| entry.id.0).max();
394        EntryId(highest.map_or(0, |id| id.saturating_add(1)))
395    }
396
397    /// Adds `entry`, or replaces the entry with the same id. Returns what
398    /// changed, or `None` when an identical entry was already there.
399    pub fn insert(&mut self, entry: Entry) -> Option<Changed> {
400        let Some(existing) = self.items.iter_mut().find(|item| item.id == entry.id) else {
401            self.items.push(entry.clone());
402            return Some(Changed {
403                change: Change::Created,
404                entry,
405                before: None,
406            });
407        };
408        if *existing == entry {
409            return None;
410        }
411        let before = std::mem::replace(existing, entry.clone());
412        Some(Changed {
413            change: Change::Updated,
414            entry,
415            before: Some(before),
416        })
417    }
418
419    /// Removes the entry with `id`, if there is one.
420    pub fn remove(&mut self, id: EntryId) -> Option<Changed> {
421        let index = self.items.iter().position(|entry| entry.id == id)?;
422        Some(Changed {
423            change: Change::Removed,
424            entry: self.items.remove(index),
425            before: None,
426        })
427    }
428
429    /// The calendar date of `instant` in the collection's time zone.
430    pub fn date_of(&self, instant: Timestamp) -> Date {
431        date_of(instant, &self.time_zone)
432    }
433
434    /// Midnight at the start of `date` in the collection's time zone.
435    pub fn midnight(&self, date: Date) -> Timestamp {
436        midnight(date, &self.time_zone)
437    }
438
439    /// Every occurrence that overlaps the time from `from` up to `to`,
440    /// earliest first. Repeating entries are expanded.
441    pub fn occurrences(&self, from: Timestamp, to: Timestamp) -> Vec<Occurrence> {
442        let mut found: Vec<Occurrence> = self
443            .items
444            .iter()
445            .flat_map(|entry| repeat::occurrences(entry, &self.time_zone, from, to))
446            .collect();
447        found.sort_by_key(|occurrence| (occurrence.start, occurrence.entry));
448        found
449    }
450
451    /// Every occurrence that touches a date from `first` to `last`
452    /// inclusive.
453    pub fn between(&self, first: Date, last: Date) -> Vec<Occurrence> {
454        self.occurrences(self.midnight(first), self.midnight(next_day(last)))
455    }
456
457    /// Every occurrence that touches `date`.
458    pub fn on(&self, date: Date) -> Vec<Occurrence> {
459        self.between(date, date)
460    }
461}
462
463#[cfg(test)]
464mod tests {
465    use super::*;
466    use jiff::civil::date;
467
468    fn at(day: i8, hour: i8) -> Timestamp {
469        date(2026, 11, day)
470            .at(hour, 0, 0, 0)
471            .to_zoned_datetime(TimeZone::UTC)
472            .map(|zoned| zoned.timestamp())
473            .unwrap_or_default()
474    }
475
476    fn meeting(id: u64, day: i8, hour: i8) -> Entry {
477        Entry::new(EntryId(id), "Meeting", at(day, hour), at(day, hour + 1))
478    }
479
480    #[test]
481    fn days_are_added_and_stop_at_the_ends_of_time() {
482        let day = date(2026, 11, 3);
483        assert_eq!(add_days(day, 1), date(2026, 11, 4));
484        assert_eq!(add_days(day, -3), date(2026, 10, 31));
485        assert_eq!(add_days(day, 0), day);
486        assert_eq!(add_days(day, i32::MAX), Date::MAX);
487        assert_eq!(add_days(day, i32::MIN), Date::MIN);
488        assert_eq!(add_days(Date::MAX, 1), Date::MAX);
489        assert_eq!(next_day(date(2026, 12, 31)), date(2027, 1, 1));
490    }
491
492    #[test]
493    fn spans_are_put_in_order() {
494        assert_eq!(
495            When::timed(at(3, 10), at(3, 9)),
496            When::Timed {
497                start: at(3, 9),
498                end: at(3, 10)
499            }
500        );
501        assert_eq!(
502            When::all_day(date(2026, 11, 5), date(2026, 11, 3)),
503            When::AllDay {
504                first: date(2026, 11, 3),
505                last: date(2026, 11, 5)
506            }
507        );
508    }
509
510    #[test]
511    fn whole_days_run_from_midnight_to_the_midnight_after_the_last_day() {
512        let when = When::all_day(date(2026, 11, 3), date(2026, 11, 4));
513        assert!(when.is_all_day());
514        assert_eq!(when.start(&TimeZone::UTC), at(3, 0));
515        assert_eq!(when.end(&TimeZone::UTC), at(5, 0));
516        assert_eq!(When::day(date(2026, 11, 3)).end(&TimeZone::UTC), at(4, 0));
517    }
518
519    #[test]
520    fn whole_days_follow_the_time_zone() {
521        let Ok(tokyo) = TimeZone::get("Asia/Tokyo") else {
522            panic!("the time zone database is bundled for tests");
523        };
524        let when = When::day(date(2026, 11, 3));
525        // Midnight in Tokyo is 15:00 the day before in UTC.
526        assert_eq!(when.start(&tokyo), at(2, 15));
527        assert_eq!(date_of(at(2, 15), &tokyo), date(2026, 11, 3));
528        assert_eq!(date_of(at(2, 14), &tokyo), date(2026, 11, 2));
529    }
530
531    #[test]
532    fn entry_builder_defaults_and_options() {
533        let entry = meeting(1, 3, 9);
534        assert_eq!(entry.id(), EntryId(1));
535        assert_eq!(entry.title(), "Meeting");
536        assert_eq!(entry.tone_of(), Tone::Primary);
537        assert_eq!(entry.tag_of(), None);
538        assert_eq!(entry.repeat_of(), None);
539        assert!(!entry.is_all_day());
540
541        let entry = entry
542            .tone(Tone::Warning)
543            .tag("work")
544            .repeat(Repeat::daily())
545            .titled("Review")
546            .rescheduled(When::day(date(2026, 11, 9)));
547        assert_eq!(entry.tone_of(), Tone::Warning);
548        assert_eq!(entry.tag_of(), Some("work"));
549        assert_eq!(entry.repeat_of(), Some(Repeat::daily()));
550        assert_eq!(entry.title(), "Review");
551        assert!(entry.is_all_day());
552    }
553
554    #[test]
555    fn location_and_notes_are_trimmed_and_blank_clears_them() {
556        let entry = meeting(1, 3, 9);
557        assert_eq!(entry.location_of(), None);
558        assert_eq!(entry.notes_of(), None);
559
560        let entry = entry
561            .location("  Room 4 ")
562            .notes("Bring the plan\nand the figures\n");
563        assert_eq!(entry.location_of(), Some("Room 4"));
564        assert_eq!(entry.notes_of(), Some("Bring the plan\nand the figures"));
565
566        let entry = entry.location("   ").notes("");
567        assert_eq!(entry.location_of(), None);
568        assert_eq!(entry.notes_of(), None);
569    }
570
571    #[test]
572    fn insert_reports_created_updated_and_unchanged() {
573        let mut entries = Entries::utc();
574        let created = entries.insert(meeting(1, 3, 9));
575        assert_eq!(created.map(|changed| changed.change), Some(Change::Created));
576
577        assert_eq!(entries.insert(meeting(1, 3, 9)), None);
578
579        let updated = entries.insert(meeting(1, 4, 9));
580        let Some(updated) = updated else {
581            panic!("a moved entry is an update");
582        };
583        assert_eq!(updated.change, Change::Updated);
584        assert_eq!(updated.before, Some(meeting(1, 3, 9)));
585        assert_eq!(updated.entry, meeting(1, 4, 9));
586        assert_eq!(entries.len(), 1);
587    }
588
589    #[test]
590    fn remove_hands_back_the_entry() {
591        let mut entries = Entries::utc().with([meeting(1, 3, 9), meeting(2, 4, 9)]);
592        let removed = entries.remove(EntryId(1));
593        assert_eq!(
594            removed.map(|changed| (changed.change, changed.entry)),
595            Some((Change::Removed, meeting(1, 3, 9)))
596        );
597        assert_eq!(entries.remove(EntryId(1)), None);
598        assert_eq!(entries.len(), 1);
599        assert!(entries.get(EntryId(2)).is_some());
600    }
601
602    #[test]
603    fn next_id_is_unused() {
604        let mut entries = Entries::utc();
605        assert!(entries.is_empty());
606        assert_eq!(entries.next_id(), EntryId(0));
607        let _ = entries.insert(meeting(7, 3, 9));
608        assert_eq!(entries.next_id(), EntryId(8));
609        let _ = entries.insert(meeting(u64::MAX, 3, 9));
610        assert_eq!(entries.next_id(), EntryId(u64::MAX));
611    }
612
613    #[test]
614    fn occurrences_overlap_the_range_and_come_in_order() {
615        let entries = Entries::utc().with([
616            meeting(1, 5, 9),
617            meeting(2, 3, 14),
618            meeting(3, 3, 9),
619            Entry::all_day(EntryId(4), "Trip", date(2026, 11, 2), date(2026, 11, 3)),
620        ]);
621        let found = entries.on(date(2026, 11, 3));
622        let ids: Vec<_> = found.iter().map(|occurrence| occurrence.entry.0).collect();
623        assert_eq!(ids, vec![4, 3, 2]);
624        assert!(found[0].all_day);
625        assert!(!found[1].all_day);
626
627        let week = entries.between(date(2026, 11, 2), date(2026, 11, 8));
628        assert_eq!(week.len(), 4);
629        assert!(entries.on(date(2026, 11, 4)).is_empty());
630    }
631
632    #[test]
633    fn an_entry_ending_at_midnight_does_not_touch_the_next_day() {
634        let entries = Entries::utc().with([Entry::new(EntryId(1), "Late", at(3, 22), at(4, 0))]);
635        assert_eq!(entries.on(date(2026, 11, 3)).len(), 1);
636        assert!(entries.on(date(2026, 11, 4)).is_empty());
637        let occurrence = entries.on(date(2026, 11, 3))[0];
638        assert_eq!(
639            occurrence.dates(&TimeZone::UTC),
640            (date(2026, 11, 3), date(2026, 11, 3))
641        );
642        assert_eq!(occurrence.duration(), SignedDuration::from_hours(2));
643    }
644
645    #[test]
646    fn an_entry_with_no_length_sits_on_its_day() {
647        let entries =
648            Entries::utc().with([Entry::new(EntryId(1), "Deadline", at(3, 17), at(3, 17))]);
649        let found = entries.on(date(2026, 11, 3));
650        assert_eq!(found.len(), 1);
651        assert_eq!(
652            found[0].dates(&TimeZone::UTC),
653            (date(2026, 11, 3), date(2026, 11, 3))
654        );
655    }
656}