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