Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Sources/Shared/Compose/ComposeViews.swift3// Description: The composer view — header (sender, signature, recipient tokens, subject), formatting bar, rich text, the quoted original as4// an untouched collapsible block, attachment tray (thumbnails, Quick Look, size meter, reorder, drop), footer with the draft state and5// the send split button (send · send later · send and remind), and the checks a send goes through before anything leaves.6import PhotosUI7import QuickLook8import SPMailCore9import SwiftUI10import UniformTypeIdentifiers1112// MARK: - composer1314struct ComposeView: View {15 @Bindable var model: ComposeModel16 var onClose: () -> Void17 @State private var showImporter = false18 @State private var importImages = false19 @State private var showPhotos = false20 @State private var photos: [PhotosPickerItem] = []21 @State private var dropTargeted = false22 @State private var showLink = false23 @State private var showSignatures = false24 @State private var showSnippets = false25 @State private var showSnippetManager = false26 @State private var showTemplates = false27 @State private var showLater = false28 @State private var showQuote = false29 @State private var check: SendCheck?30 @State private var mode = SendMode.now31 @State private var skipped: Set<String> = []32 @Environment(\.horizontalSizeClass) private var sizeClass3334 private var center: ComposeCenter? { model.app?.compose }35 /// iPhone (and a narrow iPad window): the formatting bar rides on the keyboard instead of sitting above the text.36 private var usesAccessoryBar: Bool {37 #if os(iOS)38 sizeClass == .compact39 #else40 false41 #endif42 }4344 var body: some View {45 VStack(spacing: 0) {46 if model.conflictNotice { banner(L("Ce brouillon a été modifié sur un autre appareil : les deux versions sont conservées."), icon: "arrow.triangle.branch", tint: SPColor.warn) { model.conflictNotice = false } }47 ScrollView {48 VStack(alignment: .leading, spacing: 10) {49 header50 Divider()51 if !usesAccessoryBar {52 FormatBar(editor: model.editor, model: model, showLink: $showLink)53 Divider()54 }55 editor56 if model.hasQuote { quote }57 if !model.files.isEmpty || model.attachmentError != nil { AttachmentTray(model: model) }58 }59 .frame(maxWidth: .infinity, alignment: .leading)60 .padding(SPSpacing.xl)61 .disabled(model.isLocked)62 }63 .scrollDismissesKeyboard(.interactively)64 Divider().overlay(SPColor.border)65 footer66 }67 .background(SPColor.surface)68 // drop target: accent-soft with a 2 pt accent outline69 .overlay { if dropTargeted { RoundedRectangle(cornerRadius: SPRadius.card, style: .continuous).stroke(SPColor.accent, lineWidth: 2).background(SPColor.accentSoft.opacity(0.35)).allowsHitTesting(false) } }70 .focusedSceneValue(model)71 .task { await model.prepare() }72 .onChange(of: model.attachRequest) { _, _ in importImages = false; showImporter = true }73 .onChange(of: model.imageRequest) { _, _ in74 #if os(iOS)75 showPhotos = true76 #else77 importImages = true; showImporter = true78 #endif79 }80 .onChange(of: model.linkRequest) { _, _ in showLink = true }81 .onChange(of: model.snippetRequest) { _, _ in showSnippets = true }82 .onChange(of: model.templateRequest) { _, _ in showTemplates = true }83 .onChange(of: model.sendRequest) { _, _ in attempt(.now) }84 .onDrop(of: [.fileURL, .image, .data], isTargeted: $dropTargeted) { providers in85 DropLoader.load(providers) { name, type, data in86 // dropped on the composer (outside the text): pictures and files alike are attached87 model.addAttachment(name: name, type: type, data: data)88 }89 return true90 }91 .fileImporter(isPresented: $showImporter, allowedContentTypes: importImages ? [.image] : [.item], allowsMultipleSelection: true) { result in92 guard case .success(let urls) = result else { return }93 if importImages { model.addDropped(urls: urls) } else { urls.forEach(model.addAttachment(url:)) }94 }95 .photosPicker(isPresented: $showPhotos, selection: $photos, maxSelectionCount: 8, matching: .images)96 .onChange(of: photos) { _, items in97 guard !items.isEmpty else { return }98 Task {99 for item in items {100 guard let data = try? await item.loadTransferable(type: Data.self) else { continue }101 let ext = item.supportedContentTypes.first?.preferredFilenameExtension ?? "jpg"102 model.addInlineImage(data: data, name: "photo.\(ext)")103 }104 photos = []105 }106 }107 .modifier(LinkPresentation(isPresented: $showLink, editor: model.editor, popover: !usesAccessoryBar))108 .sheet(isPresented: $showSignatures) { if let center { ManagerSheet(title: L("Signatures")) { SignatureManager(center: center) } } }109 .sheet(isPresented: $showSnippetManager) { if let center { ManagerSheet(title: L("Extraits")) { SnippetManager(center: center) } } }110 .sheet(isPresented: $showSnippets) { if let center { SnippetPicker(center: center, insert: { s in insert(snippet: s) }, manage: { showSnippets = false; showSnippetManager = true }) } }111 .sheet(isPresented: $showTemplates) {112 TemplateInsertSheet(model: model) { result in113 showTemplates = false114 guard let result else { return }115 // the confirmation dialog of a sensitive recipient is presented once the sheet is gone (an alert asked for while a sheet116 // is still closing is dropped)117 if case .needsConfirmation = result { Task { try? await Task.sleep(for: .milliseconds(500)); finish(result) } } else { finish(result) }118 }119 }120 .sheet(isPresented: Binding(get: { model.assistant.isPresented }, set: { if !$0 { model.cancelAssist() } })) { WritingAssistantSheet(model: model) }121 .sheet(isPresented: $showLater) { SendLaterSheet { date in showLater = false; if let date { attempt(.later(date)) } } }122 .alert(check?.title ?? "", isPresented: Binding(get: { check != nil }, set: { if !$0 { check = nil } }), presenting: check) { c in123 checkButtons(c)124 } message: { c in Text(c.message) }125 .toolbar { toolbar }126 .onChange(of: model.subject) { _, _ in model.edited() }127 .onChange(of: model.to) { _, _ in model.edited() }128 .onChange(of: model.cc) { _, _ in model.edited() }129 .onChange(of: model.bcc) { _, _ in model.edited() }130 .onChange(of: model.senderId) { old, _ in model.senderChanged(from: old) }131 .onChange(of: model.includeQuote) { _, _ in model.edited() }132 #if DEBUG133 .task { await ComposeDemo.runIfRequested(model) { what in if what == "later" { showLater = true } else if what == "signatures" { showSignatures = true } else { showQuote = true } } }134 #endif135 }136137 @ToolbarContentBuilder private var toolbar: some ToolbarContent {138 #if os(iOS)139 ToolbarItem(placement: .confirmationAction) { SendSplitButton(model: model, send: attempt, custom: { showLater = true }) }140 #endif141 ToolbarItem(placement: .cancellationAction) {142 Button { Task { await model.close(); onClose() } } label: { Label("Fermer", systemImage: "xmark") }143 .help("Fermer et garder le brouillon")144 }145 ToolbarItemGroup(placement: .primaryAction) {146 Button { model.attachRequest += 1 } label: { Label("Joindre un fichier", systemImage: "paperclip") }.help("Joindre un fichier (⇧⌘A)")147 Menu {148 Button { showSnippets = true } label: { Label("Insérer un extrait…", systemImage: "text.badge.plus") }149 Button { showTemplates = true } label: { Label("Insérer un modèle…", systemImage: "rectangle.on.rectangle.angled") }150 if model.assistantAvailable { Menu { WritingAssistantItems(model: model) } label: { Label("Aide à la rédaction", systemImage: "sparkles") }.disabled(model.isLocked) }151 Divider()152 Button { showSignatures = true } label: { Label("Gérer les signatures…", systemImage: "signature") }153 Button { showSnippetManager = true } label: { Label("Gérer les extraits…", systemImage: "text.badge.star") }154 Divider()155 Button(role: .destructive) { Task { await model.discard(); model.app?.composerClosed(model.id); onClose() } } label: { Label("Supprimer le brouillon", systemImage: "trash") }156 } label: { Label("Plus", systemImage: "ellipsis.circle") }157 }158 }159160 // MARK: header161162 private var header: some View {163 VStack(alignment: .leading, spacing: 8) {164 HStack(spacing: 8) {165 Text("De").foregroundStyle(SPColor.text3).frame(minWidth: 34, alignment: .leading)166 if model.availableSenders.count > 1 {167 #if os(iOS)168 // a menu whose label can shrink: a long address is truncated in the middle instead of pushing the header off screen169 Menu {170 Picker("De", selection: $model.senderId) {171 ForEach(model.senderGroups, id: \.mailbox) { g in172 Section(g.mailbox) { ForEach(g.senders) { s in Text(s.isAlias ? L("\(s.address.formatted) — alias") : s.address.formatted).tag(s.id) } }173 }174 }175 } label: {176 HStack(spacing: 4) {177 Text(usesAccessoryBar ? (model.sender?.email ?? "") : (model.sender?.address.formatted ?? "")).lineLimit(1).truncationMode(.middle)178 Image(systemName: "chevron.up.chevron.down").imageScale(.small)179 }180 .foregroundStyle(SPColor.accent).frame(minHeight: 32)181 }182 .accessibilityLabel(Text("Expéditeur"))183 .accessibilityValue(Text(model.sender?.email ?? ""))184 #else185 SenderPicker(groups: model.senderGroups, selection: $model.senderId).fixedSize()186 #endif187 } else if let i = model.sender { Text(i.address.formatted).foregroundStyle(SPColor.text2).lineLimit(1).truncationMode(.middle) }188 Spacer(minLength: 4)189 if let center { SignaturePicker(model: model, center: center, showManager: $showSignatures, compact: usesAccessoryBar) }190 }191 Divider()192 HStack(alignment: .top) {193 RecipientField(label: L("À"), addresses: $model.to, model: model, kind: .to)194 if !model.showCcBcc { Button("Cc/Cci") { model.showCcBcc = true }.buttonStyle(.borderless).font(.callout) }195 }196 if model.showCcBcc {197 Divider()198 RecipientField(label: L("Cc"), addresses: $model.cc, model: model, kind: .cc)199 Divider()200 RecipientField(label: L("Cci"), addresses: $model.bcc, model: model, kind: .bcc)201 }202 Divider()203 HStack {204 Text("Objet").foregroundStyle(SPColor.text3)205 TextField("", text: $model.subject).textFieldStyle(.plain).accessibilityLabel(Text("Objet"))206 }207 }208 }209210 @ViewBuilder private var editor: some View {211 #if os(iOS)212 let model = model213 let link = $showLink214 RichTextEditorView(controller: model.editor, minHeight: model.hasQuote ? 140 : 220, accessory: usesAccessoryBar ? {215 let host = UIHostingController(rootView: FormatBar(editor: model.editor, model: model, accessory: true, showLink: link).background(.bar))216 host.view.frame = CGRect(x: 0, y: 0, width: 320, height: 46)217 host.view.autoresizingMask = [.flexibleWidth]218 host.view.backgroundColor = .clear219 model.editor.accessoryHost = host220 return host.view221 } : nil)222 .id(usesAccessoryBar)223 #else224 RichTextEditorView(controller: model.editor, minHeight: model.hasQuote ? 140 : 220)225 #endif226 }227228 // MARK: quoted original229230 /// The original of a reply or a forward (or content the composer keeps as it is): never edited, shown collapsed, removable.231 private var quote: some View {232 VStack(alignment: .leading, spacing: 6) {233 HStack(spacing: SPSpacing.l) {234 if model.includeQuote {235 Button { spWithAnimation { showQuote.toggle() } } label: {236 Label(showQuote ? (model.quoteIsOriginal ? L("Masquer le message cité") : L("Masquer le contenu d’origine")) : (model.quoteIsOriginal ? L("Afficher le message cité") : L("Afficher le contenu d’origine")),237 systemImage: showQuote ? "chevron.down" : "ellipsis")238 .font(SPFont.callout).padding(.horizontal, 8).padding(.vertical, 3)239 .background(SPColor.surface2, in: Capsule()).foregroundStyle(SPColor.text2)240 }241 .buttonStyle(.plain)242 Spacer()243 Button { model.includeQuote = false } label: { Label(model.quoteIsOriginal ? L("Retirer le message cité") : L("Retirer le contenu d’origine"), systemImage: "xmark").font(SPFont.callout) }244 .buttonStyle(.borderless).foregroundStyle(SPColor.text3)245 } else {246 Label(model.quoteIsOriginal ? L("Le message cité ne sera pas envoyé.") : L("Le contenu d’origine ne sera pas envoyé."), systemImage: "text.badge.minus").font(SPFont.callout).foregroundStyle(SPColor.text3)247 Spacer()248 Button("Rétablir") { model.includeQuote = true }.buttonStyle(.borderless).font(SPFont.callout)249 }250 }251 if model.includeQuote, showQuote {252 Text(model.quotedPreview).font(.callout).foregroundStyle(SPColor.text2).textSelection(.enabled)253 .frame(maxWidth: .infinity, alignment: .leading)254 .padding(.leading, 10).overlay(alignment: .leading) { Rectangle().fill(SPColor.borderStrong).frame(width: 2) }255 .accessibilityLabel(Text("Message cité"))256 }257 }258 }259260 private func banner(_ text: String, icon: String, tint: SPToken, dismiss: @escaping () -> Void) -> some View {261 HStack(spacing: SPSpacing.m) {262 Image(systemName: icon).foregroundStyle(tint)263 Text(text).font(SPFont.callout).foregroundStyle(SPColor.text)264 Spacer()265 Button(action: dismiss) { Image(systemName: "xmark") }.buttonStyle(.borderless).accessibilityLabel(Text("Fermer"))266 }267 .padding(.horizontal, SPSpacing.xl).padding(.vertical, SPSpacing.m).background(SPColor.warnSoft)268 }269270 // MARK: footer271272 private var footer: some View {273 HStack(spacing: SPSpacing.m) {274 DraftStateLabel(model: model)275 Spacer(minLength: SPSpacing.m)276 if model.status == .unconfirmed {277 Button("Modifier quand même") { model.unlockAfterUnconfirmedSend() }.buttonStyle(.borderless).font(SPFont.callout)278 Button("Réessayer") { attempt(mode) }.buttonStyle(.borderedProminent)279 }280 #if os(macOS)281 if model.status != .unconfirmed { SendSplitButton(model: model, send: attempt, custom: { showLater = true }) }282 #endif283 }284 .font(.callout).padding(.horizontal, SPSpacing.xl).padding(.vertical, SPSpacing.m).background(SPColor.surface2)285 }286287 // MARK: sending288289 /// Send with this mode, after the checks: recipients, subject, announced attachment, external and sensitive recipients.290 private func attempt(_ wanted: SendMode) {291 mode = wanted292 skipped = []293 model.pendingTemplate = nil // a normal send: a template that was waiting for a confirmation is given up294 advance()295 }296297 private func advance(confirmSensitive: Bool = false) {298 guard !model.isLocked || model.status == .unconfirmed else { return }299 // the confirmation of a template send: the SAME template leaves, never the draft underneath300 if confirmSensitive, let template = model.pendingTemplate {301 Task { finish(await model.deliverTemplate(template, confirmSensitive: true)) }302 return303 }304 let issues = model.recipientIssues305 if issues.none { check = .noRecipient; return }306 if !issues.invalid.isEmpty { check = .invalid(issues.invalid.map(\.email)); return }307 if !issues.duplicates.isEmpty, !skipped.contains("duplicates") { check = .duplicates(issues.duplicates.map(\.email)); return }308 if model.missingSubject, !skipped.contains("subject") { check = .noSubject; return }309 let prefs = center?.prefs ?? ComposePrefs()310 if prefs.warnMissingAttachment, !skipped.contains("attachment"), MissingAttachmentDetector.shouldWarn(model.currentMessage()) { check = .missingAttachment; return }311 if prefs.warnExternal, !skipped.contains("external") {312 let mine = Set((center?.addresses.map { $0.address } ?? []).map { EmailAddress(email: $0).domain } + model.senders.map { $0.address.domain })313 let external = (model.to + model.cc + model.bcc).filter { !mine.contains($0.domain) }.map(\.email)314 if !external.isEmpty { check = .external(external); return }315 }316 if case .later(let date) = mode, !SendLaterPreset.isValid(date) { check = .badDate; return }317 Task {318 let result = await model.deliver(mode, confirmSensitive: confirmSensitive)319 finish(result)320 }321 }322323 @ViewBuilder private func checkButtons(_ c: SendCheck) -> some View {324 switch c {325 case .noRecipient, .invalid, .badDate: Button("OK", role: .cancel) {}326 case .duplicates:327 Button("Retirer les doublons et envoyer") { model.removeDuplicateRecipients(); skipped.insert("duplicates"); advance() }328 Button("Annuler", role: .cancel) {}329 case .noSubject:330 Button("Envoyer") { skipped.insert("subject"); advance() }331 Button("Annuler", role: .cancel) {}332 case .missingAttachment:333 Button("Envoyer quand même") { skipped.insert("attachment"); advance() }334 Button("Joindre un fichier") { model.attachRequest += 1 }335 Button("Annuler", role: .cancel) {}336 case .external:337 Button("Envoyer") { skipped.insert("external"); advance() }338 Button("Annuler", role: .cancel) {}339 case .sensitive:340 Button("Confirmer et envoyer") { advance(confirmSensitive: true) }341 Button("Annuler", role: .cancel) { model.pendingTemplate = nil }342 }343 }344345 /// What the interface says is what the server said — never « envoyé » before it took the message.346 private func finish(_ result: SendResult) {347 guard let app = model.app else { return }348 var closes = true349 switch result {350 case .held: SPHaptics.selection() // the countdown toast of the session takes over (« Envoi dans N s »)351 case .accepted(let o):352 SPHaptics.success()353 app.toast = Toast(message: OutboundLabels.label(o.outbound.status).text, kind: o.outbound.status == "sent" || o.outbound.status == "delivered" ? .success : .info)354 case .scheduled(let o):355 let at = (o.outbound.sendAt ?? Date()).formatted(date: .abbreviated, time: .shortened)356 app.toast = Toast(message: L("Programmé pour le \(at) (\(TimeZone.current.localizedName(for: .shortGeneric, locale: .current) ?? TimeZone.current.identifier))"), kind: .info, actionTitle: L("Annuler"), action: { await app.compose.undo(o.id) })357 case .pendingApproval(let o): app.toast = Toast(message: OutboundLabels.label(o.outbound.status).text, kind: .warning)358 case .acceptedByOutbox:359 SPHaptics.success()360 app.toast = Toast(message: L("Accepté pour livraison"), kind: .success)361 case .queuedOffline:362 app.toast = Toast(message: L("En attente (hors ligne) — le message partira au retour de la connexion, sans délai d’annulation."), kind: .warning)363 case .needsConfirmation(let recipients): check = .sensitive(recipients); closes = false364 case .unconfirmed, .failed: SPHaptics.warning(); closes = false365 }366 if closes {367 app.composerClosed(model.id)368 Task { await app.reloadOutbox() }369 onClose()370 }371 }372373 private func insert(snippet: Snippet) {374 showSnippets = false375 model.editor.insert(rich: SnippetExpander.content(of: snippet), actionName: L("Extrait"))376 if model.subject.isEmpty, let s = snippet.subject, !s.isEmpty { model.subject = s }377 }378}379380/// A question a send must answer before it goes.381enum SendCheck: Identifiable {382 case noRecipient, invalid([String]), duplicates([String]), noSubject, missingAttachment, external([String]), sensitive([String]), badDate383 var id: String { title }384 var title: String {385 switch self {386 case .noRecipient: L("Aucun destinataire")387 case .invalid: L("Adresse invalide")388 case .duplicates: L("Destinataire en double")389 case .noSubject: L("Envoyer ce message sans objet ?")390 case .missingAttachment: L("Pièce jointe oubliée ?")391 case .external: L("Destinataires externes")392 case .sensitive: L("Destinataires sensibles")393 case .badDate: L("Date d’envoi invalide")394 }395 }396 var message: String {397 switch self {398 case .noRecipient: L("Ajoutez au moins un destinataire.")399 case .invalid(let l): L("Corrigez ou retirez : \(l.joined(separator: ", "))")400 case .duplicates(let l): L("Cette adresse figure plus d’une fois : \(l.joined(separator: ", "))")401 case .noSubject: L("L’objet est vide.")402 case .missingAttachment: L("Le message parle d’une pièce jointe, mais aucun fichier n’est joint.")403 case .external(let l): L("Ce message sort de vos domaines : \(l.joined(separator: ", "))")404 case .sensitive(let l): L("Vous avez marqué ces destinataires comme sensibles. Rien n’a été envoyé : confirmez pour envoyer à \(l.joined(separator: ", ")).")405 case .badDate: L("Choisissez une date entre une minute et trente jours à partir de maintenant.")406 }407 }408}409410/// « Enregistré » / « Enregistrement… » / « Hors ligne — conservé sur cet appareil », and what a send is doing.411struct DraftStateLabel: View {412 let model: ComposeModel413 var body: some View {414 let offline = model.app?.isOnline == false415 Group {416 switch model.status {417 case .editing:418 if offline { Label("Hors ligne — sans connexion, l’envoi ne peut pas être annulé", systemImage: "wifi.slash").foregroundStyle(SPColor.warn) } else { Text(" ") }419 case .saving: Label("Enregistrement…", systemImage: "arrow.triangle.2.circlepath").foregroundStyle(SPColor.text3)420 case .savedLocally: Label("Hors ligne — conservé sur cet appareil", systemImage: "internaldrive").foregroundStyle(offline ? SPColor.warn : SPColor.text3)421 case .savedOnServer: Label("Enregistré", systemImage: "checkmark.icloud").foregroundStyle(SPColor.text3)422 case .sending: HStack(spacing: 6) { ProgressView().controlSize(.small); Text("Envoi au serveur…") }423 case .queuedOffline: Label("En attente (hors ligne)", systemImage: "clock.arrow.circlepath").foregroundStyle(SPColor.warn)424 case .accepted: Label("Pris en charge par le serveur", systemImage: "checkmark.circle").foregroundStyle(SPColor.ok)425 case .unconfirmed: Label("Le serveur n’a pas confirmé l’envoi. Réessayez : le message ne partira pas deux fois.", systemImage: "questionmark.circle").foregroundStyle(SPColor.warn)426 case .failed(let m): Label(m.isEmpty ? L("Le serveur a refusé le message") : L("Refusé : ") + m, systemImage: "exclamationmark.triangle").foregroundStyle(SPColor.danger)427 }428 }429 .lineLimit(2)430 .accessibilityElement(children: .combine)431 }432}433434/// Presents the link editor: a popover from the format bar where there is room, a sheet on iPhone.435private struct LinkPresentation: ViewModifier {436 @Binding var isPresented: Bool437 let editor: RichTextController438 let popover: Bool439 func body(content: Content) -> some View {440 content.sheet(isPresented: $isPresented) {441 LinkEditor(editor: editor, isPresented: $isPresented)442 .presentationDetents([.height(250)])443 }444 }445}446447// MARK: - send split button448449/// Send · send later (presets and a custom date, in the local time zone) · send and remind me if nobody replies.450struct SendSplitButton: View {451 let model: ComposeModel452 let send: (SendMode) -> Void453 let custom: () -> Void454455 var body: some View {456 #if os(macOS)457 // one control, two targets: the label sends, the chevron opens the other ways of sending458 HStack(spacing: 0) {459 Button { send(.now) } label: {460 Label("Envoyer", systemImage: "paperplane.fill").labelStyle(.titleAndIcon).font(SPFont.bodyStrong).padding(.leading, 12).padding(.trailing, 10).frame(height: 30).contentShape(Rectangle())461 }462 .buttonStyle(.plain)463 .accessibilityLabel(Text("Envoyer"))464 Rectangle().fill(SPColor.onAccent.opacity(0.35)).frame(width: 1, height: 16)465 Menu { items } label: {466 Image(systemName: "chevron.down").font(.system(size: 10, weight: .bold)).frame(width: 28, height: 30).contentShape(Rectangle())467 }468 .menuStyle(.button).buttonStyle(.plain).menuIndicator(.hidden).fixedSize()469 .accessibilityLabel(Text("Autres façons d’envoyer"))470 }471 .foregroundStyle(SPColor.onAccent)472 .background(SPColor.accent, in: RoundedRectangle(cornerRadius: 8, style: .continuous))473 .opacity(model.canSend ? 1 : 0.45)474 .disabled(!model.canSend)475 .help("Envoyer (⇧⌘D) — le chevron programme l’envoi ou demande un rappel")476 #else477 Menu { items } label: {478 Label("Envoyer", systemImage: "paperplane.fill").labelStyle(.titleAndIcon)479 } primaryAction: { send(.now) }480 .disabled(!model.canSend)481 .accessibilityLabel(Text("Envoyer"))482 .accessibilityHint(Text("Ouvrez le menu pour envoyer plus tard ou demander un rappel."))483 #endif484 }485486 @ViewBuilder private var items: some View {487 let offline = model.app?.isOnline == false || model.app?.compose.nextUnavailable == true488 Button { send(.now) } label: { Label("Envoyer", systemImage: "paperplane") }489 Section(L("Envoyer plus tard — \(TimeZone.current.localizedName(for: .shortGeneric, locale: .current) ?? TimeZone.current.identifier)")) {490 ForEach(SendLaterPreset.options(), id: \.preset) { option in491 Button { send(.later(option.date)) } label: { Label("\(Self.title(option.preset)) — \(Self.short(option.date))", systemImage: "clock") }492 }493 Button { custom() } label: { Label("Choisir la date et l’heure…", systemImage: "calendar") }494 }495 .disabled(offline)496 Section(L("Envoyer et me rappeler s’il n’y a pas de réponse")) {497 ForEach(RemindPreset.allCases) { p in498 Button { send(.remind(p.date(), onlyIfNoReply: true)) } label: { Label("\(Self.title(p)) — \(Self.short(p.date()))", systemImage: "bell") }499 }500 }501 .disabled(offline)502 if offline { Text("Hors ligne : ni programmation, ni rappel, ni délai d’annulation.") }503 }504505 static func short(_ date: Date) -> String { date.formatted(.dateTime.weekday(.abbreviated).day().month(.abbreviated).hour().minute()) }506 static func title(_ p: SendLaterPreset) -> String {507 switch p {508 case .inOneHour: L("Dans une heure"); case .thisEvening: L("Ce soir"); case .tomorrowMorning: L("Demain matin"); case .tomorrowAfternoon: L("Demain après-midi"); case .mondayMorning: L("Lundi matin")509 }510 }511 static func title(_ p: RemindPreset) -> String {512 switch p {513 case .tomorrow: L("Demain"); case .inTwoDays: L("Dans 2 jours"); case .inFourDays: L("Dans 4 jours"); case .inOneWeek: L("Dans une semaine"); case .inTwoWeeks: L("Dans 2 semaines")514 }515 }516}517518/// A custom send date. The time zone is always said: a scheduled message leaves at that wall-clock time here.519struct SendLaterSheet: View {520 var initial: Date?521 let done: (Date?) -> Void522 @State private var date = Date().addingTimeInterval(3600)523524 var body: some View {525 NavigationStack {526 Form {527 DatePicker("Date et heure d’envoi", selection: $date, in: Date().addingTimeInterval(120)...Date().addingTimeInterval(30 * 86400))528 #if os(iOS)529 .datePickerStyle(.graphical)530 #endif531 LabeledContent("Fuseau horaire") { Text("\(TimeZone.current.localizedName(for: .generic, locale: .current) ?? TimeZone.current.identifier) (\(TimeZone.current.identifier))").foregroundStyle(SPColor.text2) }532 Text("Le message reste sur le serveur jusqu’à cette heure. Il peut être modifié ou annulé dans « Programmés ».").font(SPFont.caption).foregroundStyle(SPColor.text3)533 }534 .formStyle(.grouped)535 .navigationTitle("Envoyer plus tard")536 .toolbar {537 ToolbarItem(placement: .cancellationAction) { Button("Annuler") { done(nil) } }538 ToolbarItem(placement: .confirmationAction) { Button("Programmer") { done(date) }.disabled(!SendLaterPreset.isValid(date)) }539 }540 }541 .frame(minWidth: 380, minHeight: 300)542 .presentationDetents([.large])543 .onAppear { if let initial, SendLaterPreset.isValid(initial) { date = initial } }544 }545}546547// MARK: - attachment tray548549/// An attachment being dragged inside the tray (to reorder it).550struct TrayAttachmentTransfer: Codable, Transferable {551 var attachmentId: String552 static var transferRepresentation: some TransferRepresentation { CodableRepresentation(contentType: .json) }553}554555/// The files of the message: thumbnail or type glyph, Quick Look, remove, drag to reorder, total size against the limit.556struct AttachmentTray: View {557 @Bindable var model: ComposeModel558 @State private var preview: URL?559 @State private var target: String?560561 var body: some View {562 let files = model.files563 VStack(alignment: .leading, spacing: SPSpacing.m) {564 if !files.isEmpty {565 HStack(spacing: SPSpacing.m) {566 Label(files.count == 1 ? L("1 pièce jointe") : L("\(files.count) pièces jointes"), systemImage: "paperclip").font(SPFont.callout).foregroundStyle(SPColor.text2)567 let total = model.totalAttachmentBytes568 ProgressView(value: min(1, Double(total) / Double(ComposeModel.attachmentLimit))).frame(width: 72).tint(total > ComposeModel.attachmentLimit * 9 / 10 ? SPColor.warn : SPColor.accent)569 .accessibilityHidden(true)570 Text("\(total.byteLabel) sur \(ComposeModel.attachmentLimit.byteLabel)").font(SPFont.caption).foregroundStyle(SPColor.text3)571 Spacer()572 }573 .accessibilityElement(children: .combine)574 LazyVGrid(columns: [GridItem(.adaptive(minimum: 220, maximum: 380), spacing: SPSpacing.m)], alignment: .leading, spacing: SPSpacing.m) {575 ForEach(files) { a in chip(a) }576 }577 }578 if let e = model.attachmentError { Label(e, systemImage: "exclamationmark.triangle").font(.callout).foregroundStyle(SPColor.danger) }579 }580 .quickLookPreview($preview)581 .dropDestination(for: TrayAttachmentTransfer.self) { items, _ in582 // dropped after the last chip: to the end583 if let id = items.first?.attachmentId { model.moveAttachment(id, before: nil) }584 return !items.isEmpty585 }586 }587588 private func chip(_ a: OutgoingAttachment) -> some View {589 let risky = OutgoingAttachment.isDangerous(name: a.name, type: a.type)590 let model = model591 return AttachmentChip(info: AttachmentInfo(id: a.id, name: a.name, type: a.type, size: a.size, isRisky: risky), file: { await model.temporaryFile(for: a) }) {592 if risky { Image(systemName: "exclamationmark.triangle.fill").foregroundStyle(SPColor.warn).help("Ce type de fichier peut être bloqué par le destinataire.") }593 Button { Task { preview = await model.temporaryFile(for: a) } } label: { Image(systemName: "eye").frame(minWidth: 28, minHeight: 28) }594 .help("Coup d’œil").accessibilityLabel(Text("Aperçu de \(a.name)"))595 Button { model.removeAttachment(a) } label: { Image(systemName: "xmark.circle").frame(minWidth: 28, minHeight: 28) }596 .help("Retirer").accessibilityLabel(Text("Retirer \(a.name)"))597 }598 .overlay(alignment: .leading) { if target == a.id { RoundedRectangle(cornerRadius: 1).fill(SPColor.accent).frame(width: 3).padding(.vertical, 4).offset(x: -5) } }599 .draggable(TrayAttachmentTransfer(attachmentId: a.id)) { Label(a.name, systemImage: "doc").padding(6).background(SPColor.surface2, in: RoundedRectangle(cornerRadius: SPRadius.chip)) }600 .dropDestination(for: TrayAttachmentTransfer.self) { items, _ in601 if let id = items.first?.attachmentId { model.moveAttachment(id, before: a.id) }602 return !items.isEmpty603 } isTargeted: { on in target = on ? a.id : (target == a.id ? nil : target) }604 .contextMenu {605 Button("Coup d’œil") { Task { preview = await model.temporaryFile(for: a) } }606 Button("Retirer", role: .destructive) { model.removeAttachment(a) }607 }608 .accessibilityElement(children: .contain)609 .accessibilityLabel(Text("\(a.name), \(a.size.byteLabel)"))610 }611}612613/// Reads what was dropped on the composer: files from Finder or Files, pictures from Photos, items of the attachments gallery.614enum DropLoader {615 @MainActor616 static func load(_ providers: [NSItemProvider], add: @escaping @MainActor (_ name: String, _ type: String, _ data: Data) -> Void) {617 for p in providers {618 let suggested = p.suggestedName619 if p.hasItemConformingToTypeIdentifier(UTType.fileURL.identifier) {620 _ = p.loadObject(ofClass: URL.self) { url, _ in621 guard let url else { return }622 let scoped = url.startAccessingSecurityScopedResource()623 let data = try? Data(contentsOf: url)624 if scoped { url.stopAccessingSecurityScopedResource() }625 guard let data else { return }626 let type = UTType(filenameExtension: url.pathExtension)?.preferredMIMEType ?? "application/octet-stream"627 let name = url.lastPathComponent628 Task { @MainActor in add(name, type, data) }629 }630 continue631 }632 guard let id = p.registeredTypeIdentifiers.first(where: { UTType($0)?.conforms(to: .data) == true }) ?? p.registeredTypeIdentifiers.first else { continue }633 p.loadFileRepresentation(forTypeIdentifier: id) { url, _ in634 guard let url, let data = try? Data(contentsOf: url) else { return }635 let ut = UTType(id)636 let ext = url.pathExtension.isEmpty ? (ut?.preferredFilenameExtension ?? "") : url.pathExtension637 let base = suggested ?? url.deletingPathExtension().lastPathComponent638 let name = ext.isEmpty || base.lowercased().hasSuffix("." + ext.lowercased()) ? base : "\(base).\(ext)"639 let type = ut?.preferredMIMEType ?? UTType(filenameExtension: ext)?.preferredMIMEType ?? "application/octet-stream"640 Task { @MainActor in add(name, type, data) }641 }642 }643 }644}645646// MARK: - restoration (iOS / iPadOS)647648/// Remembers the composer open in a scene: after a relaunch (or when the scene is rebuilt) its draft is read back from the local outbox and649/// the sheet comes back. macOS restores composer windows by itself (value-based window group).650struct ComposeSheetRestoration: ViewModifier {651 let scene: MailScene652 let app: AppModel653 @SceneStorage("spm.openComposer") private var stored = ""654655 func body(content: Content) -> some View {656 content657 .onChange(of: scene.composeRequest) { _, id in stored = id ?? "" }658 .task(id: app.phase == .ready) {659 guard app.phase == .ready, !stored.isEmpty, scene.composeRequest == nil else { return }660 #if DEBUG661 if AppConfig.selfTest { return }662 #endif663 if await app.restoreComposer(id: stored) != nil { scene.composeRequest = stored } else { stored = "" }664 }665 }666}667