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