Cotton code
170 lines · 10.1 KB · SwiftRaw
// COTTON CONTACTS' CALLS: every screen asks the core with a call it was given (or the home's first), and draws the// answer. Until a method lands in the core (it answers `unknown_method`), the stand-in below answers the same shape// from what the phone already keeps (the `person` table), so the app opens and reads his contacts from the first build;// each method moves to the core's own answer as it lands, with nothing to change here.#if os(iOS)import CottonKitimport Foundation@MainActorstruct ContactsCalls {    let core: any CottonCalling    /// The call as given; the stand-in only while the core does not know the method.    func ask<Answer: Decodable & Sendable>(_ call: ContactsCall, as type: Answer.Type = Answer.self) async -> ContactsRead<Answer> {        do {            return .read(try await core.call(call.method, call.request ?? .object([:]), as: type))        } catch let error as CottonCallError where error.code == "unknown_method" {            return await ContactsStandIn(core: core).answer(call, as: type)        } catch let error as CottonCallError {            Log.write("contacts: \(call.method) refused — \(error.code)")            return .refused(error.message)        } catch {            Log.write("contacts: \(call.method) did not read — \(error)")            return .refused(ContactsWords.line("ask.could_not_load"))        }    }    func home(kind: String?, query: String?) async -> ContactsRead<ContactsHome> {        var request: [String: JSONValue] = [:]        if let kind { request["kind"] = .string(kind) }        if let query, !query.isEmpty { request["query"] = .string(query) }        return await ask(ContactsCall(method: "contacts.home", request: .object(request)))    }    func person(_ id: String) async -> ContactsRead<ContactsPerson> {        await ask(ContactsCall(method: "contacts.person", request: .object(["id": .string(id)])))    }    func groups() async -> ContactsRead<ContactsGroups> { await ask(ContactsCall(method: "contacts.groups")) }    func group(_ id: String) async -> ContactsRead<ContactsGroup> {        await ask(ContactsCall(method: "contacts.group", request: .object(["id": .string(id)])))    }    func same() async -> ContactsRead<ContactsSameList> { await ask(ContactsCall(method: "contacts.same.list")) }    func circle() async -> ContactsRead<ContactsCircle> { await ask(ContactsCall(method: "contacts.circle")) }    func form(_ call: ContactsCall) async -> ContactsRead<ContactsForm> { await ask(call) }    /// A write the core named, with `extra` added to its request (a form's values, a title's id).    func act(_ call: ContactsCall, adding extra: [String: JSONValue] = [:]) async -> ContactsRead<ContactsSaid> {        var request = (call.request ?? .object([:])).contactsFields        for (key, value) in extra { request[key] = value }        switch await ask(ContactsCall(method: call.method, request: .object(request)), as: ContactsSaid.self) {        case .read(let said) where said.error != nil: return .refused(said.error ?? "")        case let other: return other        }    }    /// Every card of the phone's address book, in one call (`contacts.read`; until it lands, the tool People's import    /// already uses, `sync_device_contacts`, which matches a card already seen and makes the rest).    func read(_ cards: [DeviceContact]) async -> ContactsRead<String> {        let entries = JSONValue.array(cards.map(ContactBook.syncEntry))        do {            let said = try await core.call("contacts.read", JSONValue.object(["cards": entries, "device": .string("iphone")]), as: ContactsSaid.self)            return .read(said.said ?? ContactsWords.line("import.said", ["count": cards.count.formatted()]))        } catch let error as CottonCallError where error.code == "unknown_method" {            do {                _ = try await core.call(CottonMethod.write, WriteRequest(tool: ContactImport.syncDeviceContacts, args: .object(["contacts": entries])), as: WriteAnswer.self)                return .read(ContactsWords.line("import.said", ["count": cards.count.formatted()]))            } catch let error as CottonCallError {                return .refused(error.message)            } catch {                return .refused(ContactsWords.line("ask.could_not_load"))            }        } catch let error as CottonCallError {            return .refused(error.message)        } catch {            return .refused(ContactsWords.line("ask.could_not_load"))        }    }}/// The stand-in for the core's Contacts methods not landed yet: the same shapes, from the `person` table, in the/// app's own lines (`stub.*`). Reads only; a write the core does not know yet says so.@MainActorstruct ContactsStandIn {    let core: any CottonCalling    private func w(_ key: String) -> String { ContactsWords.line(Self.lines[key] ?? key) }    /// The stand-in's words, from the app's line set.    private static let lines: [String: String] = ["title": "home.title", "search": "home.search", "all": "home.kind_all", "people": "home.kind_people", "organisations": "home.kind_organisations", "assistants": "home.kind_assistants", "rest": "home.tier_rest", "found": "home.found", "add": "home.add", "import": "home.import", "import_hint": "home.import_hint", "empty_title": "home.empty_title", "empty_message": "home.empty_line", "groups": "groups.title", "groups_foot": "groups.foot", "same": "same.title", "same_empty": "same.none", "circle": "circle.title", "soon": "circle.soon", "circle_message": "circle.line", "person": "edit.kind_person", "not_ready": "ask.could_not_load"]    private struct Person {        let id: String        let name: String        let phone: String?        let email: String?        let org: String?    }    private func people() async -> [Person] {        let request: [String: JSONValue] = ["table": .string("person")]        guard let page = try? await core.call(CottonMethod.recordsList, JSONValue.object(request), as: JSONValue.self) else { return [] }        return (page.contactsFields["records"]?.array ?? []).compactMap { record in            let fields = record.contactsFields            guard let id = fields["id"]?.string else { return nil }            let data = fields["data"]?.contactsFields ?? [:]            if let archived = data["archived_at"]?.string, !archived.isEmpty { return nil }            func text(_ key: String) -> String? { data[key]?.string.flatMap { $0.isEmpty ? nil : $0 } }            return Person(id: id, name: text("full_name") ?? text("phone") ?? text("email") ?? "", phone: text("phone"), email: text("email"), org: text("org"))        }        .sorted { $0.name.localizedCaseInsensitiveCompare($1.name) == .orderedAscending }    }    static func initials(_ name: String) -> String {        let words = name.split(separator: " ").filter { $0.first?.isLetter == true }        guard let first = words.first?.first else { return "#" }        let second = words.count > 1 ? words.last?.first.map(String.init) ?? "" : ""        return (String(first) + second).uppercased()    }    private func row(_ p: Person) -> ContactsRow {        ContactsRow(id: p.id, words: p.name, detail: p.org ?? p.phone ?? p.email, initials: Self.initials(p.name), picture: nil, kind: "person",                    call: ContactsCall(method: "contacts.person", request: .object(["id": .string(p.id)])))    }    func answer<Answer: Decodable & Sendable>(_ call: ContactsCall, as type: Answer.Type) async -> ContactsRead<Answer> {        let request = (call.request ?? .object([:])).contactsFields        let built: Any?        switch call.method {        case "contacts.home": built = await home(kind: request["kind"]?.string ?? "all", query: request["query"]?.string ?? "")        case "contacts.person": built = await person(request["id"]?.string ?? "")        case "contacts.groups":            built = ContactsGroups(title: w("groups"), sections: [], foot: w("groups_foot"), add: nil)        case "contacts.same.list":            built = ContactsSameList(title: w("same"), count: 0, pairs: [], empty: ContactsEmpty(title: w("same_empty"), message: nil))        case "contacts.circle":            built = ContactsCircle(title: w("circle"), empty: ContactsEmpty(title: w("soon"), message: w("circle_message")))        default: built = nil        }        guard let answer = built as? Answer else { return .refused(w("not_ready")) }        return .read(answer)    }    private func home(kind: String, query: String) async -> ContactsHome {        let everyone = kind == "all" || kind == "person" ? await people() : []        let q = query.trimmingCharacters(in: .whitespaces)        let shown = q.isEmpty ? everyone : everyone.filter {            $0.name.localizedCaseInsensitiveContains(q) || ($0.phone?.contains(q) ?? false) || ($0.email?.localizedCaseInsensitiveContains(q) ?? false)        }        let kinds = [("all", "all"), ("person", "people"), ("organisation", "organisations"), ("assistant", "assistants")].map { id, word in            ContactsHome.Kind(id: id, words: w(word), on: id == kind, call: ContactsCall(method: "contacts.home", request: .object(["kind": .string(id)])))        }        let sections = shown.isEmpty ? [] : [ContactsSection(id: q.isEmpty ? "rest" : "found", title: w(q.isEmpty ? "rest" : "found"), count: shown.count, rows: shown.map(row))]        return ContactsHome(            title: w("title"), search: .init(placeholder: w("search"), query: q), kinds: kinds, same: nil, sections: sections,            add: nil, import: .init(words: w("import"), hint: w("import_hint")),            empty: everyone.isEmpty && q.isEmpty ? ContactsEmpty(title: w("empty_title"), message: w("empty_message")) : nil        )    }    private func person(_ id: String) async -> ContactsPerson? {        guard let p = await people().first(where: { $0.id == id }) else { return nil }        var reach: [ContactsPerson.Reach] = []        if let phone = p.phone { reach.append(.init(id: "phone", kind: "phone", words: phone)) }        if let email = p.email { reach.append(.init(id: "email", kind: "email", words: email)) }        return ContactsPerson(id: p.id, kind: "person", title: p.name, initials: Self.initials(p.name), subtitle: p.org ?? w("person"), reach: reach)    }}#endif