| 1 | import AppKit |
| 2 | import EquipoKit |
| 3 | import SwiftUI |
| 4 | |
| 5 | /// The conversation in AppKit: Roster's bylines and cards over the live feed |
| 6 | /// (EquipoKit's `Feed.build`), in a centred column with a 48-point author |
| 7 | /// gutter, and the composer at the bottom. Updates reconcile rows by identity |
| 8 | /// and revision; the view stays pinned to the newest item |
| 9 | /// unless the person has scrolled up. |
| 10 | @MainActor |
| 11 | final class LiveTranscript: NSView { |
| 12 | override var isFlipped: Bool { true } |
| 13 | |
| 14 | /// What a question card is doing, kept here across rebuilds. |
| 15 | enum AnswerState: Equatable { |
| 16 | case sending(String) |
| 17 | case changed, offline, failed |
| 18 | } |
| 19 | |
| 20 | let session: EquipoSession |
| 21 | var openTask: (String) -> Void |
| 22 | private(set) var items: [FeedItem] = [] |
| 23 | private var answers: [String: AnswerState] = [:] |
| 24 | /// The card revision each answer state belongs to: a newer card clears it. |
| 25 | private var answeredRevision: [String: Int64] = [:] |
| 26 | /// Set aside and Undo in flight or refused, by card ("aside" or "undo"). |
| 27 | private var asides: [String: AnswerState] = [:] |
| 28 | /// Where each item starts in the document, for bringing a card into view. |
| 29 | private var tops: [String: CGFloat] = [:] |
| 30 | private let scroll = NSScrollView() |
| 31 | private let document = FlippedView() |
| 32 | let composer = MacComposer() |
| 33 | // Keep each reply's SwiftUI host across delta and completion rebuilds. |
| 34 | // In particular, closing a fence keeps its scroll position and Copy state. |
| 35 | private var questionHosts: [String: NSHostingView<QuestionCardHost>] = [:] |
| 36 | var hostedQuestionIDs: Set<String> { Set(questionHosts.keys) } |
| 37 | private let selectionHost: NSHostingView<ProjectSelectionChip> |
| 38 | var selectionFrame: NSRect { selectionHost.frame } |
| 39 | private var replyHosts: [String: NSHostingView<MarkdownReplyHost>] = [:] |
| 40 | private struct RowRevision: Equatable { |
| 41 | let item: FeedItem |
| 42 | let width: CGFloat |
| 43 | let task: ThinTask? |
| 44 | let answer: AnswerState? |
| 45 | let aside: AnswerState? |
| 46 | let stopping: Bool |
| 47 | } |
| 48 | private struct Row { |
| 49 | let view: NSView |
| 50 | let revision: RowRevision |
| 51 | } |
| 52 | // Counts row content updates independently of frame-only positioning. |
| 53 | private(set) var renderedRevisions = 0 |
| 54 | private var rows: [String: Row] = [:] |
| 55 | private var rowOrder: [String] = [] |
| 56 | private var emptyView: NSView? |
| 57 | private var contentHeight: CGFloat = 0 |
| 58 | private var laidOutWidth: CGFloat = 0 |
| 59 | private var hasScrolledOnce = false |
| 60 | private var wantsComposerFocus = false |
| 61 | func focusComposer() { |
| 62 | wantsComposerFocus = true |
| 63 | if let window { window.makeFirstResponder(composer.editor); wantsComposerFocus = false } |
| 64 | } |
| 65 | override func viewDidMoveToWindow() { |
| 66 | super.viewDidMoveToWindow() |
| 67 | if wantsComposerFocus { focusComposer() } |
| 68 | } |
| 69 | |
| 70 | init(session: EquipoSession, openTask: @escaping (String) -> Void, draft: MacComposerDraft? = nil) { |
| 71 | self.session = session |
| 72 | selectionHost = NSHostingView(rootView: ProjectSelectionChip(catalog: session.projectCatalog)) |
| 73 | self.openTask = openTask |
| 74 | super.init(frame: .zero) |
| 75 | scroll.documentView = document |
| 76 | scroll.hasVerticalScroller = true |
| 77 | scroll.drawsBackground = false |
| 78 | scroll.automaticallyAdjustsContentInsets = false |
| 79 | addSubview(scroll) |
| 80 | addSubview(composer) |
| 81 | addSubview(selectionHost) |
| 82 | composer.setText(draft?.text ?? "") |
| 83 | composer.onTextChange = { [weak draft] text in draft?.text = text } |
| 84 | composer.attach(session.attachments) |
| 85 | composer.onHeightChange = { [weak self] in self?.needsLayout = true } |
| 86 | composer.onSend = { [weak self] text in |
| 87 | guard let self else { return } |
| 88 | let session = self.session |
| 89 | _ = session.sendFromComposer(text) |
| 90 | self.needsLayout = true |
| 91 | } |
| 92 | setAccessibilityLabel(EquipoStrings.text("tab.conversation")) |
| 93 | } |
| 94 | required init?(coder: NSCoder) { fatalError() } |
| 95 | |
| 96 | func update(items: [FeedItem]) { |
| 97 | let wasAtBottom = isAtBottom |
| 98 | self.items = items |
| 99 | needsLayout = true |
| 100 | session.markdown.retainMessages(Set(items.filter { $0.reply != nil }.map(\.id)), origin: session.origin) |
| 101 | rebuild() |
| 102 | if wasAtBottom || !hasScrolledOnce { scrollToBottom(); hasScrolledOnce = !items.isEmpty } |
| 103 | } |
| 104 | |
| 105 | private var column: (x: CGFloat, width: CGFloat) { |
| 106 | let width = min(max(bounds.width - 64, 300), 768) |
| 107 | return (floor((bounds.width - width) / 2), width) |
| 108 | } |
| 109 | private var isAtBottom: Bool { |
| 110 | let clip = scroll.contentView.bounds |
| 111 | return clip.maxY >= document.frame.height - 24 |
| 112 | } |
| 113 | private func scrollToBottom() { |
| 114 | let maxY = max(0, document.frame.height - scroll.contentView.bounds.height) |
| 115 | scroll.contentView.scroll(to: NSPoint(x: 0, y: maxY)) |
| 116 | scroll.reflectScrolledClipView(scroll.contentView) |
| 117 | } |
| 118 | |
| 119 | override func layout() { |
| 120 | super.layout() |
| 121 | let height = composer.desiredHeight |
| 122 | let column = self.column |
| 123 | composer.frame = NSRect(x: column.x, y: bounds.height - height - 18, width: column.width, height: height) |
| 124 | selectionHost.frame.size.width = column.width |
| 125 | let chipHeight = session.projectCatalog.selection == nil && session.projectCatalog.selectionNotice == nil ? 0 : ceil(selectionHost.fittingSize.height) |
| 126 | selectionHost.frame = NSRect(x: column.x, y: composer.frame.minY - chipHeight, width: column.width, height: chipHeight) |
| 127 | scroll.frame = NSRect(x: 0, y: 0, width: bounds.width, height: selectionHost.frame.minY - 12) |
| 128 | if laidOutWidth != bounds.width { |
| 129 | let wasAtBottom = isAtBottom |
| 130 | laidOutWidth = bounds.width |
| 131 | rebuild() |
| 132 | if wasAtBottom { scrollToBottom() } |
| 133 | } |
| 134 | } |
| 135 | |
| 136 | override func draw(_ dirtyRect: NSRect) { NSColor.webBackground.setFill(); bounds.fill() } |
| 137 | |
| 138 | // MARK: Building the feed |
| 139 | |
| 140 | private func rebuild() { |
| 141 | let ids = Set(items.map(\.id)) |
| 142 | for id in Array(rows.keys) where !ids.contains(id) { |
| 143 | rows.removeValue(forKey: id)?.view.removeFromSuperview() |
| 144 | replyHosts.removeValue(forKey: id) |
| 145 | questionHosts.removeValue(forKey: id) |
| 146 | } |
| 147 | let column = self.column |
| 148 | var y: CGFloat = 24 |
| 149 | tops = [:] |
| 150 | for item in items { |
| 151 | let task: ThinTask? |
| 152 | switch item { |
| 153 | case .question(let card, _), .decision(let card, _): task = session.task(card.taskId) |
| 154 | default: task = nil |
| 155 | } |
| 156 | let stopping: Bool |
| 157 | if case .thinking(let turn, _) = item { stopping = session.stopping.contains(turn.id) } else { stopping = false } |
| 158 | let revision = RowRevision(item: item, width: column.width, task: task, answer: answers[item.id], aside: asides[item.id], stopping: stopping) |
| 159 | let row: NSView |
| 160 | if let existing = rows[item.id], existing.revision == revision { |
| 161 | row = existing.view |
| 162 | } else { |
| 163 | row = makeRow(item, width: column.width) |
| 164 | rows[item.id] = Row(view: row, revision: revision) |
| 165 | } |
| 166 | tops[item.id] = y |
| 167 | row.frame.origin = NSPoint(x: column.x, y: y) |
| 168 | if row.superview == nil { document.addSubview(row) } |
| 169 | y += row.frame.height |
| 170 | } |
| 171 | // Sorting does not detach hosts or trigger SwiftUI disappearance. |
| 172 | let order = items.map(\.id) |
| 173 | if rowOrder != order { |
| 174 | var ranks = Dictionary(items.enumerated().map { (ObjectIdentifier(rows[$0.element.id]!.view), $0.offset) }, uniquingKeysWith: { a, _ in a }) |
| 175 | withUnsafeMutablePointer(to: &ranks) { pointer in |
| 176 | document.sortSubviews({ a, b, context in |
| 177 | let ranks = context!.assumingMemoryBound(to: [ObjectIdentifier: Int].self).pointee |
| 178 | let left = ranks[ObjectIdentifier(a)] ?? -1, right = ranks[ObjectIdentifier(b)] ?? -1 |
| 179 | return left == right ? .orderedSame : left < right ? .orderedAscending : .orderedDescending |
| 180 | }, context: pointer) |
| 181 | } |
| 182 | rowOrder = order |
| 183 | } |
| 184 | if items.isEmpty && session.status == .ready { |
| 185 | if emptyView == nil { emptyView = makeText(EquipoStrings.text("conversation.empty"), MacType.line, .webSecondary, width: column.width) } |
| 186 | if let emptyView { |
| 187 | emptyView.frame.origin = NSPoint(x: column.x, y: y) |
| 188 | if emptyView.superview == nil { document.addSubview(emptyView) } |
| 189 | y += emptyView.frame.height |
| 190 | } |
| 191 | } else { emptyView?.removeFromSuperview(); emptyView = nil } |
| 192 | contentHeight = y + 24 |
| 193 | document.frame = NSRect(x: 0, y: 0, width: bounds.width, height: max(contentHeight, scroll.bounds.height)) |
| 194 | } |
| 195 | |
| 196 | private func makeRow(_ item: FeedItem, width: CGFloat) -> NSView { |
| 197 | renderedRevisions += 1 |
| 198 | if let reply = item.reply { return coordinatorRow(reply, id: item.id, width: width) } |
| 199 | let row = rows[item.id]?.view ?? FlippedView() |
| 200 | row.subviews.forEach { $0.removeFromSuperview() } |
| 201 | let content = width - MacMetric.gutter |
| 202 | var y: CGFloat = 0 |
| 203 | func place(_ view: NSView, x: CGFloat = 0, gapAfter: CGFloat = 22) { |
| 204 | view.frame.origin = NSPoint(x: x, y: y) |
| 205 | row.addSubview(view) |
| 206 | y = view.frame.maxY + gapAfter |
| 207 | } |
| 208 | func placeCard(_ plate: RaisedPlate) { |
| 209 | plate.frame.origin = NSPoint(x: MacMetric.gutter - MacMetric.shadow, y: y - MacMetric.shadow) |
| 210 | row.addSubview(plate, positioned: .below, relativeTo: nil) |
| 211 | y += plate.content.frame.height + 24 |
| 212 | } |
| 213 | switch item { |
| 214 | case .own(let message): |
| 215 | let bubble = ownBubble(message.text, attachments: message.attachments ?? [], width: width) |
| 216 | place(bubble, x: width - bubble.frame.width) |
| 217 | case .coordinator, .draft, .notice: break |
| 218 | case .outgoing(let outgoing): |
| 219 | if let project = outgoing.projectName { place(makeText(project, MacType.caption, .webSecondary, width: width), gapAfter: 4) } |
| 220 | let bubble = ownBubble(outgoing.text, attachments: outgoing.attachments, width: width) |
| 221 | bubble.alphaValue = outgoing.state == .sending ? 0.6 : 1 |
| 222 | place(bubble, x: width - bubble.frame.width, gapAfter: 4) |
| 223 | if let notice = outgoing.notice { |
| 224 | place(makeText(notice, MacType.small, .webNegative, width: width)) |
| 225 | } |
| 226 | let status = outgoingStatus(outgoing) |
| 227 | place(status, x: width - status.frame.width) |
| 228 | case .report(_, let byline, let report, let compact): |
| 229 | place(bylineView(byline, width: width), gapAfter: MacMetric.bylineGap) |
| 230 | let session = self.session |
| 231 | place(hosted(LiveReport(report: report, session: session, compact: compact, wide: true, onRunNow: { run in Task { await session.runNow(task: report.task.id, run) } }) { [weak self] in self?.openTask(report.task.id) }, width: width), gapAfter: 24) |
| 232 | case .question(let card, let byline): |
| 233 | place(bylineView(byline, width: width), gapAfter: MacMetric.bylineGap) |
| 234 | if card.rememberName != nil || card.isTypedProjectChoice { |
| 235 | let root = QuestionCardHost(card: card, taskTitle: session.task(card.taskId)?.title, session: session, width: content) { [weak self] in |
| 236 | Task { @MainActor [weak self] in |
| 237 | await Task.yield() |
| 238 | guard let self, let host = self.questionHosts[card.id] else { return } |
| 239 | self.resizeHost(host) |
| 240 | } |
| 241 | } |
| 242 | let host = questionHosts[card.id] ?? NSHostingView(rootView: root) |
| 243 | host.rootView = root |
| 244 | host.frame.size = NSSize(width: content, height: ceil(host.fittingSize.height)) |
| 245 | questionHosts[card.id] = host |
| 246 | place(host, x: MacMetric.gutter, gapAfter: 24) |
| 247 | } else { |
| 248 | placeCard(questionCard(card, taskTitle: session.task(card.taskId)?.title, width: content)) |
| 249 | } |
| 250 | case .decision(let card, let byline): |
| 251 | place(bylineView(byline, width: width), gapAfter: MacMetric.bylineGap) |
| 252 | placeCard(decisionCard(card, taskTitle: session.task(card.taskId)?.title, width: content)) |
| 253 | case .receipt(let card, _): place(receiptRow(card, width: width)) |
| 254 | case .thinking(let turn, let activity): |
| 255 | let session = self.session |
| 256 | place(hosted(ThinkingLine(turn: turn, activity: activity, stopping: session.stopping.contains(turn.id)) { Task { await session.stop(turn) } }, width: width)) |
| 257 | } |
| 258 | row.frame.size = NSSize(width: width, height: y) |
| 259 | return row |
| 260 | } |
| 261 | |
| 262 | /// Scrolls a card (a tapped notification's) into view; false while the feed lacks it. |
| 263 | @discardableResult |
| 264 | func reveal(card id: String) -> Bool { |
| 265 | guard let top = tops[id] else { return false } |
| 266 | let maxY = max(0, document.frame.height - scroll.contentView.bounds.height) |
| 267 | scroll.contentView.scroll(to: NSPoint(x: 0, y: min(maxY, max(0, top - 48)))) |
| 268 | scroll.reflectScrolledClipView(scroll.contentView) |
| 269 | return true |
| 270 | } |
| 271 | |
| 272 | private func ownWidth(_ text: String, width: CGFloat) -> CGFloat { |
| 273 | makeText(text, MacType.line, .webText, width: min(width * 0.7, 520) - 28, lineSpacing: 2).frame.width + 28 |
| 274 | } |
| 275 | private func ownBubble(_ value: String, attachments: [MessageAttachment] = [], width: CGFloat) -> NSView { |
| 276 | if !attachments.isEmpty { |
| 277 | let host = NSHostingView(rootView: VStack(alignment: .leading, spacing: 8) { |
| 278 | MessageAttachments(attachments, client: session.client) |
| 279 | if !value.isEmpty { Text(value).textSelection(.enabled) } |
| 280 | }.padding(14).frame(width: min(width * 0.8, 520)) |
| 281 | .background(Color(nsColor: .webSoft), in: .rect(cornerRadius: 16))) |
| 282 | host.frame.size = NSSize(width: min(width * 0.8, 520), height: ceil(host.fittingSize.height)) |
| 283 | return host |
| 284 | } |
| 285 | let label = makeText(value, MacType.line, .webText, width: min(width * 0.7, 520) - 28, lineSpacing: 2, selectable: true) |
| 286 | let card = PaintView(frame: NSRect(x: 0, y: 0, width: label.frame.width + 28, height: label.frame.height + 20)) { r in |
| 287 | let p = NSBezierPath(roundedRect: r.insetBy(dx: 0.5, dy: 0.5), xRadius: 16, yRadius: 16) |
| 288 | NSColor.webSoft.setFill(); p.fill(); NSColor.webLightRim.withAlphaComponent(0.7).setStroke(); p.stroke() |
| 289 | } |
| 290 | label.frame.origin = NSPoint(x: 14, y: 10) |
| 291 | card.addSubview(label) |
| 292 | card.setAccessibilityElement(true); card.setAccessibilityRole(.group) |
| 293 | card.setAccessibilityLabel(EquipoStrings.text("thread.own_spoken \(value)")) |
| 294 | return card |
| 295 | } |
| 296 | |
| 297 | /// A SwiftUI Roster view (the report's track and facts, the thinking |
| 298 | /// line), sized to the column. |
| 299 | private func hosted<V: View>(_ view: V, width: CGFloat) -> NSView { |
| 300 | ResizingHostingView(content: view, width: width) { [weak self] host, height in |
| 301 | guard let self else { return } |
| 302 | let pinned = self.isAtBottom |
| 303 | self.resizeHost(host, measuredHeight: height) |
| 304 | if pinned { self.scrollToBottom() } |
| 305 | } |
| 306 | } |
| 307 | |
| 308 | private func receiptRow(_ card: ThinCard, width: CGFloat) -> NSView { |
| 309 | let row = FlippedView(frame: NSRect(x: 0, y: 0, width: width, height: MacMetric.tile)) |
| 310 | let mark = sparkleView(); mark.frame.origin = NSPoint(x: 0, y: 4); row.addSubview(mark) |
| 311 | let line = makeText(Feed.receiptLine(card), MacType.small, .webSecondary, width: width - MacMetric.gutter) |
| 312 | centre(line, x: MacMetric.gutter, row: 0, height: MacMetric.tile); row.addSubview(line) |
| 313 | row.setAccessibilityElement(true); row.setAccessibilityLabel(Feed.receiptLine(card)) |
| 314 | return row |
| 315 | } |
| 316 | |
| 317 | private func coordinatorRow(_ reply: TranscriptReply, id: String, width: CGFloat) -> NSView { |
| 318 | let row = rows[id]?.view ?? FlippedView() |
| 319 | if rows[id]?.revision.item.reply?.date != reply.date { |
| 320 | for child in row.subviews where child !== replyHosts[id] { child.removeFromSuperview() } |
| 321 | let mark = sparkleView(); mark.frame.origin = NSPoint(x: 0, y: 4); row.addSubview(mark) |
| 322 | let time = reply.date.formatted(date: .omitted, time: .shortened) |
| 323 | let timeLabel = makeText(time, MacType.time, .webFaint) |
| 324 | centre(timeLabel, x: MacMetric.gutter, row: 0, height: MacMetric.tile); row.addSubview(timeLabel) |
| 325 | } |
| 326 | let innerWidth = min(width - MacMetric.gutter, 620) |
| 327 | let content = MarkdownReplyHost(messageID: id, reply: reply, origin: session.origin, transcript: session.markdown, width: innerWidth, openTask: { [weak self] in self?.openTask($0) }, onHeightChange: { [weak self] in |
| 328 | // Parsing completes away from the main actor. Remeasure the host |
| 329 | // when the resulting SwiftUI content changes its intrinsic height. |
| 330 | Task { @MainActor [weak self] in |
| 331 | await Task.yield() |
| 332 | guard let self else { return } |
| 333 | let pinned = self.isAtBottom |
| 334 | self.resizeReply(id) |
| 335 | if pinned { self.scrollToBottom() } |
| 336 | } |
| 337 | }) |
| 338 | let host = replyHosts[id] ?? NSHostingView(rootView: content) |
| 339 | host.rootView = content |
| 340 | host.frame = NSRect(x: MacMetric.gutter, y: MacMetric.tile + 2, width: innerWidth, height: ceil(host.fittingSize.height)) |
| 341 | replyHosts[id] = host |
| 342 | if host.superview == nil { row.addSubview(host) } |
| 343 | row.frame.size = NSSize(width: width, height: host.frame.maxY + 22) |
| 344 | return row |
| 345 | } |
| 346 | |
| 347 | private func resizeReply(_ id: String) { |
| 348 | guard let host = replyHosts[id] else { return } |
| 349 | resizeHost(host) |
| 350 | } |
| 351 | |
| 352 | private func resizeHost(_ host: NSView, measuredHeight: CGFloat? = nil) { |
| 353 | guard let row = host.superview, row.superview === document else { return } |
| 354 | let height = measuredHeight ?? ceil(host.fittingSize.height) |
| 355 | let delta = height - host.frame.height |
| 356 | guard abs(delta) > 0.5 else { return } |
| 357 | let top = row.frame.minY |
| 358 | let previousBottom = host.frame.maxY |
| 359 | for sibling in row.subviews where sibling !== host && sibling.frame.minY >= previousBottom { sibling.frame.origin.y += delta } |
| 360 | host.frame.size.height = height |
| 361 | row.frame.size.height += delta |
| 362 | for view in document.subviews where view !== row && view.frame.minY > top { |
| 363 | view.frame.origin.y += delta |
| 364 | } |
| 365 | for (key, value) in tops where value > top { tops[key] = value + delta } |
| 366 | contentHeight += delta |
| 367 | document.frame.size.height = max(contentHeight, scroll.bounds.height) |
| 368 | } |
| 369 | |
| 370 | private func outgoingStatus(_ outgoing: EquipoSession.Outgoing) -> NSView { |
| 371 | let session = self.session |
| 372 | let id = outgoing.id |
| 373 | switch outgoing.state { |
| 374 | case .sending: |
| 375 | return makeText(EquipoStrings.text("message.sending"), MacType.caption, .webFaint) |
| 376 | case .waiting: |
| 377 | return button(EquipoStrings.text("message.waiting"), .link) { Task { await session.retry(id) } } |
| 378 | case .failed: |
| 379 | let b = button(EquipoStrings.text("message.failed"), .link) { Task { await session.retry(id) } } |
| 380 | b.contentTintColor = .webNegative |
| 381 | return b |
| 382 | } |
| 383 | } |
| 384 | |
| 385 | // MARK: Cards |
| 386 | |
| 387 | private func finish(_ plate: RaisedPlate, height: CGFloat) -> RaisedPlate { |
| 388 | let m = MacMetric.shadow |
| 389 | plate.content.frame.size.height = height |
| 390 | plate.frame.size = NSSize(width: plate.content.frame.width + 2 * m, height: height + 2 * m) |
| 391 | return plate |
| 392 | } |
| 393 | |
| 394 | private func questionCard(_ card: ThinCard, taskTitle: String?, width: CGFloat) -> RaisedPlate { |
| 395 | if let seen = answeredRevision[card.id], !AnswerFeedback.stillChanged(conflictAt: seen, now: card.revision) { |
| 396 | if case .sending = answers[card.id] {} else { answers[card.id] = nil; answeredRevision[card.id] = nil } |
| 397 | } |
| 398 | if card.isAside { return asideStub(card, width: width) } |
| 399 | let state = answers[card.id] |
| 400 | let plate = RaisedPlate(width: width, height: 0, flat: !card.isOpen) |
| 401 | let inner = width - 2 * MacMetric.pad |
| 402 | var y = MacMetric.pad |
| 403 | func add(_ view: NSView, gap: CGFloat = MacMetric.gap) { |
| 404 | view.frame.origin = NSPoint(x: MacMetric.pad, y: y); plate.content.addSubview(view); y = view.frame.maxY + gap |
| 405 | } |
| 406 | if let taskTitle, !card.question.contains(taskTitle) { |
| 407 | add(makeText(taskTitle, MacType.caption, .webSecondary, width: inner), gap: 4) |
| 408 | } |
| 409 | let aside = asideButton(card, plate: plate, top: y, width: width) |
| 410 | add(makeText(card.question.isEmpty ? EquipoStrings.text("card.question") : card.question, MacType.line, .webText, width: inner - (aside == nil ? 0 : 40), lineSpacing: 2, selectable: true)) |
| 411 | guard card.isOpen else { |
| 412 | if card.choice.isEmpty { |
| 413 | add(makeText(EquipoStrings.text("question.closed"), MacType.small, .webSecondary, width: inner)) |
| 414 | } else { |
| 415 | add(outcome(EquipoStrings.text("question.answered \(card.choice)"), width: inner)) |
| 416 | } |
| 417 | return finish(plate, height: y - MacMetric.gap + MacMetric.pad) |
| 418 | } |
| 419 | let sending: String? = { if case .sending(let id) = state { return id }; return nil }() |
| 420 | let options = card.options ?? [] |
| 421 | if options.isEmpty { |
| 422 | let field = QuestionAnswerField(draft: session.questionDraft(for: card)) { [weak self] choice in |
| 423 | self?.submit(card: card, choice: choice) |
| 424 | } |
| 425 | field.placeholderString = EquipoStrings.text("chat.card.answer") |
| 426 | field.setAccessibilityLabel(EquipoStrings.text("chat.card.answer")) |
| 427 | field.font = MacType.line; field.textColor = .webText |
| 428 | field.frame.size = NSSize(width: inner, height: 32) |
| 429 | field.isEnabled = sending == nil |
| 430 | add(field) |
| 431 | let answer = button(EquipoStrings.text("chat.card.answer"), .primary) { [weak field] in |
| 432 | field?.submit() |
| 433 | } |
| 434 | answer.frame.size = NSSize(width: inner, height: 32); add(answer) |
| 435 | } else { |
| 436 | let buttons = options.enumerated().map { index, option in |
| 437 | let busy = sending == option ? EquipoStrings.text("action.sending") : nil |
| 438 | let b = button(option, index == 0 ? .primary : .choice, busy: busy) { [weak self] in |
| 439 | self?.submit(card: card, choice: option) |
| 440 | } |
| 441 | if sending != nil && sending != option { b.isEnabled = false } |
| 442 | b.setAccessibilityLabel(busy ?? option) |
| 443 | return b |
| 444 | } |
| 445 | y = placeChoices(buttons, in: plate.content, x: MacMetric.pad, y: y, width: inner) + MacMetric.gap |
| 446 | } |
| 447 | let feedback: String? = { |
| 448 | switch asides[card.id] ?? state { |
| 449 | case .changed: return EquipoStrings.text("card.changed") |
| 450 | case .offline: return EquipoStrings.text("card.offline") |
| 451 | case .failed: return EquipoStrings.text("card.failed") |
| 452 | default: return nil |
| 453 | } |
| 454 | }() |
| 455 | if let feedback { |
| 456 | let line = makeText(feedback, MacType.small, .webNegative, width: inner) |
| 457 | line.setAccessibilityRole(.staticText) |
| 458 | add(line) |
| 459 | NSAccessibility.post(element: line, notification: .announcementRequested, userInfo: [.announcement: feedback]) |
| 460 | } |
| 461 | return finish(plate, height: y - MacMetric.gap + MacMetric.pad) |
| 462 | } |
| 463 | |
| 464 | // MARK: Set aside (D5) |
| 465 | |
| 466 | /// The web's Set aside: an x centred on the card's first line, on a card |
| 467 | /// that still waits on the person. It never answers anything. |
| 468 | private func asideButton(_ card: ThinCard, plate: RaisedPlate, top: CGFloat, width: CGFloat) -> ActionButton? { |
| 469 | guard Feed.canSetAside(card) else { return nil } |
| 470 | if case .sending = answers[card.id] { return nil } |
| 471 | let busy = asides[card.id] == .sending("aside") ? EquipoStrings.text("roster.setting_aside") : nil |
| 472 | let b = button("", .aside, symbol: "xmark", busy: busy) { [weak self] in self?.setAside(card, true) } |
| 473 | b.frame.size = busy == nil ? NSSize(width: 36, height: 36) : NSSize(width: textWidth(busy!, MacType.caption) + 40, height: 32) |
| 474 | b.frame.origin = NSPoint(x: width - MacMetric.pad - b.frame.width + 6, y: top - 8) |
| 475 | b.toolTip = EquipoStrings.text("roster.set_aside") |
| 476 | b.setAccessibilityLabel(busy ?? EquipoStrings.text("roster.set_aside")) |
| 477 | plate.content.addSubview(b) |
| 478 | return b |
| 479 | } |
| 480 | |
| 481 | /// chat.html equipo-aside-stub: the card's one line, "Set aside, still |
| 482 | /// in Needs you", and Undo. |
| 483 | private func asideStub(_ card: ThinCard, width: CGFloat) -> RaisedPlate { |
| 484 | let plate = RaisedPlate(width: width, height: 0, flat: true) |
| 485 | let inner = width - 2 * MacMetric.pad |
| 486 | let restoring = asides[card.id] == .sending("undo") |
| 487 | let undo = button(EquipoStrings.text("roster.undo"), .choice, busy: restoring ? EquipoStrings.text("roster.restoring") : nil) { [weak self] in |
| 488 | self?.setAside(card, false) |
| 489 | } |
| 490 | let textWidth = inner - undo.frame.width - 12 |
| 491 | let title = makeText(Feed.asideTitle(card, task: session.task(card.taskId)), MacType.smallStrong, .webText, width: textWidth, lines: 1) |
| 492 | let note = makeText(EquipoStrings.text("roster.aside"), MacType.caption, .webSecondary, width: textWidth) |
| 493 | title.frame.origin = NSPoint(x: MacMetric.pad, y: MacMetric.pad) |
| 494 | note.frame.origin = NSPoint(x: MacMetric.pad, y: title.frame.maxY + 2) |
| 495 | var height = max(note.frame.maxY, MacMetric.pad + undo.frame.height) |
| 496 | undo.frame.origin = NSPoint(x: width - MacMetric.pad - undo.frame.width, y: MacMetric.pad + (note.frame.maxY - MacMetric.pad - undo.frame.height) / 2) |
| 497 | [title, note, undo].forEach { plate.content.addSubview($0) } |
| 498 | let feedback: String? = { |
| 499 | switch asides[card.id] { |
| 500 | case .changed: return EquipoStrings.text("card.changed") |
| 501 | case .offline: return EquipoStrings.text("card.offline") |
| 502 | case .failed: return EquipoStrings.text("card.failed") |
| 503 | default: return nil |
| 504 | } |
| 505 | }() |
| 506 | if let feedback { |
| 507 | let line = makeText(feedback, MacType.small, .webNegative, width: inner) |
| 508 | line.frame.origin = NSPoint(x: MacMetric.pad, y: height + 6) |
| 509 | plate.content.addSubview(line) |
| 510 | height = line.frame.maxY |
| 511 | NSAccessibility.post(element: line, notification: .announcementRequested, userInfo: [.announcement: feedback]) |
| 512 | } |
| 513 | return finish(plate, height: height + MacMetric.pad) |
| 514 | } |
| 515 | |
| 516 | private func setAside(_ card: ThinCard, _ aside: Bool) { |
| 517 | if case .sending = asides[card.id] { return } |
| 518 | asides[card.id] = .sending(aside ? "aside" : "undo") |
| 519 | rebuild() |
| 520 | let session = self.session |
| 521 | Task { [weak self] in |
| 522 | let outcome = await session.setAside(card, aside) |
| 523 | guard let self else { return } |
| 524 | switch outcome { |
| 525 | case .answered: self.asides[card.id] = nil |
| 526 | case .changed: self.asides[card.id] = .changed |
| 527 | case .offline: self.asides[card.id] = .offline |
| 528 | case .failed: self.asides[card.id] = .failed |
| 529 | } |
| 530 | self.rebuild() |
| 531 | } |
| 532 | } |
| 533 | |
| 534 | private func submit(card: ThinCard, choice: String) { |
| 535 | if case .sending = answers[card.id] { return } |
| 536 | answers[card.id] = .sending(choice) |
| 537 | answeredRevision[card.id] = card.revision |
| 538 | rebuild() |
| 539 | let session = self.session |
| 540 | Task { [weak self] in |
| 541 | let outcome = await session.answer(card, choice: choice) |
| 542 | guard let self else { return } |
| 543 | switch outcome { |
| 544 | case .answered: self.answers[card.id] = nil |
| 545 | case .changed: |
| 546 | self.answers[card.id] = .changed |
| 547 | // The card as it is now: the message stays until it moves past it. |
| 548 | self.answeredRevision[card.id] = session.cards.first { $0.id == card.id }?.revision ?? card.revision |
| 549 | case .offline: self.answers[card.id] = .offline |
| 550 | case .failed: self.answers[card.id] = .failed |
| 551 | } |
| 552 | self.rebuild() |
| 553 | } |
| 554 | } |
| 555 | |
| 556 | private func decisionCard(_ card: ThinCard, taskTitle: String?, width: CGFloat) -> RaisedPlate { |
| 557 | if card.isAside { return asideStub(card, width: width) } |
| 558 | let open = Feed.decision(card, task: session.task(card.taskId))?.open ?? card.isOpen |
| 559 | let plate = RaisedPlate(width: width, height: 0, flat: !open) |
| 560 | let inner = width - 2 * MacMetric.pad |
| 561 | var y = MacMetric.pad |
| 562 | func add(_ view: NSView, gap: CGFloat = MacMetric.gap) { |
| 563 | view.frame.origin = NSPoint(x: MacMetric.pad, y: y); plate.content.addSubview(view); y = view.frame.maxY + gap |
| 564 | } |
| 565 | if let taskTitle, !card.question.isEmpty, !card.question.contains(taskTitle) { |
| 566 | add(makeText(taskTitle, MacType.caption, .webSecondary, width: inner), gap: 4) |
| 567 | } |
| 568 | let decision = Feed.decision(card, task: session.task(card.taskId)) |
| 569 | if let decision, decision.showsOnlyNote, let note = decision.note { |
| 570 | // As the web's equipo-card-done: the outcome alone. |
| 571 | add(outcome(note, width: inner)) |
| 572 | return finish(plate, height: y - MacMetric.gap + MacMetric.pad) |
| 573 | } |
| 574 | let head = card.question.isEmpty ? (taskTitle ?? EquipoStrings.text("decision.untitled")) : card.question |
| 575 | let aside = asideButton(card, plate: plate, top: y, width: width) |
| 576 | add(makeText(head, MacType.line, .webText, width: inner - (aside == nil ? 0 : 40), lineSpacing: 2, selectable: true), gap: 4) |
| 577 | if let failed = asides[card.id], failed != .sending("aside") { |
| 578 | let said = failed == .changed ? EquipoStrings.text("card.changed") : failed == .offline ? EquipoStrings.text("card.offline") : EquipoStrings.text("card.failed") |
| 579 | add(makeText(said, MacType.small, .webNegative, width: inner)) |
| 580 | } |
| 581 | // Merges and "Does main ship?" are answered here, in the web's words. |
| 582 | if let view = decision { |
| 583 | if view.hasPreview { |
| 584 | let preview = Feed.previewURL(card, origin: session.origin) |
| 585 | add(button(EquipoStrings.text("chat.card.preview_link"), .link) { NSWorkspace.shared.open(preview) }) |
| 586 | } |
| 587 | if view.open { |
| 588 | if let seen = answeredRevision[card.id], !AnswerFeedback.stillChanged(conflictAt: seen, now: card.revision) { |
| 589 | if case .sending = answers[card.id] {} else { answers[card.id] = nil; answeredRevision[card.id] = nil } |
| 590 | } |
| 591 | let state = answers[card.id] |
| 592 | let sending: String? = { if case .sending(let v) = state { return v }; return nil }() |
| 593 | let buttons = view.choices.map { choice in |
| 594 | let busy = sending == choice.value ? EquipoStrings.text("action.sending") : nil |
| 595 | let b = button(choice.label, choice.primary ? .primary : .choice, busy: busy) { [weak self] in |
| 596 | self?.submit(card: card, choice: choice.value) |
| 597 | } |
| 598 | if sending != nil && sending != choice.value { b.isEnabled = false } |
| 599 | b.setAccessibilityLabel(busy ?? choice.label) |
| 600 | return b |
| 601 | } |
| 602 | y = placeChoices(buttons, in: plate.content, x: MacMetric.pad, y: y, width: inner) + MacMetric.gap |
| 603 | let feedback: String? = { |
| 604 | switch state { |
| 605 | case .changed: return EquipoStrings.text("card.changed") |
| 606 | case .offline: return EquipoStrings.text("card.offline") |
| 607 | case .failed: return EquipoStrings.text("card.failed") |
| 608 | default: return nil |
| 609 | } |
| 610 | }() |
| 611 | if let feedback { |
| 612 | let line = makeText(feedback, MacType.small, .webNegative, width: inner) |
| 613 | line.setAccessibilityRole(.staticText) |
| 614 | add(line) |
| 615 | NSAccessibility.post(element: line, notification: .announcementRequested, userInfo: [.announcement: feedback]) |
| 616 | } |
| 617 | } |
| 618 | return finish(plate, height: y - MacMetric.gap + MacMetric.pad) |
| 619 | } |
| 620 | if card.isOpen { |
| 621 | add(makeText(EquipoStrings.text("decision.on_web"), MacType.small, .webSecondary, width: inner)) |
| 622 | } |
| 623 | add(openOnWeb(card, primary: card.isOpen)) |
| 624 | return finish(plate, height: y - MacMetric.gap + MacMetric.pad) |
| 625 | } |
| 626 | |
| 627 | private func openOnWeb(_ card: ThinCard, primary: Bool) -> ActionButton { |
| 628 | let url = Feed.webURL(for: card, origin: session.origin) |
| 629 | return button(EquipoStrings.text("card.open_on_web"), primary ? .primary : .choice) { NSWorkspace.shared.open(url) } |
| 630 | } |
| 631 | |
| 632 | private func outcome(_ line: String, width: CGFloat) -> NSView { |
| 633 | let label = makeText(line, MacType.smallStrong, .webPositive, width: width - 20) |
| 634 | let view = FlippedView(frame: NSRect(x: 0, y: 0, width: width, height: label.frame.height)) |
| 635 | if let check = symbolImage("checkmark", size: 11, weight: .bold, color: .webPositive) { |
| 636 | let image = NSImageView(image: check) |
| 637 | image.frame = NSRect(x: 0, y: ((label.frame.height - check.size.height) / 2).rounded(), width: check.size.width, height: check.size.height) |
| 638 | view.addSubview(image) |
| 639 | } |
| 640 | label.frame.origin = NSPoint(x: 18, y: 0); view.addSubview(label) |
| 641 | view.setAccessibilityElement(true); view.setAccessibilityLabel(line) |
| 642 | return view |
| 643 | } |
| 644 | } |
| 645 | |
| 646 | /// The AppKit transcript in the SwiftUI window. The feed is built in the |
| 647 | /// SwiftUI body, so any change to the session it reads updates it here. |
| 648 | struct TranscriptView: NSViewRepresentable { |
| 649 | let projectSelectionID: String? |
| 650 | let projectSelectionNotice: String? |
| 651 | let items: [FeedItem] |
| 652 | let session: EquipoSession |
| 653 | @Binding var focusCard: String? |
| 654 | var openTask: (String) -> Void |
| 655 | var composerFocus: Int = 0 |
| 656 | var draft: MacComposerDraft? = nil |
| 657 | final class Coordinator { var focus = -1 } |
| 658 | func makeCoordinator() -> Coordinator { Coordinator() } |
| 659 | |
| 660 | func makeNSView(context: Context) -> LiveTranscript { |
| 661 | let view = LiveTranscript(session: session, openTask: openTask, draft: draft) |
| 662 | view.update(items: items) |
| 663 | focus(view) |
| 664 | return view |
| 665 | } |
| 666 | func updateNSView(_ view: LiveTranscript, context: Context) { |
| 667 | view.openTask = openTask |
| 668 | view.update(items: items) |
| 669 | focus(view) |
| 670 | if context.coordinator.focus != composerFocus { |
| 671 | context.coordinator.focus = composerFocus |
| 672 | if composerFocus > 0 { Task { @MainActor [weak view] in |
| 673 | guard let view else { return } |
| 674 | view.focusComposer() |
| 675 | } } |
| 676 | } |
| 677 | } |
| 678 | /// Brings the card into view once the feed has it; reads again if not yet. |
| 679 | private func focus(_ view: LiveTranscript) { |
| 680 | guard let id = focusCard else { return } |
| 681 | let binding = $focusCard |
| 682 | let session = self.session |
| 683 | if view.reveal(card: id) { |
| 684 | Task { @MainActor in binding.wrappedValue = nil } |
| 685 | } else { |
| 686 | Task { @MainActor in |
| 687 | await session.refresh() |
| 688 | if !Feed.build(session).contains(where: { $0.id == id }) { binding.wrappedValue = nil } |
| 689 | } |
| 690 | } |
| 691 | } |
| 692 | } |
| 693 | |
| 694 | private struct MarkdownReplyHost: View { |
| 695 | let messageID: String |
| 696 | let reply: TranscriptReply |
| 697 | let origin: URL |
| 698 | let transcript: MarkdownTranscript |
| 699 | let width: CGFloat |
| 700 | let openTask: (String) -> Void |
| 701 | let onHeightChange: () -> Void |
| 702 | var body: some View { |
| 703 | ChatMarkdownView(reply.text, draft: reply.draft, messageID: messageID, origin: origin, transcript: transcript, openTask: openTask, onHeightChange: onHeightChange) |
| 704 | .frame(width: width, alignment: .leading) |
| 705 | } |
| 706 | } |
| 707 | |
| 708 | private struct QuestionCardHost: View { |
| 709 | let card: ThinCard |
| 710 | let taskTitle: String? |
| 711 | let session: EquipoSession |
| 712 | let width: CGFloat |
| 713 | let onHeightChange: () -> Void |
| 714 | var body: some View { |
| 715 | LiveQuestionCard(card: card, taskTitle: taskTitle, session: session) |
| 716 | .id(card.id) |
| 717 | .frame(width: width, alignment: .leading) |
| 718 | .fixedSize(horizontal: false, vertical: true) |
| 719 | .onGeometryChange(for: CGFloat.self) { $0.size.height } action: { _ in onHeightChange() } |
| 720 | } |
| 721 | } |
| 722 | |