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