Sources/OrgPresentation/AgendaRows.swift
413 lines · 18820 bytes
1import Foundation
2import OrgCore
3
4/// An event from the system Calendar or a reminder from Reminders, read-only (OrgApp's
5/// `CalendarEvents` and `ReminderLists` read them). A reminder starts and ends at its due date;
6/// one without a time is all day.
7public struct AgendaEvent: Sendable, Equatable, Identifiable {
8 public let id: String
9 public let title: String
10 public let calendarID: String
11 public let calendarTitle: String
12 /// The calendar's color; nil uses the theme's `agenda-event`.
13 public let color: RGBA?
14 public let start: Date
15 public let end: Date
16 public let isAllDay: Bool
17 public let location: String?
18 public let isReminder: Bool
19
20 public init(
21 id: String, title: String, calendarID: String, calendarTitle: String, color: RGBA?, start: Date, end: Date,
22 isAllDay: Bool, location: String? = nil, isReminder: Bool = false
23 ) {
24 self.id = id
25 self.title = title
26 self.calendarID = calendarID
27 self.calendarTitle = calendarTitle
28 self.color = color
29 self.start = start
30 self.end = end
31 self.isAllDay = isAllDay
32 self.location = location
33 self.isReminder = isReminder
34 }
35
36 /// The days (as `Days` numbers them) the event covers; an end at midnight ends the day before.
37 public func days(calendar: Calendar) -> ClosedRange<Int> {
38 let first = Days.absolute(start, calendar: calendar)
39 var last = Days.absolute(end, calendar: calendar)
40 if end > start, calendar.startOfDay(for: end) == end { last -= 1 }
41 return first...max(first, last)
42 }
43}
44
45/// One line of the agenda: an Org entry or a calendar event.
46///
47/// The gutter holds the time (`08:00`, `13:50–14:30`) or, untimed, a short status:
48/// deadlines `Due today`, `Due in 2d`, `3d late`, `Due` (on a day other than today);
49/// scheduled `Scheduled`, `4d ago`; habits `Habit`; timestamps, diary sexps and
50/// calendar events `All day`; ranges `Day 2/5`; log mode `Closed`, `Clocked`, `State`; TODO
51/// and match lists nothing. Ages use `AgendaAge.compact`.
52public struct AgendaRow: Sendable, Equatable, Identifiable {
53 /// What the gutter's color says.
54 public enum Status: String, Sendable {
55 /// Not done, with a deadline or scheduled date before today.
56 case overdue
57 /// Not done, with a deadline today or within its warning period.
58 case dueSoon = "due-soon"
59 case normal
60 /// A done TODO keyword.
61 case done
62 }
63
64 public enum Icon: String, Sendable {
65 case scheduled, deadline, habit, event, timestamp, reminder
66 }
67
68 /// Unique within a day group.
69 public internal(set) var id: String
70 public let gutter: String
71 public let status: Status
72 /// Nil for TODO and match list entries.
73 public let icon: Icon?
74 /// The category line above the title: the entry's category, or the event's calendar.
75 public let category: String
76 public let title: String
77 public let tags: [String]
78 public let todo: String?
79 public let isDone: Bool
80 /// Blocked from becoming done (`org-agenda-dim-blocked-tasks`): shown dimmed.
81 public let isBlocked: Bool
82 public let priority: String?
83 /// The statistics cookie: `1/3`, `50%`.
84 public let progress: String?
85 /// Log mode: the time clocked (`1:30`) or the state set (`DONE`).
86 public let detail: String?
87 /// What the view's prefix format adds, such as the effort or the outline path.
88 public let prefixDetail: String?
89 /// `HHMM` of the start and the end, when timed.
90 public let start: Int?
91 public let end: Int?
92 /// The deadline or scheduled day, as `Days` numbers it.
93 public let planningDay: Int?
94 /// The Org entry, for its actions.
95 public let item: AgendaItem?
96 public let event: AgendaEvent?
97
98 public var isEvent: Bool { event != nil }
99 /// The calendar's color for an event.
100 public var color: RGBA? { event?.color }
101
102 /// Nil for the time grid and the current-time line.
103 public init?(item: AgendaItem, day: Int, today: Int) {
104 if item.kind == .timeGrid || item.kind == .currentTime { return nil }
105 let timed = item.timeOfDay.map { start in (start, Self.endTime(item.time)) }
106 let planning = item.planningDay
107 let late = planning.map { $0 < today } ?? false
108 var icon: Icon?
109 var status: Status = .normal
110 var untimed = ""
111 switch item.kind {
112 case .deadline, .upcomingDeadline:
113 icon = .deadline
114 let due = planning ?? day
115 if day == today {
116 untimed = due == today ? String(localized: "Due today", bundle: .main)
117 : due < today ? String(localized: "\(AgendaAge.compact(today - due)) late", bundle: .main)
118 : String(localized: "Due in \(AgendaAge.compact(due - today))", bundle: .main)
119 } else {
120 untimed = String(localized: "Due", bundle: .main)
121 }
122 status = late ? .overdue : day == today ? .dueSoon : .normal
123 case .scheduled, .pastScheduled:
124 if item.habit != nil {
125 icon = .habit
126 untimed = String(localized: "Habit", bundle: .main)
127 } else {
128 icon = .scheduled
129 let on = planning ?? day
130 untimed = on < day ? String(localized: "\(AgendaAge.compact(day - on)) ago", bundle: .main) : String(localized: "Scheduled", bundle: .main)
131 }
132 status = late ? .overdue : .normal
133 case .timestamp, .sexp:
134 icon = .timestamp
135 untimed = String(localized: "All day", bundle: .main)
136 case .block:
137 icon = .timestamp
138 let ns = item.extra as NSString
139 if let m = Self.rangeDay.firstMatch(in: item.extra, range: NSRange(location: 0, length: ns.length)) {
140 untimed = String(localized: "Day \(ns.substring(with: m.range(at: 1)))", bundle: .main)
141 } else {
142 untimed = String(localized: "All day", bundle: .main)
143 }
144 case .closed: (icon, untimed) = (.timestamp, String(localized: "Closed", bundle: .main))
145 case .clock: (icon, untimed) = (.timestamp, String(localized: "Clocked", bundle: .main))
146 case .state: (icon, untimed) = (.timestamp, String(localized: "State", bundle: .main))
147 case .todo, .tagsMatch, .search, .timeGrid, .currentTime: break
148 }
149 if item.isDone { status = .done }
150 self.id = [item.path ?? "", "\(item.headingOffset ?? -1)", "\(item.markerOffset ?? -1)", item.kind.rawValue, item.text].joined(separator: "\u{1f}")
151 self.gutter = timed.map { Self.timeText($0.0, $0.1) } ?? untimed
152 self.status = status
153 self.icon = icon
154 self.category = item.category
155 self.title = item.title
156 self.tags = item.tags
157 self.todo = item.todo
158 self.isDone = item.isDone
159 self.isBlocked = item.isBlocked
160 self.priority = item.priorityLetter
161 self.progress = item.progress
162 self.detail = item.kind == .clock || item.kind == .state ? Self.logDetail(item.extra) : nil
163 self.prefixDetail = item.prefixDetail
164 self.start = timed?.0
165 self.end = timed?.1
166 self.planningDay = planning
167 self.item = item
168 self.event = nil
169 }
170
171 /// The event's row on `day`: its times on the day it starts (the end only when it ends that
172 /// day too), `Until 10:00` on the day a longer event ends, `All day` otherwise.
173 /// A reminder due before `day` shows as late, untimed.
174 public init(event: AgendaEvent, day: Int, calendar: Calendar) {
175 let days = event.days(calendar: calendar)
176 func hhmm(_ date: Date) -> Int {
177 let c = calendar.dateComponents([.hour, .minute], from: date)
178 return (c.hour ?? 0) * 100 + (c.minute ?? 0)
179 }
180 var start: Int?
181 var end: Int?
182 let gutter: String
183 if event.isReminder {
184 if days.lowerBound < day {
185 gutter = String(localized: "\(AgendaAge.compact(day - days.lowerBound)) late", bundle: .main)
186 } else if event.isAllDay {
187 gutter = String(localized: "Reminder", bundle: .main)
188 } else {
189 start = hhmm(event.start)
190 gutter = Self.timeText(start!, nil)
191 }
192 } else if event.isAllDay || (day != days.lowerBound && day != days.upperBound) {
193 gutter = String(localized: "All day", bundle: .main)
194 } else if day == days.lowerBound {
195 start = hhmm(event.start)
196 if days.lowerBound == days.upperBound { end = hhmm(event.end) }
197 gutter = Self.timeText(start!, end)
198 } else {
199 gutter = String(localized: "Until \(Self.timeText(hhmm(event.end), nil))", bundle: .main)
200 }
201 self.id = (event.isReminder ? "reminder\u{1f}" : "event\u{1f}") + event.id
202 self.gutter = gutter
203 self.status = event.isReminder && days.lowerBound < day ? .overdue : .normal
204 self.icon = event.isReminder ? .reminder : .event
205 self.category = event.calendarTitle
206 self.title = event.title
207 self.tags = []
208 self.todo = nil
209 self.isDone = false
210 self.isBlocked = false
211 self.priority = nil
212 self.progress = nil
213 self.detail = nil
214 self.prefixDetail = nil
215 self.start = start
216 self.end = end
217 self.planningDay = event.isReminder ? days.lowerBound : nil
218 self.item = nil
219 self.event = event
220 }
221
222 static let rangeDay = try! NSRegularExpression(pattern: "^\\(([0-9]+/[0-9]+)\\)")
223 static let logParen = try! NSRegularExpression(pattern: "\\(([^)]+)\\)")
224 static let rangeEnd = try! NSRegularExpression(pattern: "-\\+?([0-9]{1,2}):([0-9]{2})")
225
226 /// The text in parentheses of a log row's `extra`: `Clocked: (1:30)`.
227 static func logDetail(_ extra: String) -> String? {
228 let ns = extra as NSString
229 guard let m = logParen.firstMatch(in: extra, range: NSRange(location: 0, length: ns.length)) else { return nil }
230 let text = ns.substring(with: m.range(at: 1)).trimmingCharacters(in: .whitespaces)
231 return text.isEmpty ? nil : text
232 }
233
234 /// The end of a `%t` time range (` 9:00-10:30`), as `HHMM`; past midnight (`+1:00`) adds 24 hours.
235 static func endTime(_ time: String) -> Int? {
236 let ns = time as NSString
237 guard let m = rangeEnd.firstMatch(in: time, range: NSRange(location: 0, length: ns.length)) else { return nil }
238 let overtime = ns.substring(with: m.range).contains("+") ? 24 : 0
239 return (Int(ns.substring(with: m.range(at: 1)))! + overtime) * 100 + Int(ns.substring(with: m.range(at: 2)))!
240 }
241
242 /// `08:00`, `13:50–14:30`; hours past midnight wrap.
243 static func timeText(_ start: Int, _ end: Int?) -> String {
244 func text(_ t: Int) -> String { String(format: "%02d:%02d", (t / 100) % 24, t % 100) }
245 return end.map { text(start) + "–" + text($0) } ?? text(start)
246 }
247}
248
249/// One day of the agenda: today's entries carried from earlier days in `overdue`, the rest
250/// in `rows`.
251public struct AgendaDayGroup: Sendable, Equatable, Identifiable {
252 /// As `Days` numbers it.
253 public let day: Int
254 public let isToday: Bool
255 /// Org's day header: `Thursday 8 October 2026`.
256 public let header: String
257 /// Today only: deadlines and scheduled entries from before today, oldest first.
258 public let overdue: [AgendaRow]
259 public let rows: [AgendaRow]
260 /// `org-agenda-time-grid` lines: each time, before the row it precedes in Org's order
261 /// (`rows.count` for after the last).
262 public var grid: [GridLine] = []
263 /// Org puts the current-time line on this day.
264 public var showsNow = false
265
266 public struct GridLine: Sendable, Equatable {
267 public let before: Int
268 /// `HHMM`.
269 public let time: Int
270 }
271
272 /// What a day shows, in order: rows by index, grid lines and the now line.
273 public enum Line: Sendable, Equatable {
274 case row(Int)
275 case grid(Int)
276 case now
277 }
278
279 public var id: Int { day }
280 public var isEmpty: Bool { overdue.isEmpty && rows.isEmpty }
281
282 /// `Today`, `Tomorrow`, `Yesterday`, or nil.
283 public func relativeName(today: Int) -> String? {
284 switch day - today {
285 case 0: String(localized: "Today", bundle: .main)
286 case 1: String(localized: "Tomorrow", bundle: .main)
287 case -1: String(localized: "Yesterday", bundle: .main)
288 default: nil
289 }
290 }
291
292 /// Midnight starting the day.
293 public func date(calendar: Calendar) -> Date {
294 let d = Days.date(day)
295 return calendar.date(from: DateComponents(year: d.year, month: d.month, day: d.day))!
296 }
297
298 /// Where the current-time line goes in `rows`: before the first timed row starting after
299 /// `now` (`HHMM`), or after the last timed row when all have started. Nil on other days
300 /// and when no row is timed, as Org adds the line only among timed entries.
301 public func nowIndex(now: Int) -> Int? {
302 guard isToday, showsNow else { return nil }
303 return AgendaRows.nowIndex(rows, now: now) ?? (grid.isEmpty ? nil : 0)
304 }
305
306 /// The rows with the grid lines and, at `now` (`HHMM`), the now line among them; lines
307 /// before the same row go by time.
308 public func lines(now: Int) -> [Line] {
309 let nowAt = nowIndex(now: now)
310 var lines: [Line] = []
311 for index in 0...rows.count {
312 var marks = grid.filter { $0.before == index }.map { ($0.time, Line.grid($0.time)) }
313 if index == nowAt { marks.append((now, .now)) }
314 lines += marks.enumerated().sorted { a, b in
315 a.element.0 != b.element.0 ? a.element.0 < b.element.0 : a.offset < b.offset
316 }.map(\.element.1)
317 if index < rows.count { lines.append(.row(index)) }
318 }
319 return lines
320 }
321}
322
323public enum AgendaRows {
324 /// The days of `Agenda.list` as rows, with `events` merged in.
325 ///
326 /// - Days with no rows are left out unless `showAllDates` (`org-agenda-show-all-dates`);
327 /// today always stays.
328 /// - Today's past-scheduled entries and past deadlines (not habits) go in `overdue`,
329 /// oldest date first, Org's order among the same date.
330 /// - Other rows keep the agenda's order (timed by time, then untimed by urgency, habits
331 /// after other entries at the same time).
332 /// All-day events come first, timed events go among the timed entries by start time,
333 /// after entries at the same time. Reminders due before today show in today's
334 /// `overdue`.
335 /// - `keep` filters the Org entries (an `AgendaFilter`); events are not filtered.
336 public static func groups(
337 _ days: [AgendaDay], events: [AgendaEvent] = [], today: Int, showAllDates: Bool = false, calendar: Calendar = .current,
338 keep: (AgendaItem) -> Bool = { _ in true }
339 ) -> [AgendaDayGroup] {
340 let eventDays = events.map { ($0, $0.days(calendar: calendar)) }
341 var groups: [AgendaDayGroup] = []
342 for day in days {
343 var overdue: [AgendaRow] = []
344 var rows: [AgendaRow] = []
345 // Grid lines by the number of Org rows before them; filters leave them.
346 var grid: [(ordinal: Int, time: Int)] = []
347 var showsNow = false
348 for item in day.items {
349 if item.kind == .timeGrid, let time = item.timeOfDay { grid.append((rows.count, time)) }
350 if item.kind == .currentTime { showsNow = true }
351 guard keep(item), let row = AgendaRow(item: item, day: day.day, today: today) else { continue }
352 if day.day == today, item.habit == nil, let planning = row.planningDay, planning < today {
353 overdue.append(row)
354 } else {
355 rows.append(row)
356 }
357 }
358 let dayEvents = eventDays.filter { event, days in
359 days.contains(day.day) || (event.isReminder && day.day == today && days.upperBound < today)
360 }.map { AgendaRow(event: $0.0, day: day.day, calendar: calendar) }
361 overdue += dayEvents.filter { $0.status == .overdue }
362 overdue = overdue.enumerated().sorted { a, b in
363 a.element.planningDay! != b.element.planningDay! ? a.element.planningDay! < b.element.planningDay! : a.offset < b.offset
364 }.map(\.element)
365 rows = merge(rows, events: dayEvents.filter { $0.status != .overdue })
366 let orgIndices = rows.indices.filter { !rows[$0].isEvent }
367 var group = AgendaDayGroup(day: day.day, isToday: day.day == today, header: day.header, overdue: unique(overdue), rows: unique(rows))
368 group.grid = grid.map { .init(before: $0.ordinal < orgIndices.count ? orgIndices[$0.ordinal] : rows.count, time: $0.time) }
369 group.showsNow = showsNow
370 if group.isEmpty, !group.isToday, !showAllDates { continue }
371 groups.append(group)
372 }
373 return groups
374 }
375
376 /// `org` (in agenda order) with event rows added: untimed events first, timed ones before
377 /// the first untimed entry, or the first timed entry starting later.
378 static func merge(_ org: [AgendaRow], events: [AgendaRow]) -> [AgendaRow] {
379 let allDay = events.filter { $0.start == nil }
380 var result = org
381 let timed = events.filter { $0.start != nil }.enumerated().sorted { a, b in
382 a.element.start! != b.element.start! ? a.element.start! < b.element.start! : a.offset < b.offset
383 }.map(\.element)
384 for event in timed {
385 let at = result.firstIndex { row in
386 if row.isEvent { return row.start.map { $0 > event.start! } ?? false }
387 guard let start = row.start else { return true }
388 return start > event.start!
389 } ?? result.count
390 result.insert(event, at: at)
391 }
392 return allDay + result
393 }
394
395 /// Ids made unique: a repeat gets `#2`, `#3`.
396 static func unique(_ rows: [AgendaRow]) -> [AgendaRow] {
397 var seen: [String: Int] = [:]
398 return rows.map { row in
399 var row = row
400 let n = seen[row.id, default: 0] + 1
401 seen[row.id] = n
402 if n > 1 { row.id += "#\(n)" }
403 return row
404 }
405 }
406
407 /// See `AgendaDayGroup.nowIndex(now:)`.
408 public static func nowIndex(_ rows: [AgendaRow], now: Int) -> Int? {
409 let timed = rows.indices.filter { rows[$0].start != nil }
410 guard let last = timed.last else { return nil }
411 return timed.first { rows[$0].start! > now } ?? last + 1
412 }
413}