Sources/Orgstar/AgendaView.swift
562 lines · 23920 bytes
1import OrgApp
2import OrgCore
3import OrgPresentation
4import SwiftUI
5
6/// The agenda window: the day/week agenda, the TODO list, tag matches and saved views.
7/// Return or a double click jumps to the entry in the main window. Keys as in Emacs's agenda:
8/// f/b/. move the span, g refreshes, l shows the log (closed and clocked), / filters
9/// (`+cat-tag<0:10-/regexp/`), \ by tag, < by the line's category, = by regexp, _ by effort,
10/// | clears filters, t cycles the TODO state, +/- change the priority, : or
11/// C-c C-q sets tags, C-c C-s / C-c C-d schedule and set a deadline, S-→/S-← move the date.
12struct AgendaView: View {
13 let workspace: WorkspaceModel
14 let session: DocumentSession
15 let commands: AppCommands
16 let scheduler: ReminderScheduler?
17 @State private var agenda: AgendaModel
18 @State private var views = AgendaViewLoader.builtIn
19 @State private var viewName = AgendaViewLoader.builtIn[0].name
20 @State private var matchText = ""
21 @State private var selection: String?
22 @State private var tick = 0
23 @State private var message: String?
24 @State private var prompt: PendingPrompt?
25 @State private var promptText = ""
26 @State private var prefix = false
27 @State private var logMode = false
28 @State private var filter = AgendaFilter()
29 /// A filter question: its title, the text it starts with, and how the answer applies.
30 @State private var filterPrompt: (title: String, kind: Character)?
31 @State private var filterText = ""
32 @AppStorage("agendaSpan") private var span = 10
33 @AppStorage("agendaStartOffset") private var startOffset = -3
34 @AppStorage("agendaSubfolders") private var includeSubfolders = false
35 @AppStorage("agendaPrefixAgenda") private var prefixAgenda = PrefixFormat.defaults["agenda"]!
36 @AppStorage("agendaPrefixTodo") private var prefixTodo = PrefixFormat.defaults["todo"]!
37 @AppStorage("agendaPrefixTags") private var prefixTags = PrefixFormat.defaults["tags"]!
38 @Environment(\.openWindow) private var openWindow
39
40 static let match = "Match…"
41 static let todoMatch = "TODO Match…"
42
43 init(workspace: WorkspaceModel, session: DocumentSession, commands: AppCommands, scheduler: ReminderScheduler?) {
44 self.workspace = workspace
45 self.session = session
46 self.commands = commands
47 self.scheduler = scheduler
48 _agenda = State(initialValue: AgendaModel(workspace: workspace))
49 }
50
51 struct PendingPrompt: Identifiable {
52 let id = UUID()
53 let prompt: Prompt
54 let command: any OrgCommand
55 let atMarker: Bool
56 let answers: [String: String]
57 let itemID: String
58 }
59
60 private struct RefreshKey: Hashable {
61 var mode: AgendaMode
62 var start: Int?
63 var span: Int
64 var startOffset: Int
65 var includeSubfolders: Bool
66 var prefix: [String]
67 var logMode: Bool
68 var files: Int
69 var changed: Int?
70 var edits: Int
71 var path: String?
72 var tick: Int
73 }
74
75 private var refreshKey: RefreshKey {
76 RefreshKey(
77 mode: agenda.mode, start: agenda.start, span: span, startOffset: startOffset, includeSubfolders: includeSubfolders, prefix: [prefixAgenda, prefixTodo, prefixTags], logMode: logMode,
78 files: workspace.files.count, changed: workspace.changedFile?.version, edits: session.editVersion,
79 path: session.path, tick: tick
80 )
81 }
82
83 private var isAgenda: Bool {
84 if case .agenda = agenda.mode { return true }
85 return false
86 }
87
88 private var isMatch: Bool { viewName == Self.match || viewName == Self.todoMatch }
89
90 private var customPrefix: Bool {
91 switch agenda.mode {
92 case .agenda: prefixAgenda != PrefixFormat.defaults["agenda"]
93 case .todo: prefixTodo != PrefixFormat.defaults["todo"]
94 case .match: prefixTags != PrefixFormat.defaults["tags"]
95 }
96 }
97
98 @Environment(\.orgTheme) private var theme
99
100 var body: some View {
101 List(selection: $selection) {
102 if isAgenda {
103 ForEach(agenda.days, id: \.day) { day in
104 Section {
105 rows(day.items.filter(filter.keeps), prefix: "\(day.day)", day: day.day)
106 } header: {
107 Text(day.header)
108 .font(.headline)
109 .foregroundStyle(day.isToday ? theme.color("agenda-today") ?? .accentColor : theme.color("agenda-date") ?? .primary)
110 }
111 }
112 } else {
113 Section {
114 rows(agenda.list.filter(filter.keeps), prefix: "list")
115 } header: {
116 Text(listTitle).font(.headline)
117 }
118 }
119 }
120 .themedListBackground(theme.color("agenda-background"))
121 .contextMenu(forSelectionType: String.self) { _ in
122 } primaryAction: { ids in
123 if let id = ids.first { jump(id) }
124 }
125 .onKeyPress(phases: .down) { press in handle(press) }
126 .safeAreaInset(edge: .bottom, spacing: 0) {
127 if let message = message ?? (filter.isEmpty ? reminderStatus : "Filter: " + filter.description) {
128 Text(message)
129 .font(.callout)
130 .frame(maxWidth: .infinity, alignment: .leading)
131 .padding(.horizontal, 12)
132 .padding(.vertical, 6)
133 .background(.bar)
134 }
135 }
136 .toolbar {
137 ToolbarItemGroup(placement: .navigation) {
138 Menu {
139 ForEach(views) { view in Button(view.name) { viewName = view.name } }
140 Divider()
141 Button(Self.match) { viewName = Self.match }
142 Button(Self.todoMatch) { viewName = Self.todoMatch }
143 } label: {
144 Label(viewName, systemImage: "calendar").labelStyle(.titleAndIcon)
145 }
146 .help("What the agenda shows")
147 if isMatch {
148 TextField("+work-boss|LEVEL>2/!TODO", text: $matchText)
149 .frame(minWidth: 220)
150 .onSubmit { applyView() }
151 }
152 }
153 ToolbarItemGroup {
154 if agenda.isComputing { ProgressView().controlSize(.small) }
155 if isAgenda {
156 Button("Earlier", systemImage: "chevron.left") { agenda.shift(forward: false) }
157 .help("Previous days (b)")
158 Button("Today") { agenda.showToday() }
159 .help("Back to today (.)")
160 Button("Later", systemImage: "chevron.right") { agenda.shift(forward: true) }
161 .help("Next days (f)")
162 }
163 }
164 }
165 .overlay {
166 if agenda.files.isEmpty {
167 ContentUnavailableView("No agenda files", systemImage: "calendar", description: Text("The agenda reads the org files at the top of each folder you add."))
168 }
169 }
170 .sheet(item: Binding(get: { prompt?.prompt.fast == nil ? nil : prompt }, set: { if $0 == nil { prompt = nil } })) { pending in
171 if let fast = pending.prompt.fast {
172 FastSelectionView(selection: fast, message: pending.prompt.message) { answer in
173 prompt = nil
174 guard let answer else { return }
175 promptText = answer
176 prompt = pending
177 answerPrompt()
178 }
179 .frame(minWidth: 420)
180 }
181 }
182 .alert(prompt?.prompt.message ?? "", isPresented: Binding(get: { prompt != nil && prompt?.prompt.fast == nil }, set: { if !$0 { prompt = nil } })) {
183 TextField("", text: $promptText)
184 Button("OK") { answerPrompt() }
185 Button("Cancel", role: .cancel) { prompt = nil }
186 } message: {
187 if let choices = prompt?.prompt.choices, !choices.isEmpty {
188 Text(choices.prefix(12).joined(separator: " "))
189 }
190 }
191 .alert(filterPrompt?.title ?? "", isPresented: Binding(get: { filterPrompt != nil }, set: { if !$0 { filterPrompt = nil } })) {
192 TextField("", text: $filterText)
193 Button("Filter") { applyFilter() }
194 Button("Cancel", role: .cancel) { filterPrompt = nil }
195 } message: {
196 if filterPrompt?.kind == "/" || filterPrompt?.kind == "\\" {
197 Text(shown.tags.sorted().prefix(20).joined(separator: " "))
198 }
199 }
200 .navigationTitle(viewName.replacingOccurrences(of: "…", with: ""))
201 .onChange(of: viewName) { applyView() }
202 .task(id: refreshKey) {
203 agenda.span = span
204 agenda.startOffset = startOffset
205 agenda.includeSubfolders = includeSubfolders
206 agenda.options.prefixFormat = ["agenda": prefixAgenda, "todo": prefixTodo, "tags": prefixTags]
207 agenda.options.logMode = logMode
208 let open = session.openTexts
209 await agenda.refresh(open: open)
210 }
211 .task {
212 loadViews()
213 // The time grid's "now" line and the day itself move on.
214 while !Task.isCancelled {
215 try? await Task.sleep(for: .seconds(60))
216 tick += 1
217 }
218 }
219 }
220
221 @ViewBuilder
222 private func rows(_ items: [AgendaItem], prefix: String, day: Int? = nil) -> some View {
223 ForEach(Array(items.enumerated()), id: \.offset) { index, item in
224 AgendaRow(item: item, day: day, customPrefix: customPrefix)
225 .tag("\(prefix):\(index)")
226 .selectionDisabled(item.path == nil)
227 }
228 }
229
230 @AppStorage("reminders") private var remindersEnabled = true
231
232 /// How far ahead notifications are set, as the design asks the agenda to show.
233 private var reminderStatus: String? {
234 guard let scheduler, remindersEnabled else { return nil }
235 if !scheduler.isAuthorized { return "Notifications are off for Orgstar in System Settings." }
236 guard let through = scheduler.scheduledThrough else { return nil }
237 return "Reminders are set through " + through.formatted(.dateTime.weekday(.abbreviated).day().month(.abbreviated).hour().minute()) + "."
238 }
239
240 private var listTitle: String {
241 switch agenda.mode {
242 case .todo(let keywords): "TODO items: \(keywords ?? "all")"
243 case .match(let match, let todoOnly): (todoOnly ? "TODO entries" : "Entries") + " matching \(match)"
244 case .agenda: ""
245 }
246 }
247
248 private func loadViews() {
249 let loaded = AgendaViewLoader.load()
250 views = loaded.views
251 message = loaded.problems.first
252 }
253
254 private func applyView() {
255 selection = nil
256 agenda.start = nil
257 switch viewName {
258 case Self.match, Self.todoMatch:
259 let match = matchText.trimmingCharacters(in: .whitespaces)
260 guard !match.isEmpty else { return }
261 agenda.mode = .match(match, todoOnly: viewName == Self.todoMatch)
262 default:
263 if let view = views.first(where: { $0.name == viewName }) { agenda.mode = view.mode }
264 }
265 }
266
267 // MARK: - Items
268
269 private func item(_ id: String) -> AgendaItem? {
270 let parts = id.split(separator: ":")
271 guard parts.count == 2, let index = Int(parts[1]) else { return nil }
272 let items = (parts[0] == "list" ? agenda.list : agenda.days.first { "\($0.day)" == parts[0] }?.items ?? []).filter(filter.keeps)
273 return index < items.count ? items[index] : nil
274 }
275
276 // MARK: - Filters
277
278 /// The tags and categories on the view's lines, which filter words are read against.
279 private var shown: (tags: Set<String>, categories: Set<String>) {
280 let items = (isAgenda ? agenda.days.flatMap(\.items) : agenda.list).filter { $0.path != nil }
281 return (Set(items.flatMap(\.tags)), Set(items.map(\.category)))
282 }
283
284 private func askFilter(_ kind: Character) {
285 switch kind {
286 case "/": filterText = filter.description
287 default: filterText = ""
288 }
289 let title = switch kind {
290 case "/": "Filter [+cat-tag<0:10-/regexp/]:"
291 case "\\": "Tag filter (+tag-tag):"
292 case "=": "Regexp filter (-re to drop):"
293 default: "Effort filter (<0:30, >1:00, =1:00):"
294 }
295 filterPrompt = (title, kind)
296 }
297
298 private func applyFilter() {
299 guard let kind = filterPrompt?.kind else { return }
300 filterPrompt = nil
301 let text = filterText.trimmingCharacters(in: .whitespaces)
302 var current = filter
303 switch kind {
304 case "/":
305 let (parsed, ignored) = AgendaFilter().parse(text, tags: shown.tags, categories: shown.categories)
306 current = parsed
307 if !ignored.isEmpty { message = "\(ignored.joined(separator: " ")) ignored: no line has that tag or category" }
308 case "\\":
309 // Every word as a tag.
310 current.tags = AgendaFilter().parse(text, tags: Set(text.split(whereSeparator: { "+- ".contains($0) }).map(String.init)), categories: []).filter.tags
311 case "=":
312 current.regexps = text.isEmpty ? [] : [text.hasPrefix("-") || text.hasPrefix("+") ? text : "+" + text]
313 default:
314 current.efforts = text.isEmpty ? [] : ["+" + text]
315 }
316 filter = current
317 selection = nil
318 }
319
320 /// `<`: keep only the selected line's category, or drop that filter.
321 private func toggleCategoryFilter() {
322 if !filter.categories.isEmpty {
323 filter.categories = []
324 } else if let selection, let item = item(selection) {
325 filter.categories = ["+" + item.category]
326 } else {
327 message = "No entry selected"
328 }
329 }
330
331 private func jump(_ id: String) {
332 guard let item = item(id), let path = item.path, let offset = item.markerOffset ?? item.headingOffset else { return }
333 commands.jump(path: path, offset: offset)
334 openWindow(id: "main")
335 }
336
337 // MARK: - Commands
338
339 private func handle(_ press: KeyPress) -> KeyPress.Result {
340 let control = press.modifiers.contains(.control)
341 if prefix {
342 prefix = false
343 switch (control, press.characters) {
344 case (true, "\u{13}"), (true, "s"): run(SetPlanning(deadline: false))
345 case (true, "\u{04}"), (true, "d"): run(SetPlanning(deadline: true))
346 case (true, "\u{11}"), (true, "q"): run(SetTags())
347 case (true, "\u{14}"), (true, "t"): run(TodoCycle())
348 default: message = "C-c \(press.characters) is undefined"
349 }
350 return .handled
351 }
352 if control, press.characters == "c" || press.characters == "\u{03}" {
353 prefix = true
354 message = "C-c-"
355 return .handled
356 }
357 if press.key == .return, let selection {
358 jump(selection)
359 return .handled
360 }
361 if press.modifiers == .shift, press.key == .rightArrow || press.key == .leftArrow {
362 run(ShiftTimestampDay(later: press.key == .rightArrow), atMarker: true)
363 return .handled
364 }
365 guard press.modifiers.subtracting(.shift).isEmpty else { return .ignored }
366 switch press.characters {
367 case "f" where isAgenda: agenda.shift(forward: true)
368 case "b" where isAgenda: agenda.shift(forward: false)
369 case "." where isAgenda: agenda.showToday()
370 case "/", "\\", "=", "_": askFilter(press.characters.first!)
371 case "<": toggleCategoryFilter()
372 case "|":
373 filter = AgendaFilter()
374 message = "Filters removed"
375 case "l" where isAgenda:
376 logMode.toggle()
377 message = logMode ? "Log mode on" : "Log mode off"
378 case "g", "r":
379 loadViews()
380 tick += 1
381 case "t": run(TodoCycle())
382 case "+": run(PriorityUp())
383 case "-": run(PriorityDown())
384 case ":": run(SetTags())
385 default: return .ignored
386 }
387 return .handled
388 }
389
390 /// Runs `command` on the selected entry, at its heading or, with `atMarker`, at the
391 /// timestamp the entry is listed for.
392 private func run(_ command: any OrgCommand, atMarker: Bool = false, answers: [String: String] = [:], itemID: String? = nil) {
393 guard let id = itemID ?? selection, let item = item(id), let path = item.path, let start = item.headingOffset else {
394 message = "No entry selected"
395 return
396 }
397 if atMarker, ![.deadline, .upcomingDeadline, .scheduled, .pastScheduled, .timestamp].contains(item.kind) {
398 message = "Only dated entries can move"
399 return
400 }
401 let offset = atMarker ? (item.markerOffset ?? start) : start
402 let step = session.perform(command, path: path, at: offset, expect: item.headingLine.map { (start, $0) }, answers: answers)
403 switch step {
404 case .prompt(let request):
405 promptText = request.initial
406 prompt = PendingPrompt(prompt: request, command: command, atMarker: atMarker, answers: answers, itemID: id)
407 case .failed(let text):
408 message = text
409 tick += 1
410 case .external:
411 message = "Not available from the agenda"
412 case .commit:
413 message = nil
414 tick += 1
415 }
416 }
417
418 private func answerPrompt() {
419 guard let pending = prompt else { return }
420 prompt = nil
421 var answers = pending.answers
422 answers[pending.prompt.key] = promptText
423 run(pending.command, atMarker: pending.atMarker, answers: answers, itemID: pending.itemID)
424 }
425}
426
427struct AgendaRow: View {
428 let item: AgendaItem
429 /// The agenda day the row is on, for habit graphs.
430 var day: Int?
431 /// A user `org-agenda-prefix-format`: the prefix as Emacs prints it, not the columns.
432 var customPrefix = false
433 @Environment(\.orgTheme) private var theme
434
435 var body: some View {
436 switch item.kind {
437 case .timeGrid:
438 HStack(spacing: 8) {
439 Text(Self.trim(item.time))
440 .monospacedDigit()
441 .frame(width: 140, alignment: .trailing)
442 VStack { Divider() }
443 }
444 .font(.caption)
445 .foregroundStyle(theme.color("agenda-time").map(AnyShapeStyle.init) ?? AnyShapeStyle(.tertiary))
446 case .currentTime:
447 HStack(spacing: 8) {
448 Text("now " + Self.trim(item.time))
449 .monospacedDigit()
450 .frame(width: 140, alignment: .trailing)
451 Rectangle().fill(theme.color("agenda-today") ?? .accentColor).frame(height: 1)
452 }
453 .font(.caption)
454 .foregroundStyle(theme.color("agenda-today") ?? .accentColor)
455 default:
456 if customPrefix {
457 HStack(spacing: 0) {
458 Text(item.prefix)
459 .font(.body.monospaced())
460 .foregroundStyle(theme.color("agenda-category") ?? .secondary)
461 title.lineLimit(1)
462 Spacer(minLength: 8)
463 if let habit = item.habit, let day { HabitGraph(cells: habit.graph(today: day), theme: theme) }
464 if !item.tags.isEmpty {
465 Text(":" + item.tags.joined(separator: ":") + ":").font(.caption).foregroundStyle(theme.color("tags") ?? .secondary)
466 }
467 }
468 } else {
469 HStack(spacing: 8) {
470 Text(item.category)
471 .lineLimit(1)
472 .foregroundStyle(theme.color("agenda-category") ?? .secondary)
473 .frame(width: 80, alignment: .leading)
474 if item.kind != .todo, item.kind != .tagsMatch {
475 Text(Self.trim(item.time))
476 .monospacedDigit()
477 .foregroundStyle(theme.color("agenda-time") ?? .primary)
478 .frame(width: 80, alignment: .leading)
479 }
480 if !item.extra.isEmpty {
481 Text(item.extra.trimmingCharacters(in: .whitespaces))
482 .monospacedDigit()
483 .foregroundStyle(leaderColor)
484 }
485 title
486 .lineLimit(1)
487 Spacer(minLength: 8)
488 if let habit = item.habit, let day {
489 HabitGraph(cells: habit.graph(today: day), theme: theme)
490 }
491 if !item.tags.isEmpty {
492 Text(":" + item.tags.joined(separator: ":") + ":")
493 .font(.caption)
494 .foregroundStyle(theme.color("tags") ?? .secondary)
495 }
496 }
497 }
498 }
499 }
500
501 static func trim(_ time: String) -> String {
502 time.trimmingCharacters(in: CharacterSet(charactersIn: " ┄."))
503 }
504
505 private var leaderColor: Color {
506 switch item.kind {
507 case .deadline: theme.color("agenda-deadline") ?? .red
508 case .upcomingDeadline: theme.color("agenda-upcoming") ?? .orange
509 case .pastScheduled: theme.color("agenda-scheduled-past") ?? .brown
510 default: theme.color("agenda-scheduled") ?? .secondary
511 }
512 }
513
514 /// The TODO keyword colored as in the editor.
515 private var title: Text {
516 let text = item.text.trimmingCharacters(in: .whitespaces)
517 guard let todo = item.todo, text.hasPrefix(todo + " ") else { return Text(text) }
518 let rest = String(text.dropFirst(todo.count))
519 let rest_ = Text(rest).foregroundColor(item.isDone ? theme.color("comment") ?? .secondary : theme.color("foreground") ?? .primary)
520 return Text(todo).foregroundColor(theme.keywordColor(todo, done: item.isDone)).bold() + rest_
521 }
522}
523
524/// org-habit's consistency graph: a cell per day, `*` where the habit was done, `!` today.
525struct HabitGraph: View {
526 let cells: [Habit.Cell]
527 var theme: ThemeSpec = .default
528
529 var body: some View {
530 HStack(spacing: 1) {
531 ForEach(cells, id: \.day) { cell in
532 Text(String(cell.glyph))
533 .font(.system(size: 9, weight: .bold, design: .monospaced))
534 .frame(width: 8, height: 14)
535 .background(color(cell.face))
536 .help(Self.label(cell))
537 }
538 }
539 .accessibilityElement(children: .ignore)
540 .accessibilityLabel("Done \(cells.filter { $0.glyph == "*" }.count) of the last \(Habit.precedingDays) days")
541 }
542
543 /// Due-state colors, lighter for days to come, as org-habit's faces.
544 func color(_ face: Habit.Face) -> Color {
545 func themed(_ key: String, _ fallback: Color) -> Color { theme.color(key) ?? fallback }
546 switch face {
547 case .clear: return themed("habit-clear", .blue).opacity(0.7)
548 case .clearFuture: return themed("habit-clear", .blue).opacity(0.35)
549 case .ready: return themed("habit-ready", .green).opacity(0.75)
550 case .readyFuture: return themed("habit-ready", .green).opacity(0.35)
551 case .alert: return themed("habit-alert", .yellow).opacity(0.85)
552 case .alertFuture: return themed("habit-alert", .yellow).opacity(0.4)
553 case .overdue: return themed("habit-overdue", .red).opacity(0.75)
554 case .overdueFuture: return themed("habit-overdue", .red).opacity(0.35)
555 }
556 }
557
558 static func label(_ cell: Habit.Cell) -> String {
559 let date = Days.date(cell.day)
560 return String(format: "%04d-%02d-%02d", date.year, date.month, date.day) + (cell.glyph == "*" ? " DONE" : "")
561 }
562}