SPB Git

Repository Public

RecipientTokens.swift 14.7 KB 295 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Sources/Shared/Compose/RecipientTokens.swift3// Description: Recipient token fields (To / Cc / Bcc) — tokens with name and validity, autocomplete (saved contacts, favourites, groups that4// expand to their members), keyboard entry (comma, semicolon, Return, Backspace, arrows in the suggestions), drag of tokens between5// fields — and the sender and signature pickers of the composer header.6import SPMailCore7import SwiftUI8import UniformTypeIdentifiers910/// A recipient being dragged from one field to another (or out of the app, as text).11struct RecipientTransfer: Codable, Transferable {12    var name: String?13    var email: String14    var address: EmailAddress { EmailAddress(name: name, email: email) }15    static var transferRepresentation: some TransferRepresentation {16        CodableRepresentation(contentType: .json)17        ProxyRepresentation(exporting: { EmailAddress(name: $0.name, email: $0.email).formatted })18    }19}2021struct RecipientField: View {22    #if os(iOS)23    static let suggestionHeight: CGFloat = 4424    /// An invisible first character: deleting it is how Backspace in an empty field is seen on a software keyboard.25    static let sentinel = "\u{200B}"26    #else27    static let suggestionHeight: CGFloat = 2628    static let sentinel = ""29    #endif30    let label: String31    @Binding var addresses: [EmailAddress]32    let model: any RecipientHost33    var kind: RecipientFieldKind = .to34    @State private var draft = RecipientField.sentinel35    @State private var suggestions: [RecipientSuggestion] = []36    @State private var highlighted = 037    @State private var lookup: Task<Void, Never>?38    @State private var dropTargeted = false39    @FocusState private var focused: Bool4041    private var typed: String { draft.replacingOccurrences(of: "\u{200B}", with: "") }4243    var body: some View {44        VStack(alignment: .leading, spacing: 4) {45            HStack(alignment: .firstTextBaseline, spacing: 8) {46                Text(label).foregroundStyle(SPColor.text3).frame(minWidth: 34, alignment: .leading)47                FlowLayout(spacing: 6) {48                    ForEach(addresses) { a in RecipientToken(address: a, remove: { remove(a) }, move: move(a)) }49                    field50                }51            }52            if focused, !suggestions.isEmpty { suggestionList }53        }54        .contentShape(Rectangle())55        .onTapGesture { focused = true }56        .background { if dropTargeted { RoundedRectangle(cornerRadius: SPRadius.chip, style: .continuous).fill(SPColor.accentSoft).padding(-4) } }57        .dropDestination(for: RecipientTransfer.self) { items, _ in58            for t in items where !model.moveRecipient(t.address, to: kind) { append(t.address) }59            model.edited()60            return !items.isEmpty61        } isTargeted: { dropTargeted = $0 }62    }6364    private var field: some View {65        TextField("", text: $draft)66            .textFieldStyle(.plain)67            .frame(minWidth: 140)68            .focused($focused)69            .autocorrectionDisabled()70            #if os(iOS)71            .textInputAutocapitalization(.never)72            .keyboardType(.emailAddress)73            .textContentType(.emailAddress)74            #endif75            .onSubmit { if suggestions.indices.contains(highlighted), !typed.contains("@") { pick(suggestions[highlighted]) } else { commit(force: true) }; focused = true }76            .onChange(of: draft) { old, new in changed(from: old, to: new) }77            .onChange(of: focused) { _, isFocused in if !isFocused { commit(force: true); suggestions = [] } }78            .onKeyPress(.downArrow) { guard !suggestions.isEmpty else { return .ignored }; highlighted = min(suggestions.count - 1, highlighted + 1); return .handled }79            .onKeyPress(.upArrow) { guard !suggestions.isEmpty else { return .ignored }; highlighted = max(0, highlighted - 1); return .handled }80            .onKeyPress(.escape) { guard !suggestions.isEmpty else { return .ignored }; suggestions = []; return .handled }81            .onKeyPress(.tab) { guard suggestions.indices.contains(highlighted), !typed.isEmpty else { return .ignored }; pick(suggestions[highlighted]); return .handled }82            #if os(macOS)83            .onKeyPress(.delete) { guard typed.isEmpty, let last = addresses.last else { return .ignored }; remove(last); return .handled }84            #endif85            .accessibilityLabel(Text(label))86            .accessibilityHint(Text("Séparez les adresses par une virgule."))87    }8889    private var suggestionList: some View {90        VStack(alignment: .leading, spacing: 0) {91            ForEach(Array(suggestions.prefix(6).enumerated()), id: \.element.id) { n, s in92                Button { pick(s) } label: {93                    HStack(spacing: 8) {94                        Image(systemName: icon(s)).foregroundStyle(s.isGroup ? SPColor.info : SPColor.text3).frame(width: 18)95                        Text(s.name.isEmpty ? s.email : s.name).foregroundStyle(SPColor.text).lineLimit(1)96                        if s.isGroup { Text("Groupe").font(SPFont.caption).foregroundStyle(SPColor.text3) } else if !s.name.isEmpty { Text(s.email).foregroundStyle(SPColor.text3).lineLimit(1) }97                        Spacer(minLength: 0)98                    }99                    .padding(.vertical, 3).padding(.horizontal, 8).frame(minHeight: RecipientField.suggestionHeight).contentShape(Rectangle())100                    .background { if n == highlighted { RoundedRectangle(cornerRadius: SPRadius.chip, style: .continuous).fill(SPColor.accentSoft) } }101                }102                .buttonStyle(.plain)103                .accessibilityLabel(Text(s.isGroup ? L("Groupe \(s.name)") : s.name.isEmpty ? s.email : "\(s.name), \(s.email)"))104            }105        }106        .padding(3)107        .background(SPColor.surface2, in: RoundedRectangle(cornerRadius: SPRadius.card, style: .continuous))108        .overlay(RoundedRectangle(cornerRadius: SPRadius.card, style: .continuous).stroke(SPColor.border, lineWidth: 0.5))109        .padding(.leading, 42)110    }111112    private func icon(_ s: RecipientSuggestion) -> String {113        switch s.kind {114        case .group: "person.2.fill"115        case .contact(_, let favorite) where favorite: "star.fill"116        case .contact(let saved, _): saved ? "person.crop.circle.fill" : "person.crop.circle"117        }118    }119120    private func changed(from old: String, to new: String) {121        #if os(iOS)122        if !new.hasPrefix(RecipientField.sentinel) {123            // the sentinel was deleted: Backspace in an empty field removes the last token124            if old == RecipientField.sentinel, new.isEmpty, let last = addresses.last { remove(last) }125            draft = RecipientField.sentinel + new.replacingOccurrences(of: "\u{200B}", with: "")126            return127        }128        #endif129        let text = typed130        if text.contains(where: { ",;\n\t".contains($0) }) { commit(force: false); return }131        highlighted = 0132        lookup?.cancel()133        guard !text.trimmingCharacters(in: .whitespaces).isEmpty else { suggestions = []; return }134        lookup = Task {135            try? await Task.sleep(for: .milliseconds(120))136            guard !Task.isCancelled else { return }137            let found = await model.recipientSuggestions(for: text)138            if !Task.isCancelled, typed == text { suggestions = found }139        }140    }141142    private func append(_ a: EmailAddress) { if !addresses.contains(where: { $0.id == a.id }) { addresses.append(a) } }143    private func remove(_ a: EmailAddress) { addresses.removeAll { $0.id == a.id }; model.edited() }144    /// The other fields this token can be sent to (only when the host owns them).145    private func move(_ a: EmailAddress) -> ((RecipientFieldKind) -> Void)? {146        guard model is ComposeModel else { return nil }147        return { target in _ = model.moveRecipient(a, to: target) }148    }149150    private func pick(_ s: RecipientSuggestion) {151        lookup?.cancel()152        draft = RecipientField.sentinel; suggestions = []153        if case .group(let id) = s.kind {154            Task {155                for a in await model.members(ofGroup: id) { append(a) }156                model.edited()157            }158        } else { append(s.address); model.edited() }159    }160161    /// Turns what was typed into tokens. An entry that is not an address becomes a token too — shown as invalid, never silently dropped.162    private func commit(force: Bool) {163        let result = RecipientInput.commit(typed, force: force)164        guard !result.entries.isEmpty || result.rest != typed else { return }165        for a in result.entries { append(a) }166        lookup?.cancel()167        draft = RecipientField.sentinel + result.rest168        suggestions = []169        if !result.entries.isEmpty { model.edited() }170    }171}172173/// One recipient: name (or address), a warning when the address is not valid, remove button; draggable to another field.174struct RecipientToken: View {175    let address: EmailAddress176    let remove: () -> Void177    var move: ((RecipientFieldKind) -> Void)?178179    var body: some View {180        let valid = AddressParser.isValid(address.email)181        HStack(spacing: 4) {182            if !valid { Image(systemName: "exclamationmark.triangle.fill").imageScale(.small).foregroundStyle(SPColor.danger) }183            Text(address.displayName).lineLimit(1)184            Button(action: remove) { Image(systemName: "xmark.circle.fill").imageScale(.small) }185                .buttonStyle(.plain).foregroundStyle(SPColor.text3)186                .accessibilityLabel(Text("Retirer \(address.displayName)"))187        }188        .padding(.horizontal, 8).padding(.vertical, 3)189        .background(valid ? SPColor.accentSoft : SPColor.dangerSoft, in: Capsule())190        .overlay { if !valid { Capsule().stroke(SPColor.danger.opacity(0.5), lineWidth: 0.5) } }191        .foregroundStyle(SPColor.text)192        .help(valid ? address.email : L("Adresse invalide : \(address.email)"))193        .draggable(RecipientTransfer(name: address.name, email: address.email)) {194            Text(address.displayName).padding(.horizontal, 8).padding(.vertical, 3).background(SPColor.accentSoft, in: Capsule())195        }196        .contextMenu {197            Button("Copier l’adresse") { copy(address.email) }198            if let move {199                Divider()200                Button("Déplacer vers À") { move(.to) }201                Button("Déplacer vers Cc") { move(.cc) }202                Button("Déplacer vers Cci") { move(.bcc) }203            }204            Divider()205            Button("Retirer", role: .destructive, action: remove)206        }207        .accessibilityElement(children: .combine)208        .accessibilityLabel(Text(valid ? (address.name == nil ? address.email : "\(address.displayName), \(address.email)") : L("Adresse invalide : \(address.email)")))209        .accessibilityAddTraits(.isButton)210        .accessibilityAction(named: Text("Retirer"), remove)211    }212213    private func copy(_ s: String) {214        #if os(macOS)215        NSPasteboard.general.clearContents(); NSPasteboard.general.setString(s, forType: .string)216        #else217        UIPasteboard.general.string = s218        #endif219    }220}221222/// Wrapping horizontal layout for recipient tokens: the last subview (the text field) takes what is left of its row.223struct FlowLayout: Layout {224    var spacing: CGFloat = 6225    func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {226        arrange(width: proposal.width ?? 400, subviews: subviews).size227    }228    func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {229        let r = arrange(width: bounds.width, subviews: subviews)230        for (i, p) in r.points.enumerated() { subviews[i].place(at: CGPoint(x: bounds.minX + p.x, y: bounds.minY + p.y), proposal: ProposedViewSize(width: r.widths[i], height: nil)) }231    }232    private func arrange(width: CGFloat, subviews: Subviews) -> (size: CGSize, points: [CGPoint], widths: [CGFloat]) {233        var x: CGFloat = 0, y: CGFloat = 0, row: CGFloat = 0234        var points: [CGPoint] = [], widths: [CGFloat] = []235        for (n, v) in subviews.enumerated() {236            var s = v.sizeThatFits(.unspecified)237            let last = n == subviews.count - 1238            if last { s.width = max(140, min(s.width, width)) } // the text field takes what is left on its row239            if x > 0, x + s.width > width { x = 0; y += row + spacing; row = 0 }240            let w = last ? max(s.width, width - x) : min(s.width, width)241            points.append(CGPoint(x: x, y: y)); widths.append(w)242            x += w + spacing; row = max(row, s.height)243        }244        return (CGSize(width: width, height: y + row), points, widths)245    }246}247248// MARK: - sender and signature249250/// From picker: mailboxes and their sendable aliases, grouped by mailbox. Only addresses the server lists as sendable — never free text.251struct SenderPicker: View {252    let groups: [(mailbox: String, senders: [SenderIdentity])]253    @Binding var selection: String254    var body: some View {255        Picker("De", selection: $selection) {256            ForEach(groups, id: \.mailbox) { g in257                Section(g.mailbox) {258                    ForEach(g.senders) { s in Text(s.isAlias ? L("\(s.address.formatted) — alias") : s.address.formatted).tag(s.id) }259                }260            }261        }262        .labelsHidden()263        .accessibilityLabel(Text("Expéditeur"))264    }265}266267/// Signature menu of the composer: the signatures of the account, « none », and the manager.268struct SignaturePicker: View {269    let model: ComposeModel270    let center: ComposeCenter271    @Binding var showManager: Bool272    /// iPhone: the glyph alone.273    var compact = false274275    var body: some View {276        let current = model.currentSignatureId277        Menu {278            ForEach(center.signatures) { s in279                Button { model.chooseSignature(SignatureChoice(s)) } label: { if current == s.id { Label(s.name.isEmpty ? L("Signature") : s.name, systemImage: "checkmark") } else { Text(s.name.isEmpty ? L("Signature") : s.name) } }280            }281            if !center.signatures.isEmpty { Divider() }282            Button { model.chooseSignature(nil) } label: { if current == nil { Label("Aucune signature", systemImage: "checkmark") } else { Text("Aucune signature") } }283            Divider()284            Button("Gérer les signatures…") { showManager = true }285        } label: {286            let title = center.signatures.first { $0.id == current }.map { $0.name.isEmpty ? L("Signature") : $0.name } ?? L("Signature")287            if compact { Image(systemName: "signature").frame(minWidth: 36, minHeight: 32) } else { Label(title, systemImage: "signature").labelStyle(.titleAndIcon).font(SPFont.callout).lineLimit(1) }288        }289        .menuStyle(.borderlessButton)290        .fixedSize()291        .help("Choisir la signature de ce message")292        .accessibilityLabel(Text("Signature"))293    }294}295
Files main
Menu

Theme