Sources/Orgstar/BoardView.swift
332 lines · 15812 bytes
1import OrgApp
2import OrgCore
3import OrgPresentation
4import SwiftUI
5import UniformTypeIdentifiers
6
7/// Entries of the agenda files as a sortable table with property columns, or as a kanban
8/// board by TODO keyword. Dragging a card to a column sets its keyword; edits go through the
9/// open buffer or the file.
10struct BoardView: View {
11 let workspace: WorkspaceModel
12 let session: DocumentSession
13 let commands: AppCommands
14 @State private var agenda: AgendaModel
15 @State private var entries: [BoardEntry] = []
16 @State private var keywords: [String] = []
17 @State private var selection: Set<String> = []
18 @State private var sortOrder = [KeyPathComparator(\BoardRow.todoOrder), KeyPathComparator(\BoardRow.title)]
19 @State private var message: String?
20 @State private var tick = 0
21 /// Whether the first load has finished, so an empty board says so.
22 @State private var loaded = false
23 /// The kanban card the arrow keys move from.
24 @State private var current: String?
25 @FocusState private var boardFocused: Bool
26 @AppStorage("boardKanban") private var kanban = false
27 @AppStorage("boardMatch") private var match = ""
28 @AppStorage("boardColumns") private var columnText = "EFFORT"
29 @AppStorage("agendaSubfolders") private var includeSubfolders = false
30 @Environment(\.openWindow) private var openWindow
31 @Environment(\.orgTheme) private var theme
32 @Environment(\.colorScheme) private var colorScheme
33 @Environment(\.colorSchemeContrast) private var contrast
34
35 init(workspace: WorkspaceModel, session: DocumentSession, commands: AppCommands) {
36 self.workspace = workspace
37 self.session = session
38 self.commands = commands
39 _agenda = State(initialValue: AgendaModel(workspace: workspace))
40 }
41
42 private var propertyColumns: [String] {
43 columnText.split(separator: ",").map { $0.trimmingCharacters(in: .whitespaces).uppercased() }.filter { !$0.isEmpty }
44 }
45
46 private var rows: [BoardRow] {
47 entries.map { BoardRow(entry: $0, todoOrder: $0.todo.flatMap { keywords.firstIndex(of: $0) } ?? Int.max) }.sorted(using: sortOrder)
48 }
49
50 private struct RefreshKey: Hashable {
51 var match: String
52 var subfolders: Bool
53 var files: Int
54 var changed: Int?
55 var edits: Int
56 var path: String?
57 var tick: Int
58 }
59
60 var body: some View {
61 Group {
62 if kanban { board } else { table }
63 }
64 .overlay {
65 if loaded, entries.isEmpty {
66 ContentUnavailableView(
67 "No entries", systemImage: "rectangle.split.3x1",
68 description: Text(match.isEmpty ? "Headings with a TODO keyword in the agenda files show here." : "Nothing in the agenda files matches this.")
69 )
70 }
71 }
72 .safeAreaInset(edge: .bottom, spacing: 0) {
73 if let message {
74 Text(message).font(.callout).frame(maxWidth: .infinity, alignment: .leading).padding(.horizontal, 12).padding(.vertical, 6).background(.bar)
75 }
76 }
77 .toolbar {
78 ToolbarItemGroup(placement: .navigation) {
79 Picker("View", selection: $kanban) {
80 Label("Table", systemImage: "tablecells").tag(false)
81 Label("Kanban", systemImage: "rectangle.split.3x1").tag(true)
82 }
83 .pickerStyle(.segmented)
84 TextField("Match: +work/!TODO", text: $match)
85 .frame(minWidth: 200)
86 if !kanban {
87 TextField("Property columns", text: $columnText)
88 .frame(minWidth: 140)
89 .help("Property names to show as columns, separated by commas")
90 }
91 }
92 }
93 .navigationTitle(kanban ? "Kanban" : "Entries")
94 .task(id: RefreshKey(match: match, subfolders: includeSubfolders, files: workspace.files.count, changed: workspace.changedFile?.version, edits: session.editVersion, path: session.path, tick: tick)) {
95 agenda.includeSubfolders = includeSubfolders
96 agenda.excludeArchives = OrgPreferences.agendaExcludeArchives()
97 agenda.agendaFiles = OrgPreferences.agendaFiles()
98 let open = session.openTexts
99 let result = await agenda.board(open: open, match: match)
100 entries = result.entries
101 keywords = result.keywords
102 loaded = true
103 }
104 }
105
106 // MARK: - Table
107
108 private var table: some View {
109 Table(rows, selection: $selection, sortOrder: $sortOrder) {
110 TableColumn("TODO", value: \.todoOrder) { row in
111 Text(row.entry.todo ?? "").foregroundStyle(keywordColor(row.entry.todo ?? "", done: row.entry.isDone)).bold()
112 }
113 .width(min: 50, ideal: 60, max: 90)
114 TableColumn("P", value: \.priority) { row in Text(row.priority) }
115 .width(min: 20, ideal: 24, max: 40)
116 TableColumn("Title", value: \.title) { row in Text(row.title).lineLimit(1) }
117 .width(min: 160, ideal: 320)
118 TableColumn("Tags", value: \.tags) { row in Text(row.tags).foregroundStyle(.secondary).lineLimit(1) }
119 .width(min: 60, ideal: 120)
120 TableColumn("Scheduled", value: \.scheduled) { row in Text(row.scheduled).monospacedDigit() }
121 .width(min: 80, ideal: 130)
122 TableColumn("Deadline", value: \.deadline) { row in Text(row.deadline).monospacedDigit() }
123 .width(min: 80, ideal: 130)
124 TableColumnForEach(propertyColumns, id: \.self) { key in
125 TableColumn(key.capitalized) { (row: BoardRow) in Text(row.entry.properties[key] ?? "") }
126 .width(min: 50, ideal: 80)
127 }
128 TableColumn("File", value: \.file) { row in Text(row.file).foregroundStyle(.secondary).lineLimit(1) }
129 .width(min: 60, ideal: 120)
130 }
131 .contextMenu(forSelectionType: String.self) { ids in
132 if let entry = entries.first(where: { ids.contains($0.id) }) {
133 Menu("Set TODO") {
134 ForEach(keywords, id: \.self) { keyword in Button(keyword) { setTodo(entry, keyword) } }
135 Divider()
136 Button(String(localized: "none.state", defaultValue: "None", comment: "No TODO state")) { setTodo(entry, nil) }
137 }
138 Button("Set Property…") { askProperty(entry) }
139 Button("Open") { jump(entry) }
140 }
141 } primaryAction: { ids in
142 if let entry = entries.first(where: { ids.contains($0.id) }) { jump(entry) }
143 }
144 }
145
146 // MARK: - Kanban
147
148 private var board: some View {
149 ScrollViewReader { proxy in
150 ScrollView(.horizontal) {
151 HStack(alignment: .top, spacing: 12) {
152 ForEach(keywords, id: \.self) { keyword in
153 column(keyword)
154 }
155 }
156 .padding(12)
157 }
158 .onChange(of: current) {
159 if let current { proxy.scrollTo(current) }
160 }
161 }
162 .background(theme.color("agenda-background", in: colorScheme) ?? .clear)
163 .focusable()
164 .focused($boardFocused)
165 .focusEffectDisabled()
166 .onKeyPress(phases: .down) { press in handle(press) }
167 }
168
169 /// The arrow keys move between cards, Shift-Left and Shift-Right move the card to the
170 /// column before or after, Return opens it.
171 private func handle(_ press: KeyPress) -> KeyPress.Result {
172 let columns = keywords.map { keyword in entries.filter { $0.todo == keyword } }
173 let arrows: [KeyEquivalent] = [.upArrow, .downArrow, .leftArrow, .rightArrow]
174 guard let c = columns.firstIndex(where: { $0.contains { $0.id == current } }),
175 let r = columns[c].firstIndex(where: { $0.id == current }) else {
176 guard arrows.contains(press.key), press.modifiers.isEmpty, let first = columns.lazy.compactMap(\.first).first else { return .ignored }
177 current = first.id
178 return .handled
179 }
180 let entry = columns[c][r]
181 let step = press.key == .leftArrow ? -1 : 1
182 if press.key == .return, press.modifiers.isEmpty {
183 jump(entry)
184 } else if press.modifiers == .shift, press.key == .leftArrow || press.key == .rightArrow {
185 if keywords.indices.contains(c + step) { setTodo(entry, keywords[c + step]) }
186 } else if press.modifiers.isEmpty, press.key == .upArrow || press.key == .downArrow {
187 current = columns[c][min(max(r + (press.key == .upArrow ? -1 : 1), 0), columns[c].count - 1)].id
188 } else if press.modifiers.isEmpty, press.key == .leftArrow || press.key == .rightArrow {
189 // The nearest column with cards, at the same height.
190 var k = c + step
191 while columns.indices.contains(k), columns[k].isEmpty { k += step }
192 if columns.indices.contains(k) { current = columns[k][min(r, columns[k].count - 1)].id }
193 } else {
194 return .ignored
195 }
196 return .handled
197 }
198
199 private func column(_ keyword: String) -> some View {
200 let cards = entries.filter { $0.todo == keyword }
201 return VStack(alignment: .leading, spacing: 8) {
202 HStack {
203 Text(keyword).font(.headline).foregroundStyle(keywordColor(keyword, done: cards.first?.isDone ?? false))
204 Text("\(cards.count)").foregroundStyle(.secondary)
205 }
206 ScrollView {
207 VStack(alignment: .leading, spacing: 6) {
208 ForEach(cards) { entry in
209 card(entry)
210 .id(entry.id)
211 .draggable(entry.id)
212 .onTapGesture(count: 2) { jump(entry) }
213 .simultaneousGesture(TapGesture().onEnded {
214 current = entry.id
215 boardFocused = true
216 })
217 .accessibilityElement(children: .combine)
218 .accessibilityAddTraits(current == entry.id ? [.isButton, .isSelected] : .isButton)
219 .accessibilityAction { jump(entry) }
220 .accessibilityActions {
221 // Dragging between columns, for VoiceOver.
222 ForEach(keywords.filter { $0 != keyword }, id: \.self) { other in
223 Button("Move to \(other)") { setTodo(entry, other) }
224 }
225 }
226 }
227 }
228 }
229 }
230 .frame(width: 240, alignment: .topLeading)
231 .frame(maxHeight: .infinity, alignment: .top)
232 .padding(8)
233 .background(RoundedRectangle(cornerRadius: 8).fill(Color.secondary.opacity(0.08)))
234 .dropDestination(for: String.self) { ids, _ in
235 for id in ids {
236 if let entry = entries.first(where: { $0.id == id }), entry.todo != keyword { setTodo(entry, keyword) }
237 }
238 return true
239 }
240 }
241
242 private func card(_ entry: BoardEntry) -> some View {
243 let selected = current == entry.id
244 return VStack(alignment: .leading, spacing: 4) {
245 Text((entry.priority.map { "[#\($0)] " } ?? "") + entry.title).lineLimit(3)
246 .foregroundStyle(theme.color("foreground") ?? .primary)
247 HStack(spacing: 6) {
248 Text(entry.category).font(.caption).foregroundStyle(secondary("agenda-category"))
249 if !entry.tags.isEmpty {
250 Text(entry.tags.joined(separator: " ")).font(.caption).foregroundStyle(secondary("tags")).lineLimit(1)
251 }
252 }
253 if let deadline = entry.deadline {
254 // As the agenda colours a deadline: overdue when past, else due soon.
255 let overdue = deadline.prefix(10) < Date().formatted(Date.ISO8601FormatStyle(timeZone: .current).year().month().day())
256 Text("Deadline \(deadline)").font(.caption).foregroundStyle(theme.color(overdue ? "agenda-overdue" : "agenda-due-soon") ?? .red)
257 } else if let scheduled = entry.scheduled {
258 Text("Scheduled \(scheduled)").font(.caption).foregroundStyle(secondary("agenda-time"))
259 }
260 }
261 .padding(8)
262 .frame(maxWidth: .infinity, alignment: .leading)
263 .background(RoundedRectangle(cornerRadius: 6).fill(theme.color("block-background") ?? Color(nsColor: .controlBackgroundColor)))
264 .overlay {
265 // Increase Contrast: a full outline on every card and a heavier one on the selected card.
266 if selected {
267 RoundedRectangle(cornerRadius: 6).strokeBorder(theme.color("accent") ?? .accentColor, lineWidth: contrast == .increased ? 3 : 2)
268 } else if contrast == .increased {
269 RoundedRectangle(cornerRadius: 6).strokeBorder(Color.primary.opacity(0.6), lineWidth: 1)
270 }
271 }
272 }
273
274 /// A secondary text colour from the theme; the foreground under Increase Contrast.
275 private func secondary(_ key: String) -> Color {
276 contrast == .increased ? theme.color("foreground") ?? .primary : theme.color(key) ?? .secondary
277 }
278
279 /// A keyword's colour as the agenda draws it: its own, else its class's (NEXT, WAIT, …).
280 private func keywordColor(_ keyword: String, done: Bool) -> Color {
281 theme.dynamic(done ? .systemGreen : .systemRed) { [theme] in theme.todoColor(keyword, isDone: done, dark: $0) }
282 }
283
284 // MARK: - Editing
285
286 private func perform(_ command: any OrgCommand, on entry: BoardEntry, answers: [String: String] = [:]) {
287 switch session.perform(command, path: entry.path, at: entry.headingOffset, expect: (entry.headingOffset, entry.headingLine), answers: answers) {
288 case .failed(let text): message = text
289 case .prompt(let prompt):
290 // A state note: asked in the main window's echo area.
291 commands.ask(prompt) { answer in
292 guard let answer else { return }
293 perform(command, on: entry, answers: answers.merging([prompt.key: answer]) { $1 })
294 }
295 openWindow(id: "main")
296 default: message = nil
297 }
298 tick += 1
299 }
300
301 private func setTodo(_ entry: BoardEntry, _ keyword: String?) {
302 perform(SetTodo(keyword: keyword), on: entry)
303 }
304
305 private func askProperty(_ entry: BoardEntry) {
306 commands.ask(Prompt(key: "property", message: "Property (NAME value):")) { answer in
307 guard let answer, let space = answer.firstIndex(of: " ") else { return }
308 let key = String(answer[..<space])
309 let value = String(answer[answer.index(after: space)...]).trimmingCharacters(in: .whitespaces)
310 perform(SetProperty(key: key, value: value), on: entry)
311 }
312 openWindow(id: "main")
313 }
314
315 private func jump(_ entry: BoardEntry) {
316 commands.jump(path: entry.path, offset: entry.headingOffset)
317 openWindow(id: "main")
318 }
319}
320
321/// A table row with sortable values.
322struct BoardRow: Identifiable {
323 let entry: BoardEntry
324 let todoOrder: Int
325 var id: String { entry.id }
326 var title: String { entry.title }
327 var priority: String { entry.priority ?? "" }
328 var tags: String { entry.tags.joined(separator: " ") }
329 var scheduled: String { entry.scheduled ?? "" }
330 var deadline: String { entry.deadline ?? "" }
331 var file: String { (entry.path as NSString).lastPathComponent }
332}