Cotton code
198 lines · 9.9 KB · SwiftRaw
// How to reach someone — and it is always somebody else's app that does it.//// Cotton sends nothing. "Call" hands the number to the Phone app (`tel:`),// "Message" hands it to Messages (`sms:`) or, when the conversation Cotton// holds with them came over WhatsApp, to WhatsApp — its URL scheme first and// Messages behind it when WhatsApp is unavailable. Contact actions always// hand off to a phone app; they never open a web page.//// Every URL a page opens is built HERE, as pure functions, so the whole table// is tested rather than spread across buttons. A column marked `reach` draws// its values through `ReachLines`: a line each that opens the sheet of what// can be done with it (`ContactSheetContent`), a long press copying it, and —// under the definition's first phone column — the quiet "Call" and "Message".// The call log rings back through `ContactHandoff.callBack`. Moved here from// the old person page, which drew them first.import CottonValuesimport SwiftUI/// What can be done with a contact point.enum ContactAction: Equatable, Sendable {    case call, message, whatsApp, whatsAppCall, copy, mail, instagram, faceTime}/// A link to open, and the one to try when it will not.struct Handoff: Equatable, Sendable {    let url: URL    let fallback: URL?}enum ContactHandoff {    /// The fewest digits that can plausibly address a real subscriber.    static let minAddressableDigits = 10    /// The number as it is dialled: digits only, with the leading `+` kept    /// when the number was written with one — `tel:+919876543210` reaches the    /// same phone from any country, `tel:919876543210` does not.    static func dialable(_ phone: String) -> String {        let digits = phone.filter(\.isNumber)        let international = phone.trimmingCharacters(in: .whitespaces).hasPrefix("+")        return international && !digits.isEmpty ? "+\(digits)" : digits    }    /// Digits only — what WhatsApp's links take, which have no `+`.    static func digits(_ phone: String) -> String {        phone.filter(\.isNumber)    }    /// An Instagram handle as its links take it: no "@", no profile URL    /// round it, only the characters a handle can hold.    static func instagramHandle(_ value: String) -> String {        var handle = value.trimmingCharacters(in: .whitespacesAndNewlines)        for prefix in ["https://www.instagram.com/", "https://instagram.com/", "instagram.com/", "@"] where handle.lowercased().hasPrefix(prefix) {            handle = String(handle.dropFirst(prefix.count))        }        handle = handle.trimmingCharacters(in: CharacterSet(charactersIn: "/"))        return handle.allSatisfy({ $0.isLetter || $0.isNumber || $0 == "." || $0 == "_" }) ? handle : ""    }    /// WhatsApp is offered only for a number long enough to address: a short    /// entry (an extension, a half-typed number) would open a dead chat.    static func canWhatsApp(_ phone: String) -> Bool {        digits(phone).count >= minAddressableDigits    }    /// Which app "Message" goes to. WhatsApp when Cotton's conversation with    /// them is a WhatsApp one AND the number can address a chat; Messages    /// otherwise — Messages takes iMessage and SMS alike.    static func messagesInWhatsApp(channel: String?, phone: String) -> Bool {        channel == "whatsapp" && canWhatsApp(phone)    }    /// The link for one action on one contact point. `nil` when the point    /// cannot take the action (an email cannot be called, a number with no    /// digits cannot be dialled, a short number has no WhatsApp) — the button    /// is then absent, never offered and dead. `.copy` is not a link.    static func link(_ action: ContactAction, _ target: ContactTarget) -> Handoff? {        switch (target.kind, action) {        case (_, .copy):            return nil        case (.email, .mail):            let address = target.value.trimmingCharacters(in: .whitespaces)            guard address.contains("@"), let url = URL(string: "mailto:\(address)") else { return nil }            return Handoff(url: url, fallback: nil)        case (.instagram, .instagram):            // The app's own link first; the profile on the web behind it.            let handle = instagramHandle(target.value)            guard !handle.isEmpty, let url = URL(string: "instagram://user?username=\(handle)"),                let web = URL(string: "https://www.instagram.com/\(handle)/")            else { return nil }            return Handoff(url: url, fallback: web)        case (.phone, .faceTime), (.email, .faceTime):            // FaceTime reaches a number or an Apple ID's address alike.            let point = target.kind == .phone ? dialable(target.value) : target.value.trimmingCharacters(in: .whitespaces)            guard !point.isEmpty, let url = URL(string: "facetime:\(point)") else { return nil }            return Handoff(url: url, fallback: nil)        case (.instagram, _), (_, .instagram), (.email, _), (.phone, .mail):            return nil        case (.phone, .call):            let number = dialable(target.value)            guard !digits(number).isEmpty, let url = URL(string: "tel:\(number)") else { return nil }            return Handoff(url: url, fallback: nil)        case (.phone, .message):            let number = dialable(target.value)            guard !digits(number).isEmpty, let url = URL(string: "sms:\(number)") else { return nil }            return Handoff(url: url, fallback: nil)        case (.phone, .whatsApp), (.phone, .whatsAppCall):            // WhatsApp publishes no link that starts a CALL; the chat is as            // close as a link can land, with the call button one tap away.            guard canWhatsApp(target.value) else { return nil }            let number = digits(target.value)            guard let url = URL(string: "whatsapp://send?phone=\(number)"),                let messages = URL(string: "sms:\(dialable(target.value))")            else { return nil }            return Handoff(url: url, fallback: messages)        }    }    /// The page's quiet "Message" action for a person: their first number,    /// into WhatsApp or Messages by the conversation's channel.    static func message(phones: [String], channel: String?) -> Handoff? {        guard let phone = phones.first(where: { !digits($0).isEmpty }) else { return nil }        let target = ContactTarget(value: phone, kind: .phone)        return link(messagesInWhatsApp(channel: channel, phone: phone) ? .whatsApp : .message, target)    }    /// The page's quiet "Call" action: their first dialable number.    static func call(phones: [String]) -> Handoff? {        guard let phone = phones.first(where: { !digits($0).isEmpty }) else { return nil }        return link(.call, ContactTarget(value: phone, kind: .phone))    }    /// "+91 98765 43210" — grouped for READING. The number that is copied and    /// dialled is still the raw one; only the reading changes, and only for the    /// one shape this app actually shows. A wrong grouping reads worse than    /// none, so everything else passes through untouched.    static func forReading(_ phone: String) -> String {        let compact = phone.filter { !$0.isWhitespace && $0 != "-" }        guard compact.hasPrefix("+91") else { return phone }        let rest = String(compact.dropFirst(3))        guard rest.count == 10, rest.allSatisfy(\.isNumber) else { return phone }        return "+91 \(rest.prefix(5)) \(rest.dropFirst(5))"    }    /// An email address laid out for READING on the narrow contact card: a    /// zero-width break before the "@", so an address too long for one line    /// breaks into its name and its domain rather than mid-word    /// ("karan.velloran@examp / le.com"). The address that is copied and mailed    /// is still the raw one.    static func forReading(email: String) -> String {        guard let at = email.firstIndex(of: "@"), at != email.startIndex else { return email }        return String(email[..<at]) + "\u{200B}" + String(email[at...])    }    /// Opens a link, with the universal-link fallback behind it where there    /// is one. Only the LAST candidate failing is `failed`: `whatsapp://`    /// not opening is expected on a phone without WhatsApp.    @MainActor static func open(_ handoff: Handoff, with openURL: OpenURLAction, failed: @escaping () -> Void) {        openURL(handoff.url) { opened in            guard !opened else { return }            guard let fallback = handoff.fallback else { return failed() }            openURL(fallback) { landed in                if !landed { failed() }            }        }    }    /// What a contact point's sheet offers, in order.    static func actions(for target: ContactTarget) -> [(action: ContactAction, symbol: String, label: String)] {        if target.kind == .email {            return [(.mail, "envelope", ShellLines.line("faces", "contact.write_email")), (.copy, "doc.on.doc", ShellLines.line("faces", "contact.copy_address"))]        }        if target.kind == .instagram {            return [(.instagram, "camera", ShellLines.line("faces", "contact.open_instagram")), (.copy, "doc.on.doc", ShellLines.line("faces", "contact.copy_handle"))]        }        var out: [(ContactAction, String, String)] = [            (.call, "phone", ShellLines.line("faces", "contact.call")),            (.message, "message", ShellLines.line("faces", "contact.message")),        ]        if canWhatsApp(target.value) {            out.append((.whatsApp, "bubble.left", ShellLines.line("faces", "contact.whatsapp")))            out.append((.whatsAppCall, "phone.bubble", ShellLines.line("faces", "contact.whatsapp_call")))        }        out.append((.copy, "doc.on.doc", ShellLines.line("faces", "contact.copy_number")))        return out    }}extension ContactTarget.Kind {    /// The kind a `reach` column's values are.    init(_ reach: ReachKind) {        switch reach {        case .phone: self = .phone        case .email: self = .email        case .instagram: self = .instagram        }    }}