Repository Public
1//2// SP Chat iOS3// File: SPChat-iOS/Components/ChatBubble.swift4// Description: One message of the thread: user bubble or assistant answer with its parts, end state, stats and actions.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8//910import SwiftUI11import UIKit1213struct MessageActions {14 var copy: (ChatMessage) -> Void15 var regenerate: (ChatMessage) -> Void16 /// « Régénérer avec un autre modèle » : nil = let the owner pick in the model sheet.17 var regenerateWith: (ChatMessage, _ modelId: String?) -> Void18 var edit: (ChatMessage) -> Void19 var selectText: (ChatMessage) -> Void20 var speak: (ChatMessage) -> Void21 var fork: (ChatMessage) -> Void22 var lens: (ChatMessage) -> Void23 var details: (ChatMessage) -> Void24 var followUp: (String) -> Void25 var switchVersion: (String) -> Void26 var resolveTools: (ChatMessage, _ approve: [String], _ deny: [String]) -> Void27 var openAttachment: (_ id: String, _ name: String) -> Void28 var openArtifact: (_ id: String) -> Void29}3031/// Who answered: maker logo, exact name, route. Resolved from the catalogue, or from the id when the model left it.32struct ModelIdentity: Equatable, Sendable {33 var logo: String?34 var creatorName: String35 var name: String36 var route: String?3738 init(model: AIModel?, modelId: String?, provider: String?) {39 if let model { logo = model.logo; creatorName = model.creatorName; name = model.displayName; route = model.route; return }40 let id = modelId ?? ""41 if id.hasPrefix("or:") {42 let vendor = String(id.dropFirst(3).prefix { $0 != "/" })43 logo = LogoRegistry.slug(for: vendor); creatorName = AIModel.providerLabel(vendor); name = String(id.dropFirst(3)); route = "openrouter"44 } else if id.hasPrefix("local:") {45 logo = nil; creatorName = AIModel.providerLabel("local"); name = String(id.dropFirst(6)); route = "local"46 } else {47 logo = LogoRegistry.slug(for: provider); creatorName = AIModel.providerLabel(provider); name = id.isEmpty ? String(localized: "Assistant") : id; route = "direct"48 }49 }50}5152struct ChatBubble: View, Equatable {53 let message: ChatMessage54 /// Sibling versions of this message (edit / regenerate history), oldest first.55 let versions: [String]56 let identity: ModelIdentity57 /// Favourite models offered in « régénérer avec » (id, name), at most 5.58 let quickModels: [QuickModel]59 let isLast: Bool60 let canAct: Bool61 let showReasoning: Bool62 let showStats: Bool63 let showFollowUps: Bool64 let isSpeaking: Bool65 let actions: MessageActions6667 struct QuickModel: Equatable, Identifiable { var id: String; var name: String; var route: String }6869 // Rows are compared by value: a token arriving in the last message never re-renders the ones above it.70 nonisolated static func == (a: ChatBubble, b: ChatBubble) -> Bool {71 a.message == b.message && a.versions == b.versions && a.identity == b.identity && a.quickModels == b.quickModels && a.isLast == b.isLast && a.canAct == b.canAct72 && a.showReasoning == b.showReasoning && a.showStats == b.showStats && a.showFollowUps == b.showFollowUps && a.isSpeaking == b.isSpeaking73 }7475 var body: some View {76 Group {77 if message.role == .user { userBubble } else { assistantBlock }78 }79 .accessibilityElement(children: .contain)80 }8182 // MARK: user8384 private var userBubble: some View {85 VStack(alignment: .trailing, spacing: 6) {86 let media = message.parts.filter { if case .text = $0 { return false } else { return true } }87 if !media.isEmpty { AttachmentStrip(parts: media, open: actions.openAttachment).frame(maxWidth: .infinity, alignment: .trailing) }88 if !message.text.isEmpty {89 Text(message.text)90 .font(.body)91 .foregroundStyle(Color.textPrimary)92 .padding(.horizontal, 14).padding(.vertical, 10)93 .background(Color.userBubble, in: .rect(cornerRadius: Radius.bubble, style: .continuous))94 .contentShape(.contextMenuPreview, .rect(cornerRadius: Radius.bubble, style: .continuous))95 .contextMenu { menu }96 }97 if versions.count > 1 { VersionSwitcher(versions: versions, current: message.id, enabled: canAct, select: actions.switchVersion) }98 }99 .frame(maxWidth: .infinity, alignment: .trailing)100 .padding(.leading, 56) // the bubble never spans the whole reading column101 .accessibilityElement(children: .combine)102 .accessibilityLabel(String(localized: "Toi : \(message.text)"))103 }104105 // MARK: assistant106107 private var assistantBlock: some View {108 VStack(alignment: .leading, spacing: 10) {109 header110 ForEach(message.ignoredParams, id: \.param) { i in IncompatibilityNotice(param: i.param, reason: i.reason) }111 if showReasoning, let reasoning = message.reasoningText { ReasoningDisclosure(text: reasoning, streaming: message.isStreaming && message.text.isEmpty) }112113 VStack(alignment: .leading, spacing: 10) {114 ForEach(Array(message.parts.enumerated()), id: \.offset) { _, part in115 partView(part)116 }117 }118 .contextMenu { menu }119120 if message.isStreaming && message.text.isEmpty && !message.parts.contains(where: { if case .toolCall(let t) = $0 { return t.status == .running } else { return false } }) { PresenceDots() }121122 let sources = message.citations123 if !sources.isEmpty { SourceCards(citations: sources) }124125 let pending = message.pendingApprovals126 if !pending.isEmpty && canAct {127 HStack(spacing: 10) {128 Button { actions.resolveTools(message, pending.map(\.id), []) } label: { Label("Autoriser", systemImage: "checkmark.circle.fill") }.buttonStyle(.borderedProminent)129 Button(role: .destructive) { actions.resolveTools(message, [], pending.map(\.id)) } label: { Label("Refuser", systemImage: "xmark.circle") }.buttonStyle(.bordered)130 }131 .controlSize(.regular)132 }133 endState134 if !message.isStreaming { footer }135 if showFollowUps, isLast, canAct, message.status == .complete, !message.followups.isEmpty { FollowUpChips(suggestions: message.followups, send: actions.followUp) }136 }137 .frame(maxWidth: .infinity, alignment: .leading)138 }139140 /// `[ModelMark] name · route · time` — the mark breathes while this answer is being written.141 private var header: some View {142 HStack(spacing: 6) {143 ModelChip(logo: identity.logo, creatorName: identity.creatorName, name: identity.name, route: identity.route, markSize: 16, font: .system(.footnote, weight: .semibold), breathing: message.isStreaming)144 if !message.isStreaming {145 Text(message.createdAt, format: .dateTime.hour().minute()).font(.caption2).foregroundStyle(Color.muted).monospacedDigit()146 }147 Spacer(minLength: 0)148 }149 }150151 @ViewBuilder private func partView(_ part: MessagePart) -> some View {152 switch part {153 case .text(let t):154 if !t.isEmpty { MarkdownView(text: t).foregroundStyle(Color.textPrimary) }155 case .reasoning, .unknown, .citation:156 EmptyView() // reasoning has its disclosure; sources are gathered in one row of cards157 case .image, .file, .generatedImage:158 AttachmentStrip(parts: [part], open: actions.openAttachment)159 case .toolCall(let call):160 ToolCallLine(call: call)161 case .artifact(let id, let title, let type, _):162 Button { actions.openArtifact(id) } label: {163 HStack(spacing: 10) {164 Image(systemName: "doc.richtext").font(.body).foregroundStyle(Color.accentColor)165 VStack(alignment: .leading, spacing: 1) {166 Text(title).font(.subheadline.weight(.semibold)).foregroundStyle(Color.textPrimary).lineLimit(1)167 Text(String(localized: "Artefact · \(type)")).font(.caption).foregroundStyle(Color.muted)168 }169 Spacer(minLength: 0)170 Image(systemName: "chevron.right").font(.footnote.weight(.semibold)).foregroundStyle(Color.muted)171 }172 .padding(12).cardSurface()173 }174 .buttonStyle(PressScale(scale: 0.98))175 }176 }177178 @ViewBuilder private var endState: some View {179 switch message.status {180 case .cancelled:181 Label("Arrêtée", systemImage: "stop.circle").font(.footnote).foregroundStyle(Color.muted)182 case .incomplete:183 VStack(alignment: .leading, spacing: 8) {184 Banner(kind: .warning, text: message.error ?? String(localized: "Réponse incomplète : la génération a été interrompue."))185 if canAct { Button { actions.regenerate(message) } label: { Label("Reprendre", systemImage: "arrow.clockwise") }.buttonStyle(.bordered).controlSize(.small) }186 }187 case .error:188 VStack(alignment: .leading, spacing: 8) {189 Banner(kind: .error, text: message.error ?? String(localized: "La génération a échoué."))190 if canAct {191 HStack(spacing: 8) {192 Button { actions.regenerate(message) } label: { Label("Réessayer", systemImage: "arrow.clockwise") }193 Button { actions.regenerateWith(message, nil) } label: { Label("Autre modèle", systemImage: "arrow.triangle.2.circlepath") }194 }195 .buttonStyle(.bordered).controlSize(.small)196 }197 }198 case .streaming, .complete:199 EmptyView()200 }201 }202203 private var footer: some View {204 VStack(alignment: .leading, spacing: 4) {205 if showStats, message.usage != nil || message.costUsd != nil || message.latencyMs != nil || message.routing?.servedBy != nil {206 HStack(spacing: 8) {207 if let u = message.usage { Text("\(Format.tokens(u.input)) → \(Format.tokens(u.output))").accessibilityLabel(String(localized: "\(u.input) jetons en entrée, \(u.output) en sortie")) }208 if let label = AIModel.costLabel(message.costUsd, exact: message.exactCost, route: identity.route) { Text(label) }209 if let l = message.latencyMs { Text(Format.duration(ms: l)) }210 if let served = message.routing?.servedBy { Text(served).lineLimit(1) }211 }212 .font(.caption2.monospacedDigit()).foregroundStyle(Color.muted).lineLimit(1)213 }214 HStack(spacing: 0) {215 if !message.text.isEmpty {216 iconButton("square.on.square", String(localized: "Copier la réponse")) { actions.copy(message) }217 }218 if canAct {219 Menu {220 Button { actions.regenerate(message) } label: { Label("Régénérer", systemImage: "arrow.clockwise") }221 Section("Régénérer avec") {222 ForEach(quickModels) { q in223 Button { actions.regenerateWith(message, q.id) } label: { Text(q.route == "openrouter" ? "\(q.name) · OpenRouter" : q.route == "local" ? String(localized: "\(q.name) · local") : q.name) }224 }225 Button { actions.regenerateWith(message, nil) } label: { Label("Un autre modèle…", systemImage: "square.stack.3d.up") }226 }227 } label: { iconLabel("arrow.clockwise") } primaryAction: { actions.regenerate(message) }228 .accessibilityLabel(String(localized: "Régénérer"))229 .accessibilityHint(String(localized: "Appui long : régénérer avec un autre modèle"))230 iconButton("arrow.triangle.branch", String(localized: "Bifurquer à partir d’ici")) { actions.fork(message) }231 }232 if !message.text.isEmpty {233 iconButton("camera.filters", String(localized: "Lentilles de réponse")) { actions.lens(message) }234 iconButton(isSpeaking ? "stop.circle.fill" : "speaker.wave.2", isSpeaking ? String(localized: "Arrêter la lecture") : String(localized: "Lire à voix haute")) { actions.speak(message) }235 }236 iconButton("info.circle", String(localized: "Détails de la réponse")) { actions.details(message) }237 if versions.count > 1 { VersionSwitcher(versions: versions, current: message.id, enabled: canAct, select: actions.switchVersion) }238 Spacer(minLength: 0)239 }240 .padding(.leading, -11)241 }242 }243244 private func iconLabel(_ symbol: String) -> some View {245 Image(systemName: symbol).font(.system(size: 14, weight: .medium)).foregroundStyle(Color.textSecondary)246 .frame(width: 40, height: 44).contentShape(.rect)247 }248 private func iconButton(_ symbol: String, _ label: String, action: @escaping () -> Void) -> some View {249 Button(action: action) { iconLabel(symbol) }250 .buttonStyle(PressScale(scale: 0.88))251 .accessibilityLabel(label)252 }253254 // MARK: context menu255256 @ViewBuilder private var menu: some View {257 if !message.text.isEmpty {258 Button { actions.copy(message) } label: { Label("Copier", systemImage: "square.on.square") }259 Button { actions.selectText(message) } label: { Label("Sélectionner le texte", systemImage: "text.cursor") }260 ShareLink(item: message.text) { Label("Partager", systemImage: "square.and.arrow.up") }261 }262 if message.role == .user, canAct, !message.id.hasPrefix("tmp_") {263 Button { actions.edit(message) } label: { Label("Modifier et renvoyer", systemImage: "pencil") }264 }265 if message.role == .assistant, !message.isStreaming {266 if canAct {267 Button { actions.regenerate(message) } label: { Label("Régénérer", systemImage: "arrow.clockwise") }268 Button { actions.regenerateWith(message, nil) } label: { Label("Régénérer avec un autre modèle…", systemImage: "square.stack.3d.up") }269 }270 if !message.text.isEmpty {271 Button { actions.lens(message) } label: { Label("Lentilles de réponse", systemImage: "camera.filters") }272 Button { actions.speak(message) } label: { Label(isSpeaking ? "Arrêter la lecture" : "Lire à voix haute", systemImage: "speaker.wave.2") }273 }274 Button { actions.fork(message) } label: { Label("Bifurquer à partir d’ici…", systemImage: "arrow.triangle.branch") }275 Button { actions.details(message) } label: { Label("Détails de la réponse", systemImage: "info.circle") }276 }277 }278}279280/// « images : ignoré — ce modèle n’accepte pas les images » (from `applied.ignored` of the `start` event).281struct IncompatibilityNotice: View {282 let param: String283 let reason: String284 var body: some View {285 HStack(alignment: .firstTextBaseline, spacing: 6) {286 Image(systemName: "exclamationmark.circle").font(.caption).foregroundStyle(Color.warning)287 (Text(param).fontWeight(.semibold) + Text(String(localized: " ignoré — ")) + Text(reason))288 .font(.caption).foregroundStyle(Color.textSecondary)289 }290 .padding(.horizontal, 10).padding(.vertical, 7)291 .background(Color.warning.opacity(0.10), in: .rect(cornerRadius: Radius.control, style: .continuous))292 .accessibilityElement(children: .combine)293 .accessibilityLabel(String(localized: "Paramètre \(param) ignoré par ce modèle : \(reason)"))294 .accessibilityIdentifier("message.ignored")295 }296}297298/// Sources of a web search: one horizontal row of compact numbered cards (domain in caption, title on two lines).299struct SourceCards: View {300 let citations: [Citation]301 @Environment(\.openURL) private var openURL302303 var body: some View {304 VStack(alignment: .leading, spacing: 6) {305 Label(String(localized: "Sources · \(citations.count)"), systemImage: "globe").font(.spMicro).foregroundStyle(Color.muted).textCase(.uppercase).tracking(0.3)306 ScrollView(.horizontal, showsIndicators: false) {307 HStack(spacing: 8) {308 ForEach(Array(citations.enumerated()), id: \.element.id) { index, c in309 Button { if let u = URL(string: c.url) { openURL(u) } } label: {310 VStack(alignment: .leading, spacing: 5) {311 HStack(spacing: 6) {312 Text("\(index + 1)").font(.system(size: 10, weight: .bold).monospacedDigit()).foregroundStyle(Color.accentColor)313 .frame(minWidth: 16, minHeight: 16).background(Color.accentSoft, in: .rect(cornerRadius: 5, style: .continuous))314 Text(c.domain).font(.caption2.weight(.medium)).foregroundStyle(Color.muted).lineLimit(1)315 }316 Text(c.displayTitle).font(.caption.weight(.medium)).foregroundStyle(Color.textPrimary).lineLimit(2, reservesSpace: true).multilineTextAlignment(.leading)317 }318 .padding(10).frame(width: 178, alignment: .leading)319 .cardSurface()320 }321 .buttonStyle(PressScale(scale: 0.97))322 .contextMenu {323 Button { UIPasteboard.general.string = c.url } label: { Label("Copier le lien", systemImage: "link") }324 if let u = URL(string: c.url) { ShareLink(item: u) { Label("Partager", systemImage: "square.and.arrow.up") } }325 } preview: {326 VStack(alignment: .leading, spacing: 8) {327 Text(c.displayTitle).font(.headline); Text(c.domain).font(.caption).foregroundStyle(Color.muted)328 if let s = c.snippet, !s.isEmpty { Text(s).font(.footnote).foregroundStyle(Color.textSecondary) }329 }.padding(16).frame(width: 300, alignment: .leading)330 }331 .accessibilityLabel(String(localized: "Source \(index + 1) : \(c.displayTitle), \(c.domain)"))332 .accessibilityHint(String(localized: "Ouvre la page dans le navigateur"))333 .accessibilityIdentifier("message.source")334 }335 }336 .padding(.vertical, 1)337 }338 .scrollClipDisabled()339 }340 }341}342343/// Smart Follow-Ups: the server's suggestions, sent as the next message when tapped.344struct FollowUpChips: View {345 let suggestions: [String]346 let send: (String) -> Void347 var body: some View {348 VStack(alignment: .leading, spacing: 6) {349 ForEach(suggestions, id: \.self) { s in350 Button { send(s) } label: {351 HStack(spacing: 8) {352 Image(systemName: "arrow.turn.down.right").font(.system(size: 11, weight: .semibold)).foregroundStyle(Color.accentColor)353 Text(s).font(.subheadline).foregroundStyle(Color.textPrimary).multilineTextAlignment(.leading)354 Spacer(minLength: 0)355 }356 .padding(.horizontal, 12).padding(.vertical, 9).frame(minHeight: 44)357 .cardSurface(cornerRadius: Radius.card)358 }359 .buttonStyle(PressScale(scale: 0.98))360 .accessibilityHint(String(localized: "Envoie cette question"))361 .accessibilityIdentifier("message.followup")362 }363 }364 .padding(.top, 2)365 .transition(.opacity.combined(with: .offset(y: 6)))366 }367}368369struct VersionSwitcher: View {370 let versions: [String]371 let current: String372 let enabled: Bool373 let select: (String) -> Void374375 var body: some View {376 let index = versions.firstIndex(of: current) ?? versions.count - 1377 HStack(spacing: 0) {378 Button { select(versions[index - 1]) } label: { Image(systemName: "chevron.left").frame(width: 36, height: 36).contentShape(.rect) }379 .disabled(!enabled || index == 0).accessibilityLabel(String(localized: "Version précédente"))380 Text("\(index + 1) / \(versions.count)").font(.caption.monospacedDigit()).accessibilityLabel(String(localized: "Version \(index + 1) sur \(versions.count)"))381 Button { select(versions[index + 1]) } label: { Image(systemName: "chevron.right").frame(width: 36, height: 36).contentShape(.rect) }382 .disabled(!enabled || index >= versions.count - 1).accessibilityLabel(String(localized: "Version suivante"))383 }384 .font(.footnote.weight(.semibold)).foregroundStyle(Color.textSecondary).buttonStyle(.plain)385 }386}387388struct ReasoningDisclosure: View {389 let text: String390 let streaming: Bool391 @State private var expanded = false392393 var body: some View {394 VStack(alignment: .leading, spacing: 8) {395 Button { withAnimation(.snappy(duration: 0.22)) { expanded.toggle() } } label: {396 HStack(spacing: 6) {397 Image(systemName: "brain").symbolEffect(.pulse, isActive: streaming)398 Text(streaming ? "Raisonnement en cours…" : "Raisonnement")399 Image(systemName: "chevron.right").font(.caption2.weight(.bold)).rotationEffect(.degrees(expanded ? 90 : 0))400 }401 .font(.footnote.weight(.medium)).foregroundStyle(Color.muted)402 .frame(minHeight: 32).contentShape(.rect)403 }404 .buttonStyle(.plain)405 .accessibilityHint(expanded ? String(localized: "Masquer le raisonnement") : String(localized: "Afficher le raisonnement"))406 if expanded {407 Text(text).font(.footnote).foregroundStyle(Color.textSecondary)408 .padding(12).frame(maxWidth: .infinity, alignment: .leading)409 .background(Color.surface2, in: .rect(cornerRadius: 12, style: .continuous))410 .transition(.opacity)411 }412 }413 }414}415416/// One line per tool call — « web_search · query » with a state dot (running pulse → ok / error) — expandable.417struct ToolCallLine: View {418 let call: ToolCall419 @State private var expanded = false420 @Environment(\.accessibilityReduceMotion) private var reduceMotion421422 private var label: String {423 switch call.name {424 case "web_search": String(localized: "Recherche web")425 case "fetch_page": String(localized: "Lecture d’une page")426 case "python": String(localized: "Exécution Python")427 case "search_documents": String(localized: "Recherche dans les documents")428 case "generate_image": String(localized: "Génération d’image")429 case "save_memory": String(localized: "Mémoire")430 default: call.name431 }432 }433 private var symbol: String {434 switch call.name { case "web_search": "magnifyingglass"; case "fetch_page": "globe"; case "python": "terminal"; case "search_documents": "doc.text.magnifyingglass"; case "generate_image": "photo"; case "save_memory": "brain.head.profile"; default: "wrench.and.screwdriver" }435 }436 private var summary: String? {437 (call.input["query"] ?? call.input["url"] ?? call.input["prompt"] ?? call.input["content"])?.stringValue438 }439440 var body: some View {441 VStack(alignment: .leading, spacing: 8) {442 Button { withAnimation(Motion.snappy(reduceMotion)) { expanded.toggle() } } label: {443 HStack(spacing: 8) {444 stateDot445 Image(systemName: symbol).font(.system(size: 12, weight: .medium)).foregroundStyle(Color.textSecondary)446 Text(label).font(.footnote.weight(.medium)).foregroundStyle(Color.textPrimary).layoutPriority(1)447 if let summary { Text("· \(summary)").font(.footnote).foregroundStyle(Color.muted).lineLimit(1) }448 Spacer(minLength: 4)449 if call.status == .ok, let d = call.durationMs { Text(Format.duration(ms: d)).font(.caption2.monospacedDigit()).foregroundStyle(Color.muted) }450 Image(systemName: "chevron.right").font(.system(size: 9, weight: .bold)).foregroundStyle(Color.muted).rotationEffect(.degrees(expanded ? 90 : 0))451 }452 .frame(minHeight: 36).contentShape(.rect)453 }454 .buttonStyle(.plain)455 if expanded {456 VStack(alignment: .leading, spacing: 8) {457 detail(String(localized: "Entrée"), call.input.prettyPrinted(limit: 3000))458 if let out = call.output, !out.isNull { detail(String(localized: "Résultat"), out.prettyPrinted(limit: 6000)) }459 if let e = call.error { Text(e).font(.caption).foregroundStyle(Color.danger) }460 }461 .padding(.bottom, 8)462 .transition(.opacity)463 }464 }465 .padding(.horizontal, 12)466 .background(Color.surface2.opacity(0.6), in: .rect(cornerRadius: Radius.control, style: .continuous))467 .accessibilityElement(children: .combine)468 .accessibilityLabel("\(label), \(statusText)")469 .accessibilityIdentifier("message.tool")470 }471472 private func detail(_ title: String, _ body: String) -> some View {473 VStack(alignment: .leading, spacing: 4) {474 Text(title).font(.spMicro).foregroundStyle(Color.muted).textCase(.uppercase)475 ScrollView(.horizontal, showsIndicators: false) {476 Text(body).font(.system(.caption, design: .monospaced)).foregroundStyle(Color.textSecondary).fixedSize(horizontal: true, vertical: true)477 }478 .frame(maxHeight: 220)479 }480 }481482 private var statusText: String {483 switch call.status {484 case .running: String(localized: "en cours"); case .ok: String(localized: "terminé"); case .error: String(localized: "erreur")485 case .denied: String(localized: "refusé"); case .pendingApproval: String(localized: "en attente d’autorisation")486 }487 }488 private var stateDot: some View {489 let color: Color = switch call.status { case .running: .accentColor; case .ok: .success; case .error: .danger; case .denied: .muted; case .pendingApproval: .warning }490 return Circle().fill(color).frame(width: 7, height: 7)491 .phaseAnimator(call.status == .running && !reduceMotion ? [1.0, 0.35] : [1.0]) { v, o in v.opacity(o) } animation: { _ in .easeInOut(duration: 0.7) }492 }493}494495struct AttachmentStrip: View {496 let parts: [MessagePart]497 let open: (_ id: String, _ name: String) -> Void498499 var body: some View {500 VStack(alignment: .leading, spacing: 8) {501 ForEach(Array(parts.enumerated()), id: \.offset) { _, part in502 switch part {503 case .image(let id, _, let name):504 RemoteImage(attachmentId: id, maxHeight: 240).onTapGesture { open(id, name ?? "image.jpg") }505 .accessibilityLabel(String(localized: "Image \(name ?? "")")).accessibilityAddTraits(.isButton)506 case .generatedImage(let id, let prompt, _):507 RemoteImage(attachmentId: id, maxHeight: 320).onTapGesture { open(id, "image.png") }508 .accessibilityLabel(String(localized: "Image générée : \(prompt)")).accessibilityAddTraits(.isButton)509 case .file(let id, _, let name, let size, let pages):510 Button { open(id, name) } label: {511 HStack(spacing: 10) {512 Image(systemName: "doc.fill").font(.title3).foregroundStyle(Color.accentColor)513 VStack(alignment: .leading, spacing: 1) {514 Text(name).font(.subheadline.weight(.medium)).foregroundStyle(Color.textPrimary).lineLimit(1)515 Text([Format.bytes(size), pages.map { String(localized: "\($0) pages") }].compactMap { $0 }.filter { !$0.isEmpty }.joined(separator: " · ")).font(.caption).foregroundStyle(Color.muted)516 }517 }518 .padding(.horizontal, 12).padding(.vertical, 9)519 .background(Color.surface2, in: .rect(cornerRadius: 12, style: .continuous))520 }521 .buttonStyle(.plain)522 default: EmptyView()523 }524 }525 }526 }527}528529/// An attachment image loaded through the authenticated API and the on-disk cache, decoded at display size.530struct RemoteImage: View {531 let attachmentId: String532 var maxHeight: CGFloat = 240533 @Environment(AppEnvironment.self) private var env534 @State private var image: UIImage?535 @State private var failed = false536537 var body: some View {538 Group {539 if let image {540 Image(uiImage: image).resizable().scaledToFit()541 .frame(maxWidth: min(image.size.width, 420), maxHeight: maxHeight)542 .clipShape(.rect(cornerRadius: 14, style: .continuous))543 } else {544 RoundedRectangle(cornerRadius: 14, style: .continuous).fill(Color.surface2)545 .frame(width: 180, height: 130)546 .overlay { if failed { Image(systemName: "photo.badge.exclamationmark").foregroundStyle(Color.muted) } else { ProgressView() } }547 }548 }549 .task(id: attachmentId) {550 let scale = UITraitCollection.current.displayScale551 if let img = await env.files.thumbnail(for: attachmentId, maxPixel: 420 * max(scale, 2)) { image = img } else { failed = true }552 }553 }554}555