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
22import Observation
33import OrgCore
44import OrgIndex
5import OrgPresentation
56
67/// The day/week agenda over the workspace's agenda files. Sources are read from disk and
78/// 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 {
2223 public var includeSubfolders = false
2324 public var options = AgendaOptions()
2425 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
2534
2635 private let workspace: WorkspaceModel
2736 @ObservationIgnored private var cache: [String: (mtime: Date, size: Int, source: AgendaSource)] = [:]
@@ -57,23 +66,33 @@ public final class AgendaModel {
5766 let first = start ?? today + startOffset
5867 let options = self.options
5968 let mode = self.mode
69 let provider = calendarEvents
70 let names = calendarNames
6071 let all = await sources(open: open)
6172 let result = await Task.detached {
6273 var days: [AgendaDay] = []
6374 var list: [AgendaItem] = []
75 var events: [AgendaEvent] = []
6476 switch mode {
6577 case .agenda:
6678 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 }
6783 case .todo(let keywords):
6884 list = Agenda.todoList(all, keywords: keywords, options: options)
6985 case .match(let match, let todoOnly):
7086 list = Agenda.tagsMatch(all, match: match, todoOnly: todoOnly, now: now, calendar: calendar, options: options)
7187 }
72 return (days, list)
88 return (days, list, events)
7389 }.value
7490 guard id == generation else { return }
7591 days = result.0
7692 list = result.1
93 events = result.2
94 self.today = today
95 self.calendar = calendar
7796 isComputing = false
7897 }
7998
@@ -126,6 +145,17 @@ public final class AgendaModel {
126145 return loaded.map(\.source)
127146 }
128147
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
129159 public func showToday() { start = nil }
130160
131161 /// 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 {
5050 public static func agendaSpan(_ defaults: UserDefaults = .standard) -> Int { integer("agendaSpan", defaults) }
5151 public static func agendaStartOffset(_ defaults: UserDefaults = .standard) -> Int { integer("agendaStartOffset", defaults) }
5252 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 }
5370 public static func reminders(_ defaults: UserDefaults = .standard) -> Bool { bool("reminders", defaults) }
5471 /// `appt-message-warning-time`, in minutes.
5572 public static func reminderLead(_ defaults: UserDefaults = .standard) -> Int { integer("reminderLead", defaults) }
Sources/OrgApp/UserConfig.swift +10
@@ -141,6 +141,12 @@ public enum UserConfig {
141141 comment: "days the agenda shows", legacy: "agenda.span"),
142142 Setting(section: "", key: "org-agenda-start-day", defaultsKey: "agendaStartOffset", kind: .dayOffset, fallback: .string("-3d"),
143143 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: ""),
144150 Setting(section: "", key: "appt-message-warning-time", defaultsKey: "reminderLead", kind: .integer, fallback: .integer(12),
145151 comment: "minutes of warning before timed entries; APPT_WARNTIME overrides", legacy: "agenda.reminder-lead"),
146152 Setting(section: "", key: "org-clock-idle-time", defaultsKey: "clockIdleTime", kind: .integer, fallback: .integer(0),
@@ -183,6 +189,10 @@ public enum UserConfig {
183189 comment: "the agenda reads org files in subfolders too", legacy: "agenda.include-subfolders"),
184190 Setting(section: "orgstar", key: "reminders", defaultsKey: "reminders", kind: .bool, fallback: .bool(true),
185191 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: ""),
186196 Setting(section: "orgstar", key: "global-capture-hotkey", defaultsKey: "globalCapture", kind: .bool, fallback: .bool(true),
187197 comment: "⌃⌥Space opens Capture from any app; templates go in capture.toml", legacy: "capture.global-hotkey"),
188198 ]
Sources/OrgCore/Agenda/Agenda.swift +18 −6
@@ -48,6 +48,9 @@ public struct AgendaItem: Sendable, Equatable {
4848 public var prefix = ""
4949 /// The entry's `Effort` property.
5050 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?
5154}
5255
5356public struct AgendaDay: Sendable, Equatable {
@@ -71,6 +74,11 @@ public struct AgendaOptions: Sendable, Equatable {
7174 public var logMode = false
7275 /// `org-agenda-log-mode-items`.
7376 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
7482
7583 public init() {}
7684
@@ -139,7 +147,7 @@ public enum Agenda {
139147 continue
140148 }
141149 }
142 if heading.isDone, deadline != current { continue }
150 if heading.isDone, options.skipDeadlineIfDone || deadline != current { continue }
143151 let time: Dotime? = current != deadline && current != repeat_ ? nil : (timeIn(s).map { .string($0) } ?? .headline)
144152 let extra: String
145153 if isToday, deadline < today {
@@ -150,10 +158,12 @@ public enum Agenda {
150158 extra = "Deadline: "
151159 }
152160 let upcoming = isToday && deadline > today
153 items.append(format(
161 var item = format(
154162 source, heading, kind: upcoming ? .upcomingDeadline : .deadline, marker: offset, extra: extra,
155163 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)
157167 }
158168 return items
159169 }
@@ -171,17 +181,19 @@ public enum Agenda {
171181 || (current != schedule && current != today && current != repeat_) {
172182 continue
173183 }
174 if heading.isDone, schedule != current { continue }
184 if heading.isDone, options.skipScheduledIfDone || schedule != current { continue }
175185 // org-habit: habits only on today's agenda, and not when done.
176186 if heading.isHabit, heading.isDone || !isToday { continue }
177187 let time: Dotime? = !heading.isHabit && current != schedule && current != repeat_ ? nil : (timeIn(s).map { .string($0) } ?? .headline)
178188 let extra = heading.isHabit ? "" : isToday && past ? String(format: "Sched.%2dx: ", diff) : "Scheduled: "
179189 let habit = heading.isHabit ? heading.habit : nil
180 items.append(format(
190 var item = format(
181191 source, heading, kind: past ? .pastScheduled : .scheduled, marker: offset, extra: extra,
182192 dotime: time, removing: nil, trailing: options.gridTrailing, prefix: options.prefix("agenda"), habit: habit,
183193 urgency: { habit?.urgency(today: today) ?? 99 + diff + $0 }
184 ))
194 )
195 item.planningDay = current != schedule && current == repeat_ ? repeat_ : schedule
196 items.append(item)
185197 }
186198 return items
187199 }
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 {
3333}
3434
3535/// 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
37/// `[theme.todo]` in config.toml, on top of the default theme.
36/// TODO keywords and categories, and type. Read from `[theme]`, `[theme.light]`, `[theme.dark]`,
37/// `[theme.todo]` and `[theme.category]` in config.toml, on top of the default theme.
3838public struct ThemeSpec: Equatable, Sendable {
3939 /// A font family; empty for the system's monospaced font.
4040 public var font = ""
@@ -47,6 +47,8 @@ public struct ThemeSpec: Equatable, Sendable {
4747 public var dark: [String: RGBA]
4848 /// `org-todo-keyword-faces`: a color per keyword, the same in both appearances.
4949 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] = [:]
5052
5153 public init(light: [String: RGBA], dark: [String: RGBA]) {
5254 self.light = light
@@ -69,8 +71,14 @@ public struct ThemeSpec: Equatable, Sendable {
6971 ("heading-4", "level 4 headings"), ("heading-5", "level 5 headings"), ("heading-6", "level 6 headings"),
7072 ("heading-7", "level 7 headings"), ("heading-8", "level 8 and deeper headings"),
7173 ("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"),
7276 ("done", "DONE keywords"),
77 ("todo-cancelled", "done keywords that cancel: KILL, CANCELLED, CANCELED, CANCEL, SKIPPED, SKIP, ABORTED, NO, WONTFIX"),
7378 ("priority", "[#A] cookies"),
79 ("priority-a", "agenda: priority A"),
80 ("priority-b", "agenda: priority B"),
81 ("priority-c", "agenda: priority C"),
7482 ("tags", ":tags:"),
7583 ("link", "links"),
7684 ("timestamp", "timestamps"),
@@ -113,6 +121,9 @@ public struct ThemeSpec: Equatable, Sendable {
113121 ("agenda-upcoming", "deadlines coming up"),
114122 ("agenda-scheduled", "scheduled items"),
115123 ("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"),
116127 ("habit-clear", "habit graph: not due yet"),
117128 ("habit-ready", "habit graph: due"),
118129 ("habit-alert", "habit graph: due today, last chance"),
@@ -138,6 +149,8 @@ public struct ThemeSpec: Equatable, Sendable {
138149 "heading-1": "#0550ae", "heading-2": "#8250df", "heading-3": "#116329", "heading-4": "#953800",
139150 "heading-5": "#0550ae", "heading-6": "#8250df", "heading-7": "#116329", "heading-8": "#953800",
140151 "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",
141154 "link": "#0969da", "timestamp": "#8250df", "code": "#953800", "verbatim": "#0a3069", "inline-background": "#afb8c133",
142155 "markup": "#8c959f", "comment": "#6e7781", "keyword": "#6e7781", "metadata": "#6e7781", "special": "#1b7c83",
143156 "block-background": "#f6f8fa", "block-delimiter": "#8c959f", "table": "#1f2328",
@@ -147,6 +160,7 @@ public struct ThemeSpec: Equatable, Sendable {
147160 "modeline-highlight": "#1f2328", "state-normal": "#0969da", "state-insert": "#1a7f37", "state-visual": "#bc4c00",
148161 "agenda-date": "#1f2328", "agenda-today": "#0969da", "agenda-time": "#6e7781", "agenda-category": "#6e7781",
149162 "agenda-deadline": "#cf222e", "agenda-upcoming": "#bc4c00", "agenda-scheduled": "#6e7781", "agenda-scheduled-past": "#953800",
163 "agenda-overdue": "#cf222e", "agenda-due-soon": "#bc4c00", "agenda-event": "#8250df",
150164 "habit-clear": "#54aeff", "habit-ready": "#4ac26b", "habit-alert": "#d4a72c", "habit-overdue": "#ff8182",
151165 ]),
152166 dark: palette([
@@ -154,6 +168,8 @@ public struct ThemeSpec: Equatable, Sendable {
154168 "heading-1": "#79c0ff", "heading-2": "#d2a8ff", "heading-3": "#7ee787", "heading-4": "#ffa657",
155169 "heading-5": "#79c0ff", "heading-6": "#d2a8ff", "heading-7": "#7ee787", "heading-8": "#ffa657",
156170 "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",
157173 "link": "#58a6ff", "timestamp": "#d2a8ff", "code": "#ffa657", "verbatim": "#a5d6ff", "inline-background": "#6e768166",
158174 "markup": "#6e7681", "comment": "#8b949e", "keyword": "#8b949e", "metadata": "#8b949e", "special": "#56d4dd",
159175 "block-background": "#161b22", "block-delimiter": "#6e7681", "table": "#e6edf3",
@@ -163,6 +179,7 @@ public struct ThemeSpec: Equatable, Sendable {
163179 "modeline-highlight": "#e6edf3", "state-normal": "#1f6feb", "state-insert": "#238636", "state-visual": "#9e6a03",
164180 "agenda-date": "#e6edf3", "agenda-today": "#58a6ff", "agenda-time": "#8b949e", "agenda-category": "#8b949e",
165181 "agenda-deadline": "#ff7b72", "agenda-upcoming": "#ffa657", "agenda-scheduled": "#8b949e", "agenda-scheduled-past": "#d29922",
182 "agenda-overdue": "#ff7b72", "agenda-due-soon": "#ffa657", "agenda-event": "#d2a8ff",
166183 "habit-clear": "#1f6feb", "habit-ready": "#238636", "habit-alert": "#9e6a03", "habit-overdue": "#da3633",
167184 ])
168185 )
@@ -193,6 +210,8 @@ public struct ThemeSpec: Equatable, Sendable {
193210 switch table.name {
194211 case "theme.todo":
195212 spec.todo[key] = color
213 case "theme.category":
214 spec.category[key] = color
196215 case "theme", "theme.light", "theme.dark":
197216 guard known.contains(key) else {
198217 problems.append("\(file): unknown theme color \(key)")
@@ -219,6 +238,10 @@ public struct ThemeSpec: Equatable, Sendable {
219238 # [theme.todo]
220239 # WAIT = "#bf8700"
221240 #
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 #
222245 # A theme kept in its own file (with the same tables) is used with
223246 # `theme-file = "name.toml"` under [theme] in config.toml.
224247
@@ -238,3 +261,100 @@ public struct ThemeSpec: Equatable, Sendable {
238261 return out
239262 }
240263}
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 {
251251 agenda.includeSubfolders = includeSubfolders
252252 agenda.options.prefixFormat = ["agenda": prefixAgenda, "todo": prefixTodo, "tags": prefixTags]
253253 agenda.options.logMode = logMode
254 agenda.options = OrgPreferences.agendaOptions(agenda.options)
254255 let open = session.openTexts
255256 await agenda.refresh(open: open)
256257 }
Sources/OrgstarMobile/MobileModel.swift +1
@@ -114,6 +114,7 @@ final class MobileModel {
114114 agenda.span = OrgPreferences.agendaSpan()
115115 agenda.startOffset = OrgPreferences.agendaStartOffset()
116116 agenda.includeSubfolders = OrgPreferences.agendaSubfolders()
117 agenda.options = OrgPreferences.agendaOptions(agenda.options)
117118 }
118119 settingsVersion += 1
119120 }
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 {
115115
116116 static func compare(
117117 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
119119 ) throws {
120120 let date = Days.date(start)
121121 var form = "(org-agenda-list nil \"\(String(format: "%04d-%02d-%02d", date.year, date.month, date.day))\" \(span))"
122122 if let prefix { form = "(let ((org-agenda-prefix-format \(prefixLisp(prefix)))) \(form))" }
123123 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))" }
124125 let emacs = try run(files: files, form: form, today: today, hour: hour, minute: minute)
125126 let defaults = OrgSettings.default.withTodoKeywords(keywords)!
126127 let sources = files.map { AgendaSource(path: $0.name, text: $0.text, defaults: defaults) }
127128 var options = AgendaOptions.terminal
128129 if let prefix { options.prefixFormat = prefix }
129130 options.logMode = logMode
131 options.skipScheduledIfDone = skipIfDone
132 options.skipDeadlineIfDone = skipIfDone
130133 let ours = Agenda.list(sources, start: start, days: span, today: today, now: (hour, minute), options: options)
131134 #expect(ours.count == emacs.count)
132135 for (o, e) in zip(ours, emacs) {
@@ -325,6 +328,27 @@ struct AgendaTests {
325328 try AgendaOracle.compare(files: files, start: day + 1, span: 1, today: day)
326329 }
327330
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
328352 /// `ORGSTAR_ORACLE_CORPUS=<folder>`: the top-level files of the folder, ten days around
329353 /// two dates.
330354 @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 @@
2727 </array>
2828 <key>CFBundleVersion</key>
2929 <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>
3032 <key>UIApplicationSceneManifest</key>
3133 <dict>
3234 <key>UIApplicationSupportsMultipleScenes</key>
scripts/build-app.sh +2
@@ -94,6 +94,8 @@ cat > "$app/Contents/Info.plist" <<EOF
9494 <string>26.0</string>
9595 <key>LSApplicationCategoryType</key>
9696 <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>
9799 <key>NSHighResolutionCapable</key>
98100 <true/>
99101 <key>NSPrincipalClass</key>
scripts/build-ios-app.sh +2
@@ -47,6 +47,8 @@ cat > "$app/Info.plist" <<PLIST
4747 <array><string>iPhoneSimulator</string></array>
4848 <key>MinimumOSVersion</key>
4949 <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>
5052 <key>UIDeviceFamily</key>
5153 <array><integer>1</integer><integer>2</integer></array>
5254 <key>UILaunchScreen</key>