Sources/OrgPresentation/AgendaRows.swift

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