Agenda redesign: shared rows, groups, theme keys and calendar events !181

merged merged by cmc on 2026-10-09 04:51 UTC · krz/orgstar:agenda-foundation into main

18 files changed, +1150 −10

Layout: unified · split

Sources/OrgApp/AgendaModel.swift +31 −1
@@ -2,6 +2,7 @@ import Foundation
2import Observation 2import Observation
3import OrgCore 3import OrgCore
4import OrgIndex 4import OrgIndex
5import OrgPresentation
5 6
6/// The day/week agenda over the workspace's agenda files. Sources are read from disk and 7/// The day/week agenda over the workspace's agenda files. Sources are read from disk and
7/// cached by modification date and size; the open file's come from its buffer, so the agenda 8/// cached by modification date and size; the open file's come from its buffer, so the agenda
@@ -22,6 +23,14 @@ public final class AgendaModel {
22 public var includeSubfolders = false 23 public var includeSubfolders = false
23 public var options = AgendaOptions() 24 public var options = AgendaOptions()
24 public private(set) var isComputing = false 25 public private(set) var isComputing = false
26 /// Calendar events over the days shown, from `calendarEvents` (nil reads none) and the
27 /// calendars in `calendarNames` (all when empty).
28 public private(set) var events: [AgendaEvent] = []
29 public var calendarEvents: CalendarEvents?
30 public var calendarNames: [String] = []
31 /// Today and the calendar of the last refresh.
32 public private(set) var today = Days.absolute(Date(), calendar: .current)
33 @ObservationIgnored private var calendar = Calendar.current
25 34
26 private let workspace: WorkspaceModel 35 private let workspace: WorkspaceModel
27 @ObservationIgnored private var cache: [String: (mtime: Date, size: Int, source: AgendaSource)] = [:] 36 @ObservationIgnored private var cache: [String: (mtime: Date, size: Int, source: AgendaSource)] = [:]
@@ -57,23 +66,33 @@ public final class AgendaModel {
57 let first = start ?? today + startOffset 66 let first = start ?? today + startOffset
58 let options = self.options 67 let options = self.options
59 let mode = self.mode 68 let mode = self.mode
69 let provider = calendarEvents
70 let names = calendarNames
60 let all = await sources(open: open) 71 let all = await sources(open: open)
61 let result = await Task.detached { 72 let result = await Task.detached {
62 var days: [AgendaDay] = [] 73 var days: [AgendaDay] = []
63 var list: [AgendaItem] = [] 74 var list: [AgendaItem] = []
75 var events: [AgendaEvent] = []
64 switch mode { 76 switch mode {
65 case .agenda: 77 case .agenda:
66 days = Agenda.list(all, start: first, days: span, today: today, now: (clock.hour ?? 0, clock.minute ?? 0), options: options) 78 days = Agenda.list(all, start: first, days: span, today: today, now: (clock.hour ?? 0, clock.minute ?? 0), options: options)
79 if let provider {
80 let from = Self.date(first, calendar: calendar)
81 events = provider.events(from: from, to: Self.date(first + span, calendar: calendar), chosen: names)
82 }
67 case .todo(let keywords): 83 case .todo(let keywords):
68 list = Agenda.todoList(all, keywords: keywords, options: options) 84 list = Agenda.todoList(all, keywords: keywords, options: options)
69 case .match(let match, let todoOnly): 85 case .match(let match, let todoOnly):
70 list = Agenda.tagsMatch(all, match: match, todoOnly: todoOnly, now: now, calendar: calendar, options: options) 86 list = Agenda.tagsMatch(all, match: match, todoOnly: todoOnly, now: now, calendar: calendar, options: options)
71 } 87 }
72 return (days, list) 88 return (days, list, events)
73 }.value 89 }.value
74 guard id == generation else { return } 90 guard id == generation else { return }
75 days = result.0 91 days = result.0
76 list = result.1 92 list = result.1
93 events = result.2
94 self.today = today
95 self.calendar = calendar
77 isComputing = false 96 isComputing = false
78 } 97 }
79 98
@@ -126,6 +145,17 @@ public final class AgendaModel {
126 return loaded.map(\.source) 145 return loaded.map(\.source)
127 } 146 }
128 147
148 /// The days as rows with the events, empty days hidden unless `showAllDates`; see
149 /// `AgendaRows.groups`.
150 public func groups(showAllDates: Bool = false, keep: (AgendaItem) -> Bool = { _ in true }) -> [AgendaDayGroup] {
151 AgendaRows.groups(days, events: events, today: today, showAllDates: showAllDates, calendar: calendar, keep: keep)
152 }
153
154 nonisolated static func date(_ day: Int, calendar: Calendar) -> Date {
155 let d = Days.date(day)
156 return calendar.date(from: DateComponents(year: d.year, month: d.month, day: d.day)) ?? Date()
157 }
158
129 public func showToday() { start = nil } 159 public func showToday() { start = nil }
130 160
131 /// Moves the view by a whole span, forward or back. 161 /// Moves the view by a whole span, forward or back.
Sources/OrgApp/CalendarEvents.swift added +86
@@ -0,0 +1,86 @@
1import CoreGraphics
2import EventKit
3import Foundation
4import OrgCore
5import OrgPresentation
6
7/// What the agenda reads from a calendar event: `EKEvent`, or a value made in tests.
8public protocol CalendarEventRecord {
9 var recordID: String { get }
10 var recordTitle: String { get }
11 var recordStart: Date { get }
12 var recordEnd: Date { get }
13 var recordIsAllDay: Bool { get }
14 var recordLocation: String? { get }
15 var recordCalendarID: String { get }
16 var recordCalendarTitle: String { get }
17 var recordCalendarColor: CGColor? { get }
18}
19
20extension EKEvent: CalendarEventRecord {
21 /// A repeating event's occurrences share an identifier; the start tells them apart.
22 public var recordID: String { (eventIdentifier ?? calendarItemIdentifier) + "@" + String(Int(startDate.timeIntervalSince1970)) }
23 public var recordTitle: String { title ?? "" }
24 public var recordStart: Date { startDate }
25 public var recordEnd: Date { endDate }
26 public var recordIsAllDay: Bool { isAllDay }
27 public var recordLocation: String? { location.flatMap { $0.isEmpty ? nil : $0 } }
28 public var recordCalendarID: String { calendar?.calendarIdentifier ?? "" }
29 public var recordCalendarTitle: String { calendar?.title ?? "" }
30 public var recordCalendarColor: CGColor? { calendar?.cgColor }
31}
32
33/// Read-only events from the system Calendar for the agenda (`calendar-events` in
34/// config.toml), from the calendars `calendar-event-calendars` names.
35public final class CalendarEvents: @unchecked Sendable {
36 private let store = EKEventStore()
37
38 public init() {}
39
40 /// Reading events needs full access; EventKit has no read-only level.
41 public static var isAuthorized: Bool { EKEventStore.authorizationStatus(for: .event) == .fullAccess }
42
43 /// Asks for access once; later calls answer with what the person chose.
44 public func requestAccess() async -> Bool {
45 if Self.isAuthorized { return true }
46 return (try? await store.requestFullAccessToEvents()) ?? false
47 }
48
49 /// The event calendars, for choosing among them.
50 public func calendars() -> [(id: String, title: String, color: RGBA?)] {
51 guard Self.isAuthorized else { return [] }
52 return store.calendars(for: .event).map { ($0.calendarIdentifier, $0.title, $0.cgColor.flatMap(Self.rgba)) }
53 }
54
55 /// Events overlapping `start..<end` in the chosen calendars (all when `chosen` is empty),
56 /// by start. None without access.
57 public func events(from start: Date, to end: Date, chosen: [String]) -> [AgendaEvent] {
58 guard Self.isAuthorized else { return [] }
59 let calendars = store.calendars(for: .event).filter { Self.chooses(id: $0.calendarIdentifier, title: $0.title, chosen: chosen) }
60 guard !calendars.isEmpty else { return [] }
61 let predicate = store.predicateForEvents(withStart: start, end: end, calendars: calendars)
62 return store.events(matching: predicate).map(Self.event).sorted { $0.start < $1.start }
63 }
64
65 /// Whether a calendar is among those chosen by identifier or title; every calendar is when
66 /// none are.
67 public static func chooses(id: String, title: String, chosen: [String]) -> Bool {
68 chosen.isEmpty || chosen.contains(id) || chosen.contains(title)
69 }
70
71 public static func event(_ record: some CalendarEventRecord) -> AgendaEvent {
72 AgendaEvent(
73 id: record.recordID, title: record.recordTitle, calendarID: record.recordCalendarID, calendarTitle: record.recordCalendarTitle,
74 color: record.recordCalendarColor.flatMap(rgba), start: record.recordStart, end: record.recordEnd,
75 isAllDay: record.recordIsAllDay, location: record.recordLocation
76 )
77 }
78
79 /// A color in sRGB.
80 static func rgba(_ color: CGColor) -> RGBA? {
81 guard let space = CGColorSpace(name: CGColorSpace.sRGB),
82 let converted = color.converted(to: space, intent: .defaultIntent, options: nil),
83 let c = converted.components, c.count >= 3 else { return nil }
84 return RGBA(red: Double(c[0]), green: Double(c[1]), blue: Double(c[2]), alpha: Double(converted.alpha))
85 }
86}
Sources/OrgApp/OrgPreferences.swift +17
@@ -50,6 +50,23 @@ public enum OrgPreferences {
50 public static func agendaSpan(_ defaults: UserDefaults = .standard) -> Int { integer("agendaSpan", defaults) } 50 public static func agendaSpan(_ defaults: UserDefaults = .standard) -> Int { integer("agendaSpan", defaults) }
51 public static func agendaStartOffset(_ defaults: UserDefaults = .standard) -> Int { integer("agendaStartOffset", defaults) } 51 public static func agendaStartOffset(_ defaults: UserDefaults = .standard) -> Int { integer("agendaStartOffset", defaults) }
52 public static func agendaSubfolders(_ defaults: UserDefaults = .standard) -> Bool { bool("agendaSubfolders", defaults) } 52 public static func agendaSubfolders(_ defaults: UserDefaults = .standard) -> Bool { bool("agendaSubfolders", defaults) }
53 /// `org-agenda-show-all-dates`: days without entries show.
54 public static func agendaShowAllDates(_ defaults: UserDefaults = .standard) -> Bool { bool("agendaShowAllDates", defaults) }
55 public static func agendaSkipScheduledIfDone(_ defaults: UserDefaults = .standard) -> Bool { bool("agendaSkipScheduledIfDone", defaults) }
56 public static func agendaSkipDeadlineIfDone(_ defaults: UserDefaults = .standard) -> Bool { bool("agendaSkipDeadlineIfDone", defaults) }
57 /// `options` with the skip-if-done settings.
58 public static func agendaOptions(_ options: AgendaOptions, _ defaults: UserDefaults = .standard) -> AgendaOptions {
59 var options = options
60 options.skipScheduledIfDone = agendaSkipScheduledIfDone(defaults)
61 options.skipDeadlineIfDone = agendaSkipDeadlineIfDone(defaults)
62 return options
63 }
64 /// `calendar-events`: Calendar's events show in the agenda.
65 public static func calendarEvents(_ defaults: UserDefaults = .standard) -> Bool { bool("calendarEvents", defaults) }
66 /// `calendar-event-calendars`: the calendars chosen, by title or identifier; empty for all.
67 public static func calendarEventCalendars(_ defaults: UserDefaults = .standard) -> [String] {
68 string("calendarEventCalendars", defaults).split(separator: ",").map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty }
69 }
53 public static func reminders(_ defaults: UserDefaults = .standard) -> Bool { bool("reminders", defaults) } 70 public static func reminders(_ defaults: UserDefaults = .standard) -> Bool { bool("reminders", defaults) }
54 /// `appt-message-warning-time`, in minutes. 71 /// `appt-message-warning-time`, in minutes.
55 public static func reminderLead(_ defaults: UserDefaults = .standard) -> Int { integer("reminderLead", defaults) } 72 public static func reminderLead(_ defaults: UserDefaults = .standard) -> Int { integer("reminderLead", defaults) }
Sources/OrgApp/UserConfig.swift +10
@@ -141,6 +141,12 @@ public enum UserConfig {
141 comment: "days the agenda shows", legacy: "agenda.span"), 141 comment: "days the agenda shows", legacy: "agenda.span"),
142 Setting(section: "", key: "org-agenda-start-day", defaultsKey: "agendaStartOffset", kind: .dayOffset, fallback: .string("-3d"), 142 Setting(section: "", key: "org-agenda-start-day", defaultsKey: "agendaStartOffset", kind: .dayOffset, fallback: .string("-3d"),
143 comment: "the agenda's first day: \"-3d\", \"+0d\"", legacy: "agenda.start-offset"), 143 comment: "the agenda's first day: \"-3d\", \"+0d\"", legacy: "agenda.start-offset"),
144 Setting(section: "", key: "org-agenda-show-all-dates", defaultsKey: "agendaShowAllDates", kind: .bool, fallback: .bool(false),
145 comment: "show days with no entries (Emacs's default is t; Orgstar hides them); today always shows", legacy: ""),
146 Setting(section: "", key: "org-agenda-skip-scheduled-if-done", defaultsKey: "agendaSkipScheduledIfDone", kind: .bool, fallback: .bool(false),
147 comment: "leave done entries out of the agenda even on the day they are scheduled", legacy: ""),
148 Setting(section: "", key: "org-agenda-skip-deadline-if-done", defaultsKey: "agendaSkipDeadlineIfDone", kind: .bool, fallback: .bool(false),
149 comment: "leave done entries out of the agenda even on the day they are due", legacy: ""),
144 Setting(section: "", key: "appt-message-warning-time", defaultsKey: "reminderLead", kind: .integer, fallback: .integer(12), 150 Setting(section: "", key: "appt-message-warning-time", defaultsKey: "reminderLead", kind: .integer, fallback: .integer(12),
145 comment: "minutes of warning before timed entries; APPT_WARNTIME overrides", legacy: "agenda.reminder-lead"), 151 comment: "minutes of warning before timed entries; APPT_WARNTIME overrides", legacy: "agenda.reminder-lead"),
146 Setting(section: "", key: "org-clock-idle-time", defaultsKey: "clockIdleTime", kind: .integer, fallback: .integer(0), 152 Setting(section: "", key: "org-clock-idle-time", defaultsKey: "clockIdleTime", kind: .integer, fallback: .integer(0),
@@ -183,6 +189,10 @@ public enum UserConfig {
183 comment: "the agenda reads org files in subfolders too", legacy: "agenda.include-subfolders"), 189 comment: "the agenda reads org files in subfolders too", legacy: "agenda.include-subfolders"),
184 Setting(section: "orgstar", key: "reminders", defaultsKey: "reminders", kind: .bool, fallback: .bool(true), 190 Setting(section: "orgstar", key: "reminders", defaultsKey: "reminders", kind: .bool, fallback: .bool(true),
185 comment: "notify before timed entries", legacy: "agenda.reminders"), 191 comment: "notify before timed entries", legacy: "agenda.reminders"),
192 Setting(section: "orgstar", key: "calendar-events", defaultsKey: "calendarEvents", kind: .bool, fallback: .bool(false),
193 comment: "show events from Calendar in the agenda, read-only", legacy: ""),
194 Setting(section: "orgstar", key: "calendar-event-calendars", defaultsKey: "calendarEventCalendars", kind: .string, fallback: .string(""),
195 comment: "the calendars whose events show, by title or identifier, separated by commas; \"\" for all", legacy: ""),
186 Setting(section: "orgstar", key: "global-capture-hotkey", defaultsKey: "globalCapture", kind: .bool, fallback: .bool(true), 196 Setting(section: "orgstar", key: "global-capture-hotkey", defaultsKey: "globalCapture", kind: .bool, fallback: .bool(true),
187 comment: "⌃⌥Space opens Capture from any app; templates go in capture.toml", legacy: "capture.global-hotkey"), 197 comment: "⌃⌥Space opens Capture from any app; templates go in capture.toml", legacy: "capture.global-hotkey"),
188 ] 198 ]
Sources/OrgCore/Agenda/Agenda.swift +18 −6
@@ -48,6 +48,9 @@ public struct AgendaItem: Sendable, Equatable {
48 public var prefix = "" 48 public var prefix = ""
49 /// The entry's `Effort` property. 49 /// The entry's `Effort` property.
50 public var effort: String? 50 public var effort: String?
51 /// Deadlines and scheduled items: the day (as `Days` numbers it) of the timestamp the item
52 /// is for, the repeater's occurrence when the item shows on it.
53 public var planningDay: Int?
51} 54}
52 55
53public struct AgendaDay: Sendable, Equatable { 56public struct AgendaDay: Sendable, Equatable {
@@ -71,6 +74,11 @@ public struct AgendaOptions: Sendable, Equatable {
71 public var logMode = false 74 public var logMode = false
72 /// `org-agenda-log-mode-items`. 75 /// `org-agenda-log-mode-items`.
73 public var logItems: Set<String> = ["closed", "clock"] 76 public var logItems: Set<String> = ["closed", "clock"]
77 /// `org-agenda-skip-scheduled-if-done`: done entries' scheduled items are left out even
78 /// on the day they are scheduled.
79 public var skipScheduledIfDone = false
80 /// `org-agenda-skip-deadline-if-done`: done entries' deadlines are left out even on the day due.
81 public var skipDeadlineIfDone = false
74 82
75 public init() {} 83 public init() {}
76 84
@@ -139,7 +147,7 @@ public enum Agenda {
139 continue 147 continue
140 } 148 }
141 } 149 }
142 if heading.isDone, deadline != current { continue } 150 if heading.isDone, options.skipDeadlineIfDone || deadline != current { continue }
143 let time: Dotime? = current != deadline && current != repeat_ ? nil : (timeIn(s).map { .string($0) } ?? .headline) 151 let time: Dotime? = current != deadline && current != repeat_ ? nil : (timeIn(s).map { .string($0) } ?? .headline)
144 let extra: String 152 let extra: String
145 if isToday, deadline < today { 153 if isToday, deadline < today {
@@ -150,10 +158,12 @@ public enum Agenda {
150 extra = "Deadline: " 158 extra = "Deadline: "
151 } 159 }
152 let upcoming = isToday && deadline > today 160 let upcoming = isToday && deadline > today
153 items.append(format( 161 var item = format(
154 source, heading, kind: upcoming ? .upcomingDeadline : .deadline, marker: offset, extra: extra, 162 source, heading, kind: upcoming ? .upcomingDeadline : .deadline, marker: offset, extra: extra,
155 dotime: time, removing: nil, trailing: options.gridTrailing, prefix: options.prefix("agenda"), urgency: { (isToday ? -diff : 0) + $0 } 163 dotime: time, removing: nil, trailing: options.gridTrailing, prefix: options.prefix("agenda"), urgency: { (isToday ? -diff : 0) + $0 }
156 )) 164 )
165 item.planningDay = current != deadline && current == repeat_ ? repeat_ : deadline
166 items.append(item)
157 } 167 }
158 return items 168 return items
159 } 169 }
@@ -171,17 +181,19 @@ public enum Agenda {
171 || (current != schedule && current != today && current != repeat_) { 181 || (current != schedule && current != today && current != repeat_) {
172 continue 182 continue
173 } 183 }
174 if heading.isDone, schedule != current { continue } 184 if heading.isDone, options.skipScheduledIfDone || schedule != current { continue }
175 // org-habit: habits only on today's agenda, and not when done. 185 // org-habit: habits only on today's agenda, and not when done.
176 if heading.isHabit, heading.isDone || !isToday { continue } 186 if heading.isHabit, heading.isDone || !isToday { continue }
177 let time: Dotime? = !heading.isHabit && current != schedule && current != repeat_ ? nil : (timeIn(s).map { .string($0) } ?? .headline) 187 let time: Dotime? = !heading.isHabit && current != schedule && current != repeat_ ? nil : (timeIn(s).map { .string($0) } ?? .headline)
178 let extra = heading.isHabit ? "" : isToday && past ? String(format: "Sched.%2dx: ", diff) : "Scheduled: " 188 let extra = heading.isHabit ? "" : isToday && past ? String(format: "Sched.%2dx: ", diff) : "Scheduled: "
179 let habit = heading.isHabit ? heading.habit : nil 189 let habit = heading.isHabit ? heading.habit : nil
180 items.append(format( 190 var item = format(
181 source, heading, kind: past ? .pastScheduled : .scheduled, marker: offset, extra: extra, 191 source, heading, kind: past ? .pastScheduled : .scheduled, marker: offset, extra: extra,
182 dotime: time, removing: nil, trailing: options.gridTrailing, prefix: options.prefix("agenda"), habit: habit, 192 dotime: time, removing: nil, trailing: options.gridTrailing, prefix: options.prefix("agenda"), habit: habit,
183 urgency: { habit?.urgency(today: today) ?? 99 + diff + $0 } 193 urgency: { habit?.urgency(today: today) ?? 99 + diff + $0 }
184 )) 194 )
195 item.planningDay = current != schedule && current == repeat_ ? repeat_ : schedule
196 items.append(item)
185 } 197 }
186 return items 198 return items
187 } 199 }
Sources/OrgCore/Agenda/AgendaItemText.swift added +61
@@ -0,0 +1,61 @@
1import Foundation
2
3/// The parts of an item's heading text the agenda rows show apart: the title alone, the
4/// priority letter and the statistics cookie.
5extension AgendaItem {
6 static let priorityCookie = try! NSRegularExpression(pattern: "^\\[#([A-Z]|[0-9]+)\\][ \\t]*")
7 static let statisticsCookie = try! NSRegularExpression(pattern: "\\[([0-9]*(?:%|/[0-9]*))\\]")
8 static let anyTimestamp = try! NSRegularExpression(
9 pattern: "<%%\\([^>\\n]*>|<[0-9]{4}-[0-9]{2}-[0-9]{2}[^>\\n]*>(?:--<[0-9]{4}-[0-9]{2}-[0-9]{2}[^>\\n]*>)?|\\[[0-9]{4}-[0-9]{2}-[0-9]{2}[^\\]\\n]*\\](?:--\\[[0-9]{4}-[0-9]{2}-[0-9]{2}[^\\]\\n]*\\])?"
10 )
11
12 /// `text` after the TODO keyword.
13 private var afterKeyword: String {
14 var t = Substring(text.trimmingCharacters(in: .whitespaces))
15 if let todo, t.hasPrefix(todo), t.dropFirst(todo.count).first.map({ $0 == " " || $0 == "\t" }) ?? true {
16 t = t.dropFirst(todo.count)
17 }
18 return t.trimmingCharacters(in: .whitespaces)
19 }
20
21 /// The heading's title without TODO keyword, priority cookie, statistics cookies,
22 /// timestamps or tags, links as their descriptions, runs of spaces made one. The text itself
23 /// when nothing is left.
24 public var title: String {
25 var t = afterKeyword
26 t = Self.priorityCookie.stringByReplacingMatches(in: t, range: NSRange(location: 0, length: (t as NSString).length), withTemplate: "")
27 t = Self.statisticsCookie.stringByReplacingMatches(in: t, range: NSRange(location: 0, length: (t as NSString).length), withTemplate: "")
28 t = Self.anyTimestamp.stringByReplacingMatches(in: t, range: NSRange(location: 0, length: (t as NSString).length), withTemplate: "")
29 t = Links.displayFormat(t).replacingOccurrences(of: "[ \\t]+", with: " ", options: .regularExpression)
30 .trimmingCharacters(in: .whitespaces)
31 return t.isEmpty ? text.trimmingCharacters(in: .whitespaces) : t
32 }
33
34 /// The letter or number of the priority cookie (`[#A]`), when the heading has one.
35 public var priorityLetter: String? {
36 let t = afterKeyword
37 guard let m = Self.priorityCookie.firstMatch(in: t, range: NSRange(location: 0, length: (t as NSString).length)) else { return nil }
38 return (t as NSString).substring(with: m.range(at: 1))
39 }
40
41 /// The first statistics cookie's value: `1/3` or `50%`.
42 public var progress: String? {
43 let t = afterKeyword
44 guard let m = Self.statisticsCookie.firstMatch(in: t, range: NSRange(location: 0, length: (t as NSString).length)) else { return nil }
45 return (t as NSString).substring(with: m.range(at: 1))
46 }
47}
48
49/// Ages and distances in days, compactly: under 14 days in days (`3d`), under 60 in whole
50/// weeks (`2w`), under a year in 30-day months (`4mo`, at most 11), then years of 365 days with
51/// any remaining months (`1y`, `1y 4mo`). Values round down; the sign is ignored.
52public enum AgendaAge {
53 public static func compact(_ days: Int) -> String {
54 let d = abs(days)
55 if d < 14 { return "\(d)d" }
56 if d < 60 { return "\(d / 7)w" }
57 if d < 365 { return "\(min(11, d / 30))mo" }
58 let months = min(11, (d % 365) / 30)
59 return months == 0 ? "\(d / 365)y" : "\(d / 365)y \(months)mo"
60 }
61}
Sources/OrgPresentation/AgendaRows.swift added +319
@@ -0,0 +1,319 @@
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`, `Sched. 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 public let priority: String?
77 /// The statistics cookie: `1/3`, `50%`.
78 public let progress: String?
79 /// `HHMM` of the start and the end, when timed.
80 public let start: Int?
81 public let end: Int?
82 /// The deadline or scheduled day, as `Days` numbers it.
83 public let planningDay: Int?
84 /// The Org entry, for its actions.
85 public let item: AgendaItem?
86 public let event: AgendaEvent?
87
88 public var isEvent: Bool { event != nil }
89 /// The calendar's color for an event.
90 public var color: RGBA? { event?.color }
91
92 /// Nil for the time grid and the current-time line.
93 public init?(item: AgendaItem, day: Int, today: Int) {
94 if item.kind == .timeGrid || item.kind == .currentTime { return nil }
95 let timed = item.timeOfDay.map { start in (start, Self.endTime(item.time)) }
96 let planning = item.planningDay
97 let late = planning.map { $0 < today } ?? false
98 var icon: Icon?
99 var status: Status = .normal
100 var untimed = ""
101 switch item.kind {
102 case .deadline, .upcomingDeadline:
103 icon = .deadline
104 let due = planning ?? day
105 if day == today {
106 untimed = due == today ? "Due today" : due < today ? "\(AgendaAge.compact(today - due)) late" : "Due in \(AgendaAge.compact(due - today))"
107 } else {
108 untimed = "Due"
109 }
110 status = late ? .overdue : day == today ? .dueSoon : .normal
111 case .scheduled, .pastScheduled:
112 if item.habit != nil {
113 icon = .habit
114 untimed = "Habit"
115 } else {
116 icon = .scheduled
117 let on = planning ?? day
118 untimed = on < day ? "Sched. \(AgendaAge.compact(day - on)) ago" : "Scheduled"
119 }
120 status = late ? .overdue : .normal
121 case .timestamp, .sexp:
122 icon = .timestamp
123 untimed = "All day"
124 case .block:
125 icon = .timestamp
126 let ns = item.extra as NSString
127 if let m = Self.rangeDay.firstMatch(in: item.extra, range: NSRange(location: 0, length: ns.length)) {
128 untimed = "Day " + ns.substring(with: m.range(at: 1))
129 } else {
130 untimed = "All day"
131 }
132 case .closed: (icon, untimed) = (.timestamp, "Closed")
133 case .clock: (icon, untimed) = (.timestamp, "Clocked")
134 case .state: (icon, untimed) = (.timestamp, "State")
135 case .todo, .tagsMatch, .timeGrid, .currentTime: break
136 }
137 if item.isDone { status = .done }
138 self.id = [item.path ?? "", "\(item.headingOffset ?? -1)", "\(item.markerOffset ?? -1)", item.kind.rawValue, item.text].joined(separator: "\u{1f}")
139 self.gutter = timed.map { Self.timeText($0.0, $0.1) } ?? untimed
140 self.status = status
141 self.icon = icon
142 self.category = item.category
143 self.title = item.title
144 self.tags = item.tags
145 self.todo = item.todo
146 self.isDone = item.isDone
147 self.priority = item.priorityLetter
148 self.progress = item.progress
149 self.start = timed?.0
150 self.end = timed?.1
151 self.planningDay = planning
152 self.item = item
153 self.event = nil
154 }
155
156 /// The event's row on `day`: its times on the day it starts (the end only when it ends that
157 /// day too), `Until 10:00` on the day a longer event ends, `All day` otherwise.
158 public init(event: AgendaEvent, day: Int, calendar: Calendar) {
159 let days = event.days(calendar: calendar)
160 func hhmm(_ date: Date) -> Int {
161 let c = calendar.dateComponents([.hour, .minute], from: date)
162 return (c.hour ?? 0) * 100 + (c.minute ?? 0)
163 }
164 var start: Int?
165 var end: Int?
166 let gutter: String
167 if event.isAllDay || (day != days.lowerBound && day != days.upperBound) {
168 gutter = "All day"
169 } else if day == days.lowerBound {
170 start = hhmm(event.start)
171 if days.lowerBound == days.upperBound { end = hhmm(event.end) }
172 gutter = Self.timeText(start!, end)
173 } else {
174 gutter = "Until " + Self.timeText(hhmm(event.end), nil)
175 }
176 self.id = "event\u{1f}" + event.id
177 self.gutter = gutter
178 self.status = .normal
179 self.icon = .event
180 self.category = event.calendarTitle
181 self.title = event.title
182 self.tags = []
183 self.todo = nil
184 self.isDone = false
185 self.priority = nil
186 self.progress = nil
187 self.start = start
188 self.end = end
189 self.planningDay = nil
190 self.item = nil
191 self.event = event
192 }
193
194 static let rangeDay = try! NSRegularExpression(pattern: "^\\(([0-9]+/[0-9]+)\\)")
195 static let rangeEnd = try! NSRegularExpression(pattern: "-\\+?([0-9]{1,2}):([0-9]{2})")
196
197 /// The end of a `%t` time range (` 9:00-10:30`), as `HHMM`; past midnight (`+1:00`) adds 24 hours.
198 static func endTime(_ time: String) -> Int? {
199 let ns = time as NSString
200 guard let m = rangeEnd.firstMatch(in: time, range: NSRange(location: 0, length: ns.length)) else { return nil }
201 let overtime = ns.substring(with: m.range).contains("+") ? 24 : 0
202 return (Int(ns.substring(with: m.range(at: 1)))! + overtime) * 100 + Int(ns.substring(with: m.range(at: 2)))!
203 }
204
205 /// `08:00`, `13:50–14:30`; hours past midnight wrap.
206 static func timeText(_ start: Int, _ end: Int?) -> String {
207 func text(_ t: Int) -> String { String(format: "%02d:%02d", (t / 100) % 24, t % 100) }
208 return end.map { text(start) + "–" + text($0) } ?? text(start)
209 }
210}
211
212/// One day of the agenda: today's entries carried from earlier days in `overdue`, the rest
213/// in `rows`.
214public struct AgendaDayGroup: Sendable, Equatable, Identifiable {
215 /// As `Days` numbers it.
216 public let day: Int
217 public let isToday: Bool
218 /// Org's day header: `Thursday 8 October 2026`.
219 public let header: String
220 /// Today only: deadlines and scheduled entries from before today, oldest first.
221 public let overdue: [AgendaRow]
222 public let rows: [AgendaRow]
223
224 public var id: Int { day }
225 public var isEmpty: Bool { overdue.isEmpty && rows.isEmpty }
226
227 /// Midnight starting the day.
228 public func date(calendar: Calendar) -> Date {
229 let d = Days.date(day)
230 return calendar.date(from: DateComponents(year: d.year, month: d.month, day: d.day))!
231 }
232
233 /// Where the current-time line goes in `rows`: before the first timed row starting after
234 /// `now` (`HHMM`), or after the last timed row when all have started. Nil on other days
235 /// and when no row is timed, as Org adds the line only among timed entries.
236 public func nowIndex(now: Int) -> Int? {
237 guard isToday else { return nil }
238 return AgendaRows.nowIndex(rows, now: now)
239 }
240}
241
242public enum AgendaRows {
243 /// The days of `Agenda.list` as rows, with `events` merged in.
244 ///
245 /// - Days with no rows are left out unless `showAllDates` (`org-agenda-show-all-dates`);
246 /// today always stays.
247 /// - Today's past-scheduled entries and past deadlines (not habits) go in `overdue`,
248 /// oldest date first, Org's order among the same date.
249 /// - Other rows keep Org's order (timed by time, then untimed by urgency, habits last).
250 /// All-day events come first, timed events go among the timed entries by start time,
251 /// after entries at the same time.
252 /// - `keep` filters the Org entries (an `AgendaFilter`); events are not filtered.
253 public static func groups(
254 _ days: [AgendaDay], events: [AgendaEvent] = [], today: Int, showAllDates: Bool = false, calendar: Calendar = .current,
255 keep: (AgendaItem) -> Bool = { _ in true }
256 ) -> [AgendaDayGroup] {
257 let eventDays = events.map { ($0, $0.days(calendar: calendar)) }
258 var groups: [AgendaDayGroup] = []
259 for day in days {
260 var overdue: [AgendaRow] = []
261 var rows: [AgendaRow] = []
262 for item in day.items where keep(item) {
263 guard let row = AgendaRow(item: item, day: day.day, today: today) else { continue }
264 if day.day == today, item.habit == nil, let planning = row.planningDay, planning < today {
265 overdue.append(row)
266 } else {
267 rows.append(row)
268 }
269 }
270 overdue = overdue.enumerated().sorted { a, b in
271 a.element.planningDay! != b.element.planningDay! ? a.element.planningDay! < b.element.planningDay! : a.offset < b.offset
272 }.map(\.element)
273 let dayEvents = eventDays.filter { $0.1.contains(day.day) }.map { AgendaRow(event: $0.0, day: day.day, calendar: calendar) }
274 rows = merge(rows, events: dayEvents)
275 let group = AgendaDayGroup(day: day.day, isToday: day.day == today, header: day.header, overdue: unique(overdue), rows: unique(rows))
276 if group.isEmpty, !group.isToday, !showAllDates { continue }
277 groups.append(group)
278 }
279 return groups
280 }
281
282 /// `org` (in Org's order) with event rows added: untimed events first, timed ones before
283 /// the first untimed or habit entry, or the first timed entry starting later.
284 static func merge(_ org: [AgendaRow], events: [AgendaRow]) -> [AgendaRow] {
285 let allDay = events.filter { $0.start == nil }
286 var result = org
287 let timed = events.filter { $0.start != nil }.enumerated().sorted { a, b in
288 a.element.start! != b.element.start! ? a.element.start! < b.element.start! : a.offset < b.offset
289 }.map(\.element)
290 for event in timed {
291 let at = result.firstIndex { row in
292 if row.isEvent { return row.start.map { $0 > event.start! } ?? false }
293 guard let start = row.start, row.item?.habit == nil else { return true }
294 return start > event.start!
295 } ?? result.count
296 result.insert(event, at: at)
297 }
298 return allDay + result
299 }
300
301 /// Ids made unique: a repeat gets `#2`, `#3`.
302 static func unique(_ rows: [AgendaRow]) -> [AgendaRow] {
303 var seen: [String: Int] = [:]
304 return rows.map { row in
305 var row = row
306 let n = seen[row.id, default: 0] + 1
307 seen[row.id] = n
308 if n > 1 { row.id += "#\(n)" }
309 return row
310 }
311 }
312
313 /// See `AgendaDayGroup.nowIndex(now:)`.
314 public static func nowIndex(_ rows: [AgendaRow], now: Int) -> Int? {
315 let timed = rows.indices.filter { rows[$0].start != nil && rows[$0].item?.habit == nil }
316 guard let last = timed.last else { return nil }
317 return timed.first { rows[$0].start! > now } ?? last + 1
318 }
319}
Sources/OrgPresentation/ThemeSpec.swift +122 −2
@@ -33,8 +33,8 @@ public struct RGBA: Hashable, Sendable {
33} 33}
34 34
35/// The editor's look: colors for each kind of text in light and dark appearance, colors for 35/// The editor's look: colors for each kind of text in light and dark appearance, colors for
36/// TODO keywords, and type. Read from `[theme]`, `[theme.light]`, `[theme.dark]` and 36/// TODO keywords and categories, and type. Read from `[theme]`, `[theme.light]`, `[theme.dark]`,
37/// `[theme.todo]` in config.toml, on top of the default theme. 37/// `[theme.todo]` and `[theme.category]` in config.toml, on top of the default theme.
38public struct ThemeSpec: Equatable, Sendable { 38public struct ThemeSpec: Equatable, Sendable {
39 /// A font family; empty for the system's monospaced font. 39 /// A font family; empty for the system's monospaced font.
40 public var font = "" 40 public var font = ""
@@ -47,6 +47,8 @@ public struct ThemeSpec: Equatable, Sendable {
47 public var dark: [String: RGBA] 47 public var dark: [String: RGBA]
48 /// `org-todo-keyword-faces`: a color per keyword, the same in both appearances. 48 /// `org-todo-keyword-faces`: a color per keyword, the same in both appearances.
49 public var todo: [String: RGBA] = [:] 49 public var todo: [String: RGBA] = [:]
50 /// A color per agenda category, the same in both appearances, over `categoryColor`'s hue.
51 public var category: [String: RGBA] = [:]
50 52
51 public init(light: [String: RGBA], dark: [String: RGBA]) { 53 public init(light: [String: RGBA], dark: [String: RGBA]) {
52 self.light = light 54 self.light = light
@@ -69,8 +71,14 @@ public struct ThemeSpec: Equatable, Sendable {
69 ("heading-4", "level 4 headings"), ("heading-5", "level 5 headings"), ("heading-6", "level 6 headings"), 71 ("heading-4", "level 4 headings"), ("heading-5", "level 5 headings"), ("heading-6", "level 6 headings"),
70 ("heading-7", "level 7 headings"), ("heading-8", "level 8 and deeper headings"), 72 ("heading-7", "level 7 headings"), ("heading-8", "level 8 and deeper headings"),
71 ("todo", "TODO keywords not yet done"), 73 ("todo", "TODO keywords not yet done"),
74 ("todo-next", "keywords of work under way: NEXT, STRT, STARTED, DOING, ACTIVE"),
75 ("todo-waiting", "keywords of work on hold: WAIT, WAITING, HOLD, BLOCKED, DEFERRED, SOMEDAY, MAYBE"),
72 ("done", "DONE keywords"), 76 ("done", "DONE keywords"),
77 ("todo-cancelled", "done keywords that cancel: KILL, CANCELLED, CANCELED, CANCEL, SKIPPED, SKIP, ABORTED, NO, WONTFIX"),
73 ("priority", "[#A] cookies"), 78 ("priority", "[#A] cookies"),
79 ("priority-a", "agenda: priority A"),
80 ("priority-b", "agenda: priority B"),
81 ("priority-c", "agenda: priority C"),
74 ("tags", ":tags:"), 82 ("tags", ":tags:"),
75 ("link", "links"), 83 ("link", "links"),
76 ("timestamp", "timestamps"), 84 ("timestamp", "timestamps"),
@@ -113,6 +121,9 @@ public struct ThemeSpec: Equatable, Sendable {
113 ("agenda-upcoming", "deadlines coming up"), 121 ("agenda-upcoming", "deadlines coming up"),
114 ("agenda-scheduled", "scheduled items"), 122 ("agenda-scheduled", "scheduled items"),
115 ("agenda-scheduled-past", "items scheduled on an earlier day"), 123 ("agenda-scheduled-past", "items scheduled on an earlier day"),
124 ("agenda-overdue", "agenda: the status of entries past their deadline or scheduled date"),
125 ("agenda-due-soon", "agenda: the status of deadlines due today or coming up"),
126 ("agenda-event", "agenda: calendar events whose calendar has no color"),
116 ("habit-clear", "habit graph: not due yet"), 127 ("habit-clear", "habit graph: not due yet"),
117 ("habit-ready", "habit graph: due"), 128 ("habit-ready", "habit graph: due"),
118 ("habit-alert", "habit graph: due today, last chance"), 129 ("habit-alert", "habit graph: due today, last chance"),
@@ -138,6 +149,8 @@ public struct ThemeSpec: Equatable, Sendable {
138 "heading-1": "#0550ae", "heading-2": "#8250df", "heading-3": "#116329", "heading-4": "#953800", 149 "heading-1": "#0550ae", "heading-2": "#8250df", "heading-3": "#116329", "heading-4": "#953800",
139 "heading-5": "#0550ae", "heading-6": "#8250df", "heading-7": "#116329", "heading-8": "#953800", 150 "heading-5": "#0550ae", "heading-6": "#8250df", "heading-7": "#116329", "heading-8": "#953800",
140 "todo": "#cf222e", "done": "#1a7f37", "priority": "#bc4c00", "tags": "#6e7781", 151 "todo": "#cf222e", "done": "#1a7f37", "priority": "#bc4c00", "tags": "#6e7781",
152 "todo-next": "#0969da", "todo-waiting": "#9a6700", "todo-cancelled": "#6e7781",
153 "priority-a": "#cf222e", "priority-b": "#bc4c00", "priority-c": "#57606a",
141 "link": "#0969da", "timestamp": "#8250df", "code": "#953800", "verbatim": "#0a3069", "inline-background": "#afb8c133", 154 "link": "#0969da", "timestamp": "#8250df", "code": "#953800", "verbatim": "#0a3069", "inline-background": "#afb8c133",
142 "markup": "#8c959f", "comment": "#6e7781", "keyword": "#6e7781", "metadata": "#6e7781", "special": "#1b7c83", 155 "markup": "#8c959f", "comment": "#6e7781", "keyword": "#6e7781", "metadata": "#6e7781", "special": "#1b7c83",
143 "block-background": "#f6f8fa", "block-delimiter": "#8c959f", "table": "#1f2328", 156 "block-background": "#f6f8fa", "block-delimiter": "#8c959f", "table": "#1f2328",
@@ -147,6 +160,7 @@ public struct ThemeSpec: Equatable, Sendable {
147 "modeline-highlight": "#1f2328", "state-normal": "#0969da", "state-insert": "#1a7f37", "state-visual": "#bc4c00", 160 "modeline-highlight": "#1f2328", "state-normal": "#0969da", "state-insert": "#1a7f37", "state-visual": "#bc4c00",
148 "agenda-date": "#1f2328", "agenda-today": "#0969da", "agenda-time": "#6e7781", "agenda-category": "#6e7781", 161 "agenda-date": "#1f2328", "agenda-today": "#0969da", "agenda-time": "#6e7781", "agenda-category": "#6e7781",
149 "agenda-deadline": "#cf222e", "agenda-upcoming": "#bc4c00", "agenda-scheduled": "#6e7781", "agenda-scheduled-past": "#953800", 162 "agenda-deadline": "#cf222e", "agenda-upcoming": "#bc4c00", "agenda-scheduled": "#6e7781", "agenda-scheduled-past": "#953800",
163 "agenda-overdue": "#cf222e", "agenda-due-soon": "#bc4c00", "agenda-event": "#8250df",
150 "habit-clear": "#54aeff", "habit-ready": "#4ac26b", "habit-alert": "#d4a72c", "habit-overdue": "#ff8182", 164 "habit-clear": "#54aeff", "habit-ready": "#4ac26b", "habit-alert": "#d4a72c", "habit-overdue": "#ff8182",
151 ]), 165 ]),
152 dark: palette([ 166 dark: palette([
@@ -154,6 +168,8 @@ public struct ThemeSpec: Equatable, Sendable {
154 "heading-1": "#79c0ff", "heading-2": "#d2a8ff", "heading-3": "#7ee787", "heading-4": "#ffa657", 168 "heading-1": "#79c0ff", "heading-2": "#d2a8ff", "heading-3": "#7ee787", "heading-4": "#ffa657",
155 "heading-5": "#79c0ff", "heading-6": "#d2a8ff", "heading-7": "#7ee787", "heading-8": "#ffa657", 169 "heading-5": "#79c0ff", "heading-6": "#d2a8ff", "heading-7": "#7ee787", "heading-8": "#ffa657",
156 "todo": "#ff7b72", "done": "#3fb950", "priority": "#ffa657", "tags": "#8b949e", 170 "todo": "#ff7b72", "done": "#3fb950", "priority": "#ffa657", "tags": "#8b949e",
171 "todo-next": "#58a6ff", "todo-waiting": "#d29922", "todo-cancelled": "#8b949e",
172 "priority-a": "#ff7b72", "priority-b": "#ffa657", "priority-c": "#8b949e",
157 "link": "#58a6ff", "timestamp": "#d2a8ff", "code": "#ffa657", "verbatim": "#a5d6ff", "inline-background": "#6e768166", 173 "link": "#58a6ff", "timestamp": "#d2a8ff", "code": "#ffa657", "verbatim": "#a5d6ff", "inline-background": "#6e768166",
158 "markup": "#6e7681", "comment": "#8b949e", "keyword": "#8b949e", "metadata": "#8b949e", "special": "#56d4dd", 174 "markup": "#6e7681", "comment": "#8b949e", "keyword": "#8b949e", "metadata": "#8b949e", "special": "#56d4dd",
159 "block-background": "#161b22", "block-delimiter": "#6e7681", "table": "#e6edf3", 175 "block-background": "#161b22", "block-delimiter": "#6e7681", "table": "#e6edf3",
@@ -163,6 +179,7 @@ public struct ThemeSpec: Equatable, Sendable {
163 "modeline-highlight": "#e6edf3", "state-normal": "#1f6feb", "state-insert": "#238636", "state-visual": "#9e6a03", 179 "modeline-highlight": "#e6edf3", "state-normal": "#1f6feb", "state-insert": "#238636", "state-visual": "#9e6a03",
164 "agenda-date": "#e6edf3", "agenda-today": "#58a6ff", "agenda-time": "#8b949e", "agenda-category": "#8b949e", 180 "agenda-date": "#e6edf3", "agenda-today": "#58a6ff", "agenda-time": "#8b949e", "agenda-category": "#8b949e",
165 "agenda-deadline": "#ff7b72", "agenda-upcoming": "#ffa657", "agenda-scheduled": "#8b949e", "agenda-scheduled-past": "#d29922", 181 "agenda-deadline": "#ff7b72", "agenda-upcoming": "#ffa657", "agenda-scheduled": "#8b949e", "agenda-scheduled-past": "#d29922",
182 "agenda-overdue": "#ff7b72", "agenda-due-soon": "#ffa657", "agenda-event": "#d2a8ff",
166 "habit-clear": "#1f6feb", "habit-ready": "#238636", "habit-alert": "#9e6a03", "habit-overdue": "#da3633", 183 "habit-clear": "#1f6feb", "habit-ready": "#238636", "habit-alert": "#9e6a03", "habit-overdue": "#da3633",
167 ]) 184 ])
168 ) 185 )
@@ -193,6 +210,8 @@ public struct ThemeSpec: Equatable, Sendable {
193 switch table.name { 210 switch table.name {
194 case "theme.todo": 211 case "theme.todo":
195 spec.todo[key] = color 212 spec.todo[key] = color
213 case "theme.category":
214 spec.category[key] = color
196 case "theme", "theme.light", "theme.dark": 215 case "theme", "theme.light", "theme.dark":
197 guard known.contains(key) else { 216 guard known.contains(key) else {
198 problems.append("\(file): unknown theme color \(key)") 217 problems.append("\(file): unknown theme color \(key)")
@@ -219,6 +238,10 @@ public struct ThemeSpec: Equatable, Sendable {
219 # [theme.todo] 238 # [theme.todo]
220 # WAIT = "#bf8700" 239 # WAIT = "#bf8700"
221 # 240 #
241 # Otherwise a keyword takes its class's color: todo, todo-next, todo-waiting, done or
242 # todo-cancelled. [theme.category] colors agenda categories by name the same way;
243 # categories without one get a hue of their own from their name.
244 #
222 # A theme kept in its own file (with the same tables) is used with 245 # A theme kept in its own file (with the same tables) is used with
223 # `theme-file = "name.toml"` under [theme] in config.toml. 246 # `theme-file = "name.toml"` under [theme] in config.toml.
224 247
@@ -238,3 +261,100 @@ public struct ThemeSpec: Equatable, Sendable {
238 return out 261 return out
239 } 262 }
240} 263}
264
265// MARK: - Agenda colors
266
267extension ThemeSpec {
268 /// The color classes of TODO keywords, by name: keywords of work under way and on hold,
269 /// and done keywords that cancel; the others are `todo` or `done`.
270 public enum TodoClass: String, Sendable {
271 case todo, next, waiting, done, cancelled
272
273 /// The theme key.
274 public var key: String {
275 switch self {
276 case .todo: "todo"
277 case .next: "todo-next"
278 case .waiting: "todo-waiting"
279 case .done: "done"
280 case .cancelled: "todo-cancelled"
281 }
282 }
283
284 static let nextWords: Set<String> = ["NEXT", "STRT", "STARTED", "START", "DOING", "ACTIVE", "INPROGRESS", "IN-PROGRESS"]
285 static let waitingWords: Set<String> = ["WAIT", "WAITING", "HOLD", "ONHOLD", "BLOCKED", "DEFERRED", "SOMEDAY", "MAYBE"]
286 static let cancelledWords: Set<String> = ["KILL", "KILLED", "CANCELLED", "CANCELED", "CANCEL", "SKIPPED", "SKIP", "ABORTED", "NO", "WONTFIX"]
287
288 public static func of(_ keyword: String, isDone: Bool) -> TodoClass {
289 let word = keyword.uppercased()
290 if isDone { return cancelledWords.contains(word) ? .cancelled : .done }
291 if nextWords.contains(word) { return .next }
292 if waitingWords.contains(word) { return .waiting }
293 return .todo
294 }
295 }
296
297 /// `[theme.todo]`'s color for the keyword, else its class's.
298 public func todoColor(_ keyword: String, isDone: Bool, dark isDark: Bool) -> RGBA? {
299 todo[keyword] ?? color(TodoClass.of(keyword, isDone: isDone).key, dark: isDark)
300 }
301
302 /// `priority-a`, `-b`, `-c`; `priority` for the others.
303 public func priorityColor(_ priority: String, dark isDark: Bool) -> RGBA? {
304 let key = ["A": "priority-a", "B": "priority-b", "C": "priority-c"][priority] ?? "priority"
305 return color(key, dark: isDark) ?? color("priority", dark: isDark)
306 }
307
308 /// The gutter's color: `agenda-overdue`, `agenda-due-soon`, `done`, else `agenda-time`.
309 public func statusColor(_ status: AgendaRow.Status, dark isDark: Bool) -> RGBA? {
310 switch status {
311 case .overdue: color("agenda-overdue", dark: isDark)
312 case .dueSoon: color("agenda-due-soon", dark: isDark)
313 case .done: color("done", dark: isDark)
314 case .normal: color("agenda-time", dark: isDark)
315 }
316 }
317
318 /// An event's calendar color, else `agenda-event`.
319 public func eventColor(_ event: AgendaEvent, dark isDark: Bool) -> RGBA? {
320 event.color ?? color("agenda-event", dark: isDark)
321 }
322
323 /// `[theme.category]`'s color for the category, else its hue (`categoryHue`) at a
324 /// saturation and lightness that read on the appearance's background.
325 public func categoryColor(_ name: String, dark isDark: Bool) -> RGBA {
326 if let set = category[name] { return set }
327 let hue = Self.categoryHue(name)
328 return isDark ? RGBA(hue: hue, saturation: 0.65, lightness: 0.70) : RGBA(hue: hue, saturation: 0.60, lightness: 0.40)
329 }
330
331 /// A hue in degrees from the category's name (FNV-1a of its UTF-8), the same on every run
332 /// and device.
333 public static func categoryHue(_ name: String) -> Double {
334 var hash: UInt32 = 2166136261
335 for byte in name.utf8 {
336 hash ^= UInt32(byte)
337 hash = hash &* 16777619
338 }
339 return Double(hash % 360)
340 }
341}
342
343extension RGBA {
344 /// From HSL: hue in degrees, saturation and lightness 0 to 1.
345 public init(hue: Double, saturation s: Double, lightness l: Double, alpha: Double = 1) {
346 let c = (1 - abs(2 * l - 1)) * s
347 let h = (hue.truncatingRemainder(dividingBy: 360) + 360).truncatingRemainder(dividingBy: 360) / 60
348 let x = c * (1 - abs(h.truncatingRemainder(dividingBy: 2) - 1))
349 let (r, g, b): (Double, Double, Double) = switch Int(h) {
350 case 0: (c, x, 0)
351 case 1: (x, c, 0)
352 case 2: (0, c, x)
353 case 3: (0, x, c)
354 case 4: (x, 0, c)
355 default: (c, 0, x)
356 }
357 let m = l - c / 2
358 self.init(red: r + m, green: g + m, blue: b + m, alpha: alpha)
359 }
360}
Sources/Orgstar/AgendaView.swift +1
@@ -251,6 +251,7 @@ struct AgendaView: View {
251 agenda.includeSubfolders = includeSubfolders 251 agenda.includeSubfolders = includeSubfolders
252 agenda.options.prefixFormat = ["agenda": prefixAgenda, "todo": prefixTodo, "tags": prefixTags] 252 agenda.options.prefixFormat = ["agenda": prefixAgenda, "todo": prefixTodo, "tags": prefixTags]
253 agenda.options.logMode = logMode 253 agenda.options.logMode = logMode
254 agenda.options = OrgPreferences.agendaOptions(agenda.options)
254 let open = session.openTexts 255 let open = session.openTexts
255 await agenda.refresh(open: open) 256 await agenda.refresh(open: open)
256 } 257 }
Sources/OrgstarMobile/MobileModel.swift +1
@@ -114,6 +114,7 @@ final class MobileModel {
114 agenda.span = OrgPreferences.agendaSpan() 114 agenda.span = OrgPreferences.agendaSpan()
115 agenda.startOffset = OrgPreferences.agendaStartOffset() 115 agenda.startOffset = OrgPreferences.agendaStartOffset()
116 agenda.includeSubfolders = OrgPreferences.agendaSubfolders() 116 agenda.includeSubfolders = OrgPreferences.agendaSubfolders()
117 agenda.options = OrgPreferences.agendaOptions(agenda.options)
117 } 118 }
118 settingsVersion += 1 119 settingsVersion += 1
119 } 120 }
Tests/OrgAppTests/CalendarEventsTests.swift added +72
@@ -0,0 +1,72 @@
1import CoreGraphics
2import Foundation
3import OrgCore
4import OrgPresentation
5import Testing
6@testable import OrgApp
7
8struct AgendaSettingsTests {
9 @Test func agendaSettingsReadFromConfigToml() throws {
10 let defaults = try #require(UserDefaults(suiteName: "orgstar-agenda-settings-\(UUID().uuidString)"))
11 #expect(!OrgPreferences.agendaShowAllDates(defaults))
12 #expect(!OrgPreferences.agendaSkipScheduledIfDone(defaults) && !OrgPreferences.agendaSkipDeadlineIfDone(defaults))
13 #expect(!OrgPreferences.calendarEvents(defaults) && OrgPreferences.calendarEventCalendars(defaults).isEmpty)
14 let problems = UserConfig.apply("""
15 org-agenda-show-all-dates = true
16 org-agenda-skip-scheduled-if-done = true
17 org-agenda-skip-deadline-if-done = true
18 [orgstar]
19 calendar-events = true
20 calendar-event-calendars = "Work, Family , ,ABC-123"
21 """, to: defaults)
22 #expect(problems.isEmpty, "\(problems)")
23 #expect(OrgPreferences.agendaShowAllDates(defaults))
24 #expect(OrgPreferences.calendarEvents(defaults))
25 #expect(OrgPreferences.calendarEventCalendars(defaults) == ["Work", "Family", "ABC-123"])
26 let options = OrgPreferences.agendaOptions(AgendaOptions(), defaults)
27 #expect(options.skipScheduledIfDone && options.skipDeadlineIfDone)
28 #expect(UserConfig.template(from: defaults).contains("org-agenda-show-all-dates = true"))
29 }
30}
31
32struct CalendarEventsTests {
33 struct Record: CalendarEventRecord {
34 var recordID = "e1@0"
35 var recordTitle = "Standup"
36 var recordStart = Date(timeIntervalSince1970: 1_791_190_800)
37 var recordEnd = Date(timeIntervalSince1970: 1_791_192_600)
38 var recordIsAllDay = false
39 var recordLocation: String? = "Room 4"
40 var recordCalendarID = "cal-1"
41 var recordCalendarTitle = "Work"
42 var recordCalendarColor: CGColor? = CGColor(srgbRed: 1, green: 0.5, blue: 0, alpha: 1)
43 }
44
45 @Test func recordsBecomeAgendaEvents() {
46 let event = CalendarEvents.event(Record())
47 #expect(event.id == "e1@0" && event.title == "Standup" && event.calendarTitle == "Work" && event.calendarID == "cal-1")
48 #expect(event.color?.hex == "#ff8000" && event.location == "Room 4" && !event.isAllDay)
49 var noColor = Record()
50 noColor.recordCalendarColor = nil
51 #expect(CalendarEvents.event(noColor).color == nil)
52 }
53
54 @Test func eventsBecomeRows() {
55 var utc = Calendar(identifier: .gregorian)
56 utc.timeZone = TimeZone(identifier: "UTC")!
57 let event = CalendarEvents.event(Record())
58 let day = Days.absolute(event.start, calendar: utc)
59 let row = AgendaRow(event: event, day: day, calendar: utc)
60 #expect(row.gutter == "09:00–09:30" && row.category == "Work" && row.title == "Standup" && row.isEvent && row.icon == .event)
61 var allDay = Record()
62 allDay.recordIsAllDay = true
63 #expect(AgendaRow(event: CalendarEvents.event(allDay), day: day, calendar: utc).gutter == "All day")
64 }
65
66 @Test func calendarsChosenByTitleOrIdentifier() {
67 #expect(CalendarEvents.chooses(id: "x", title: "Work", chosen: []))
68 #expect(CalendarEvents.chooses(id: "x", title: "Work", chosen: ["Work"]))
69 #expect(CalendarEvents.chooses(id: "x", title: "Work", chosen: ["x"]))
70 #expect(!CalendarEvents.chooses(id: "x", title: "Work", chosen: ["Home"]))
71 }
72}
Tests/OrgCoreTests/AgendaItemTextTests.swift added +69
@@ -0,0 +1,69 @@
1import Foundation
2import Testing
3@testable import OrgCore
4
5struct AgendaItemTextTests {
6 static let file = """
7 * TODO [#A] Write the report [1/3] :work:urgent:
8 SCHEDULED: <2026-10-01 Thu>
9 * WAIT Call [[https://example.com][the bank]] about <2026-10-05 Mon> fees [50%]
10 DEADLINE: <2026-10-05 Mon>
11 * Plain heading with no keyword :home:
12 SCHEDULED: <2026-10-05 Mon 08:00-09:30>
13 * DONE [#C] Spaced out title
14 SCHEDULED: <2026-10-05 Mon>
15 * TODO Renew passport
16 DEADLINE: <2026-10-09 Fri>
17 * TODO Weekly review
18 SCHEDULED: <2026-09-28 Mon +1w>
19 """
20
21 static let today = Days.absolute(year: 2026, month: 10, day: 5)
22
23 static func items(on day: Int = today) -> [AgendaItem] {
24 let source = AgendaSource(path: "t.org", text: file, defaults: OrgSettings.default.withTodoKeywords("TODO WAIT | DONE KILL")!)
25 return Agenda.list([source], start: day, days: 1, today: today, now: (9, 0)).flatMap(\.items).filter { $0.path != nil }
26 }
27
28 static func item(_ title: String, on day: Int = today) -> AgendaItem {
29 items(on: day).first { $0.title == title && $0.kind != .timestamp }!
30 }
31
32 @Test func titlesLeaveOutKeywordPriorityCookiesTimestampsAndTags() {
33 let titles = Set(Self.items().map(\.title))
34 #expect(titles == ["Write the report", "Call the bank about fees", "Plain heading with no keyword", "Spaced out title", "Renew passport", "Weekly review"])
35 let report = Self.item("Write the report")
36 #expect(report.extra.hasPrefix("Sched."))
37 #expect(report.priorityLetter == "A" && report.progress == "1/3" && report.tags == ["work", "urgent"] && report.todo == "TODO")
38 let call = Self.item("Call the bank about fees")
39 #expect(call.priorityLetter == nil && call.progress == "50%" && call.todo == "WAIT")
40 let done = Self.item("Spaced out title")
41 #expect(done.isDone && done.priorityLetter == "C")
42 #expect(Self.item("Plain heading with no keyword").todo == nil)
43 }
44
45 @Test func planningDaysAreTheTimestampsDays() {
46 #expect(Self.item("Write the report").planningDay == Self.today - 4)
47 #expect(Self.item("Call the bank about fees").planningDay == Self.today)
48 #expect(Self.item("Renew passport").planningDay == Self.today + 4)
49 // A repeater's occurrence on a later day.
50 #expect(Self.item("Weekly review", on: Self.today + 7).planningDay == Self.today + 7)
51 #expect(Self.items().filter { $0.kind == .timestamp }.allSatisfy { $0.planningDay == nil })
52 }
53
54 @Test func skipIfDoneLeavesDoneEntriesOutOnTheirDay() {
55 let source = AgendaSource(path: "t.org", text: Self.file, defaults: OrgSettings.default.withTodoKeywords("TODO WAIT | DONE KILL")!)
56 var options = AgendaOptions()
57 #expect(Agenda.list([source], start: Self.today, days: 1, today: Self.today, now: (9, 0), options: options)[0].items.contains { $0.isDone })
58 options.skipScheduledIfDone = true
59 #expect(!Agenda.list([source], start: Self.today, days: 1, today: Self.today, now: (9, 0), options: options)[0].items.contains { $0.isDone })
60 }
61
62 @Test(arguments: [
63 (0, "0d"), (3, "3d"), (13, "13d"), (14, "2w"), (59, "8w"), (60, "2mo"), (120, "4mo"), (364, "11mo"),
64 (365, "1y"), (499, "1y 4mo"), (730, "2y"), (729, "1y 11mo"), (-3, "3d"),
65 ])
66 func compactAges(days: Int, text: String) {
67 #expect(AgendaAge.compact(days) == text)
68 }
69}
Tests/OrgCoreTests/AgendaTests.swift +25 −1
@@ -115,18 +115,21 @@ enum AgendaOracle {
115 115
116 static func compare( 116 static func compare(
117 files: [(name: String, text: String)], start: Int, span: Int, today: Int, hour: Int = 9, minute: Int = 30, 117 files: [(name: String, text: String)], start: Int, span: Int, today: Int, hour: Int = 9, minute: Int = 30,
118 prefix: [String: String]? = nil, logMode: Bool = false 118 prefix: [String: String]? = nil, logMode: Bool = false, skipIfDone: Bool = false
119 ) throws { 119 ) throws {
120 let date = Days.date(start) 120 let date = Days.date(start)
121 var form = "(org-agenda-list nil \"\(String(format: "%04d-%02d-%02d", date.year, date.month, date.day))\" \(span))" 121 var form = "(org-agenda-list nil \"\(String(format: "%04d-%02d-%02d", date.year, date.month, date.day))\" \(span))"
122 if let prefix { form = "(let ((org-agenda-prefix-format \(prefixLisp(prefix)))) \(form))" } 122 if let prefix { form = "(let ((org-agenda-prefix-format \(prefixLisp(prefix)))) \(form))" }
123 if logMode { form = "(let ((org-agenda-start-with-log-mode t)) \(form))" } 123 if logMode { form = "(let ((org-agenda-start-with-log-mode t)) \(form))" }
124 if skipIfDone { form = "(let ((org-agenda-skip-scheduled-if-done t) (org-agenda-skip-deadline-if-done t)) \(form))" }
124 let emacs = try run(files: files, form: form, today: today, hour: hour, minute: minute) 125 let emacs = try run(files: files, form: form, today: today, hour: hour, minute: minute)
125 let defaults = OrgSettings.default.withTodoKeywords(keywords)! 126 let defaults = OrgSettings.default.withTodoKeywords(keywords)!
126 let sources = files.map { AgendaSource(path: $0.name, text: $0.text, defaults: defaults) } 127 let sources = files.map { AgendaSource(path: $0.name, text: $0.text, defaults: defaults) }
127 var options = AgendaOptions.terminal 128 var options = AgendaOptions.terminal
128 if let prefix { options.prefixFormat = prefix } 129 if let prefix { options.prefixFormat = prefix }
129 options.logMode = logMode 130 options.logMode = logMode
131 options.skipScheduledIfDone = skipIfDone
132 options.skipDeadlineIfDone = skipIfDone
130 let ours = Agenda.list(sources, start: start, days: span, today: today, now: (hour, minute), options: options) 133 let ours = Agenda.list(sources, start: start, days: span, today: today, now: (hour, minute), options: options)
131 #expect(ours.count == emacs.count) 134 #expect(ours.count == emacs.count)
132 for (o, e) in zip(ours, emacs) { 135 for (o, e) in zip(ours, emacs) {
@@ -325,6 +328,27 @@ struct AgendaTests {
325 try AgendaOracle.compare(files: files, start: day + 1, span: 1, today: day) 328 try AgendaOracle.compare(files: files, start: day + 1, span: 1, today: day)
326 } 329 }
327 330
331 static let doneEntries = """
332 * DONE Scheduled today
333 SCHEDULED: <2026-10-05 Mon>
334 * DONE Due today
335 DEADLINE: <2026-10-05 Mon>
336 * KILL Scheduled earlier
337 SCHEDULED: <2026-10-01 Thu>
338 * DONE Due later
339 DEADLINE: <2026-10-07 Wed>
340 * TODO Still open
341 SCHEDULED: <2026-10-05 Mon> DEADLINE: <2026-10-06 Tue>
342 """
343
344 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
345 func skipsDoneEntriesLikeEmacs() throws {
346 let today = Days.absolute(year: 2026, month: 10, day: 5)
347 for skip in [false, true] {
348 try AgendaOracle.compare(files: [("done.org", Self.doneEntries)], start: today - 4, span: 8, today: today, skipIfDone: skip)
349 }
350 }
351
328 /// `ORGSTAR_ORACLE_CORPUS=<folder>`: the top-level files of the folder, ten days around 352 /// `ORGSTAR_ORACLE_CORPUS=<folder>`: the top-level files of the folder, ten days around
329 /// two dates. 353 /// two dates.
330 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_ORACLE_CORPUS"] != nil)) 354 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_ORACLE_CORPUS"] != nil))
Tests/OrgPresentationTests/AgendaRowsTests.swift added +196
@@ -0,0 +1,196 @@
1import Foundation
2import OrgCore
3import Testing
4@testable import OrgPresentation
5
6struct AgendaRowsTests {
7 static let file = """
8 #+CATEGORY: life
9 * TODO [#B] Pay rent [0/2] :home:
10 SCHEDULED: <2026-10-01 Thu>
11 * TODO Ancient chore
12 SCHEDULED: <2025-05-24 Sat>
13 * TODO Send forms
14 DEADLINE: <2026-10-02 Fri>
15 * TODO File taxes
16 DEADLINE: <2026-10-05 Mon>
17 * TODO Renew passport
18 DEADLINE: <2026-10-09 Fri>
19 * TODO Water plants
20 SCHEDULED: <2026-10-05 Mon>
21 * DONE Took out bins
22 SCHEDULED: <2026-10-05 Mon>
23 * Standup
24 SCHEDULED: <2026-10-05 Mon 08:00>
25 * Dentist <2026-10-05 Mon 13:50-14:30>
26 * Birthday <2026-10-05 Mon>
27 * Conference
28 <2026-10-04 Sun>--<2026-10-06 Tue>
29 * TODO Stretch
30 SCHEDULED: <2026-10-04 Sun .+1d>
31 :PROPERTIES:
32 :STYLE: habit
33 :END:
34 * Far off
35 <2026-10-11 Sun>
36 """
37
38 static let today = Days.absolute(year: 2026, month: 10, day: 5)
39 static let utc: Calendar = {
40 var c = Calendar(identifier: .gregorian)
41 c.timeZone = TimeZone(identifier: "UTC")!
42 return c
43 }()
44
45 static func days(start: Int = today, span: Int = 1) -> [AgendaDay] {
46 let source = AgendaSource(path: "life.org", text: file, defaults: OrgSettings.default.withTodoKeywords("TODO | DONE")!)
47 return Agenda.list([source], start: start, days: span, today: today, now: (10, 0))
48 }
49
50 static func rows(day: Int = today) -> [String: AgendaRow] {
51 var rows: [String: AgendaRow] = [:]
52 for item in days(start: day)[0].items {
53 guard let row = AgendaRow(item: item, day: day, today: today) else { continue }
54 rows[row.title] = rows[row.title] ?? row
55 }
56 return rows
57 }
58
59 static func date(_ day: Int, _ hour: Int, _ minute: Int = 0) -> Date {
60 Date(timeIntervalSince1970: Double((day - 719163) * 86400 + hour * 3600 + minute * 60))
61 }
62
63 @Test func guttersAndStatusesOnToday() {
64 let rows = Self.rows()
65 func check(_ title: String, _ gutter: String, _ status: AgendaRow.Status, _ icon: AgendaRow.Icon?, sourceLocation: SourceLocation = #_sourceLocation) {
66 let row = rows[title]
67 #expect(row?.gutter == gutter, "\(title)", sourceLocation: sourceLocation)
68 #expect(row?.status == status, "\(title)", sourceLocation: sourceLocation)
69 #expect(row?.icon == icon, "\(title)", sourceLocation: sourceLocation)
70 }
71 check("Pay rent", "Sched. 4d ago", .overdue, .scheduled)
72 check("Ancient chore", "Sched. 1y 4mo ago", .overdue, .scheduled)
73 check("Send forms", "3d late", .overdue, .deadline)
74 check("File taxes", "Due today", .dueSoon, .deadline)
75 check("Renew passport", "Due in 4d", .dueSoon, .deadline)
76 check("Water plants", "Scheduled", .normal, .scheduled)
77 check("Took out bins", "Scheduled", .done, .scheduled)
78 check("Standup", "08:00", .normal, .scheduled)
79 check("Dentist", "13:50–14:30", .normal, .timestamp)
80 check("Birthday", "All day", .normal, .timestamp)
81 check("Conference", "Day 2/3", .normal, .timestamp)
82 check("Stretch", "Habit", .overdue, .habit)
83 #expect(rows["Dentist"]?.start == 1350 && rows["Dentist"]?.end == 1430)
84 let rent = rows["Pay rent"]!
85 #expect(rent.category == "life" && rent.tags == ["home"] && rent.todo == "TODO" && rent.priority == "B" && rent.progress == "0/2")
86 #expect(!rent.isEvent && rent.item != nil)
87 }
88
89 @Test func guttersOnOtherDays() {
90 let later = Self.rows(day: Self.today + 4)
91 #expect(later["Renew passport"]?.gutter == "Due" && later["Renew passport"]?.status == .normal)
92 let earlier = Self.rows(day: Self.today - 3)
93 #expect(earlier["Send forms"]?.gutter == "Due" && earlier["Send forms"]?.status == .overdue)
94 }
95
96 @Test func emptyDaysAreHiddenButTodayStays() {
97 let days = Self.days(start: Self.today - 1, span: 8)
98 let shown = AgendaRows.groups(days, today: Self.today).map(\.day)
99 // Sunday has the conference and the habit's first day; Wednesday to Saturday only Friday's deadline.
100 #expect(shown == [Self.today - 1, Self.today, Self.today + 1, Self.today + 4, Self.today + 6])
101 #expect(AgendaRows.groups(days, today: Self.today, showAllDates: true).count == 8)
102 let empty = AgendaRows.groups(days, today: Self.today, keep: { _ in false })
103 #expect(empty.map(\.day) == [Self.today] && empty[0].isEmpty && empty[0].isToday)
104 }
105
106 @Test func overdueEntriesGroupAboveTodayOldestFirst() {
107 let today = AgendaRows.groups(Self.days(), today: Self.today)[0]
108 #expect(today.overdue.map(\.title) == ["Ancient chore", "Pay rent", "Send forms"])
109 #expect(!today.rows.contains { $0.status == .overdue && $0.icon != .habit })
110 #expect(today.rows.contains { $0.title == "Stretch" })
111 #expect(Set(today.rows.map(\.id)).count == today.rows.count)
112 }
113
114 @Test func eventsMergeByTime() {
115 let day = Self.today
116 let events = [
117 AgendaEvent(id: "a", title: "Coffee", calendarID: "c1", calendarTitle: "Work", color: RGBA(hex: "#ff0000"), start: Self.date(day, 9), end: Self.date(day, 9, 30), isAllDay: false),
118 AgendaEvent(id: "b", title: "Holiday", calendarID: "c2", calendarTitle: "Home", color: nil, start: Self.date(day, 0), end: Self.date(day + 1, 0), isAllDay: true),
119 AgendaEvent(id: "c", title: "Flight", calendarID: "c1", calendarTitle: "Work", color: nil, start: Self.date(day - 1, 22), end: Self.date(day + 1, 2), isAllDay: false),
120 AgendaEvent(id: "d", title: "Lunch", calendarID: "c1", calendarTitle: "Work", color: nil, start: Self.date(day, 13, 50), end: Self.date(day, 14, 30), isAllDay: false),
121 ]
122 let groups = AgendaRows.groups(Self.days(start: day - 1, span: 3), events: events, today: day, calendar: Self.utc)
123 let today = groups.first { $0.isToday }!
124 #expect(today.rows.prefix(2).map(\.title) == ["Holiday", "Flight"])
125 #expect(today.rows.map(\.gutter).prefix(6) == ["All day", "All day", "08:00", "09:00–09:30", "13:50–14:30", "13:50–14:30"])
126 #expect(today.rows[4].title == "Dentist" && today.rows[5].title == "Lunch")
127 #expect(today.rows[3].isEvent && today.rows[3].category == "Work" && today.rows[3].color == RGBA(hex: "#ff0000") && today.rows[3].icon == .event)
128 let before = groups.first { $0.day == day - 1 }!
129 #expect(before.rows.first { $0.title == "Flight" }?.gutter == "22:00")
130 let after = groups.first { $0.day == day + 1 }!
131 #expect(after.rows.first { $0.title == "Flight" }?.gutter == "Until 02:00")
132 // The all-day event ends at midnight: one day only.
133 #expect(!after.rows.contains { $0.title == "Holiday" })
134 }
135
136 @Test func nowLineGoesAmongTimedRows() {
137 let today = AgendaRows.groups(Self.days(), today: Self.today)[0]
138 let timed = today.rows.indices.filter { today.rows[$0].start != nil }
139 #expect(today.nowIndex(now: 700) == timed[0])
140 #expect(today.nowIndex(now: 800) == timed[1])
141 #expect(today.nowIndex(now: 1000) == timed[1])
142 #expect(today.nowIndex(now: 1500) == timed.last! + 1)
143 #expect(AgendaRows.nowIndex([], now: 900) == nil)
144 let later = AgendaRows.groups(Self.days(start: Self.today + 4), today: Self.today)[0]
145 #expect(later.nowIndex(now: 900) == nil)
146 }
147}
148
149struct AgendaThemeTests {
150 @Test func newKeysHaveDefaultsInBothAppearances() {
151 for key in ["todo-next", "todo-waiting", "todo-cancelled", "priority-a", "priority-b", "priority-c", "agenda-overdue", "agenda-due-soon", "agenda-event", "agenda-today"] {
152 #expect(ThemeSpec.default.light[key] != nil && ThemeSpec.default.dark[key] != nil, "\(key)")
153 }
154 }
155
156 @Test func keywordClasses() {
157 #expect(ThemeSpec.TodoClass.of("TODO", isDone: false) == .todo)
158 #expect(ThemeSpec.TodoClass.of("STRT", isDone: false) == .next)
159 #expect(ThemeSpec.TodoClass.of("NEXT", isDone: false) == .next)
160 #expect(ThemeSpec.TodoClass.of("WAIT", isDone: false) == .waiting)
161 #expect(ThemeSpec.TodoClass.of("HOLD", isDone: false) == .waiting)
162 #expect(ThemeSpec.TodoClass.of("DONE", isDone: true) == .done)
163 #expect(ThemeSpec.TodoClass.of("KILL", isDone: true) == .cancelled)
164 #expect(ThemeSpec.TodoClass.of("SKIPPED", isDone: true) == .cancelled)
165 // Only done keywords cancel.
166 #expect(ThemeSpec.TodoClass.of("SKIPPED", isDone: false) == .todo)
167 }
168
169 @Test func colorsResolveOverridesFirst() throws {
170 let (spec, problems) = ThemeSpec.reading(try TOML.parse("""
171 [theme.todo]
172 WAIT = "#010203"
173 [theme.category]
174 work = "#0a0b0c"
175 """))
176 #expect(problems.isEmpty)
177 #expect(spec.todoColor("WAIT", isDone: false, dark: true)?.hex == "#010203")
178 #expect(spec.todoColor("HOLD", isDone: false, dark: true) == ThemeSpec.default.dark["todo-waiting"])
179 #expect(spec.todoColor("KILL", isDone: true, dark: false) == ThemeSpec.default.light["todo-cancelled"])
180 #expect(spec.categoryColor("work", dark: false).hex == "#0a0b0c" && spec.categoryColor("work", dark: true).hex == "#0a0b0c")
181 #expect(spec.priorityColor("A", dark: false) == ThemeSpec.default.light["priority-a"])
182 #expect(spec.priorityColor("D", dark: false) == ThemeSpec.default.light["priority"])
183 #expect(spec.statusColor(.overdue, dark: true) == ThemeSpec.default.dark["agenda-overdue"])
184 let event = AgendaEvent(id: "x", title: "", calendarID: "", calendarTitle: "", color: nil, start: Date(), end: Date(), isAllDay: true)
185 #expect(spec.eventColor(event, dark: false) == ThemeSpec.default.light["agenda-event"])
186 }
187
188 @Test func categoryHuesAreStable() {
189 #expect(ThemeSpec.categoryHue("work") == 264)
190 #expect(ThemeSpec.categoryHue("home") == 206)
191 #expect(ThemeSpec.default.categoryColor("home", dark: false) == ThemeSpec.default.categoryColor("home", dark: false))
192 #expect(ThemeSpec.default.categoryColor("home", dark: false) != ThemeSpec.default.categoryColor("home", dark: true))
193 #expect(RGBA(hue: 0, saturation: 1, lightness: 0.5).hex == "#ff0000")
194 #expect(RGBA(hue: 240, saturation: 1, lightness: 0.5).hex == "#0000ff")
195 }
196}
docs/plans/2026-10-08-agenda-redesign.md added +116
@@ -0,0 +1,116 @@
1# Agenda Redesign: Shared Model
2
3The Mac (`Sources/Orgstar/AgendaView.swift`) and iOS (`Sources/OrgstarMobile/AgendaScreen.swift`) agendas are rebuilt on one platform-neutral row model. Item selection stays `Agenda.list`, oracle-tested against Emacs; only the settings below change which items appear.
4
5## Row anatomy
6
7`AgendaRow` (`Sources/OrgPresentation/AgendaRows.swift`):
8
9| Part | Field |
10| --- | --- |
11| Gutter: time or short status | `gutter`, `status`, `icon` |
12| Category line above the title | `category` (entry category, or the event's calendar title) |
13| Title without keyword, `[#A]`, statistics cookies, timestamps, tags; links as descriptions | `title` |
14| Tags | `tags` (inherited first) |
15| TODO keyword | `todo`, `isDone` |
16| Priority letter | `priority` |
17| Statistics cookie | `progress` (`1/3`, `50%`) |
18| Times, `HHMM` | `start`, `end` |
19| Deadline / scheduled day | `planningDay` (`Days` numbering) |
20| Source | `item: AgendaItem?` (for the existing actions), `event: AgendaEvent?`, `isEvent`, `color` (calendar color) |
21
22`AgendaRow.init?(item:day:today:)` returns nil for time-grid and current-time items.
23
24## Gutter rules
25
26Timed rows show `08:00` or `13:50–14:30` (zero-padded, en dash; past midnight wraps). Untimed rows:
27
28| Kind | Gutter | Status |
29| --- | --- | --- |
30| Deadline, on today | `Due today` | due-soon |
31| Deadline, on today, past | `3d late` | overdue |
32| Deadline, on today, upcoming | `Due in 2d` | due-soon |
33| Deadline, on another day | `Due` | overdue if before today, else normal |
34| Scheduled | `Scheduled` | overdue if before today, else normal |
35| Scheduled, carried to today | `Sched. 4d ago` | overdue |
36| Habit | `Habit` | overdue if scheduled before today |
37| Timestamp, diary sexp | `All day` | normal |
38| Range, middle days | `Day 2/5` | normal |
39| Log mode | `Closed`, `Clocked`, `State` (when untimed) | normal |
40| TODO / match list | empty, no icon | normal |
41| Calendar event | `All day`, times, `22:00` on the start day of a multi-day event, `Until 02:00` on its last day | normal |
42
43A done keyword makes the status `done`. Icons: `scheduled`, `deadline`, `habit`, `event`, `timestamp`.
44
45## Ages
46
47`AgendaAge.compact(days)` (`Sources/OrgCore/Agenda/AgendaItemText.swift`): under 14 days `3d`; under 60 whole weeks `2w`; under 365 30-day months `4mo` (at most 11); then 365-day years with remaining months, `1y`, `1y 4mo`. Rounds down; sign ignored.
48
49## Grouping
50
51`AgendaRows.groups(days, events:, today:, showAllDates:, calendar:, keep:) -> [AgendaDayGroup]`, or `AgendaModel.groups(showAllDates:keep:)`.
52
53- Days with no rows are dropped unless `org-agenda-show-all-dates`. Today always stays (`isEmpty` true for the empty state).
54- On today, past-scheduled entries and past deadlines (not habits) go in `overdue`, oldest `planningDay` first, Org's order for ties. Oldest first was chosen over Org's urgency order so the list reads as a backlog.
55- `rows` keep Org's order (`habit-down time-up urgency-down`). All-day events go first, as calendars show them; timed events go among timed entries by start, after entries at the same time and before untimed entries and habits.
56- `keep` is the `AgendaFilter`; events are never filtered.
57- Row ids are unique within a group.
58
59## Now marker
60
61`AgendaDayGroup.nowIndex(now: HHMM) -> Int?`: draw the line before `rows[index]`. It goes before the first timed row starting after now, or after the last timed row when all have started. Nil on other days and when no row is timed (Org adds the line only with timed entries). Rows starting exactly at now count as started.
62
63## Settings (config.toml)
64
65| Key | Default | Read with |
66| --- | --- | --- |
67| `org-agenda-show-all-dates` | `false` (Org's default is `t`) | `OrgPreferences.agendaShowAllDates()` |
68| `org-agenda-skip-scheduled-if-done` | `false` (Org's) | `OrgPreferences.agendaOptions(_:)` |
69| `org-agenda-skip-deadline-if-done` | `false` (Org's) | `OrgPreferences.agendaOptions(_:)` |
70| `[orgstar] calendar-events` | `false` | `OrgPreferences.calendarEvents()` |
71| `[orgstar] calendar-event-calendars` | `""` (all), comma-separated titles or identifiers | `OrgPreferences.calendarEventCalendars()` |
72
73The skip settings are `AgendaOptions.skipScheduledIfDone` / `skipDeadlineIfDone`, oracle-tested. With both nil (the default), done entries show only on their own date, as before. Both screens already apply them through `OrgPreferences.agendaOptions`.
74
75`SKIPPED` in the user's files is not a TODO keyword: `org-todo-keywords` is `TODO PROJ LOOP STRT WAIT HOLD IDEA | DONE KILL` and the files have no `#+TODO`. Org shows such headings as plain past-scheduled entries too. Adding `SKIPPED` after the `|` makes it a done keyword, and the entries leave the agenda.
76
77## Theme keys
78
79New keys in `ThemeSpec.slots`, with light and dark defaults: `todo-next`, `todo-waiting`, `todo-cancelled` (with the existing `todo` and `done`), `priority-a`, `priority-b`, `priority-c` (others fall back to `priority`), `agenda-overdue`, `agenda-due-soon`, `agenda-event`. Today's header stays `agenda-today`. `[theme.category]` sets category colors by name, as `[theme.todo]` sets keyword colors.
80
81Helpers on `ThemeSpec`:
82
83- `TodoClass.of(keyword, isDone:)`: `next` for NEXT, STRT, STARTED, START, DOING, ACTIVE, INPROGRESS; `waiting` for WAIT, WAITING, HOLD, ONHOLD, BLOCKED, DEFERRED, SOMEDAY, MAYBE; `cancelled` for done keywords KILL, KILLED, CANCELLED, CANCELED, CANCEL, SKIPPED, SKIP, ABORTED, NO, WONTFIX; else `todo` / `done`.
84- `todoColor(keyword, isDone:, dark:)`: `[theme.todo]` first, then the class key.
85- `priorityColor(letter, dark:)`, `statusColor(status, dark:)` (`normal` uses `agenda-time`), `eventColor(event, dark:)`.
86- `categoryColor(name, dark:)`: `[theme.category]`, else `categoryHue(name)` (FNV-1a of the UTF-8, mod 360, stable across runs) at HSL saturation 0.60 / lightness 0.40 in light, 0.65 / 0.70 in dark.
87
88## Calendar events
89
90`CalendarEvents` (`Sources/OrgApp/CalendarEvents.swift`) wraps `EKEventStore`:
91
92- `requestAccess() async -> Bool` uses `requestFullAccessToEvents`. EventKit has no read-only level, so reading needs full access. `CalendarEvents.isAuthorized`.
93- `events(from:to:chosen:) -> [AgendaEvent]` and `calendars()` for a picker.
94- `CalendarEventRecord` is what conversion reads; `EKEvent` conforms, and tests use plain values.
95
96`AgendaModel.calendarEvents` (nil reads none) and `calendarNames`: `refresh` fetches events for the agenda span into `AgendaModel.events`. The screens set both from the settings and call `requestAccess()` when `calendar-events` is on.
97
98`NSCalendarsFullAccessUsageDescription` is in `ios/Orgstar/Info.plist`, `scripts/build-ios-app.sh` and `scripts/build-app.sh`. The Mac app is not sandboxed, so it needs no calendar entitlement.
99
100## For the screen rebuilds
101
102```swift
103agenda.calendarEvents = OrgPreferences.calendarEvents() ? CalendarEvents() : nil // keep one instance
104agenda.calendarNames = OrgPreferences.calendarEventCalendars()
105let groups = agenda.groups(showAllDates: OrgPreferences.agendaShowAllDates(), keep: filter.keeps)
106for group in groups {
107 // group.header / group.date(calendar:), group.isToday, group.isEmpty
108 // group.overdue (today), group.rows, group.nowIndex(now:)
109}
110// row.gutter colored by theme.statusColor(row.status, dark:), icon by row.icon,
111// category tint theme.categoryColor(row.category, dark:) or theme.eventColor(row.event!, dark:),
112// keyword theme.todoColor(row.todo!, isDone: row.isDone, dark:), priority theme.priorityColor(_:dark:).
113// Actions take row.item as before.
114```
115
116The TODO and match views (`agenda.list`) can use `AgendaRow(item:day:today:)` per item with `day: agenda.today`.
ios/Orgstar/Info.plist +2
@@ -27,6 +27,8 @@
27 </array> 27 </array>
28 <key>CFBundleVersion</key> 28 <key>CFBundleVersion</key>
29 <string>$(CURRENT_PROJECT_VERSION)</string> 29 <string>$(CURRENT_PROJECT_VERSION)</string>
30 <key>NSCalendarsFullAccessUsageDescription</key>
31 <string>The agenda shows your calendar events alongside your Org entries. Orgstar only reads them.</string>
30 <key>UIApplicationSceneManifest</key> 32 <key>UIApplicationSceneManifest</key>
31 <dict> 33 <dict>
32 <key>UIApplicationSupportsMultipleScenes</key> 34 <key>UIApplicationSupportsMultipleScenes</key>
scripts/build-app.sh +2
@@ -94,6 +94,8 @@ cat > "$app/Contents/Info.plist" <<EOF
94 <string>26.0</string> 94 <string>26.0</string>
95 <key>LSApplicationCategoryType</key> 95 <key>LSApplicationCategoryType</key>
96 <string>public.app-category.productivity</string> 96 <string>public.app-category.productivity</string>
97 <key>NSCalendarsFullAccessUsageDescription</key>
98 <string>The agenda shows your calendar events alongside your Org entries. Orgstar only reads them.</string>
97 <key>NSHighResolutionCapable</key> 99 <key>NSHighResolutionCapable</key>
98 <true/> 100 <true/>
99 <key>NSPrincipalClass</key> 101 <key>NSPrincipalClass</key>
scripts/build-ios-app.sh +2
@@ -47,6 +47,8 @@ cat > "$app/Info.plist" <<PLIST
47 <array><string>iPhoneSimulator</string></array> 47 <array><string>iPhoneSimulator</string></array>
48 <key>MinimumOSVersion</key> 48 <key>MinimumOSVersion</key>
49 <string>26.0</string> 49 <string>26.0</string>
50 <key>NSCalendarsFullAccessUsageDescription</key>
51 <string>The agenda shows your calendar events alongside your Org entries. Orgstar only reads them.</string>
50 <key>UIDeviceFamily</key> 52 <key>UIDeviceFamily</key>
51 <array><integer>1</integer><integer>2</integer></array> 53 <array><integer>1</integer><integer>2</integer></array>
52 <key>UILaunchScreen</key> 54 <key>UILaunchScreen</key>