import SwiftUI /// A question the coordinator asks: its options, answered here, bound to /// the revision the person saw. A card that changed underneath is shown as /// it is now and never answered on the person's behalf. Words of their own /// go in the composer, as a message. public struct LiveQuestionCard: View { let card: ThinCard let taskTitle: String? let session: EquipoSession private var taskHeader: (task: ThinTask, open: () -> Void)? @State private var phase: Phase = .open @Bindable private var draft: QuestionAnswerDraft public init(card: ThinCard, taskTitle: String?, session: EquipoSession) { self.card = card; self.taskTitle = taskTitle; self.session = session draft = session.questionDraft(for: card) } init(card: ThinCard, task: ThinTask, session: EquipoSession, openTask: @escaping () -> Void) { self.init(card: card, taskTitle: nil, session: session) taskHeader = (task, openTask) } enum Phase: Equatable { case open, sending(String), settingAside, changed(at: Int64), offline, failed } public var body: some View { if card.isAside { AsideStub(card: card, title: Feed.asideTitle(card, task: session.task(card.taskId)), session: session) } else { raised } } private var raised: some View { RaisedCard(flat: !card.isOpen) { if let taskHeader { TaskRowButton(task: taskHeader.task, needsYou: true, showsNeedsBadge: false, action: taskHeader.open) .accessibilityIdentifier("needs-question-header-" + taskHeader.task.id) } if let taskTitle, !card.question.contains(taskTitle) { Text(taskTitle).font(Typo.caption).foregroundStyle(Palette.secondary) } CardHead(text: card.question.isEmpty ? String(localized: "card.question", bundle: .module) : card.question, aside: aside, settingAside: phase == .settingAside) if card.isOpen { if card.rememberName != nil { RosterCheck(title: String(format: EquipoStrings.text("projects.remember_name"), draft.name), isOn: $draft.remembers).disabled(isSending) RosterField(title: EquipoStrings.text("projects.name_to_remember"), text: $draft.name) .disabled(!draft.remembers || isSending) } choices feedback } else if !card.choice.isEmpty { Label { Text(String(localized: "question.answered \(card.choice)", bundle: .module)) } icon: { Image(systemName: "checkmark") } .font(Typo.secondaryStrong).foregroundStyle(Palette.positive) } else { Text(String(localized: "question.closed", bundle: .module)).font(Typo.secondary).foregroundStyle(Palette.secondary) } } .accessibilityElement(children: .contain) .onChange(of: card.revision) { _, now in if case .changed(let at) = phase, !AnswerFeedback.stillChanged(conflictAt: at, now: now) { phase = .open } } } private var isSending: Bool { if case .sending = phase { return true }; return false } private var aside: (() -> Void)? { guard Feed.canSetAside(card), !isSending, phase != .settingAside else { return nil } return { Task { await setAside() } } } @ViewBuilder private var choices: some View { let options = card.options ?? [] if options.isEmpty { RosterField(title: EquipoStrings.text(String.LocalizationValue(card.answerFieldKey)), text: $draft.typedChoice).onSubmit { Task { await submit(draft.typedChoice) } } .disabled(isSending) RosterButton(title: EquipoStrings.text("chat.card.answer"), primary: true, expanded: false) { Task { await submit(draft.typedChoice) } }.disabled(isSending || draft.typedChoice.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty) } else { ChoiceRow { optionButtons(options) } } } @ViewBuilder private func optionButtons(_ options: [String]) -> some View { ForEach(Array(options.enumerated()), id: \.offset) { index, option in let busy: String? = phase == .sending(option) ? String(localized: "action.sending", bundle: .module) : nil RosterButton(title: option, primary: index == 0, expanded: true, busy: busy, busyInPlace: true) { Task { await submit(option) } } .disabled(isSending) } } @ViewBuilder private var feedback: some View { switch phase { case .changed: Text(String(localized: "card.changed", bundle: .module)).font(Typo.secondary).foregroundStyle(Palette.negative) case .offline: Text(String(localized: "card.offline", bundle: .module)).font(Typo.secondary).foregroundStyle(Palette.negative) case .failed: Text(session.answerNotices[card.id] ?? String(localized: "card.failed", bundle: .module)).font(Typo.secondary).foregroundStyle(Palette.negative) default: EmptyView() } } private func submit(_ choice: String) async { guard !isSending, !choice.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return } phase = .sending(choice) switch await draft.submit(choice, card: card, session: session) { case .answered: phase = .open case .changed: phase = .changed(at: session.cards.first { $0.id == card.id }?.revision ?? card.revision) case .offline: phase = .offline case .failed: phase = .failed } } private func setAside() async { if isSending || phase == .settingAside { return } phase = .settingAside switch await session.setAside(card, true) { case .answered: phase = .open case .changed: phase = .changed(at: session.cards.first { $0.id == card.id }?.revision ?? card.revision) case .offline: phase = .offline case .failed: phase = .failed } } } /// A decision card. Merges and "Does main ship?" are answered here, in the /// web's words (Feed.decision); every other decision opens the web app, /// where its full context is. struct LiveDecisionCard: View { let card: ThinCard let taskTitle: String? let session: EquipoSession @State private var phase: Phase = .open @Environment(\.openURL) private var openURL enum Phase: Equatable { case open, sending(String), settingAside, changed(at: Int64), offline, failed } var body: some View { if card.isAside { AsideStub(card: card, title: Feed.asideTitle(card, task: session.task(card.taskId)), session: session) } else { raised } } private var aside: (() -> Void)? { guard Feed.canSetAside(card), phase == .open || phase == .offline || phase == .failed else { return nil } return { Task { await setAside() } } } @ViewBuilder private var raised: some View { let view = Feed.decision(card, task: session.task(card.taskId)) RaisedCard(flat: !(view?.open ?? card.isOpen)) { if let taskTitle, !card.question.isEmpty, !card.question.contains(taskTitle) { Text(taskTitle).font(Typo.caption).foregroundStyle(Palette.secondary) } if let view, view.showsOnlyNote, let note = view.note { // As the web's equipo-card-done: the outcome alone. Label { Text(note) } icon: { Image(systemName: "checkmark") } .font(Typo.secondaryStrong).foregroundStyle(Palette.positive) } else { CardHead(text: card.question.isEmpty ? (taskTitle ?? String(localized: "decision.untitled", bundle: .module)) : card.question, aside: aside, settingAside: phase == .settingAside) if let view { answerable(view) } else if card.isOpen { Text(String(localized: "decision.on_web", bundle: .module)).font(Typo.secondary).foregroundStyle(Palette.secondary) .fixedSize(horizontal: false, vertical: true) RosterButton(title: String(localized: "card.open_on_web", bundle: .module), primary: true) { openURL(Feed.webURL(for: card, origin: session.origin)) } } else { QuietLink(title: String(localized: "card.open_on_web", bundle: .module), icon: "arrow.up.right") { openURL(Feed.webURL(for: card, origin: session.origin)) } } // An answer's or a Set aside's outcome, on every decision card. feedback } } .accessibilityElement(children: .contain) .onChange(of: card.revision) { _, now in if case .changed(let at) = phase, !AnswerFeedback.stillChanged(conflictAt: at, now: now) { phase = .open } } } @ViewBuilder private func answerable(_ view: DecisionView) -> some View { if view.hasPreview { QuietLink(title: String(localized: "chat.card.preview_link", bundle: .module), icon: "arrow.up.right") { openURL(Feed.previewURL(card, origin: session.origin)) } } if view.open { let sending: String? = { if case .sending(let v) = phase { return v }; return nil }() ChoiceRow { buttons(view, sending: sending) } } } @ViewBuilder private func buttons(_ view: DecisionView, sending: String?) -> some View { ForEach(view.choices) { choice in RosterButton(title: choice.label, primary: choice.primary, expanded: true, busy: sending == choice.value ? String(localized: "action.sending", bundle: .module) : nil, busyInPlace: true) { Task { await submit(choice.value) } } .disabled(sending != nil) } } @ViewBuilder private var feedback: some View { switch phase { case .changed: Text(String(localized: "card.changed", bundle: .module)).font(Typo.secondary).foregroundStyle(Palette.negative) case .offline: Text(String(localized: "card.offline", bundle: .module)).font(Typo.secondary).foregroundStyle(Palette.negative) case .failed: Text(String(localized: "card.failed", bundle: .module)).font(Typo.secondary).foregroundStyle(Palette.negative) default: EmptyView() } } private func submit(_ choice: String) async { if case .sending = phase { return } phase = .sending(choice) let outcome = await session.answer(card, choice: choice) switch outcome { case .answered: phase = .open case .changed: // The card as it is now, after the conflict: the message stays until it moves past it. phase = .changed(at: session.cards.first { $0.id == card.id }?.revision ?? card.revision) announce(String(localized: "card.changed", bundle: .module)) case .offline: phase = .offline; announce(String(localized: "card.offline", bundle: .module)) case .failed: phase = .failed; announce(String(localized: "card.failed", bundle: .module)) } } private func setAside() async { if phase != .open && phase != .offline && phase != .failed { return } phase = .settingAside switch await session.setAside(card, true) { case .answered: phase = .open case .changed: phase = .changed(at: session.cards.first { $0.id == card.id }?.revision ?? card.revision) announce(String(localized: "card.changed", bundle: .module)) case .offline: phase = .offline; announce(String(localized: "card.offline", bundle: .module)) case .failed: phase = .failed; announce(String(localized: "card.failed", bundle: .module)) } } private func announce(_ text: String) { AccessibilityNotification.Announcement(text).post() } } /// A card set aside (chat.html equipo-aside-stub): one line naming it, /// "Set aside, still in Needs you", and Undo, which brings it back at the /// revision seen. It never answers, cancels or starts anything. struct AsideStub: View { let card: ThinCard let title: String let session: EquipoSession @State private var phase: Phase = .idle enum Phase: Equatable { case idle, restoring, changed, offline, failed } var body: some View { let shape = RoundedRectangle(cornerRadius: Metric.raised - 4, style: .continuous) VStack(alignment: .leading, spacing: 6) { HStack(alignment: .center, spacing: 12) { VStack(alignment: .leading, spacing: 2) { Text(title).font(Typo.secondaryStrong).foregroundStyle(Palette.text).lineLimit(1).truncationMode(.tail) Text(String(localized: "roster.aside", bundle: .module)).font(Typo.caption).foregroundStyle(Palette.secondary) } Spacer(minLength: 8) RosterButton(title: String(localized: "roster.undo", bundle: .module), busy: phase == .restoring ? String(localized: "roster.restoring", bundle: .module) : nil) { Task { await undo() } } } switch phase { case .changed: Text(String(localized: "card.changed", bundle: .module)).font(Typo.secondary).foregroundStyle(Palette.negative) case .offline: Text(String(localized: "card.offline", bundle: .module)).font(Typo.secondary).foregroundStyle(Palette.negative) case .failed: Text(String(localized: "card.failed", bundle: .module)).font(Typo.secondary).foregroundStyle(Palette.negative) default: EmptyView() } } .padding(.horizontal, 14).padding(.vertical, 10) .background(Palette.surface2, in: shape) .overlay(shape.strokeBorder(Palette.border, lineWidth: 1)) .accessibilityElement(children: .contain) } private func undo() async { if phase == .restoring { return } phase = .restoring let outcome = await session.setAside(card, false) let said: String? switch outcome { case .answered: phase = .idle; said = nil case .changed: phase = .changed; said = String(localized: "card.changed", bundle: .module) case .offline: phase = .offline; said = String(localized: "card.offline", bundle: .module) case .failed: phase = .failed; said = String(localized: "card.failed", bundle: .module) } if let said { AccessibilityNotification.Announcement(said).post() } } } /// A task report on its rail: eyebrow, title, the five-stop track and the /// facts; one line while its decision is open beside it. public struct LiveReport: View { let report: TaskReport var session: EquipoSession? var compact = false var wide = false var onOpen: () -> Void = {} var onRunNow: ((TaskPause.RunNow) -> Void)? = nil public init(report: TaskReport, session: EquipoSession? = nil, compact: Bool = false, wide: Bool = false, onRunNow: ((TaskPause.RunNow) -> Void)? = nil, onOpen: @escaping () -> Void = {}) { self.report = report; self.session = session; self.compact = compact; self.wide = wide; self.onRunNow = onRunNow; self.onOpen = onOpen } public var body: some View { VStack(alignment: .leading, spacing: Metric.gap) { if compact { Button(action: onOpen) { FlowLayout(spacing: 8, lineSpacing: 4) { Text(report.title).font(Typo.compactTitle).foregroundStyle(Palette.text) Text(report.eyebrow).font(Typo.eyebrow).foregroundStyle(report.tone.eyebrow) if report.needsYou { NeedsChip() } } .frame(maxWidth: .infinity, alignment: .leading).contentShape(Rectangle()) } .buttonStyle(.plain) .accessibilityHint(Text(String(localized: "task.open_hint", bundle: .module))) } else { VStack(alignment: .leading, spacing: 4) { HStack(alignment: .center, spacing: 8) { // A pause says it in its lead and its stop. if report.pause == nil { Text(report.eyebrow).font(Typo.eyebrow).foregroundStyle(report.tone.eyebrow).lineLimit(1) } Spacer(minLength: 0) if report.needsYou { NeedsChip() } } Text(report.title).font(Typo.reportTitle).foregroundStyle(Palette.text) .fixedSize(horizontal: false, vertical: true) } if let pause = report.pause { if let session { TaskPauseActions(pause: pause, taskID: report.task.id, session: session) } else { PauseLead(pause: pause, onRunNow: onRunNow) } } if !report.cancelled { StageTrack(track: report.track, allLabels: wide) } if !report.facts.isEmpty { FactsView(facts: report.facts, wide: wide) } QuietLink(title: String(localized: "task.open", bundle: .module), icon: "chevron.right", action: onOpen) } } .padding(.leading, Metric.indent).padding(.bottom, compact ? 2 : 4) .background(alignment: .topLeading) { // The neutral rail hangs from the byline tile's centre. Capsule().fill(Palette.border).frame(width: 2).padding(.leading, Metric.tile / 2 - 1) } } } /// A one-line receipt: a project added, where new projects go. struct LiveReceipt: View { let card: ThinCard var body: some View { HStack(spacing: 0) { CoordinatorMark(size: 22).frame(width: Metric.indent, alignment: .leading) Text(Feed.receiptLine(card)).font(Typo.secondary).foregroundStyle(Palette.secondary) .fixedSize(horizontal: false, vertical: true) } .accessibilityElement(children: .combine) } } /// The coordinator at work: the mark, what it is doing, elapsed time and a /// quiet Stop for that turn only. A turn waiting for a connection says so, /// without a clock. A Stop the server did not take is offered again. public struct ThinkingLine: View { let turn: ThinTurn let activity: String? let stopping: Bool var onStop: () -> Void public init(turn: ThinTurn, activity: String?, stopping: Bool, onStop: @escaping () -> Void) { self.turn = turn; self.activity = activity; self.stopping = stopping; self.onStop = onStop } public var body: some View { TimelineView(.periodic(from: .now, by: 1)) { context in let waiting = turn.state == "waiting" let seconds = max(0, Int(context.date.timeIntervalSince(turn.createdAt))) let doing = waiting ? String(localized: "thinking.waiting", bundle: .module) : activity ?? String(localized: "thinking.working", bundle: .module) HStack(spacing: 0) { CoordinatorMark(size: 22).frame(width: Metric.indent, alignment: .leading) HStack(spacing: 0) { Text(doing).font(Typo.secondaryStrong).foregroundStyle(Palette.text).lineLimit(1).truncationMode(.tail) if !waiting { Text(" ยท ").foregroundStyle(Palette.faint).accessibilityHidden(true) Text(Duration.seconds(seconds).formatted(.units(allowed: [.minutes, .seconds], width: .narrow))) .monospacedDigit().foregroundStyle(Palette.secondary).fixedSize() } }.font(Typo.secondary) Spacer(minLength: 8) QuietLink(title: stopping ? String(localized: "thinking.stopping", bundle: .module) : String(localized: "thinking.stop", bundle: .module)) { if !stopping { onStop() } } } .accessibilityElement(children: .combine) } } }