Tests/OrgPresentationTests/AgendaRowsTests.swift
272 lines · 14418 bytes
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 * TODO Walk dog
35 SCHEDULED: <2026-10-03 Sat 18:00 .+1d>
36 :PROPERTIES:
37 :STYLE: habit
38 :END:
39 * Far off
40 <2026-10-11 Sun>
41 """
42
43 static let today = Days.absolute(year: 2026, month: 10, day: 5)
44 static let utc: Calendar = {
45 var c = Calendar(identifier: .gregorian)
46 c.timeZone = TimeZone(identifier: "UTC")!
47 return c
48 }()
49
50 static func days(start: Int = today, span: Int = 1) -> [AgendaDay] {
51 let source = AgendaSource(path: "life.org", text: file, defaults: OrgSettings.default.withTodoKeywords("TODO | DONE")!)
52 return Agenda.list([source], start: start, days: span, today: today, now: (10, 0))
53 }
54
55 static func rows(day: Int = today) -> [String: AgendaRow] {
56 var rows: [String: AgendaRow] = [:]
57 for item in days(start: day)[0].items {
58 guard let row = AgendaRow(item: item, day: day, today: today) else { continue }
59 rows[row.title] = rows[row.title] ?? row
60 }
61 return rows
62 }
63
64 static func date(_ day: Int, _ hour: Int, _ minute: Int = 0) -> Date {
65 Date(timeIntervalSince1970: Double((day - 719163) * 86400 + hour * 3600 + minute * 60))
66 }
67
68 @Test func guttersAndStatusesOnToday() {
69 let rows = Self.rows()
70 func check(_ title: String, _ gutter: String, _ status: AgendaRow.Status, _ icon: AgendaRow.Icon?, sourceLocation: SourceLocation = #_sourceLocation) {
71 let row = rows[title]
72 #expect(row?.gutter == gutter, "\(title)", sourceLocation: sourceLocation)
73 #expect(row?.status == status, "\(title)", sourceLocation: sourceLocation)
74 #expect(row?.icon == icon, "\(title)", sourceLocation: sourceLocation)
75 }
76 check("Pay rent", "4d ago", .overdue, .scheduled)
77 check("Ancient chore", "1y 4mo ago", .overdue, .scheduled)
78 check("Send forms", "3d late", .overdue, .deadline)
79 check("File taxes", "Due today", .dueSoon, .deadline)
80 check("Renew passport", "Due in 4d", .dueSoon, .deadline)
81 check("Water plants", "Scheduled", .normal, .scheduled)
82 check("Took out bins", "Scheduled", .done, .scheduled)
83 check("Standup", "08:00", .normal, .scheduled)
84 check("Dentist", "13:50–14:30", .normal, .timestamp)
85 check("Birthday", "All day", .normal, .timestamp)
86 check("Conference", "Day 2/3", .normal, .timestamp)
87 check("Stretch", "1d ago", .overdue, .habit)
88 // An earlier day's time says nothing about today.
89 check("Walk dog", "2d ago", .overdue, .habit)
90 #expect(rows["Walk dog"]?.start == nil)
91 #expect(rows["Dentist"]?.start == 1350 && rows["Dentist"]?.end == 1430)
92 let rent = rows["Pay rent"]!
93 #expect(rent.category == "life" && rent.tags == ["home"] && rent.todo == "TODO" && rent.priority == "B" && rent.progress == "0/2")
94 #expect(!rent.isEvent && rent.item != nil)
95 }
96
97 @Test func logRowsKeepTheDurationAndState() {
98 let text = """
99 * DONE Write report
100 CLOSED: [2026-10-05 Mon 11:00]
101 :LOGBOOK:
102 - State "DONE" from "TODO" [2026-10-05 Mon 11:00]
103 CLOCK: [2026-10-05 Mon 09:00]--[2026-10-05 Mon 10:30] => 1:30
104 :END:
105 """
106 var options = AgendaOptions()
107 options.logMode = true
108 options.logItems = ["closed", "clock", "state"]
109 let source = AgendaSource(path: "w.org", text: text, defaults: OrgSettings.default.withTodoKeywords("TODO | DONE")!)
110 let items = Agenda.list([source], start: Self.today, days: 1, today: Self.today, now: (12, 0), options: options)[0].items
111 let rows = items.compactMap { AgendaRow(item: $0, day: Self.today, today: Self.today) }
112 #expect(rows.first { $0.item?.kind == .clock }?.detail == "1:30")
113 #expect(rows.first { $0.item?.kind == .state }?.detail == "DONE")
114 #expect(rows.first { $0.item?.kind == .closed }?.detail == nil)
115 }
116
117 @Test func guttersOnOtherDays() {
118 let later = Self.rows(day: Self.today + 4)
119 #expect(later["Renew passport"]?.gutter == "Due" && later["Renew passport"]?.status == .normal)
120 let earlier = Self.rows(day: Self.today - 3)
121 #expect(earlier["Send forms"]?.gutter == "Due" && earlier["Send forms"]?.status == .overdue)
122 }
123
124 @Test func emptyDaysAreHiddenButTodayStays() {
125 let days = Self.days(start: Self.today - 1, span: 8)
126 let shown = AgendaRows.groups(days, today: Self.today).map(\.day)
127 // Sunday has the conference and the habit's first day; Wednesday to Saturday only Friday's deadline.
128 #expect(shown == [Self.today - 1, Self.today, Self.today + 1, Self.today + 4, Self.today + 6])
129 #expect(AgendaRows.groups(days, today: Self.today, showAllDates: true).count == 8)
130 let empty = AgendaRows.groups(days, today: Self.today, keep: { _ in false })
131 #expect(empty.map(\.day) == [Self.today] && empty[0].isEmpty && empty[0].isToday)
132 }
133
134 @Test func overdueEntriesGroupAboveTodayOldestFirst() {
135 let today = AgendaRows.groups(Self.days(), today: Self.today)[0]
136 #expect(today.overdue.map(\.title) == ["Ancient chore", "Pay rent", "Send forms", "Walk dog", "Stretch"])
137 #expect(!today.rows.contains { $0.status == .overdue })
138 #expect(Set(today.rows.map(\.id)).count == today.rows.count)
139 }
140
141 @Test func eventsMergeByTime() {
142 let day = Self.today
143 let events = [
144 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),
145 AgendaEvent(id: "b", title: "Holiday", calendarID: "c2", calendarTitle: "Home", color: nil, start: Self.date(day, 0), end: Self.date(day + 1, 0), isAllDay: true),
146 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),
147 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),
148 ]
149 let groups = AgendaRows.groups(Self.days(start: day - 1, span: 3), events: events, today: day, calendar: Self.utc)
150 let today = groups.first { $0.isToday }!
151 #expect(today.rows.prefix(2).map(\.title) == ["Holiday", "Flight"])
152 #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"])
153 #expect(today.rows[4].title == "Dentist" && today.rows[5].title == "Lunch")
154 #expect(today.rows[3].isEvent && today.rows[3].category == "Work" && today.rows[3].color == RGBA(hex: "#ff0000") && today.rows[3].icon == .event)
155 let before = groups.first { $0.day == day - 1 }!
156 #expect(before.rows.first { $0.title == "Flight" }?.gutter == "22:00")
157 let after = groups.first { $0.day == day + 1 }!
158 #expect(after.rows.first { $0.title == "Flight" }?.gutter == "Until 02:00")
159 // The all-day event ends at midnight: one day only.
160 #expect(!after.rows.contains { $0.title == "Holiday" })
161 }
162
163 @Test func nowLineGoesAmongTimedRows() {
164 let today = AgendaRows.groups(Self.days(), today: Self.today)[0]
165 let timed = today.rows.indices.filter { today.rows[$0].start != nil }
166 #expect(today.nowIndex(now: 700) == timed[0])
167 #expect(today.nowIndex(now: 800) == timed[1])
168 #expect(today.nowIndex(now: 1000) == timed[1])
169 #expect(today.nowIndex(now: 1500) == timed.last! + 1)
170 #expect(AgendaRows.nowIndex([], now: 900) == nil)
171 let later = AgendaRows.groups(Self.days(start: Self.today + 4), today: Self.today)[0]
172 #expect(later.nowIndex(now: 900) == nil)
173 }
174
175 @Test func timedHabitsGoAmongTimedRows() {
176 let file = """
177 * TODO Lunch
178 SCHEDULED: <2026-10-05 Mon 12:00>
179 * TODO Medication
180 SCHEDULED: <2026-10-05 Mon 20:00>
181 * TODO Bathe
182 SCHEDULED: <2026-10-05 Mon 18:30 .+1d>
183 :PROPERTIES:
184 :STYLE: habit
185 :END:
186 """
187 let source = AgendaSource(path: "life.org", text: file, defaults: OrgSettings.default.withTodoKeywords("TODO | DONE")!)
188 let days = Agenda.list([source], start: Self.today, days: 1, today: Self.today, now: (10, 0))
189 let day = Self.today
190 let events = [
191 AgendaEvent(id: "a", title: "Call", calendarID: "c1", calendarTitle: "Work", color: nil, start: Self.date(day, 19), end: Self.date(day, 19, 30), isAllDay: false),
192 ]
193 let today = AgendaRows.groups(days, events: events, today: day, calendar: Self.utc)[0]
194 #expect(today.rows.map(\.title) == ["Lunch", "Bathe", "Call", "Medication"])
195 #expect(today.nowIndex(now: 1800) == 1)
196 #expect(today.nowIndex(now: 1904) == 3)
197 #expect(today.grid.first { $0.time == 1800 }?.before == 1)
198 }
199
200 @Test func gridLinesGoBeforeLaterRows() {
201 let today = AgendaRows.groups(Self.days(), today: Self.today)[0]
202 #expect(today.grid.map(\.time) == [800, 1000, 1200, 1400, 1600, 1800, 2000])
203 let lines = today.lines(now: 1100)
204 // Each grid line comes before the first timed row after its time, entries at the same
205 // time first, as `time-up urgency-down` orders them; the rest after the last timed row.
206 var last = -1
207 for line in lines {
208 switch line {
209 case .row(let index):
210 if let start = today.rows[index].start { #expect(start >= last) ; last = start }
211 case .grid(let time): #expect(time >= last); last = time
212 case .now: #expect(1100 >= last); last = 1100
213 }
214 }
215 #expect(lines.filter { if case .row = $0 { return true } else { return false } }.count == today.rows.count)
216 #expect(lines.contains(.now))
217 var options = AgendaOptions()
218 options.useTimeGrid = false
219 let source = AgendaSource(path: "life.org", text: Self.file, defaults: OrgSettings.default.withTodoKeywords("TODO | DONE")!)
220 let plain = AgendaRows.groups(Agenda.list([source], start: Self.today, days: 1, today: Self.today, now: (10, 0), options: options), today: Self.today)[0]
221 #expect(plain.grid.isEmpty && plain.nowIndex(now: 1100) == nil)
222 }
223}
224
225struct AgendaThemeTests {
226 @Test func newKeysHaveDefaultsInBothAppearances() {
227 for key in ["todo-next", "todo-waiting", "todo-cancelled", "priority-a", "priority-b", "priority-c", "agenda-overdue", "agenda-due-soon", "agenda-event", "agenda-today"] {
228 #expect(ThemeSpec.default.light[key] != nil && ThemeSpec.default.dark[key] != nil, "\(key)")
229 }
230 }
231
232 @Test func keywordClasses() {
233 #expect(ThemeSpec.TodoClass.of("TODO", isDone: false) == .todo)
234 #expect(ThemeSpec.TodoClass.of("STRT", isDone: false) == .next)
235 #expect(ThemeSpec.TodoClass.of("NEXT", isDone: false) == .next)
236 #expect(ThemeSpec.TodoClass.of("WAIT", isDone: false) == .waiting)
237 #expect(ThemeSpec.TodoClass.of("HOLD", isDone: false) == .waiting)
238 #expect(ThemeSpec.TodoClass.of("DONE", isDone: true) == .done)
239 #expect(ThemeSpec.TodoClass.of("KILL", isDone: true) == .cancelled)
240 #expect(ThemeSpec.TodoClass.of("SKIPPED", isDone: true) == .cancelled)
241 // Only done keywords cancel.
242 #expect(ThemeSpec.TodoClass.of("SKIPPED", isDone: false) == .todo)
243 }
244
245 @Test func colorsResolveOverridesFirst() throws {
246 let (spec, problems) = ThemeSpec.reading(try TOML.parse("""
247 [theme.todo]
248 WAIT = "#010203"
249 [theme.category]
250 work = "#0a0b0c"
251 """))
252 #expect(problems.isEmpty)
253 #expect(spec.todoColor("WAIT", isDone: false, dark: true)?.hex == "#010203")
254 #expect(spec.todoColor("HOLD", isDone: false, dark: true) == ThemeSpec.default.dark["todo-waiting"])
255 #expect(spec.todoColor("KILL", isDone: true, dark: false) == ThemeSpec.default.light["todo-cancelled"])
256 #expect(spec.categoryColor("work", dark: false).hex == "#0a0b0c" && spec.categoryColor("work", dark: true).hex == "#0a0b0c")
257 #expect(spec.priorityColor("A", dark: false) == ThemeSpec.default.light["priority-a"])
258 #expect(spec.priorityColor("D", dark: false) == ThemeSpec.default.light["priority"])
259 #expect(spec.statusColor(.overdue, dark: true) == ThemeSpec.default.dark["agenda-overdue"])
260 let event = AgendaEvent(id: "x", title: "", calendarID: "", calendarTitle: "", color: nil, start: Date(), end: Date(), isAllDay: true)
261 #expect(spec.eventColor(event, dark: false) == ThemeSpec.default.light["agenda-event"])
262 }
263
264 @Test func categoryHuesAreStable() {
265 #expect(ThemeSpec.categoryHue("work") == 264)
266 #expect(ThemeSpec.categoryHue("home") == 206)
267 #expect(ThemeSpec.default.categoryColor("home", dark: false) == ThemeSpec.default.categoryColor("home", dark: false))
268 #expect(ThemeSpec.default.categoryColor("home", dark: false) != ThemeSpec.default.categoryColor("home", dark: true))
269 #expect(RGBA(hue: 0, saturation: 1, lightness: 0.5).hex == "#ff0000")
270 #expect(RGBA(hue: 240, saturation: 1, lightness: 0.5).hex == "#0000ff")
271 }
272}