Sources/Orgstar/AgendaView.swift
374 lines · 14479 bytes
1import OrgApp
2import OrgCore
3import SwiftUI
4
5/// The agenda window: the day/week agenda, the TODO list, tag matches and saved views.
6/// Return or a double click jumps to the entry in the main window. Keys as in Emacs's agenda:
7/// f/b/. move the span, g refreshes, t cycles the TODO state, +/- change the priority, : or
8/// C-c C-q sets tags, C-c C-s / C-c C-d schedule and set a deadline, S-→/S-← move the date.
9struct AgendaView: View {
10 let workspace: WorkspaceModel
11 let session: DocumentSession
12 let commands: AppCommands
13 @State private var agenda: AgendaModel
14 @State private var views = AgendaViewLoader.builtIn
15 @State private var viewName = AgendaViewLoader.builtIn[0].name
16 @State private var matchText = ""
17 @State private var selection: String?
18 @State private var tick = 0
19 @State private var message: String?
20 @State private var prompt: PendingPrompt?
21 @State private var promptText = ""
22 @State private var prefix = false
23 @AppStorage("agendaSpan") private var span = 10
24 @AppStorage("agendaStartOffset") private var startOffset = -3
25 @AppStorage("agendaSubfolders") private var includeSubfolders = false
26 @Environment(\.openWindow) private var openWindow
27
28 static let match = "Match…"
29 static let todoMatch = "TODO Match…"
30
31 init(workspace: WorkspaceModel, session: DocumentSession, commands: AppCommands) {
32 self.workspace = workspace
33 self.session = session
34 self.commands = commands
35 _agenda = State(initialValue: AgendaModel(workspace: workspace))
36 }
37
38 struct PendingPrompt: Identifiable {
39 let id = UUID()
40 let prompt: Prompt
41 let command: any OrgCommand
42 let atMarker: Bool
43 let answers: [String: String]
44 let itemID: String
45 }
46
47 private struct RefreshKey: Hashable {
48 var mode: AgendaMode
49 var start: Int?
50 var span: Int
51 var startOffset: Int
52 var includeSubfolders: Bool
53 var files: Int
54 var changed: Int?
55 var edits: Int
56 var path: String?
57 var tick: Int
58 }
59
60 private var refreshKey: RefreshKey {
61 RefreshKey(
62 mode: agenda.mode, start: agenda.start, span: span, startOffset: startOffset, includeSubfolders: includeSubfolders,
63 files: workspace.files.count, changed: workspace.changedFile?.version, edits: session.editVersion,
64 path: session.path, tick: tick
65 )
66 }
67
68 private var isAgenda: Bool {
69 if case .agenda = agenda.mode { return true }
70 return false
71 }
72
73 private var isMatch: Bool { viewName == Self.match || viewName == Self.todoMatch }
74
75 var body: some View {
76 List(selection: $selection) {
77 if isAgenda {
78 ForEach(agenda.days, id: \.day) { day in
79 Section {
80 rows(day.items, prefix: "\(day.day)")
81 } header: {
82 Text(day.header)
83 .font(.headline)
84 .foregroundStyle(day.isToday ? Color.accentColor : .primary)
85 }
86 }
87 } else {
88 Section {
89 rows(agenda.list, prefix: "list")
90 } header: {
91 Text(listTitle).font(.headline)
92 }
93 }
94 }
95 .contextMenu(forSelectionType: String.self) { _ in
96 } primaryAction: { ids in
97 if let id = ids.first { jump(id) }
98 }
99 .onKeyPress(phases: .down) { press in handle(press) }
100 .safeAreaInset(edge: .bottom, spacing: 0) {
101 if let message {
102 Text(message)
103 .font(.callout)
104 .frame(maxWidth: .infinity, alignment: .leading)
105 .padding(.horizontal, 12)
106 .padding(.vertical, 6)
107 .background(.bar)
108 }
109 }
110 .toolbar {
111 ToolbarItemGroup(placement: .navigation) {
112 Menu {
113 ForEach(views) { view in Button(view.name) { viewName = view.name } }
114 Divider()
115 Button(Self.match) { viewName = Self.match }
116 Button(Self.todoMatch) { viewName = Self.todoMatch }
117 } label: {
118 Label(viewName, systemImage: "calendar").labelStyle(.titleAndIcon)
119 }
120 .help("What the agenda shows")
121 if isMatch {
122 TextField("+work-boss|LEVEL>2/!TODO", text: $matchText)
123 .frame(minWidth: 220)
124 .onSubmit { applyView() }
125 }
126 }
127 ToolbarItemGroup {
128 if agenda.isComputing { ProgressView().controlSize(.small) }
129 if isAgenda {
130 Button("Earlier", systemImage: "chevron.left") { agenda.shift(forward: false) }
131 .help("Previous days (b)")
132 Button("Today") { agenda.showToday() }
133 .help("Back to today (.)")
134 Button("Later", systemImage: "chevron.right") { agenda.shift(forward: true) }
135 .help("Next days (f)")
136 }
137 }
138 }
139 .overlay {
140 if agenda.files.isEmpty {
141 ContentUnavailableView("No agenda files", systemImage: "calendar", description: Text("The agenda reads the org files at the top of each folder you add."))
142 }
143 }
144 .alert(prompt?.prompt.message ?? "", isPresented: Binding(get: { prompt != nil }, set: { if !$0 { prompt = nil } })) {
145 TextField("", text: $promptText)
146 Button("OK") { answerPrompt() }
147 Button("Cancel", role: .cancel) { prompt = nil }
148 } message: {
149 if let choices = prompt?.prompt.choices, !choices.isEmpty {
150 Text(choices.prefix(12).joined(separator: " "))
151 }
152 }
153 .navigationTitle(viewName.replacingOccurrences(of: "…", with: ""))
154 .onChange(of: viewName) { applyView() }
155 .task(id: refreshKey) {
156 agenda.span = span
157 agenda.startOffset = startOffset
158 agenda.includeSubfolders = includeSubfolders
159 let open = session.path.flatMap { path in session.document.map { (path, $0.text) } }
160 await agenda.refresh(open: open)
161 }
162 .task {
163 loadViews()
164 // The time grid's "now" line and the day itself move on.
165 while !Task.isCancelled {
166 try? await Task.sleep(for: .seconds(60))
167 tick += 1
168 }
169 }
170 }
171
172 @ViewBuilder
173 private func rows(_ items: [AgendaItem], prefix: String) -> some View {
174 ForEach(Array(items.enumerated()), id: \.offset) { index, item in
175 AgendaRow(item: item)
176 .tag("\(prefix):\(index)")
177 .selectionDisabled(item.path == nil)
178 }
179 }
180
181 private var listTitle: String {
182 switch agenda.mode {
183 case .todo(let keywords): "TODO items: \(keywords ?? "all")"
184 case .match(let match, let todoOnly): (todoOnly ? "TODO entries" : "Entries") + " matching \(match)"
185 case .agenda: ""
186 }
187 }
188
189 private func loadViews() {
190 let loaded = AgendaViewLoader.load()
191 views = loaded.views
192 message = loaded.problems.first
193 }
194
195 private func applyView() {
196 selection = nil
197 agenda.start = nil
198 switch viewName {
199 case Self.match, Self.todoMatch:
200 let match = matchText.trimmingCharacters(in: .whitespaces)
201 guard !match.isEmpty else { return }
202 agenda.mode = .match(match, todoOnly: viewName == Self.todoMatch)
203 default:
204 if let view = views.first(where: { $0.name == viewName }) { agenda.mode = view.mode }
205 }
206 }
207
208 // MARK: - Items
209
210 private func item(_ id: String) -> AgendaItem? {
211 let parts = id.split(separator: ":")
212 guard parts.count == 2, let index = Int(parts[1]) else { return nil }
213 let items = parts[0] == "list" ? agenda.list : agenda.days.first { "\($0.day)" == parts[0] }?.items ?? []
214 return index < items.count ? items[index] : nil
215 }
216
217 private func jump(_ id: String) {
218 guard let item = item(id), let path = item.path, let offset = item.markerOffset ?? item.headingOffset else { return }
219 commands.jump(path: path, offset: offset)
220 openWindow(id: "main")
221 }
222
223 // MARK: - Commands
224
225 private func handle(_ press: KeyPress) -> KeyPress.Result {
226 let control = press.modifiers.contains(.control)
227 if prefix {
228 prefix = false
229 switch (control, press.characters) {
230 case (true, "\u{13}"), (true, "s"): run(SetPlanning(deadline: false))
231 case (true, "\u{04}"), (true, "d"): run(SetPlanning(deadline: true))
232 case (true, "\u{11}"), (true, "q"): run(SetTags())
233 case (true, "\u{14}"), (true, "t"): run(TodoCycle())
234 default: message = "C-c \(press.characters) is undefined"
235 }
236 return .handled
237 }
238 if control, press.characters == "c" || press.characters == "\u{03}" {
239 prefix = true
240 message = "C-c-"
241 return .handled
242 }
243 if press.key == .return, let selection {
244 jump(selection)
245 return .handled
246 }
247 if press.modifiers == .shift, press.key == .rightArrow || press.key == .leftArrow {
248 run(ShiftTimestampDay(later: press.key == .rightArrow), atMarker: true)
249 return .handled
250 }
251 guard press.modifiers.subtracting(.shift).isEmpty else { return .ignored }
252 switch press.characters {
253 case "f" where isAgenda: agenda.shift(forward: true)
254 case "b" where isAgenda: agenda.shift(forward: false)
255 case "." where isAgenda: agenda.showToday()
256 case "g", "r":
257 loadViews()
258 tick += 1
259 case "t": run(TodoCycle())
260 case "+": run(PriorityUp())
261 case "-": run(PriorityDown())
262 case ":": run(SetTags())
263 default: return .ignored
264 }
265 return .handled
266 }
267
268 /// Runs `command` on the selected entry, at its heading or, with `atMarker`, at the
269 /// timestamp the entry is listed for.
270 private func run(_ command: any OrgCommand, atMarker: Bool = false, answers: [String: String] = [:], itemID: String? = nil) {
271 guard let id = itemID ?? selection, let item = item(id), let path = item.path, let start = item.headingOffset else {
272 message = "No entry selected"
273 return
274 }
275 if atMarker, ![.deadline, .upcomingDeadline, .scheduled, .pastScheduled, .timestamp].contains(item.kind) {
276 message = "Only dated entries can move"
277 return
278 }
279 let offset = atMarker ? (item.markerOffset ?? start) : start
280 let step = session.perform(command, path: path, at: offset, expect: item.headingLine.map { (start, $0) }, answers: answers)
281 switch step {
282 case .prompt(let request):
283 promptText = request.initial
284 prompt = PendingPrompt(prompt: request, command: command, atMarker: atMarker, answers: answers, itemID: id)
285 case .failed(let text):
286 message = text
287 tick += 1
288 case .commit:
289 message = nil
290 tick += 1
291 }
292 }
293
294 private func answerPrompt() {
295 guard let pending = prompt else { return }
296 prompt = nil
297 var answers = pending.answers
298 answers[pending.prompt.key] = promptText
299 run(pending.command, atMarker: pending.atMarker, answers: answers, itemID: pending.itemID)
300 }
301}
302
303struct AgendaRow: View {
304 let item: AgendaItem
305
306 var body: some View {
307 switch item.kind {
308 case .timeGrid:
309 HStack(spacing: 8) {
310 Text(Self.trim(item.time))
311 .monospacedDigit()
312 .frame(width: 140, alignment: .trailing)
313 VStack { Divider() }
314 }
315 .font(.caption)
316 .foregroundStyle(.tertiary)
317 case .currentTime:
318 HStack(spacing: 8) {
319 Text("now " + Self.trim(item.time))
320 .monospacedDigit()
321 .frame(width: 140, alignment: .trailing)
322 Rectangle().fill(Color.accentColor).frame(height: 1)
323 }
324 .font(.caption)
325 .foregroundStyle(Color.accentColor)
326 default:
327 HStack(spacing: 8) {
328 Text(item.category)
329 .lineLimit(1)
330 .foregroundStyle(.secondary)
331 .frame(width: 80, alignment: .leading)
332 if item.kind != .todo, item.kind != .tagsMatch {
333 Text(Self.trim(item.time))
334 .monospacedDigit()
335 .frame(width: 80, alignment: .leading)
336 }
337 if !item.extra.isEmpty {
338 Text(item.extra.trimmingCharacters(in: .whitespaces))
339 .monospacedDigit()
340 .foregroundStyle(leaderColor)
341 }
342 title
343 .lineLimit(1)
344 Spacer(minLength: 8)
345 if !item.tags.isEmpty {
346 Text(":" + item.tags.joined(separator: ":") + ":")
347 .font(.caption)
348 .foregroundStyle(.secondary)
349 }
350 }
351 }
352 }
353
354 static func trim(_ time: String) -> String {
355 time.trimmingCharacters(in: CharacterSet(charactersIn: " ┄."))
356 }
357
358 private var leaderColor: Color {
359 switch item.kind {
360 case .deadline: .red
361 case .upcomingDeadline: .orange
362 case .pastScheduled: .brown
363 default: .secondary
364 }
365 }
366
367 /// The TODO keyword colored as in the editor.
368 private var title: Text {
369 let text = item.text.trimmingCharacters(in: .whitespaces)
370 guard let todo = item.todo, text.hasPrefix(todo + " ") else { return Text(text) }
371 let rest = String(text.dropFirst(todo.count))
372 return Text(todo).foregroundColor(item.isDone ? .green : .red).bold() + Text(rest).foregroundColor(item.isDone ? .secondary : .primary)
373 }
374}