use jiff::civil::{Date, Time};
use jiff::tz::TimeZone;
use jiff::{SignedDuration, Span, Timestamp};
use super::repeat::{self, Repeat};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct EntryId(pub u64);
#[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,
];
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum When {
Timed { start: Timestamp, end: Timestamp },
AllDay { first: Date, last: Date },
}
impl When {
pub fn timed(start: Timestamp, end: Timestamp) -> Self {
When::Timed {
start: start.min(end),
end: start.max(end),
}
}
pub fn all_day(first: Date, last: Date) -> Self {
When::AllDay {
first: first.min(last),
last: first.max(last),
}
}
pub fn day(date: Date) -> Self {
When::AllDay {
first: date,
last: date,
}
}
pub fn is_all_day(&self) -> bool {
matches!(self, When::AllDay { .. })
}
pub fn start(&self, time_zone: &TimeZone) -> Timestamp {
match *self {
When::Timed { start, .. } => start,
When::AllDay { first, .. } => midnight(first, time_zone),
}
}
pub fn end(&self, time_zone: &TimeZone) -> Timestamp {
match *self {
When::Timed { end, .. } => end,
When::AllDay { last, .. } => midnight(next_day(last), time_zone),
}
}
}
pub fn midnight(date: Date, time_zone: &TimeZone) -> Timestamp {
date.to_zoned_datetime(time_zone.clone())
.map(|zoned| zoned.timestamp())
.unwrap_or(Timestamp::MAX)
}
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))
}
pub fn date_of(instant: Timestamp, time_zone: &TimeZone) -> Date {
instant.to_zoned_datetime(time_zone.clone()).date()
}
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)
}
#[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>,
}
fn filled(text: String) -> Option<String> {
let trimmed = text.trim();
if trimmed.is_empty() {
return None;
}
Some(trimmed.to_owned())
}
impl Entry {
pub fn new(id: EntryId, title: impl Into<String>, start: Timestamp, end: Timestamp) -> Self {
Self::at(id, title, When::timed(start, end))
}
pub fn all_day(id: EntryId, title: impl Into<String>, first: Date, last: Date) -> Self {
Self::at(id, title, When::all_day(first, last))
}
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,
}
}
pub fn location(mut self, location: impl Into<String>) -> Self {
self.location = filled(location.into());
self
}
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
}
pub fn tag(mut self, tag: impl Into<String>) -> Self {
self.tag = Some(tag.into());
self
}
pub fn repeat(mut self, repeat: Repeat) -> Self {
self.repeat = Some(repeat);
self
}
pub fn titled(mut self, title: impl Into<String>) -> Self {
self.title = title.into();
self
}
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
}
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()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Occurrence {
pub entry: EntryId,
pub index: u32,
pub start: Timestamp,
pub end: Timestamp,
pub all_day: bool,
}
impl Occurrence {
pub fn duration(&self) -> SignedDuration {
self.end.duration_since(self.start)
}
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))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Draft {
pub when: When,
}
#[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];
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Changed {
pub change: Change,
pub entry: Entry,
pub before: Option<Entry>,
}
#[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 {
pub fn new(time_zone: TimeZone) -> Self {
Self {
items: Vec::new(),
time_zone,
}
}
pub fn utc() -> Self {
Self::new(TimeZone::UTC)
}
pub fn system() -> Self {
Self::new(TimeZone::system())
}
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)
}
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)))
}
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),
})
}
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,
})
}
pub fn date_of(&self, instant: Timestamp) -> Date {
date_of(instant, &self.time_zone)
}
pub fn midnight(&self, date: Date) -> Timestamp {
midnight(date, &self.time_zone)
}
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
}
pub fn between(&self, first: Date, last: Date) -> Vec<Occurrence> {
self.occurrences(self.midnight(first), self.midnight(next_day(last)))
}
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));
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))
);
}
}