Sources/OrgCore/Agenda/Reminders.swift
61 lines · 3167 bytes
1import Foundation
2
3/// A notification for an agenda entry with a time of day.
4public struct Reminder: Sendable, Equatable {
5 /// Stable while the entry, its day and time stay the same.
6 public let id: String
7 public let fireDate: Date
8 public let eventDate: Date
9 public let title: String
10 public let body: String
11 public let path: String
12 public let offset: Int
13 /// The folder the entry's file is in, for Focus filters to mute.
14 public var folder: String?
15
16 public init(id: String, fireDate: Date, eventDate: Date, title: String, body: String, path: String, offset: Int) {
17 self.id = id
18 self.fireDate = fireDate
19 self.eventDate = eventDate
20 self.title = title
21 self.body = body
22 self.path = path
23 self.offset = offset
24 }
25}
26
27/// What `org-agenda-to-appt` hands appt: timed entries, each with a warning before it.
28public enum Reminders {
29 /// Reminders for the next `days` days from `now`, earliest first, at most `limit`. An
30 /// entry whose warning time has passed but which hasn't started fires now.
31 public static func upcoming(
32 _ sources: [AgendaSource], now: Date, calendar: Calendar, days: Int = 7, lead: Int = 12, limit: Int = 64
33 ) -> [Reminder] {
34 let today = Days.absolute(now, calendar: calendar)
35 let clock = calendar.dateComponents([.hour, .minute], from: now)
36 let list = Agenda.list(sources, start: today, days: days, today: today, now: (clock.hour ?? 0, clock.minute ?? 0))
37 var reminders: [Reminder] = []
38 for day in list {
39 let date = Days.date(day.day)
40 guard let midnight = calendar.date(from: DateComponents(year: date.year, month: date.month, day: date.day)) else { continue }
41 for item in day.items {
42 guard let time = item.timeOfDay, let path = item.path, !item.isDone,
43 [.deadline, .scheduled, .timestamp, .block].contains(item.kind),
44 let event = calendar.date(byAdding: .minute, value: (time / 100) * 60 + time % 100, to: midnight),
45 event > now else { continue }
46 let fire = max(event.addingTimeInterval(-Double((item.warntime ?? lead) * 60)), now.addingTimeInterval(1))
47 let clockText = String(format: "%d:%02d", time / 100, time % 100)
48 // `Scheduled:` reads `Scheduled` beside the time.
49 var leader = item.extra.trimmingCharacters(in: .whitespaces)
50 if leader.hasSuffix(":") { leader.removeLast() }
51 reminders.append(Reminder(
52 id: "orgstar.\(path)|\(item.headingLine ?? item.text.trimmingCharacters(in: .whitespaces))|\(day.day)|\(time)|\(item.kind.rawValue)",
53 fireDate: fire, eventDate: event, title: item.title,
54 body: ([clockText] + (leader.isEmpty ? [] : [leader]) + [item.category]).joined(separator: " · "),
55 path: path, offset: item.markerOffset ?? item.headingOffset ?? 0
56 ))
57 }
58 }
59 return Array(reminders.sorted { $0.fireDate < $1.fireDate }.prefix(limit))
60 }
61}