Sources/Orgstar/BoardView.swift

251 lines · 11133 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.excludeArchives = OrgPreferences.agendaExcludeArchives()
 83            agenda.agendaFiles = OrgPreferences.agendaFiles()
 84            let open = session.openTexts
 85            let result = await agenda.board(open: open, match: match)
 86            entries = result.entries
 87            keywords = result.keywords
 88        }
 89    }
 90
 91    // MARK: - Table
 92
 93    private var table: some View {
 94        Table(rows, selection: $selection, sortOrder: $sortOrder) {
 95            TableColumn("TODO", value: \.todoOrder) { row in
 96                Text(row.entry.todo ?? "").foregroundStyle(theme.keywordColor(row.entry.todo ?? "", done: row.entry.isDone)).bold()
 97            }
 98            .width(min: 50, ideal: 60, max: 90)
 99            TableColumn("P", value: \.priority) { row in Text(row.priority) }
100                .width(min: 20, ideal: 24, max: 40)
101            TableColumn("Title", value: \.title) { row in Text(row.title).lineLimit(1) }
102                .width(min: 160, ideal: 320)
103            TableColumn("Tags", value: \.tags) { row in Text(row.tags).foregroundStyle(.secondary).lineLimit(1) }
104                .width(min: 60, ideal: 120)
105            TableColumn("Scheduled", value: \.scheduled) { row in Text(row.scheduled).monospacedDigit() }
106                .width(min: 80, ideal: 110)
107            TableColumn("Deadline", value: \.deadline) { row in Text(row.deadline).monospacedDigit() }
108                .width(min: 80, ideal: 110)
109            TableColumnForEach(propertyColumns, id: \.self) { key in
110                TableColumn(key.capitalized) { (row: BoardRow) in Text(row.entry.properties[key] ?? "") }
111                    .width(min: 50, ideal: 80)
112            }
113            TableColumn("File", value: \.file) { row in Text(row.file).foregroundStyle(.secondary).lineLimit(1) }
114                .width(min: 60, ideal: 120)
115        }
116        .contextMenu(forSelectionType: String.self) { ids in
117            if let entry = entries.first(where: { ids.contains($0.id) }) {
118                Menu("Set TODO") {
119                    ForEach(keywords, id: \.self) { keyword in Button(keyword) { setTodo(entry, keyword) } }
120                    Divider()
121                    Button("None") { setTodo(entry, nil) }
122                }
123                Button("Set Property…") { askProperty(entry) }
124                Button("Open") { jump(entry) }
125            }
126        } primaryAction: { ids in
127            if let entry = entries.first(where: { ids.contains($0.id) }) { jump(entry) }
128        }
129    }
130
131    // MARK: - Kanban
132
133    private var board: some View {
134        ScrollView(.horizontal) {
135            HStack(alignment: .top, spacing: 12) {
136                ForEach(keywords, id: \.self) { keyword in
137                    column(keyword)
138                }
139            }
140            .padding(12)
141        }
142        .background(theme.color("agenda-background", in: colorScheme) ?? .clear)
143    }
144
145    private func column(_ keyword: String) -> some View {
146        let cards = entries.filter { $0.todo == keyword }
147        return VStack(alignment: .leading, spacing: 8) {
148            HStack {
149                Text(keyword).font(.headline).foregroundStyle(theme.keywordColor(keyword, done: cards.first?.isDone ?? false))
150                Text("\(cards.count)").foregroundStyle(.secondary)
151            }
152            ScrollView {
153                VStack(alignment: .leading, spacing: 6) {
154                    ForEach(cards) { entry in
155                        card(entry)
156                            .draggable(entry.id)
157                            .onTapGesture(count: 2) { jump(entry) }
158                            .accessibilityElement(children: .combine)
159                            .accessibilityAddTraits(.isButton)
160                            .accessibilityAction { jump(entry) }
161                            .accessibilityActions {
162                                // Dragging between columns, for VoiceOver.
163                                ForEach(keywords.filter { $0 != keyword }, id: \.self) { other in
164                                    Button("Move to \(other)") { setTodo(entry, other) }
165                                }
166                            }
167                    }
168                }
169            }
170        }
171        .frame(width: 240, alignment: .topLeading)
172        .frame(maxHeight: .infinity, alignment: .top)
173        .padding(8)
174        .background(RoundedRectangle(cornerRadius: 8).fill(Color.secondary.opacity(0.08)))
175        .dropDestination(for: String.self) { ids, _ in
176            for id in ids {
177                if let entry = entries.first(where: { $0.id == id }), entry.todo != keyword { setTodo(entry, keyword) }
178            }
179            return true
180        }
181    }
182
183    private func card(_ entry: BoardEntry) -> some View {
184        VStack(alignment: .leading, spacing: 4) {
185            Text((entry.priority.map { "[#\($0)] " } ?? "") + entry.title).lineLimit(3)
186            HStack(spacing: 6) {
187                Text(entry.category).font(.caption).foregroundStyle(.secondary)
188                if !entry.tags.isEmpty {
189                    Text(entry.tags.joined(separator: " ")).font(.caption).foregroundStyle(.secondary).lineLimit(1)
190                }
191            }
192            if let deadline = entry.deadline {
193                Text("Deadline \(deadline)").font(.caption).foregroundStyle(.red)
194            } else if let scheduled = entry.scheduled {
195                Text("Scheduled \(scheduled)").font(.caption).foregroundStyle(.secondary)
196            }
197        }
198        .padding(8)
199        .frame(maxWidth: .infinity, alignment: .leading)
200        .background(RoundedRectangle(cornerRadius: 6).fill(Color(nsColor: .controlBackgroundColor)))
201    }
202
203    // MARK: - Editing
204
205    private func perform(_ command: any OrgCommand, on entry: BoardEntry, answers: [String: String] = [:]) {
206        switch session.perform(command, path: entry.path, at: entry.headingOffset, expect: (entry.headingOffset, entry.headingLine), answers: answers) {
207        case .failed(let text): message = text
208        case .prompt(let prompt):
209            // A state note: asked in the main window's echo area.
210            commands.ask(prompt) { answer in
211                guard let answer else { return }
212                perform(command, on: entry, answers: answers.merging([prompt.key: answer]) { $1 })
213            }
214            openWindow(id: "main")
215        default: message = nil
216        }
217        tick += 1
218    }
219
220    private func setTodo(_ entry: BoardEntry, _ keyword: String?) {
221        perform(SetTodo(keyword: keyword), on: entry)
222    }
223
224    private func askProperty(_ entry: BoardEntry) {
225        commands.ask(Prompt(key: "property", message: "Property (NAME value):")) { answer in
226            guard let answer, let space = answer.firstIndex(of: " ") else { return }
227            let key = String(answer[..<space])
228            let value = String(answer[answer.index(after: space)...]).trimmingCharacters(in: .whitespaces)
229            perform(SetProperty(key: key, value: value), on: entry)
230        }
231        openWindow(id: "main")
232    }
233
234    private func jump(_ entry: BoardEntry) {
235        commands.jump(path: entry.path, offset: entry.headingOffset)
236        openWindow(id: "main")
237    }
238}
239
240/// A table row with sortable values.
241struct BoardRow: Identifiable {
242    let entry: BoardEntry
243    let todoOrder: Int
244    var id: String { entry.id }
245    var title: String { entry.title }
246    var priority: String { entry.priority ?? "" }
247    var tags: String { entry.tags.joined(separator: " ") }
248    var scheduled: String { entry.scheduled ?? "" }
249    var deadline: String { entry.deadline ?? "" }
250    var file: String { (entry.path as NSString).lastPathComponent }
251}