SPB Git

Repository Public

ComposeManagers.swift 31.2 KB 547 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Sources/Shared/Compose/ComposeManagers.swift3// Description: What the composer manages besides the message itself — signatures (rich text, default per address and for replies), snippets4// (`;shortcut` expansion, picker), « insert a template » from the templates library (as editable content, or sent as a template), and the5// « Rédaction » settings pane (undo-send delay, warnings, sensitive recipients).6import SPMailCore7import SwiftUI89/// A manager shown as a sheet from the composer: its own navigation stack and a close button.10struct ManagerSheet<Content: View>: View {11    let title: String12    @ViewBuilder var content: () -> Content13    @Environment(\.dismiss) private var dismiss14    var body: some View {15        NavigationStack {16            content()17                .navigationTitle(title)18                .toolbar { ToolbarItem(placement: .confirmationAction) { Button("OK") { dismiss() } } }19        }20        .frame(minWidth: 520, minHeight: 460)21    }22}2324/// A small rich text field with its formatting bar (signatures, snippets).25struct MiniRichEditor: View {26    let editor: RichTextController27    @State private var showLink = false28    var body: some View {29        VStack(alignment: .leading, spacing: 6) {30            FormatBar(editor: editor, showLink: $showLink)31            Divider()32            RichTextEditorView(controller: editor, minHeight: 110)33        }34        .padding(SPSpacing.m)35        .background(SPColor.surface, in: RoundedRectangle(cornerRadius: SPRadius.card, style: .continuous))36        .overlay(RoundedRectangle(cornerRadius: SPRadius.card, style: .continuous).stroke(SPColor.border, lineWidth: 0.5))37        .sheet(isPresented: $showLink) { LinkEditor(editor: editor, isPresented: $showLink).presentationDetents([.height(250)]) }38    }39}4041// MARK: - signatures4243struct SignatureManager: View {44    let center: ComposeCenter45    @State private var creating = false4647    var body: some View {48        List {49            Section {50                ForEach(center.signatures) { s in51                    NavigationLink { SignatureEditor(center: center, signature: s) } label: {52                        VStack(alignment: .leading, spacing: 2) {53                            HStack { Text(s.name.isEmpty ? L("Signature") : s.name); if s.isReadOnly { StatusBadge(text: L("Adresse"), icon: "at", color: SPColor.text2, soft: SPColor.surface3) } }54                            Text(defaults(s)).font(SPFont.caption).foregroundStyle(SPColor.text3).lineLimit(1)55                        }56                    }57                }58                if center.signatures.isEmpty { Text("Aucune signature. Créez-en une : elle pourra être la signature par défaut d’une adresse, ou de ses réponses.").foregroundStyle(SPColor.text3) }59            } footer: {60                Text("Une signature choisie par défaut pour une adresse remplace la signature historique de cette adresse. Changer d’expéditeur dans un message remplace la signature, sauf si vous l’avez modifiée.")61            }62            if let e = center.lastError { Section { Label(e, systemImage: "exclamationmark.triangle").foregroundStyle(SPColor.danger) } }63        }64        .toolbar { ToolbarItem(placement: .primaryAction) { Button { creating = true } label: { Label("Nouvelle signature", systemImage: "plus") } } }65        .navigationDestination(isPresented: $creating) { SignatureEditor(center: center, signature: nil) }66        .task { await center.load() }67    }6869    private func defaults(_ s: Signature) -> String {70        func names(_ ids: [String]) -> String { ids.compactMap { id in center.addresses.first { $0.id == id }?.address }.joined(separator: ", ") }71        var parts: [String] = []72        if !s.defaultFor.isEmpty { parts.append(L("Nouveaux messages : \(names(s.defaultFor))")) }73        if !s.defaultForReplies.isEmpty { parts.append(L("Réponses : \(names(s.defaultForReplies))")) }74        return parts.isEmpty ? L("Aucune adresse par défaut") : parts.joined(separator: " · ")75    }76}7778struct SignatureEditor: View {79    let center: ComposeCenter80    let signature: Signature?81    @State private var name = ""82    @State private var editor = RichTextController()83    @State private var defaultFor: Set<String> = []84    @State private var defaultForReplies: Set<String> = []85    @State private var confirmDelete = false86    @State private var saving = false87    @Environment(\.dismiss) private var dismiss8889    private var readOnly: Bool { signature?.isReadOnly == true }9091    var body: some View {92        Form {93            if readOnly {94                Section { Text("Signature historique de l’adresse. Elle reste la signature par défaut tant qu’aucune autre signature ne réclame cette adresse ; elle se modifie dans « Signatures » des réglages.").foregroundStyle(SPColor.text3) }95            }96            Section("Nom") { TextField("Nom de la signature", text: $name).disabled(readOnly).accessibilityLabel(Text("Nom de la signature")) }97            Section("Contenu") { MiniRichEditor(editor: editor).disabled(readOnly).listRowInsets(EdgeInsets()) }98            if !readOnly {99                Section("Par défaut pour les nouveaux messages") { ForEach(sendable) { a in Toggle(a.address, isOn: binding($defaultFor, a.id)) } }100                Section("Par défaut pour les réponses") { ForEach(sendable) { a in Toggle(a.address, isOn: binding($defaultForReplies, a.id)) } }101                if signature != nil { Section { Button("Supprimer la signature", role: .destructive) { confirmDelete = true } } }102            }103        }104        .formStyle(.grouped)105        .navigationTitle(signature == nil ? L("Nouvelle signature") : (name.isEmpty ? L("Signature") : name))106        .toolbar {107            if !readOnly {108                ToolbarItem(placement: .primaryAction) {109                    Button("Enregistrer") { Task { await save() } }.disabled(name.trimmingCharacters(in: .whitespaces).isEmpty || saving)110                }111            }112        }113        .confirmationDialog("Supprimer cette signature ?", isPresented: $confirmDelete, titleVisibility: .visible) {114            Button("Supprimer", role: .destructive) { Task { if let s = signature { await center.deleteSignature(id: s.id) }; dismiss() } }115            Button("Annuler", role: .cancel) {}116        }117        .onAppear {118            guard let s = signature else { return }119            name = s.name120            defaultFor = Set(s.defaultFor); defaultForReplies = Set(s.defaultForReplies)121            let parsed = s.html.isEmpty ? RichText.attributed(fromPlain: s.text) : RichHTML.parse(s.html, mode: .paste, allowedCIDs: []).text122            editor.setDocument(parsed.length > 0 ? parsed : RichText.attributed(fromPlain: s.text))123        }124    }125126    private var sendable: [MailAddress] { center.addresses.filter(\.isSendable) }127    private func binding(_ set: Binding<Set<String>>, _ id: String) -> Binding<Bool> {128        Binding(get: { set.wrappedValue.contains(id) }, set: { if $0 { set.wrappedValue.insert(id) } else { set.wrappedValue.remove(id) } })129    }130    private func save() async {131        saving = true132        let doc = editor.document133        let content = SignatureContent(name: name.trimmingCharacters(in: .whitespaces), html: RichHTML.html(from: doc), text: RichHTML.plainText(from: doc),134                                       defaultFor: Array(defaultFor).sorted(), defaultForReplies: Array(defaultForReplies).sorted())135        await center.saveSignature(id: signature?.id, content)136        saving = false137        dismiss()138    }139}140141// MARK: - snippets142143struct SnippetManager: View {144    let center: ComposeCenter145    @State private var creating = false146147    var body: some View {148        List {149            Section {150                ForEach(center.snippets) { s in151                    NavigationLink { SnippetEditor(center: center, snippet: s) } label: { SnippetRow(snippet: s) }152                }153                if center.snippets.isEmpty { Text("Aucun extrait. Un extrait est un texte que vous réutilisez : tapez son raccourci précédé d’un point-virgule, par exemple « ;merci », pour l’insérer.").foregroundStyle(SPColor.text3) }154            }155            if let e = center.lastError { Section { Label(e, systemImage: "exclamationmark.triangle").foregroundStyle(SPColor.danger) } }156        }157        .toolbar { ToolbarItem(placement: .primaryAction) { Button { creating = true } label: { Label("Nouvel extrait", systemImage: "plus") } } }158        .navigationDestination(isPresented: $creating) { SnippetEditor(center: center, snippet: nil) }159        .task { await center.load() }160    }161}162163struct SnippetRow: View {164    let snippet: Snippet165    var body: some View {166        HStack(spacing: SPSpacing.m) {167            VStack(alignment: .leading, spacing: 2) {168                Text(snippet.name.isEmpty ? L("Extrait") : snippet.name).foregroundStyle(SPColor.text)169                Text(snippet.text.replacingOccurrences(of: "\n", with: " ")).font(SPFont.caption).foregroundStyle(SPColor.text3).lineLimit(1)170            }171            Spacer()172            if let sc = snippet.shortcut, !sc.isEmpty { Text(";" + sc).font(SPFont.mono).foregroundStyle(SPColor.accent).padding(.horizontal, 6).padding(.vertical, 2).background(SPColor.accentSoft, in: RoundedRectangle(cornerRadius: SPRadius.chip)) }173        }174        .accessibilityElement(children: .combine)175    }176}177178struct SnippetEditor: View {179    let center: ComposeCenter180    let snippet: Snippet?181    @State private var name = ""182    @State private var shortcut = ""183    @State private var subject = ""184    @State private var editor = RichTextController()185    @State private var confirmDelete = false186    @State private var saving = false187    @Environment(\.dismiss) private var dismiss188189    private var shortcutTaken: Bool { !shortcut.isEmpty && center.snippets.contains { $0.shortcut == shortcut.lowercased() && $0.id != snippet?.id } }190    private var shortcutValid: Bool { shortcut.isEmpty || Snippet.isValidShortcut(shortcut.lowercased()) }191192    var body: some View {193        Form {194            Section("Nom") { TextField("Nom de l’extrait", text: $name).accessibilityLabel(Text("Nom de l’extrait")) }195            Section {196                HStack(spacing: 2) {197                    Text(";").font(SPFont.mono).foregroundStyle(SPColor.text3)198                    TextField("raccourci", text: $shortcut).font(SPFont.mono).autocorrectionDisabled()199                        #if os(iOS)200                        .textInputAutocapitalization(.never)201                        #endif202                        .accessibilityLabel(Text("Raccourci"))203                }204            } header: { Text("Raccourci") } footer: {205                if !shortcutValid { Text("Lettres minuscules, chiffres, tiret et soulignement, 24 caractères au plus.").foregroundStyle(SPColor.danger) }206                else if shortcutTaken { Text("Ce raccourci est déjà utilisé par un autre extrait.").foregroundStyle(SPColor.danger) }207                else { Text("Dans un message, tapez « ;\(shortcut.isEmpty ? "raccourci" : shortcut.lowercased()) » puis une espace.") }208            }209            Section("Objet (facultatif)") { TextField("Objet proposé quand le message n’en a pas", text: $subject).accessibilityLabel(Text("Objet")) }210            Section("Contenu") { MiniRichEditor(editor: editor).listRowInsets(EdgeInsets()) }211            if snippet != nil { Section { Button("Supprimer l’extrait", role: .destructive) { confirmDelete = true } } }212        }213        .formStyle(.grouped)214        .navigationTitle(snippet == nil ? L("Nouvel extrait") : (name.isEmpty ? L("Extrait") : name))215        .toolbar {216            ToolbarItem(placement: .primaryAction) {217                Button("Enregistrer") { Task { await save() } }.disabled(name.trimmingCharacters(in: .whitespaces).isEmpty || !shortcutValid || shortcutTaken || editor.isEmpty || saving)218            }219        }220        .confirmationDialog("Supprimer cet extrait ?", isPresented: $confirmDelete, titleVisibility: .visible) {221            Button("Supprimer", role: .destructive) { Task { if let s = snippet { await center.deleteSnippet(id: s.id) }; dismiss() } }222            Button("Annuler", role: .cancel) {}223        }224        .onAppear {225            guard let s = snippet else { return }226            name = s.name; shortcut = s.shortcut ?? ""; subject = s.subject ?? ""227            editor.setDocument(SnippetExpander.content(of: s))228        }229    }230231    private func save() async {232        saving = true233        let doc = editor.document234        let content = SnippetContent(name: name.trimmingCharacters(in: .whitespaces), shortcut: shortcut.lowercased(), subject: subject, html: RichHTML.html(from: doc), text: RichHTML.plainText(from: doc))235        await center.saveSnippet(id: snippet?.id, content)236        saving = false237        dismiss()238    }239}240241/// Pick a snippet to insert at the insertion point.242struct SnippetPicker: View {243    let center: ComposeCenter244    let insert: (Snippet) -> Void245    let manage: () -> Void246    @State private var query = ""247    @Environment(\.dismiss) private var dismiss248249    private var shown: [Snippet] {250        let q = query.folding(options: [.diacriticInsensitive, .caseInsensitive], locale: nil)251        guard !q.isEmpty else { return center.snippets }252        return center.snippets.filter { ($0.name + " " + ($0.shortcut ?? "") + " " + $0.text).folding(options: [.diacriticInsensitive, .caseInsensitive], locale: nil).contains(q) }253    }254255    var body: some View {256        NavigationStack {257            List {258                ForEach(shown) { s in Button { insert(s) } label: { SnippetRow(snippet: s) }.buttonStyle(.plain) }259                if center.snippets.isEmpty { Text("Aucun extrait pour l’instant.").foregroundStyle(SPColor.text3) }260            }261            .searchable(text: $query, prompt: Text("Rechercher un extrait"))262            .navigationTitle("Insérer un extrait")263            .toolbar {264                ToolbarItem(placement: .cancellationAction) { Button("Annuler") { dismiss() } }265                ToolbarItem(placement: .primaryAction) { Button("Gérer…", action: manage) }266            }267        }268        .frame(minWidth: 440, minHeight: 380)269        .task { await center.load() }270    }271}272273// MARK: - insert a template274275/// The templates library inside the composer: fill the variables, then insert the rendered content as editable text — or send the276/// template itself (its layout is kept; the composer's recipients, sender and subject are used).277struct TemplateInsertSheet: View {278    let model: ComposeModel279    /// nil = closed without sending; a result = the template was sent in place of the draft.280    let done: (SendResult?) -> Void281    @State private var templates: [MailTemplate] = []282    @State private var loaded = false283    @State private var error: String?284    @State private var selected: MailTemplate?285286    var body: some View {287        NavigationStack {288            List {289                ForEach(templates) { t in290                    Button { selected = t } label: {291                        VStack(alignment: .leading, spacing: 2) {292                            Text(t.name).foregroundStyle(SPColor.text)293                            Text(t.subject).font(SPFont.caption).foregroundStyle(SPColor.text3).lineLimit(1)294                        }295                        .frame(maxWidth: .infinity, alignment: .leading).contentShape(Rectangle())296                    }297                    .buttonStyle(.plain)298                }299                if loaded, templates.isEmpty, error == nil { Text("Aucun modèle. Créez-en dans le studio de modèles.").foregroundStyle(SPColor.text3) }300                if let error { Label(error, systemImage: "exclamationmark.triangle").foregroundStyle(SPColor.danger) }301            }302            .overlay { if !loaded { ProgressView().controlSize(.small) } }303            .navigationTitle("Insérer un modèle")304            .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Annuler") { done(nil) } } }305            .navigationDestination(item: $selected) { t in TemplateFill(model: model, template: t, done: done) }306        }307        .frame(minWidth: 480, minHeight: 440)308        .task {309            guard let api = model.app?.api else { return }310            do { templates = try await api.templates().templates } catch { self.error = model.app?.describe(error) ?? error.localizedDescription }311            loaded = true312        }313    }314}315316struct TemplateFill: View {317    let model: ComposeModel318    let template: MailTemplate319    let done: (SendResult?) -> Void320    @State private var values: [String: String] = [:]321    @State private var rendered: RenderedTemplate?322    @State private var busy = false323    @State private var error: String?324325    private var missing: [String] { TemplateSend.missing(template.variables, values: values) }326327    var body: some View {328        Form {329            if !template.variables.isEmpty {330                Section("Variables") {331                    ForEach(template.variables) { v in332                        LabeledContent(v.required ? "\(v.name) *" : v.name) {333                            TextField(v.example.isEmpty ? v.description : v.example, text: Binding(get: { values[v.name] ?? "" }, set: { values[v.name] = $0 }))334                                .accessibilityLabel(Text(v.name))335                        }336                    }337                }338            }339            Section("Aperçu") {340                if let rendered {341                    Text(rendered.subject).font(SPFont.bodyStrong)342                    Text(rendered.text.isEmpty ? HTMLText.plainText(fromHTML: rendered.html) : rendered.text).font(.callout).foregroundStyle(SPColor.text2).lineLimit(12)343                } else { ProgressView().controlSize(.small) }344            }345            if let error { Section { Label(error, systemImage: "exclamationmark.triangle").foregroundStyle(SPColor.danger) } }346            Section {347                Button { Task { await insert() } } label: { Label("Insérer dans le message (texte modifiable)", systemImage: "text.insert") }.disabled(busy || !missing.isEmpty)348                Button { Task { await send() } } label: { Label("Envoyer comme modèle (mise en page conservée)", systemImage: "paperplane") }.disabled(busy || !missing.isEmpty || !model.canSend)349            } footer: {350                if !missing.isEmpty { Text("À remplir : \(missing.joined(separator: ", "))") }351                else if !model.canSend { Text("Pour envoyer comme modèle, ajoutez d’abord un destinataire au message.") }352                else { Text("« Insérer » place le texte du modèle dans votre message, où vous pouvez le retoucher ; sa mise en page (colonnes, couleurs) n’est conservée que par « Envoyer comme modèle ».") }353            }354        }355        .formStyle(.grouped)356        .navigationTitle(template.name)357        .task(id: values) {358            try? await Task.sleep(for: .milliseconds(350))359            guard !Task.isCancelled, let api = model.app?.api else { return }360            if let r = try? await api.renderTemplate(id: template.id, values: values.filter { !$0.value.isEmpty }, useExamples: false), !Task.isCancelled { rendered = r }361        }362    }363364    private func insert() async {365        guard let api = model.app?.api else { return }366        busy = true367        defer { busy = false }368        do {369            let r = try await api.renderTemplate(id: template.id, values: values.filter { !$0.value.isEmpty }, useExamples: false)370            let parsed = RichHTML.parse(r.html, mode: .paste, allowedCIDs: []).text371            model.editor.insert(rich: parsed.length > 0 ? parsed : RichText.attributed(fromPlain: r.text), actionName: L("Modèle"))372            if model.subject.isEmpty { model.setSubject(r.subject) }373            done(nil)374        } catch { self.error = model.app?.describe(error) ?? error.localizedDescription }375    }376377    /// Sends the template itself to the composer's recipients (`ComposeModel.deliverTemplate`). A sensitive recipient goes through the378    /// composer's confirmation dialog, exactly as a normal send does: the sheet closes and the composer asks.379    private func send() async {380        busy = true381        defer { busy = false }382        let result = await model.deliverTemplate(TemplateDelivery(templateId: template.id, values: values))383        if case .failed(let message) = result { error = message.isEmpty ? L("Le serveur a refusé le message") : message; return }384        done(result)385    }386}387388// MARK: - settings pane « Rédaction »389390/// Undo-send delay, warnings before sending, sensitive recipients; signatures and snippets. Stored on the server (same on every device).391struct ComposeSettings: View {392    let app: AppModel393    @State private var newSensitive = ""394    @State private var invalid = false395396    var body: some View {397        let center = app.compose398        Form {399            Section {400                Picker("Délai d’annulation de l’envoi", selection: Binding(get: { center.prefs.undoSeconds }, set: { v in update { $0.undoSeconds = v } })) {401                    ForEach(Self.delays(including: center.prefs.undoSeconds), id: \.self) { s in Text(s == 0 ? L("Aucun") : L("\(s) secondes")).tag(s) }402                }403            } header: { Text("Annuler l’envoi") } footer: {404                Text("Pendant ce délai, le message est retenu par le serveur : « Annuler l’envoi » le reprend avant qu’il ne parte. Sans connexion au moment d’envoyer, il n’y a pas de délai.")405            }406            Section("Avant d’envoyer") {407                Toggle("Prévenir si une pièce jointe semble oubliée", isOn: Binding(get: { center.prefs.warnMissingAttachment }, set: { v in update { $0.warnMissingAttachment = v } }))408                Toggle("Prévenir avant d’écrire hors de mes domaines", isOn: Binding(get: { center.prefs.warnExternal }, set: { v in update { $0.warnExternal = v } }))409            }410            Section {411                ForEach(center.prefs.sensitive, id: \.self) { entry in412                    HStack {413                        Image(systemName: entry.hasPrefix("@") ? "building.2" : "person").foregroundStyle(SPColor.text3)414                        Text(entry)415                        Spacer()416                        Button { update { $0.sensitive.removeAll { $0 == entry } } } label: { Image(systemName: "minus.circle") }.buttonStyle(.borderless).foregroundStyle(SPColor.danger)417                            .accessibilityLabel(Text("Retirer \(entry)"))418                    }419                }420                HStack {421                    TextField("adresse@exemple.org ou @domaine.org", text: $newSensitive).autocorrectionDisabled()422                        #if os(iOS)423                        .textInputAutocapitalization(.never).keyboardType(.emailAddress)424                        #endif425                        .onSubmit(addSensitive)426                        .accessibilityLabel(Text("Destinataire sensible à ajouter"))427                    Button("Ajouter", action: addSensitive).disabled(newSensitive.trimmingCharacters(in: .whitespaces).isEmpty)428                }429                if invalid { Text("Entrez une adresse complète ou un domaine précédé de @.").font(SPFont.caption).foregroundStyle(SPColor.danger) }430            } header: { Text("Destinataires sensibles") } footer: {431                Text("Avant tout envoi à l’une de ces adresses — ou à ce domaine — une confirmation explicite est demandée, et rien ne part sans elle.")432            }433            Section("Signatures et extraits") {434                NavigationLink { SignatureManager(center: center).navigationTitle("Signatures") } label: { LabeledContent { Text("\(center.signatures.count)") } label: { Label("Signatures", systemImage: "signature") } }435                NavigationLink { SnippetManager(center: center).navigationTitle("Extraits") } label: { LabeledContent { Text("\(center.snippets.count)") } label: { Label("Extraits", systemImage: "text.badge.plus") } }436            }437            if center.nextUnavailable { Section { Label("Ce serveur ne propose pas encore ces réglages.", systemImage: "exclamationmark.triangle").foregroundStyle(SPColor.warn) } }438            else if !app.isOnline { Section { Label("Hors ligne — les changements seront envoyés au retour de la connexion.", systemImage: "wifi.slash").foregroundStyle(SPColor.warn) } }439        }440        .formStyle(.grouped)441        .task { await center.load(force: true) }442    }443444    static func delays(including current: Int) -> [Int] { ([0, 5, 10, 20, 30, 60] + [current]).reduce(into: [Int]()) { if !$0.contains($1) { $0.append($1) } }.sorted() }445446    private func update(_ change: (inout ComposePrefs) -> Void) {447        var p = app.compose.prefs448        change(&p)449        Task { await app.compose.setPrefs(p) }450    }451    private func addSensitive() {452        let t = newSensitive.trimmingCharacters(in: .whitespaces).lowercased()453        let ok = AddressParser.isValid(t) || (t.hasPrefix("@") && AddressParser.isValid("x" + t))454        guard ok else { invalid = true; return }455        invalid = false; newSensitive = ""456        update { if !$0.sensitive.contains(t) { $0.sensitive.append(t) } }457    }458}459460/// The « Rédaction » pane hosted in the macOS Settings window (its own navigation stack, for the signature and snippet managers).461struct ComposeSettingsPane: View {462    let app: AppModel463    var body: some View { NavigationStack { ComposeSettings(app: app) } }464}465466// MARK: - design captures467468#if DEBUG469/// `-spmDemo YES -spmScene compose -spmComposeDemo rich|undo|toast|later|signatures`: fills the composer with representative content for design captures (DEBUG only, demo data).470@MainActor471enum ComposeDemo {472    static func runIfRequested(_ model: ComposeModel, show: (String) -> Void) async {473        guard let scene = UserDefaults.standard.string(forKey: "spmComposeDemo"), !scene.isEmpty else { return }474        try? await Task.sleep(for: .milliseconds(500))475        model.to = [EmailAddress(name: "Camille Tremblay", email: "camille.tremblay@example.org"), EmailAddress(name: "Olivier Roy", email: "olivier.roy@example.org"), EmailAddress(email: "adresse-invalide")]476        model.showCcBcc = true477        model.cc = [EmailAddress(name: "Équipe budget", email: "budget@example.org")]478        model.subject = "Compte rendu — suite et prochaines étapes"479        let html = "<h2>Compte rendu de la réunion</h2><div>Bonjour Camille,</div><div><br></div><div>Voici les <b>trois décisions</b> prises ce matin, avec le <a href=\"https://example.org/budget\">budget révisé</a> et la note <i>pour information</i> :</div><ul><li>le calendrier est <u>confirmé</u> ;</li><li>la salle B est réservée<ul><li>jeudi, 10 h</li></ul></li><li>l’ancienne version est <s>abandonnée</s>.</li></ul><ol><li>Relire le rapport</li><li>Valider <code>budget_v3.xlsx</code></li></ol><blockquote><div>« Livrer peu, livrer bien. »</div></blockquote>"480        let doc = NSMutableAttributedString(attributedString: RichHTML.parse(html, mode: .paste).text)481        if let png = demoImage(), let prepared = InlineImageCodec.prepare(png, name: "graphique.png") {482            doc.append(NSAttributedString(string: "\n", attributes: [RichKey.block: "p"]))483            model.editor.setDocument(doc)484            model.editor.selection = NSRange(location: doc.length, length: 0)485            model.addInlineImage(data: prepared.data, name: prepared.name)486            try? await Task.sleep(for: .milliseconds(400))487            model.editor.selection = NSRange(location: max(0, model.editor.storage.length - 1), length: 1)488            model.editor.refresh()489            model.resizeSelectedImage(to: .medium)490        } else { model.editor.setDocument(doc) }491        model.editor.selection = NSRange(location: model.editor.storage.length, length: 0)492        model.editor.insert(text: "\nMerci,\nSimon-Pierre")493        model.addAttachment(name: "Budget révisé.xlsx", type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", data: Data(count: 184_220))494        model.addAttachment(name: "Rapport.pdf", type: "application/pdf", data: Data(count: 2_412_800))495        if let png = demoImage() { model.addAttachment(name: "Plan de salle.png", type: "image/png", data: png) }496        // a selection, so that the formatting bar shows active states497        let s = model.editor.storage.string as NSString498        let r = s.range(of: "trois décisions")499        if r.location != NSNotFound { model.editor.selection = r; model.editor.refresh() }500        if scene == "undo" || scene == "toast", let app = model.app {501            // the countdown toast, as after a real send (nothing is sent here)502            if let o = SendOutcome(json: ["id": "msg_out_demo000000", "status": "scheduled", "from": "demo@example.org", "recipients": [], "undo_until": .string(ISO8601DateFormatter().string(from: Date().addingTimeInterval(45)))]) { app.compose.addHold(o, item: nil, data: [:]) }503        }504        #if os(macOS)505        // a window tall enough to show the whole composer in one capture506        if let window = NSApp.windows.first(where: { $0.title == model.subject }) {507            var frame = window.frame508            let height: CGFloat = 1040509            frame.origin.y -= height - frame.height510            frame.size = CGSize(width: 780, height: height)511            if let screen = window.screen?.visibleFrame { frame.origin.y = max(screen.minY, frame.origin.y); frame.size.height = min(height, screen.height) }512            window.setFrame(frame, display: true)513        }514        #endif515        show(scene)516        if scene == "toast", let app = model.app { await model.discard(); app.composerClosed(model.id); app.main.composeRequest = nil } // as after a real send: the composer is gone517        #if os(iOS)518        if scene == "rich" { try? await Task.sleep(for: .milliseconds(600)); model.editor.focus() } // the keyboard and its formatting bar519        #endif520    }521522    static func demoImage() -> Data? {523        let size = CGSize(width: 480, height: 180)524        #if os(macOS)525        // drawn in a bitmap of exactly that many pixels, whatever the screen526        guard let rep = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: Int(size.width), pixelsHigh: Int(size.height), bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false, colorSpaceName: .deviceRGB, bytesPerRow: 0, bitsPerPixel: 0),527              let context = NSGraphicsContext(bitmapImageRep: rep) else { return nil }528        NSGraphicsContext.saveGraphicsState()529        NSGraphicsContext.current = context530        NSColor(red: 0.88, green: 0.93, blue: 0.91, alpha: 1).setFill(); CGRect(origin: .zero, size: size).fill()531        NSColor(red: 0.17, green: 0.36, blue: 0.30, alpha: 1).setFill()532        for (n, h) in [0.35, 0.55, 0.42, 0.78, 0.63, 0.9].enumerated() { NSBezierPath(roundedRect: CGRect(x: 40 + CGFloat(n) * 70, y: 20, width: 44, height: 140 * h), xRadius: 5, yRadius: 5).fill() }533        NSGraphicsContext.restoreGraphicsState()534        return rep.representation(using: .png, properties: [:])535        #else536        let format = UIGraphicsImageRendererFormat()537        format.scale = 1 // the same pixels on every device538        return UIGraphicsImageRenderer(size: size, format: format).pngData { ctx in539            UIColor(red: 0.88, green: 0.93, blue: 0.91, alpha: 1).setFill(); ctx.fill(CGRect(origin: .zero, size: size))540            UIColor(red: 0.17, green: 0.36, blue: 0.30, alpha: 1).setFill()541            for (n, h) in [0.35, 0.55, 0.42, 0.78, 0.63, 0.9].enumerated() { UIBezierPath(roundedRect: CGRect(x: 40 + CGFloat(n) * 70, y: 160 - 140 * h, width: 44, height: 140 * h), cornerRadius: 5).fill() }542        }543        #endif544    }545}546#endif547
Files main
Menu

Theme