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