Cotton code
828 lines · 36.6 KB · SwiftRaw
// `/people/import` — curate on import: People's "Import from contacts" act,// covering the whole screen over the list (`PeopleListFlow`), never a page of// the list's own.// A person is a record and is drawn by the person table's page; what is left// here is the flow over this phone's address book, which no table holds.//// Every visit re-reads this phone's address book (WITHOUT photos — see the gap// below), shows who is already in People, and files only what gets selected.// The list starts with NOTHING selected: curation is the point, and "Select// all" is one tap away for the opposite mood.//// ## The identity spine//// The write is ONE `sync_device_contacts` call carrying the whole selection,// not N `create_person` calls. That verb is the insert half of the// contact sync, and every row it writes carries// `device_contact_id` — which `uq_cotton_people_device_contact` makes unique// and which a second run SKIPS. That is what makes running this twice safe,// what makes renaming somebody in Cotton harmless, and what fills the "Already// in People" section and the sync bar's linked count. Matching on the full// name instead — which is what N creates left us with — got none of the three,// and let a rename mint a twin.//// ## What this sheet still cannot do//// [people-import-writes-no-avatars] CLOSED 2026-09-12. The pictures come with// the people now — `bringFaces` re-reads each new person's card by identifier,// stages a square and calls `capture.avatar`. It runs AFTER the receipt and// detached, because a portrait per person is a second per person and the owner// has already been told their contacts landed.//// PORT GAP: [contact-mirror-write-half-unbuilt] The contact MIRROR's write half// — pushing a person's fields back into the iPhone's address book and recording// that it did — has no verb in this catalogue at all.//// PORT GAP: [contact-sync-refresh-has-no-verb] "Sync now" re-reads the linked// cards and PATCHES the people who follow them; `sync_device_contacts` is// insert-only and says so, so the bar states the two facts it can (the count// and when this device last ran) and offers no verb.//// The search is the app's ONE grammar — the trailing circle and the pull-down// pill — rather than an inline field, which is the same// substitution the directory makes one screen back.import CottonKitimport SwiftUI// ── This phone's address book ───────────────────────────────────────────────/// Where the permission stands. `checking` never raises the system prompt: a/// screen that asks on arrival asks before the person has read why.enum ContactsPhase: Sendable {    case checking    case ask    case denied    case loading    case ready}/// The one gate to the iPhone address book, so the FIELDS asked for are/// written down once.////// iOS 18's LIMITED authorisation reads as granted: the person chose which/// cards Cotton may see, and the honest thing is to show exactly those rather/// than to argue with the choice.enum ContactBook {    /// iOS stores a birthday with no year as 1604 — the Gregorian calendar's    /// reference year. Any year at or below it is "no year", not somebody born    /// in the 1600s.    static let noYearCeiling = 1604    /// Total over ``CapabilityAccess``, so a state nobody thought about cannot    /// fall through to a `default` that reads as "fine".    ///    /// iOS 18's LIMITED authorisation is a YES, and that mapping now lives once,    /// in `SystemCapabilityAuthority` — this screen sees `.authorized` for it    /// and shows exactly the cards the person chose, rather than arguing with    /// the choice.    static func phase(_ access: CapabilityAccess) -> ContactsPhase {        switch access {        case .authorized: return .loading        case .notDetermined: return .ask        case .denied, .restricted, .unavailable: return .denied        }    }    /// What the OS already thinks. **Never prompts** — a screen that asks on    /// arrival asks before the person has read why.    static func current(        _ capabilities: any CapabilityAuthority = SystemCapabilityAuthority()    ) async -> ContactsPhase {        phase(await capabilities.status(.contacts))    }    /// The ask, through the one seam allowed to raise a prompt. It never    /// re-prompts a decided permission, which is why the person who declined    /// once lands on `.denied` and a sentence rather than on a dialog that    /// never appears.    static func request(        _ capabilities: any CapabilityAuthority = SystemCapabilityAuthority()    ) async -> ContactsPhase {        phase(await capabilities.ask(.contacts))    }    /// Read the book off the main actor. Only `DeviceContact` — a value type —    /// crosses back.    static func read() async throws -> [DeviceContact] {        let book = try LiveStores.reachAddressBook()        return try await Task.detached(priority: .userInitiated) {            var out: [DeviceContact] = []            try book.enumerate(.whole) { contact in                if let mapped = map(contact) { out.append(mapped) }            }            return out        }.value    }    /// One card, or nothing.    ///    /// A card with no NAME is dropped: a bare-number SIM entry adds only noise    /// to a curated directory, and there is nothing to put in the row's title.    ///    /// The name is the PLATFORM's composed one, preferred over    /// first-plus-last: `CNContactFormatter` knows    /// about prefixes, middle names, suffixes, nicknames and the ordering the    /// device's locale uses, and given-plus-family throws all of that away.    /// Given-plus-family remains the fallback for a card the formatter cannot    /// compose — it must never be the reason a contact is lost.    static func map(_ contact: AddressCard) -> DeviceContact? {        let composed = trimmedOrNil(contact.composedName)        let name = composed            ?? [contact.givenName, contact.familyName]                .map { $0.trimmingCharacters(in: .whitespaces) }                .filter { !$0.isEmpty }                .joined(separator: " ")        guard !name.isEmpty else { return nil }        let birthday = self.birthday(contact.birthday)        return DeviceContact(            id: contact.id,            fullName: name,            phones: clean(contact.phones),            emails: clean(contact.emails),            org: trimmedOrNil(contact.organization),            roleTitle: trimmedOrNil(contact.jobTitle),            city: contact.cities.lazy                .compactMap { trimmedOrNil($0) }                .first,            birthMonth: birthday?.month,            birthDay: birthday?.day,            birthYear: birthday?.year        )    }    /// A card's birthday, or NOTHING — never a reason to lose the contact.    ///    /// Half a birthday is no birthday (month and day are one fact), and a    /// month or day the schema would refuse is DROPPED here rather than    /// forwarded: sending it would have the whole person refused for the sake    /// of a field nobody typed.    static func birthday(_ raw: DateComponents?) -> (month: Int, day: Int, year: Int?)? {        guard let raw, let month = raw.month, let day = raw.day else { return nil }        guard month >= 1, month <= 12, day >= 1, day <= 31 else { return nil }        let year = raw.year        return (month, day, (year != nil && year! > noYearCeiling) ? year : nil)    }    /// One card's picture, read back by identifier AFTER the import.    ///    /// **Not carried on `DeviceContact`.** That value type crosses actors once    /// per contact and a book of two thousand cards with a megabyte of image    /// data on each is the jetsam kill this app has already paid for once. The    /// picture is fetched for the handful of people the import actually    /// created, one at a time, off the main actor.    ///    /// The FULL image, falling back to the thumbnail: a portrait is stored at    /// 1024 points and the card's thumbnail is often smaller than that, so    /// taking the thumbnail first would throw away detail the book had.    static func picture(of identifier: String) -> Data? {        (try? LiveStores.reachAddressBook().picture(identifier)) ?? nil    }    /// Trim, drop empties, dedupe — keeping the card's own order, which is the    /// order the person put them in.    static func clean(_ values: [String]) -> [String] {        var out: [String] = []        for value in values {            let trimmed = value.trimmingCharacters(in: .whitespacesAndNewlines)            if !trimmed.isEmpty, !out.contains(trimmed) { out.append(trimmed) }        }        return out    }    static func trimmedOrNil(_ value: String?) -> String? {        let trimmed = value?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""        return trimmed.isEmpty ? nil : trimmed    }    /// One card as `sync_device_contacts` reads it. Absent facts are ABSENT    /// keys, not nulls: the schema has no null branch, and an invented key is a    /// refusal (`additionalProperties: false`).    ///    /// `deviceContactId` is THE key — the unique index is on it, and it is what    /// makes a second run of this screen write nothing rather than a twin.    static func syncEntry(_ contact: DeviceContact) -> JSONValue {        var args: [String: JSONValue] = [            "deviceContactId": .string(contact.id),            "fullName": .string(contact.fullName),        ]        if !contact.phones.isEmpty {            args["phones"] = .array(contact.phones.map(JSONValue.string))        }        if !contact.emails.isEmpty {            args["emails"] = .array(contact.emails.map(JSONValue.string))        }        if let org = contact.org { args["org"] = .string(org) }        if let role = contact.roleTitle { args["roleTitle"] = .string(role) }        if let city = contact.city { args["city"] = .string(city) }        // Half a birthday is no birthday: the schema requires month AND day.        if let month = contact.birthMonth, let day = contact.birthDay {            var birthday: [String: JSONValue] = [                "month": .number(Double(month)), "day": .number(Double(day)),            ]            if let year = contact.birthYear { birthday["year"] = .number(Double(year)) }            args["birthday"] = .object(birthday)        }        return .object(args)    }}// ── The model ───────────────────────────────────────────────────────────────/// **DELIBERATELY NOT `Rereadable`** — `DayDestination` builds it through/// `Hosted(unwired:)`. Its read is mostly NOT of the database: `start()` asks/// this phone's address book and walks a permission phase, and a fold has/// nothing to say about either. Re-running it on every change to/// `cotton_people` would re-read the whole address book — and the write this/// screen makes already re-reads the linked set itself.@MainActor@Observablefinal class PeopleImportModel {    private(set) var phase: ContactsPhase = .checking    private(set) var contacts: [DeviceContact] = []    private(set) var alreadyLinked: Set<String> = []    /// How many people follow a card in this phone's address book. Computed by    /// the read FOR the sync bar, which is the one thing that draws it.    private(set) var linkedCount = 0    private(set) var isImporting = false    /// The address-book read that failed, held until the view has said so.    private(set) var readFailure: Error?    private let core: any CottonCalling    /// Who answers for the contacts permission: the system's, in the app.    private let capabilities: any CapabilityAuthority    /// Where the cards come from: this phone's address book, in the app.    private let book: @Sendable () async throws -> [DeviceContact]    init(        core: any CottonCalling,        capabilities: any CapabilityAuthority = SystemCapabilityAuthority(),        book: @escaping @Sendable () async throws -> [DeviceContact] = { try await ContactBook.read() }    ) {        self.core = core        self.capabilities = capabilities        self.book = book    }    var split: (eligible: [DeviceContact], alreadyImported: [DeviceContact]) {        ContactImport.partitionContacts(contacts, alreadyLinked: alreadyLinked)    }    /// The workspace's side FIRST, then the device's. A read that failed leaves    /// the set empty — every card is then offered, and the unique index on    /// `device_contact_id` is what stops a second copy landing. The set is read    /// so the LIST can say who is already in; the index is what makes it safe.    func start() async {        await loadLinked()        await advance(await ContactBook.current(capabilities))    }    func ask() async {        await advance(await ContactBook.request(capabilities))    }    private func advance(_ next: ContactsPhase) async {        if next == .loading {            phase = .loading            await loadContacts()        } else {            phase = next        }    }    /// Who this workspace already holds a card for. `read.peopleImport` answers    /// `linked` — one row per person with a `deviceContactId` — and the    /// `linkedCount` the sync bar reads out.    private func loadLinked() async {        guard let read = try? await core.callJSON(CottonMethod.readPeopleImport)        else { return }        alreadyLinked = ContactImport.alreadyLinked(read)        linkedCount = read.number("linkedCount") ?? 0    }    private func loadContacts() async {        do {            contacts = try await book()            phase = .ready        } catch {            // Back to `ask`: the read            // can fail for a permission revoked while the screen was open, and            // the way back from that is the same prompt. It also SAYS so — a            // screen that rewinds in silence is a screen that looks broken.            readFailure = error            phase = .ask        }    }    /// Clear the read failure once its sentence has been said. The model holds    /// it only long enough for the view to toast it once.    func readFailureShown() { readFailure = nil }    /// File the chosen people — ONE call.    ///    /// Batched rather than looped because `device_contact_id` is the identity:    /// the handler skips a contact already linked, guards the batch against    /// itself, and commits in chunks, so a re-import of the same selection    /// writes nothing and a partial failure is the fold's own all-or-nothing    /// rather than a half-written directory this screen would have to unwind.    ///    /// Throws what the core said, so the screen can say it.    func importing(_ chosen: [DeviceContact]) async throws -> ContactSyncOutcome {        isImporting = true        defer { isImporting = false }        let answer = try await core.call(            CottonMethod.write,            WriteRequest(                tool: ContactImport.syncDeviceContacts,                args: .object([                    "contacts": .array(chosen.map(ContactBook.syncEntry))                ])            ),            as: WriteAnswer.self        )        await loadLinked()        return ContactSyncOutcome(answer)    }    /// The faces the address book already had, after the people exist.    ///    /// **This is what closes [contacts-import-brings-no-avatar], and it closes    /// it on the PHONE** — which is where the address book is. The Rust half    /// cannot: `sync_device_contacts` takes a card's FIELDS, and a card's    /// picture is bytes, which never cross that boundary.    ///    /// Best effort, and never the import's problem. It runs AFTER the receipt,    /// one person at a time so a book of five hundred new contacts does not    /// stage five hundred JPEGs at once, and a card with no picture, a picture    /// ImageIO will not read and a capture the core refused are all the same    /// thing here: that person has no picture yet.    func bringFaces(_ made: [(personId: String, deviceContactId: String)]) async {        for person in made {            let staged = await Task.detached(priority: .utility) { () -> URL? in                guard let bytes = ContactBook.picture(of: person.deviceContactId) else {                    return nil                }                let original = FileManager.default.temporaryDirectory                    .appendingPathComponent("card-\(UUID().uuidString)")                guard (try? bytes.write(to: original, options: .atomic)) != nil else { return nil }                defer { try? FileManager.default.removeItem(at: original) }                return AvatarStaging.square(atPath: original.path)            }.value            guard let staged else { continue }            defer { try? FileManager.default.removeItem(at: staged) }            _ = try? await core.call(                CottonMethod.captureAvatar,                CaptureAvatarRequest(                    personId: person.personId,                    path: staged.path,                    mime: "image/jpeg",                    filename: "contact.jpg"                ),                as: CaptureAvatarAnswer.self            )        }    }}/// What one sync did. `updated` is DELIBERATELY absent rather than reported as/// zero — the verb has no update half, and "0 updated" would read as "nothing/// had drifted", which this screen cannot know.struct ContactSyncOutcome: Equatable, Sendable {    let inserted: Int    let skipped: Int    /// The people this call MADE, paired with the card each one follows — the    /// answer's own `people` rows. The faces pass needs both halves: the id to    /// write to and the identifier to read the picture from.    let made: [(personId: String, deviceContactId: String)]    init(        inserted: Int,        skipped: Int,        made: [(personId: String, deviceContactId: String)] = []    ) {        self.inserted = inserted        self.skipped = skipped        self.made = made    }    init(_ answer: WriteAnswer) {        self.init(            inserted: ContactSyncOutcome.count(answer.answer, "inserted"),            skipped: ContactSyncOutcome.count(answer.answer, "skipped"),            made: ContactSyncOutcome.made(answer.answer)        )    }    static func == (left: ContactSyncOutcome, right: ContactSyncOutcome) -> Bool {        left.inserted == right.inserted && left.skipped == right.skipped            && left.made.map(\.personId) == right.made.map(\.personId)            && left.made.map(\.deviceContactId) == right.made.map(\.deviceContactId)    }    /// The answer's `people`, reduced to the two ids. A row missing either half    /// is dropped rather than half-used: a face with nobody to put it on is a    /// write nothing would ever read.    static func made(_ answer: JSONValue?) -> [(personId: String, deviceContactId: String)] {        guard case .object(let fields)? = answer, case .array(let rows)? = fields["people"]        else { return [] }        return rows.compactMap { row in            guard case .object(let person) = row,                case .string(let id)? = person["id"],                case .string(let card)? = person["deviceContactId"]            else { return nil }            return (personId: id, deviceContactId: card)        }    }    /// A count the answer did not carry reads as ZERO, which is the honest    /// reading: the receipt then says "everything's up to date" rather than    /// inventing a number nobody wrote.    static func count(_ answer: JSONValue?, _ key: String) -> Int {        guard case .object(let fields)? = answer, case .number(let value)? = fields[key]        else { return 0 }        return Int(value)    }}// ── The sheet ───────────────────────────────────────────────────────────────/// The import, covering the screen over the People list. It is handed only `close`,/// never a route: leaving it — the close circle, a swipe, or an import that/// landed — puts the plain People list in its place (`PeopleListFlow`), and/// the new people are on that list.struct PeopleImportSheet: View {    /// Built by `Hosted(unwired:)` from the environment's core — the view    /// holds no database of its own.    let model: PeopleImportModel    /// Back to the People list under the sheet.    let close: () -> Void    @Environment(ToastCenter.self) private var toasts    @State private var selected: Set<String> = []    @State private var query = ""    @State private var searchOpen = false    /// When this DEVICE last brought contacts in. Device-local by nature: it    /// is a fact about this phone's address book, not about the workspace, and    /// no tool carries it.    @AppStorage("people.import.lastSyncAt") private var lastSyncAt: Double = 0    /// The band's clock, read once per visit for the reason the person page's    /// is: a minute timer would re-render this screen to keep a figure honest    /// that nobody is watching.    @State private var clock = Date()    @Environment(\.cottonHaptics) private var haptics    @Environment(\.theme) private var theme    init(model: PeopleImportModel, close: @escaping () -> Void) {        self.model = model        self.close = close    }    private var eligible: [DeviceContact] { model.split.eligible }    private var isDimmed: Bool {        searchOpen && query.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty    }    /// On paper: the page's title in the serif, the checklist typed straight    /// onto the plaster — a curation list of two thousand cards is a list, not    /// two thousand sheets — with a pencil box ticked in red for each person    /// chosen, and the one verb on a slip pinned at the foot.    var body: some View {        ZStack(alignment: .top) {            PaperScreen(                title: ShellLines.line("people", "import.choose_who_to_import"),                subtitle: ShellLines.line("people", "import.only_the_people_you"),                showsBack: false,                trailing: {                    // The close circle gives way to the search pill, which is                    // centred on the row it stands in, as Back did.                    if !searchOpen {                        NavCircle(symbol: "xmark", label: ShellLines.line("people", "import.close")) { close() }                            .accessibilityIdentifier("people-import-close")                    }                }            ) {                VStack(alignment: .leading, spacing: 0) {                    // Search is the slip under the title, as on every list                    // (owner's ruling, 6 Oct 2026).                    if model.phase == .ready && !searchOpen {                        SearchSlip(placeholder: ShellLines.line("people", "import.search_contacts"), identifier: "people-import-search") {                            haptics.select()                            searchOpen = true                        }                        .padding(.bottom, RecordListSurfaceKnobs.paperGap)                    }                    // The band is shown once anyone is linked — the count is                    // the read's own, computed for exactly this.                    if model.linkedCount > 0 {                        ContactSyncBar(                            linkedCount: model.linkedCount,                            lastRunAt: lastSyncAt > 0 ? Date(timeIntervalSince1970: lastSyncAt) : nil,                            now: clock                        )                    }                    content                }                .opacity(isDimmed ? 0.4 : 1)            }            if searchOpen {                SearchPill(                    text: $query,                    placeholder: ShellLines.line("people", "import.search_contacts")                ) { searchOpen = false }                // Centred on the row the circles stood in, the notes and                // documents screens' arrangement.                .padding(.top, 6 + (ScreenBarKnobs.chromeNavCircleTarget - 40) / 2)            }        }        .safeAreaInset(edge: .bottom) {            if model.phase == .ready {                importSlip            }        }        .task {            clock = Date()            await model.start()        }        .onChange(of: model.readFailure != nil) { _, failed in            // A revoked permission rewinds the screen to the prompt, and it            // SAYS so: rewinding in silence reads as the screen breaking.            guard failed, let error = model.readFailure else { return }            toasts.show(readFailureSaid(error), tone: .error)            model.readFailureShown()        }    }    /// A failed address-book read, said rather than swallowed. The sentence is    /// this screen's own; a refusal carrying its own message shows THAT,    /// through the app's one write-failure rule.    private func readFailureSaid(_ error: Error) -> String {        guard let refusal = error as? CottonCallError,            !refusal.message.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty        else { return ShellLines.line("people", "import.couldn_t_read_your") }        return refusal.message    }    @ViewBuilder private var content: some View {        switch model.phase {        case .checking, .loading:            SkeletonPage(rows: 4)                .padding(.top, 16)        case .ask:            ObjectEmpty(                print: "people-import-ask",                line1: ShellLines.line("people", "import.bring_in_the_people"),                line2: ShellLines.line("people", "import.cotton_asks_for_contact"),                actionLabel: ShellLines.line("people", "import.allow_contact_access"),                action: { Task { await model.ask() } }            )            .padding(.top, 48)        case .denied:            ObjectEmpty(                print: "people-import-denied",                line1: ShellLines.line("people", "import.contacts_access_is_off"),                line2: ShellLines.line("people", "import.turn_on_contact_access"),                actionLabel: ShellLines.line("people", "import.open_settings"),                action: { openSettings() }            )            .padding(.top, 48)        case .ready:            // No "everyone is already in" pane. The one written here was only            // reachable on a phone with NO contacts, where its copy was a flat            // falsehood. A phone with nothing to offer draws the list, which            // states the count it has and disables the verb — the same answer,            // without the invented sentence.            checklist        }    }    private var checklist: some View {        let split = model.split        let shownEligible = ContactImport.filterContacts(split.eligible, query: query)        let shownImported = ContactImport.filterContacts(split.alreadyImported, query: query)        let allSelected = !split.eligible.isEmpty && selected.count == split.eligible.count        return LazyVStack(alignment: .leading, spacing: 0) {            HStack(alignment: .firstTextBaseline) {                Text(ShellLines.line("people", "import.selected", ["count": "\(selected.count)"]))                    .paperHand(18, ink: .ink)                Spacer()                Button {                    haptics.select()                    selected = allSelected ? [] : Set(split.eligible.map(\.id))                } label: {                    Text(allSelected ? ShellLines.line("people", "import.clear_all") : ShellLines.line("people", "import.select_all"))                        .font(CottonFonts.type(14))                        .foregroundStyle(CottonColors.accent)                }                .buttonStyle(OpacityButtonStyle())            }            .padding(.top, 14)            .padding(.bottom, 6)            ForEach(shownEligible) { contact in                ContactChecklistRow(                    contact: contact,                    selected: selected.contains(contact.id),                    alreadyImported: false                ) { selected = ContactImport.toggleSelected(selected, contact.id) }            }            if !shownImported.isEmpty {                PaperSection(title: ShellLines.line("people", "import.already_in_people"))                    .padding(.top, 24)                    .padding(.bottom, 4)                ForEach(shownImported) { contact in                    ContactChecklistRow(                        contact: contact,                        selected: false,                        alreadyImported: true                    ) {}                }            }        }    }    /// The one verb, on a slip pinned at the foot of the page.    private var importSlip: some View {        let count = selected.count        let canImport = count > 0 && !model.isImporting        return Button {            guard canImport else { return }            run()        } label: {            Paper(dye: .cream, edge: .cut, seed: "people-import-verb", tilt: false, shadow: .lifted, inset: 14) {                Text(PeopleImportSheet.verbLabel(count: count, importing: model.isImporting))                    .font(CottonFonts.type(16))                    .foregroundStyle(canImport ? CottonColors.accent : CottonColors.inkTertiary)                    .frame(maxWidth: .infinity)            }            .fixedSize(horizontal: false, vertical: true)        }        .buttonStyle(MotionButtonStyle())        .disabled(!canImport)        .cottonContentMargin()        .padding(.top, 8)        .padding(.bottom, 12)        .accessibilityIdentifier("people-import-verb")    }    /// What the slip says: what a tap would do, in the count chosen.    static func verbLabel(count: Int, importing: Bool) -> String {        if importing { return ShellLines.line("people", "import.importing") }        switch count {        case 0: return ShellLines.line("people", "import.select_people_to_import")        case 1: return ShellLines.line("people", "import.import.one")        default: return ShellLines.line("people", "import.import.many", ["count": "\(count)"])        }    }    /// One import, then OUT — the sheet's whole job is done and the People    /// list under it is where the new people are. Nothing landing keeps the    /// sheet up, with the selection intact.    ///    /// Nothing landing is a SUCCESS, not a failure: with `device_contact_id` as    /// the key, "inserted 0" means every card chosen was already a person here,    /// which is what "Everything's up to date" says. Only a refusal is an    /// error, and it says what the core said.    private func run() {        let chosen = ContactImport.selectedContacts(eligible, selected: selected)        Task {            do {                let outcome = try await model.importing(chosen)                lastSyncAt = Date().timeIntervalSince1970                clock = Date()                if outcome.inserted > 0 {                    haptics.success()                    toasts.show(outcome.inserted == 1 ? "Imported 1" : "Imported \(outcome.inserted)", tone: .success)                    selected = []                    // The faces follow the people, detached: the receipt has                    // already been shown and this sheet is about to close, so                    // a pass that took a second per portrait must not be                    // something the owner waits behind. Every face lands on a                    // person who already exists, so nothing is lost if the app                    // is put away mid-pass — the next import picks up whoever                    // is still without one.                    Task.detached { await model.bringFaces(outcome.made) }                    close()                    return                }                selected = []                toasts.show(ShellLines.line("people", "import.everything_s_up_to"), tone: .success)            } catch {                toasts.show(CottonStrings.writeFailure(error), tone: .error)            }        }    }    private func openSettings() {        guard let url = URL(string: UIApplication.openSettingsURLString) else { return }        UIApplication.shared.open(url)    }}// ── One row of the checklist ────────────────────────────────────────────────/// Tick box · name · phone/org snippet · "in People", handwritten.////// An already-imported row is SHOWN and inert: import is idempotent, and hiding/// the people who are already in would leave somebody scrolling a list looking/// for a name that is deliberately missing.////// Typed straight onto the page rather than onto a strip each: a curation list/// of two thousand cards is a checklist, and two thousand sheets would be the/// slab again in paper. The box is drawn in pencil and ticked in red, the/// event page's mark for the choice you made.struct ContactChecklistRow: View {    let contact: DeviceContact    let selected: Bool    let alreadyImported: Bool    let onToggle: () -> Void    @Environment(\.theme) private var theme    private var snippet: String? {        let parts = [contact.phones.first, contact.org].compactMap { $0 }        return parts.isEmpty ? nil : parts.joined(separator: " \u{00B7} ")    }    var body: some View {        Button(action: alreadyImported ? {} : onToggle) {            HStack(spacing: 14) {                tickBox                VStack(alignment: .leading, spacing: 3) {                    Text(contact.fullName)                        .paperBody(15)                        .lineLimit(1)                    if let snippet {                        Text(snippet)                            .paperBody(12, ink: .pencil)                            .lineLimit(1)                    }                }                .frame(maxWidth: .infinity, alignment: .leading)                if alreadyImported {                    Text(ShellLines.line("people", "import.in_people"))                        .paperHand(14)                }            }            .padding(.vertical, 11)            .contentShape(Rectangle())            .opacity(alreadyImported ? 0.6 : 1)        }        .buttonStyle(MotionButtonStyle())        .disabled(alreadyImported)        .accessibilityLabel(contact.fullName)        .accessibilityAddTraits(selected ? [.isSelected] : [])    }    private var tickBox: some View {        ZStack {            RoundedRectangle(cornerRadius: 3, style: .continuous)                .stroke(theme.print(.pencil), lineWidth: 1.2)                .frame(width: 20, height: 20)            if selected || alreadyImported {                HandTick(theme: theme)                    .stroke(                        theme.print(alreadyImported ? .pencil : .red),                        style: StrokeStyle(lineWidth: 1.8, lineCap: .round, lineJoin: .round)                    )                    .frame(width: 20, height: 16)                    .offset(x: 2, y: -3)            }        }        .frame(width: 26, height: 26)        .accessibilityHidden(true)    }}// ── The band above the list ─────────────────────────────────────────────────/// How many people follow the iPhone address book, and when this phone last/// checked. Shown once anyone is linked at all.////// A third thing would belong here — the loud verb "Sync now", which/// re-reads the linked cards and PATCHES the people who follow them. There is/// no verb for that half (see the file header's gap), so this band states the/// two facts it can and offers nothing it cannot do. A button that did half of/// a sync would be worse than no button.struct ContactSyncBar: View {    let linkedCount: Int    /// When this device last finished bringing contacts in, or nothing.    let lastRunAt: Date?    let now: Date    var body: some View {        VStack(alignment: .leading, spacing: 3) {            Text(ShellLines.line("people", "import.linked", ["count": "\(linkedCount.formatted(.number.grouping(.automatic)))"]))                .paperBody(13)            Text(when)                .paperBody(12, ink: .pencil)        }        .padding(.top, 4)        .frame(maxWidth: .infinity, alignment: .leading)    }    /// The app's ONE relative-age rule rather than a second spelling of "ago"    /// invented for this band.    private var when: String {        guard let lastRunAt else { return ShellLines.line("people", "import.never_synced") }        return ShellLines.line("people", "import.last_synced", ["when": "\(DateFormats.recordDateLabel(lastRunAt, now: now))"])    }}