Branchwell

OpenTalon / app · opentalon.ai / native / Sources / OpenTalon / KanbanView.swift

1import CompanionCore
2import SwiftUI
3
4struct KanbanView: View {
5 @Environment(WorkspaceModel.self) private var model
6 @Environment(\.palette) private var palette
7 @State private var drag = BoardDrag()
8 var body: some View {
9 @Bindable var model = model
10 VStack(alignment: .leading, spacing: 0) {
11 HStack(spacing: 11) {
12 if let board = model.board {
13 ProjectIcon(key: board.icon, size: 23).foregroundStyle(palette.muted)
14 }
15 Text(model.board?.name ?? "All tasks")
16 .font(palette.display(35))
17 .lineLimit(1)
18 .truncationMode(.tail)
19 .accessibilityAddTraits(.isHeader)
20 if let board = model.board {
21 Menu { ProjectActions(board: board) } label: {
22 Image(systemName: "ellipsis")
23 .font(.system(size: 13, weight: .semibold))
24 .frame(width: 30, height: 30)
25 .glassControl(in: Circle(), fill: palette.card)
26 }
27 .menuStyle(.borderlessButton).menuIndicator(.hidden).fixedSize()
28 .accessibilityLabel("Project options")
29 }
30 Spacer()
31 GlassCommandGroup {
32 HStack(spacing: 9) {
33 SearchField()
34 Button { model.newTask() } label: { Label("New task", systemImage: "plus") }
35 .glassPrimary()
36 }
37 }
38 }
39 .padding(.horizontal, 27)
40 .padding(.top, 28)
41 .padding(.bottom, 22)
42
43 HStack(spacing: 10) {
44 BoardDropdown(selection: $model.priority, title: "Priority", symbol: "line.3.horizontal.decrease",
45 choices: [nil] + Priority.allCases.map(Optional.some)) {
46 $0?.label ?? "All priorities"
47 }
48 .frame(idealWidth: 176, maxWidth: 176)
49
50 BoardDropdown(selection: $model.sort, title: "Order", symbol: "arrow.up.arrow.down",
51 choices: BoardSort.allCases, label: \.title)
52 .frame(idealWidth: 207, maxWidth: 207)
53
54 Spacer(minLength: 4)
55 let count = WorkStatus.allCases.reduce(0) { $0 + model.column($1).count }
56 Text("\(count) \(count == 1 ? "task" : "tasks")")
57 .font(.system(size: 12))
58 .foregroundStyle(palette.muted)
59 .monospacedDigit()
60 .fixedSize()
61 }
62 .padding(.horizontal, 27)
63 .padding(.bottom, 18)
64
65 GeometryReader { geometry in
66 let statuses = WorkStatus.allCases.filter { $0 != .sent || model.canUseAgents || !model.column(.sent).isEmpty }
67 let width = max(177, (geometry.size.width - 54 - CGFloat(statuses.count - 1) * 15) / CGFloat(statuses.count))
68 ThemedScrollView(.horizontal) {
69 HStack(alignment: .top, spacing: 15) {
70 ForEach(statuses) { status in
71 ColumnView(status: status, drag: drag)
72 .frame(width: width)
73 .frame(height: max(220, geometry.size.height - 23))
74 }
75 }
76 .padding(.horizontal, 27)
77 .padding(.bottom, 23)
78 }
79 .dragFrame(.viewport)
80 }
81 }
82 .overlay(alignment: .topLeading) {
83 if let lifted = drag.lifted, let point = drag.point {
84 TaskCard(item: lifted.item, includeProject: model.page == .all, presentationOnly: true)
85 .frame(width: lifted.frame.width, height: lifted.frame.height)
86 .shadow(color: .black.opacity(0.24), radius: 16, y: 7)
87 .position(x: point.x + lifted.centerOffset.width, y: point.y + lifted.centerOffset.height)
88 .allowsHitTesting(false)
89 .accessibilityHidden(true)
90 }
91 }
92 .coordinateSpace(name: BoardDrag.space)
93 .onChange(of: model.page) { _, _ in drag.reset() }
94 .onDisappear { drag.reset() }
95 .onExitCommand { drag.reset() }
96 .onPreferenceChange(DragFrames.self) { frames in
97 drag.setFrames(frames)
98 }
99 }
100}
101
102@Observable
103private final class BoardDrag {
104 static let space = "OpenTalonBoardDrag"
105 @ObservationIgnored private var frames: [DragArea: CGRect] = [:]
106 struct LiftedCard {
107 let item: WorkItem
108 let frame: CGRect
109 let centerOffset: CGSize
110 }
111
112 private(set) var lifted: LiftedCard?
113 var source: String? { lifted?.item.id }
114 private(set) var target: WorkStatus?
115 private(set) var anchor: String?
116 private(set) var before = true
117 private(set) var point: CGPoint?
118
119 func setFrames(_ frames: [DragArea: CGRect]) {
120 self.frames = frames
121 if let point { update(at: point) }
122 }
123
124 func lift(_ item: WorkItem, from status: WorkStatus, at start: CGPoint) {
125 guard lifted == nil, let frame = frames[.card(status, item.id)] else { return }
126 lifted = LiftedCard(item: item, frame: frame,
127 centerOffset: CGSize(width: frame.midX - start.x, height: frame.midY - start.y))
128 }
129
130 func update(at point: CGPoint) {
131 guard lifted != nil else { return }
132 self.point = point
133 guard let viewport = frames[.viewport], viewport.contains(point) else {
134 target = nil
135 anchor = nil
136 return
137 }
138 target = WorkStatus.allCases.first { frames[.column($0)]?.contains(point) == true }
139 guard let target, let well = frames[.well(target)], well.contains(point) else {
140 anchor = nil
141 return
142 }
143 let visibleCards = frames.compactMap { area, rect -> (String, CGRect)? in
144 guard case .card(target, let id) = area, well.intersects(rect) else { return nil }
145 return (id, rect)
146 }.sorted { $0.1.minY < $1.1.minY }
147 if let (id, rect) = visibleCards.first(where: { $0.1.maxY >= point.y - 4 }) {
148 anchor = id
149 before = point.y < rect.midY
150 } else {
151 anchor = nil
152 }
153 }
154
155 func edgeDirection(_ status: WorkStatus) -> Int {
156 guard target == status, let point, let frame = frames[.well(status)], frame.contains(point) else { return 0 }
157 if point.y - frame.minY < 34 { return -1 }
158 if frame.maxY - point.y < 34 { return 1 }
159 return 0
160 }
161
162 func reset() {
163 lifted = nil
164 target = nil
165 anchor = nil
166 point = nil
167 }
168}
169
170private enum DragArea: Hashable {
171 case viewport, column(WorkStatus), well(WorkStatus), card(WorkStatus, String)
172}
173
174private struct DragFrames: PreferenceKey {
175 static let defaultValue: [DragArea: CGRect] = [:]
176 static func reduce(value: inout [DragArea: CGRect], nextValue: () -> [DragArea: CGRect]) {
177 value.merge(nextValue(), uniquingKeysWith: { _, last in last })
178 }
179}
180
181private extension View {
182 func dragFrame(_ area: DragArea) -> some View {
183 background {
184 GeometryReader { geometry in
185 Color.clear.preference(key: DragFrames.self, value: [area: geometry.frame(in: .named(BoardDrag.space))])
186 }
187 }
188 }
189}
190
191private struct ColumnView: View {
192 @Environment(WorkspaceModel.self) private var model
193 @Environment(\.palette) private var palette
194 let status: WorkStatus
195 let drag: BoardDrag
196
197 @State private var scrollID: String?
198 @State private var page = TaskPageWindow()
199 private var scrollSpace: String { "Task column " + status.rawValue }
200
201 private var usesCompletionOrder: Bool { status == .done && model.doneOrder != .manual }
202
203 var body: some View {
204 let items = model.column(status)
205 VStack(spacing: 0) {
206 heading(items.count)
207 GeometryReader { viewport in
208 ThemedScrollView(track: palette.well) {
209 LazyVStack(spacing: 9) {
210 ForEach(items.prefix(page.limit)) { item in
211 TaskCard(item: item, includeProject: model.page == .all)
212 .dragFrame(.card(status, item.id))
213 .opacity(drag.source == item.id ? 0.22 : 1)
214 .overlay(alignment: drag.before ? .top : .bottom) {
215 if !usesCompletionOrder && drag.anchor == item.id && drag.source != item.id {
216 Capsule().fill(palette.accent).frame(height: 3)
217 .offset(y: drag.before ? -4 : 4).allowsHitTesting(false)
218 }
219 }
220 .highPriorityGesture(cardDrag(item))
221 }
222 endOfColumn(isEmpty: items.isEmpty)
223 if items.count > page.limit {
224 TaskPageBoundary(space: scrollSpace, viewportHeight: viewport.size.height) {
225 page.revealNext(total: items.count)
226 }
227 }
228 }
229 .scrollTargetLayout()
230 .padding(.horizontal, 9)
231 .padding(.bottom, 10)
232 .frame(minHeight: 165, alignment: .top)
233 }
234 .coordinateSpace(name: scrollSpace)
235 .scrollPosition(id: $scrollID, anchor: .top)
236 .defaultScrollAnchor(.top)
237 .onChange(of: items.first?.id) { previous, next in
238 if usesCompletionOrder, scrollID == previous { scrollID = next }
239 }
240 .dragFrame(.well(status))
241 .task(id: drag.edgeDirection(status)) {
242 let direction = drag.edgeDirection(status)
243 guard direction != 0, items.count > 1 else { return }
244 while !Task.isCancelled {
245 do { try await Task.sleep(for: .milliseconds(180)) }
246 catch { return }
247 let current = items.firstIndex { $0.id == scrollID } ?? 0
248 let next = min(items.count - 1, max(0, current + direction))
249 guard next != current else { return }
250 page.revealThrough(index: next, total: items.count)
251 withAnimation(.easeOut(duration: 0.15)) { scrollID = items[next].id }
252 }
253 }
254 }
255 }
256 .onChange(of: model.page) { _, _ in page.reset(); scrollID = nil }
257 .onChange(of: model.search) { _, _ in page.reset(); scrollID = nil }
258 .onChange(of: model.priority) { _, _ in page.reset(); scrollID = nil }
259 .onChange(of: model.sort) { _, _ in page.reset(); scrollID = nil }
260 .onChange(of: model.doneOrder) { _, _ in if status == .done { page.reset(); scrollID = nil } }
261 .frame(maxHeight: .infinity, alignment: .top)
262 .background(palette.well, in: .rect(cornerRadius: 12))
263 .dragFrame(.column(status))
264 .overlay {
265 if drag.target == status {
266 RoundedRectangle(cornerRadius: 12).strokeBorder(palette.accent, lineWidth: 2).allowsHitTesting(false)
267 }
268 }
269 .accessibilityElement(children: .contain)
270 .accessibilityLabel(status.rawValue)
271 }
272
273 private func cardDrag(_ item: WorkItem) -> some Gesture {
274 DragGesture(minimumDistance: 7, coordinateSpace: .named(BoardDrag.space))
275 .onChanged { value in
276 guard !model.draftDirty else { return }
277 drag.lift(item, from: status, at: value.startLocation)
278 if drag.source == item.id { drag.update(at: value.location) }
279 }
280 .onEnded { value in
281 guard drag.source == item.id else { return }
282 drag.update(at: value.location)
283 let destination = drag.target
284 let anchor = drag.anchor
285 let before = drag.before
286 drag.reset()
287 if let destination {
288 _ = model.drop(item.id, in: destination, anchor: anchor, before: before)
289 }
290 }
291 }
292
293 private func heading(_ count: Int) -> some View {
294 @Bindable var model = model
295 return HStack(spacing: 7) {
296 Image(systemName: status.symbol).foregroundStyle(status == .working ? palette.accent : palette.muted)
297 Text(drag.target == status ? "Drop in \(status.rawValue)" : status.rawValue)
298 .fontWeight(.semibold)
299 .lineLimit(1)
300 Text(count.formatted()).font(.system(size: 11)).foregroundStyle(palette.muted)
301 Spacer(minLength: 0)
302 if status == .done {
303 Menu {
304 Picker("Sort completed tasks", selection: $model.doneOrder) {
305 ForEach(DoneOrder.allCases) { order in Text(order.title).tag(order) }
306 }
307 } label: {
308 Image(systemName: "arrow.up.arrow.down")
309 .foregroundStyle(palette.muted)
310 }
311 .menuStyle(.borderlessButton)
312 .menuIndicator(.hidden)
313 .fixedSize()
314 .help(model.doneOrder.title)
315 .accessibilityLabel("Sort completed tasks")
316 .accessibilityValue(model.doneOrder.title)
317 .accessibilityIdentifier("doneColumnSort")
318 .onChange(of: model.doneOrder) { scrollID = model.column(.done).first?.id }
319 }
320 if status != .sent || model.canUseAgents {
321 IconButton(symbol: "plus", label: "Add task in \(status.rawValue)") { model.newTask(status) }
322 .foregroundStyle(palette.muted)
323 }
324 }
325 .font(.system(size: 13))
326 .padding(.horizontal, 13)
327 .frame(height: 50)
328 .contentShape(Rectangle())
329 .background(drag.target == status ? palette.active : .clear)
330 }
331
332 private func endOfColumn(isEmpty: Bool) -> some View {
333 VStack {
334 if isEmpty, status != .sent || model.canUseAgents {
335 Button {
336 model.newTask(status)
337 } label: {
338 Label("Add a task", systemImage: "plus")
339 .font(.system(size: 12))
340 .foregroundStyle(palette.muted)
341 .padding(10)
342 }
343 .buttonStyle(.plain)
344 }
345 }
346 .frame(maxWidth: .infinity, minHeight: isEmpty ? 147 : 34)
347 .background(drag.target == status && drag.anchor == nil ? palette.active.opacity(0.7) : Color.clear)
348 .contentShape(Rectangle())
349 }
350}
351
352struct TaskCard: View {
353 @Environment(WorkspaceModel.self) private var model
354 @Environment(\.palette) private var palette
355 @State private var hovered = false
356 let item: WorkItem
357 let includeProject: Bool
358 var presentationOnly = false
359
360 private var notesPreview: String {
361 let text = item.notes.hasPrefix("Imported from Daily Brief\n")
362 ? item.notes.components(separatedBy: "\n\n").dropFirst().joined(separator: " ")
363 .components(separatedBy: "Original Daily Brief action (complete source record):")[0]
364 : item.notes
365 return String(text.split(whereSeparator: \.isWhitespace).joined(separator: " ").prefix(220))
366 }
367
368 private var run: AgentRun? {
369 guard let id = model.workspace?.agentAssignments[item.id] else { return nil }
370 return model.workspace?.agentRuns.first { $0.id == id }
371 }
372
373 var body: some View {
374 if presentationOnly {
375 card
376 } else {
377 interactiveCard
378 }
379 }
380
381 private var card: some View {
382 VStack(alignment: .leading, spacing: 8) {
383 HStack(spacing: 6) {
384 if item.kind == .bug { IssueTypeBadge(.bug, tint: palette.actionAccent) }
385 PriorityBadge(priority: item.priority)
386 }
387 if let key = item.taskKey {
388 Text(key).font(.system(.caption2, design: .monospaced)).foregroundStyle(palette.muted)
389 }
390 Text(item.title).font(.system(size: 13, weight: .medium)).lineLimit(3)
391 Text(notesPreview.isEmpty ? "No notes yet" : notesPreview)
392 .font(.system(size: 11)).foregroundStyle(palette.muted).lineLimit(2)
393 if includeProject {
394 Label(model.projectName(item.boardId), systemImage: "rectangle.split.3x1")
395 .font(.system(size: 10)).foregroundStyle(palette.muted).lineLimit(1)
396 }
397 HStack(spacing: 6) {
398 Image(systemName: "circle.grid.2x2.fill").font(.system(size: 8))
399 Label(item.dueLabel ?? "No due date", systemImage: "calendar")
400 .foregroundStyle(item.late ? palette.danger : palette.muted)
401 .lineLimit(1)
402 Spacer(minLength: 0)
403 if let agent = run?.agent {
404 AgentBrandLabel(agent: agent, iconSize: 11)
405 } else {
406 Text("Manual")
407 }
408 }
409 .font(.system(size: 10)).foregroundStyle(palette.muted)
410 if let date = item.creationDate {
411 Text("Created \(date.formatted(date: .abbreviated, time: .omitted))")
412 .font(.system(size: 10)).foregroundStyle(palette.muted)
413 }
414 if item.commentCount > 0 || item.imageCount > 0 || run != nil {
415 HStack(spacing: 8) {
416 if item.commentCount > 0 { Label("\(item.commentCount)", systemImage: "bubble") }
417 if item.imageCount > 0 { Label("\(item.imageCount)", systemImage: "photo") }
418 if let run { Text(run.statusLabel) }
419 }
420 .font(.system(size: 10)).foregroundStyle(palette.muted)
421 }
422 }
423 .frame(maxWidth: .infinity, alignment: .leading)
424 .padding(12)
425 .surface(8, fill: model.selection == item.id ? palette.active : palette.card)
426 .shadow(color: .black.opacity(hovered ? 0.11 : 0.05), radius: hovered ? 4 : 2, y: 2)
427 }
428
429 private var interactiveCard: some View {
430 card.contentShape(Rectangle())
431 .onTapGesture { model.select(item) }
432 .accessibilityElement(children: .ignore)
433 .accessibilityAddTraits(.isButton)
434 .accessibilityAction { model.select(item) }
435 .onHover { hovered = $0 }
436 .accessibilityLabel(item.taskKey.map { "\($0), \(item.title)" } ?? item.title)
437 .accessibilityHint([item.status.rawValue, item.priority.label,
438 item.creationDate.map { "Created \($0.formatted(date: .abbreviated, time: .omitted))" }]
439 .compactMap { $0 }.joined(separator: ", "))
440 .contextMenu {
441 Button("Open task") { model.select(item) }
442 Menu("Move to") {
443 ForEach(model.editableStatuses.filter { $0 != item.status }) { status in
444 Button(status.rawValue) { model.move(item, to: status) }
445 }
446 }
447 Divider()
448 Button("Move to Trash", role: .destructive) { model.trash(item) }
449 }
450 }
451}