iced-cube 0.0.15

Themeable application components for the iced GUI library, with Lucide icons
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
//! Calendar entries and the collection that holds them.

use jiff::civil::{Date, Time};
use jiff::tz::TimeZone;
use jiff::{SignedDuration, Span, Timestamp};

use super::repeat::{self, Repeat};

/// Identifies an entry. The app chooses the number, usually its own
/// record id, or takes a free one from [`Entries::next_id`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct EntryId(pub u64);

/// The colour of an entry, taken from the theme's tokens.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum Tone {
    #[default]
    Primary,
    Neutral,
    Success,
    Warning,
    Destructive,
}

impl Tone {
    pub const ALL: [Tone; 5] = [
        Tone::Primary,
        Tone::Neutral,
        Tone::Success,
        Tone::Warning,
        Tone::Destructive,
    ];
}

/// When an entry happens.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum When {
    /// From one instant to another. `end` is not part of the entry, so an
    /// entry ending at 10:00 does not overlap one starting at 10:00.
    Timed { start: Timestamp, end: Timestamp },
    /// Whole days, from `first` to `last` inclusive, in whatever time zone
    /// the calendar shows.
    AllDay { first: Date, last: Date },
}

impl When {
    /// A timed span. The two instants are put in order.
    pub fn timed(start: Timestamp, end: Timestamp) -> Self {
        When::Timed {
            start: start.min(end),
            end: start.max(end),
        }
    }

    /// Whole days. The two dates are put in order.
    pub fn all_day(first: Date, last: Date) -> Self {
        When::AllDay {
            first: first.min(last),
            last: first.max(last),
        }
    }

    /// A single whole day.
    pub fn day(date: Date) -> Self {
        When::AllDay {
            first: date,
            last: date,
        }
    }

    pub fn is_all_day(&self) -> bool {
        matches!(self, When::AllDay { .. })
    }

    /// The first instant of the span in `time_zone`.
    pub fn start(&self, time_zone: &TimeZone) -> Timestamp {
        match *self {
            When::Timed { start, .. } => start,
            When::AllDay { first, .. } => midnight(first, time_zone),
        }
    }

    /// The instant the span stops at in `time_zone`. For whole days this
    /// is midnight after the last day.
    pub fn end(&self, time_zone: &TimeZone) -> Timestamp {
        match *self {
            When::Timed { end, .. } => end,
            When::AllDay { last, .. } => midnight(next_day(last), time_zone),
        }
    }
}

/// Midnight at the start of `date` in `time_zone`, or the first instant of
/// the day when a clock change skips midnight.
pub fn midnight(date: Date, time_zone: &TimeZone) -> Timestamp {
    date.to_zoned_datetime(time_zone.clone())
        .map(|zoned| zoned.timestamp())
        .unwrap_or(Timestamp::MAX)
}

/// The instant it is `time` on `date` in `time_zone`. A time a clock
/// change skips moves forward by the gap, and one that happens twice
/// takes the first.
///
/// ```
/// use iced_cube::data::calendar::instant;
/// use jiff::civil::{date, time};
/// use jiff::tz::TimeZone;
///
/// let nine = instant(date(2026, 11, 19), time(9, 0, 0, 0), &TimeZone::UTC);
/// assert_eq!(nine.to_string(), "2026-11-19T09:00:00Z");
/// ```
pub fn instant(date: Date, time: Time, time_zone: &TimeZone) -> Timestamp {
    date.to_datetime(time)
        .to_zoned_datetime(time_zone.clone())
        .map(|zoned| zoned.timestamp())
        .unwrap_or_else(|_| midnight(date, time_zone))
}

/// The calendar date of `instant` in `time_zone`.
pub fn date_of(instant: Timestamp, time_zone: &TimeZone) -> Date {
    instant.to_zoned_datetime(time_zone.clone()).date()
}

/// `date` moved by `days`, stopping at the first or last date there is.
pub fn add_days(date: Date, days: i32) -> Date {
    match Span::new().try_days(i64::from(days)) {
        Ok(span) => date.saturating_add(span),
        Err(_) if days < 0 => Date::MIN,
        Err(_) => Date::MAX,
    }
}

