Sources/OrgPresentation/AgendaRows.swift

0e0e407283348bd34049ed9fd407e459e98d4d07
orgstar/Sources/OrgPresentation/AgendaRows.swift

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

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form