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