Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Sources/Shared/Studio/StudioModel.swift3// Description: State of the template studio — library (search, filter, sort, delete with undo), AI generation with honest progress and4// per-code error messages, brand kit shared with the webmail, and the editor of one template (draft, live preview, save, versions, revision).5import SPMailCore6import SwiftUI7#if os(iOS)8import UIKit9#endif1011struct StarterBrief: Identifiable {12 let id: String13 let category: String14 let label: String15 let fr: String16 let en: String17}1819enum StudioText {20 static func category(_ c: String) -> String {21 switch c {22 case "transactional": L("Transactionnel"); case "notification": L("Notification"); case "newsletter": L("Infolettre"); case "announcement": L("Annonce")23 case "personal": L("Personnel"); case "invitation": L("Invitation"); case "receipt": L("Reçu"); case "security": L("Sécurité"); default: L("Autre")24 }25 }2627 /// The same eight intents as the webmail generator.28 static let starters: [StarterBrief] = [29 StarterBrief(id: "welcome", category: "transactional", label: L("Bienvenue"),30 fr: "Courriel de bienvenue envoyé juste après l'inscription. Saluer la personne par son prénom, rappeler en une phrase ce que le service lui apporte, puis proposer trois premiers pas concrets (compléter son profil, découvrir la fonction principale, inviter une collègue), chacun avec un court texte. Un seul bouton principal « Commencer » vers son espace. Terminer par une ligne chaleureuse signée de l'équipe et un lien vers l'aide.",31 en: "Welcome email sent right after sign-up. Greet the person by first name, remind them in one sentence what the service does for them, then offer three concrete first steps (complete their profile, try the main feature, invite a colleague), each with a short line of copy. One primary button, “Get started”, leading to their workspace. Close with a warm line signed by the team and a link to the help centre."),32 StarterBrief(id: "receipt", category: "receipt", label: L("Reçu / facture"),33 fr: "Reçu de paiement clair et vérifiable. En tête : montant payé, date et numéro de reçu. Ensuite un tableau des articles (description, quantité, prix), sous-total, taxes (TPS et TVQ sur deux lignes) et total. Rappeler le mode de paiement (quatre derniers chiffres de la carte) et l'adresse de facturation. Bouton « Télécharger la facture (PDF) ». Pied de page : coordonnées de l'entreprise, numéros de taxes et adresse du soutien. Ton neutre, aucun texte promotionnel.",34 en: "A clear, verifiable payment receipt. At the top: amount paid, date and receipt number. Then a table of line items (description, quantity, price), subtotal, tax and total. Mention the payment method (last four digits of the card) and the billing address. A “Download invoice (PDF)” button. Footer: company details, tax numbers and support address. Neutral tone, no promotional copy."),35 StarterBrief(id: "security", category: "security", label: L("Alerte de sécurité"),36 fr: "Alerte de sécurité : une nouvelle connexion au compte vient d'avoir lieu. Aller droit au fait, sans dramatiser. Présenter dans un encadré l'appareil, le navigateur, le lieu approximatif, l'adresse IP et l'heure. Deux issues nettes : « C'était moi » (rien à faire) et un bouton « Sécuriser mon compte » si ce n'était pas la personne. Rappeler que l'équipe ne demande jamais de mot de passe par courriel. Aucune image décorative, contraste élevé.",37 en: "Security alert: a new sign-in to the account just happened. Get to the point without drama. Show the device, browser, approximate location, IP address and time in a framed block. Two clear outcomes: “That was me” (nothing to do) and a “Secure my account” button if it was not them. Remind the reader that the team never asks for a password by email. No decorative images, high contrast."),38 StarterBrief(id: "newsletter", category: "newsletter", label: L("Infolettre"),39 fr: "Numéro d'une infolettre mensuelle. En-tête avec le nom de l'infolettre, le numéro et la date. Un mot d'ouverture de trois ou quatre phrases signé par la rédaction, puis un article principal (titre, chapeau, lien « Lire la suite ») et trois brèves avec titre, deux lignes de texte et lien. Une section « À l'agenda » avec deux dates. Pied de page : pourquoi la personne reçoit ce courriel, lien de désabonnement et lien vers les archives. Mise en page éditoriale, aérée, agréable à lire sur téléphone.",40 en: "One issue of a monthly newsletter. Masthead with the newsletter name, issue number and date. An opening note of three or four sentences signed by the editor, then a lead story (headline, standfirst, “Read more” link) and three short items, each with a headline, two lines of copy and a link. An “On the calendar” section with two dates. Footer: why the reader is receiving this, an unsubscribe link and a link to the archive. Editorial, airy layout that reads well on a phone."),41 StarterBrief(id: "invitation", category: "invitation", label: L("Invitation"),42 fr: "Invitation à un événement. Mettre en avant le nom de l'événement, puis la date, l'heure et le lieu dans un bloc très lisible. Deux ou trois phrases sur ce qui attend les personnes invitées et le nom de l'hôte. Bouton principal « Confirmer ma présence » et lien secondaire « Je ne pourrai pas venir ». Préciser la date limite de réponse, le stationnement ou l'accès, et une personne à joindre pour les questions. Ton élégant et accueillant.",43 en: "Invitation to an event. Lead with the event name, then the date, time and venue in a highly legible block. Two or three sentences on what guests can expect, and the host's name. Primary button “Confirm my attendance” and a secondary link “I can't make it”. Mention the reply-by date, parking or access details and a contact person for questions. Elegant, welcoming tone."),44 StarterBrief(id: "magic-link", category: "security", label: L("Lien de connexion"),45 fr: "Courriel de connexion sans mot de passe. Très court : une phrase d'explication, un grand bouton « Me connecter », puis la durée de validité du lien (15 minutes, utilisable une seule fois). En dessous, l'adresse complète du lien en petit pour qui préfère la copier. Préciser que si la personne n'a rien demandé, elle peut ignorer ce message et que personne ne pourra se connecter sans ce lien. Aucun élément superflu.",46 en: "Password-less sign-in email. Very short: one sentence of explanation, a large “Sign in” button, then how long the link stays valid (15 minutes, single use). Below it, the full link in small type for people who prefer to copy it. State that if they did not request this they can ignore the message and that nobody can sign in without this link. Nothing superfluous."),47 StarterBrief(id: "announcement", category: "announcement", label: L("Annonce de produit"),48 fr: "Annonce d'une nouvelle fonctionnalité. Un titre fort qui dit ce qui change pour la personne, puis trois bénéfices concrets présentés avec un court titre et une phrase chacun. Une citation d'une cliente qui l'a essayée en avant-première. Bouton principal « Essayer maintenant » et lien secondaire vers les notes de version. Pied de page avec lien de désabonnement. Ton enthousiaste mais précis, sans superlatifs creux.",49 en: "Announcement of a new feature. A strong headline that says what changes for the reader, then three concrete benefits, each with a short title and one sentence. A quote from a customer who tried it early. Primary button “Try it now” and a secondary link to the release notes. Footer with an unsubscribe link. Enthusiastic but precise tone, no empty superlatives."),50 StarterBrief(id: "personal", category: "personal", label: L("Mot personnel"),51 fr: "Mot personnel envoyé à une personne après une rencontre. Mise en page très sobre, proche d'une lettre : pas de bannière, une seule colonne étroite, typographie soignée. Saluer par le prénom, remercier pour l'échange en rappelant le sujet abordé, proposer une suite concrète avec une date, puis une formule de politesse et une signature avec nom, fonction et téléphone. Un seul lien discret pour prendre rendez-vous.",52 en: "A personal note sent to one person after a meeting. Very restrained layout, close to a letter: no banner, a single narrow column, careful typography. Greet them by first name, thank them for the conversation and recall its topic, propose a concrete next step with a date, then a sign-off and a signature with name, role and phone number. One discreet link to book a meeting."),53 ]5455 static let revisionIdeas: [(fr: String, en: String)] = [("Rends le bouton plus sobre", "Make the button more understated"), ("Ajoute une section FAQ de trois questions", "Add a three-question FAQ section"),56 ("Raccourcis le texte de moitié", "Cut the copy by half"), ("Passe au tutoiement", "Make the tone more casual")]5758 /// A minimal email document, readable everywhere, with a dark rendition — the starting point of a blank template.59 static func blankHTML(french: Bool) -> String {60 """61 <!DOCTYPE html>62 <html lang="\(french ? "fr" : "en")">63 <head>64 <meta charset="utf-8">65 <meta name="viewport" content="width=device-width, initial-scale=1">66 <meta name="color-scheme" content="light dark">67 <title></title>68 <style>69 body{margin:0;padding:0;background:#f4f3ef;}70 .card{background:#ffffff;color:#1c1b19;}71 @media (max-width:600px){.container{width:100% !important;}.px{padding-left:20px !important;padding-right:20px !important;}}72 @media (prefers-color-scheme:dark){body{background:#161716 !important;}.card{background:#1f201e !important;color:#ecebe6 !important;}}73 </style>74 </head>75 <body>76 <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0">77 <tr>78 <td align="center" style="padding:32px 12px;">79 <table role="presentation" class="container card" width="600" cellpadding="0" cellspacing="0" border="0" style="width:600px;max-width:100%;border-radius:12px;">80 <tr>81 <td class="px" style="padding:36px 40px;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,Helvetica,Arial,sans-serif;font-size:16px;line-height:1.55;">82 <p style="margin:0 0 16px;">\(french ? "Bonjour {{first_name}}," : "Hello {{first_name}},")</p>83 <p style="margin:0;">\(french ? "Écrivez ici le contenu de votre courriel." : "Write the content of your email here.")</p>84 </td>85 </tr>86 </table>87 </td>88 </tr>89 </table>90 </body>91 </html>9293 """94 }9596 /// What to tell the person for each way a generation can fail — and what to do next.97 static func generationError(_ e: Error) -> String {98 if let g = e as? GenerationError {99 switch g.code {100 case "ai_not_configured": return L("La génération par IA n’est pas configurée sur ce serveur (aucune clé Anthropic). Le reste du studio fonctionne : créez un modèle vierge ou modifiez le HTML.")101 case "ai_rate_limited": return L("Le service d’IA est momentanément saturé. Réessayez dans une minute ; votre brief est conservé.")102 case "rate_limited": return L("Limite atteinte : 30 générations par heure. Réessayez plus tard ; votre brief est conservé.")103 case "ai_refused": return L("Le modèle a refusé cette demande. Reformulez le brief (contenu ou ton), puis réessayez.")104 case "ai_output_truncated": return L("Le modèle généré a été coupé avant la fin. Raccourcissez le brief ou demandez un courriel plus simple.")105 case "ai_invalid_output", "bad_response": return L("Le modèle a rendu un résultat inutilisable. Réessayez ; rien n’a été enregistré.")106 case "ai_unreachable": return L("Le serveur n’a pas pu joindre le service d’IA. Réessayez dans un instant.")107 case "ai_bad_request": return L("Le service d’IA a rejeté la demande : ") + g.message108 case "stream_cut": return L("La connexion a été coupée pendant la génération. Si le serveur avait terminé, le modèle est dans la bibliothèque ; sinon, relancez — votre brief est conservé.")109 case "cancelled": return L("Génération annulée.")110 case "invalid_request": return L("Le brief doit compter entre 8 et 6000 caractères.")111 case "not_found": return L("Ce modèle n’existe plus sur le serveur.")112 default: return L("La génération a échoué (\(g.code)). Réessayez ; votre brief est conservé.")113 }114 }115 if let a = e as? APIError, a.isOffline { return L("Le serveur est injoignable. Vérifiez la connexion.") }116 return e.localizedDescription117 }118}119120/// One AI run (a new template, or the revision of an open one). Progress is only what the server reported.121@MainActor @Observable122final class GenerationRun {123 enum Phase: Equatable { case idle, running, failed(String) }124 var phase = Phase.idle125 var startedAt: Date?126 var model = ""127 var revising = false128 /// Characters written by the model so far (0 while it is still thinking).129 var chars = 0130 var lastSignal: Date?131 @ObservationIgnored private var task: Task<MailTemplate?, Never>?132 var isRunning: Bool { phase == .running }133134 /// Runs to the end and returns the saved template, or nil (failure message in `phase`, nil phase change on cancel).135 func run(api: APIClient, request: GenerationRequest) async -> MailTemplate? {136 guard !isRunning else { return nil }137 phase = .running; startedAt = Date(); chars = 0; model = ""; revising = request.baseTemplateId != nil; lastSignal = Date()138 Self.keepAwake(true)139 let t = Task { [weak self] () -> MailTemplate? in140 do {141 for try await e in TemplateGenerationStream.events(api: api, request: request) {142 guard let self else { return nil }143 self.lastSignal = Date()144 switch e {145 case .start(let m, let r): self.model = m; self.revising = r146 case .progress(let c): self.chars = c147 case .alive: break148 case .done(let template, _): self.phase = .idle; return template149 }150 }151 self?.phase = .failed(StudioText.generationError(GenerationError.streamCut))152 } catch is CancellationError {153 self?.phase = .idle154 } catch {155 if Task.isCancelled { self?.phase = .idle } else { self?.phase = .failed(StudioText.generationError(error)) }156 }157 return nil158 }159 task = t160 let result = await t.value161 Self.keepAwake(false)162 return result163 }164165 /// Closing the connection cancels the generation on the server.166 func cancel() { task?.cancel() }167 func dismissError() { if case .failed = phase { phase = .idle } }168169 /// iOS: the screen stays on while a generation runs (one to two minutes).170 static func keepAwake(_ on: Bool) {171 #if os(iOS)172 UIApplication.shared.isIdleTimerDisabled = on173 #endif174 }175}176177@MainActor @Observable178final class StudioModel {179 enum Sort: String, CaseIterable, Identifiable { case updated, name, created; var id: String { rawValue } }180 @ObservationIgnored weak var app: AppModel?181 var api: APIClient { app!.api }182183 var templates: [MailTemplate] = []184 var aiConfigured = true185 var aiModel = ""186 var categories = MailTemplate.categories187 var isLoading = false188 var loaded = false189 var loadError: String?190 var search = ""191 var category: String?192 var sort = Sort.updated193 /// The template open in the editor (nil = the library).194 var current: EditorModel?195 var showGenerator = false196 var brief = ""197 var language = Locale.current.language.languageCode?.identifier == "en" ? "en" : "fr"198 var briefCategory: String?199 var brand = TemplateBrand()200 var brandStatus = ""201 let generation = GenerationRun()202 /// The template just deleted, while « Annuler » is still offered.203 var undo: MailTemplate?204 var notice: String?205 var usage: AIUsage?206 @ObservationIgnored private var undoTimer: Task<Void, Never>?207208 init(app: AppModel) { self.app = app }209210 func reset() {211 generation.cancel()212 templates = []; current = nil; loaded = false; undo = nil; brief = ""; showGenerator = false213 ThumbnailStore.shared.clear()214 }215216 var filtered: [MailTemplate] {217 let q = search.trimmingCharacters(in: .whitespaces).lowercased()218 let list = templates.filter { t in219 (category == nil || t.category == category) && (q.isEmpty || t.name.lowercased().contains(q) || t.subject.lowercased().contains(q) || StudioText.category(t.category).lowercased().contains(q))220 }221 switch sort {222 case .updated: return list.sorted { ($0.updatedAt ?? .distantPast) > ($1.updatedAt ?? .distantPast) }223 case .created: return list.sorted { ($0.createdAt ?? .distantPast) > ($1.createdAt ?? .distantPast) }224 case .name: return list.sorted { $0.name.localizedCaseInsensitiveCompare($1.name) == .orderedAscending }225 }226 }227 var usedCategories: [String] { categories.filter { c in templates.contains { $0.category == c } } }228229 func describe(_ error: Error) -> String {230 if let a = error as? APIError {231 if a.isOffline { return L("Le studio de modèles a besoin du serveur : il est injoignable pour l’instant.") }232 switch a.code {233 case "not_found": return L("Ce modèle n’existe plus sur le serveur.")234 case "invalid_request": return L("Le serveur a refusé ce contenu : ") + (a.message.isEmpty ? a.code : a.message)235 case "payload_too_large", "http_413": return L("Ce modèle est trop volumineux pour le serveur.")236 default: return a.message.isEmpty ? a.code : a.message237 }238 }239 return error.localizedDescription240 }241242 func reload() async {243 guard app?.phase == .ready || app?.phase == .locked else { return }244 isLoading = true245 defer { isLoading = false }246 do {247 let lib = try await api.templates()248 templates = lib.templates; aiConfigured = lib.aiConfigured; aiModel = lib.aiModel; categories = lib.categories249 loaded = true; loadError = nil250 if let prefs = app?.me?.user.prefs, brand.isEmpty { brand = TemplateBrand(json: prefs["templateBrand"]) }251 if let me = try? await api.me() { app?.me = me; brand = TemplateBrand(json: me.user.prefs?["templateBrand"] ?? .null) }252 usage = try? await api.aiUsage()253 } catch { loadError = describe(error) }254 }255256 func open(_ id: String) async {257 if current?.id == id { return }258 do {259 let t = try await api.template(id: id)260 current = EditorModel(template: t, studio: self)261 } catch { notice = describe(error); await reload() }262 }263264 /// Leaves the editor. The caller checked for unsaved changes first.265 func closeEditor() { current = nil; Task { await reload() } }266267 func createBlank() async {268 let french = language != "en"269 do {270 let t = try await api.createTemplate(TemplateContent(name: french ? "Nouveau modèle" : "New template", category: "other", subject: french ? "Bonjour {{first_name}}" : "Hello {{first_name}}",271 html: StudioText.blankHTML(french: french), text: french ? "Bonjour {{first_name}},\n\nÉcrivez ici le contenu de votre courriel.\n" : "Hello {{first_name}},\n\nWrite the content of your email here.\n",272 variables: [TemplateVariable(name: "first_name", description: french ? "Prénom" : "First name", example: french ? "Zoé" : "Zoe")]))273 templates.insert(t, at: 0)274 current = EditorModel(template: t, studio: self)275 } catch { notice = describe(error) }276 }277278 func duplicate(_ t: MailTemplate) async {279 do { let copy = try await api.duplicateTemplate(id: t.id); templates.insert(copy, at: 0); notice = L("Copie créée : \(copy.name)") } catch { notice = describe(error) }280 }281282 /// Deleting archives the template on the server; « Annuler » restores it (the server keeps archives 30 days).283 func delete(_ t: MailTemplate) async {284 do {285 try await api.archiveTemplate(id: t.id)286 templates.removeAll { $0.id == t.id }287 if current?.id == t.id { current = nil }288 undo = t289 undoTimer?.cancel()290 undoTimer = Task { [weak self] in try? await Task.sleep(for: .seconds(8)); if !Task.isCancelled, self?.undo?.id == t.id { self?.undo = nil } }291 } catch { notice = describe(error) }292 }293294 func undoDelete() async {295 guard let t = undo else { return }296 undo = nil297 do { let back = try await api.unarchiveTemplate(id: t.id); templates.insert(back, at: 0); notice = L("Modèle rétabli") } catch { notice = describe(error) }298 }299300 func saveBrand() async {301 do { try await api.saveBrand(brand); brandStatus = L("Marque enregistrée — partagée avec le webmail") } catch { brandStatus = describe(error) }302 }303304 var canGenerate: Bool { GenerationRequest(brief: brief).isValid && !generation.isRunning }305306 /// Generates a new template from the brief. The brief stays in place on failure; on success the editor opens on the result.307 func generate() async {308 let request = GenerationRequest(brief: brief.trimmingCharacters(in: .whitespacesAndNewlines), language: language, category: briefCategory, brand: brand)309 guard request.isValid else { return }310 if !brand.isEmpty { try? await api.saveBrand(brand) }311 if let t = await generation.run(api: api, request: request) {312 templates.removeAll { $0.id == t.id }313 templates.insert(t, at: 0)314 brief = ""315 showGenerator = false316 current = EditorModel(template: t, studio: self)317 usage = try? await api.aiUsage()318 } else if case .failed = generation.phase {319 await reload() // the server may have finished although the stream was cut320 }321 }322323 /// Coming back to the foreground: a generation whose stream died while the app was suspended is reported, and the library is refreshed324 /// in case the server finished.325 func didBecomeActive() async {326 guard loaded else { return }327 if generation.isRunning, let last = generation.lastSignal, Date().timeIntervalSince(last) > TemplateGenerationStream.idleTimeout { generation.cancel() }328 if !generation.isRunning { await reload() }329 }330}331332/// The editor of one template: a local draft of every field, compared with what the server holds.333@MainActor @Observable334final class EditorModel: Identifiable, RecipientHost {335 enum Device: String, CaseIterable, Identifiable { case desktop, phone; var id: String { rawValue }; var width: CGFloat { self == .desktop ? 680 : 390 } }336 enum Pane: String, CaseIterable, Identifiable { case preview, html, text; var id: String { rawValue } }337338 nonisolated let id: String339 @ObservationIgnored unowned let studio: StudioModel340 /// What the server holds.341 var template: MailTemplate342 var name: String343 var category: String344 var subject: String345 var preheader: String346 var html: String347 var text: String348 var variables: [TemplateVariable]349 /// Values typed in the variables panel (the examples fill what is empty).350 var values: [String: String] = [:]351 var rawPlaceholders = false352 var rendered: RenderedTemplate?353 var previewError: String?354 var isRendering = false355 var scheme = TemplatePreview.Scheme.light356 var device = Device.desktop357 var pane = Pane.preview358 var isSaving = false359 var saveError: String?360 /// The server's sanitiser changed the HTML of the last save.361 var sanitizerNotice = false362 var versions: [TemplateVersionInfo] = []363 var versionPreview: TemplateVersion?364 var revisionBrief = ""365 var showSend = false366 var find = ""367 let generation = GenerationRun()368 @ObservationIgnored private var previewTask: Task<Void, Never>?369 @ObservationIgnored private var previewGeneration = 0370371 init(template: MailTemplate, studio: StudioModel) {372 id = template.id373 self.studio = studio374 self.template = template375 name = template.name; category = template.category; subject = template.subject; preheader = template.preheader376 html = template.html ?? ""; text = template.text ?? ""; variables = template.variables377 }378379 var api: APIClient { studio.api }380 var isDirty: Bool {381 name != template.name || category != template.category || subject != template.subject || preheader != template.preheader || html != (template.html ?? "") || text != (template.text ?? "") || variables != template.variables382 }383 var htmlBytes: Int { html.utf8.count }384 var isClipped: Bool { TemplateText.isClipped(bytes: (rendered?.html ?? html).utf8.count) }385 /// Variables really present in the draft, with the declarations kept — what the server will store.386 var liveVariables: [TemplateVariable] { TemplateText.reconcile(variables, texts: [subject, preheader, html, text]) }387 var missingRequired: [String] { liveVariables.filter { $0.required && (values[$0.name] ?? "").isEmpty && $0.example.isEmpty }.map(\.name) }388389 /// The document shown by the isolated renderer.390 var previewDocument: String? {391 guard let r = rendered else { return nil }392 return TemplatePreview.document(html: rawPlaceholders ? (r.sanitizedHTML ?? html) : r.html, scheme: scheme)393 }394 var shownSubject: String { rawPlaceholders ? subject : (rendered?.subject ?? subject) }395 var shownPreheader: String { rawPlaceholders ? preheader : (rendered?.preheader ?? preheader) }396397 private func adopt(_ t: MailTemplate) {398 template = t399 name = t.name; category = t.category; subject = t.subject; preheader = t.preheader; html = t.html ?? ""; text = t.text ?? ""; variables = t.variables400 if let n = studio.templates.firstIndex(where: { $0.id == t.id }) { studio.templates[n] = t } else { studio.templates.insert(t, at: 0) }401 }402403 // RecipientHost (the send dialog's token field edits through its own model; nothing to do here)404 func edited() { schedulePreview() }405 func suggestions(for prefix: String) async -> [EmailAddress] { ((try? await studio.app?.store?.suggestCorrespondents(prefix)) ?? []) }406407 /// Debounced live preview of the draft, rendered and sanitised by the server (`POST /api/templates/preview`), nothing stored.408 func schedulePreview(immediately: Bool = false) {409 previewTask?.cancel()410 previewGeneration += 1411 let generation = previewGeneration412 previewTask = Task { [weak self] in413 if !immediately { try? await Task.sleep(for: .milliseconds(450)) }414 guard !Task.isCancelled, let self else { return }415 await self.renderPreview(generation)416 }417 }418419 func renderPreview(_ generation: Int? = nil) async {420 isRendering = true421 defer { isRendering = false }422 do {423 let r = try await api.previewTemplate(html: html, subject: subject, preheader: preheader, text: text, variables: variables, values: values.filter { !$0.value.isEmpty })424 if let generation, generation != previewGeneration { return }425 rendered = r426 previewError = nil427 // the server's list is the truth for which variables exist; local edits of description / example / required are kept428 if let v = r.variables, v.map(\.name) != variables.map(\.name) { variables = TemplateText.reconcile(variables, texts: [subject, preheader, r.sanitizedHTML ?? html, text]) }429 } catch { if !(error is CancellationError) { previewError = studio.describe(error) } }430 }431432 func resetValues() { values = [:]; schedulePreview(immediately: true) }433434 func load() async {435 await renderPreview()436 await loadVersions()437 }438 func loadVersions() async { versions = (try? await api.templateVersions(id: id)) ?? versions }439440 /// Explicit save. A content change makes a new version on the server; a rename alone does not.441 @discardableResult442 func save(note: String? = nil) async -> Bool {443 guard isDirty, !isSaving else { return !isDirty }444 guard !name.trimmingCharacters(in: .whitespaces).isEmpty, !html.isEmpty else { saveError = L("Un modèle a besoin d’un nom et d’un contenu HTML."); return false }445 isSaving = true446 defer { isSaving = false }447 let sent = html448 do {449 let t = try await api.updateTemplate(id: id, TemplateContent(name: name, category: category, subject: subject, preheader: preheader, html: html, text: text, variables: liveVariables, note: note))450 sanitizerNotice = (t.html ?? "") != sent451 adopt(t)452 saveError = nil453 ThumbnailStore.shared.forget(id)454 await loadVersions()455 schedulePreview(immediately: true)456 return true457 } catch { saveError = studio.describe(error); return false }458 }459460 func discardChanges() { adopt(template); sanitizerNotice = false; saveError = nil; schedulePreview(immediately: true) }461462 func preview(version: Int) async {463 do { versionPreview = try await api.templateVersion(id: id, version: version) } catch { studio.notice = studio.describe(error) }464 }465466 /// Restoring makes a NEW version with the old content: nothing is lost.467 func restore(version: Int) async {468 do {469 adopt(try await api.restoreTemplateVersion(id: id, version: version))470 versionPreview = nil471 ThumbnailStore.shared.forget(id)472 await loadVersions()473 schedulePreview(immediately: true)474 studio.notice = L("Version \(version) rétablie (nouvelle version \(template.version))")475 } catch { studio.notice = studio.describe(error) }476 }477478 var canRevise: Bool { GenerationRequest(brief: revisionBrief).isValid && !generation.isRunning && !isDirty }479480 /// « Retoucher avec l’IA »: the saved template is the base, the result is a new version of the same template.481 func revise() async {482 let request = GenerationRequest(brief: revisionBrief.trimmingCharacters(in: .whitespacesAndNewlines), language: studio.language, brand: template.brand, baseTemplateId: id)483 guard request.isValid, !isDirty else { return }484 if let t = await generation.run(api: api, request: request) {485 adopt(t)486 revisionBrief = ""487 ThumbnailStore.shared.forget(id)488 await loadVersions()489 schedulePreview(immediately: true)490 studio.notice = L("Retouche enregistrée : version \(t.version)")491 } else if case .failed = generation.phase, let fresh = try? await api.template(id: id), fresh.version != template.version {492 adopt(fresh); await loadVersions(); schedulePreview(immediately: true) // the server finished although the stream was cut493 }494 }495496 func insert(variable name: String, into field: ReferenceWritableKeyPath<EditorModel, String>) {497 self[keyPath: field] += (self[keyPath: field].isEmpty || self[keyPath: field].hasSuffix(" ") ? "" : " ") + "{{\(name)}}"498 schedulePreview()499 }500501 // export502 var fileBase: String { let s = name.replacingOccurrences(of: "/", with: "-").replacingOccurrences(of: ":", with: "-").trimmingCharacters(in: .whitespaces); return s.isEmpty ? "modele" : s }503 var renderedHTML: String { rendered?.html ?? html }504 var renderedText: String { rendered?.text ?? text }505}506