Repository Public
1//2// SP Chat iOS3// File: SPChat-iOS/Features/Images/ImageStudioView.swift4// Description: Image studio: gallery of the images generated on the account, a floating prompt composer (model, size,5// quality — the options the server accepts), real generation and editing, full screen, share, delete.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9//1011import QuickLook12import SwiftUI1314struct ImageStudioView: View {15 @Environment(AppEnvironment.self) private var env16 @Environment(\.dismiss) private var dismiss17 @Environment(\.accessibilityReduceMotion) private var reduceMotion18 @State private var images: [GeneratedImage] = []19 @State private var hasLoaded = false20 @State private var error: String?21 @State private var prompt = ""22 @State private var modelId = ""23 @State private var size = ImageOptions.sizes[0]24 @State private var quality = "medium"25 @State private var editing: GeneratedImage?26 @State private var busy = false27 @State private var lastCost: String?28 @State private var selected: GeneratedImage?29 @FocusState private var focused: Bool3031 private var imageModels: [AIModel] { env.catalog.models.filter { $0.kind == "image" && $0.available && !$0.hidden } }32 private var chosenModel: String { !modelId.isEmpty ? modelId : (imageModels.first { $0.id == "gpt-image-1.5" }?.id ?? imageModels.first?.id ?? "") }33 private var canGenerate: Bool { !busy && !prompt.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty && env.network.isOnline }3435 var body: some View {36 NavigationStack {37 ScrollView {38 LazyVGrid(columns: [GridItem(.adaptive(minimum: 150, maximum: 260), spacing: 10)], spacing: 10) {39 if busy { generatingTile }40 ForEach(images) { img in41 Button { selected = img } label: { StudioThumbnail(image: img) }42 .buttonStyle(PressScale(scale: 0.97))43 .contextMenu { menu(for: img) }44 .accessibilityLabel(String(localized: "Image : \(img.prompt ?? img.filename)"))45 .accessibilityIdentifier("images.tile")46 .transition(.scale(scale: 0.92).combined(with: .opacity))47 }48 }49 .padding(12)50 .animation(Motion.smooth(reduceMotion), value: images.map(\.id))51 }52 .background(Color.appBackground)53 .scrollDismissesKeyboard(.interactively)54 .overlay {55 if !hasLoaded { ProgressView() }56 else if images.isEmpty && !busy {57 ContentUnavailableView { Label("Aucune image", systemImage: "photo.on.rectangle.angled") } description: { Text(error ?? String(localized: "Décris l’image à créer ci-dessous. Les images produites dans les conversations apparaissent ici aussi.")) }58 }59 }60 .safeAreaInset(edge: .bottom, spacing: 0) { composer }61 .navigationTitle("Studio d’images").navigationBarTitleDisplayMode(.inline)62 .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Fermer") { dismiss() } } }63 .sheet(item: $selected) { img in64 ImageDetailSheet(image: img, onEdit: { startEditing(img) }, onReuse: { prompt = img.prompt ?? ""; focused = true }, onDelete: { await delete(img) })65 }66 .task { await load() }67 .refreshable { await load() }68 }69 .accessibilityIdentifier("images.screen")70 }7172 private func load() async {73 do { images = try await env.api.generatedImages(); error = nil }74 catch { if images.isEmpty { self.error = (error as? APIError)?.message ?? String(localized: "Galerie indisponible.") } }75 hasLoaded = true76 }7778 private func startEditing(_ img: GeneratedImage) {79 withAnimation(Motion.smooth(reduceMotion)) { editing = img }80 focused = true81 }8283 private func delete(_ img: GeneratedImage) async {84 do { try await env.api.deleteAttachment(img.id); withAnimation(Motion.snappy(reduceMotion)) { images.removeAll { $0.id == img.id } }; if editing?.id == img.id { editing = nil } }85 catch { self.error = (error as? APIError)?.message ?? String(localized: "Suppression impossible.") }86 }8788 private func generate() {89 guard canGenerate else { return }90 let text = prompt, target = editing91 focused = false; busy = true; error = nil; lastCost = nil92 env.haptics.tap()93 Task {94 defer { busy = false }95 do {96 let r = try await env.api.generateImage(prompt: text, model: chosenModel.isEmpty ? nil : chosenModel, size: size, quality: quality, editAttachmentId: target?.id)97 prompt = ""; editing = nil98 lastCost = r.costUsd.map { String(localized: "Dernière image : \(Format.usd($0)) estimé · \(r.model ?? "")") }99 env.haptics.success()100 await load()101 } catch let e as APIError {102 if e.kind != .cancelled { error = e.message; env.haptics.warning() }103 } catch { self.error = String(localized: "La génération a échoué.") }104 }105 }106107 @ViewBuilder private func menu(for img: GeneratedImage) -> some View {108 Button { startEditing(img) } label: { Label("Modifier cette image", systemImage: "wand.and.stars") }109 if let p = img.prompt, !p.isEmpty {110 Button { prompt = p; focused = true } label: { Label("Réutiliser le prompt", systemImage: "arrow.uturn.left") }111 Button { UIPasteboard.general.string = p } label: { Label("Copier le prompt", systemImage: "square.on.square") }112 }113 Button(role: .destructive) { Task { await delete(img) } } label: { Label("Supprimer", systemImage: "trash") }114 }115116 private var generatingTile: some View {117 RoundedRectangle(cornerRadius: Radius.card, style: .continuous).fill(Color.surface)118 .aspectRatio(1, contentMode: .fit)119 .overlay { VStack(spacing: 8) { PresenceDots(); Text(editing == nil ? "Génération…" : "Retouche…").font(.caption).foregroundStyle(Color.muted) } }120 .overlay(RoundedRectangle(cornerRadius: Radius.card, style: .continuous).strokeBorder(Color.accentColor.opacity(0.5), lineWidth: 1))121 .accessibilityLabel(String(localized: "Image en cours de génération"))122 .accessibilityIdentifier("images.generating")123 }124125 // MARK: composer126127 private var composer: some View {128 VStack(alignment: .leading, spacing: 6) {129 if let e = error, hasLoaded, !(images.isEmpty && !busy) { Banner(kind: .error, text: e) { error = nil } }130 if let lastCost { Text(lastCost).font(.caption2.monospacedDigit()).foregroundStyle(Color.muted).padding(.horizontal, 6).accessibilityIdentifier("images.cost") }131 VStack(alignment: .leading, spacing: 6) {132 if let target = editing {133 HStack(spacing: 8) {134 StudioThumbnail(image: target, side: 36, corner: 8)135 Text("Retouche de cette image").font(.spCaption).foregroundStyle(Color.textSecondary)136 Spacer(minLength: 0)137 Button { withAnimation(Motion.snappy(reduceMotion)) { editing = nil } } label: { Image(systemName: "xmark.circle.fill").foregroundStyle(Color.muted).frame(width: 40, height: 40).contentShape(.rect) }138 .buttonStyle(.plain).accessibilityLabel(String(localized: "Annuler la retouche"))139 }140 .transition(.opacity.combined(with: .offset(y: 6)))141 }142 TextField(editing == nil ? "Décris l’image à créer" : "Décris la modification", text: $prompt, axis: .vertical)143 .lineLimit(1...5).font(.body).focused($focused)144 .padding(.horizontal, 6).padding(.vertical, 6).frame(minHeight: 36)145 .contentShape(.rect).onTapGesture { focused = true }146 .accessibilityIdentifier("images.prompt")147 HStack(spacing: 6) {148 Menu {149 Picker("Modèle", selection: Binding(get: { chosenModel }, set: { modelId = $0 })) { ForEach(imageModels) { m in Text(m.displayName).tag(m.id) } }150 } label: { option(env.catalog.model(chosenModel)?.displayName ?? String(localized: "Modèle"), "cpu") }151 .accessibilityLabel(String(localized: "Modèle d’image : \(env.catalog.model(chosenModel)?.displayName ?? "—")"))152 .accessibilityIdentifier("images.model")153 if editing == nil {154 Menu {155 Picker("Format", selection: $size) { ForEach(ImageOptions.sizes, id: \.self) { s in Text("\(ImageOptions.sizeLabel(s)) · \(s.replacingOccurrences(of: "x", with: " × "))").tag(s) } }156 } label: { option(ImageOptions.sizeLabel(size), "aspectratio") }157 .accessibilityLabel(String(localized: "Format : \(ImageOptions.sizeLabel(size))")).accessibilityIdentifier("images.size")158 Menu {159 Picker("Qualité", selection: $quality) { ForEach(ImageOptions.qualities, id: \.self) { q in Text(ImageOptions.qualityLabel(q)).tag(q) } }160 } label: { option(ImageOptions.qualityLabel(quality), "sparkles") }161 .accessibilityLabel(String(localized: "Qualité : \(ImageOptions.qualityLabel(quality))")).accessibilityIdentifier("images.quality")162 }163 Spacer(minLength: 2)164 Button(action: generate) {165 Group { if busy { ProgressView().tint(.white) } else { Image(systemName: editing == nil ? "arrow.up" : "wand.and.stars").font(.system(size: 15, weight: .bold)).foregroundStyle(.white) } }166 .frame(width: 34, height: 34).background(canGenerate || busy ? Color.accentColor : Color.muted.opacity(0.5), in: .circle).frame(width: 38, height: 44).contentShape(.rect)167 }168 .buttonStyle(PressScale()).disabled(!canGenerate)169 .accessibilityLabel(editing == nil ? String(localized: "Générer l’image") : String(localized: "Appliquer la retouche"))170 .accessibilityIdentifier("images.generate")171 }172 }173 .padding(.horizontal, 10).padding(.top, 10).padding(.bottom, 8)174 .floatSurface(cornerRadius: Radius.float)175 .overlay(alignment: .top) { LumenLine(active: busy).animation(Motion.fade, value: busy) }176 .animation(Motion.smooth(reduceMotion), value: editing)177 Text("Chaque image est un appel réel au modèle, facturé.").font(.caption2).foregroundStyle(Color.muted).padding(.horizontal, 6)178 }179 .padding(.horizontal, 12).padding(.bottom, 8).padding(.top, 4)180 .frame(maxWidth: 760).frame(maxWidth: .infinity)181 }182183 private func option(_ text: String, _ symbol: String) -> some View {184 HStack(spacing: 4) { Image(systemName: symbol).font(.system(size: 11, weight: .semibold)); Text(text).font(.spCaption).lineLimit(1) }185 .foregroundStyle(Color.textSecondary).padding(.horizontal, 9).frame(minHeight: 32).background(Color.textPrimary.opacity(0.07), in: .capsule).frame(minHeight: 44).contentShape(.rect)186 }187}188189/// A square, downsampled tile of a generated image (authenticated download + disk cache).190struct StudioThumbnail: View {191 let image: GeneratedImage192 var side: CGFloat?193 var corner: CGFloat = Radius.card194 @Environment(AppEnvironment.self) private var env195 @State private var thumb: UIImage?196 @State private var failed = false197198 var body: some View {199 Color.surface2200 .aspectRatio(1, contentMode: .fit)201 .frame(width: side, height: side)202 .overlay {203 if let thumb { Image(uiImage: thumb).resizable().scaledToFill() }204 else if failed { Image(systemName: "photo.badge.exclamationmark").foregroundStyle(Color.muted) }205 else { ProgressView() }206 }207 .overlay(alignment: .bottomLeading) {208 if image.editedFrom != nil, side == nil {209 Text("retouche").font(.spMicro).foregroundStyle(.white).padding(.horizontal, 6).padding(.vertical, 3).background(.black.opacity(0.55), in: .capsule).padding(6)210 }211 }212 .clipShape(.rect(cornerRadius: corner, style: .continuous))213 .overlay(RoundedRectangle(cornerRadius: corner, style: .continuous).strokeBorder(Color.hairline, lineWidth: 0.75))214 .task(id: image.id) {215 let scale = max(UITraitCollection.current.displayScale, 2)216 if let img = await env.files.thumbnail(for: image.id, maxPixel: (side ?? 260) * scale) { thumb = img } else { failed = true }217 }218 }219}220221struct ImageDetailSheet: View {222 let image: GeneratedImage223 let onEdit: () -> Void224 let onReuse: () -> Void225 let onDelete: () async -> Void226 @Environment(AppEnvironment.self) private var env227 @Environment(\.dismiss) private var dismiss228 @State private var full: UIImage?229 @State private var fileURL: URL?230 @State private var previewURL: URL?231 @State private var confirmDelete = false232 @State private var error: String?233234 var body: some View {235 NavigationStack {236 ScrollView {237 VStack(alignment: .leading, spacing: 14) {238 Button { previewURL = fileURL } label: {239 Group {240 if let full { Image(uiImage: full).resizable().scaledToFit() }241 else { Color.surface2.aspectRatio(1, contentMode: .fit).overlay { ProgressView() } }242 }243 .clipShape(.rect(cornerRadius: Radius.card, style: .continuous))244 .overlay(RoundedRectangle(cornerRadius: Radius.card, style: .continuous).strokeBorder(Color.hairline, lineWidth: 0.75))245 }246 .buttonStyle(.plain).disabled(fileURL == nil)247 .accessibilityLabel(String(localized: "Afficher en plein écran")).accessibilityIdentifier("images.full")248249 ScrollView(.horizontal, showsIndicators: false) {250 HStack(spacing: 8) {251 Button { dismiss(); onEdit() } label: { ChipLabel(text: String(localized: "Modifier cette image"), systemImage: "wand.and.stars", selected: true).frame(minHeight: 44) }.accessibilityIdentifier("images.edit")252 if let fileURL { ShareLink(item: fileURL) { ChipLabel(text: String(localized: "Partager"), systemImage: "square.and.arrow.up").frame(minHeight: 44) }.accessibilityIdentifier("images.share") }253 if image.prompt?.isEmpty == false { Button { dismiss(); onReuse() } label: { ChipLabel(text: String(localized: "Réutiliser le prompt"), systemImage: "arrow.uturn.left").frame(minHeight: 44) } }254 if let c = image.conversationId { Button { env.open(c); env.router.sheet = nil } label: { ChipLabel(text: String(localized: "Conversation"), systemImage: "bubble.left").frame(minHeight: 44) } }255 }256 .buttonStyle(PressScale())257 }258259 if let p = image.prompt, !p.isEmpty {260 VStack(alignment: .leading, spacing: 6) {261 Text("Prompt").font(.spMicro).foregroundStyle(Color.muted).textCase(.uppercase)262 Text(p).font(.subheadline).foregroundStyle(Color.textPrimary).textSelection(.enabled)263 }264 .padding(14).frame(maxWidth: .infinity, alignment: .leading).cardSurface()265 }266 if let r = image.revisedPrompt, !r.isEmpty, r != image.prompt {267 VStack(alignment: .leading, spacing: 6) {268 Text("Prompt réécrit par le modèle").font(.spMicro).foregroundStyle(Color.muted).textCase(.uppercase)269 Text(r).font(.footnote).foregroundStyle(Color.textSecondary).textSelection(.enabled)270 }271 .padding(14).frame(maxWidth: .infinity, alignment: .leading).cardSurface()272 }273 LazyVGrid(columns: [GridItem(.adaptive(minimum: 104), spacing: 12, alignment: .topLeading)], alignment: .leading, spacing: 14) {274 if let m = image.model, !m.isEmpty { FactCell(title: String(localized: "Modèle"), value: env.catalog.model(m)?.displayName ?? m) }275 if let s = image.size { FactCell(title: String(localized: "Format"), value: s.replacingOccurrences(of: "x", with: " × ")) }276 if let q = image.quality { FactCell(title: String(localized: "Qualité"), value: ImageOptions.qualityLabel(q)) }277 if let d = image.createdAt { FactCell(title: String(localized: "Créée"), value: d.formatted(date: .abbreviated, time: .shortened)) }278 if image.editedFrom != nil { FactCell(title: String(localized: "Origine"), value: String(localized: "retouche")) }279 }280 .padding(14).cardSurface()281 if let error { Banner(kind: .error, text: error) }282 Button(role: .destructive) { confirmDelete = true } label: { Label("Supprimer l’image", systemImage: "trash").frame(maxWidth: .infinity).frame(minHeight: 44) }283 .buttonStyle(.bordered).accessibilityIdentifier("images.delete")284 }285 .padding(16)286 .frame(maxWidth: 720).frame(maxWidth: .infinity)287 }288 .background(Color.appBackground)289 .navigationTitle("Image").navigationBarTitleDisplayMode(.inline)290 .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Fermer") { dismiss() } } }291 .quickLookPreview($previewURL)292 .confirmationDialog("Supprimer cette image ?", isPresented: $confirmDelete, titleVisibility: .visible) {293 Button("Supprimer", role: .destructive) { Task { await onDelete(); dismiss() } }294 } message: { Text("Elle est supprimée du serveur, sur tous tes appareils.") }295 .task(id: image.id) {296 do {297 let url = try await env.files.fileURL(for: image.id, filename: image.filename)298 fileURL = url299 let scale = max(UITraitCollection.current.displayScale, 2)300 full = await env.files.thumbnail(for: image.id, maxPixel: 720 * scale)301 } catch { self.error = (error as? APIError)?.message ?? String(localized: "Image indisponible.") }302 }303 }304 .accessibilityIdentifier("images.detail")305 }306}307