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