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