Sources/Orgstar/BoardView.swift
250 lines · 11057 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 @AppStorage("boardKanban") private var kanban = false
22 @AppStorage("boardMatch") private var match = ""
23 @AppStorage("boardColumns") private var columnText = "EFFORT"
24 @AppStorage("agendaSubfolders") private var includeSubfolders = false
25 @Environment(\.openWindow) private var openWindow
26 @Environment(\.orgTheme) private var theme
27 @Environment(\.colorScheme) private var colorScheme
28
29 init(workspace: WorkspaceModel, session: DocumentSession, commands: AppCommands) {
30 self.workspace = workspace
31 self.session = session
32 self.commands = commands
33 _agenda = State(initialValue: AgendaModel(workspace: workspace))
34 }
35
36 private var propertyColumns: [String] {
37 columnText.split(separator: ",").map { $0.trimmingCharacters(in: .whitespaces).uppercased() }.filter { !$0.isEmpty }
38 }
39
40 private var rows: [BoardRow] {
41 entries.map { BoardRow(entry: $0, todoOrder: $0.todo.flatMap { keywords.firstIndex(of: $0) } ?? Int.max) }.sorted(using: sortOrder)
42 }
43
44 private struct RefreshKey: Hashable {
45 var match: String
46 var subfolders: Bool
47 var files: Int
48 var changed: Int?
49 var edits: Int
50 var path: String?
51 var tick: Int
52 }
53
54 var body: some View {
55 Group {
56 if kanban { board } else { table }
57 }
58 .safeAreaInset(edge: .bottom, spacing: 0) {
59 if let message {
60 Text(message).font(.callout).frame(maxWidth: .infinity, alignment: .leading).padding(.horizontal, 12).padding(.vertical, 6).background(.bar)
61 }
62 }
63 .toolbar {
64 ToolbarItemGroup(placement: .navigation) {
65 Picker("View", selection: $kanban) {
66 Label("Table", systemImage: "tablecells").tag(false)
67 Label("Kanban", systemImage: "rectangle.split.3x1").tag(true)
68 }
69 .pickerStyle(.segmented)
70 TextField("Match: +work/!TODO", text: $match)
71 .frame(minWidth: 200)
72 if !kanban {
73 TextField("Property columns", text: $columnText)
74 .frame(minWidth: 140)
75 .help("Property names to show as columns, separated by commas")
76 }
77 }
78 }
79 .navigationTitle(kanban ? "Kanban" : "Entries")
80 .task(id: RefreshKey(match: match, subfolders: includeSubfolders, files: workspace.files.count, changed: workspace.changedFile?.version, edits: session.editVersion, path: session.path, tick: tick)) {
81 agenda.includeSubfolders = includeSubfolders
82 agenda.agendaFiles = OrgPreferences.agendaFiles()
83 let open = session.openTexts
84 let result = await agenda.board(open: open, match: match)
85 entries = result.entries
86 keywords = result.keywords
87 }
88 }
89
90 // MARK: - Table
91
92 private var table: some View {
93 Table(rows, selection: $selection, sortOrder: $sortOrder) {
94 TableColumn("TODO", value: \.todoOrder) { row in
95 Text(row.entry.todo ?? "").foregroundStyle(theme.keywordColor(row.entry.todo ?? "", done: row.entry.isDone)).bold()
96 }
97 .width(min: 50, ideal: 60, max: 90)
98 TableColumn("P", value: \.priority) { row in Text(row.priority) }
99 .width(min: 20, ideal: 24, max: 40)
100 TableColumn("Title", value: \.title) { row in Text(row.title).lineLimit(1) }
101 .width(min: 160, ideal: 320)
102 TableColumn("Tags", value: \.tags) { row in Text(row.tags).foregroundStyle(.secondary).lineLimit(1) }
103 .width(min: 60, ideal: 120)
104 TableColumn("Scheduled", value: \.scheduled) { row in Text(row.scheduled).monospacedDigit() }
105 .width(min: 80, ideal: 110)
106 TableColumn("Deadline", value: \.deadline) { row in Text(row.deadline).monospacedDigit() }
107 .width(min: 80, ideal: 110)
108 TableColumnForEach(propertyColumns, id: \.self) { key in
109 TableColumn(key.capitalized) { (row: BoardRow) in Text(row.entry.properties[key] ?? "") }
110 .width(min: 50, ideal: 80)
111 }
112 TableColumn("File", value: \.file) { row in Text(row.file).foregroundStyle(.secondary).lineLimit(1) }
113 .width(min: 60, ideal: 120)
114 }
115 .contextMenu(forSelectionType: String.self) { ids in
116 if let entry = entries.first(where: { ids.contains($0.id) }) {
117 Menu("Set TODO") {
118 ForEach(keywords, id: \.self) { keyword in Button(keyword) { setTodo(entry, keyword) } }
119 Divider()
120 Button("None") { setTodo(entry, nil) }
121 }
122 Button("Set Property…") { askProperty(entry) }
123 Button("Open") { jump(entry) }
124 }
125 } primaryAction: { ids in
126 if let entry = entries.first(where: { ids.contains($0.id) }) { jump(entry) }
127 }
128 }
129
130 // MARK: - Kanban
131
132 private var board: some View {
133 ScrollView(.horizontal) {
134 HStack(alignment: .top, spacing: 12) {
135 ForEach(keywords, id: \.self) { keyword in
136 column(keyword)
137 }
138 }
139 .padding(12)
140 }
141 .background(theme.color("agenda-background", in: colorScheme) ?? .clear)
142 }
143
144 private func column(_ keyword: String) -> some View {
145 let cards = entries.filter { $0.todo == keyword }
146 return VStack(alignment: .leading, spacing: 8) {
147 HStack {
148 Text(keyword).font(.headline).foregroundStyle(theme.keywordColor(keyword, done: cards.first?.isDone ?? false))
149 Text("\(cards.count)").foregroundStyle(.secondary)
150 }
151 ScrollView {
152 VStack(alignment: .leading, spacing: 6) {
153 ForEach(cards) { entry in
154 card(entry)
155 .draggable(entry.id)
156 .onTapGesture(count: 2) { jump(entry) }
157 .accessibilityElement(children: .combine)
158 .accessibilityAddTraits(.isButton)
159 .accessibilityAction { jump(entry) }
160 .accessibilityActions {
161 // Dragging between columns, for VoiceOver.
162 ForEach(keywords.filter { $0 != keyword }, id: \.self) { other in
163 Button("Move to \(other)") { setTodo(entry, other) }
164 }
165 }
166 }
167 }
168 }
169 }
170 .frame(width: 240, alignment: .topLeading)
171 .frame(maxHeight: .infinity, alignment: .top)
172 .padding(8)
173 .background(RoundedRectangle(cornerRadius: 8).fill(Color.secondary.opacity(0.08)))
174 .dropDestination(for: String.self) { ids, _ in
175 for id in ids {
176 if let entry = entries.first(where: { $0.id == id }), entry.todo != keyword { setTodo(entry, keyword) }
177 }
178 return true
179 }
180 }
181
182 private func card(_ entry: BoardEntry) -> some View {
183 VStack(alignment: .leading, spacing: 4) {
184 Text((entry.priority.map { "[#\($0)] " } ?? "") + entry.title).lineLimit(3)
185 HStack(spacing: 6) {
186 Text(entry.category).font(.caption).foregroundStyle(.secondary)
187 if !entry.tags.isEmpty {
188 Text(entry.tags.joined(separator: " ")).font(.caption).foregroundStyle(.secondary).lineLimit(1)
189 }
190 }
191 if let deadline = entry.deadline {
192 Text("Deadline \(deadline)").font(.caption).foregroundStyle(.red)
193 } else if let scheduled = entry.scheduled {
194 Text("Scheduled \(scheduled)").font(.caption).foregroundStyle(.secondary)
195 }
196 }
197 .padding(8)
198 .frame(maxWidth: .infinity, alignment: .leading)
199 .background(RoundedRectangle(cornerRadius: 6).fill(Color(nsColor: .controlBackgroundColor)))
200 }
201
202 // MARK: - Editing
203
204 private func perform(_ command: any OrgCommand, on entry: BoardEntry, answers: [String: String] = [:]) {
205 switch session.perform(command, path: entry.path, at: entry.headingOffset, expect: (entry.headingOffset, entry.headingLine), answers: answers) {
206 case .failed(let text): message = text
207 case .prompt(let prompt):
208 // A state note: asked in the main window's echo area.
209 commands.ask(prompt) { answer in
210 guard let answer else { return }
211 perform(command, on: entry, answers: answers.merging([prompt.key: answer]) { $1 })
212 }
213 openWindow(id: "main")
214 default: message = nil
215 }
216 tick += 1
217 }
218
219 private func setTodo(_ entry: BoardEntry, _ keyword: String?) {
220 perform(SetTodo(keyword: keyword), on: entry)
221 }
222
223 private func askProperty(_ entry: BoardEntry) {
224 commands.ask(Prompt(key: "property", message: "Property (NAME value):")) { answer in
225 guard let answer, let space = answer.firstIndex(of: " ") else { return }
226 let key = String(answer[..<space])
227 let value = String(answer[answer.index(after: space)...]).trimmingCharacters(in: .whitespaces)
228 perform(SetProperty(key: key, value: value), on: entry)
229 }
230 openWindow(id: "main")
231 }
232
233 private func jump(_ entry: BoardEntry) {
234 commands.jump(path: entry.path, offset: entry.headingOffset)
235 openWindow(id: "main")
236 }
237}
238
239/// A table row with sortable values.
240struct BoardRow: Identifiable {
241 let entry: BoardEntry
242 let todoOrder: Int
243 var id: String { entry.id }
244 var title: String { entry.title }
245 var priority: String { entry.priority ?? "" }
246 var tags: String { entry.tags.joined(separator: " ") }
247 var scheduled: String { entry.scheduled ?? "" }
248 var deadline: String { entry.deadline ?? "" }
249 var file: String { (entry.path as NSString).lastPathComponent }
250}