pub(super) fn next_day(date: Date) -> Date {
    add_days(date, 1)
}

/// Something on the calendar: a meeting, a deadline, a holiday.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Entry {
    id: EntryId,
    title: String,
    when: When,
    tone: Tone,
    tag: Option<String>,
    repeat: Option<Repeat>,
    location: Option<String>,
    notes: Option<String>,
}

/// `text` without the space around it, or `None` when nothing is left.
fn filled(text: String) -> Option<String> {
    let trimmed = text.trim();
    if trimmed.is_empty() {
        return None;
    }
    Some(trimmed.to_owned())
}

impl Entry {
    /// A timed entry from `start` up to `end`.
    pub fn new(id: EntryId, title: impl Into<String>, start: Timestamp, end: Timestamp) -> Self {
        Self::at(id, title, When::timed(start, end))
    }

    /// An entry covering whole days, `first` to `last` inclusive.
    pub fn all_day(id: EntryId, title: impl Into<String>, first: Date, last: Date) -> Self {
        Self::at(id, title, When::all_day(first, last))
    }

    /// An entry covering `when`.
    pub fn at(id: EntryId, title: impl Into<String>, when: When) -> Self {
        Self {
            id,
            title: title.into(),
            when,
            tone: Tone::default(),
            tag: None,
            repeat: None,
            location: None,
            notes: None,
        }
    }

    /// Where the entry takes place. Blank text clears it.
    pub fn location(mut self, location: impl Into<String>) -> Self {
        self.location = filled(location.into());
        self
    }

    /// Free text kept with the entry, which may run over several lines.
    /// Blank text clears it.
    pub fn notes(mut self, notes: impl Into<String>) -> Self {
        self.notes = filled(notes.into());
        self
    }

    pub fn tone(mut self, tone: Tone) -> Self {
        self.tone = tone;
        self
    }

    /// A label that triggers can be limited to, such as `"work"`. See
    /// [`Scope::Tagged`](super::schedule::Scope::Tagged).
    pub fn tag(mut self, tag: impl Into<String>) -> Self {
        self.tag = Some(tag.into());
        self
    }

    /// Makes the entry repeat. Every occurrence keeps the length of the
    /// first.
    pub fn repeat(mut self, repeat: Repeat) -> Self {
        self.repeat = Some(repeat);
        self
    }

    /// Replaces the title.
    pub fn titled(mut self, title: impl Into<String>) -> Self {
        self.title = title.into();
        self
    }

    /// Moves the entry. A repeating entry moves as a whole, since `when` is
    /// its first occurrence.
    pub fn rescheduled(mut self, when: When) -> Self {
        self.when = when;
        self
    }

    pub fn id(&self) -> EntryId {
        self.id
    }

    pub fn title(&self) -> &str {
        &self.title
    }

    /// When the entry, or its first occurrence, happens.
    pub fn when(&self) -> When {
        self.when
    }

    pub fn tone_of(&self) -> Tone {
        self.tone
    }

    pub fn tag_of(&self) -> Option<&str> {
        self.tag.as_deref()
    }

    pub fn repeat_of(&self) -> Option<Repeat> {
        self.repeat
    }

    pub fn location_of(&self) -> Option<&str> {
        self.location.as_deref()
    }

    pub fn notes_of(&self) -> Option<&str> {
        self.notes.as_deref()
    }

    pub fn is_all_day(&self) -> bool {
        self.when.is_all_day()
    }
}

/// One time an entry happens. An entry that does not repeat has a single
/// occurrence with index 0.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Occurrence {
    pub entry: EntryId,
    /// Which repetition this is, counted from 0.
    pub index: u32,
    pub start: Timestamp,
    /// The instant the occurrence stops at, which is not part of it.
    pub end: Timestamp,
    pub all_day: bool,
}

impl Occurrence {
    pub fn duration(&self) -> SignedDuration {
        self.end.duration_since(self.start)
    }

    /// The first and last calendar dates the occurrence touches.
    pub fn dates(&self, time_zone: &TimeZone) -> (Date, Date) {
        let first = date_of(self.start, time_zone);
        if self.end <= self.start {
            return (first, first);
        }
        let last_instant = self
            .end
            .saturating_sub(SignedDuration::from_nanos(1))
            .unwrap_or(self.end);
        (first, date_of(last_instant, time_zone).max(first))
    }
}

