Sources/OrgstarMobile/AgendaScreen.swift
378 lines · 16562 bytes
1#if os(iOS)
2import OrgApp
3import OrgCore
4import OrgDocument
5import SwiftUI
6
7/// The agenda over the workspace's agenda files: the day/week view, the TODO list, tag and
8/// property matches and the views in `views.toml`, with Org's filters and the agenda's
9/// actions on each entry.
10struct AgendaScreen: View {
11 let workspace: WorkspaceModel
12 let session: DocumentSession
13 @Bindable var agenda: AgendaModel
14 let scheduler: ReminderScheduler
15 @State private var message: String?
16 @Environment(ClockModel.self) private var clock
17 @State private var tick = 0
18 @State private var views = AgendaViewLoader.builtIn
19 @State private var viewName = "Agenda"
20 @State private var filter = AgendaFilter()
21 @State private var showingFilter = false
22 @State private var asking: Asking?
23 @State private var prompt: EditorScreen.PromptRequest?
24 @State private var refiling: AgendaItem?
25 @State private var archiving: AgendaItem?
26
27 /// A match typed for the tag and property view.
28 private enum Asking: Identifiable {
29 case match
30 var id: Int { 0 }
31 }
32
33 private struct Key: Equatable {
34 var files: Int
35 var changed: Int?
36 var edits: Int
37 var tick: Int
38 var mode: AgendaMode
39 var start: Int?
40 var span: Int
41 var startOffset: Int
42 var subfolders: Bool
43 }
44
45 var body: some View {
46 List {
47 if case .agenda = agenda.mode {
48 ForEach(agenda.days, id: \.day) { day in
49 Section {
50 let items = day.items.filter(\.isEntry).filter(filter.keeps)
51 ForEach(items.indices, id: \.self) { i in row(items[i]) }
52 } header: {
53 Text(day.header.split(separator: " ", omittingEmptySubsequences: true).prefix(4).joined(separator: " "))
54 .foregroundStyle(day.isToday ? Color.accentColor : .secondary)
55 }
56 }
57 } else {
58 let items = agenda.list.filter(filter.keeps)
59 if items.isEmpty, !agenda.isComputing { Text("No entries").foregroundStyle(.secondary) }
60 ForEach(items.indices, id: \.self) { i in row(items[i]) }
61 }
62 if let reminderStatus {
63 Section { } footer: { Text(reminderStatus) }
64 }
65 }
66 .listStyle(.insetGrouped)
67 .navigationTitle(viewName)
68 .overlay {
69 if workspace.rootPaths.isEmpty {
70 ContentUnavailableView("No folders", systemImage: "folder", description: Text("Add a folder of org files under Folders."))
71 }
72 }
73 .safeAreaInset(edge: .bottom) {
74 if let status = message ?? (filter.isEmpty ? nil : "Filter: " + filter.description) {
75 Text(status).font(.callout).padding(8).frame(maxWidth: .infinity).background(.bar)
76 .onTapGesture { message = nil }
77 }
78 }
79 .toolbar {
80 ToolbarItem(placement: .topBarLeading) {
81 Menu {
82 ForEach(views) { definition in
83 Button(definition.name) { show(definition) }
84 }
85 Button("Tags and Properties…") { asking = .match }
86 if case .agenda = agenda.mode {
87 Divider()
88 Button("Today", systemImage: "calendar.circle") { agenda.showToday() }
89 Button("Earlier", systemImage: "chevron.left") { agenda.shift(forward: false) }
90 Button("Later", systemImage: "chevron.right") { agenda.shift(forward: true) }
91 }
92 } label: {
93 Label("Views", systemImage: "calendar")
94 }
95 }
96 ToolbarItem(placement: .topBarLeading) {
97 Button("Filter", systemImage: filter.isEmpty ? "line.3.horizontal.decrease.circle" : "line.3.horizontal.decrease.circle.fill") {
98 showingFilter = true
99 }
100 }
101 }
102 .sheet(isPresented: $showingFilter) {
103 FilterSheet(filter: $filter, items: shownItems)
104 }
105 .sheet(item: $asking) { _ in
106 PromptSheet(prompt: Prompt(key: "match", message: "Match: tags and properties, as +work-home or TODO=\"WAIT\"")) { answer in
107 asking = nil
108 guard let answer, !answer.isEmpty else { return }
109 agenda.mode = .match(answer, todoOnly: false)
110 viewName = answer
111 }
112 }
113 .sheet(item: $prompt) { request in
114 PromptSheet(prompt: request.prompt) { answer in
115 prompt = nil
116 request.reply(answer)
117 }
118 }
119 .sheet(item: $refiling) { item in
120 RefileSheet(targets: workspace.refileTargets(openPath: session.path, document: session.document)) { target in
121 refiling = nil
122 if let target { refile(item, to: target) }
123 }
124 }
125 .confirmationDialog("Archive this entry?", isPresented: Binding { archiving != nil } set: { if !$0 { archiving = nil } }, titleVisibility: .visible) {
126 Button("Archive", role: .destructive) {
127 if let item = archiving { archive(item) }
128 archiving = nil
129 }
130 } message: {
131 Text(archiving?.text ?? "")
132 }
133 .refreshable {
134 await workspace.refresh()
135 await agenda.refresh(open: session.openTexts)
136 }
137 .task {
138 let loaded = AgendaViewLoader.load()
139 views = loaded.views
140 if let problem = loaded.problems.first { message = problem }
141 }
142 .task(id: Key(files: workspace.files.count, changed: workspace.changedFile?.version, edits: session.editVersion, tick: tick,
143 mode: agenda.mode, start: agenda.start, span: agenda.span, startOffset: agenda.startOffset,
144 subfolders: agenda.includeSubfolders)) {
145 await agenda.refresh(open: session.openTexts)
146 }
147 }
148
149 private var shownItems: [AgendaItem] {
150 if case .agenda = agenda.mode { return agenda.days.flatMap(\.items).filter(\.isEntry) }
151 return agenda.list
152 }
153
154 private func show(_ definition: AgendaViewDefinition) {
155 viewName = definition.name
156 agenda.mode = definition.mode
157 }
158
159 /// How far ahead notifications are set, as the design asks the agenda to show: iOS keeps
160 /// at most 64, and sets no more while the app isn't opened.
161 private var reminderStatus: String? {
162 guard OrgPreferences.reminders() else { return nil }
163 if !scheduler.isAuthorized { return "Notifications are off for Orgstar in Settings." }
164 guard let through = scheduler.scheduledThrough else { return nil }
165 return "Reminders are set through " + through.formatted(.dateTime.weekday(.abbreviated).day().month(.abbreviated).hour().minute())
166 + ". Open Orgstar to set later ones."
167 }
168
169 // MARK: - Rows
170
171 private func row(_ item: AgendaItem) -> some View {
172 Group {
173 if let path = item.path, let offset = item.headingOffset {
174 NavigationLink(value: ReaderRoute.offset(path, offset)) { entry(item) }
175 } else {
176 entry(item)
177 }
178 }
179 .swipeActions(edge: .trailing) {
180 if item.todo != nil, !item.isDone, doneKeyword(for: item) != nil {
181 Button("Done", systemImage: "checkmark") { markDone(item) }.tint(.green)
182 }
183 }
184 .contextMenu {
185 if item.path != nil {
186 Button("TODO State…", systemImage: "checkmark.circle") { run("org.todo.cycle", on: item) }
187 Button("Schedule…", systemImage: "calendar") { run("org.schedule", on: item) }
188 Button("Deadline…", systemImage: "calendar.badge.exclamationmark") { run("org.deadline", on: item) }
189 Button("Tags…", systemImage: "tag") { run("org.tags.set", on: item) }
190 Button("Priority…", systemImage: "exclamationmark.circle") { run("org.priority.set", on: item) }
191 Button("Clock In", systemImage: "stopwatch") {
192 if let (path, offset) = locate(item) { message = clock.clockIn(session, path: path, at: offset) }
193 }
194 Divider()
195 Button("Refile…", systemImage: "arrow.turn.down.right") { refiling = item }
196 Button("Archive…", systemImage: "archivebox") { archiving = item }
197 }
198 }
199 }
200
201 private func entry(_ item: AgendaItem) -> some View {
202 VStack(alignment: .leading, spacing: 2) {
203 HStack(alignment: .firstTextBaseline, spacing: 6) {
204 if let time = item.time.firstMatch(of: /[0-9]{1,2}:[0-9]{2}(-[0-9]{1,2}:[0-9]{2})?/) {
205 Text(time.output.0).font(.callout.monospacedDigit()).foregroundStyle(.secondary)
206 }
207 Text(item.text).strikethrough(item.isDone)
208 }
209 HStack(spacing: 6) {
210 Text(item.category)
211 let extra = item.extra.split(whereSeparator: \.isWhitespace).joined(separator: " ")
212 if !extra.isEmpty { Text(extra) }
213 if !item.tags.isEmpty { Text(item.tags.map { ":" + $0 }.joined() + ":") }
214 }
215 .font(.caption)
216 .foregroundStyle(.secondary)
217 }
218 }
219
220 // MARK: - Actions
221
222 /// The heading of `item` now, found again by its line in case the file changed.
223 private func locate(_ item: AgendaItem) -> (path: String, offset: Int)? {
224 guard let path = item.path, let line = item.headingLine, let near = item.headingOffset,
225 let offset = session.locateHeading(path: path, line: line, near: near) else {
226 message = "The entry changed; the agenda has been refreshed."
227 tick += 1
228 return nil
229 }
230 return (path, offset)
231 }
232
233 /// Runs a command at the entry's heading, asking what it asks.
234 private func run(_ id: String, on item: AgendaItem, answers: [String: String] = [:]) {
235 guard let command = Commands.command(id) else { return }
236 run(command, on: item, answers: answers)
237 }
238
239 private func run(_ command: any OrgCommand, on item: AgendaItem, answers: [String: String] = [:]) {
240 guard let (path, offset) = locate(item), let line = item.headingLine else { return }
241 switch session.perform(command, path: path, at: offset, expect: (offset, line), answers: answers) {
242 case .prompt(let request):
243 prompt = EditorScreen.PromptRequest(prompt: request) { answer in
244 guard let answer else { return }
245 run(command, on: item, answers: answers.merging([request.key: answer]) { $1 })
246 }
247 case .failed(let text):
248 message = text
249 case .external:
250 message = "\(command.title) needs Emacs, which runs on the Mac."
251 case .commit:
252 message = nil
253 }
254 tick += 1
255 }
256
257 /// The first done keyword of the item's TODO sequence.
258 private func doneKeyword(for item: AgendaItem) -> String? {
259 guard let todo = item.todo, let path = item.path else { return nil }
260 let text = session.openTexts[path] ?? (try? String(contentsOfFile: path, encoding: .utf8)) ?? ""
261 let settings = OrgParser.parse(text).settings
262 return settings.todoSequences.first { ($0.active + $0.done).contains { $0.name == todo } }?.done.first?.name
263 }
264
265 private func markDone(_ item: AgendaItem) {
266 guard let keyword = doneKeyword(for: item) else { return }
267 run(SetTodo(keyword: keyword), on: item)
268 }
269
270 private func refile(_ item: AgendaItem, to target: RefileTarget) {
271 guard let (path, offset) = locate(item) else { return }
272 // Targets in the entry's own file come from its text now.
273 let document = session.openDocuments.first { $0.path == path }?.document
274 ?? FileManager.default.contents(atPath: path).map { DocumentState(bytes: [UInt8]($0)) }
275 guard let current = workspace.refileTargets(openPath: path, document: document).first(where: { $0.label == target.label }) else {
276 message = "Can't find \(target.label) any more."
277 return
278 }
279 message = session.refile(to: current, from: (path, offset))
280 tick += 1
281 }
282
283 private func archive(_ item: AgendaItem) {
284 guard let (path, offset) = locate(item) else { return }
285 message = session.archive(from: (path, offset))
286 tick += 1
287 }
288}
289
290extension AgendaItem: Identifiable {
291 public var id: String { "\(path ?? "")|\(headingOffset ?? -1)|\(kind.rawValue)|\(text)" }
292
293 /// An entry, not a time-grid line.
294 var isEntry: Bool { kind != .timeGrid && kind != .currentTime }
295}
296
297/// Org's agenda filter: tags and categories of the entries shown, kept or left out, or the
298/// filter typed as `/` takes it.
299struct FilterSheet: View {
300 @Binding var filter: AgendaFilter
301 let items: [AgendaItem]
302 @State private var typed = ""
303 @Environment(\.dismiss) private var dismiss
304
305 var body: some View {
306 let tags = Set(items.flatMap(\.tags)).sorted()
307 let categories = Set(items.filter { $0.path != nil }.map(\.category)).sorted()
308 NavigationStack {
309 Form {
310 Section {
311 TextField("+work-home", text: $typed)
312 .autocorrectionDisabled()
313 .textInputAutocapitalization(.never)
314 .onSubmit(apply)
315 } footer: {
316 Text("As Org's / filter: +keep and -drop tags or categories, <0:30 for effort, /regexp/.")
317 }
318 if !tags.isEmpty {
319 Section("Tags") { ForEach(tags, id: \.self) { term($0, in: \.tags) } }
320 }
321 if !categories.isEmpty {
322 Section("Categories") { ForEach(categories, id: \.self) { term($0, in: \.categories) } }
323 }
324 }
325 .navigationTitle("Filter")
326 .navigationBarTitleDisplayMode(.inline)
327 .toolbar {
328 ToolbarItem(placement: .cancellationAction) { Button("Clear") { filter = AgendaFilter(); dismiss() } }
329 ToolbarItem(placement: .confirmationAction) { Button("Done") { apply(); dismiss() } }
330 }
331 }
332 .onAppear { typed = filter.description }
333 }
334
335 /// Keep, leave out, or no filter on `name`.
336 private func term(_ name: String, in list: WritableKeyPath<AgendaFilter, [String]>) -> some View {
337 let state = filter[keyPath: list].contains("+" + name) ? 1 : filter[keyPath: list].contains("-" + name) ? -1 : 0
338 return Button {
339 var terms = filter[keyPath: list].filter { $0.dropFirst() != Substring(name) }
340 if state == 0 { terms.append("+" + name) } else if state == 1 { terms.append("-" + name) }
341 filter[keyPath: list] = terms
342 typed = filter.description
343 } label: {
344 HStack {
345 Text(name).foregroundStyle(.primary)
346 Spacer()
347 Text(state == 1 ? "Keep" : state == -1 ? "Leave out" : "").foregroundStyle(.secondary)
348 }
349 }
350 }
351
352 private func apply() {
353 guard typed != filter.description else { return }
354 let tags = Set(items.flatMap(\.tags))
355 let categories = Set(items.map(\.category))
356 filter = AgendaFilter().parse(typed, tags: tags, categories: categories).filter
357 }
358}
359
360/// Where to refile: the targets `org-refile` offers, searchable.
361struct RefileSheet: View {
362 let targets: [RefileTarget]
363 let choose: (RefileTarget?) -> Void
364 @State private var query = ""
365
366 var body: some View {
367 NavigationStack {
368 List(targets.filter { query.isEmpty || $0.label.localizedCaseInsensitiveContains(query) }, id: \.self) { target in
369 Button(target.label) { choose(target) }.foregroundStyle(.primary)
370 }
371 .searchable(text: $query, placement: .navigationBarDrawer(displayMode: .always))
372 .navigationTitle("Refile to")
373 .navigationBarTitleDisplayMode(.inline)
374 .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Cancel") { choose(nil) } } }
375 }
376 }
377}
378#endif