SPB Git

Repository Public

ComposeView.swift 29.1 KB 484 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : MacLustr SMS Gateway9// File             : ios/MacLustrSMS/UI/ComposeView.swift10// Description      : Composer un SMS : destinataire, ligne, éditeur avec11//                    compteur de segments, modèles à variables, aperçu,12//                    confirmation, envoi idempotent.13// Module           : ios14// Repository       : https://git.spboucher.ai/maclustr-sms15// Project Website  : https://sms.spboucher.ai16// Created          : 2026-11-3017// Last Modified    : 2026-12-0118//19// =============================================================================20// AUTHOR & PROFESSIONAL AFFILIATION21// =============================================================================22//23// Author           : Simon-Pierre Boucher24// Position         : Professor of Finance25// Institution      : Université du Québec en Outaouais (UQO)26// Department       : Département des sciences administratives27// Organization     : SP Boucher28//29// Website          : https://spboucher.ai30// Git              : https://git.spboucher.ai31//32// =============================================================================33// OFFICIAL CONTACT DIRECTORY34// =============================================================================35//36// General          : info@spboucher.ai37// Professional     : contact@spboucher.ai38// Direct           : simon@spboucher.ai39// Research         : research@spboucher.ai40// Development      : dev@spboucher.ai41// Support          : support@spboucher.ai42// Security/Admin   : admin@spboucher.ai43// Notifications    : notifications@spboucher.ai44//45// Preferred Contact: admin@spboucher.ai46//47// =============================================================================48// COPYRIGHT & INTELLECTUAL PROPERTY49// =============================================================================50//51// Copyright (c) 202652// Simon-Pierre Boucher53//54// All rights reserved where applicable.55//56// This file is governed by the applicable project license,57// copyright notices, institutional agreements and relevant law.58//59// Unless expressly authorized by the applicable license or60// rights holder, copying, redistribution, sublicensing,61// publication and commercial exploitation are not permitted.62//63// Existing third-party rights and notices remain unaffected.64//65// =============================================================================66// CONFIDENTIALITY & SECURITY67// =============================================================================68//69// Classification   : Public70// Distribution     : Public repository; use is governed by the project license71// Security Contact : admin@spboucher.ai72//73// Access to this source does not independently grant permission74// to redistribute or disclose confidential materials.75//76// Do not embed credentials, private keys, access tokens,77// certificates or confidential personal information.78//79// =============================================================================80// LICENSE & MAINTENANCE81// =============================================================================82//83// License          : None specified (no license file in this repository)84// Maintainer       : Simon-Pierre Boucher85// Technical Contact: dev@spboucher.ai86//87// =============================================================================88// END OF SP BOUCHER SOURCE HEADER89// =============================================================================9091import ContactsUI92import SwiftData93import SwiftUI9495struct ComposeView: View {96    @Environment(AppModel.self) private var model97    @Environment(\.modelContext) private var store98    @Query(sort: \RecentRecipient.lastUsed, order: .reverse) private var recents: [RecentRecipient]99    @Query(sort: \MessageTemplate.order) private var templates: [MessageTemplate]100101    @State private var recipient = ""102    @State private var recipientName = ""103    @State private var text = ""104    @State private var simId: String?105    @State private var variableValues: [String: String] = [:]106    @State private var variableDates: [String: Date] = [:]107    @State private var suggestion: WritingSuggestion?108    @State private var openPicker: String?109    @State private var showContacts = false110    @State private var showTemplates = false111    @State private var showConfirm = false112    @State private var sending = false113    @State private var error: String?114    @State private var notAllowed: String?115    @State private var idempotencyKey = UUID().uuidString116    @State private var tracked: SMSMessage?117    @FocusState private var focus: Field?118    enum Field: Hashable { case recipient, text, variable(String) }119120    private var e164: String? { PhoneNumber.e164(recipient) }121    private var variables: [String] { TemplateEngine.variables(in: text) }122    /// Texte final : variables remplies, signature ajoutée si elle est activée.123    private var finalText: String {124        // Valeurs saisies (normalisées selon leur type : « 125,50 $ », lien sans https://), complétées par les valeurs automatiques.125        var values: [String: String] = [:]126        for v in variables {127            if let typed = variableValues[v], !typed.trimmingCharacters(in: .whitespaces).isEmpty { values[v] = VariableFormat.normalized(VariableKind.of(v), typed) }128            else if let auto = VariableFormat.automatic(v) { values[v] = auto }129        }130        let filled = TemplateEngine.fill(text, values: values)131        return model.signatureEnabled ? TemplateEngine.withSignature(filled, signature: model.signature) : filled132    }133    private var info: SegmentInfo { Segments.info(finalText) }134    private var unresolved: [String] { TemplateEngine.unresolved(in: finalText) }135    private var chosenSim: Sim? { model.usableSims.first { $0.id == simId } }136    private var canSend: Bool { e164 != nil && !finalText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty && info.segments <= Segments.maxSegments && unresolved.isEmpty && !sending && !model.killSwitch }137138    var body: some View {139        NavigationStack {140            Screen {141                if let b = model.sendBlocker { Banner(text: b, tone: model.killSwitch ? .bad : .warn).accessibilityIdentifier("sendBlocker") }142                recipientCard143                if model.usableSims.count > 1 { lineCard }144                editorCard145                if !variables.isEmpty { variablesCard }146                if !finalText.isEmpty { previewCard }147                if let error { Banner(text: error, tone: .bad, symbol: "exclamationmark.circle").accessibilityIdentifier("composeError") }148                if let n = notAllowed { notAllowedCard(n) }149                Button { focus = nil; showConfirm = true } label: { Label("Vérifier et envoyer", systemImage: "paperplane.fill") }150                    .buttonStyle(PrimaryButtonStyle()).disabled(!canSend).accessibilityIdentifier("sendButton")151                Text("Un SMS est du texte brut : ni logo, ni image, ni mise en forme ne peuvent y figurer.").font(.caption).foregroundStyle(Theme.faint).frame(maxWidth: .infinity)152            }153            // En-tête fixe : le contenu ne défile jamais sous la barre d'état.154            .safeAreaInset(edge: .top, spacing: 0) { header.padding(.horizontal, 16).padding(.vertical, 10).background(Theme.bg) }155            .toolbar(.hidden, for: .navigationBar)156            .toolbar { ToolbarItemGroup(placement: .keyboard) { Spacer(); Button("Terminé") { focus = nil }.fontWeight(.semibold).accessibilityIdentifier("keyboardDone") } }157            .navigationDestination(item: $tracked) { m in TrackingView(messageId: m.id, initial: m) }158            .sheet(isPresented: $showContacts) { ContactPicker { name, number in recipientName = name; recipient = PhoneNumber.pretty(PhoneNumber.e164(number) ?? number) }.ignoresSafeArea() }159            .sheet(isPresented: $showTemplates) { TemplateLibrary { choice in apply(choice) } }160            .sheet(item: $suggestion) { s in SuggestionSheet(suggestion: s) { text = $0 } }161            .sheet(isPresented: $showConfirm) { confirmSheet.presentationDetents([.medium, .large]) }162            .onChange(of: text) { _, _ in changed() }163            .onChange(of: recipient) { _, _ in changed() }164            .onChange(of: simId) { _, _ in changed() }165            .onChange(of: model.pendingDraft) { _, d in if let d { load(d) } }166            .onAppear { if let d = model.pendingDraft { load(d) } }167        }168    }169170    private var header: some View {171        HStack(spacing: 12) {172            LogoMark(size: 38)173            VStack(alignment: .leading, spacing: 1) {174                Text("Nouveau message").font(.title2.weight(.semibold)).foregroundStyle(Theme.text)175                HStack(spacing: 6) {176                    StatusDot(tone: model.primaryDevice?.tone ?? .neutral)177                    Text(model.primaryDevice.map { "\($0.name) · \($0.stateLabel.lowercased())" } ?? "Passerelle…").font(.caption).foregroundStyle(Theme.muted).lineLimit(1)178                }179            }180            Spacer()181            if !text.isEmpty || !recipient.isEmpty { Button("Effacer") { reset() }.font(.subheadline).foregroundStyle(Theme.muted) }182        }183    }184185    private var recipientCard: some View {186        Card {187            VStack(alignment: .leading, spacing: 10) {188                SectionLabel("Destinataire")189                HStack(spacing: 10) {190                    TextField("418 555-0123", text: $recipient)191                        .keyboardType(.phonePad).textContentType(.telephoneNumber).font(.title3.monospacedDigit()).foregroundStyle(Theme.text)192                        .focused($focus, equals: .recipient).accessibilityIdentifier("recipientField")193                        .onChange(of: recipient) { old, new in194                            // mise en forme pendant la frappe (jamais pendant un effacement, pour ne pas gêner la correction)195                            if new.count > old.count { let f = PhoneNumber.formatWhileTyping(new); if f != new { recipient = f } }196                            if PhoneNumber.e164(new) != PhoneNumber.e164(old) { recipientName = recents.first { $0.number == PhoneNumber.e164(new) }?.name ?? (PhoneNumber.e164(new) == nil ? "" : recipientName) }197                        }198                    Button { focus = nil; showContacts = true } label: { Image(systemName: "person.crop.circle").font(.title2) }.accessibilityLabel("Choisir dans les contacts")199                }200                if !recipient.isEmpty {201                    HStack(spacing: 6) {202                        Image(systemName: e164 == nil ? "xmark.circle" : "checkmark.circle.fill").foregroundStyle(e164 == nil ? Theme.bad : Theme.ok)203                        Text(e164.map { ($0 + (recipientName.isEmpty ? "" : " · \(recipientName)")) } ?? "Numéro incomplet ou invalide").font(.footnote.monospacedDigit()).foregroundStyle(Theme.muted)204                            .accessibilityIdentifier("recipientValidation")205                        if let n = e164, model.allowlistMode, !model.allowed.isEmpty, !model.allowed.contains(where: { $0.number == n }) {206                            Text("hors liste autorisée").font(.caption2).foregroundStyle(Theme.warn)207                        }208                    }209                }210                if recipient.isEmpty, !recents.isEmpty {211                    ScrollView(.horizontal, showsIndicators: false) {212                        HStack(spacing: 8) {213                            ForEach(recents.prefix(8)) { r in214                                Button { recipient = PhoneNumber.pretty(r.number); recipientName = r.name } label: {215                                    VStack(alignment: .leading, spacing: 1) {216                                        if !r.name.isEmpty { Text(r.name).font(.caption.weight(.medium)).foregroundStyle(Theme.text) }217                                        Text(PhoneNumber.pretty(r.number)).font(.caption.monospacedDigit()).foregroundStyle(Theme.muted)218                                    }219                                }.buttonStyle(QuietButtonStyle())220                            }221                        }222                    }223                }224            }225        }226    }227228    private var lineCard: some View {229        Card {230            VStack(alignment: .leading, spacing: 8) {231                SectionLabel("Ligne expéditrice")232                Picker("Ligne", selection: $simId) {233                    Text("Automatique").tag(String?.none)234                    ForEach(model.usableSims) { s in Text(s.title).tag(String?.some(s.id)) }235                }.pickerStyle(.menu).tint(Theme.text)236                Text("En automatique, la passerelle garde la ligne déjà utilisée avec ce destinataire ; elle ne change jamais de numéro d'elle-même.").font(.caption).foregroundStyle(Theme.faint)237            }238        }239    }240241    private var editorCard: some View {242        Card {243            VStack(alignment: .leading, spacing: 10) {244                HStack {245                    SectionLabel("Message")246                    Spacer()247                    Button { focus = nil; showTemplates = true } label: { Label("Modèles", systemImage: "rectangle.stack").font(.subheadline) }.accessibilityIdentifier("templatesButton")248                }249                TextField("Écrivez votre message…", text: $text, axis: .vertical).lineLimit(4...12).font(.body).foregroundStyle(Theme.text)250                    .focused($focus, equals: .text).accessibilityIdentifier("messageEditor")251                SegmentGauge(info: info)252                HStack {253                    Text("\(info.segments) segment\(info.segments > 1 ? "s" : "") · \(info.encoding == .gsm7 ? "GSM 7 bits" : "Unicode")").foregroundStyle(info.segments > Segments.maxSegments ? Theme.bad : info.encoding == .ucs2 ? Theme.warn : Theme.muted)254                        .accessibilityIdentifier("segmentSummary")255                    Spacer()256                    Text(info.segments > Segments.maxSegments ? "trop long (max \(Segments.maxSegments))" : "\(info.remainingInSegment) avant le suivant").foregroundStyle(Theme.faint)257                }.font(.caption.monospacedDigit())258                if info.encoding == .ucs2 { unicodeAdvice }259                if info.segments > 1 {260                    Button { suggestion = WritingTools.shortenToOneSegment(text) } label: { Label("Raccourcir pour tenir en 1 segment", systemImage: "arrow.down.right.and.arrow.up.left") }261                        .buttonStyle(QuietButtonStyle(tone: Theme.accent)).accessibilityIdentifier("shortenButton")262                }263                if model.signatureEnabled, !model.signature.isEmpty { Label("Signature ajoutée : \(model.signature)", systemImage: "signature").font(.caption).foregroundStyle(Theme.faint).lineLimit(1) }264            }265        }266    }267268    /// Explique ce qui force l'Unicode et propose de ramener le texte à l'alphabet GSM quand c'est possible.269    private var unicodeAdvice: some View {270        let off = Segments.offenders(finalText)271        let fixable = off.filter { $0.replacement != nil }272        return VStack(alignment: .leading, spacing: 8) {273            Text("Passage en Unicode (70 caractères par segment au lieu de 160) à cause de :").font(.caption).foregroundStyle(Theme.warn)274            ScrollView(.horizontal, showsIndicators: false) {275                HStack(spacing: 6) {276                    ForEach(off.prefix(12)) { o in277                        HStack(spacing: 4) {278                            Text(String(o.character) == "\u{00A0}" || String(o.character) == "\u{202F}" ? "espace insécable" : String(o.character)).font(.callout)279                            if let r = o.replacement { Image(systemName: "arrow.right").font(.caption2); Text(r == " " ? "espace" : r).font(.callout.monospaced()) }280                            if o.count > 1 { Text("×\(o.count)").font(.caption2).foregroundStyle(Theme.faint) }281                        }282                        .padding(.horizontal, 8).padding(.vertical, 4).background(Theme.panel2, in: RoundedRectangle(cornerRadius: 7))283                    }284                }285            }286            if !fixable.isEmpty {287                Button {288                    text = Segments.simplified(text)289                } label: {290                    if let s = Segments.savings(finalText), s.simplified < s.now { Label("Simplifier (\(s.now) → \(s.simplified) segment\(s.simplified > 1 ? "s" : ""))", systemImage: "wand.and.stars") }291                    else { Label("Remplacer les caractères typographiques", systemImage: "wand.and.stars") }292                }.buttonStyle(QuietButtonStyle(tone: Theme.accent)).accessibilityIdentifier("simplifyButton")293            }294            if off.contains(where: { $0.replacement == nil }) { Text("Les émoji et certains accents n'ont pas d'équivalent : les garder coûte plus de segments, rien d'autre.").font(.caption2).foregroundStyle(Theme.faint) }295        }296        .accessibilityElement(children: .contain).accessibilityIdentifier("unicodeAdvice")297    }298299    private var variablesCard: some View {300        Card {301            VStack(alignment: .leading, spacing: 10) {302                SectionLabel("Variables du modèle")303                ForEach(variables, id: \.self) { v in variableRow(v) }304                if !unresolved.isEmpty { Text("À remplir avant l'envoi : \(unresolved.joined(separator: ", "))").font(.caption).foregroundStyle(Theme.warn) }305            }306        }307    }308309    /// Une ligne par variable, avec le clavier et le sélecteur adaptés à son type (déduit du nom).310    @ViewBuilder private func variableRow(_ v: String) -> some View {311        let kind = VariableKind.of(v)312        let binding = Binding(get: { variableValues[v] ?? "" }, set: { variableValues[v] = $0; changed() })313        HStack(spacing: 8) {314            Label(v, systemImage: kind.symbol).font(.subheadline).foregroundStyle(Theme.muted).labelStyle(.titleAndIcon).frame(width: 118, alignment: .leading).lineLimit(1).minimumScaleFactor(0.8)315            if let auto = VariableFormat.automatic(v) {316                Text(auto).font(.body).foregroundStyle(Theme.text).frame(maxWidth: .infinity, alignment: .leading)317                Text("auto").font(.caption2.weight(.semibold)).foregroundStyle(Theme.faint)318            } else {319                TextField(placeholder(kind, v), text: binding)320                    .keyboardType(kind == .amount ? .decimalPad : kind == .code || kind == .number ? .numberPad : kind == .link ? .URL : .default)321                    .textInputAutocapitalization(kind == .link || kind == .code ? .never : .sentences).autocorrectionDisabled(kind == .link || kind == .code || kind == .brand)322                    .font(.body).foregroundStyle(Theme.text).focused($focus, equals: .variable(v)).accessibilityIdentifier("variable-\(v)")323                if kind == .time || kind == .date {324                    // Le sélecteur s'ouvre sous la ligne : la valeur saisie garde toute la largeur.325                    Button { focus = nil; withAnimation(.snappy) { openPicker = openPicker == v ? nil : v } } label: {326                        Image(systemName: kind == .time ? "clock" : "calendar").font(.body.weight(.medium)).foregroundStyle(openPicker == v ? Theme.onAccent : Theme.accent)327                            .frame(width: 34, height: 30).background(openPicker == v ? Theme.accent : Theme.panel2, in: RoundedRectangle(cornerRadius: 8))328                    }.buttonStyle(.plain).accessibilityLabel(kind == .time ? "Choisir l'heure" : "Choisir la date").accessibilityIdentifier("picker-\(v)")329                }330                if kind.isRemembered, !binding.wrappedValue.isEmpty, RememberedValues.value(for: v) != binding.wrappedValue {331                    Button("Mémoriser") { RememberedValues.set(binding.wrappedValue, for: v) }.font(.caption.weight(.medium)).accessibilityIdentifier("remember-\(v)")332                }333            }334        }335        .padding(.vertical, 2)336        if openPicker == v, kind == .time || kind == .date {337            DatePicker("", selection: Binding(get: { variableDates[v] ?? Date.now }, set: { d in338                variableDates[v] = d; variableValues[v] = kind == .time ? VariableFormat.time(d) : VariableFormat.date(d); changed()339            }), displayedComponents: kind == .time ? .hourAndMinute : .date)340            .labelsHidden().datePickerStyle(kind == .time ? AnyDatePickerStyle(.wheel) : AnyDatePickerStyle(.graphical))341            .environment(\.locale, VariableFormat.locale).frame(maxWidth: .infinity).frame(maxHeight: kind == .time ? 130 : nil).clipped()342        }343    }344    private func placeholder(_ kind: VariableKind, _ v: String) -> String {345        switch kind {346        case .time: "10 h 30"; case .date: "jeudi 3 décembre"; case .amount: "125,50"; case .link: "exemple.ca/page"; case .brand: "Votre marque"347        case .signature: "Votre nom"; case .code: "493817"; case .number: "15"; case .firstName: "Marie"; case .address: "123, rue Principale"; case .text: "valeur"348        }349    }350351    private var previewCard: some View {352        VStack(alignment: .leading, spacing: 8) {353            SectionLabel("Aperçu chez le destinataire")354            VStack(spacing: 6) {355                Text(chosenSim?.number.map(PhoneNumber.pretty) ?? model.usableSims.first?.number.map(PhoneNumber.pretty) ?? "Votre ligne").font(.caption).foregroundStyle(Theme.faint)356                Bubble(text: finalText, outgoing: false)357            }358            .padding(14).frame(maxWidth: .infinity)359            .background(Theme.panel, in: RoundedRectangle(cornerRadius: 14, style: .continuous))360            .overlay(RoundedRectangle(cornerRadius: 14, style: .continuous).strokeBorder(Theme.line, lineWidth: 1))361            .accessibilityElement(children: .combine).accessibilityIdentifier("preview")362        }363    }364365    private func notAllowedCard(_ number: String) -> some View {366        Card {367            VStack(alignment: .leading, spacing: 10) {368                Label("Destinataire hors de la liste autorisée", systemImage: "hand.raised").font(.subheadline.weight(.semibold)).foregroundStyle(Theme.warn)369                Text("La passerelle n'envoie qu'aux numéros que vous avez autorisés. Ajoutez \(PhoneNumber.pretty(number)) seulement si cette personne s'attend à recevoir vos messages.").font(.footnote).foregroundStyle(Theme.muted)370                Button("Autoriser ce numéro") { Task { await allow(number) } }.buttonStyle(QuietButtonStyle(tone: Theme.accent)).accessibilityIdentifier("allowRecipientButton")371            }372        }373    }374375    private var confirmSheet: some View {376        NavigationStack {377            Screen {378                Banner(text: "Vous allez envoyer un vrai SMS par le réseau cellulaire. Il est facturé selon votre forfait et ne peut pas être rappelé une fois parti.", tone: .info, symbol: "antenna.radiowaves.left.and.right")379                Card {380                    VStack(alignment: .leading, spacing: 10) {381                        row("À", (e164.map(PhoneNumber.pretty) ?? "") + (recipientName.isEmpty ? "" : " · \(recipientName)"))382                        row("De", chosenSim?.title ?? "ligne choisie par la passerelle")383                        row("Taille", "\(info.segments) segment\(info.segments > 1 ? "s" : "") · \(info.characters) caractères · \(info.encoding == .gsm7 ? "GSM" : "Unicode")")384                    }385                }386                Bubble(text: finalText, outgoing: true)387                if let b = model.sendBlocker { Banner(text: b, tone: .warn) }388                Button { Task { await send() } } label: { if sending { ProgressView().tint(Theme.onAccent) } else { Label("Envoyer le SMS", systemImage: "paperplane.fill") } }389                    .buttonStyle(PrimaryButtonStyle()).disabled(sending).accessibilityIdentifier("confirmSendButton")390            }391            .navigationTitle("Confirmer l'envoi").navigationBarTitleDisplayMode(.inline)392            .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Modifier") { showConfirm = false } } }393        }394    }395    private func row(_ k: String, _ v: String) -> some View {396        HStack(alignment: .firstTextBaseline) { Text(k).font(.subheadline).foregroundStyle(Theme.muted).frame(width: 56, alignment: .leading); Text(v).font(.subheadline.monospacedDigit()).foregroundStyle(Theme.text) }397    }398399    // MARK: Actions400    /// Tout changement de contenu donne une nouvelle clé d'idempotence ; tant que rien ne change, un second envoi rend le même message.401    private func changed() { idempotencyKey = UUID().uuidString; error = nil; notAllowed = nil }402    private func reset() { recipient = ""; recipientName = ""; text = ""; variableValues = [:]; variableDates = [:]; simId = nil; changed() }403    private func load(_ d: ComposeDraft) {404        recipient = d.to.isEmpty ? "" : PhoneNumber.pretty(d.to); text = d.text; simId = d.simId; variableValues = [:]405        recipientName = recents.first { $0.number == d.to }?.name ?? ""406        model.pendingDraft = nil; changed()407    }408    private func apply(_ c: TemplateChoice) {409        let t = c.template410        text = t.text(english: c.english)411        // Valeurs connues d'avance : marque et signature mémorisées, prénom du contact choisi. Les dates automatiques se calculent seules.412        var known = TemplateEngine.prefill(text, recipientName: recipientName)413        if known["signature"] == nil, TemplateEngine.variables(in: text).contains("signature"), !model.signature.isEmpty { known["signature"] = model.signature }414        variableValues = known.filter { VariableFormat.automatic($0.key) == nil }415        variableDates = [:]416        t.uses += 1; t.lastUsed = .now; showTemplates = false417    }418    private func send() async {419        guard let to = e164 else { return }420        sending = true; defer { sending = false }421        do {422            let m = try await model.api.send(to: to, text: finalText, simId: simId, idempotencyKey: idempotencyKey)423            remember(to)424            UINotificationFeedbackGenerator().notificationOccurred(.success)425            showConfirm = false426            let name = recipientName427            reset(); recipientName = ""; _ = name428            tracked = m429        } catch let e as APIError where e.code == "recipient_not_allowed" {430            showConfirm = false; notAllowed = to431        } catch {432            showConfirm = false433            let e = error as? APIError434            self.error = model.handle(error) + (e?.retryAfter.map { " Réessayez dans \($0) s." } ?? "")435            UINotificationFeedbackGenerator().notificationOccurred(.error)436        }437    }438    private func allow(_ number: String) async {439        do { try await model.api.allow(number, label: recipientName); await model.refreshGateway(); notAllowed = nil; showConfirm = true } catch { self.error = model.handle(error) }440    }441    private func remember(_ number: String) {442        if let r = recents.first(where: { $0.number == number }) { r.lastUsed = .now; r.uses += 1; if !recipientName.isEmpty { r.name = recipientName } }443        else { let r = RecentRecipient(number: number, name: recipientName); r.uses = 1; store.insert(r) }444    }445}446447/// Sélecteur de contact du système : l'application ne reçoit que le numéro choisi, sans accès au carnet.448struct ContactPicker: UIViewControllerRepresentable {449    let onPick: (String, String) -> Void450    func makeCoordinator() -> Coordinator { Coordinator(onPick: onPick) }451    func makeUIViewController(context: Context) -> CNContactPickerViewController {452        let p = CNContactPickerViewController()453        p.displayedPropertyKeys = [CNContactPhoneNumbersKey]454        p.predicateForEnablingContact = NSPredicate(format: "phoneNumbers.@count > 0")455        p.predicateForSelectionOfContact = NSPredicate(format: "phoneNumbers.@count == 1")456        p.delegate = context.coordinator457        return p458    }459    func updateUIViewController(_ vc: CNContactPickerViewController, context: Context) {}460    final class Coordinator: NSObject, CNContactPickerDelegate {461        let onPick: (String, String) -> Void462        init(onPick: @escaping (String, String) -> Void) { self.onPick = onPick }463        func contactPicker(_ picker: CNContactPickerViewController, didSelect contact: CNContact) {464            if let n = contact.phoneNumbers.first?.value.stringValue { onPick(CNContactFormatter.string(from: contact, style: .fullName) ?? "", n) }465        }466        func contactPicker(_ picker: CNContactPickerViewController, didSelect contactProperty: CNContactProperty) {467            if let n = (contactProperty.value as? CNPhoneNumber)?.stringValue { onPick(CNContactFormatter.string(from: contactProperty.contact, style: .fullName) ?? "", n) }468        }469    }470}471472/// Permet de choisir le style du sélecteur de date à l'exécution (roue pour l'heure, calendrier pour la date).473struct AnyDatePickerStyle: DatePickerStyle {474    enum Kind { case wheel, graphical }475    let kind: Kind476    init(_ kind: Kind) { self.kind = kind }477    @ViewBuilder func makeBody(configuration: Configuration) -> some View {478        switch kind {479        case .wheel: DatePicker(selection: configuration.$selection, displayedComponents: configuration.displayedComponents) { configuration.label }.datePickerStyle(.wheel)480        case .graphical: DatePicker(selection: configuration.$selection, displayedComponents: configuration.displayedComponents) { configuration.label }.datePickerStyle(.graphical)481        }482    }483}484
Files main
Menu

Theme