Sources/Orgstar/BoardView.swift

8714ee09211f42f94ac2c75672f19c309b84860b
orgstar/Sources/Orgstar/BoardView.swift

302 lines · 13962 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(theme.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(theme.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            HStack(spacing: 6) {
235                Text(entry.category).font(.caption).foregroundStyle(.secondary)
236                if !entry.tags.isEmpty {
237                    Text(entry.tags.joined(separator: " ")).font(.caption).foregroundStyle(.secondary).lineLimit(1)
238                }
239            }
240            if let deadline = entry.deadline {
241                Text("Deadline \(deadline)").font(.caption).foregroundStyle(.red)
242            } else if let scheduled = entry.scheduled {
243                Text("Scheduled \(scheduled)").font(.caption).foregroundStyle(.secondary)
244            }
245        }
246        .padding(8)
247        .frame(maxWidth: .infinity, alignment: .leading)
248        .background(RoundedRectangle(cornerRadius: 6).fill(Color(nsColor: .controlBackgroundColor)))
249        .overlay {
250            if selected { RoundedRectangle(cornerRadius: 6).strokeBorder(theme.color("accent") ?? .accentColor, lineWidth: 2) }
251        }
252    }
253
254    // MARK: - Editing
255
256    private func perform(_ command: any OrgCommand, on entry: BoardEntry, answers: [String: String] = [:]) {
257        switch session.perform(command, path: entry.path, at: entry.headingOffset, expect: (entry.headingOffset, entry.headingLine), answers: answers) {
258        case .failed(let text): message = text
259        case .prompt(let prompt):
260            // A state note: asked in the main window's echo area.
261            commands.ask(prompt) { answer in
262                guard let answer else { return }
263                perform(command, on: entry, answers: answers.merging([prompt.key: answer]) { $1 })
264            }
265            openWindow(id: "main")
266        default: message = nil
267        }
268        tick += 1
269    }
270
271    private func setTodo(_ entry: BoardEntry, _ keyword: String?) {
272        perform(SetTodo(keyword: keyword), on: entry)
273    }
274
275    private func askProperty(_ entry: BoardEntry) {
276        commands.ask(Prompt(key: "property", message: "Property (NAME value):")) { answer in
277            guard let answer, let space = answer.firstIndex(of: " ") else { return }
278            let key = String(answer[..<space])
279            let value = String(answer[answer.index(after: space)...]).trimmingCharacters(in: .whitespaces)
280            perform(SetProperty(key: key, value: value), on: entry)
281        }
282        openWindow(id: "main")
283    }
284
285    private func jump(_ entry: BoardEntry) {
286        commands.jump(path: entry.path, offset: entry.headingOffset)
287        openWindow(id: "main")
288    }
289}
290
291/// A table row with sortable values.
292struct BoardRow: Identifiable {
293    let entry: BoardEntry
294    let todoOrder: Int
295    var id: String { entry.id }
296    var title: String { entry.title }
297    var priority: String { entry.priority ?? "" }
298    var tags: String { entry.tags.joined(separator: " ") }
299    var scheduled: String { entry.scheduled ?? "" }
300    var deadline: String { entry.deadline ?? "" }
301    var file: String { (entry.path as NSString).lastPathComponent }
302}
Keyboard shortcuts

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form