Sources/OrgPresentation/AgendaRows.swift

b4eeefea9b0dbf6952995d9accda575f1b2b5060
orgstar/Sources/OrgPresentation/AgendaRows.swift

350 lines · 15094 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
245    public var id: Int { day }
246    public var isEmpty: Bool { overdue.isEmpty && rows.isEmpty }
247
248    /// `Today`, `Tomorrow`, `Yesterday`, or nil.
249    public func relativeName(today: Int) -> String? {
250        switch day - today {
251        case 0: "Today"
252        case 1: "Tomorrow"
253        case -1: "Yesterday"
254        default: nil
255        }
256    }
257
258    /// Midnight starting the day.
259    public func date(calendar: Calendar) -> Date {
260        let d = Days.date(day)
261        return calendar.date(from: DateComponents(year: d.year, month: d.month, day: d.day))!
262    }
263
264    /// Where the current-time line goes in `rows`: before the first timed row starting after
265    /// `now` (`HHMM`), or after the last timed row when all have started. Nil on other days
266    /// and when no row is timed, as Org adds the line only among timed entries.
267    public func nowIndex(now: Int) -> Int? {
268        guard isToday else { return nil }
269        return AgendaRows.nowIndex(rows, now: now)
270    }
271}
272
273public enum AgendaRows {
274    /// The days of `Agenda.list` as rows, with `events` merged in.
275    ///
276    /// - Days with no rows are left out unless `showAllDates` (`org-agenda-show-all-dates`);
277    ///   today always stays.
278    /// - Today's past-scheduled entries and past deadlines (not habits) go in `overdue`,
279    ///   oldest date first, Org's order among the same date.
280    /// - Other rows keep Org's order (timed by time, then untimed by urgency, habits last).
281    ///   All-day events come first, timed events go among the timed entries by start time,
282    ///   after entries at the same time.
283    /// - `keep` filters the Org entries (an `AgendaFilter`); events are not filtered.
284    public static func groups(
285        _ days: [AgendaDay], events: [AgendaEvent] = [], today: Int, showAllDates: Bool = false, calendar: Calendar = .current,
286        keep: (AgendaItem) -> Bool = { _ in true }
287    ) -> [AgendaDayGroup] {
288        let eventDays = events.map { ($0, $0.days(calendar: calendar)) }
289        var groups: [AgendaDayGroup] = []
290        for day in days {
291            var overdue: [AgendaRow] = []
292            var rows: [AgendaRow] = []
293            for item in day.items where keep(item) {
294                guard let row = AgendaRow(item: item, day: day.day, today: today) else { continue }
295                if day.day == today, item.habit == nil, let planning = row.planningDay, planning < today {
296                    overdue.append(row)
297                } else {
298                    rows.append(row)
299                }
300            }
301            overdue = overdue.enumerated().sorted { a, b in
302                a.element.planningDay! != b.element.planningDay! ? a.element.planningDay! < b.element.planningDay! : a.offset < b.offset
303            }.map(\.element)
304            let dayEvents = eventDays.filter { $0.1.contains(day.day) }.map { AgendaRow(event: $0.0, day: day.day, calendar: calendar) }
305            rows = merge(rows, events: dayEvents)
306            let group = AgendaDayGroup(day: day.day, isToday: day.day == today, header: day.header, overdue: unique(overdue), rows: unique(rows))
307            if group.isEmpty, !group.isToday, !showAllDates { continue }
308            groups.append(group)
309        }
310        return groups
311    }
312
313    /// `org` (in Org's order) with event rows added: untimed events first, timed ones before
314    /// the first untimed or habit entry, or the first timed entry starting later.
315    static func merge(_ org: [AgendaRow], events: [AgendaRow]) -> [AgendaRow] {
316        let allDay = events.filter { $0.start == nil }
317        var result = org
318        let timed = events.filter { $0.start != nil }.enumerated().sorted { a, b in
319            a.element.start! != b.element.start! ? a.element.start! < b.element.start! : a.offset < b.offset
320        }.map(\.element)
321        for event in timed {
322            let at = result.firstIndex { row in
323                if row.isEvent { return row.start.map { $0 > event.start! } ?? false }
324                guard let start = row.start, row.item?.habit == nil else { return true }
325                return start > event.start!
326            } ?? result.count
327            result.insert(event, at: at)
328        }
329        return allDay + result
330    }
331
332    /// Ids made unique: a repeat gets `#2`, `#3`.
333    static func unique(_ rows: [AgendaRow]) -> [AgendaRow] {
334        var seen: [String: Int] = [:]
335        return rows.map { row in
336            var row = row
337            let n = seen[row.id, default: 0] + 1
338            seen[row.id] = n
339            if n > 1 { row.id += "#\(n)" }
340            return row
341        }
342    }
343
344    /// See `AgendaDayGroup.nowIndex(now:)`.
345    public static func nowIndex(_ rows: [AgendaRow], now: Int) -> Int? {
346        let timed = rows.indices.filter { rows[$0].start != nil && rows[$0].item?.habit == nil }
347        guard let last = timed.last else { return nil }
348        return timed.first { rows[$0].start! > now } ?? last + 1
349    }
350}
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