Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Sources/Shared/Next/ContactsViews.swift3// Description: Contacts — the list (search, favourites, groups, saved vs suggested), the contact card with the relationship view (recent4// messages across mailboxes, pending reminders), create / edit / delete, groups, merging duplicates, vCard import (file, drop) and export,5// and « add the sender to contacts ». The address book lives on the SP Mail server: the system Contacts framework is never asked.6import SPMailCore7import SwiftUI8import UniformTypeIdentifiers910enum ContactFilter: Hashable, Sendable {11 case saved, favorites, suggested, all, group(String)12}1314struct ContactEditRequest: Identifiable {15 let id = UUID()16 /// nil: a new contact (optionally prefilled from an address).17 var contact: Contact?18 var prefill: EmailAddress?19}2021@MainActor @Observable22final class ContactsState {23 var contacts: [Contact] = []24 var cursor: String?25 var query = ""26 var filter = ContactFilter.saved27 var groups: [ContactGroup] = []28 var selectedId: String?29 var selected: Contact?30 var history: ContactHistory?31 var historyError: String?32 var isLoading = false33 var isLoadingMore = false34 var error: String?35 var duplicates: [ContactDuplicates] = []36 var editor: ContactEditRequest?37 var showDuplicates = false38 var showGroups = false39 @ObservationIgnored var generation = 04041 func reset() { generation += 1; contacts = []; cursor = nil; query = ""; filter = .saved; groups = []; selectedId = nil; selected = nil; history = nil; historyError = nil; isLoading = false; error = nil; duplicates = []; editor = nil; showDuplicates = false; showGroups = false }42 func groupName(_ id: String) -> String { groups.first { $0.id == id }?.name ?? id }43}4445struct VCardDocument: FileDocument {46 static let readableContentTypes: [UTType] = [.vCard]47 var data: Data48 init(data: Data) { self.data = data }49 init(configuration: ReadConfiguration) throws { data = configuration.file.regularFileContents ?? Data() }50 func fileWrapper(configuration: WriteConfiguration) throws -> FileWrapper { FileWrapper(regularFileWithContents: data) }51}5253// MARK: - scene behaviour5455extension MailScene {56 private var contactQuery: ContactQuery {57 let c = next.contacts58 var q = ContactQuery(q: c.query.trimmingCharacters(in: .whitespaces), limit: 100)59 switch c.filter {60 case .saved: q.kind = .saved61 case .favorites: q.kind = .saved; q.favoritesOnly = true62 case .suggested: q.kind = .suggested63 case .all: q.kind = .all64 case .group(let id): q.kind = .saved; q.group = id65 }66 return q67 }6869 func reloadContacts() async {70 let c = next.contacts71 c.generation += 172 let generation = c.generation73 if c.contacts.isEmpty { c.isLoading = true }74 defer { if generation == c.generation { c.isLoading = false } }75 let api = app.next.api76 do {77 let page = try await api.contacts(contactQuery)78 guard generation == c.generation else { return }79 c.contacts = page.contacts; c.cursor = page.nextCursor; c.error = nil80 if let groups = try? await api.contactGroups(), generation == c.generation { c.groups = groups }81 } catch {82 guard generation == c.generation, !(error is CancellationError) else { return }83 if NextError.isOffline(error) {84 // offline: the favourites cached on this device85 let q = c.query.trimmingCharacters(in: .whitespaces).lowercased()86 c.contacts = app.next.favorites.filter { q.isEmpty || $0.displayName.lowercased().contains(q) || $0.emails.contains { $0.email.lowercased().contains(q) } }87 c.cursor = nil88 c.error = L("Hors ligne — seuls les favoris enregistrés sur cet appareil sont affichés.")89 } else { c.error = app.next.describe(error) }90 }91 }9293 func loadMoreContacts(after contact: Contact) async {94 let c = next.contacts95 guard contact.id == c.contacts.last?.id, let cursor = c.cursor, !c.isLoadingMore else { return }96 c.isLoadingMore = true97 defer { c.isLoadingMore = false }98 var q = contactQuery99 q.cursor = cursor100 guard let page = try? await app.next.api.contacts(q), cursor == c.cursor else { return }101 let known = Set(c.contacts.map(\.id))102 c.contacts += page.contacts.filter { !known.contains($0.id) }103 c.cursor = page.nextCursor104 }105106 /// Shows a contact card: the row at once, then the fresh profile and the history of exchanges.107 func selectContact(_ contact: Contact?) async {108 let c = next.contacts109 c.selectedId = contact?.id; c.selected = contact; c.history = nil; c.historyError = nil110 guard let contact else { return }111 let api = app.next.api112 if let fresh = try? await api.contact(id: contact.id), c.selectedId == contact.id { c.selected = fresh }113 do {114 let h = try await api.contactHistory(id: contact.id, limit: 20)115 if c.selectedId == contact.id { c.history = h }116 } catch { if c.selectedId == contact.id { c.historyError = NextError.isOffline(error) ? L("L’historique n’est visible qu’en ligne.") : app.next.describe(error) } }117 }118119 private func replace(_ contact: Contact) {120 let c = next.contacts121 if let n = c.contacts.firstIndex(where: { $0.id == contact.id }) { c.contacts[n] = contact }122 if c.selectedId == contact.id { c.selected = contact }123 }124125 /// Creates or updates a contact; returns it, or nil (with a toast) when the server refused.126 @discardableResult127 func saveContact(_ existing: Contact?, _ content: ContactContent) async -> Contact? {128 do {129 if let existing {130 let updated = try await app.next.api.updateContact(id: existing.id, content)131 replace(updated)132 if next.contacts.filter == .suggested, updated.isSaved { next.contacts.contacts.removeAll { $0.id == updated.id } }133 return updated134 }135 let created = try await app.next.api.createContact(content)136 await reloadContacts()137 return created138 } catch { app.toast = Toast(message: app.next.describe(error) ?? "", kind: .error); return nil }139 }140141 func deleteContact(_ contact: Contact) async {142 do {143 try await app.next.api.deleteContact(id: contact.id)144 let c = next.contacts145 c.contacts.removeAll { $0.id == contact.id }146 if c.selectedId == contact.id { c.selectedId = nil; c.selected = nil; c.history = nil }147 } catch { app.toast = Toast(message: app.next.describe(error) ?? "", kind: .error) }148 }149150 func setFavorite(_ contact: Contact, _ on: Bool) async {151 var patched = contact152 patched.favorite = on153 replace(patched)154 await app.next.setFavorite(contact, on)155 }156 func setVIP(_ contact: Contact, _ on: Bool) async { await saveContact(contact, ContactContent(vip: on)) }157158 /// The saved or suggested contact that owns an address, if any.159 func contact(for email: String) async -> Contact? {160 guard app.next.has(.contacts), let page = try? await app.next.api.contacts(ContactQuery(q: email, kind: .all, limit: 5)) else { return nil }161 return page.contacts.first { $0.emails.contains { $0.email.caseInsensitiveCompare(email) == .orderedSame } }162 }163164 /// « Ajouter l’expéditeur aux contacts »: a harvested suggestion becomes a saved contact, an unknown address a new one.165 @discardableResult166 func addToContacts(_ address: EmailAddress) async -> Contact? {167 let known = await contact(for: address.email)168 if let known, known.isSaved { app.toast = Toast(message: L("\(known.displayName) est déjà dans vos contacts."), kind: .info); return known }169 let saved: Contact?170 if let known { saved = await saveContact(known, ContactContent(kind: .saved, name: known.name.isEmpty ? address.name : nil)) } else {171 saved = await saveContact(nil, ContactContent(kind: .saved, name: address.name ?? "", emails: [ContactEmail(email: address.email)]))172 }173 if let saved { app.toast = Toast(message: L("\(saved.displayName) ajouté aux contacts"), kind: .success) }174 return saved175 }176177 func importVCard(_ data: Data) async {178 do {179 let r = try await app.next.api.importContacts(vCard: data)180 app.toast = Toast(message: L("vCard importée : \(r.imported) nouveaux, \(r.updated) mis à jour, \(r.skipped) ignorés"), kind: r.imported + r.updated > 0 ? .success : .info)181 await reloadContacts()182 } catch { app.toast = Toast(message: app.next.describe(error) ?? "", kind: .error) }183 }184 func importVCard(url: URL) async {185 let scoped = url.startAccessingSecurityScopedResource()186 defer { if scoped { url.stopAccessingSecurityScopedResource() } }187 guard let data = try? Data(contentsOf: url) else { app.toast = Toast(message: L("Ce fichier ne peut pas être lu."), kind: .error); return }188 await importVCard(data)189 }190191 func loadDuplicates() async {192 do { next.contacts.duplicates = try await app.next.api.contactDuplicates() } catch { app.toast = Toast(message: app.next.describe(error) ?? "", kind: .error) }193 }194 @discardableResult195 func mergeContacts(keep: Contact, merge: [Contact]) async -> Contact? {196 do {197 let merged = try await app.next.api.mergeContacts(keep: keep.id, merge: merge.map(\.id))198 let gone = Set(merge.map(\.id))199 next.contacts.contacts.removeAll { gone.contains($0.id) }200 replace(merged)201 await loadDuplicates()202 return merged203 } catch { app.toast = Toast(message: app.next.describe(error) ?? "", kind: .error); return nil }204 }205206 /// Opens the Contacts screen on one contact (inspector, dashboard).207 func showContact(_ contact: Contact) {208 next.contacts.filter = contact.isSaved ? .saved : .all209 selection = .contacts210 Task { await selectContact(contact) }211 detailRequest += 1212 }213}214215// MARK: - list216217struct ContactRow: View {218 let contact: Contact219 var body: some View {220 HStack(spacing: SPSpacing.m) {221 AvatarView(name: contact.name, address: contact.primaryEmail ?? contact.name, size: 34)222 VStack(alignment: .leading, spacing: 1) {223 HStack(spacing: SPSpacing.xs) {224 Text(contact.displayName).font(SPFont.headline).foregroundStyle(SPColor.text).lineLimit(1)225 if contact.vip { Text("VIP").font(.caption2.weight(.bold)).foregroundStyle(SPColor.star).padding(.horizontal, 4).padding(.vertical, 1).overlay(Capsule().stroke(SPColor.star.opacity(0.5), lineWidth: 0.5)) }226 }227 Text([contact.name.isEmpty ? nil : contact.primaryEmail, contact.organization].compactMap { $0 }.joined(separator: " · ")).font(SPFont.callout).foregroundStyle(SPColor.text3).lineLimit(1).truncationMode(.middle)228 }229 Spacer(minLength: SPSpacing.s)230 if !contact.isSaved { Text("Suggéré").font(.caption2.weight(.medium)).foregroundStyle(SPColor.text3).padding(.horizontal, 6).padding(.vertical, 1.5).background(SPColor.surface3, in: Capsule()) }231 if contact.favorite { Image(systemName: "star.fill").imageScale(.small).foregroundStyle(SPColor.star).accessibilityLabel(Text("Favori")) }232 }233 .padding(.vertical, SPSpacing.s)234 .contentShape(Rectangle())235 .accessibilityElement(children: .combine)236 }237}238239struct ContactListView: View {240 @Bindable var scene: MailScene241 var onOpen: () -> Void242 @State private var importing = false243 @State private var exportDoc: VCardDocument?244 @State private var dropTargeted = false245 @State private var deleting: Contact?246247 private var app: AppModel { scene.app }248249 var body: some View {250 @Bindable var c = scene.next.contacts251 List(selection: Binding(get: { c.selectedId }, set: { id in252 #if os(macOS)253 if let id, id != c.selectedId, let contact = c.contacts.first(where: { $0.id == id }) { Task { await scene.selectContact(contact) }; onOpen() }254 #else255 _ = id256 #endif257 })) {258 if let e = c.error { OfflineNote(text: e) }259 ForEach(c.contacts) { contact in260 ContactRow(contact: contact)261 .tag(contact.id)262 #if os(iOS)263 .onTapGesture { Task { await scene.selectContact(contact) }; onOpen() }264 .hoverEffect(.highlight)265 #endif266 .listRowBackground(RowSelectionBackground(isSelected: c.selectedId == contact.id))267 .listRowSeparator(.hidden)268 .listRowInsets(EdgeInsets(top: 0, leading: SPSpacing.xl, bottom: 0, trailing: SPSpacing.xl))269 .contextMenu { menu(contact) }270 .swipeActions(edge: .leading) {271 Button { Task { await scene.setFavorite(contact, !contact.favorite) } } label: { Label(contact.favorite ? L("Retirer des favoris") : L("Favori"), systemImage: contact.favorite ? "star.slash" : "star") }.tint(SPColor.star)272 }273 .swipeActions(edge: .trailing) {274 Button(role: .destructive) { deleting = contact } label: { Label("Supprimer", systemImage: "trash") }275 if !contact.isSaved { Button { Task { await scene.saveContact(contact, ContactContent(kind: .saved)) } } label: { Label("Enregistrer", systemImage: "person.crop.circle.badge.plus") }.tint(SPColor.accent) }276 }277 .task { await scene.loadMoreContacts(after: contact) }278 .accessibilityAction(named: Text(contact.favorite ? "Retirer des favoris" : "Ajouter aux favoris")) { Task { await scene.setFavorite(contact, !contact.favorite) } }279 .accessibilityAddTraits(c.selectedId == contact.id ? .isSelected : [])280 }281 if c.isLoadingMore { HStack { Spacer(); ProgressView().controlSize(.small); Spacer() }.listRowBackground(Color.clear).listRowSeparator(.hidden) }282 }283 .listStyle(.plain).scrollContentBackground(.hidden).background(SPColor.bg)284 .overlay {285 if c.contacts.isEmpty {286 if c.isLoading { SkeletonRows(style: RowStyle(density: .cozy, previewLines: 0)).allowsHitTesting(false) } else if c.error == nil {287 SPEmptyState(icon: "person.2", title: c.query.isEmpty ? emptyTitle(c.filter) : L("Aucun contact trouvé"),288 message: c.filter == .saved && c.query.isEmpty ? L("Enregistrez un correspondant suggéré, créez un contact ou importez une vCard.") : nil,289 actionTitle: c.filter == .saved && c.query.isEmpty ? L("Voir les suggestions") : nil, action: { c.filter = .suggested })290 }291 }292 }293 .overlay { if dropTargeted { RoundedRectangle(cornerRadius: SPRadius.card, style: .continuous).stroke(SPColor.accent, lineWidth: 2).background(SPColor.accentSoft.opacity(0.4)).padding(6).allowsHitTesting(false) } }294 .dropDestination(for: URL.self) { urls, _ in295 let cards = urls.filter { ["vcf", "vcard"].contains($0.pathExtension.lowercased()) }296 guard !cards.isEmpty else { return false }297 Task { for u in cards { await scene.importVCard(url: u) } }298 return true299 } isTargeted: { dropTargeted = $0 }300 .navigationTitle("Contacts")301 .searchable(text: $c.query, prompt: Text("Nom, adresse, organisation"))302 .task(id: "\(c.query)|\(c.filter)") {303 try? await Task.sleep(for: .milliseconds(c.query.isEmpty ? 0 : 280))304 if !Task.isCancelled { await scene.reloadContacts() }305 }306 .refreshable { await scene.reloadContacts() }307 .toolbar { toolbar }308 .fileImporter(isPresented: $importing, allowedContentTypes: [.vCard], allowsMultipleSelection: false) { result in309 if case .success(let urls) = result, let url = urls.first { Task { await scene.importVCard(url: url) } }310 }311 .fileExporter(isPresented: Binding(get: { exportDoc != nil }, set: { if !$0 { exportDoc = nil } }), document: exportDoc, contentType: .vCard, defaultFilename: "SP Mail — contacts.vcf") { _ in exportDoc = nil }312 .sheet(item: $c.editor) { request in ContactEditorSheet(scene: scene, request: request) }313 .sheet(isPresented: $c.showDuplicates) { DuplicatesSheet(scene: scene) }314 .sheet(isPresented: $c.showGroups) { GroupsSheet(scene: scene) }315 .confirmationDialog("Supprimer ce contact ?", isPresented: Binding(get: { deleting != nil }, set: { if !$0 { deleting = nil } }), titleVisibility: .visible, presenting: deleting) { contact in316 Button("Supprimer", role: .destructive) { Task { await scene.deleteContact(contact) } }317 Button("Annuler", role: .cancel) {}318 } message: { _ in Text("Les messages échangés ne sont pas touchés.") }319 }320321 private func emptyTitle(_ f: ContactFilter) -> String {322 switch f { case .saved: L("Aucun contact enregistré"); case .favorites: L("Aucun favori"); case .suggested: L("Aucune suggestion"); case .all: L("Aucun contact"); case .group: L("Ce groupe est vide") }323 }324325 @ViewBuilder private func menu(_ contact: Contact) -> some View {326 if let address = contact.address { Button { compose(to: address) } label: { Label("Écrire", systemImage: "square.and.pencil") } }327 if !contact.isSaved { Button { Task { await scene.saveContact(contact, ContactContent(kind: .saved)) } } label: { Label("Enregistrer dans les contacts", systemImage: "person.crop.circle.badge.plus") } }328 Button { Task { await scene.setFavorite(contact, !contact.favorite) } } label: { Label(contact.favorite ? L("Retirer des favoris") : L("Ajouter aux favoris"), systemImage: "star") }329 Button { Task { await scene.setVIP(contact, !contact.vip) } } label: { Label(contact.vip ? L("Retirer des VIP") : L("Marquer VIP"), systemImage: "crown") }330 Button { scene.next.contacts.editor = ContactEditRequest(contact: contact) } label: { Label("Modifier…", systemImage: "pencil") }331 Divider()332 Button(role: .destructive) { deleting = contact } label: { Label("Supprimer", systemImage: "trash") }333 }334335 private func compose(to address: EmailAddress) {336 guard let url = URL(string: "mailto:" + (address.email.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? address.email)) else { return }337 Task { await scene.compose(.mailto(url)) }338 }339340 @ToolbarContentBuilder private var toolbar: some ToolbarContent {341 let c = scene.next.contacts342 ToolbarItem(placement: .primaryAction) {343 Button { c.editor = ContactEditRequest(contact: nil) } label: { Label("Nouveau contact", systemImage: "plus") }.help("Nouveau contact").disabled(!app.isOnline)344 }345 ToolbarItem(placement: .primaryAction) {346 Menu {347 Picker("Afficher", selection: Binding(get: { c.filter }, set: { c.filter = $0 })) {348 Text("Enregistrés").tag(ContactFilter.saved); Text("Favoris").tag(ContactFilter.favorites); Text("Suggérés").tag(ContactFilter.suggested); Text("Tous").tag(ContactFilter.all)349 ForEach(c.groups) { g in Text(g.memberCount.map { "\(g.name) (\($0))" } ?? g.name).tag(ContactFilter.group(g.id)) }350 }351 .pickerStyle(.inline)352 Divider()353 Button { c.showGroups = true } label: { Label("Groupes…", systemImage: "person.3") }354 Button { Task { await scene.loadDuplicates(); c.showDuplicates = true } } label: { Label("Fusionner les doublons…", systemImage: "arrow.triangle.merge") }355 Divider()356 Button { importing = true } label: { Label("Importer une vCard…", systemImage: "square.and.arrow.down") }357 Button { Task { if let data = try? await app.next.api.exportContacts() { exportDoc = VCardDocument(data: data) } else { app.toast = Toast(message: L("L’export n’est possible qu’en ligne."), kind: .info) } } } label: { Label("Exporter en vCard…", systemImage: "square.and.arrow.up") }358 } label: { Label("Filtrer et gérer", systemImage: "line.3.horizontal.decrease.circle") }359 .help("Filtrer, groupes, doublons, vCard")360 }361 }362}363364// MARK: - contact card365366struct ContactDetailView: View {367 @Bindable var scene: MailScene368 @State private var confirmDelete = false369 private var app: AppModel { scene.app }370371 var body: some View {372 let c = scene.next.contacts373 Group {374 if let contact = c.selected {375 ScrollView {376 VStack(alignment: .leading, spacing: SPSpacing.x3) {377 header(contact)378 if !contact.emails.isEmpty { section(L("Adresses")) { ForEach(contact.emails, id: \.email) { e in valueRow(e.label, e.email, icon: "envelope") { compose(to: EmailAddress(name: contact.name, email: e.email)) } } } }379 if !contact.phones.isEmpty { section(L("Téléphones")) { ForEach(contact.phones, id: \.number) { p in valueRow(p.label, p.number, icon: "phone", action: nil) } } }380 if contact.isSaved { groups(contact) }381 if let notes = contact.notes, !notes.isEmpty { section(L("Notes")) { Text(notes).font(SPFont.callout).foregroundStyle(SPColor.text).textSelection(.enabled).frame(maxWidth: .infinity, alignment: .leading) } }382 relationship(contact)383 }384 .padding(SPSpacing.x3)385 .frame(maxWidth: 720, alignment: .leading)386 .frame(maxWidth: .infinity)387 }388 } else {389 SPEmptyState(icon: "person.crop.circle", title: L("Aucun contact sélectionné"))390 }391 }392 .background(SPColor.surface.ignoresSafeArea())393 #if os(iOS)394 .navigationBarTitleDisplayMode(.inline)395 #endif396 .toolbar {397 if let contact = c.selected {398 ToolbarItemGroup(placement: .primaryAction) {399 if !contact.isSaved { Button { Task { await scene.saveContact(contact, ContactContent(kind: .saved)) } } label: { Label("Enregistrer dans les contacts", systemImage: "person.crop.circle.badge.plus") } }400 Button { c.editor = ContactEditRequest(contact: contact) } label: { Label("Modifier", systemImage: "pencil") }.help("Modifier le contact")401 Button(role: .destructive) { confirmDelete = true } label: { Label("Supprimer", systemImage: "trash") }.help("Supprimer le contact")402 }403 }404 }405 .confirmationDialog("Supprimer ce contact ?", isPresented: $confirmDelete, titleVisibility: .visible) {406 Button("Supprimer", role: .destructive) { if let contact = c.selected { Task { await scene.deleteContact(contact) } } }407 Button("Annuler", role: .cancel) {}408 } message: { Text("Les messages échangés ne sont pas touchés.") }409 }410411 private func header(_ contact: Contact) -> some View {412 HStack(alignment: .top, spacing: SPSpacing.xl) {413 AvatarView(name: contact.name, address: contact.primaryEmail ?? contact.name, size: 64)414 VStack(alignment: .leading, spacing: SPSpacing.xs) {415 Text(contact.displayName).font(SPFont.title).foregroundStyle(SPColor.text).textSelection(.enabled).fixedSize(horizontal: false, vertical: true).accessibilityAddTraits(.isHeader)416 let role = [contact.title, contact.organization].compactMap { $0 }.filter { !$0.isEmpty }.joined(separator: " · ")417 if !role.isEmpty { Text(role).font(SPFont.callout).foregroundStyle(SPColor.text2) }418 if !contact.isSaved { Text("Correspondant suggéré — pas encore dans vos contacts").font(SPFont.caption).foregroundStyle(SPColor.text3) }419 WrapLayout(spacing: SPSpacing.m) {420 if let address = contact.address { Button { compose(to: address) } label: { Label("Écrire", systemImage: "square.and.pencil") }.buttonStyle(.borderedProminent) }421 Toggle(isOn: Binding(get: { contact.favorite }, set: { on in Task { await scene.setFavorite(contact, on) } })) { Label("Favori", systemImage: contact.favorite ? "star.fill" : "star") }.toggleStyle(.button)422 Toggle(isOn: Binding(get: { contact.vip }, set: { on in Task { await scene.setVIP(contact, on) } })) { Label("VIP", systemImage: contact.vip ? "crown.fill" : "crown") }.toggleStyle(.button)423 .help("Les messages d’un contact VIP sont prioritaires pour les notifications")424 }425 .buttonStyle(.bordered)426 .padding(.top, SPSpacing.s)427 }428 }429 }430431 private func section<V: View>(_ title: String, @ViewBuilder _ content: () -> V) -> some View {432 VStack(alignment: .leading, spacing: SPSpacing.m) {433 SectionTitle(text: title)434 content()435 }436 }437438 private func valueRow(_ label: String?, _ value: String, icon: String, action: (() -> Void)?) -> some View {439 HStack(spacing: SPSpacing.m) {440 Image(systemName: icon).frame(width: 20).foregroundStyle(SPColor.text3)441 Text(value).font(SPFont.body).foregroundStyle(SPColor.text).textSelection(.enabled).lineLimit(1).truncationMode(.middle)442 if let label, !label.isEmpty { Text(label).font(SPFont.caption).foregroundStyle(SPColor.text3) }443 Spacer(minLength: 0)444 if let action { Button(action: action) { Image(systemName: "square.and.pencil").frame(minWidth: 28, minHeight: 28) }.buttonStyle(.borderless).help("Écrire à cette adresse").accessibilityLabel(Text("Écrire à \(value)")) }445 }446 }447448 @ViewBuilder private func groups(_ contact: Contact) -> some View {449 let all = scene.next.contacts.groups450 if !all.isEmpty {451 section(L("Groupes")) {452 WrapLayout(spacing: 6) {453 ForEach(all) { g in454 let on = contact.groups.contains(g.id)455 Button {456 var ids = contact.groups457 if on { ids.removeAll { $0 == g.id } } else { ids.append(g.id) }458 Task { await scene.saveContact(contact, ContactContent(groups: ids)) }459 } label: {460 HStack(spacing: 4) { if on { Image(systemName: "checkmark").imageScale(.small) }; Text(g.name) }461 .font(SPFont.caption).padding(.horizontal, 9).padding(.vertical, 4)462 .background(on ? AnyShapeStyle(SPColor.accentSoft) : AnyShapeStyle(SPColor.surface3), in: Capsule()).foregroundStyle(on ? SPColor.accent : SPColor.text2)463 }464 .buttonStyle(.plain).accessibilityAddTraits(on ? .isSelected : [])465 }466 }467 }468 }469 }470471 /// The relationship view: counters, reminders pending on this correspondent, the latest messages exchanged in any mailbox.472 @ViewBuilder private func relationship(_ contact: Contact) -> some View {473 let c = scene.next.contacts474 section(L("Échanges")) {475 HStack(spacing: SPSpacing.x3) {476 stat("\(contact.stats.received)", L("reçus")); stat("\(contact.stats.sent)", L("envoyés"))477 if let last = contact.stats.lastAt { stat(last.formatted(date: .abbreviated, time: .omitted), L("dernier échange")) }478 }479 if let e = c.historyError { Label(e, systemImage: "wifi.slash").font(SPFont.callout).foregroundStyle(SPColor.text3) } else if c.history == nil { BodySkeleton() }480 }481 if let reminders = c.history?.reminders, !reminders.isEmpty {482 section(L("Rappels en attente")) {483 ForEach(reminders) { r in484 Button { scene.presentMessage(account: r.mailboxId, emailId: r.emailId) } label: {485 HStack(spacing: SPSpacing.m) {486 Image(systemName: "bell").foregroundStyle(r.status == .due ? SPColor.warn : SPColor.text3).frame(width: 20)487 Text(r.subject.isEmpty ? L("(sans objet)") : r.subject).font(SPFont.callout).foregroundStyle(SPColor.text).lineLimit(1)488 Spacer(minLength: SPSpacing.m)489 if let due = r.dueAt { Text(due.formatted(date: .abbreviated, time: .shortened)).font(SPFont.caption).foregroundStyle(SPColor.text3) }490 }.contentShape(Rectangle())491 }.buttonStyle(.plain)492 }493 }494 }495 if let messages = c.history?.messages, !messages.isEmpty {496 section(L("Derniers messages")) {497 VStack(spacing: 0) {498 ForEach(messages) { m in499 Button { scene.presentMessage(account: m.mailboxId, emailId: m.emailId) } label: {500 let mine = app.myAddresses.contains(m.from.first?.email.lowercased() ?? "")501 HStack(alignment: .firstTextBaseline, spacing: SPSpacing.m) {502 Image(systemName: mine ? "arrow.up.right" : "arrow.down.left").imageScale(.small).foregroundStyle(mine ? SPColor.text3 : SPColor.accent).frame(width: 20)503 .accessibilityLabel(Text(mine ? "Envoyé" : "Reçu"))504 VStack(alignment: .leading, spacing: 1) {505 Text(m.subject.isEmpty ? L("(sans objet)") : m.subject).font(SPFont.callout).fontWeight(m.isUnread ? .semibold : .regular).foregroundStyle(SPColor.text).lineLimit(1)506 if !m.preview.isEmpty { Text(m.preview).font(SPFont.callout).foregroundStyle(SPColor.text3).lineLimit(1) }507 }508 Spacer(minLength: SPSpacing.m)509 if m.hasAttachment { Image(systemName: "paperclip").imageScale(.small).foregroundStyle(SPColor.text3) }510 if let d = m.receivedAt { Text(d.listLabel).font(SPFont.caption).foregroundStyle(SPColor.text3) }511 }512 .padding(.vertical, SPSpacing.m).contentShape(Rectangle())513 }514 .buttonStyle(.plain)515 Divider().overlay(SPColor.border)516 }517 }518 }519 } else if c.history != nil {520 Text("Aucun message échangé pour l’instant.").font(SPFont.callout).foregroundStyle(SPColor.text3)521 }522 }523524 private func stat(_ value: String, _ label: String) -> some View {525 VStack(alignment: .leading, spacing: 0) {526 Text(value).font(.title3.weight(.semibold).monospacedDigit()).foregroundStyle(SPColor.text)527 Text(label).font(SPFont.caption).foregroundStyle(SPColor.text3)528 }529 .accessibilityElement(children: .combine)530 }531532 private func compose(to address: EmailAddress) {533 guard let url = URL(string: "mailto:" + (address.email.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? address.email)) else { return }534 Task { await scene.compose(.mailto(url)) }535 }536}537538// MARK: - editor539540struct ContactEditorSheet: View {541 let scene: MailScene542 let request: ContactEditRequest543 @State private var name = ""544 @State private var organization = ""545 @State private var title = ""546 @State private var notes = ""547 @State private var emails: [EditableValue] = []548 @State private var phones: [EditableValue] = []549 @State private var groups: Set<String> = []550 @State private var saving = false551 @Environment(\.dismiss) private var dismiss552553 struct EditableValue: Identifiable { let id = UUID(); var value = ""; var label = "" }554555 private var validEmails: [ContactEmail] {556 emails.map { ContactEmail(email: $0.value.trimmingCharacters(in: .whitespaces), label: $0.label.isEmpty ? nil : $0.label) }.filter { $0.email.contains("@") && !$0.email.contains(" ") }557 }558 private var canSave: Bool { !saving && (!name.trimmingCharacters(in: .whitespaces).isEmpty || !validEmails.isEmpty) && emails.allSatisfy { $0.value.isEmpty || ($0.value.contains("@") && !$0.value.trimmingCharacters(in: .whitespaces).contains(" ")) } }559560 var body: some View {561 NavigationStack {562 Form {563 Section("Identité") {564 TextField("Nom", text: $name)565 TextField("Organisation", text: $organization)566 TextField("Fonction", text: $title)567 }568 Section("Adresses") {569 ForEach($emails) { $e in570 HStack {571 TextField("adresse@exemple.org", text: $e.value).autocorrectionDisabled()572 #if os(iOS)573 .textInputAutocapitalization(.never).keyboardType(.emailAddress)574 #endif575 TextField("Étiquette", text: $e.label).frame(maxWidth: 110).foregroundStyle(SPColor.text2)576 Button { emails.removeAll { $0.id == e.id } } label: { Image(systemName: "minus.circle").foregroundStyle(SPColor.danger) }.buttonStyle(.borderless).accessibilityLabel(Text("Retirer cette adresse"))577 }578 }579 Button { emails.append(EditableValue()) } label: { Label("Ajouter une adresse", systemImage: "plus.circle") }580 }581 Section("Téléphones") {582 ForEach($phones) { $p in583 HStack {584 TextField("Numéro", text: $p.value)585 #if os(iOS)586 .keyboardType(.phonePad)587 #endif588 TextField("Étiquette", text: $p.label).frame(maxWidth: 110).foregroundStyle(SPColor.text2)589 Button { phones.removeAll { $0.id == p.id } } label: { Image(systemName: "minus.circle").foregroundStyle(SPColor.danger) }.buttonStyle(.borderless).accessibilityLabel(Text("Retirer ce numéro"))590 }591 }592 Button { phones.append(EditableValue()) } label: { Label("Ajouter un numéro", systemImage: "plus.circle") }593 }594 if !scene.next.contacts.groups.isEmpty {595 Section("Groupes") {596 ForEach(scene.next.contacts.groups) { g in597 Toggle(g.name, isOn: Binding(get: { groups.contains(g.id) }, set: { on in if on { groups.insert(g.id) } else { groups.remove(g.id) } }))598 }599 }600 }601 Section("Notes") {602 TextEditor(text: $notes).frame(minHeight: 70).accessibilityLabel(Text("Notes"))603 }604 }605 .formStyle(.grouped)606 .navigationTitle(request.contact == nil ? L("Nouveau contact") : L("Modifier le contact"))607 #if os(iOS)608 .navigationBarTitleDisplayMode(.inline)609 #endif610 .toolbar {611 ToolbarItem(placement: .cancellationAction) { Button("Annuler") { dismiss() } }612 ToolbarItem(placement: .confirmationAction) { Button("Enregistrer") { save() }.disabled(!canSave) }613 }614 }615 #if os(macOS)616 .frame(width: 480, height: 600)617 #endif618 .spTheme(scene.app.settings)619 .onAppear(perform: load)620 }621622 private func load() {623 if let c = request.contact {624 name = c.name; organization = c.organization ?? ""; title = c.title ?? ""; notes = c.notes ?? ""; groups = Set(c.groups)625 emails = c.emails.map { EditableValue(value: $0.email, label: $0.label ?? "") }626 phones = c.phones.map { EditableValue(value: $0.number, label: $0.label ?? "") }627 } else if let a = request.prefill {628 name = a.name ?? ""; emails = [EditableValue(value: a.email)]629 }630 if emails.isEmpty { emails = [EditableValue()] }631 }632633 private func save() {634 saving = true635 let content = ContactContent(kind: .saved, name: name.trimmingCharacters(in: .whitespaces), emails: validEmails, organization: organization.trimmingCharacters(in: .whitespaces),636 title: title.trimmingCharacters(in: .whitespaces),637 phones: phones.map { ContactPhone(number: $0.value.trimmingCharacters(in: .whitespaces), label: $0.label.isEmpty ? nil : $0.label) }.filter { !$0.number.isEmpty },638 notes: notes.trimmingCharacters(in: .whitespacesAndNewlines), groups: Array(groups))639 Task {640 let saved = await scene.saveContact(request.contact, content)641 saving = false642 if let saved { if request.contact == nil { await scene.selectContact(saved) }; dismiss() }643 }644 }645}646647// MARK: - groups and duplicates648649struct GroupsSheet: View {650 let scene: MailScene651 @State private var newName = ""652 @State private var renaming: ContactGroup?653 @State private var renameText = ""654 @Environment(\.dismiss) private var dismiss655 private var api: NextAPI { scene.app.next.api }656657 var body: some View {658 let c = scene.next.contacts659 NavigationStack {660 List {661 Section {662 ForEach(c.groups) { g in663 HStack {664 Circle().fill(LabelPalette.token(LabelPalette.index(forHex: g.color))).frame(width: 10, height: 10)665 Text(g.name)666 Spacer()667 if let n = g.memberCount { Text("\(n)").font(SPFont.caption).foregroundStyle(SPColor.text3) }668 Button { renameText = g.name; renaming = g } label: { Image(systemName: "pencil") }.buttonStyle(.borderless).accessibilityLabel(Text("Renommer \(g.name)"))669 Button(role: .destructive) { Task { try? await api.deleteContactGroup(id: g.id); await reload() } } label: { Image(systemName: "trash") }.buttonStyle(.borderless).accessibilityLabel(Text("Supprimer \(g.name)"))670 }671 }672 if c.groups.isEmpty { Text("Aucun groupe").foregroundStyle(SPColor.text3) }673 } footer: { Text("Supprimer un groupe ne supprime pas ses contacts.") }674 Section("Nouveau groupe") {675 HStack {676 TextField("Nom du groupe", text: $newName).onSubmit(add)677 Button("Ajouter", action: add).disabled(newName.trimmingCharacters(in: .whitespaces).isEmpty)678 }679 }680 }681 .navigationTitle("Groupes")682 #if os(iOS)683 .navigationBarTitleDisplayMode(.inline)684 #endif685 .toolbar { ToolbarItem(placement: .confirmationAction) { Button("OK") { dismiss() } } }686 .alert("Renommer le groupe", isPresented: Binding(get: { renaming != nil }, set: { if !$0 { renaming = nil } })) {687 TextField("Nom", text: $renameText)688 Button("Renommer") { if let g = renaming { let n = renameText; Task { do { _ = try await api.updateContactGroup(id: g.id, name: n) } catch { fail(error) }; await reload() } } }689 Button("Annuler", role: .cancel) {}690 }691 }692 #if os(macOS)693 .frame(width: 400, height: 420)694 #else695 .presentationDetents([.medium, .large])696 #endif697 .spTheme(scene.app.settings)698 }699700 private func add() {701 let name = newName.trimmingCharacters(in: .whitespaces)702 guard !name.isEmpty else { return }703 newName = ""704 Task { do { _ = try await api.createContactGroup(name: name, color: LabelPalette.suggestion(existing: scene.next.contacts.groups.map(\.color))) } catch { fail(error) }; await reload() }705 }706 private func reload() async { if let g = try? await api.contactGroups() { scene.next.contacts.groups = g } }707 private func fail(_ error: Error) { scene.app.toast = Toast(message: scene.app.next.describe(error) ?? "", kind: .error) }708}709710struct DuplicatesSheet: View {711 let scene: MailScene712 @State private var keep: [String: String] = [:]713 @State private var merging: String?714 @Environment(\.dismiss) private var dismiss715716 var body: some View {717 let groups = scene.next.contacts.duplicates718 NavigationStack {719 List {720 ForEach(groups) { group in721 Section {722 ForEach(group.contacts) { contact in723 let kept = (keep[group.id] ?? group.contacts.first?.id) == contact.id724 Button { keep[group.id] = contact.id } label: {725 HStack(spacing: SPSpacing.m) {726 Image(systemName: kept ? "largecircle.fill.circle" : "circle").foregroundStyle(kept ? SPColor.accent : SPColor.text3)727 VStack(alignment: .leading, spacing: 1) {728 Text(contact.displayName).foregroundStyle(SPColor.text)729 Text(contact.emails.map(\.email).joined(separator: ", ")).font(SPFont.caption).foregroundStyle(SPColor.text3).lineLimit(1)730 }731 Spacer()732 if kept { Text("À conserver").font(SPFont.caption).foregroundStyle(SPColor.accent) }733 }.contentShape(Rectangle())734 }735 .buttonStyle(.plain).accessibilityAddTraits(kept ? .isSelected : [])736 }737 Button {738 let keepId = keep[group.id] ?? group.contacts.first?.id739 guard let target = group.contacts.first(where: { $0.id == keepId }) else { return }740 merging = group.id741 Task { await scene.mergeContacts(keep: target, merge: group.contacts.filter { $0.id != target.id }); merging = nil }742 } label: { if merging == group.id { ProgressView().controlSize(.small) } else { Label("Fusionner ces \(group.contacts.count) fiches", systemImage: "arrow.triangle.merge") } }743 .disabled(merging != nil)744 } header: { Text(group.reason == "email" ? L("Même adresse") : group.reason == "name" ? L("Même nom") : L("Doublon probable")) }745 }746 }747 .overlay { if groups.isEmpty { SPEmptyState(icon: "checkmark.circle", title: L("Aucun doublon"), message: L("Deux fiches sont des doublons quand elles partagent une adresse ou un nom.")) } }748 .navigationTitle("Doublons")749 #if os(iOS)750 .navigationBarTitleDisplayMode(.inline)751 #endif752 .toolbar { ToolbarItem(placement: .confirmationAction) { Button("OK") { dismiss() } } }753 }754 #if os(macOS)755 .frame(width: 460, height: 480)756 #endif757 .spTheme(scene.app.settings)758 }759}760761// MARK: - inspector: the sender as a contact762763/// The contact profile of the sender in the inspector (macOS): organisation, phones, notes, favourite / VIP — or « add to contacts ».764struct InspectorContactCard: View {765 let scene: MailScene766 let sender: EmailAddress767 @State private var contact: Contact?768 @State private var loaded = false769770 var body: some View {771 VStack(alignment: .leading, spacing: SPSpacing.m) {772 if let contact, contact.isSaved {773 let role = [contact.title, contact.organization].compactMap { $0 }.filter { !$0.isEmpty }.joined(separator: " · ")774 if !role.isEmpty { Label(role, systemImage: "building.2").font(SPFont.callout).foregroundStyle(SPColor.text2) }775 ForEach(contact.phones, id: \.number) { p in Label(p.number, systemImage: "phone").font(SPFont.callout).foregroundStyle(SPColor.text2).textSelection(.enabled) }776 if let notes = contact.notes, !notes.isEmpty { Text(notes).font(SPFont.callout).foregroundStyle(SPColor.text3).lineLimit(4) }777 Text("\(contact.stats.received) reçus · \(contact.stats.sent) envoyés").font(SPFont.caption).foregroundStyle(SPColor.text3)778 HStack(spacing: SPSpacing.m) {779 Toggle(isOn: Binding(get: { contact.favorite }, set: { on in self.contact?.favorite = on; Task { await scene.setFavorite(contact, on) } })) { Label("Favori", systemImage: contact.favorite ? "star.fill" : "star") }.toggleStyle(.button)780 Toggle(isOn: Binding(get: { contact.vip }, set: { on in self.contact?.vip = on; Task { await scene.setVIP(contact, on) } })) { Label("VIP", systemImage: contact.vip ? "crown.fill" : "crown") }.toggleStyle(.button)781 }782 .controlSize(.small)783 Button { scene.showContact(contact) } label: { Label("Voir la fiche", systemImage: "person.crop.circle") }.controlSize(.small)784 } else if loaded {785 Button { Task { if let saved = await scene.addToContacts(sender) { contact = saved } } } label: { Label("Ajouter aux contacts", systemImage: "person.crop.circle.badge.plus") }.controlSize(.small)786 }787 }788 .task(id: sender.email) {789 loaded = false; contact = nil790 contact = await scene.contact(for: sender.email)791 loaded = true792 }793 }794}795