SPB Git

Repository Public

StudioViews.swift 18.1 KB 335 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Sources/Shared/Studio/StudioViews.swift3// Description: Template studio « Modèles » — root (library or editor), library grid with live thumbnails, search / filter / sort, delete with undo,4// and « Créer avec l’IA » (starter briefs, brand kit, honest progress, cancel, specific errors). Models are passed explicitly, never through the environment.5import SPMailCore6import SwiftUI78struct StudioRoot: View {9    @Bindable var studio: StudioModel10    /// iOS / iPadOS: closes the full-screen cover. macOS: nil (the studio is its own window).11    var onClose: (() -> Void)?12    @Environment(\.scenePhase) private var scenePhase1314    var body: some View {15        NavigationStack {16            Group {17                if let editor = studio.current { EditorView(editor: editor, studio: studio).id(editor.id) } else { LibraryView(studio: studio, onClose: onClose) }18            }19        }20        .overlay(alignment: .bottom) { StudioBanner(studio: studio) }21        .sheet(isPresented: $studio.showGenerator) {22            NavigationStack { GeneratorView(studio: studio) }23                #if os(macOS)24                .frame(minWidth: 620, idealWidth: 680, minHeight: 620, idealHeight: 700)25                #endif26                .interactiveDismissDisabled(studio.generation.isRunning)27        }28        .task { if !studio.loaded { await studio.reload() } }29        .onChange(of: scenePhase) { _, phase in if phase == .active { Task { await studio.didBecomeActive() } } }30        .environment(\.spMidnight, studio.app?.settings.theme == .midnight)31        .preferredColorScheme(studio.app?.settings.colorScheme)32    }33}3435/// Bottom banner: « Annuler » after a delete, and short notices.36struct StudioBanner: View {37    @Bindable var studio: StudioModel38    var body: some View {39        VStack(spacing: 8) {40            if let t = studio.undo {41                HStack(spacing: 12) {42                    Text("« \(t.name) » supprimé").lineLimit(1)43                    Button("Annuler") { Task { await studio.undoDelete() } }.buttonStyle(.borderedProminent).controlSize(.small).keyboardShortcut("z", modifiers: .command)44                }45                .font(.callout).padding(.horizontal, 14).padding(.vertical, 8).background(.regularMaterial, in: Capsule()).shadow(radius: 4, y: 2)46                .accessibilityElement(children: .contain)47            }48            if let n = studio.notice {49                Text(n).font(.callout).padding(.horizontal, 14).padding(.vertical, 9).background(.regularMaterial, in: Capsule()).shadow(radius: 4, y: 2)50                    .task(id: n) { try? await Task.sleep(for: .seconds(4)); if studio.notice == n { studio.notice = nil } }51                    .onTapGesture { studio.notice = nil }52            }53        }54        .padding(.bottom, 14)55        .animation(.default, value: studio.undo?.id)56    }57}5859// MARK: - library6061struct LibraryView: View {62    @Bindable var studio: StudioModel63    var onClose: (() -> Void)?64    @Environment(\.horizontalSizeClass) private var sizeClass65    @State private var deleting: MailTemplate?6667    var body: some View {68        let list = studio.filtered69        Group {70            if !studio.loaded {71                if let e = studio.loadError {72                    ContentUnavailableView { Label("Bibliothèque indisponible", systemImage: "wifi.slash") } description: { Text(e) } actions: { Button("Réessayer") { Task { await studio.reload() } } }73                } else { ProgressView().controlSize(.large).frame(maxWidth: .infinity, maxHeight: .infinity) }74            } else if studio.templates.isEmpty {75                ContentUnavailableView {76                    Label("Aucun modèle", systemImage: "rectangle.3.group")77                } description: {78                    Text("Décrivez le courriel voulu : l’IA rédige et met en page un modèle complet, que vous retouchez ensuite. Ou partez d’un modèle vierge.")79                } actions: {80                    Button { studio.showGenerator = true } label: { Label("Créer avec l’IA", systemImage: "sparkles") }.buttonStyle(.borderedProminent)81                    Button("Modèle vierge") { Task { await studio.createBlank() } }82                }83            } else if list.isEmpty {84                ContentUnavailableView.search(text: studio.search)85            } else if sizeClass == .compact {86                List(list) { t in87                    Button { Task { await studio.open(t.id) } } label: { TemplateRowCompact(template: t, api: studio.api) }88                        .buttonStyle(.plain)89                        .swipeActions(edge: .trailing) {90                            Button(role: .destructive) { Task { await studio.delete(t) } } label: { Label("Supprimer", systemImage: "trash") }91                            Button { Task { await studio.duplicate(t) } } label: { Label("Dupliquer", systemImage: "plus.square.on.square") }.tint(.blue)92                        }93                        .contextMenu { TemplateMenu(studio: studio, template: t) }94                }95                .listStyle(.plain)96            } else {97                ScrollView {98                    LazyVGrid(columns: [GridItem(.adaptive(minimum: 210, maximum: 300), spacing: 18)], spacing: 18) {99                        ForEach(list) { t in100                            Button { Task { await studio.open(t.id) } } label: { TemplateCard(template: t, api: studio.api) }101                                .buttonStyle(.plain)102                                .contextMenu { TemplateMenu(studio: studio, template: t) }103                        }104                    }105                    .padding(20)106                }107            }108        }109        .navigationTitle("Modèles")110        .searchable(text: $studio.search, prompt: Text("Rechercher un modèle"))111        .refreshable { await studio.reload() }112        .toolbar {113            if let onClose { ToolbarItem(placement: .cancellationAction) { Button("Fermer") { onClose() } } }114            ToolbarItem(placement: .primaryAction) {115                Button { studio.showGenerator = true } label: { Label("Créer avec l’IA", systemImage: "sparkles") }.help("Créer un modèle avec l’IA (⌥⌘G)")116            }117            ToolbarItem(placement: .primaryAction) {118                Menu {119                    Button { Task { await studio.createBlank() } } label: { Label("Modèle vierge", systemImage: "doc.badge.plus") }120                    Divider()121                    Picker("Catégorie", selection: $studio.category) {122                        Text("Toutes les catégories").tag(String?.none)123                        ForEach(studio.usedCategories, id: \.self) { c in Text(StudioText.category(c)).tag(String?.some(c)) }124                    }125                    Picker("Trier par", selection: $studio.sort) {126                        Text("Dernière modification").tag(StudioModel.Sort.updated); Text("Nom").tag(StudioModel.Sort.name); Text("Date de création").tag(StudioModel.Sort.created)127                    }128                } label: { Label("Filtrer et trier", systemImage: studio.category == nil ? "line.3.horizontal.decrease.circle" : "line.3.horizontal.decrease.circle.fill") }129            }130        }131    }132}133134/// Context menu of a template (model passed explicitly).135struct TemplateMenu: View {136    let studio: StudioModel137    let template: MailTemplate138    var body: some View {139        Button { Task { await studio.open(template.id) } } label: { Label("Ouvrir", systemImage: "pencil") }140        Button { Task { await studio.duplicate(template) } } label: { Label("Dupliquer", systemImage: "plus.square.on.square") }141        Divider()142        Button(role: .destructive) { Task { await studio.delete(template) } } label: { Label("Supprimer", systemImage: "trash") }143    }144}145146struct TemplateMeta: View {147    let template: MailTemplate148    var body: some View {149        HStack(spacing: 6) {150            Text(StudioText.category(template.category)).font(.caption).padding(.horizontal, 6).padding(.vertical, 1.5).background(.quaternary, in: Capsule())151            if template.isAI { Text("IA").font(.caption.bold()).padding(.horizontal, 6).padding(.vertical, 1.5).background(Color.purple.opacity(0.16), in: Capsule()).foregroundStyle(.purple).accessibilityLabel(Text("Généré par IA")) }152            Text(template.variables.count == 1 ? L("1 variable") : L("\(template.variables.count) variables")).font(.caption).foregroundStyle(.secondary)153            Spacer(minLength: 0)154        }155    }156    static func label(_ t: MailTemplate) -> String {157        [t.name, StudioText.category(t.category), t.isAI ? L("Généré par IA") : "", t.variables.count == 1 ? L("1 variable") : L("\(t.variables.count) variables"),158         t.updatedAt.map { $0.formatted(.relative(presentation: .named)) } ?? ""].filter { !$0.isEmpty }.joined(separator: ", ")159    }160}161162struct TemplateCard: View {163    let template: MailTemplate164    let api: APIClient165    var body: some View {166        VStack(alignment: .leading, spacing: 8) {167            TemplateThumbnail(template: template, api: api)168                .clipShape(RoundedRectangle(cornerRadius: 8))169                .overlay(RoundedRectangle(cornerRadius: 8).strokeBorder(.quaternary))170            Text(template.name).font(.headline).lineLimit(1)171            TemplateMeta(template: template)172            if let d = template.updatedAt { Text(d.formatted(.relative(presentation: .named))).font(.caption).foregroundStyle(.secondary) }173        }174        .padding(10)175        .background(.background.secondary, in: RoundedRectangle(cornerRadius: 12))176        .contentShape(RoundedRectangle(cornerRadius: 12))177        .accessibilityElement(children: .ignore)178        .accessibilityLabel(Text(TemplateMeta.label(template)))179        .accessibilityAddTraits(.isButton)180    }181}182183struct TemplateRowCompact: View {184    let template: MailTemplate185    let api: APIClient186    var body: some View {187        HStack(alignment: .top, spacing: 12) {188            TemplateThumbnail(template: template, api: api).frame(width: 72).clipShape(RoundedRectangle(cornerRadius: 6)).overlay(RoundedRectangle(cornerRadius: 6).strokeBorder(.quaternary))189            VStack(alignment: .leading, spacing: 5) {190                Text(template.name).font(.headline).lineLimit(2)191                Text(template.subject).font(.subheadline).foregroundStyle(.secondary).lineLimit(1)192                TemplateMeta(template: template)193                if let d = template.updatedAt { Text(d.formatted(.relative(presentation: .named))).font(.caption).foregroundStyle(.secondary) }194            }195        }196        .padding(.vertical, 4)197        .contentShape(Rectangle())198        .accessibilityElement(children: .ignore)199        .accessibilityLabel(Text(TemplateMeta.label(template)))200        .accessibilityAddTraits(.isButton)201    }202}203204// MARK: - create with AI205206/// Elapsed time, characters written and model of a running generation — only what the server reported, no invented percentage.207struct GenerationProgress: View {208    let run: GenerationRun209    var body: some View {210        VStack(alignment: .leading, spacing: 8) {211            HStack(spacing: 10) {212                ProgressView().controlSize(.small)213                Text(run.revising ? L("Retouche en cours…") : L("Génération en cours…")).font(.headline)214                Spacer()215                Button("Annuler", role: .cancel) { run.cancel() }.help("Annule la génération sur le serveur")216            }217            TimelineView(.periodic(from: .now, by: 1)) { context in218                let elapsed = Int(context.date.timeIntervalSince(run.startedAt ?? context.date))219                VStack(alignment: .leading, spacing: 3) {220                    Text("Temps écoulé : \(elapsed / 60) min \(String(format: "%02d", elapsed % 60)) s").monospacedDigit()221                    Text(run.chars == 0 ? L("Le modèle réfléchit à la mise en page — aucun caractère écrit pour l’instant") : L("\(run.chars) caractères écrits")).monospacedDigit()222                    if !run.model.isEmpty { Text("Modèle : \(run.model)") }223                    Text("Durée habituelle : une à deux minutes et demie. Gardez cet écran ouvert.").foregroundStyle(.secondary)224                }225                .font(.callout)226            }227        }228        .padding(12)229        .background(Color.accentColor.opacity(0.08), in: RoundedRectangle(cornerRadius: 10))230        .accessibilityElement(children: .contain)231    }232}233234struct GenerationFailure: View {235    let run: GenerationRun236    var retry: (() -> Void)?237    var body: some View {238        if case .failed(let message) = run.phase {239            VStack(alignment: .leading, spacing: 8) {240                Label(message, systemImage: "exclamationmark.triangle.fill").foregroundStyle(.red).font(.callout)241                HStack {242                    if let retry { Button("Réessayer") { retry() } }243                    Button("OK") { run.dismissError() }244                }245            }246            .padding(12).frame(maxWidth: .infinity, alignment: .leading)247            .background(Color.red.opacity(0.08), in: RoundedRectangle(cornerRadius: 10))248        }249    }250}251252struct GeneratorView: View {253    @Bindable var studio: StudioModel254    @State private var useAccent = false255    @State private var accent = Color.indigo256    @State private var showBrand = false257258    var body: some View {259        Form {260            if !studio.aiConfigured {261                Section { Label("La génération par IA n’est pas configurée sur ce serveur. Vous pouvez tout de même créer un modèle vierge.", systemImage: "exclamationmark.triangle").foregroundStyle(.orange) }262            }263            Section("Point de départ") {264                FlowLayout(spacing: 8) {265                    ForEach(StudioText.starters) { s in266                        Button(s.label) { studio.brief = studio.language == "en" ? s.en : s.fr; studio.briefCategory = s.category }267                            .buttonStyle(.bordered).controlSize(.small)268                            .accessibilityHint(Text("Remplit le brief avec un exemple"))269                    }270                    Color.clear.frame(width: 1, height: 1)271                }272            }273            Section {274                TextEditor(text: $studio.brief).frame(minHeight: 150).font(.body).accessibilityLabel(Text("Brief"))275                HStack {276                    let n = studio.brief.trimmingCharacters(in: .whitespacesAndNewlines).count277                    Text("\(n) / 6000 caractères").font(.footnote).foregroundStyle(n > 6000 ? Color.red : Color.secondary).monospacedDigit()278                    if n > 0, n < 8 { Text("— au moins 8").font(.footnote).foregroundStyle(.secondary) }279                    Spacer()280                }281            } header: { Text("Brief") } footer: {282                Text("Décrivez le but du courriel, son contenu, son ton et le bouton principal. Seuls ce brief et la marque sont transmis au service d’IA d’Anthropic — jamais le contenu de vos boîtes.")283            }284            Section("Options") {285                Picker("Langue du courriel", selection: $studio.language) { Text("Français").tag("fr"); Text("English").tag("en") }286                Picker("Catégorie", selection: $studio.briefCategory) {287                    Text("Laisser l’IA choisir").tag(String?.none)288                    ForEach(studio.categories, id: \.self) { c in Text(StudioText.category(c)).tag(String?.some(c)) }289                }290            }291            Section {292                DisclosureGroup(isExpanded: $showBrand) {293                    TextField("Nom de la marque", text: $studio.brand.name)294                    Toggle("Couleur d’accent", isOn: $useAccent)295                    if useAccent { ColorPicker("Couleur", selection: $accent, supportsOpacity: false) }296                    TextField("Adresse du logo (https://…)", text: $studio.brand.logoURL).autocorrectionDisabled()297                        #if os(iOS)298                        .textInputAutocapitalization(.never).keyboardType(.URL)299                        #endif300                    TextField("Ton (ex. : chaleureux et précis)", text: $studio.brand.tone)301                    TextField("Pied de page", text: $studio.brand.footer)302                    TextField("Site web (https://…)", text: $studio.brand.website).autocorrectionDisabled()303                        #if os(iOS)304                        .textInputAutocapitalization(.never).keyboardType(.URL)305                        #endif306                    HStack {307                        Button("Enregistrer la marque") { Task { await studio.saveBrand() } }308                        if !studio.brandStatus.isEmpty { Text(studio.brandStatus).font(.footnote).foregroundStyle(.secondary) }309                    }310                } label: { Label(studio.brand.isEmpty ? L("Marque (facultatif)") : L("Marque : \(studio.brand.name.isEmpty ? studio.brand.accent : studio.brand.name)"), systemImage: "paintpalette") }311            } footer: { Text("La marque est enregistrée dans votre compte et partagée avec le webmail.") }312            Section {313                if studio.generation.isRunning { GenerationProgress(run: studio.generation) }314                GenerationFailure(run: studio.generation) { Task { await studio.generate() } }315                if let u = studio.usage { Text("30 derniers jours : \(u.generations) générations · modèle \(u.model)").font(.footnote).foregroundStyle(.secondary) }316            }317        }318        .formStyle(.grouped)319        .navigationTitle("Créer avec l’IA")320        #if os(iOS)321        .navigationBarTitleDisplayMode(.inline)322        #endif323        .toolbar {324            ToolbarItem(placement: .cancellationAction) { Button("Fermer") { studio.showGenerator = false }.disabled(studio.generation.isRunning) }325            ToolbarItem(placement: .confirmationAction) {326                Button { Task { await studio.generate() } } label: { Label("Générer", systemImage: "sparkles") }327                    .disabled(!studio.canGenerate || !studio.aiConfigured).keyboardShortcut(.return, modifiers: .command).help("Générer (⌘↩)")328            }329        }330        .onAppear { if let c = Color(hex: studio.brand.accent) { accent = c; useAccent = true } }331        .onChange(of: accent) { _, c in if useAccent { studio.brand.accent = c.hex } }332        .onChange(of: useAccent) { _, on in studio.brand.accent = on ? accent.hex : "" }333    }334}335
Files main
Menu

Theme