oficina / base Public

Clone
git clone https://amadan.net/oficina/base

Plain git — no account needed to clone.

Download

Download this file

1import SwiftUI
2
3/// How wide the thread's bubbles may grow: 86% of the thread on the Mac
4/// and in the menu-bar panel, 92% on the iPhone (app.css `.msg`).
5public enum AskLayout: Sendable { case window, panel, phone
6 var bubbleShare: CGFloat { self == .phone ? 0.92 : 0.86 }
7 var padding: EdgeInsets {
8 switch self {
9 case .window: EdgeInsets(top: 18, leading: 24, bottom: 18, trailing: 24)
10 case .panel, .phone: EdgeInsets(top: 14, leading: 12, bottom: 8, trailing: 12)
11 }
12 }
13}
14
15/// The conversation (chat.html `.thread`): its lines, pills and cards from
16/// AskModel, newest at the foot. It follows the newest line while the
17/// person is at (or within 80 pt of) the foot; scrolled up to read, it
18/// stays put and Jump to latest appears when something new arrives.
19struct AskThread: View {
20 @Bindable var model: AskModel
21 let layout: AskLayout
22 let timeZone: TimeZone?
23 @State private var transcript = MarkdownTranscript()
24 @State private var position = ScrollPosition(edge: .bottom)
25 @State private var pinned = true
26 @State private var unseen = false
27 @State private var width: CGFloat = 600
28 @Environment(\.colorScheme) private var scheme
29
30 var body: some View {
31 let p = Palette(scheme)
32 ScrollView {
33 LazyVStack(alignment: .leading, spacing: 10) {
34 ForEach(model.entries) { entry in
35 row(entry)
36 }
37 }
38 .padding(layout.padding)
39 .frame(maxWidth: .infinity, alignment: .leading)
40 }
41 .scrollPosition($position)
42 .defaultScrollAnchor(.bottom)
43 .defaultScrollAnchor(.bottom, for: .sizeChanges)
44 .onScrollGeometryChange(for: Bool.self) { geo in
45 geo.contentSize.height - geo.visibleRect.maxY < 80
46 } action: { _, atFoot in
47 pinned = atFoot
48 if atFoot { unseen = false }
49 }
50 .onChange(of: model.entries) {
51 if pinned { position.scrollTo(edge: .bottom) } else { unseen = true }
52 }
53 .onGeometryChange(for: CGFloat.self) { $0.size.width } action: { width = $0 }
54 // Scrolled to its newest, the thread fades out under the header.
55 .mask {
56 VStack(spacing: 0) {
57 LinearGradient(colors: [.clear, .black], startPoint: .top, endPoint: .bottom).frame(height: 56)
58 Color.black
59 }
60 }
61 .overlay(alignment: .bottom) {
62 if unseen {
63 Button {
64 position.scrollTo(edge: .bottom)
65 unseen = false
66 } label: {
67 Text(BaseText.text("ask.jump"))
68 .font(BaseFont.body(13, .semibold, relativeTo: .footnote))
69 .foregroundStyle(p[.onSignal])
70 .padding(.horizontal, 14).frame(minHeight: 36)
71 .background(p[.signal], in: Capsule())
72 .shadow(color: p[.glassShadow].opacity(0.5), radius: 9, y: 6)
73 }
74 .buttonStyle(.plain)
75 .padding(.bottom, 10)
76 }
77 }
78 .accessibilityElement(children: .contain)
79 .accessibilityLabel(Text(BaseText.text("ask.conversation_a11y")))
80 }
81
82 private var bubbleWidth: CGFloat {
83 max(120, (width - layout.padding.leading - layout.padding.trailing) * layout.bubbleShare)
84 }
85
86 @ViewBuilder private func row(_ entry: AskModel.Entry) -> some View {
87 switch entry {
88 case .message(let m):
89 Bubble(person: m.isPerson, maxWidth: bubbleWidth) {
90 let parts = PersonBubble.parts(m)
91 VStack(alignment: .leading, spacing: 4) {
92 // The person's own words take the web's little Markdown
93 // (PersonMarkdown); with none, they are exactly as written.
94 if !parts.showsText {
95 EmptyView()
96 } else if m.isPerson, case let nodes = PersonMarkdown.parse(m.text), !PersonMarkdown.isPlain(nodes) {
97 BaseMarkdownView(person: nodes, id: m.id, transcript: transcript)
98 } else if m.isPerson {
99 Text(verbatim: m.text).font(BaseFont.body(15)).fixedSize(horizontal: false, vertical: true)
100 } else {
101 BaseMarkdownView(m.text, draft: false, id: m.id, transcript: transcript)
102 }
103 // What the Assistant looked up, after its words.
104 ForEach(Array(m.lookups.enumerated()), id: \.offset) { i, lookup in
105 LookupView(lookup: lookup, id: m.id + ":lookup:\(i)", transcript: transcript)
106 }
107 if let names = parts.names {
108 FilesLine(names: names)
109 }
110 }
111 }
112 case .draft(let d):
113 Bubble(person: false, maxWidth: bubbleWidth) {
114 VStack(alignment: .leading, spacing: 4) {
115 if !d.text.isEmpty { BaseMarkdownView(d.text, draft: !d.settled, id: "draft:" + d.turnID, transcript: transcript) }
116 if !d.settled { Caret() }
117 }
118 }
119 .accessibilityElement(children: .combine)
120 case .thinking(let t):
121 ThinkingBubble(line: t.line, maxWidth: bubbleWidth)
122 case .job(let job) where layout == .panel && (job.state == .asking || job.state == .stopped):
123 EmptyView() // the panel shows them at its top (WaitingJobs)
124 case .job(let job):
125 JobPill(job: job, busy: model.answering, timeZone: timeZone, carryOn: { card in Task { await model.carryOn(card) } },
126 carryOnErrors: model.carryOnErrors) { card, option in
127 Task { await model.answer(card, option) }
128 }
129 case .card(let card):
130 CardView(card: card, busy: model.answering.contains(card.id)) { option in
131 Task { await model.answer(card, option) }
132 }
133 case .offer(let offer):
134 OfferView(offer: offer)
135 }
136 }
137}
138
139/// What a person's bubble shows until the app draws files (slice 2, plan
140/// P9): their words, then one plain line of their files' names, so a
141/// message of files alone is never an empty bubble.
142enum PersonBubble {
143 struct Parts: Equatable { var showsText: Bool; var names: String? }
144 static func parts(_ m: AskMessage) -> Parts {
145 let names = m.attachments.map(\.name).filter { !$0.isEmpty }
146 let hasText = !m.text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
147 return Parts(showsText: hasText || names.isEmpty, names: names.isEmpty ? nil : names.joined(separator: ", "))
148 }
149}
150
151/// The names line: a paperclip and the files' names, in the secondary
152/// ink; VoiceOver reads "Attached: …".
153struct FilesLine: View {
154 let names: String
155 @Environment(\.colorScheme) private var scheme
156 var body: some View {
157 HStack(alignment: .firstTextBaseline, spacing: 5) {
158 Image(systemName: "paperclip").font(BaseFont.body(12, relativeTo: .footnote)).accessibilityHidden(true)
159 Text(verbatim: names).font(BaseFont.body(13, relativeTo: .footnote)).fixedSize(horizontal: false, vertical: true)
160 }
161 .foregroundStyle(Palette(scheme)[.haze])
162 .accessibilityElement(children: .ignore)
163 .accessibilityLabel(Text(BaseText.format("ask.files_line_a11y", ["names": names])))
164 }
165}
166
167/// A lookup under the Assistant's reply (chat.html `ask-lookup`): its
168/// answer (LookupMarkdown, never a link), then a quiet Sources line with
169/// each source's title as a link and its host after it.
170struct LookupView: View {
171 let lookup: AskLookup
172 let id: String
173 let transcript: MarkdownTranscript
174 @Environment(\.colorScheme) private var scheme
175
176 var body: some View {
177 VStack(alignment: .leading, spacing: 6) {
178 BaseMarkdownView(person: LookupMarkdown.parse(lookup.answer), id: id, transcript: transcript)
179 Text(Self.sources(lookup.sources, label: BaseText.text("ask.sources"), palette: Palette(scheme)))
180 .font(BaseFont.body(13.5, relativeTo: .footnote))
181 .foregroundStyle(Palette(scheme)[.haze])
182 .fixedSize(horizontal: false, vertical: true)
183 }
184 .padding(.top, 6)
185 }
186
187 /// The Sources line: the label, then each source's title (a link,
188 /// opening in the browser) and its host.
189 static func sources(_ sources: [AskSource], label: String, palette p: Palette) -> AttributedString {
190 var line = AttributedString(label)
191 line.font = BaseFont.body(13.5, .medium, relativeTo: .footnote)
192 for s in sources {
193 guard let url = s.url else { continue }
194 var title = AttributedString(s.label)
195 title.link = url
196 title.foregroundColor = p[.focus]
197 title.underlineStyle = .single
198 var host = AttributedString(" " + s.host)
199 host.font = BaseFont.body(12.5, relativeTo: .footnote)
200 line += AttributedString(" ") + title + host
201 }
202 return line
203 }
204}
205
206/// A line of the conversation: the person's on the right in teal, the
207/// Assistant's on the left, each with one tucked corner (app.css `.msg`).
208struct Bubble<Content: View>: View {
209 let person: Bool
210 let maxWidth: CGFloat
211 @ViewBuilder let content: Content
212 @Environment(\.colorScheme) private var scheme
213
214 var body: some View {
215 let p = Palette(scheme)
216 let shape = UnevenRoundedRectangle(topLeadingRadius: 14, bottomLeadingRadius: person ? 14 : 4,
217 bottomTrailingRadius: person ? 4 : 14, topTrailingRadius: 14, style: .continuous)
218 content
219 .foregroundStyle(p[.frost])
220 .padding(.vertical, 10).padding(.horizontal, 14)
221 .background(person ? p[.mine] : p[.theirs], in: shape)
222 .overlay { shape.strokeBorder(person ? p[.mineEdge] : p[.theirsEdge], lineWidth: 1) }
223 .frame(maxWidth: maxWidth, alignment: person ? .trailing : .leading)
224 .frame(maxWidth: .infinity, alignment: person ? .trailing : .leading)
225 }
226}
227
228/// The streaming reply's caret: a block of the accent that blinks (steps,
229/// 1 s); still with Reduce Motion.
230struct Caret: View {
231 @Environment(\.colorScheme) private var scheme
232 @Environment(\.accessibilityReduceMotion) private var reduceMotion
233 @Environment(\.skyFrozen) private var frozen
234 var body: some View {
235 let block = Rectangle().fill(Palette(scheme)[.signal]).frame(width: 7, height: 15)
236 Group {
237 if reduceMotion || frozen {
238 block
239 } else {
240 TimelineView(.periodic(from: .now, by: 0.5)) { timeline in
241 block.opacity(Int(timeline.date.timeIntervalSinceReferenceDate * 2) % 2 == 0 ? 1 : 0)
242 }
243 }
244 }
245 .accessibilityHidden(true)
246 }
247}
248
249/// The Assistant's bubble while it works on an answer: three soft dots,
250/// then what Equipo says it is doing, in the secondary ink, italic, the
251/// dots still after it; its edge glows teal into violet. (The web's spark
252/// running round the edge is drawn here as the web's reduced-motion glow.)
253struct ThinkingBubble: View {
254 let line: String?
255 let maxWidth: CGFloat
256 @Environment(\.colorScheme) private var scheme
257
258 var body: some View {
259 let p = Palette(scheme)
260 let shape = UnevenRoundedRectangle(topLeadingRadius: 14, bottomLeadingRadius: 4, bottomTrailingRadius: 14, topTrailingRadius: 14, style: .continuous)
261 HStack(spacing: 5) {
262 if let line {
263 Text(verbatim: line).font(BaseFont.body(15)).italic().foregroundStyle(p[.haze]).lineLimit(1)
264 ThinkingDots().accessibilityHidden(true)
265 } else {
266 ThinkingDots().accessibilityLabel(Text(BaseText.text("ask.thinking_a11y")))
267 }
268 }
269 .frame(minHeight: 22)
270 .padding(.vertical, 10).padding(.horizontal, 14)
271 .background(p[.theirs], in: shape)
272 .overlay {
273 shape.strokeBorder(LinearGradient(colors: [p[.edgeA], p[.edgeB], p[.spkRose]], startPoint: .leading, endPoint: .trailing), lineWidth: 1.5)
274 .opacity(0.7)
275 }
276 .shadow(color: p[.edgeGlowA].opacity(0.7), radius: 8)
277 .frame(maxWidth: maxWidth, alignment: .leading)
278 .accessibilityElement(children: .combine)
279 }
280}
281
282/// Three dots, each lifting and brightening a beat after the last while
283/// their colour drifts through teal, violet and rose; still with Reduce
284/// Motion (one of each).
285struct ThinkingDots: View {
286 @Environment(\.colorScheme) private var scheme
287 @Environment(\.accessibilityReduceMotion) private var reduceMotion
288 @Environment(\.skyFrozen) private var frozen
289 var body: some View {
290 let p = Palette(scheme)
291 let colours = [p[.edgeA], p[.edgeB], p[.spkRose]]
292 if reduceMotion || frozen {
293 HStack(spacing: 6) { ForEach(0..<3, id: \.self) { Circle().fill(colours[$0]).frame(width: 6, height: 6).opacity(0.85) } }
294 } else {
295 TimelineView(.animation(minimumInterval: 1.0 / 30)) { timeline in
296 let t = timeline.date.timeIntervalSinceReferenceDate
297 HStack(spacing: 6) {
298 ForEach(0..<3, id: \.self) { i in
299 // think-dot: 1.4 s, peaking at 35%, each 0.18 s after the last.
300 let phase = ((t - Double(i) * 0.18).truncatingRemainder(dividingBy: 1.4) + 1.4).truncatingRemainder(dividingBy: 1.4) / 1.4
301 let lift = phase < 0.35 ? SkyPainter.easeInOut(phase / 0.35) : phase < 0.7 ? SkyPainter.easeInOut(1 - (phase - 0.35) / 0.35) : 0
302 let hue = Int(((t + Double(i) * 1.4) / 1.4).rounded(.down)) % 3
303 Circle().fill(colours[hue]).frame(width: 6, height: 6)
304 .scaleEffect(0.85 + 0.15 * lift).offset(y: -2 * lift).opacity(0.45 + 0.55 * lift)
305 }
306 }
307 }
308 }
309 }
310}
311