Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Sources/Shared/Studio/StudioEditor.swift3// Description: Template editor — preview (device width, light / dark, inbox-line mock), content, variables with live preview, « Retoucher avec l’IA »,4// HTML and text source, explicit save with unsaved-changes guard, versions with preview and restore, export / share.5// macOS: three panes. iPad: split view. iPhone: tabs (Aperçu / Contenu / Variables).6import SPMailCore7import SwiftUI8import UniformTypeIdentifiers910struct EditorView: View {11 @Bindable var editor: EditorModel12 let studio: StudioModel13 @Environment(\.horizontalSizeClass) private var sizeClass14 enum Tab: String, CaseIterable, Identifiable { case preview, content, variables, tools; var id: String { rawValue } }15 @State private var tab = Tab.preview16 @State private var side = Tab.content17 @State private var confirmLeave = false18 @State private var exportDoc: HTMLDocument?19 @State private var exportName = ""20 @State private var exportType = UTType.html2122 static func title(_ t: Tab) -> String {23 switch t { case .preview: L("Aperçu"); case .content: L("Contenu"); case .variables: L("Variables"); case .tools: L("Outils") }24 }2526 var body: some View {27 layout28 .navigationTitle(editor.name.isEmpty ? L("Modèle") : editor.name)29 #if os(iOS)30 .navigationBarTitleDisplayMode(.inline)31 .navigationBarBackButtonHidden()32 #endif33 .toolbar { toolbar }34 .task { await editor.load() }35 #if os(iOS)36 .onAppear { if sizeClass == .compact, editor.rendered == nil { editor.device = .phone } } // a phone shows the phone rendering first37 #endif38 .onChange(of: editor.subject) { _, _ in editor.schedulePreview() }39 .onChange(of: editor.preheader) { _, _ in editor.schedulePreview() }40 .onChange(of: editor.html) { _, _ in editor.schedulePreview() }41 .onChange(of: editor.text) { _, _ in editor.schedulePreview() }42 .onChange(of: editor.values) { _, _ in editor.schedulePreview() }43 .confirmationDialog("Ce modèle a des modifications non enregistrées.", isPresented: $confirmLeave, titleVisibility: .visible) {44 Button("Enregistrer") { Task { if await editor.save() { studio.closeEditor() } } }45 Button("Abandonner les modifications", role: .destructive) { studio.closeEditor() }46 Button("Continuer la modification", role: .cancel) {}47 }48 .sheet(isPresented: $editor.showSend) {49 NavigationStack { TemplateSendView(model: TemplateSendModel(editor: editor)) { editor.showSend = false } }50 #if os(macOS)51 .frame(minWidth: 560, idealWidth: 620, minHeight: 560, idealHeight: 660)52 #endif53 }54 .sheet(item: Binding(get: { editor.versionPreview.map(VersionSheetItem.init) }, set: { if $0 == nil { editor.versionPreview = nil } })) { item in55 NavigationStack { VersionPreviewView(editor: editor, version: item.version) }56 #if os(macOS)57 .frame(minWidth: 720, minHeight: 620)58 #endif59 }60 .fileExporter(isPresented: Binding(get: { exportDoc != nil }, set: { if !$0 { exportDoc = nil } }), document: exportDoc, contentType: exportType, defaultFilename: exportName) { _ in exportDoc = nil }61 }6263 @ViewBuilder private var layout: some View {64 #if os(macOS)65 HSplitView {66 VStack(spacing: 0) {67 Picker("Panneau", selection: $side) { Text("Contenu").tag(Tab.content); Text("Variables").tag(Tab.variables) }.pickerStyle(.segmented).labelsHidden().padding(10)68 if side == .variables { VariablesPane(editor: editor) } else { ContentPane(editor: editor) }69 }70 .frame(minWidth: 250, idealWidth: 290, maxWidth: 400)71 CenterPane(editor: editor).frame(minWidth: 460, idealWidth: 760, maxWidth: .infinity, maxHeight: .infinity).layoutPriority(1)72 ToolsPane(editor: editor, export: export).frame(minWidth: 240, idealWidth: 270, maxWidth: 360)73 }74 #else75 if sizeClass == .compact {76 VStack(spacing: 0) {77 Picker("Onglet", selection: $tab) { ForEach([Tab.preview, .content, .variables, .tools]) { Text(Self.title($0)).tag($0) } }.pickerStyle(.segmented).padding(.horizontal, 12).padding(.vertical, 8)78 switch tab {79 case .preview: CenterPane(editor: editor)80 case .content: ContentPane(editor: editor)81 case .variables: VariablesPane(editor: editor)82 case .tools: ToolsPane(editor: editor, export: export)83 }84 }85 } else {86 HStack(spacing: 0) {87 VStack(spacing: 0) {88 Picker("Panneau", selection: $side) { ForEach([Tab.content, .variables, .tools]) { Text(Self.title($0)).tag($0) } }.pickerStyle(.segmented).padding(10)89 switch side {90 case .variables: VariablesPane(editor: editor)91 case .tools: ToolsPane(editor: editor, export: export)92 default: ContentPane(editor: editor)93 }94 }95 .frame(width: 360)96 Divider()97 CenterPane(editor: editor)98 }99 }100 #endif101 }102103 @ToolbarContentBuilder private var toolbar: some ToolbarContent {104 ToolbarItem(placement: .navigation) {105 Button { if editor.isDirty { confirmLeave = true } else { studio.closeEditor() } } label: { Label("Bibliothèque", systemImage: "chevron.backward") }106 .help("Retour à la bibliothèque")107 }108 ToolbarItem(placement: .primaryAction) {109 Button { Task { await editor.save() } } label: {110 if editor.isSaving { ProgressView().controlSize(.small) } else { Label(editor.isDirty ? L("Enregistrer") : L("Enregistré"), systemImage: editor.isDirty ? "square.and.arrow.down.fill" : "checkmark.circle") }111 }112 .disabled(!editor.isDirty || editor.isSaving)113 .help(editor.isDirty ? L("Enregistrer (⌘S) — modifications non enregistrées") : L("Aucune modification à enregistrer"))114 .accessibilityLabel(Text(editor.isDirty ? L("Enregistrer, modifications non enregistrées") : L("Enregistré")))115 }116 ToolbarItem(placement: .primaryAction) {117 Button { editor.showSend = true } label: { Label("Envoyer…", systemImage: "paperplane") }.disabled(editor.isDirty).help(editor.isDirty ? L("Enregistrez avant d’envoyer") : L("Envoyer ce modèle"))118 }119 }120121 private func export(_ name: String, _ content: String, _ type: UTType) {122 exportName = name; exportType = type; exportDoc = HTMLDocument(content)123 }124}125126struct VersionSheetItem: Identifiable { let version: TemplateVersion; var id: Int { version.version } }127128// MARK: - centre: preview and sources129130struct CenterPane: View {131 @Bindable var editor: EditorModel132 @State private var findToken = 0133134 var body: some View {135 VStack(spacing: 0) {136 HStack(spacing: 10) {137 Picker("Vue", selection: $editor.pane) { Text("Aperçu").tag(EditorModel.Pane.preview); Text("HTML").tag(EditorModel.Pane.html); Text("Texte").tag(EditorModel.Pane.text) }138 .pickerStyle(.segmented).labelsHidden().fixedSize()139 Spacer(minLength: 4)140 if editor.pane == .preview {141 Picker("Largeur", selection: $editor.device) {142 Image(systemName: "desktopcomputer").accessibilityLabel(Text("Ordinateur")).tag(EditorModel.Device.desktop)143 Image(systemName: "iphone").accessibilityLabel(Text("Téléphone")).tag(EditorModel.Device.phone)144 }.pickerStyle(.segmented).labelsHidden().fixedSize().help("Largeur de l’aperçu : ordinateur (680) ou téléphone (390)")145 Picker("Apparence", selection: $editor.scheme) {146 Image(systemName: "sun.max").accessibilityLabel(Text("Clair")).tag(TemplatePreview.Scheme.light)147 Image(systemName: "moon").accessibilityLabel(Text("Sombre")).tag(TemplatePreview.Scheme.dark)148 }.pickerStyle(.segmented).labelsHidden().fixedSize().help("Rendu clair ou sombre du modèle")149 } else {150 Button { findToken += 1 } label: { Label("Rechercher", systemImage: "magnifyingglass") }.keyboardShortcut("f").help("Rechercher dans le code (⌘F)")151 Text(editor.pane == .html ? editor.htmlBytes.byteLabel : editor.text.utf8.count.byteLabel).font(.footnote).foregroundStyle(.secondary).monospacedDigit()152 }153 }154 .padding(.horizontal, 12).padding(.vertical, 8)155 Divider()156 if editor.sanitizerNotice {157 Label("Le serveur a retiré du contenu actif (script, formulaire, cadre ou lien non sûr) à l’enregistrement. Le code affiché est ce qui a été conservé.", systemImage: "shield.lefthalf.filled")158 .font(.footnote).padding(8).frame(maxWidth: .infinity, alignment: .leading).background(Color.orange.opacity(0.14))159 .onTapGesture { editor.sanitizerNotice = false }160 }161 if let e = editor.saveError { Label(e, systemImage: "exclamationmark.triangle").font(.footnote).foregroundStyle(.red).padding(8).frame(maxWidth: .infinity, alignment: .leading) }162 switch editor.pane {163 case .preview: preview164 case .html: CodeEditor(text: $editor.html, findToken: findToken)165 case .text: CodeEditor(text: $editor.text, findToken: findToken)166 }167 }168 }169170 private var preview: some View {171 let dark = editor.scheme == .dark172 return ScrollView([.vertical, .horizontal]) {173 VStack(spacing: 14) {174 InboxLine(sender: editor.template.brand.name.isEmpty ? (editor.studio.app?.me?.user.display_name ?? "SP Mail") : editor.template.brand.name, subject: editor.shownSubject, preheader: editor.shownPreheader, dark: dark)175 .frame(width: editor.device.width)176 if let doc = editor.previewDocument {177 TemplateWebPreview(document: doc, width: editor.device.width, api: editor.api)178 .background(dark ? Color(white: 0.09) : Color.white)179 .clipShape(RoundedRectangle(cornerRadius: editor.device == .phone ? 28 : 6))180 .overlay(RoundedRectangle(cornerRadius: editor.device == .phone ? 28 : 6).strokeBorder(editor.device == .phone ? Color.primary.opacity(0.55) : Color.primary.opacity(0.15), lineWidth: editor.device == .phone ? 6 : 1))181 .id("\(editor.device.rawValue)-\(editor.scheme.rawValue)")182 } else if let e = editor.previewError {183 ContentUnavailableView { Label("Aperçu indisponible", systemImage: "wifi.slash") } description: { Text(e) } actions: { Button("Réessayer") { editor.schedulePreview(immediately: true) } }184 .frame(width: editor.device.width)185 } else { ProgressView().frame(width: editor.device.width, height: 240) }186 }187 .padding(editor.device == .phone ? 6 : 20)188 .frame(maxWidth: .infinity)189 }190 .defaultScrollAnchor(.top)191 .background(dark ? Color(white: 0.16) : Color(white: 0.93))192 .overlay(alignment: .topTrailing) { if editor.isRendering { ProgressView().controlSize(.small).padding(8) } }193 }194}195196/// How the message shows in a mail list: sender, subject, preheader.197struct InboxLine: View {198 let sender: String199 let subject: String200 let preheader: String201 let dark: Bool202 var body: some View {203 HStack(alignment: .top, spacing: 10) {204 Circle().fill(Color.accentColor).frame(width: 9, height: 9).padding(.top, 5)205 VStack(alignment: .leading, spacing: 2) {206 HStack { Text(sender).font(.subheadline.weight(.semibold)).lineLimit(1); Spacer(); Text(Date().formatted(date: .omitted, time: .shortened)).font(.caption).opacity(0.6) }207 Text(subject.isEmpty ? L("(sans objet)") : subject).font(.subheadline).lineLimit(1)208 Text(preheader.isEmpty ? L("(pas de texte d’aperçu)") : preheader).font(.caption).lineLimit(1).opacity(0.65)209 }210 }211 .padding(10)212 .foregroundStyle(dark ? Color.white : Color.black)213 .background(dark ? Color(white: 0.2) : Color.white, in: RoundedRectangle(cornerRadius: 8))214 .accessibilityElement(children: .ignore)215 .accessibilityLabel(Text("Dans la boîte de réception : \(sender), \(subject), \(preheader)"))216 }217}218219// MARK: - content220221struct VariableInsertMenu: View {222 let editor: EditorModel223 let field: ReferenceWritableKeyPath<EditorModel, String>224 var body: some View {225 Menu {226 ForEach(editor.liveVariables) { v in Button("{{\(v.name)}}") { editor.insert(variable: v.name, into: field) } }227 if editor.liveVariables.isEmpty { Text("Aucune variable dans ce modèle") }228 } label: { Label("Insérer une variable", systemImage: "curlybraces") }229 .labelStyle(.iconOnly).menuStyle(.borderlessButton).fixedSize()230 .help("Insérer une variable")231 }232}233234struct ContentPane: View {235 @Bindable var editor: EditorModel236 var body: some View {237 Form {238 Section("Modèle") {239 TextField("Nom", text: $editor.name)240 Picker("Catégorie", selection: $editor.category) { ForEach(editor.studio.categories, id: \.self) { c in Text(StudioText.category(c)).tag(c) } }241 }242 Section {243 HStack { TextField("Objet", text: $editor.subject, axis: .vertical).lineLimit(1...3); VariableInsertMenu(editor: editor, field: \.subject) }244 let n = editor.shownSubject.count245 Text(n > TemplateText.subjectHint ? L("\(n) caractères — au-delà de 60, l’objet est souvent coupé sur téléphone") : L("\(n) caractères")).font(.footnote).foregroundStyle(n > TemplateText.subjectHint ? Color.orange : Color.secondary)246 } header: { Text("Objet") }247 Section {248 HStack { TextField("Texte d’aperçu", text: $editor.preheader, axis: .vertical).lineLimit(1...4); VariableInsertMenu(editor: editor, field: \.preheader) }249 let n = editor.shownPreheader.count250 Text(TemplateText.preheaderRange.contains(n) ? L("\(n) caractères") : L("\(n) caractères — visez 40 à 110")).font(.footnote).foregroundStyle(TemplateText.preheaderRange.contains(n) || n == 0 ? Color.secondary : Color.orange)251 } header: { Text("Texte d’aperçu") } footer: { Text("Affiché après l’objet dans la liste des messages du destinataire.") }252 Section("Détails") {253 LabeledContent("Version", value: "\(editor.template.version)")254 LabeledContent("Taille du HTML", value: editor.htmlBytes.byteLabel)255 if editor.isClipped { Label("Au-delà d’environ 100 ko, Gmail coupe le message (« Message tronqué »).", systemImage: "scissors").font(.footnote).foregroundStyle(.orange) }256 if editor.template.isAI { LabeledContent("Origine", value: L("Généré par IA") + (editor.template.aiModel.map { " (\($0))" } ?? "")) }257 if !editor.template.designNotes.isEmpty { Text(editor.template.designNotes).font(.footnote).foregroundStyle(.secondary) }258 if let b = editor.template.aiBrief, !b.isEmpty { DisclosureGroup("Brief d’origine") { Text(b).font(.footnote).foregroundStyle(.secondary).textSelection(.enabled) } }259 }260 }261 .formStyle(.grouped)262 }263}264265// MARK: - variables266267struct VariablesPane: View {268 @Bindable var editor: EditorModel269270 private func binding(_ name: String, _ key: WritableKeyPath<TemplateVariable, String>) -> Binding<String> {271 Binding(get: { editor.variables.first { $0.name == name }?[keyPath: key] ?? "" }, set: { v in mutate(name) { $0[keyPath: key] = v } })272 }273 private func mutate(_ name: String, _ change: (inout TemplateVariable) -> Void) {274 if let n = editor.variables.firstIndex(where: { $0.name == name }) { change(&editor.variables[n]) } else { var v = TemplateVariable(name: name); change(&v); editor.variables.append(v) }275 editor.schedulePreview()276 }277278 var body: some View {279 let list = editor.liveVariables280 Form {281 Section {282 Toggle("Afficher les {{variables}} brutes", isOn: $editor.rawPlaceholders)283 Button("Revenir aux exemples") { editor.resetValues() }.disabled(editor.values.values.allSatisfy(\.isEmpty))284 } footer: { Text("Les valeurs saisies ici servent à l’aperçu seulement. Un champ vide prend l’exemple de la variable.") }285 if list.isEmpty {286 Section { Text("Ce modèle n’utilise aucune variable. Écrivez {{prenom}} dans l’objet ou le HTML pour en créer une.").foregroundStyle(.secondary) }287 }288 ForEach(list) { v in289 Section {290 TextField(v.example.isEmpty ? L("Valeur") : v.example, text: Binding(get: { editor.values[v.name] ?? "" }, set: { editor.values[v.name] = $0 }), axis: .vertical).lineLimit(1...4)291 .autocorrectionDisabled()292 .accessibilityLabel(Text("Valeur de \(v.name)"))293 DisclosureGroup("Définition") {294 TextField("Description", text: binding(v.name, \.description))295 TextField("Exemple", text: binding(v.name, \.example))296 Toggle("Obligatoire à l’envoi", isOn: Binding(get: { v.required }, set: { on in mutate(v.name) { $0.required = on } }))297 }298 } header: {299 HStack(spacing: 4) {300 Text("{{\(v.name)}}").font(.system(.subheadline, design: .monospaced)).textCase(nil)301 if v.required { Text("obligatoire").font(.caption2.bold()).textCase(nil).padding(.horizontal, 5).padding(.vertical, 1).background(Color.red.opacity(0.14), in: Capsule()).foregroundStyle(.red) }302 }303 } footer: { if !v.description.isEmpty { Text(v.description) } }304 }305 }306 .formStyle(.grouped)307 }308}309310// MARK: - tools: AI revision, versions, export311312struct ToolsPane: View {313 @Bindable var editor: EditorModel314 let export: (String, String, UTType) -> Void315 @State private var restoring: TemplateVersionInfo?316317 var body: some View {318 Form {319 Section {320 TextEditor(text: $editor.revisionBrief).frame(minHeight: 70).font(.body).accessibilityLabel(Text("Retouche demandée"))321 FlowLayout(spacing: 6) {322 ForEach(StudioText.revisionIdeas, id: \.fr) { idea in323 Button(editor.studio.language == "en" ? idea.en : idea.fr) { editor.revisionBrief = editor.studio.language == "en" ? idea.en : idea.fr }.buttonStyle(.bordered).controlSize(.mini)324 }325 Color.clear.frame(width: 1, height: 1)326 }327 if editor.generation.isRunning { GenerationProgress(run: editor.generation) }328 GenerationFailure(run: editor.generation) { Task { await editor.revise() } }329 Button { Task { await editor.revise() } } label: { Label("Retoucher", systemImage: "sparkles") }.disabled(!editor.canRevise || !editor.studio.aiConfigured)330 if editor.isDirty { Text("Enregistrez vos modifications avant de demander une retouche : l’IA part de la version enregistrée.").font(.footnote).foregroundStyle(.orange) }331 } header: { Text("Retoucher avec l’IA") } footer: { Text("Décrivez le changement voulu. Le résultat devient une nouvelle version ; la précédente reste dans l’historique.") }332333 Section("Versions") {334 LabeledContent(L("Version \(editor.template.version)"), value: L("actuelle"))335 ForEach(editor.versions) { v in336 VStack(alignment: .leading, spacing: 3) {337 HStack {338 Text("Version \(v.version)").font(.subheadline.weight(.medium))339 Spacer()340 if let d = v.createdAt { Text(d.formatted(.relative(presentation: .named))).font(.caption).foregroundStyle(.secondary) }341 }342 if !v.note.isEmpty { Text(v.note).font(.footnote).foregroundStyle(.secondary).lineLimit(2) }343 HStack {344 Button("Aperçu") { Task { await editor.preview(version: v.version) } }345 Button("Rétablir") { restoring = v }.disabled(editor.isDirty)346 }.buttonStyle(.borderless).font(.footnote)347 }348 .accessibilityElement(children: .contain)349 }350 if editor.versions.isEmpty { Text("Chaque enregistrement qui change le contenu crée une version.").font(.footnote).foregroundStyle(.secondary) }351 }352353 Section {354 let file = TemplateFile(name: editor.fileBase, html: editor.renderedHTML), raw = TemplateFile(name: editor.fileBase + "-variables", html: editor.html)355 ShareLink(item: file, preview: SharePreview(editor.name)) { Label("Partager le HTML rendu…", systemImage: "square.and.arrow.up") }356 ShareLink(item: raw, preview: SharePreview(editor.name)) { Label("Partager le HTML avec variables…", systemImage: "curlybraces") }357 Button { export(editor.fileBase + ".html", editor.renderedHTML, .html) } label: { Label("Enregistrer le HTML rendu…", systemImage: "square.and.arrow.down") }358 Button { export(editor.fileBase + "-variables.html", editor.html, .html) } label: { Label("Enregistrer le HTML avec variables…", systemImage: "square.and.arrow.down") }359 Button { Clipboard.copy(editor.renderedHTML); editor.studio.notice = L("HTML copié") } label: { Label("Copier le HTML rendu", systemImage: "doc.on.doc") }360 Button { Clipboard.copy(editor.renderedText); editor.studio.notice = L("Texte copié") } label: { Label("Copier la version texte", systemImage: "doc.plaintext") }361 #if os(macOS)362 Label("Glisser le fichier .html", systemImage: "hand.draw").foregroundStyle(.secondary).draggable(file).help("Faites glisser vers le Finder ou une autre app")363 #endif364 let bytes = editor.renderedHTML.utf8.count365 Label(TemplateText.isClipped(bytes: bytes) ? L("\(bytes.byteLabel) — au-delà d’environ 100 ko, Gmail coupe le message") : L("\(bytes.byteLabel) une fois rendu"), systemImage: TemplateText.isClipped(bytes: bytes) ? "scissors" : "scalemass")366 .font(.footnote).foregroundStyle(TemplateText.isClipped(bytes: bytes) ? Color.orange : Color.secondary)367 } header: { Text("Exporter") } footer: { Text("« Rendu » = variables remplacées par les valeurs de l’aperçu.") }368 }369 .formStyle(.grouped)370 .confirmationDialog("Rétablir cette version ?", isPresented: Binding(get: { restoring != nil }, set: { if !$0 { restoring = nil } }), titleVisibility: .visible, presenting: restoring) { v in371 Button("Rétablir la version \(v.version)") { Task { await editor.restore(version: v.version) } }372 Button("Annuler", role: .cancel) {}373 } message: { _ in Text("Le contenu de cette version devient une nouvelle version ; rien n’est perdu.") }374 }375}376377struct VersionPreviewView: View {378 let editor: EditorModel379 let version: TemplateVersion380 @State private var dark = false381 var body: some View {382 ScrollView([.vertical, .horizontal]) {383 VStack(spacing: 12) {384 InboxLine(sender: "SP Mail", subject: version.subject, preheader: version.preheader, dark: dark).frame(width: 600)385 TemplateWebPreview(document: TemplatePreview.document(html: version.html, scheme: dark ? .dark : .light), width: 600, api: editor.api)386 .background(dark ? Color(white: 0.09) : Color.white).id(dark)387 }.padding(16).frame(maxWidth: .infinity)388 }389 .background(dark ? Color(white: 0.16) : Color(white: 0.93))390 .navigationTitle(L("Version \(version.version)"))391 #if os(iOS)392 .navigationBarTitleDisplayMode(.inline)393 #endif394 .toolbar {395 ToolbarItem(placement: .cancellationAction) { Button("Fermer") { editor.versionPreview = nil } }396 ToolbarItem { Toggle(isOn: $dark) { Label("Sombre", systemImage: "moon") } }397 ToolbarItem(placement: .confirmationAction) { Button("Rétablir cette version") { Task { await editor.restore(version: version.version) } }.disabled(editor.isDirty) }398 }399 }400}401402// MARK: - send a template403404@MainActor @Observable405final class TemplateSendModel: RecipientHost {406 enum Phase: Equatable { case editing, sending, done, failed(String) }407 @ObservationIgnored let editor: EditorModel408 var senders: [SenderIdentity]409 var senderId: String410 var to: [EmailAddress] = []411 var values: [String: String]412 var subject = ""413 var scheduled = false414 var date = Date().addingTimeInterval(3600)415 var rendered: RenderedTemplate?416 var phase = Phase.editing417 var outcome: OutboundStatus?418 @ObservationIgnored private var key = UUID().uuidString419 @ObservationIgnored private var keyedRequest: TemplateSend?420 @ObservationIgnored private var previewTask: Task<Void, Never>?421422 init(editor: EditorModel) {423 self.editor = editor424 let app = editor.studio.app425 let list = app?.senders ?? []426 senders = list427 senderId = (list.first { $0.account == app?.currentAccount && !$0.isAlias } ?? list.first)?.id ?? ""428 values = editor.values.filter { !$0.value.isEmpty }429 }430431 var variables: [TemplateVariable] { editor.template.variables }432 var sender: SenderIdentity? { senders.first { $0.id == senderId } }433 var missing: [String] { TemplateSend.missing(variables, values: values) }434 var groups: [(mailbox: String, senders: [SenderIdentity])] {435 var out: [(mailbox: String, senders: [SenderIdentity])] = []436 for s in senders { if let n = out.firstIndex(where: { $0.senders.first?.account == s.account }) { out[n].senders.append(s) } else { out.append((s.email, [s])) } }437 return out438 }439 var dateIsValid: Bool { !scheduled || (date > Date().addingTimeInterval(30) && date < Date().addingTimeInterval(30 * 86400)) }440 var canSend: Bool { sender != nil && !to.isEmpty && missing.isEmpty && dateIsValid && phase != .sending && phase != .done }441442 func edited() { schedulePreview() }443 func suggestions(for prefix: String) async -> [EmailAddress] {444 let taken = Set(to.map(\.id))445 return (await editor.suggestions(for: prefix)).filter { !taken.contains($0.id) }446 }447448 /// What will really be sent: rendered without examples (an empty optional variable stays empty, as in the real message).449 func schedulePreview() {450 previewTask?.cancel()451 previewTask = Task { [weak self] in452 try? await Task.sleep(for: .milliseconds(400))453 guard let self, !Task.isCancelled else { return }454 if let r = try? await self.editor.api.renderTemplate(id: self.editor.id, values: self.values.filter { !$0.value.isEmpty }, useExamples: false), !Task.isCancelled { self.rendered = r }455 }456 }457458 var request: TemplateSend? {459 guard let sender else { return nil }460 return TemplateSend(from: sender.email, to: to, templateId: editor.id, variables: values.filter { !$0.value.isEmpty }, subject: subject, sendAt: scheduled ? date : nil)461 }462463 func send() async {464 guard canSend, let request else { return }465 // one key per distinct request: a retry of the same request can never send twice, a corrected request is a new one466 if keyedRequest != request { key = UUID().uuidString; keyedRequest = request }467 phase = .sending468 do {469 let out = try await editor.api.sendTemplate(request, idempotencyKey: key)470 outcome = out471 phase = out.status == "failed" ? .failed(out.lastError ?? L("Le serveur de courrier a refusé le message.")) : .done472 if !out.isFinal, !out.isScheduled { await follow(out.id) }473 } catch let e as APIError {474 phase = .failed(Self.describe(e))475 } catch { phase = .failed(error.localizedDescription) }476 }477478 /// Follows the delivery: `sent` only says the mail server took the message; each recipient becomes `delivered` or not on its own.479 private func follow(_ id: String) async {480 for _ in 0..<40 {481 try? await Task.sleep(for: .milliseconds(1500))482 if Task.isCancelled { return }483 guard let o = try? await editor.api.outbound(id: id) else { continue }484 outcome = o485 if o.isFinal { return }486 }487 }488489 static func describe(_ e: APIError) -> String {490 if e.isOffline { return L("Le serveur est injoignable : l’envoi d’un modèle se fait en ligne. Rien n’a été envoyé ; réessayez une fois connecté.") }491 switch e.code {492 case "missing_variables": return L("Des variables obligatoires sont vides : ") + e.message493 case "unknown_variables": return L("Le modèle a changé : certaines variables n’existent plus. Fermez et rouvrez cette fenêtre.")494 case "unknown_template": return L("Ce modèle n’existe plus sur le serveur.")495 case "from_not_allowed", "address_inactive", "address_cannot_send": return L("Cette adresse d’expédition ne peut pas envoyer pour l’instant.")496 case "send_at_too_far": return L("La date d’envoi ne peut pas dépasser 30 jours.")497 case "daily_send_limit_exceeded", "rate_limited": return L("Limite d’envoi atteinte. Réessayez plus tard.")498 case "invalid_request": return L("Le serveur a refusé cette demande : ") + e.message499 default: return e.message.isEmpty ? e.code : e.message500 }501 }502}503504struct TemplateSendView: View {505 @State var model: TemplateSendModel506 let onClose: () -> Void507508 var body: some View {509 @Bindable var model = model510 Form {511 if model.phase == .done || model.outcome != nil, let o = model.outcome { outcomeSection(o) }512 if case .failed(let m) = model.phase { Section { Label(m, systemImage: "exclamationmark.triangle.fill").foregroundStyle(.red) } }513 Section("Expéditeur et destinataires") {514 if model.senders.count > 1 {515 LabeledContent("De") { SenderPicker(groups: model.groups, selection: $model.senderId) }516 } else { LabeledContent("De", value: model.sender?.address.formatted ?? "—") }517 RecipientField(label: L("À"), addresses: $model.to, model: model)518 }519 Section {520 ForEach(model.variables) { v in521 HStack(alignment: .firstTextBaseline) {522 VStack(alignment: .leading, spacing: 1) {523 Text("{{\(v.name)}}").font(.system(.footnote, design: .monospaced))524 if v.required { Text("obligatoire").font(.caption2).foregroundStyle(.red) }525 }.frame(minWidth: 110, alignment: .leading)526 TextField(v.example.isEmpty ? L("Valeur") : L("ex. : \(v.example)"), text: Binding(get: { model.values[v.name] ?? "" }, set: { model.values[v.name] = $0; model.schedulePreview() }), axis: .vertical)527 .lineLimit(1...3).autocorrectionDisabled()528 .accessibilityLabel(Text(v.required ? L("\(v.name), obligatoire") : v.name))529 }530 }531 if model.variables.isEmpty { Text("Ce modèle n’a pas de variable.").foregroundStyle(.secondary) }532 if !model.missing.isEmpty { Label("À remplir : \(model.missing.joined(separator: ", "))", systemImage: "exclamationmark.circle").font(.footnote).foregroundStyle(.red) }533 } header: { Text("Variables") } footer: { Text("Aucune valeur d’exemple n’est envoyée : une variable facultative laissée vide reste vide.") }534 Section("Options") {535 TextField("Objet (laisser vide pour celui du modèle)", text: $model.subject)536 Toggle("Programmer l’envoi", isOn: $model.scheduled)537 if model.scheduled {538 DatePicker("Date d’envoi", selection: $model.date, in: Date()...Date().addingTimeInterval(30 * 86400))539 if !model.dateIsValid { Text("Choisissez une date à venir, dans les 30 jours.").font(.footnote).foregroundStyle(.red) }540 }541 }542 Section("Aperçu de l’envoi") {543 if let r = model.rendered {544 InboxLine(sender: model.sender?.name.isEmpty == false ? model.sender!.name : (model.sender?.email ?? ""), subject: model.subject.trimmingCharacters(in: .whitespaces).isEmpty ? r.subject : model.subject, preheader: r.preheader, dark: false)545 ScrollView(.horizontal) { TemplateWebPreview(document: TemplatePreview.document(html: r.html, scheme: .light), width: 520, api: model.editor.api).background(Color.white) }.frame(maxHeight: 420)546 } else { ProgressView() }547 }548 }549 .formStyle(.grouped)550 .navigationTitle("Envoyer « \(model.editor.name) »")551 #if os(iOS)552 .navigationBarTitleDisplayMode(.inline)553 #endif554 .toolbar {555 ToolbarItem(placement: .cancellationAction) { Button(model.phase == .done ? L("Fermer") : L("Annuler")) { onClose() } }556 ToolbarItem(placement: .confirmationAction) {557 Button { Task { await model.send() } } label: {558 if model.phase == .sending { ProgressView().controlSize(.small) } else { Label(model.scheduled ? L("Programmer") : L("Envoyer"), systemImage: model.scheduled ? "clock" : "paperplane.fill") }559 }.disabled(!model.canSend).keyboardShortcut("d", modifiers: [.command, .shift])560 }561 }562 .task { model.schedulePreview(); if model.senders.isEmpty { await model.editor.studio.app?.loadSenders(); model.senders = model.editor.studio.app?.senders ?? []; model.senderId = model.senders.first?.id ?? "" } }563 }564565 @ViewBuilder private func outcomeSection(_ o: OutboundStatus) -> some View {566 Section("État de l’envoi") {567 let l = OutboundLabels.label(o.status)568 Label(o.isScheduled ? L("Programmé pour le \((o.sendAt ?? model.date).formatted(date: .abbreviated, time: .shortened)) — annulable dans « Programmés »") : l.text, systemImage: l.icon).foregroundStyle(l.color)569 if !o.isScheduled {570 ForEach(o.recipients, id: \.address) { r in571 let rl = OutboundLabels.label(r.status)572 VStack(alignment: .leading, spacing: 2) {573 HStack { Text(r.address).font(.footnote); Spacer(); Label(rl.text, systemImage: rl.icon).font(.footnote).foregroundStyle(rl.color) }574 if let reply = r.smtpReply, ["bounced", "failed", "deferred"].contains(r.status) { Text(reply).font(.caption).foregroundStyle(.secondary).lineLimit(3) }575 }576 }577 if !o.isFinal { Text("« Accepté » signifie que le serveur de courrier a pris le message. « Remis » n’apparaît que lorsque le serveur du destinataire l’a accepté.").font(.caption).foregroundStyle(.secondary) }578 }579 if let e = o.lastError, o.status == "failed" { Text(e).font(.footnote).foregroundStyle(.red) }580 }581 }582}583