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