Sources/Orgstar/AgendaView.swift
190 lines · 7455 bytes
1import OrgApp
2import OrgCore
3import SwiftUI
4
5/// The agenda window: `org-agenda-list` over the agenda files. Return or a double click jumps
6/// to the entry in the main window; f/b move a span, `.` returns to today, g refreshes.
7struct AgendaView: View {
8 let workspace: WorkspaceModel
9 let session: DocumentSession
10 let commands: AppCommands
11 @State private var agenda: AgendaModel
12 @State private var selection: String?
13 @State private var tick = 0
14 @AppStorage("agendaSpan") private var span = 10
15 @AppStorage("agendaStartOffset") private var startOffset = -3
16 @AppStorage("agendaSubfolders") private var includeSubfolders = false
17 @Environment(\.openWindow) private var openWindow
18
19 init(workspace: WorkspaceModel, session: DocumentSession, commands: AppCommands) {
20 self.workspace = workspace
21 self.session = session
22 self.commands = commands
23 _agenda = State(initialValue: AgendaModel(workspace: workspace))
24 }
25
26 private struct RefreshKey: Hashable {
27 var start: Int?
28 var span: Int
29 var startOffset: Int
30 var includeSubfolders: Bool
31 var files: Int
32 var changed: Int?
33 var edits: Int
34 var path: String?
35 var tick: Int
36 }
37
38 private var refreshKey: RefreshKey {
39 RefreshKey(
40 start: agenda.start, span: span, startOffset: startOffset, includeSubfolders: includeSubfolders,
41 files: workspace.files.count, changed: workspace.changedFile?.version, edits: session.editVersion,
42 path: session.path, tick: tick
43 )
44 }
45
46 var body: some View {
47 List(selection: $selection) {
48 ForEach(agenda.days, id: \.day) { day in
49 Section {
50 ForEach(Array(day.items.enumerated()), id: \.offset) { index, item in
51 AgendaRow(item: item)
52 .tag(Self.id(day, index))
53 .selectionDisabled(item.path == nil)
54 }
55 } header: {
56 Text(day.header)
57 .font(.headline)
58 .foregroundStyle(day.isToday ? Color.accentColor : .primary)
59 }
60 }
61 }
62 .contextMenu(forSelectionType: String.self) { _ in
63 } primaryAction: { ids in
64 if let id = ids.first { jump(id) }
65 }
66 .onKeyPress(.return) {
67 guard let selection else { return .ignored }
68 jump(selection)
69 return .handled
70 }
71 .onKeyPress(characters: CharacterSet(charactersIn: "fb.gr")) { press in
72 switch press.characters {
73 case "f": agenda.shift(forward: true)
74 case "b": agenda.shift(forward: false)
75 case ".": agenda.showToday()
76 default: tick += 1
77 }
78 return .handled
79 }
80 .toolbar {
81 ToolbarItemGroup {
82 if agenda.isComputing { ProgressView().controlSize(.small) }
83 Button("Earlier", systemImage: "chevron.left") { agenda.shift(forward: false) }
84 .help("Previous \(span) days (b)")
85 Button("Today") { agenda.showToday() }
86 .help("Back to today (.)")
87 Button("Later", systemImage: "chevron.right") { agenda.shift(forward: true) }
88 .help("Next \(span) days (f)")
89 }
90 }
91 .overlay {
92 if agenda.files.isEmpty {
93 ContentUnavailableView("No agenda files", systemImage: "calendar", description: Text("The agenda reads the org files at the top of each folder you add."))
94 }
95 }
96 .navigationTitle("Agenda")
97 .task(id: refreshKey) {
98 agenda.span = span
99 agenda.startOffset = startOffset
100 agenda.includeSubfolders = includeSubfolders
101 let open = session.path.flatMap { path in session.document.map { (path, $0.text) } }
102 await agenda.refresh(open: open)
103 }
104 .task {
105 // The time grid's "now" line and the day itself move on.
106 while !Task.isCancelled {
107 try? await Task.sleep(for: .seconds(60))
108 tick += 1
109 }
110 }
111 }
112
113 private static func id(_ day: AgendaDay, _ index: Int) -> String { "\(day.day):\(index)" }
114
115 private func jump(_ id: String) {
116 let parts = id.split(separator: ":").compactMap { Int($0) }
117 guard parts.count == 2, let day = agenda.days.first(where: { $0.day == parts[0] }), parts[1] < day.items.count else { return }
118 let item = day.items[parts[1]]
119 guard let path = item.path, let offset = item.markerOffset ?? item.headingOffset else { return }
120 commands.jump(path: path, offset: offset)
121 openWindow(id: "main")
122 }
123}
124
125struct AgendaRow: View {
126 let item: AgendaItem
127
128 var body: some View {
129 switch item.kind {
130 case .timeGrid:
131 HStack(spacing: 8) {
132 Text(item.time.trimmingCharacters(in: CharacterSet(charactersIn: " ┄.")))
133 .monospacedDigit()
134 .frame(width: 140, alignment: .trailing)
135 VStack { Divider() }
136 }
137 .font(.caption)
138 .foregroundStyle(.tertiary)
139 case .currentTime:
140 HStack(spacing: 8) {
141 Text("now " + item.time.trimmingCharacters(in: CharacterSet(charactersIn: " ┄.")))
142 .monospacedDigit()
143 .frame(width: 140, alignment: .trailing)
144 Rectangle().fill(Color.accentColor).frame(height: 1)
145 }
146 .font(.caption)
147 .foregroundStyle(Color.accentColor)
148 default:
149 HStack(spacing: 8) {
150 Text(item.category)
151 .lineLimit(1)
152 .foregroundStyle(.secondary)
153 .frame(width: 80, alignment: .leading)
154 Text(item.time.trimmingCharacters(in: CharacterSet(charactersIn: " ┄.")))
155 .monospacedDigit()
156 .frame(width: 80, alignment: .leading)
157 if !item.extra.isEmpty {
158 Text(item.extra.trimmingCharacters(in: .whitespaces))
159 .monospacedDigit()
160 .foregroundStyle(leaderColor)
161 }
162 title
163 .lineLimit(1)
164 Spacer(minLength: 8)
165 if !item.tags.isEmpty {
166 Text(":" + item.tags.joined(separator: ":") + ":")
167 .font(.caption)
168 .foregroundStyle(.secondary)
169 }
170 }
171 }
172 }
173
174 private var leaderColor: Color {
175 switch item.kind {
176 case .deadline: .red
177 case .upcomingDeadline: .orange
178 case .pastScheduled: .brown
179 default: .secondary
180 }
181 }
182
183 /// The TODO keyword colored as in the editor.
184 private var title: Text {
185 guard let todo = item.todo, item.text.hasPrefix(todo + " ") else { return Text(item.text.trimmingCharacters(in: .whitespaces)) }
186 let text = item.text.trimmingCharacters(in: .whitespaces)
187 let rest = String(text.dropFirst(todo.count))
188 return Text(todo).foregroundColor(item.isDone ? .green : .red).bold() + Text(rest).foregroundColor(item.isDone ? .secondary : .primary)
189 }
190}