Skip to main content

iced_cube/data/calendar/
repeat.rs

1//! Repeating entries: how often, and expanding them into occurrences.
2//!
3//! The rules live in [`rules`], which has no GUI
4//! dependency. This module applies them to an [`Entry`].
5
6use jiff::Timestamp;
7use jiff::tz::TimeZone;
8
9pub use super::rules::{Ends, Frequency, Instance, MAX_OCCURRENCES, Repeat};
10
11use super::entry::{Entry, Occurrence};
12use super::rules;
13
14fn occurrence(entry: &Entry, instance: Instance) -> Occurrence {
15    Occurrence {
16        entry: entry.id(),
17        index: instance.index,
18        start: instance.start,
19        end: instance.end,
20        all_day: instance.all_day,
21    }
22}
23
24/// Occurrence `index` of `entry`, or `None` once the entry has stopped
25/// repeating or the date is out of range.
26pub fn nth(entry: &Entry, time_zone: &TimeZone, index: u32) -> Option<Occurrence> {
27    rules::nth(entry.when(), entry.repeat_of(), time_zone, index)
28        .map(|instance| occurrence(entry, instance))
29}
30
31/// The occurrences of `entry` that overlap the time from `from` up to
32/// `to`, earliest first. At most [`MAX_OCCURRENCES`] are returned.
33pub fn occurrences(
34    entry: &Entry,
35    time_zone: &TimeZone,
36    from: Timestamp,
37    to: Timestamp,
38) -> Vec<Occurrence> {
39    rules::occurrences(entry.when(), entry.repeat_of(), time_zone, from, to)
40        .into_iter()
41        .map(|instance| occurrence(entry, instance))
42        .collect()
43}
44
45#[cfg(test)]
46mod tests {
47    use super::*;
48    use crate::data::calendar::entry::EntryId;
49    use jiff::SignedDuration;
50    use jiff::civil::{Date, date, time};
51
52    fn utc(year: i16, month: i8, day: i8, hour: i8) -> Timestamp {
53        zoned(&TimeZone::UTC, year, month, day, hour)
54    }
55
56    fn zoned(time_zone: &TimeZone, year: i16, month: i8, day: i8, hour: i8) -> Timestamp {
57        date(year, month, day)
58            .at(hour, 0, 0, 0)
59            .to_zoned_datetime(time_zone.clone())
60            .map(|zoned| zoned.timestamp())
61            .unwrap_or_default()
62    }
63
64    fn timed(start: Timestamp, repeat: Repeat) -> Entry {
65        let end = start
66            .checked_add(SignedDuration::from_hours(1))
67            .unwrap_or(start);
68        Entry::new(EntryId(1), "Repeats", start, end).repeat(repeat)
69    }
70
71    fn start_dates(entry: &Entry, time_zone: &TimeZone, count: u32) -> Vec<Date> {
72        (0..count)
73            .filter_map(|index| nth(entry, time_zone, index))
74            .map(|occurrence| occurrence.start.to_zoned_datetime(time_zone.clone()).date())
75            .collect()
76    }
77
78    #[test]
79    fn builder_defaults_and_options() {
80        for frequency in Frequency::ALL {
81            let repeat = Repeat::new(frequency);
82            assert_eq!(repeat.frequency(), frequency);
83            assert_eq!(repeat.every(), 1);
84            assert_eq!(repeat.ends(), Ends::Never);
85        }
86        assert_eq!(Repeat::daily().frequency(), Frequency::Daily);
87        assert_eq!(Repeat::weekly().frequency(), Frequency::Weekly);
88        assert_eq!(Repeat::monthly().frequency(), Frequency::Monthly);
89        assert_eq!(Repeat::yearly().frequency(), Frequency::Yearly);
90        assert_eq!(Repeat::daily().interval(0).every(), 1);
91        assert_eq!(Repeat::daily().interval(3).every(), 3);
92        assert_eq!(Repeat::daily().count(4).ends(), Ends::After(4));
93        let stop = date(2026, 12, 1);
94        assert_eq!(Repeat::daily().until(stop).ends(), Ends::On(stop));
95    }
96
97    #[test]
98    fn an_entry_that_does_not_repeat_has_one_occurrence() {
99        let start = utc(2026, 11, 3, 9);
100        let end = utc(2026, 11, 3, 10);
101        let entry = Entry::new(EntryId(1), "Once", start, end);
102        let first = nth(&entry, &TimeZone::UTC, 0);
103        assert_eq!(
104            first.map(|o| (o.entry, o.index, o.start, o.end)),
105            Some((EntryId(1), 0, start, end))
106        );
107        assert_eq!(nth(&entry, &TimeZone::UTC, 1), None);
108    }
109
110    #[test]
111    fn daily_and_weekly_step_by_their_interval() {
112        let daily = timed(utc(2026, 11, 3, 9), Repeat::daily().interval(2));
113        assert_eq!(
114            start_dates(&daily, &TimeZone::UTC, 3),
115            vec![date(2026, 11, 3), date(2026, 11, 5), date(2026, 11, 7)]
116        );
117        let weekly = timed(utc(2026, 11, 3, 9), Repeat::weekly());
118        assert_eq!(
119            start_dates(&weekly, &TimeZone::UTC, 3),
120            vec![date(2026, 11, 3), date(2026, 11, 10), date(2026, 11, 17)]
121        );
122    }
123
124    #[test]
125    fn monthly_on_the_31st_uses_the_last_day_of_short_months() {
126        let entry = timed(utc(2027, 1, 31, 9), Repeat::monthly());
127        assert_eq!(
128            start_dates(&entry, &TimeZone::UTC, 4),
129            vec![
130                date(2027, 1, 31),
131                date(2027, 2, 28),
132                date(2027, 3, 31),
133                date(2027, 4, 30)
134            ]
135        );
136    }
137
138    #[test]
139    fn yearly_on_a_leap_day_falls_back_to_the_28th() {
140        let entry = Entry::all_day(EntryId(1), "Leap", date(2028, 2, 29), date(2028, 2, 29))
141            .repeat(Repeat::yearly());
142        assert_eq!(
143            start_dates(&entry, &TimeZone::UTC, 5),
144            vec![
145                date(2028, 2, 29),
146                date(2029, 2, 28),
147                date(2030, 2, 28),
148                date(2031, 2, 28),
149                date(2032, 2, 29)
150            ]
151        );
152    }
153
154    #[test]
155    fn a_timed_entry_keeps_its_local_time_across_a_clock_change() {
156        let Ok(london) = TimeZone::get("Europe/London") else {
157            panic!("the time zone database is bundled for tests");
158        };
159        // The clocks go forward on 28 March 2027.
160        let entry = timed(zoned(&london, 2027, 3, 27, 9), Repeat::daily());
161        for index in 0..3 {
162            let Some(occurrence) = nth(&entry, &london, index) else {
163                panic!("occurrence {index}");
164            };
165            let local = occurrence.start.to_zoned_datetime(london.clone());
166            assert_eq!(local.time(), time(9, 0, 0, 0), "{index}");
167            assert_eq!(occurrence.duration(), SignedDuration::from_hours(1));
168        }
169        let before = nth(&entry, &london, 0).map(|o| o.start);
170        let after = nth(&entry, &london, 1).map(|o| o.start);
171        let (Some(before), Some(after)) = (before, after) else {
172            panic!("two occurrences");
173        };
174        assert_eq!(after.duration_since(before), SignedDuration::from_hours(23));
175    }
176
177    #[test]
178    fn count_and_until_stop_the_series() {
179        let counted = timed(utc(2026, 11, 3, 9), Repeat::daily().count(3));
180        assert!(nth(&counted, &TimeZone::UTC, 2).is_some());
181        assert_eq!(nth(&counted, &TimeZone::UTC, 3), None);
182
183        let until = timed(
184            utc(2026, 11, 3, 9),
185            Repeat::daily().until(date(2026, 11, 5)),
186        );
187        assert_eq!(
188            start_dates(&until, &TimeZone::UTC, 10),
189            vec![date(2026, 11, 3), date(2026, 11, 4), date(2026, 11, 5)]
190        );
191
192        let never = timed(utc(2026, 11, 3, 9), Repeat::daily().count(0));
193        assert_eq!(nth(&never, &TimeZone::UTC, 0), None);
194    }
195
196    #[test]
197    fn whole_day_occurrences_keep_their_length() {
198        let entry = Entry::all_day(EntryId(1), "Sprint", date(2026, 11, 2), date(2026, 11, 4))
199            .repeat(Repeat::weekly().interval(2));
200        let Some(second) = nth(&entry, &TimeZone::UTC, 1) else {
201            panic!("second occurrence");
202        };
203        assert!(second.all_day);
204        assert_eq!(second.start, utc(2026, 11, 16, 0));
205        assert_eq!(second.end, utc(2026, 11, 19, 0));
206    }
207
208    #[test]
209    fn a_range_only_gets_the_occurrences_that_overlap_it() {
210        let entry = timed(utc(2026, 11, 3, 9), Repeat::daily());
211        let found = occurrences(
212            &entry,
213            &TimeZone::UTC,
214            utc(2026, 11, 10, 0),
215            utc(2026, 11, 12, 0),
216        );
217        let indices: Vec<_> = found.iter().map(|o| o.index).collect();
218        assert_eq!(indices, vec![7, 8]);
219
220        let before_it_starts = occurrences(
221            &entry,
222            &TimeZone::UTC,
223            utc(2026, 10, 1, 0),
224            utc(2026, 11, 1, 0),
225        );
226        assert!(before_it_starts.is_empty());
227    }
228
229    #[test]
230    fn a_range_far_from_the_start_is_found_without_walking_there() {
231        let entry = timed(utc(1990, 1, 1, 9), Repeat::daily());
232        let found = occurrences(
233            &entry,
234            &TimeZone::UTC,
235            utc(2026, 11, 3, 0),
236            utc(2026, 11, 4, 0),
237        );
238        assert_eq!(found.len(), 1);
239        assert_eq!(found[0].start, utc(2026, 11, 3, 9));
240
241        let monthly = timed(utc(1990, 1, 31, 9), Repeat::monthly());
242        let found = occurrences(
243            &monthly,
244            &TimeZone::UTC,
245            utc(2026, 11, 1, 0),
246            utc(2026, 12, 1, 0),
247        );
248        assert_eq!(found.len(), 1);
249        assert_eq!(found[0].start, utc(2026, 11, 30, 9));
250    }
251
252    #[test]
253    fn a_range_with_too_many_occurrences_is_capped() {
254        let entry = timed(utc(2000, 1, 1, 9), Repeat::daily());
255        let found = occurrences(
256            &entry,
257            &TimeZone::UTC,
258            utc(2000, 1, 1, 0),
259            utc(2100, 1, 1, 0),
260        );
261        assert_eq!(found.len(), MAX_OCCURRENCES);
262    }
263
264    #[test]
265    fn a_finished_series_gives_nothing_later() {
266        let entry = timed(utc(2026, 11, 3, 9), Repeat::weekly().count(2));
267        let found = occurrences(
268            &entry,
269            &TimeZone::UTC,
270            utc(2026, 12, 1, 0),
271            utc(2027, 1, 1, 0),
272        );
273        assert!(found.is_empty());
274    }
275}