/// A span the user asked for by clicking or dragging on empty space. The
/// app turns it into an [`Entry`], usually after asking for a title.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Draft {
    pub when: When,
}

/// What happened to an entry.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Change {
    Created,
    Updated,
    Removed,
}

impl Change {
    pub const ALL: [Change; 3] = [Change::Created, Change::Updated, Change::Removed];
}

/// A change made to [`Entries`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Changed {
    pub change: Change,
    /// The entry as it is now, or as it was when removed.
    pub entry: Entry,
    /// The entry before an update.
    pub before: Option<Entry>,
}

/// The entries of a calendar and the time zone they are shown in.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Entries {
    items: Vec<Entry>,
    time_zone: TimeZone,
}

impl Default for Entries {
    fn default() -> Self {
        Self::utc()
    }
}

impl Entries {
    /// An empty collection shown in `time_zone`.
    pub fn new(time_zone: TimeZone) -> Self {
        Self {
            items: Vec::new(),
            time_zone,
        }
    }

    /// An empty collection shown in UTC.
    pub fn utc() -> Self {
        Self::new(TimeZone::UTC)
    }

    /// An empty collection shown in the system's time zone, or UTC when
    /// the system does not say.
    pub fn system() -> Self {
        Self::new(TimeZone::system())
    }

    /// Adds entries while building. An entry with an id already present
    /// replaces the earlier one.
    pub fn with(mut self, entries: impl IntoIterator<Item = Entry>) -> Self {
        for entry in entries {
            let _ = self.insert(entry);
        }
        self
    }

    pub fn time_zone(&self) -> &TimeZone {
        &self.time_zone
    }

    pub fn len(&self) -> usize {
        self.items.len()
    }

    pub fn is_empty(&self) -> bool {
        self.items.is_empty()
    }

    pub fn iter(&self) -> impl Iterator<Item = &Entry> {
        self.items.iter()
    }

    pub fn get(&self, id: EntryId) -> Option<&Entry> {
        self.items.iter().find(|entry| entry.id == id)
    }

    /// An id no entry uses yet.
    pub fn next_id(&self) -> EntryId {
        let highest = self.items.iter().map(|entry| entry.id.0).max();
        EntryId(highest.map_or(0, |id| id.saturating_add(1)))
    }

    /// Adds `entry`, or replaces the entry with the same id. Returns what
    /// changed, or `None` when an identical entry was already there.
    pub fn insert(&mut self, entry: Entry) -> Option<Changed> {
        let Some(existing) = self.items.iter_mut().find(|item| item.id == entry.id) else {
            self.items.push(entry.clone());
            return Some(Changed {
                change: Change::Created,
                entry,
                before: None,
            });
        };
        if *existing == entry {
            return None;
        }
        let before = std::mem::replace(existing, entry.clone());
        Some(Changed {
            change: Change::Updated,
            entry,
            before: Some(before),
        })
    }

    /// Removes the entry with `id`, if there is one.
    pub fn remove(&mut self, id: EntryId) -> Option<Changed> {
        let index = self.items.iter().position(|entry| entry.id == id)?;
        Some(Changed {
            change: Change::Removed,
            entry: self.items.remove(index),
            before: None,
        })
    }

    /// The calendar date of `instant` in the collection's time zone.
    pub fn date_of(&self, instant: Timestamp) -> Date {
        date_of(instant, &self.time_zone)
    }

    /// Midnight at the start of `date` in the collection's time zone.
    pub fn midnight(&self, date: Date) -> Timestamp {
        midnight(date, &self.time_zone)
    }

    /// Every occurrence that overlaps the time from `from` up to `to`,
    /// earliest first. Repeating entries are expanded.
    pub fn occurrences(&self, from: Timestamp, to: Timestamp) -> Vec<Occurrence> {
        let mut found: Vec<Occurrence> = self
            .items
            .iter()
            .flat_map(|entry| repeat::occurrences(entry, &self.time_zone, from, to))
            .collect();
        found.sort_by_key(|occurrence| (occurrence.start, occurrence.entry));
        found
    }

