Sources/OrgPresentation/AgendaRows.swift

06941b2cf25c6ccc1629723cd7951910ce15e67a
orgstar/Sources/OrgPresentation/AgendaRows.swift history · blame · raw

392 lines · 17024 bytes

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