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