Sources/OrgPresentation/AgendaRows.swift
437 lines · 19906 bytes
22 symbols in this file
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`, `1d ago` when missed; 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 /// The gutter as its lines: a timed row's start over its end, else the status.
103 public var gutterLines: [String] {
104 start == nil ? [gutter] : gutter.split(separator: "–", maxSplits: 1).map(String.init)
105 }
106
107 /// The SF Symbol under the gutter: a warning for overdue entries and a check for done ones,
108 /// as the status says first, else one for the kind of row.
109 public var symbol: String? {
110 guard let icon else { return nil }
111 if status == .overdue { return "exclamationmark.circle.fill" }
112 if status == .done { return "checkmark.circle.fill" }
113 switch icon {
114 case .scheduled: return "calendar"
115 case .deadline: return "flag.fill"
116 case .habit: return "repeat"
117 case .event: return "circle.fill"
118 case .reminder: return "circle"
119 case .timestamp: return start == nil ? "calendar" : "clock"
120 }
121 }
122
123 /// Nil for the time grid and the current-time line.
124 public init?(item: AgendaItem, day: Int, today: Int) {
125 if item.kind == .timeGrid || item.kind == .currentTime { return nil }
126 let planning = item.planningDay
127 let late = planning.map { $0 < today } ?? false
128 // Carried to today from an earlier day, where its time no longer applies.
129 let carried = late && day == today
130 let timed = carried ? nil : item.timeOfDay.map { start in (start, Self.endTime(item.time)) }
131 var icon: Icon?
132 var status: Status = .normal
133 var untimed = ""
134 switch item.kind {
135 case .deadline, .upcomingDeadline:
136 icon = .deadline
137 let due = planning ?? day
138 if day == today {
139 untimed = due == today ? String(localized: "Due today", bundle: .main)
140 : due < today ? String(localized: "\(AgendaAge.compact(today - due)) late", bundle: .main)
141 : String(localized: "Due in \(AgendaAge.compact(due - today))", bundle: .main)
142 } else {
143 untimed = String(localized: "Due", bundle: .main)
144 }
145 status = late ? .overdue : day == today ? .dueSoon : .normal
146 case .scheduled, .pastScheduled:
147 let on = planning ?? day
148 let ago = String(localized: "\(AgendaAge.compact(day - on)) ago", bundle: .main)
149 if item.habit != nil {
150 icon = .habit
151 untimed = carried ? ago : String(localized: "Habit", bundle: .main)
152 } else {
153 icon = .scheduled
154 untimed = on < day ? ago : String(localized: "Scheduled", bundle: .main)
155 }
156 status = late ? .overdue : .normal
157 case .timestamp, .sexp:
158 icon = .timestamp
159 untimed = String(localized: "All day", bundle: .main)
160 case .block:
161 icon = .timestamp
162 let ns = item.extra as NSString
163 if let m = Self.rangeDay.firstMatch(in: item.extra, range: NSRange(location: 0, length: ns.length)) {
164 untimed = String(localized: "Day \(ns.substring(with: m.range(at: 1)))", bundle: .main)
165 } else {
166 untimed = String(localized: "All day", bundle: .main)
167 }
168 case .closed: (icon, untimed) = (.timestamp, String(localized: "Closed", bundle: .main))
169 case .clock: (icon, untimed) = (.timestamp, String(localized: "Clocked", bundle: .main))
170 case .state: (icon, untimed) = (.timestamp, String(localized: "State", bundle: .main))
171 case .todo, .tagsMatch, .search, .timeGrid, .currentTime: break
172 }
173 if item.isDone { status = .done }
174 self.id = [item.path ?? "", "\(item.headingOffset ?? -1)", "\(item.markerOffset ?? -1)", item.kind.rawValue, item.text].joined(separator: "\u{1f}")
175 self.gutter = timed.map { Self.timeText($0.0, $0.1) } ?? untimed
176 self.status = status
177 self.icon = icon
178 self.category = item.category
179 self.title = item.title
180 self.tags = item.tags
181 self.todo = item.todo
182 self.isDone = item.isDone
183 self.isBlocked = item.isBlocked
184 self.priority = item.priorityLetter
185 self.progress = item.progress
186 self.detail = item.kind == .clock || item.kind == .state ? Self.logDetail(item.extra) : nil
187 self.prefixDetail = item.prefixDetail
188 self.start = timed?.0
189 self.end = timed?.1
190 self.planningDay = planning
191 self.item = item
192 self.event = nil
193 }
194
195 /// The event's row on `day`: its times on the day it starts (the end only when it ends that
196 /// day too), `Until 10:00` on the day a longer event ends, `All day` otherwise.
197 /// A reminder due before `day` shows as late, untimed.
198 public init(event: AgendaEvent, day: Int, calendar: Calendar) {
199 let days = event.days(calendar: calendar)
200 func hhmm(_ date: Date) -> Int {
201 let c = calendar.dateComponents([.hour, .minute], from: date)
202 return (c.hour ?? 0) * 100 + (c.minute ?? 0)
203 }
204 var start: Int?
205 var end: Int?
206 let gutter: String
207 if event.isReminder {
208 if days.lowerBound < day {
209 gutter = String(localized: "\(AgendaAge.compact(day - days.lowerBound)) late", bundle: .main)
210 } else if event.isAllDay {
211 gutter = String(localized: "Reminder", bundle: .main)
212 } else {
213 start = hhmm(event.start)
214 gutter = Self.timeText(start!, nil)
215 }
216 } else if event.isAllDay || (day != days.lowerBound && day != days.upperBound) {
217 gutter = String(localized: "All day", bundle: .main)
218 } else if day == days.lowerBound {
219 start = hhmm(event.start)
220 if days.lowerBound == days.upperBound { end = hhmm(event.end) }
221 gutter = Self.timeText(start!, end)
222 } else {
223 gutter = String(localized: "Until \(Self.timeText(hhmm(event.end), nil))", bundle: .main)
224 }
225 self.id = (event.isReminder ? "reminder\u{1f}" : "event\u{1f}") + event.id
226 self.gutter = gutter
227 self.status = event.isReminder && days.lowerBound < day ? .overdue : .normal
228 self.icon = event.isReminder ? .reminder : .event
229 self.category = event.calendarTitle
230 self.title = event.title
231 self.tags = []
232 self.todo = nil
233 self.isDone = false
234 self.isBlocked = false
235 self.priority = nil
236 self.progress = nil
237 self.detail = nil
238 self.prefixDetail = nil
239 self.start = start
240 self.end = end
241 self.planningDay = event.isReminder ? days.lowerBound : nil
242 self.item = nil
243 self.event = event
244 }
245
246 static let rangeDay = try! NSRegularExpression(pattern: "^\\(([0-9]+/[0-9]+)\\)")
247 static let logParen = try! NSRegularExpression(pattern: "\\(([^)]+)\\)")
248 static let rangeEnd = try! NSRegularExpression(pattern: "-\\+?([0-9]{1,2}):([0-9]{2})")
249
250 /// The text in parentheses of a log row's `extra`: `Clocked: (1:30)`.
251 static func logDetail(_ extra: String) -> String? {
252 let ns = extra as NSString
253 guard let m = logParen.firstMatch(in: extra, range: NSRange(location: 0, length: ns.length)) else { return nil }
254 let text = ns.substring(with: m.range(at: 1)).trimmingCharacters(in: .whitespaces)
255 return text.isEmpty ? nil : text
256 }
257
258 /// The end of a `%t` time range (` 9:00-10:30`), as `HHMM`; past midnight (`+1:00`) adds 24 hours.
259 static func endTime(_ time: String) -> Int? {
260 let ns = time as NSString
261 guard let m = rangeEnd.firstMatch(in: time, range: NSRange(location: 0, length: ns.length)) else { return nil }
262 let overtime = ns.substring(with: m.range).contains("+") ? 24 : 0
263 return (Int(ns.substring(with: m.range(at: 1)))! + overtime) * 100 + Int(ns.substring(with: m.range(at: 2)))!
264 }
265
266 /// `08:00`, `13:50–14:30`; hours past midnight wrap.
267 static func timeText(_ start: Int, _ end: Int?) -> String {
268 func text(_ t: Int) -> String { String(format: "%02d:%02d", (t / 100) % 24, t % 100) }
269 return end.map { text(start) + "–" + text($0) } ?? text(start)
270 }
271}
272
273/// One day of the agenda: today's entries carried from earlier days in `overdue`, the rest
274/// in `rows`.
275public struct AgendaDayGroup: Sendable, Equatable, Identifiable {
276 /// As `Days` numbers it.
277 public let day: Int
278 public let isToday: Bool
279 /// Org's day header: `Thursday 8 October 2026`.
280 public let header: String
281 /// Today only: deadlines and scheduled entries from before today, oldest first.
282 public let overdue: [AgendaRow]
283 public let rows: [AgendaRow]
284 /// `org-agenda-time-grid` lines: each time, before the row it precedes in Org's order
285 /// (`rows.count` for after the last).
286 public var grid: [GridLine] = []
287 /// Org puts the current-time line on this day.
288 public var showsNow = false
289
290 public struct GridLine: Sendable, Equatable {
291 public let before: Int
292 /// `HHMM`.
293 public let time: Int
294 }
295
296 /// What a day shows, in order: rows by index, grid lines and the now line.
297 public enum Line: Sendable, Equatable {
298 case row(Int)
299 case grid(Int)
300 case now
301 }
302
303 public var id: Int { day }
304 public var isEmpty: Bool { overdue.isEmpty && rows.isEmpty }
305
306 /// `Today`, `Tomorrow`, `Yesterday`, or nil.
307 public func relativeName(today: Int) -> String? {
308 switch day - today {
309 case 0: String(localized: "Today", bundle: .main)
310 case 1: String(localized: "Tomorrow", bundle: .main)
311 case -1: String(localized: "Yesterday", bundle: .main)
312 default: nil
313 }
314 }
315
316 /// Midnight starting the day.
317 public func date(calendar: Calendar) -> Date {
318 let d = Days.date(day)
319 return calendar.date(from: DateComponents(year: d.year, month: d.month, day: d.day))!
320 }
321
322 /// Where the current-time line goes in `rows`: before the first timed row starting after
323 /// `now` (`HHMM`), or after the last timed row when all have started. Nil on other days
324 /// and when no row is timed, as Org adds the line only among timed entries.
325 public func nowIndex(now: Int) -> Int? {
326 guard isToday, showsNow else { return nil }
327 return AgendaRows.nowIndex(rows, now: now) ?? (grid.isEmpty ? nil : 0)
328 }
329
330 /// The rows with the grid lines and, at `now` (`HHMM`), the now line among them; lines
331 /// before the same row go by time.
332 public func lines(now: Int) -> [Line] {
333 let nowAt = nowIndex(now: now)
334 var lines: [Line] = []
335 for index in 0...rows.count {
336 var marks = grid.filter { $0.before == index }.map { ($0.time, Line.grid($0.time)) }
337 if index == nowAt { marks.append((now, .now)) }
338 lines += marks.enumerated().sorted { a, b in
339 a.element.0 != b.element.0 ? a.element.0 < b.element.0 : a.offset < b.offset
340 }.map(\.element.1)
341 if index < rows.count { lines.append(.row(index)) }
342 }
343 return lines
344 }
345}
346
347public enum AgendaRows {
348 /// The days of `Agenda.list` as rows, with `events` merged in.
349 ///
350 /// - Days with no rows are left out unless `showAllDates` (`org-agenda-show-all-dates`);
351 /// today always stays.
352 /// - Today's past-scheduled entries, habits and past deadlines go in `overdue`, oldest
353 /// date first, Org's order among the same date.
354 /// - Other rows keep the agenda's order (timed by time, then untimed by urgency, habits
355 /// after other entries at the same time).
356 /// All-day events come first, timed events go among the timed entries by start time,
357 /// after entries at the same time. Reminders due before today show in today's
358 /// `overdue`.
359 /// - `keep` filters the Org entries (an `AgendaFilter`); events are not filtered.
360 public static func groups(
361 _ days: [AgendaDay], events: [AgendaEvent] = [], today: Int, showAllDates: Bool = false, calendar: Calendar = .current,
362 keep: (AgendaItem) -> Bool = { _ in true }
363 ) -> [AgendaDayGroup] {
364 let eventDays = events.map { ($0, $0.days(calendar: calendar)) }
365 var groups: [AgendaDayGroup] = []
366 for day in days {
367 var overdue: [AgendaRow] = []
368 var rows: [AgendaRow] = []
369 // Grid lines by the number of Org rows before them; filters leave them.
370 var grid: [(ordinal: Int, time: Int)] = []
371 var showsNow = false
372 for item in day.items {
373 if item.kind == .timeGrid, let time = item.timeOfDay { grid.append((rows.count, time)) }
374 if item.kind == .currentTime { showsNow = true }
375 guard keep(item), let row = AgendaRow(item: item, day: day.day, today: today) else { continue }
376 if day.day == today, let planning = row.planningDay, planning < today {
377 overdue.append(row)
378 } else {
379 rows.append(row)
380 }
381 }
382 let dayEvents = eventDays.filter { event, days in
383 days.contains(day.day) || (event.isReminder && day.day == today && days.upperBound < today)
384 }.map { AgendaRow(event: $0.0, day: day.day, calendar: calendar) }
385 overdue += dayEvents.filter { $0.status == .overdue }
386 overdue = overdue.enumerated().sorted { a, b in
387 a.element.planningDay! != b.element.planningDay! ? a.element.planningDay! < b.element.planningDay! : a.offset < b.offset
388 }.map(\.element)
389 rows = merge(rows, events: dayEvents.filter { $0.status != .overdue })
390 let orgIndices = rows.indices.filter { !rows[$0].isEvent }
391 var group = AgendaDayGroup(day: day.day, isToday: day.day == today, header: day.header, overdue: unique(overdue), rows: unique(rows))
392 group.grid = grid.map { .init(before: $0.ordinal < orgIndices.count ? orgIndices[$0.ordinal] : rows.count, time: $0.time) }
393 group.showsNow = showsNow
394 if group.isEmpty, !group.isToday, !showAllDates { continue }
395 groups.append(group)
396 }
397 return groups
398 }
399
400 /// `org` (in agenda order) with event rows added: untimed events first, timed ones before
401 /// the first untimed entry, or the first timed entry starting later.
402 static func merge(_ org: [AgendaRow], events: [AgendaRow]) -> [AgendaRow] {
403 let allDay = events.filter { $0.start == nil }
404 var result = org
405 let timed = events.filter { $0.start != nil }.enumerated().sorted { a, b in
406 a.element.start! != b.element.start! ? a.element.start! < b.element.start! : a.offset < b.offset
407 }.map(\.element)
408 for event in timed {
409 let at = result.firstIndex { row in
410 if row.isEvent { return row.start.map { $0 > event.start! } ?? false }
411 guard let start = row.start else { return true }
412 return start > event.start!
413 } ?? result.count
414 result.insert(event, at: at)
415 }
416 return allDay + result
417 }
418
419 /// Ids made unique: a repeat gets `#2`, `#3`.
420 static func unique(_ rows: [AgendaRow]) -> [AgendaRow] {
421 var seen: [String: Int] = [:]
422 return rows.map { row in
423 var row = row
424 let n = seen[row.id, default: 0] + 1
425 seen[row.id] = n
426 if n > 1 { row.id += "#\(n)" }
427 return row
428 }
429 }
430
431 /// See `AgendaDayGroup.nowIndex(now:)`.
432 public static func nowIndex(_ rows: [AgendaRow], now: Int) -> Int? {
433 let timed = rows.indices.filter { rows[$0].start != nil }
434 guard let last = timed.last else { return nil }
435 return timed.first { rows[$0].start! > now } ?? last + 1
436 }
437}