    /// Every occurrence that touches a date from `first` to `last`
    /// inclusive.
    pub fn between(&self, first: Date, last: Date) -> Vec<Occurrence> {
        self.occurrences(self.midnight(first), self.midnight(next_day(last)))
    }

    /// Every occurrence that touches `date`.
    pub fn on(&self, date: Date) -> Vec<Occurrence> {
        self.between(date, date)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use jiff::civil::date;

    fn at(day: i8, hour: i8) -> Timestamp {
        date(2026, 11, day)
            .at(hour, 0, 0, 0)
            .to_zoned_datetime(TimeZone::UTC)
            .map(|zoned| zoned.timestamp())
            .unwrap_or_default()
    }

    fn meeting(id: u64, day: i8, hour: i8) -> Entry {
        Entry::new(EntryId(id), "Meeting", at(day, hour), at(day, hour + 1))
    }

    #[test]
    fn days_are_added_and_stop_at_the_ends_of_time() {
        let day = date(2026, 11, 3);
        assert_eq!(add_days(day, 1), date(2026, 11, 4));
        assert_eq!(add_days(day, -3), date(2026, 10, 31));
        assert_eq!(add_days(day, 0), day);
        assert_eq!(add_days(day, i32::MAX), Date::MAX);
        assert_eq!(add_days(day, i32::MIN), Date::MIN);
        assert_eq!(add_days(Date::MAX, 1), Date::MAX);
        assert_eq!(next_day(date(2026, 12, 31)), date(2027, 1, 1));
    }

    #[test]
    fn spans_are_put_in_order() {
        assert_eq!(
            When::timed(at(3, 10), at(3, 9)),
            When::Timed {
                start: at(3, 9),
                end: at(3, 10)
            }
        );
        assert_eq!(
            When::all_day(date(2026, 11, 5), date(2026, 11, 3)),
            When::AllDay {
                first: date(2026, 11, 3),
                last: date(2026, 11, 5)
            }
        );
    }

    #[test]
    fn whole_days_run_from_midnight_to_the_midnight_after_the_last_day() {
        let when = When::all_day(date(2026, 11, 3), date(2026, 11, 4));
        assert!(when.is_all_day());
        assert_eq!(when.start(&TimeZone::UTC), at(3, 0));
        assert_eq!(when.end(&TimeZone::UTC), at(5, 0));
        assert_eq!(When::day(date(2026, 11, 3)).end(&TimeZone::UTC), at(4, 0));
    }

    #[test]
    fn whole_days_follow_the_time_zone() {
        let Ok(tokyo) = TimeZone::get("Asia/Tokyo") else {
            panic!("the time zone database is bundled for tests");
        };
        let when = When::day(date(2026, 11, 3));
        // Midnight in Tokyo is 15:00 the day before in UTC.
        assert_eq!(when.start(&tokyo), at(2, 15));
        assert_eq!(date_of(at(2, 15), &tokyo), date(2026, 11, 3));
        assert_eq!(date_of(at(2, 14), &tokyo), date(2026, 11, 2));
    }

    #[test]
    fn entry_builder_defaults_and_options() {
        let entry = meeting(1, 3, 9);
        assert_eq!(entry.id(), EntryId(1));
        assert_eq!(entry.title(), "Meeting");
        assert_eq!(entry.tone_of(), Tone::Primary);
        assert_eq!(entry.tag_of(), None);
        assert_eq!(entry.repeat_of(), None);
        assert!(!entry.is_all_day());

        let entry = entry
            .tone(Tone::Warning)
            .tag("work")
            .repeat(Repeat::daily())
            .titled("Review")
            .rescheduled(When::day(date(2026, 11, 9)));
        assert_eq!(entry.tone_of(), Tone::Warning);
        assert_eq!(entry.tag_of(), Some("work"));
        assert_eq!(entry.repeat_of(), Some(Repeat::daily()));
        assert_eq!(entry.title(), "Review");
        assert!(entry.is_all_day());
    }

    #[test]
    fn location_and_notes_are_trimmed_and_blank_clears_them() {
        let entry = meeting(1, 3, 9);
        assert_eq!(entry.location_of(), None);
        assert_eq!(entry.notes_of(), None);

        let entry = entry
            .location("  Room 4 ")
            .notes("Bring the plan\nand the figures\n");
        assert_eq!(entry.location_of(), Some("Room 4"));
        assert_eq!(entry.notes_of(), Some("Bring the plan\nand the figures"));

        let entry = entry.location("   ").notes("");
        assert_eq!(entry.location_of(), None);
        assert_eq!(entry.notes_of(), None);
    }

    #[test]
    fn insert_reports_created_updated_and_unchanged() {
        let mut entries = Entries::utc();
        let created = entries.insert(meeting(1, 3, 9));
        assert_eq!(created.map(|changed| changed.change), Some(Change::Created));

        assert_eq!(entries.insert(meeting(1, 3, 9)), None);

        let updated = entries.insert(meeting(1, 4, 9));
        let Some(updated) = updated else {
            panic!("a moved entry is an update");
        };
        assert_eq!(updated.change, Change::Updated);
        assert_eq!(updated.before, Some(meeting(1, 3, 9)));
        assert_eq!(updated.entry, meeting(1, 4, 9));
        assert_eq!(entries.len(), 1);
    }

    #[test]
    fn remove_hands_back_the_entry() {
        let mut entries = Entries::utc().with([meeting(1, 3, 9), meeting(2, 4, 9)]);
        let removed = entries.remove(EntryId(1));
        assert_eq!(
            removed.map(|changed| (changed.change, changed.entry)),
            Some((Change::Removed, meeting(1, 3, 9)))
        );
        assert_eq!(entries.remove(EntryId(1)), None);
        assert_eq!(entries.len(), 1);
        assert!(entries.get(EntryId(2)).is_some());
    }

    #[test]
    fn next_id_is_unused() {
        let mut entries = Entries::utc();
        assert!(entries.is_empty());
        assert_eq!(entries.next_id(), EntryId(0));
        let _ = entries.insert(meeting(7, 3, 9));
        assert_eq!(entries.next_id(), EntryId(8));
        let _ = entries.insert(meeting(u64::MAX, 3, 9));
        assert_eq!(entries.next_id(), EntryId(u64::MAX));
    }

    #[test]
    fn occurrences_overlap_the_range_and_come_in_order() {
        let entries = Entries::utc().with([
            meeting(1, 5, 9),
            meeting(2, 3, 14),
            meeting(3, 3, 9),
            Entry::all_day(EntryId(4), "Trip", date(2026, 11, 2), date(2026, 11, 3)),
        ]);
        let found = entries.on(date(2026, 11, 3));
        let ids: Vec<_> = found.iter().map(|occurrence| occurrence.entry.0).collect();
        assert_eq!(ids, vec![4, 3, 2]);
        assert!(found[0].all_day);
        assert!(!found[1].all_day);

        let week = entries.between(date(2026, 11, 2), date(2026, 11, 8));
        assert_eq!(week.len(), 4);
        assert!(entries.on(date(2026, 11, 4)).is_empty());
    }

    #[test]
    fn an_entry_ending_at_midnight_does_not_touch_the_next_day() {
        let entries = Entries::utc().with([Entry::new(EntryId(1), "Late", at(3, 22), at(4, 0))]);
        assert_eq!(entries.on(date(2026, 11, 3)).len(), 1);
        assert!(entries.on(date(2026, 11, 4)).is_empty());
        let occurrence = entries.on(date(2026, 11, 3))[0];
        assert_eq!(
            occurrence.dates(&TimeZone::UTC),
            (date(2026, 11, 3), date(2026, 11, 3))
        );
        assert_eq!(occurrence.duration(), SignedDuration::from_hours(2));
    }

    #[test]
    fn an_entry_with_no_length_sits_on_its_day() {
        let entries =
            Entries::utc().with([Entry::new(EntryId(1), "Deadline", at(3, 17), at(3, 17))]);
        let found = entries.on(date(2026, 11, 3));
        assert_eq!(found.len(), 1);
        assert_eq!(
            found[0].dates(&TimeZone::UTC),
            (date(2026, 11, 3), date(2026, 11, 3))
        );
    }
}