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