import SwiftUI /// How wide the thread's bubbles may grow: 86% of the thread on the Mac /// and in the menu-bar panel, 92% on the iPhone (app.css `.msg`). public enum AskLayout: Sendable { case window, panel, phone var bubbleShare: CGFloat { self == .phone ? 0.92 : 0.86 } var padding: EdgeInsets { switch self { case .window: EdgeInsets(top: 18, leading: 24, bottom: 18, trailing: 24) case .panel, .phone: EdgeInsets(top: 14, leading: 12, bottom: 8, trailing: 12) } } } /// The conversation (chat.html `.thread`): its lines, pills and cards from /// AskModel, newest at the foot. It follows the newest line while the /// person is at (or within 80 pt of) the foot; scrolled up to read, it /// stays put and Jump to latest appears when something new arrives. struct AskThread: View { @Bindable var model: AskModel let layout: AskLayout let timeZone: TimeZone? @State private var transcript = MarkdownTranscript() @State private var position = ScrollPosition(edge: .bottom) @State private var pinned = true @State private var unseen = false @State private var width: CGFloat = 600 @Environment(\.colorScheme) private var scheme var body: some View { let p = Palette(scheme) ScrollView { LazyVStack(alignment: .leading, spacing: 10) { ForEach(model.entries) { entry in row(entry) } } .padding(layout.padding) .frame(maxWidth: .infinity, alignment: .leading) } .scrollPosition($position) .defaultScrollAnchor(.bottom) .defaultScrollAnchor(.bottom, for: .sizeChanges) .onScrollGeometryChange(for: Bool.self) { geo in geo.contentSize.height - geo.visibleRect.maxY < 80 } action: { _, atFoot in pinned = atFoot if atFoot { unseen = false } } .onChange(of: model.entries) { if pinned { position.scrollTo(edge: .bottom) } else { unseen = true } } .onGeometryChange(for: CGFloat.self) { $0.size.width } action: { width = $0 } // Scrolled to its newest, the thread fades out under the header. .mask { VStack(spacing: 0) { LinearGradient(colors: [.clear, .black], startPoint: .top, endPoint: .bottom).frame(height: 56) Color.black } } .overlay(alignment: .bottom) { if unseen { Button { position.scrollTo(edge: .bottom) unseen = false } label: { Text(BaseText.text("ask.jump")) .font(BaseFont.body(13, .semibold, relativeTo: .footnote)) .foregroundStyle(p[.onSignal]) .padding(.horizontal, 14).frame(minHeight: 36) .background(p[.signal], in: Capsule()) .shadow(color: p[.glassShadow].opacity(0.5), radius: 9, y: 6) } .buttonStyle(.plain) .padding(.bottom, 10) } } .accessibilityElement(children: .contain) .accessibilityLabel(Text(BaseText.text("ask.conversation_a11y"))) } private var bubbleWidth: CGFloat { max(120, (width - layout.padding.leading - layout.padding.trailing) * layout.bubbleShare) } @ViewBuilder private func row(_ entry: AskModel.Entry) -> some View { switch entry { case .message(let m): Bubble(person: m.isPerson, maxWidth: bubbleWidth) { let parts = PersonBubble.parts(m) VStack(alignment: .leading, spacing: 4) { // The person's own words take the web's little Markdown // (PersonMarkdown); with none, they are exactly as written. if !parts.showsText { EmptyView() } else if m.isPerson, case let nodes = PersonMarkdown.parse(m.text), !PersonMarkdown.isPlain(nodes) { BaseMarkdownView(person: nodes, id: m.id, transcript: transcript) } else if m.isPerson { Text(verbatim: m.text).font(BaseFont.body(15)).fixedSize(horizontal: false, vertical: true) } else { BaseMarkdownView(m.text, draft: false, id: m.id, transcript: transcript) } // What the Assistant looked up, after its words. ForEach(Array(m.lookups.enumerated()), id: \.offset) { i, lookup in LookupView(lookup: lookup, id: m.id + ":lookup:\(i)", transcript: transcript) } if let names = parts.names { FilesLine(names: names) } } } case .draft(let d): Bubble(person: false, maxWidth: bubbleWidth) { VStack(alignment: .leading, spacing: 4) { if !d.text.isEmpty { BaseMarkdownView(d.text, draft: !d.settled, id: "draft:" + d.turnID, transcript: transcript) } if !d.settled { Caret() } } } .accessibilityElement(children: .combine) case .thinking(let t): ThinkingBubble(line: t.line, maxWidth: bubbleWidth) case .job(let job) where layout == .panel && (job.state == .asking || job.state == .stopped): EmptyView() // the panel shows them at its top (WaitingJobs) case .job(let job): JobPill(job: job, busy: model.answering, timeZone: timeZone, carryOn: { card in Task { await model.carryOn(card) } }, carryOnErrors: model.carryOnErrors) { card, option in Task { await model.answer(card, option) } } case .card(let card): CardView(card: card, busy: model.answering.contains(card.id)) { option in Task { await model.answer(card, option) } } case .offer(let offer): OfferView(offer: offer) } } } /// What a person's bubble shows until the app draws files (slice 2, plan /// P9): their words, then one plain line of their files' names, so a /// message of files alone is never an empty bubble. enum PersonBubble { struct Parts: Equatable { var showsText: Bool; var names: String? } static func parts(_ m: AskMessage) -> Parts { let names = m.attachments.map(\.name).filter { !$0.isEmpty } let hasText = !m.text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty return Parts(showsText: hasText || names.isEmpty, names: names.isEmpty ? nil : names.joined(separator: ", ")) } } /// The names line: a paperclip and the files' names, in the secondary /// ink; VoiceOver reads "Attached: …". struct FilesLine: View { let names: String @Environment(\.colorScheme) private var scheme var body: some View { HStack(alignment: .firstTextBaseline, spacing: 5) { Image(systemName: "paperclip").font(BaseFont.body(12, relativeTo: .footnote)).accessibilityHidden(true) Text(verbatim: names).font(BaseFont.body(13, relativeTo: .footnote)).fixedSize(horizontal: false, vertical: true) } .foregroundStyle(Palette(scheme)[.haze]) .accessibilityElement(children: .ignore) .accessibilityLabel(Text(BaseText.format("ask.files_line_a11y", ["names": names]))) } } /// A lookup under the Assistant's reply (chat.html `ask-lookup`): its /// answer (LookupMarkdown, never a link), then a quiet Sources line with /// each source's title as a link and its host after it. struct LookupView: View { let lookup: AskLookup let id: String let transcript: MarkdownTranscript @Environment(\.colorScheme) private var scheme var body: some View { VStack(alignment: .leading, spacing: 6) { BaseMarkdownView(person: LookupMarkdown.parse(lookup.answer), id: id, transcript: transcript) Text(Self.sources(lookup.sources, label: BaseText.text("ask.sources"), palette: Palette(scheme))) .font(BaseFont.body(13.5, relativeTo: .footnote)) .foregroundStyle(Palette(scheme)[.haze]) .fixedSize(horizontal: false, vertical: true) } .padding(.top, 6) } /// The Sources line: the label, then each source's title (a link, /// opening in the browser) and its host. static func sources(_ sources: [AskSource], label: String, palette p: Palette) -> AttributedString { var line = AttributedString(label) line.font = BaseFont.body(13.5, .medium, relativeTo: .footnote) for s in sources { guard let url = s.url else { continue } var title = AttributedString(s.label) title.link = url title.foregroundColor = p[.focus] title.underlineStyle = .single var host = AttributedString(" " + s.host) host.font = BaseFont.body(12.5, relativeTo: .footnote) line += AttributedString(" ") + title + host } return line } } /// A line of the conversation: the person's on the right in teal, the /// Assistant's on the left, each with one tucked corner (app.css `.msg`). struct Bubble: View { let person: Bool let maxWidth: CGFloat @ViewBuilder let content: Content @Environment(\.colorScheme) private var scheme var body: some View { let p = Palette(scheme) let shape = UnevenRoundedRectangle(topLeadingRadius: 14, bottomLeadingRadius: person ? 14 : 4, bottomTrailingRadius: person ? 4 : 14, topTrailingRadius: 14, style: .continuous) content .foregroundStyle(p[.frost]) .padding(.vertical, 10).padding(.horizontal, 14) .background(person ? p[.mine] : p[.theirs], in: shape) .overlay { shape.strokeBorder(person ? p[.mineEdge] : p[.theirsEdge], lineWidth: 1) } .frame(maxWidth: maxWidth, alignment: person ? .trailing : .leading) .frame(maxWidth: .infinity, alignment: person ? .trailing : .leading) } } /// The streaming reply's caret: a block of the accent that blinks (steps, /// 1 s); still with Reduce Motion. struct Caret: View { @Environment(\.colorScheme) private var scheme @Environment(\.accessibilityReduceMotion) private var reduceMotion @Environment(\.skyFrozen) private var frozen var body: some View { let block = Rectangle().fill(Palette(scheme)[.signal]).frame(width: 7, height: 15) Group { if reduceMotion || frozen { block } else { TimelineView(.periodic(from: .now, by: 0.5)) { timeline in block.opacity(Int(timeline.date.timeIntervalSinceReferenceDate * 2) % 2 == 0 ? 1 : 0) } } } .accessibilityHidden(true) } } /// The Assistant's bubble while it works on an answer: three soft dots, /// then what Equipo says it is doing, in the secondary ink, italic, the /// dots still after it; its edge glows teal into violet. (The web's spark /// running round the edge is drawn here as the web's reduced-motion glow.) struct ThinkingBubble: View { let line: String? let maxWidth: CGFloat @Environment(\.colorScheme) private var scheme var body: some View { let p = Palette(scheme) let shape = UnevenRoundedRectangle(topLeadingRadius: 14, bottomLeadingRadius: 4, bottomTrailingRadius: 14, topTrailingRadius: 14, style: .continuous) HStack(spacing: 5) { if let line { Text(verbatim: line).font(BaseFont.body(15)).italic().foregroundStyle(p[.haze]).lineLimit(1) ThinkingDots().accessibilityHidden(true) } else { ThinkingDots().accessibilityLabel(Text(BaseText.text("ask.thinking_a11y"))) } } .frame(minHeight: 22) .padding(.vertical, 10).padding(.horizontal, 14) .background(p[.theirs], in: shape) .overlay { shape.strokeBorder(LinearGradient(colors: [p[.edgeA], p[.edgeB], p[.spkRose]], startPoint: .leading, endPoint: .trailing), lineWidth: 1.5) .opacity(0.7) } .shadow(color: p[.edgeGlowA].opacity(0.7), radius: 8) .frame(maxWidth: maxWidth, alignment: .leading) .accessibilityElement(children: .combine) } } /// Three dots, each lifting and brightening a beat after the last while /// their colour drifts through teal, violet and rose; still with Reduce /// Motion (one of each). struct ThinkingDots: View { @Environment(\.colorScheme) private var scheme @Environment(\.accessibilityReduceMotion) private var reduceMotion @Environment(\.skyFrozen) private var frozen var body: some View { let p = Palette(scheme) let colours = [p[.edgeA], p[.edgeB], p[.spkRose]] if reduceMotion || frozen { HStack(spacing: 6) { ForEach(0..<3, id: \.self) { Circle().fill(colours[$0]).frame(width: 6, height: 6).opacity(0.85) } } } else { TimelineView(.animation(minimumInterval: 1.0 / 30)) { timeline in let t = timeline.date.timeIntervalSinceReferenceDate HStack(spacing: 6) { ForEach(0..<3, id: \.self) { i in // think-dot: 1.4 s, peaking at 35%, each 0.18 s after the last. let phase = ((t - Double(i) * 0.18).truncatingRemainder(dividingBy: 1.4) + 1.4).truncatingRemainder(dividingBy: 1.4) / 1.4 let lift = phase < 0.35 ? SkyPainter.easeInOut(phase / 0.35) : phase < 0.7 ? SkyPainter.easeInOut(1 - (phase - 0.35) / 0.35) : 0 let hue = Int(((t + Double(i) * 1.4) / 1.4).rounded(.down)) % 3 Circle().fill(colours[hue]).frame(width: 6, height: 6) .scaleEffect(0.85 + 0.15 * lift).offset(y: -2 * lift).opacity(0.45 + 0.55 * lift) } } } } } }