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