Sources/Orgstar/AgendaView.swift
610 lines · 27193 bytes
1import AppKit
2import OrgApp
3import OrgDocument
4import OrgCore
5import OrgPresentation
6import SwiftUI
7
8/// The days an agenda shows, as Org's `v d`, `v w` and `v m`.
9enum AgendaSpan: String, CaseIterable {
10 case day, week, month
11}
12
13/// The app's one reader of Calendar events and of Reminders, for the agenda and Settings.
14@MainActor
15enum CalendarAccess {
16 static let events = CalendarEvents()
17 static let reminders = ReminderLists()
18}
19
20/// The agenda window: the day/week agenda, the TODO list, tag matches, text search and saved views.
21/// Return or a double click jumps to the entry in the main window. Keys as in Emacs's agenda:
22/// n/p (or the arrows) move between lines, f/b/. move the span, j picks a date, v d/v w/v m (or
23/// d/w) show a day, week or month, g refreshes, l shows the log (closed and clocked), / filters
24/// (`+cat-tag<0:10-/regexp/`), \ by tag, < by the line's category, = by regexp, _ by effort,
25/// | clears filters, I/O/X clock in, out and cancel, C-c C-w refiles, $ archives, m/u/U mark
26/// and unmark, B acts on the marked entries, t cycles the TODO state, +/- change the priority and
27/// , sets it, : or C-c C-q sets tags, C-c C-s / C-c C-d schedule and set a deadline, S-→/S-← move
28/// the date, k captures on the line's day, s saves all files, TAB and SPC show the entry.
29struct AgendaView: View {
30 let workspace: WorkspaceModel
31 let session: DocumentSession
32 let commands: AppCommands
33 let scheduler: ReminderScheduler?
34 let clock: ClockModel
35 @State var agenda: AgendaModel
36 @State var views = AgendaViewLoader.builtIn
37 @State var viewName = AgendaViewLoader.builtIn[0].name
38 @State var matchText = ""
39 /// The selected line: `day:index` (`day:o` + index in the overdue group), or `list:index`.
40 @State var selection: String?
41 @State var tick = 0
42 /// The time the now line shows, kept to the minute while the agenda is open.
43 @State var now = Date()
44 /// The view picker moved to the agenda for a followed timestamp, which sets its own days.
45 @State var keepRequestedDays = false
46 @State var message: String?
47 @State var prompt: PendingPrompt?
48 @State var promptText = ""
49 @State var prefix: String?
50 /// Entries marked for a bulk action.
51 @State var marked: [EntryRef] = []
52 @State var logMode = false
53 @State var filter = AgendaFilter()
54 /// A filter question: its title and which filter it sets.
55 @State var filterPrompt: (title: String, kind: Character)?
56 @State var filterText = ""
57 /// A one-line question for an agenda action, and what to do with the answer.
58 struct TextPrompt {
59 let title: String
60 let apply: (String) -> Void
61 }
62 @State var textPrompt: TextPrompt?
63 @State private var textAnswer = ""
64 /// Day, week or month chosen with `v`; nil shows the span the settings or the view give.
65 @State var spanKind: AgendaSpan?
66 @State var showingDatePicker = false
67 @State var pickedDate = Date()
68 @AppStorage("agendaOverdueExpanded") private var overdueShown = true
69 @State private var hovered: String?
70 @FocusState private var focused: Bool
71 @AppStorage("agendaSpan") var span = 10
72 @AppStorage("agendaStartOffset") var startOffset = 0
73 @AppStorage("agendaStartOnWeekday") private var startOnWeekday = "1"
74 @AppStorage("agendaSubfolders") private var includeSubfolders = false
75 @AppStorage("agendaFiles") private var agendaFileList = ""
76 @AppStorage("agendaShowAllDates") private var showAllDates = false
77 @AppStorage("calendarEvents") private var calendarEventsOn = false
78 @AppStorage("calendarEventCalendars") private var calendarNames = ""
79 @AppStorage("agendaReminders") private var remindersOn = false
80 @AppStorage("agendaReminderLists") private var reminderListNames = ""
81 @AppStorage("agendaPrefixAgenda") private var prefixAgenda = PrefixFormat.defaults["agenda"]!
82 @AppStorage("agendaPrefixTodo") private var prefixTodo = PrefixFormat.defaults["todo"]!
83 @AppStorage("agendaPrefixTags") private var prefixTags = PrefixFormat.defaults["tags"]!
84 @AppStorage("agendaSortAgenda") private var sortAgenda = ""
85 @AppStorage("agendaSortTodo") private var sortTodo = ""
86 @AppStorage("agendaSortTags") private var sortTags = ""
87 @AppStorage("agendaSortSearch") private var sortSearch = ""
88 @AppStorage("agendaUseTimeGrid") private var useTimeGrid = true
89 @AppStorage("agendaShowCurrentTime") private var showCurrentTime = true
90 @AppStorage("agendaTimeGridWhen") private var gridWhen = ""
91 @AppStorage("agendaTimeGridTimes") private var gridTimes = ""
92 @AppStorage("stuckProjectsMatch") private var stuckMatch = ""
93 @AppStorage("stuckProjectsTodo") private var stuckTodo = ""
94 @AppStorage("stuckProjectsTags") private var stuckTags = ""
95 @AppStorage("stuckProjectsRegexp") private var stuckRegexp = ""
96 @Environment(\.openWindow) var openWindow
97
98 static let match = "Match…"
99 static let todoMatch = "TODO Match…"
100 static let search = "Search…"
101 static let todoSearch = "TODO Search…"
102
103 init(workspace: WorkspaceModel, session: DocumentSession, commands: AppCommands, scheduler: ReminderScheduler?, clock: ClockModel) {
104 self.workspace = workspace
105 self.session = session
106 self.commands = commands
107 self.scheduler = scheduler
108 self.clock = clock
109 _agenda = State(initialValue: AgendaModel(workspace: workspace))
110 }
111
112 /// An agenda entry by its file, heading line and where that line was.
113 struct EntryRef: Hashable {
114 let path: String
115 let line: String
116 let offset: Int
117
118 init?(_ item: AgendaItem) {
119 guard let path = item.path, let line = item.headingLine, let offset = item.headingOffset else { return nil }
120 self.path = path
121 self.line = line
122 self.offset = offset
123 }
124 }
125
126 struct PendingPrompt: Identifiable {
127 let id = UUID()
128 let prompt: Prompt
129 let command: any OrgCommand
130 let atMarker: Bool
131 let answers: [String: String]
132 let itemID: String
133 }
134
135 private struct RefreshKey: Hashable {
136 var mode: AgendaMode
137 var start: Int?
138 var span: Int
139 var startOffset: Int
140 var startOnWeekday: String
141 var includeSubfolders: Bool
142 var prefix: [String]
143 var settings: [String]
144 var logMode: Bool
145 var calendars: [String]
146 var files: Int
147 var changed: Int?
148 var edits: Int
149 var path: String?
150 var tick: Int
151 }
152
153 /// The settings part of the refresh key; `Refresher` adds the files and edits, so that
154 /// they redraw only it.
155 private var refreshKey: RefreshKey {
156 RefreshKey(
157 mode: agenda.mode, start: agenda.start, span: span, startOffset: startOffset, startOnWeekday: startOnWeekday, includeSubfolders: includeSubfolders, prefix: [prefixAgenda, prefixTodo, prefixTags],
158 settings: [sortAgenda, sortTodo, sortTags, sortSearch, gridWhen, gridTimes, "\(useTimeGrid) \(showCurrentTime)", stuckMatch, stuckTodo, stuckTags, stuckRegexp, agendaFileList],
159 logMode: logMode,
160 calendars: (calendarEventsOn ? [calendarNames] : []) + (remindersOn ? ["reminders", reminderListNames] : []), files: 0, changed: nil, edits: 0, path: nil, tick: tick
161 )
162 }
163
164 private func refresh() async {
165 agenda.span = span
166 agenda.startOffset = startOffset
167 agenda.startOnWeekday = Int(startOnWeekday)
168 agenda.includeSubfolders = includeSubfolders
169 agenda.agendaFiles = OrgPreferences.agendaFiles()
170 agenda.options.prefixFormat = ["agenda": prefixAgenda, "todo": prefixTodo, "tags": prefixTags]
171 agenda.options.logMode = logMode
172 agenda.options = OrgPreferences.agendaOptions(agenda.options)
173 agenda.calendarNames = OrgPreferences.calendarEventCalendars()
174 if calendarEventsOn, isAgenda || isBlocks {
175 agenda.calendarEvents = await CalendarAccess.events.requestAccess() ? CalendarAccess.events : nil
176 } else {
177 agenda.calendarEvents = nil
178 }
179 agenda.reminderListNames = OrgPreferences.agendaReminderLists()
180 if remindersOn, isAgenda || isBlocks {
181 agenda.reminderLists = await CalendarAccess.reminders.requestAccess() ? CalendarAccess.reminders : nil
182 } else {
183 agenda.reminderLists = nil
184 }
185 await agenda.refresh(open: session.openTexts)
186 }
187
188 /// Refreshes the agenda when the settings, files or edits change, once a burst of them ends.
189 private struct Refresher: View {
190 let base: RefreshKey
191 let session: DocumentSession
192 let workspace: WorkspaceModel
193 let refresh: () async -> Void
194
195 var key: RefreshKey {
196 var key = base
197 key.files = workspace.files.count
198 key.changed = workspace.changedFile?.version
199 key.edits = session.editVersion
200 key.path = session.path
201 return key
202 }
203
204 var body: some View {
205 Color.clear.task(id: key) {
206 try? await Task.sleep(for: .milliseconds(150))
207 guard !Task.isCancelled else { return }
208 await refresh()
209 }
210 }
211 }
212
213 var isAgenda: Bool {
214 if case .agenda = agenda.mode { return true }
215 return false
216 }
217
218 var isBlocks: Bool {
219 if case .blocks = agenda.mode { return true }
220 return false
221 }
222
223 var isMatch: Bool { viewName == Self.match || viewName == Self.todoMatch }
224 var isSearch: Bool { viewName == Self.search || viewName == Self.todoSearch }
225
226 @Environment(\.orgTheme) private var theme
227
228 // MARK: - Lines
229
230 /// A selectable line: its selection id, the row, and the day it is on.
231 struct Line {
232 let id: String
233 let row: AgendaRow
234 let day: Int
235 }
236
237 private var groups: [AgendaDayGroup] {
238 isAgenda ? agenda.groups(showAllDates: showAllDates, filter: filter) : []
239 }
240
241 private var listRows: [AgendaRow] { rows(agenda.list) }
242
243 private func rows(_ list: [AgendaItem]) -> [AgendaRow] {
244 list.filter(filter.keeps).compactMap { AgendaRow(item: $0, day: agenda.today, today: agenda.today) }
245 }
246
247 /// The lines in order, as up and down move through them.
248 func lines(_ groups: [AgendaDayGroup]) -> [Line] {
249 if isBlocks {
250 return agenda.blocks.enumerated().flatMap { k, block in
251 block.isAgenda ? dayLines(agenda.groups(block, showAllDates: showAllDates, filter: filter), prefix: "b\(k):")
252 : rows(block.list).enumerated().map { Line(id: "b\(k):list:\($0.offset)", row: $0.element, day: agenda.today) }
253 }
254 }
255 guard isAgenda else { return listRows.enumerated().map { Line(id: "list:\($0.offset)", row: $0.element, day: agenda.today) } }
256 return dayLines(groups, prefix: "")
257 }
258
259 private func dayLines(_ groups: [AgendaDayGroup], prefix: String) -> [Line] {
260 groups.flatMap { group in
261 (overdueShown ? group.overdue.enumerated().map { Line(id: "\(prefix)\(group.day):o\($0.offset)", row: $0.element, day: group.day) } : [])
262 + group.rows.enumerated().map { Line(id: "\(prefix)\(group.day):\($0.offset)", row: $0.element, day: group.day) }
263 }
264 }
265
266 func line(_ id: String) -> Line? { lines(groups).first { $0.id == id } }
267
268 var body: some View {
269 let groups = self.groups
270 _ = tick
271 return ScrollViewReader { proxy in
272 ScrollView {
273 LazyVStack(alignment: .leading, spacing: 0, pinnedViews: [.sectionHeaders]) {
274 if isBlocks {
275 ForEach(Array(agenda.blocks.enumerated()), id: \.offset) { k, block in
276 Section {
277 if block.isAgenda {
278 ForEach(agenda.groups(block, showAllDates: showAllDates, filter: filter)) { group in
279 dayHeader(group)
280 dayRows(group, prefix: "b\(k):")
281 }
282 } else {
283 ForEach(Array(rows(block.list).enumerated()), id: \.offset) { index, row in
284 rowView(Line(id: "b\(k):list:\(index)", row: row, day: agenda.today), showsGutter: false)
285 }
286 }
287 } header: {
288 header { Text(block.header).font(.system(size: 13, weight: .semibold)) }
289 }
290 }
291 } else if isAgenda {
292 ForEach(groups) { group in
293 Section {
294 dayRows(group)
295 } header: {
296 dayHeader(group).id("day\(group.day)")
297 }
298 }
299 } else {
300 Section {
301 ForEach(Array(listRows.enumerated()), id: \.offset) { index, row in
302 rowView(Line(id: "list:\(index)", row: row, day: agenda.today), showsGutter: false)
303 }
304 } header: {
305 header { Text(listTitle).font(.system(size: 13, weight: .semibold)) }
306 }
307 }
308 }
309 .padding(.bottom, 12)
310 }
311 .onChange(of: selection) {
312 if let selection { proxy.scrollTo(selection) }
313 }
314 .onChange(of: agenda.days.first?.day) {
315 if groups.contains(where: \.isToday) { proxy.scrollTo("day\(agenda.today)", anchor: .top) }
316 }
317 }
318 .background(theme.color("agenda-background") ?? Color(nsColor: .textBackgroundColor))
319 .focusable()
320 .focusEffectDisabled()
321 .focused($focused)
322 .onAppear { focused = true }
323 .onKeyPress(phases: .down) { press in handle(press) }
324 .safeAreaInset(edge: .bottom, spacing: 0) {
325 if let message = message ?? (filter.isEmpty ? reminderStatus : "Filter: " + filter.description) {
326 Text(message)
327 .font(.callout)
328 .frame(maxWidth: .infinity, alignment: .leading)
329 .padding(.horizontal, 12)
330 .padding(.vertical, 6)
331 .background(.bar)
332 }
333 }
334 .toolbar { toolbar }
335 .overlay {
336 if agenda.files.isEmpty {
337 ContentUnavailableView("No agenda files", systemImage: "calendar", description: Text("The agenda reads the org files at the top of each folder you add."))
338 }
339 }
340 .sheet(item: Binding(get: { prompt?.prompt.fast == nil ? nil : prompt }, set: { if $0 == nil { prompt = nil } })) { pending in
341 if let fast = pending.prompt.fast {
342 FastSelectionView(selection: fast, message: pending.prompt.message) { answer in
343 prompt = nil
344 guard let answer else { return }
345 promptText = answer
346 prompt = pending
347 answerPrompt()
348 }
349 .frame(minWidth: 420)
350 }
351 }
352 .alert(prompt?.prompt.message ?? "", isPresented: Binding(get: { prompt != nil && prompt?.prompt.fast == nil }, set: { if !$0 { prompt = nil } })) {
353 TextField("", text: $promptText)
354 Button("OK") { answerPrompt() }
355 Button("Cancel", role: .cancel) { prompt = nil }
356 } message: {
357 if let choices = prompt?.prompt.choices, !choices.isEmpty {
358 Text(choices.prefix(12).joined(separator: " "))
359 }
360 }
361 .alert(filterPrompt?.title ?? "", isPresented: Binding(get: { filterPrompt != nil }, set: { if !$0 { filterPrompt = nil } })) {
362 TextField("", text: $filterText)
363 Button("Filter") { applyFilter() }
364 Button("Cancel", role: .cancel) { filterPrompt = nil }
365 } message: {
366 if filterPrompt?.kind == "/" || filterPrompt?.kind == "\\" {
367 Text(shown.tags.sorted().prefix(20).joined(separator: " "))
368 }
369 }
370 .alert(textPrompt?.title ?? "", isPresented: Binding(get: { textPrompt != nil }, set: { if !$0 { textPrompt = nil } })) {
371 TextField("", text: $textAnswer)
372 Button("OK") {
373 let pending = textPrompt
374 let answer = textAnswer
375 textPrompt = nil
376 textAnswer = ""
377 // A follow-up question opens after this alert closes.
378 DispatchQueue.main.async { pending?.apply(answer) }
379 }
380 Button("Cancel", role: .cancel) {
381 textPrompt = nil
382 textAnswer = ""
383 }
384 }
385 .navigationTitle(title)
386 .navigationSubtitle(isAgenda && viewName != AgendaViewLoader.builtIn[0].name ? viewName : "")
387 .onChange(of: viewName) { applyView() }
388 .onChange(of: commands.agendaRequest?.start, initial: true) { showRequestedDays() }
389 .onChange(of: commands.agendaRequest?.days) { showRequestedDays() }
390 .background { Refresher(base: refreshKey, session: session, workspace: workspace, refresh: refresh) }
391 .task {
392 loadViews()
393 // The now line moves each minute; a new day refreshes the statuses.
394 while !Task.isCancelled {
395 let next = Calendar.current.nextDate(after: Date(), matching: DateComponents(second: 0), matchingPolicy: .nextTime) ?? Date().addingTimeInterval(60)
396 try? await Task.sleep(for: .seconds(next.timeIntervalSinceNow))
397 now = Date()
398 if Days.absolute(now, calendar: .current) != agenda.today { tick += 1 }
399 }
400 }
401 }
402
403 // MARK: - Days
404
405 private var todayColor: Color { theme.color("agenda-today") ?? .accentColor }
406
407 @ViewBuilder
408 private func dayRows(_ group: AgendaDayGroup, prefix: String = "") -> some View {
409 if group.isToday, !group.overdue.isEmpty {
410 overdueHeader(count: group.overdue.count)
411 if overdueShown {
412 ForEach(Array(group.overdue.enumerated()), id: \.element.id) { index, row in
413 rowView(Line(id: "\(prefix)\(group.day):o\(index)", row: row, day: group.day))
414 }
415 Divider().padding(.leading, 16).padding(.vertical, 4)
416 }
417 }
418 if group.isEmpty {
419 Text("Nothing scheduled")
420 .font(.callout)
421 .foregroundStyle(.secondary)
422 .padding(.horizontal, 16)
423 .padding(.vertical, 10)
424 }
425 ForEach(Array(group.lines(now: Self.hhmm(now)).enumerated()), id: \.offset) { _, line in
426 switch line {
427 case .row(let index): rowView(Line(id: "\(prefix)\(group.day):\(index)", row: group.rows[index], day: group.day))
428 case .grid(let time): gridLine(time)
429 case .now: nowLine
430 }
431 }
432 }
433
434 /// An `org-agenda-time-grid` line.
435 private func gridLine(_ time: Int) -> some View {
436 HStack(spacing: 6) {
437 Text(String(format: "%02d:%02d", time / 100, time % 100))
438 .font(.system(size: 10).monospacedDigit())
439 .frame(width: AgendaRowView.gutterWidth, alignment: .leading)
440 GridRule().stroke(style: StrokeStyle(lineWidth: 0.5, dash: [2, 3])).frame(height: 1)
441 }
442 .foregroundStyle(.tertiary)
443 .padding(.horizontal, 16)
444 .frame(height: 10)
445 .accessibilityHidden(true)
446 }
447
448 private func header(@ViewBuilder _ content: () -> some View) -> some View {
449 HStack(spacing: 6) { content() }
450 .padding(.horizontal, 16)
451 .frame(height: 30)
452 .frame(maxWidth: .infinity, alignment: .leading)
453 .background(theme.color("agenda-background") ?? Color(nsColor: .textBackgroundColor))
454 .overlay(alignment: .bottom) { Divider() }
455 }
456
457 private func dayHeader(_ group: AgendaDayGroup) -> some View {
458 let past = group.day < agenda.today
459 let color = group.isToday ? todayColor : past ? Color.secondary : theme.color("agenda-date") ?? .primary
460 return header {
461 if let relative = group.relativeName(today: agenda.today) {
462 Text(relative)
463 .font(.system(size: 13, weight: .bold))
464 .foregroundStyle(color)
465 Text("·").foregroundStyle(.tertiary)
466 }
467 Text(Self.format(group.day, Days.date(group.day).year == Days.date(agenda.today).year ? "EEEE d MMMM" : "EEEE d MMMM yyyy"))
468 .font(.system(size: 13, weight: group.isToday ? .bold : .semibold))
469 .foregroundStyle(color)
470 Spacer()
471 Button {
472 capture(on: group.day)
473 } label: {
474 Image(systemName: "plus")
475 .font(.system(size: 12, weight: .semibold))
476 .frame(width: 22, height: 22)
477 .contentShape(Rectangle())
478 }
479 .buttonStyle(.borderless)
480 .foregroundStyle(group.isToday ? todayColor : .secondary)
481 .help("Capture an entry scheduled on this day (k)")
482 }
483 }
484
485 private func overdueHeader(count: Int) -> some View {
486 let color = theme.dynamic(.systemRed) { [theme] in theme.statusColor(.overdue, dark: $0) }
487 return Button {
488 withAnimation(.snappy(duration: 0.2)) { overdueShown.toggle() }
489 if !overdueShown, selection?.contains(":o") == true { selection = nil }
490 } label: {
491 HStack(spacing: 6) {
492 Image(systemName: "chevron.right")
493 .font(.system(size: 10, weight: .bold))
494 .rotationEffect(.degrees(overdueShown ? 90 : 0))
495 Text("Overdue").font(.system(size: 12, weight: .semibold))
496 Text("\(count)")
497 .font(.system(size: 10, weight: .bold).monospacedDigit())
498 .padding(.horizontal, 6)
499 .padding(.vertical, 1)
500 .background(Capsule().fill(color.opacity(0.15)))
501 Spacer()
502 }
503 .foregroundStyle(color)
504 .padding(.horizontal, 16)
505 .padding(.top, 8)
506 .padding(.bottom, 4)
507 .contentShape(Rectangle())
508 }
509 .buttonStyle(.plain)
510 .help(overdueShown ? "Hide entries from earlier days" : "Show entries from earlier days")
511 }
512
513 private var nowLine: some View {
514 HStack(spacing: 6) {
515 Text(now.formatted(.dateTime.hour(.twoDigits(amPM: .omitted)).minute()))
516 .font(.system(size: 10, weight: .semibold).monospacedDigit())
517 .frame(width: AgendaRowView.gutterWidth, alignment: .leading)
518 Circle().frame(width: 6, height: 6)
519 Rectangle().frame(height: 1)
520 }
521 .foregroundStyle(todayColor)
522 .padding(.horizontal, 16)
523 .frame(height: 10)
524 .accessibilityLabel("Now")
525 }
526
527 private func rowView(_ line: Line, showsGutter: Bool = true) -> some View {
528 AgendaRowView(
529 row: line.row, day: line.day, showsGutter: showsGutter, selected: selection == line.id, hovered: hovered == line.id,
530 marked: line.row.item.flatMap(EntryRef.init).map(marked.contains) ?? false
531 )
532 .id(line.id)
533 .contentShape(Rectangle())
534 .onHover { inside in
535 if inside { hovered = line.id } else if hovered == line.id { hovered = nil }
536 }
537 .onTapGesture(count: 2) { open(line) }
538 .simultaneousGesture(TapGesture().onEnded {
539 selection = line.id
540 focused = true
541 })
542 .contextMenu { menu(line) }
543 }
544
545 @ViewBuilder
546 private func menu(_ line: Line) -> some View {
547 if let event = line.row.event {
548 Button(event.isReminder ? "Show in Reminders" : "Show in Calendar") { openEvent(event) }
549 } else if line.row.item != nil {
550 Button("Open") { selection = line.id; jump(line.id) }
551 Divider()
552 Button("Cycle TODO State") { selection = line.id; run(TodoCycle()) }
553 Button("Set Priority…") { selection = line.id; run(SetPriority()) }
554 Button("Set Tags…") { selection = line.id; run(SetTags()) }
555 Button("Schedule…") { selection = line.id; run(SetPlanning(deadline: false)) }
556 Button("Set Deadline…") { selection = line.id; run(SetPlanning(deadline: true)) }
557 Divider()
558 Button("Clock In") { selection = line.id; clockIn() }
559 Button(EntryRef(line.row.item!).map(marked.contains) == true ? "Unmark" : "Mark") {
560 selection = line.id
561 mark(!(EntryRef(line.row.item!).map(marked.contains) ?? false))
562 }
563 Button("Archive") { selection = line.id; archive() }
564 }
565 }
566
567 @AppStorage("reminders") var remindersEnabled = true
568
569 // MARK: - Items
570
571 func item(_ id: String) -> AgendaItem? { line(id)?.row.item }
572
573 /// Return and double click: the entry in the main window, or the event in Calendar or Reminders.
574 func open(_ line: Line) {
575 selection = line.id
576 if let event = line.row.event { openEvent(event) } else { jump(line.id) }
577 }
578
579 /// Calendar shows an event from its identifier (`AgendaEvent.id` adds `@` and the start);
580 /// Reminders a reminder from its own.
581 private func openEvent(_ event: AgendaEvent) {
582 if event.isReminder {
583 if let url = URL(string: "x-apple-reminderkit://REMCDReminder/\(event.id)") { NSWorkspace.shared.open(url) }
584 return
585 }
586 let identifier = event.id.split(separator: "@").dropLast().joined(separator: "@")
587 guard !identifier.isEmpty, let encoded = identifier.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed),
588 let url = URL(string: "ical://ekevent/\(encoded)?method=show&options=more") else { return }
589 NSWorkspace.shared.open(url)
590 }
591
592 /// Moves the selection by `step` lines.
593 func step(_ step: Int) {
594 let all = lines(groups)
595 guard !all.isEmpty else { return }
596 let index = selection.flatMap { id in all.firstIndex { $0.id == id } }
597 let next = index.map { min(max($0 + step, 0), all.count - 1) } ?? (step > 0 ? 0 : all.count - 1)
598 selection = all[next].id
599 }
600}
601
602/// A horizontal line through the middle of its frame.
603struct GridRule: Shape {
604 func path(in rect: CGRect) -> Path {
605 Path { path in
606 path.move(to: CGPoint(x: rect.minX, y: rect.midY))
607 path.addLine(to: CGPoint(x: rect.maxX, y: rect.midY))
608 }
609 }
610}