Cotton code
875 lines · 43.7 KB · SwiftRaw
// YOU, GROUPED, in the Warm look (assets/design/chat/you-grouped.html, the// owner's review of 22 Nov 2026; CONTRACT.md "You, grouped"), as Android's// YouTop: your picture, name and number as others see them (a card that// opens Profile), then the seven rows `chat.you` answers (Sync, Your Claude,// Privacy, Notifications, Storage, Help and feedback, About), each saying in// the core's words how it stands, each opening its own page with Back and// no place switch under it. The pages are in ChatYouPages.swift; this file// holds what they share: who you are (`chat.profile`, set with// `chat.profile.set`), the account (`shell.account`), `chat.you`, the// blocked people (`chat.blocked`) and the shared settings (`shell.settings`).#if os(iOS)import CottonKitimport PhotosUIimport SwiftUIimport UserNotifications/// The pages You's rows open, by `chat.you`'s row ids.enum ChatYouPage: String, CaseIterable {    case profile, look, export, sync, claude, privacy, notifications, blocked, storage, help, about}/// `chat.you`'s answer: the seven rows, the Sync page, the chats muted now.struct ChatYouAnswer: Decodable, Equatable, Sendable {    struct Row: Codable, Equatable, Sendable {        let id: String        let label: String        var line: String?        /// The Mail row's way to Cotton Post (COMMS WITHOUT MAIL): its address on this phone, what the row says when        /// Post is not here, and its store page once listed.        var post: PostWay?    }    struct PostWay: Codable, Equatable, Sendable {        struct IOS: Codable, Equatable, Sendable { let live: String; let dev: String }        let ios: IOS        let absent: String        var store: String?        /// Post's address for this build's kind, when Post is on the phone.        @MainActor var here: URL? {            guard let url = URL(string: AppFlavourDev.isDev ? ios.dev : ios.live), UIApplication.shared.canOpenURL(url) else { return nil }            return url        }        /// Whether Cotton Post (or Post Dev, by this build's kind) is on this phone, told to `chat.you`.        @MainActor static var onPhone: Bool {            URL(string: AppFlavourDev.isDev ? "cottonmaildev://" : "cottonmail://").map(UIApplication.shared.canOpenURL) ?? false        }    }    struct Sync: Codable, Equatable, Sendable {        let title: String        var last: String?        var trouble: Bool?        /// Changes that cannot be sent, with Send again and Let go (UNSENT HEAL, `sync.stuck`); absent when none.        var stuck: Stuck?    }    struct Stuck: Codable, Equatable, Sendable {        let title: String        var detail: String?        var acts: [StuckAct]?        /// Changes the person can act on (Send again, Let go); without acts, only changes kept on this phone are said.        var acting: Bool { !(acts ?? []).isEmpty }        /// Called once the page has shown the count of changes kept only on this phone (`sync.kept.seen`).        var seen: StuckSeen?    }    struct StuckSeen: Codable, Equatable, Sendable {        let method: String        var request: JSONValue?    }    struct StuckAct: Codable, Equatable, Sendable, Identifiable {        let id: String        let label: String        let method: String        /// The changes the screen showed (`ids`): the core refuses the act if what is stuck has changed since.        var request: JSONValue?        var tone: String?        var confirm: StuckConfirm?    }    struct StuckConfirm: Codable, Equatable, Sendable {        let title: String        let body: String        let yes: String        let no: String    }    struct Muted: Decodable, Equatable, Sendable {        let thread: String        let name: String        var picture: ChatAvatar?        let until: String    }    let rows: [Row]    var sync: Sync?    var muted: [Muted]?}/// You's rows and Sync page as this phone last read them, drawn on the first frame: every row stands at once and/// `chat.you` fills its values in place (owner, build 24: the card came first and the rows a second or two later)./// The muted chats are left out; their page waits for the read.enum ChatYouRows {    private struct Held: Codable { let rows: [ChatYouAnswer.Row]; var sync: ChatYouAnswer.Sync? }    private static let key = "chat.you.rows"    static func read() -> ChatYouAnswer? {        guard let data = UserDefaults.standard.data(forKey: key), let held = try? JSONDecoder().decode(Held.self, from: data) else { return nil }        return ChatYouAnswer(rows: held.rows, sync: held.sync, muted: nil)    }    static func keep(_ read: ChatYouAnswer) {        guard let data = try? JSONEncoder().encode(Held(rows: read.rows, sync: read.sync)) else { return }        UserDefaults.standard.set(data, forKey: key)    }    static func forget() { UserDefaults.standard.removeObject(forKey: key) }    private struct Ask: Encodable, Sendable {        let notifications: Bool?        /// Whether Cotton Post is on this phone: only then, or when it is not, does You carry its Mail row.        let post: Bool?    }    /// Read once, a moment after Comms opens, when this phone has no rows remembered yet (a fresh install or    /// update): the first You opened is drawn whole too.    static func warm(_ core: (any CottonCalling)?) async {        guard let core, read() == nil else { return }        try? await Task.sleep(for: .seconds(3))        guard read() == nil else { return }        let notifies = await SystemCapabilityAuthority().status(.notifications) == .authorized        let post = await ChatYouAnswer.PostWay.onPhone        if let rows = try? await core.call(ChatYouMethod.you, Ask(notifications: notifies, post: post), as: ChatYouAnswer.self) { keep(rows) }    }}/// A page of You stands: the floating place switch steps away (a page has Back instead).struct ChatYouPageUp: PreferenceKey {    static let defaultValue = false    static func reduce(value: inout Bool, nextValue: () -> Bool) { value = value || nextValue() }}struct ChatYouScreen: View {    private var deleteLook: SettingsLook { .warm(look) }    let core: any CottonCalling    /// A muted chat tapped on Notifications: opened as in the list.    let openChat: (String) -> Void    @Environment(\.chatLook) private var look    @Environment(\.cottonChat) private var chat    @Environment(\.openURL) private var openURL    @Environment(\.nativeKeptFlow) private var nativeFlow    @Environment(\.rekeyThisDevice) private var rekey    @Environment(\.cottonSync) private var sync    @Environment(ToastCenter.self) private var toasts: ToastCenter?    @State private var page: ChatYouPage?    /// Your Claude opened from Privacy: Back returns there.    @State private var claudeFrom: ChatYouPage?    @State private var answer: AccountAnswer?    @State private var you: ChatYouAnswer?    @State private var settings: SettingsAnswer?    @State private var profile: ChatProfileAnswer?    /// Your name and number as this phone last read them, while `chat.profile` cannot be read.    @State private var remembered: ChatYouRemembered.Held?    @State private var picture: UIImage?    @State private var name: String    @State private var receipts = false    @State private var typing = false    /// This phone fetches a link's card as he writes it (`chat.settings` linkPreviews, FEEDBACK-4 B4): on until turned off.    @State private var linkPreviews = true    /// Whether the app's chats signal at all (`chat.settings`' `offered`): where not, no switch is drawn.    @State private var signals = false    @State private var notifying: Bool?    @State private var blocked: ChatBlockedAnswer?    @State private var showingBlocked = false    /// Your Circle (CONTACTS-ANSWERS 9), opened from Privacy.    @State private var showingCircle = false    @State private var choosingPicture = false    @State private var library = false    @State private var item: PhotosPickerItem?    @State private var asked = 0    /// Let go, waiting for its confirm (UNSENT HEAL).    @State private var lettingGo: ChatYouAnswer.StuckAct?    @FocusState private var naming: Bool    private struct Ask: Encodable, Sendable { let commit: String }    private struct YouAsk: Encodable, Sendable {        let notifications: Bool?        let post: Bool?    }    /// `known`: your name and number as this phone already holds them (the    /// last profile read, else who is signed in), drawn on the first frame:    /// a signed-in phone never shows an empty profile while `chat.profile`    /// is out (owner's iPhone, Comms build 19).    init(core: any CottonCalling, known: ChatYouRemembered.Held?, openChat: @escaping (String) -> Void = { _ in }) {        self.core = core        self.openChat = openChat        _remembered = State(initialValue: known)        _name = State(initialValue: known?.name ?? "")        _you = State(initialValue: ChatYouRows.read())        #if COTTON_DEV        // A tap on the home's sync line opens You on its Sync page.        _page = State(initialValue: SyncSeenOpens.take() ? .sync : ChatWarmSeed.asked ? ChatWarmSeed.youPage.flatMap(ChatYouPage.init(rawValue:)) : nil)        #endif    }    var body: some View {        Group {            switch page {            case nil: top            case .profile?: profilePage            case .look?: ChatYouLookPage(core: core, back: back)            case .export?: ChatYouExportPage(core: core, back: back)            // Blocked, the place a blocked sender's texts wait (ChatBlocked.swift): its row's count is read again on Back.            case .blocked?: ChatBlockedPage(back: { asked += 1; back() })            case .sync?: syncPage            case .claude?:                ChatYouClaudePage(core: core) { page = claudeFrom; claudeFrom = nil; asked += 1 }            case .privacy?: privacyPage            case .notifications?: notificationsPage            case .storage?:                ChatYouStoragePage(core: core, storage: settings?.storage, said: { toasts?.show($0) }, again: { asked += 1 }, back: back)            case .help?:                ChatYouHelpPage(core: core, help: settings?.help, said: { toasts?.show($0, tone: .error) }, back: back)            case .about?:                ChatYouAboutPage(about: settings?.about, said: { toasts?.show($0) }, back: back)            }        }        .preference(key: ChatYouPageUp.self, value: page != nil)        .background(look.colours.ground.ignoresSafeArea())        .task(id: "\(sync?.revision ?? 0)-\(asked)") { await read() }        // The home's sync line was tapped while You stood: its Sync page.        .onReceive(NotificationCenter.default.publisher(for: SyncSeenOpens.notice)) { _ in page = .sync }        .onAppear {            receipts = chat?.readReceipts ?? false            typing = chat?.sendsTyping ?? false        }        .lookPanel(isPresented: $showingBlocked, style: look.panel, name: ChatWords.line("you.blocked_people")) { blockedSheet }        .sheet(isPresented: $showingCircle) {            NavigationStack {                CircleListView(core: core)                    .toolbar { ToolbarItem(placement: .cancellationAction) { Button { showingCircle = false } label: { Image(systemName: "xmark") }.accessibilityIdentifier("circle-close") } }            }        }        .lookAsk(isPresented: $choosingPicture, style: look.panel, font: look.font(17, .semibold), messageColour: look.colours.text,                 choices: pictureChoices, name: ChatWords.line("you.picture"))        .photosPicker(isPresented: $library, selection: $item, matching: .images)        .onChange(of: item) { _, chosen in            guard let chosen else { return }            item = nil            Task {                guard let staged = await MediaStaging.stage(chosen) else {                    toasts?.show(DockModel.pictureRefused, tone: .error)                    return                }                await setPicture(staged.url, mime: staged.mime)            }        }    }    private func back() { page = nil }    // MARK: the top level    private var top: some View {        ScrollView {            VStack(alignment: .leading, spacing: 0) {                Text(verbatim: ChatWords.line("you.title"))                    .font(look.font(34, .bold))                    .kerning(-0.7)                    .foregroundStyle(look.colours.text)                    .accessibilityAddTraits(.isHeader)                    .padding(.top, 10)                    .padding(.bottom, 4)                card                    .padding(.bottom, 6)                // Comms' own row, right after the card (shared/DECISIONS.md "Look").                if let look = LookModel.standing("messages").answer {                    ChatYouGoRow(symbol: "paintpalette", name: look.word("title"), line: look.line, id: "you-row-look") { page = .look }                    Spacer().frame(height: 14)                }                // A row this phone has no page for yet is not drawn, so it never draws a dead row.                ForEach((you?.rows ?? []).filter { ChatYouPage(rawValue: $0.id) != nil || $0.post != nil }, id: \.id) { row in                    if let post = row.post {                        postRow(row, post)                    } else {                        ChatYouGoRow(symbol: Self.symbol(row.id), name: row.label, line: row.line, id: "you-row-\(row.id)") {                            if let opened = ChatYouPage(rawValue: row.id) { page = opened }                        }                    }                    // After these the drawing leaves a gap: Comms' own rows (Export, then Mail pointing to Post), what you keep, how it                    // behaves, help.                    if row.id == "post" || row.id == "claude" || row.id == "storage" { Spacer().frame(height: 14) }                }            }            .padding(.horizontal, Warm.side)            .padding(.bottom, Warm.footRoom)        }        .scrollIndicators(.hidden)        .accessibilityIdentifier("you")    }    /// The Mail row: Cotton Post opens when it is on the phone; else the row says Post is not here, and offers its store    /// page only once Post is listed (the coordinator, 27 Nov 2026).    @ViewBuilder private func postRow(_ row: ChatYouAnswer.Row, _ post: ChatYouAnswer.PostWay) -> some View {        if let here = post.here {            ChatYouGoRow(symbol: Self.symbol(row.id), name: row.label, line: row.line, id: "you-row-post") { UIApplication.shared.open(here) }        } else if let store = post.store.flatMap(URL.init(string:)) {            ChatYouGoRow(symbol: Self.symbol(row.id), name: row.label, line: post.absent, id: "you-row-post") { UIApplication.shared.open(store) }        } else {            ChatYouStillRow(symbol: Self.symbol(row.id), name: row.label, line: post.absent, id: "you-row-post")        }    }    /// Each row's mark.    static func symbol(_ id: String) -> String {        switch id {        case "export": "square.and.arrow.up"        case "post": "envelope"        case "blocked": "nosign"        case "sync": "arrow.triangle.2.circlepath"        case "claude": "sparkle"        case "privacy": "lock"        case "notifications": "bell"        case "storage": "internaldrive"        case "help": "questionmark.circle"        default: "info.circle"        }    }    private var number: String? { profile?.number ?? remembered?.number }    /// Your picture, name and number, as the people you write to see them: it opens Profile.    private var card: some View {        Button { page = .profile } label: {            HStack(spacing: 14) {                face(64)                VStack(alignment: .leading, spacing: 2) {                    Text(verbatim: name).font(look.font(20, .bold)).kerning(-0.2).foregroundStyle(look.colours.text)                    if let number, number != name {                        Text(verbatim: number).font(look.font(14)).foregroundStyle(look.colours.dim)                    }                }                .frame(maxWidth: .infinity, alignment: .leading)                Image(systemName: "chevron.right")                    .font(.system(size: 14 * min(look.scale, 1.3), weight: .semibold))                    .foregroundStyle(look.colours.faint)                    .accessibilityHidden(true)            }            .padding(.leading, 14).padding(.trailing, 16).padding(.vertical, 14)            .frame(maxWidth: .infinity, alignment: .leading)            .background(RoundedRectangle(cornerRadius: 24, style: .continuous).fill(look.colours.bar))            .contentShape(Rectangle())        }        .buttonStyle(.plain)        .accessibilityElement(children: .ignore)        .accessibilityLabel(Text(verbatim: [name, number].compactMap { $0 }.filter { !$0.isEmpty }.joined(separator: ", ")))        .accessibilityAddTraits(.isButton)        .accessibilityIdentifier("you-card")    }    private func face(_ side: CGFloat) -> some View {        Group {            if let picture {                Image(uiImage: picture).resizable().scaledToFill()                    .frame(width: side * min(look.scale, 1.3), height: side * min(look.scale, 1.3))                    .clipShape(Circle())            } else {                ChatAvatarView(avatar: ChatAvatar(photo: nil, initials: initials, tint: 0), side: side * min(look.scale, 1.3))            }        }        .accessibilityHidden(true)    }    // MARK: Profile    /// YOUR PROFILE: the picture with Change picture, the name others see, the    /// number you sign in with, whether people with it find you, and Sign out    /// at the foot with what coming back takes.    private var profilePage: some View {        ChatYouPageFrame(title: nil, id: "you-profile-page", back: back) {            VStack(spacing: 10) {                face(96)                WarmPill(words: ChatWords.line(profile?.picture?.path != nil ? "you.picture" : "you.picture_add"), id: "you-picture") {                    choosingPicture = true                }            }            .frame(maxWidth: .infinity)            .padding(.vertical, 8)            VStack(alignment: .leading, spacing: 3) {                ChatYouSmall(words: ChatWords.line("you.name"))                TextField(text: $name) {                    // The hint asks for a name only once the profile is read: a                    // profile not read yet is not an empty one.                    Text(verbatim: profile == nil ? "" : ChatWords.line("you.name_hint")).foregroundStyle(look.colours.faint)                }                .font(look.font(17, .medium))                .foregroundStyle(look.colours.text)                .focused($naming)                .submitLabel(.done)                .onSubmit { Task { await setName() } }                .accessibilityLabel(Text(verbatim: ChatWords.line("you.name")))                .accessibilityIdentifier("you-name")                ChatYouQuiet(words: ChatWords.line("you.name_line"))            }            .padding(.vertical, 8)            if let number {                VStack(alignment: .leading, spacing: 3) {                    ChatYouSmall(words: ChatWords.line("you.number"))                    Text(verbatim: number).font(look.font(17, .medium)).foregroundStyle(look.colours.text)                    ChatYouQuiet(words: ChatWords.line("you.number_line"))                }                .frame(maxWidth: .infinity, alignment: .leading)                .padding(.vertical, 8)            }            // Signed in, Sign out; on a phone signed out (Chat Dev's seed), the way in.            if let act = answer?.actions.first(where: { $0.id == "account_sign_out" }) ?? answer?.actions.first(where: { $0.id == ChatYouRemembered.signIn }) {                let out = act.id == "account_sign_out"                ChatYouFootButton(words: act.label, id: out ? "you-sign-out" : "you-sign-in", main: !out, danger: out) {                    Task {                        await run(act)                        page = nil                    }                }                .padding(.top, 26)                if out {                    ChatYouQuiet(words: ChatWords.line("you.sign_out_line"))                        .multilineTextAlignment(.center)                        .frame(maxWidth: .infinity)                        .padding(.top, 8)                        .accessibilityIdentifier("you-sign-out-line")                }            }            // Delete account, last while signed in (DELETE_ACCOUNT.md; every Cotton app, as the App Store asks).            DeleteAccountPart(core: core, look: deleteLook, onDeleted: { page = nil })        }        // The app's one keyboard rule (Chrome/KeyboardDismissal.swift): a drag        // down or a tap outside the name puts the keyboard away. Worn here, not        // at Chat's root, whose UIKit tables lose their row taps under its tap.        .cottonScreenFrame()    }    private var pictureChoices: [LookChoice] {        let has = profile?.picture?.path != nil        var choices = [LookChoice(id: "choose", label: ChatWords.line(has ? "you.picture" : "you.picture_add"), colour: look.colours.text) { library = true }]        if has {            choices.append(LookChoice(id: "remove", label: ChatWords.line("you.picture_drop"), colour: look.colours.danger) {                Task { await setPicture(nil, mime: nil) }            })        }        return choices    }    private var initials: String {        let words = name.split(separator: " ")        let picked = words.count > 1 ? [words.first!, words.last!] : Array(words.prefix(1))        return picked.compactMap { $0.first.map(String.init) }.joined().uppercased()    }    // MARK: Sync    /// SYNC: signed in means syncing, so the page is how it stands: the state,    /// when it last synced while the state says something else, the    /// out-of-reach line, and Sync now.    private var syncPage: some View {        syncPageBody            // An alert, not a confirmation dialog: iOS draws a dialog's cancel button nowhere on a phone, and the core's            // "Keep them" must be there to tap (the walk on dev, 26 Nov 2026).            .alert(lettingGo?.confirm?.title ?? "", isPresented: Binding(get: { lettingGo != nil }, set: { if !$0 { lettingGo = nil } }), presenting: lettingGo) { act in                Button(act.confirm?.yes ?? act.label, role: .destructive) {                    Task { _ = try? await core.callJSON(act.method, act.request ?? .object([:])); lettingGo = nil; asked += 1 }                }                Button(act.confirm?.no ?? "", role: .cancel) { lettingGo = nil }            } message: { act in                Text(verbatim: act.confirm?.body ?? "")            }    }    private var syncPageBody: some View {        ChatYouPageFrame(title: ChatWords.line("you.rows.sync"), id: "you-sync-page", back: back) {            if let state = you?.sync {                VStack(alignment: .leading, spacing: 4) {                    // Said once (coordinator, 26 Nov 2026): while anything is stuck the line takes the stuck title                    // ("2 changes can't be sent"), and the block under it says only why and what to do.                    Text(verbatim: state.stuck.flatMap { $0.acting ? $0.title : nil } ?? state.title)                        .font(look.font(26, .bold)).kerning(-0.3)                        .foregroundStyle(look.colours.text)                        .fixedSize(horizontal: false, vertical: true)                        .accessibilityIdentifier("you-sync-state")                    if let last = state.last {                        ChatYouQuiet(words: last).accessibilityIdentifier("you-sync-last")                    }                }                .padding(.top, 6)                .padding(.bottom, 4)                if state.trouble == true {                    ChatYouBlock(tint: true) {                        Text(verbatim: ChatWords.line("you.unreachable"))                            .font(look.font(15)).foregroundStyle(look.colours.bubbleOutText)                            .fixedSize(horizontal: false, vertical: true)                    }                    .accessibilityElement(children: .combine)                    .accessibilityIdentifier("you-sync-unreachable")                }                // UNSENT HEAL (26 Nov 2026): changes that cannot be sent, said with Send again and Let go.                if let stuck = state.stuck {                    // With acts the title is the line above; with none (changes kept only here) it is the block.                    if let detail = stuck.acting ? stuck.detail : stuck.title {                        ChatYouBlock(tint: true) {                            Text(verbatim: detail)                                .font(look.font(15)).foregroundStyle(look.colours.bubbleOutText)                                .fixedSize(horizontal: false, vertical: true)                        }                        .accessibilityElement(children: .combine)                        .accessibilityIdentifier("you-sync-stuck")                        // Shown once: the kept count is said until this page has drawn it (the page keeps it while open).                        .task(id: stuck.seen) {                            if let seen = stuck.seen { _ = try? await core.callJSON(seen.method, seen.request ?? .object([:])) }                        }                    }                    ForEach(stuck.acts ?? []) { act in                        ChatYouFootButton(words: act.label, id: "you-sync-stuck-\(act.id)", main: act.id == "again", danger: act.tone == "danger") {                            if act.confirm != nil {                                lettingGo = act                            } else {                                Task { _ = try? await core.callJSON(act.method, act.request ?? .object([:])); asked += 1 }                            }                        }                        .padding(.top, 10)                    }                }            }            if let act = answer?.actions.first(where: { $0.id == "account_back_up" }) {                // While something is stuck, Send again is the one filled button and Sync now the plain one.                ChatYouFootButton(words: act.label, id: "you-sync-now", main: you?.sync?.stuck?.acting != true) { Task { await run(act) } }                    .padding(.top, 18)            }        }    }    // MARK: Privacy    /// PRIVACY: the people you blocked (each with Unblock), what others see    /// (read receipts and typing, where the chats signal; never last seen),    /// what a safety number is for, and the way to Your Claude.    private var privacyPage: some View {        ChatYouPageFrame(title: ChatWords.line("you.rows.privacy"), id: "you-privacy-page", back: back) {            // Your Circle: the people he and they both accepted, in the Circle's own words.            ChatYouGoRow(symbol: "person.2.circle", name: ShellLines.line("circle", "title"), line: ShellLines.line("circle", "intro"), id: "you-circle") {                showingCircle = true            }            Button { showingBlocked = true } label: {                HStack(alignment: .firstTextBaseline) {                    Text(verbatim: ChatWords.line("you.blocked_people")).font(look.font(16)).foregroundStyle(look.colours.text)                    Spacer(minLength: 12)                    Text(verbatim: (blocked?.people.count).flatMap { $0 > 0 ? String($0) : nil } ?? ChatWords.line("you.nobody"))                        .font(look.font(15)).foregroundStyle(look.colours.dim)                    Image(systemName: "chevron.right")                        .font(.system(size: 13 * min(look.scale, 1.3), weight: .semibold))                        .foregroundStyle(look.colours.faint)                        .accessibilityHidden(true)                }                .frame(maxWidth: .infinity, minHeight: 48)                .contentShape(Rectangle())            }            .buttonStyle(.plain)            .accessibilityIdentifier("you-blocked")            .padding(.top, 6)            WarmHeading(words: ChatWords.line("you.seen_by_others"))            if signals {                ChatYouSwitch(words: ChatWords.line("you.read_receipts"), line: ChatWords.line("you.read_receipts_line"), on: $receipts, id: "you-read-receipts") { on in                    Task { try? await chat?.set(readReceipts: on, typing: nil); asked += 1 }                }                ChatYouSwitch(words: ChatWords.line("you.typing"), line: ChatWords.line("you.typing_line"), on: $typing, id: "you-typing") { on in                    Task { try? await chat?.set(readReceipts: nil, typing: on) }                }            }            ChatYouQuiet(words: ChatWords.line("you.last_seen")).padding(.vertical, 4).accessibilityIdentifier("you-last-seen")            // This phone's own, like Read receipts: the phone that fetches is the one that asks.            ChatYouSwitch(words: ChatWords.line("you.link_previews"), line: ChatWords.line("you.link_previews_line"), on: $linkPreviews,                          id: "you-link-previews") { on in                Task { _ = try? await core.callJSON(ChatYouMethod.settings, ChatYouLinkPreviews(linkPreviews: on)); asked += 1 }            }            WarmHeading(words: ChatWords.line("you.safety"))            Text(verbatim: ChatWords.line("you.safety_line"))                .font(look.font(15)).foregroundStyle(look.colours.text)                .fixedSize(horizontal: false, vertical: true)                .accessibilityIdentifier("you-safety-line")            ChatYouGoRow(symbol: Self.symbol("claude"), name: ChatWords.line("you.rows.claude"), line: ChatWords.line("you.claude_line"), id: "you-privacy-claude") {                claudeFrom = .privacy                page = .claude            }            .padding(.top, 14)        }    }    /// Who you blocked, latest first, each with Unblock.    private var blockedSheet: some View {        VStack(alignment: .leading, spacing: 4) {            Text(verbatim: ChatWords.line("you.blocked_people"))                .font(look.font(20, .bold)).foregroundStyle(look.colours.text)                .padding(.bottom, 6)                .accessibilityAddTraits(.isHeader)            if (blocked?.people ?? []).isEmpty {                Text(verbatim: ChatWords.line("you.nobody")).font(look.font(15)).foregroundStyle(look.colours.dim)            }            ForEach(blocked?.people ?? []) { person in                HStack(spacing: 12) {                    VStack(alignment: .leading, spacing: 2) {                        Text(verbatim: person.name ?? person.number).font(look.font(16)).foregroundStyle(look.colours.text)                        if person.name != nil { Text(verbatim: person.number).font(look.font(13)).foregroundStyle(look.colours.dim) }                    }                    Spacer(minLength: 8)                    WarmPill(words: ChatWords.line("you.unblock"), id: "you-unblock-\(person.number)") { unblock(person.number) }                }                .frame(minHeight: 52)            }        }        .padding(.horizontal, Warm.side)        .padding(.vertical, 18)        .accessibilityElement(children: .contain)        .accessibilityIdentifier("you-blocked-sheet")    }    // MARK: Notifications    /// NOTIFICATIONS: what Comms tells, the phone's own settings for how it    /// tells (On or Off), and every chat muted now with until when.    private var notificationsPage: some View {        ChatYouPageFrame(title: ChatWords.line("you.rows.notifications"), id: "you-notifications-page", back: back) {            ChatYouQuiet(words: ChatWords.line("you.notifications_line")).padding(.top, 4)            Button {                if let url = URL(string: UIApplication.openNotificationSettingsURLString) { openURL(url) }            } label: {                HStack(spacing: 10) {                    VStack(alignment: .leading, spacing: 2) {                        Text(verbatim: ChatWords.line("you.notifications_phone")).font(look.font(16, .medium)).foregroundStyle(look.colours.text)                        Text(verbatim: ChatWords.line("you.notifications_phone_line")).font(look.font(13)).foregroundStyle(look.colours.dim)                            .fixedSize(horizontal: false, vertical: true)                    }                    .frame(maxWidth: .infinity, alignment: .leading)                    if let notifying {                        Text(verbatim: ChatWords.line(notifying ? "you.glance.notifications_on" : "you.glance.notifications_off"))                            .font(look.font(15)).foregroundStyle(look.colours.dim)                            .accessibilityIdentifier("you-notifications-state")                    }                    Image(systemName: "chevron.right")                        .font(.system(size: 13 * min(look.scale, 1.3), weight: .semibold))                        .foregroundStyle(look.colours.faint)                        .accessibilityHidden(true)                }                .frame(maxWidth: .infinity, minHeight: 56)                .contentShape(Rectangle())            }            .buttonStyle(.plain)            .accessibilityIdentifier("you-notifications-phone")            WarmHeading(words: ChatWords.line("you.muted"))            let muted = you?.muted ?? []            if muted.isEmpty {                ChatYouQuiet(words: ChatWords.line("you.muted_none")).accessibilityIdentifier("you-muted-none")            }            ForEach(muted, id: \.thread) { one in                Button { openChat(one.thread) } label: {                    HStack(spacing: 12) {                        ChatAvatarView(avatar: one.picture ?? ChatAvatar(photo: nil, initials: String(one.name.prefix(1)), tint: 0), side: 34 * min(look.scale, 1.3))                            .accessibilityHidden(true)                        VStack(alignment: .leading, spacing: 2) {                            Text(verbatim: one.name).font(look.font(16, .medium)).foregroundStyle(look.colours.text)                            Text(verbatim: one.until).font(look.font(13)).foregroundStyle(look.colours.dim)                        }                        .frame(maxWidth: .infinity, alignment: .leading)                    }                    .frame(minHeight: 52)                    .contentShape(Rectangle())                }                .buttonStyle(.plain)                .accessibilityIdentifier("you-muted-\(one.thread)")            }            ChatYouQuiet(words: ChatWords.line("you.muted_how")).padding(.top, 6)        }    }    // MARK: reading and acting    private func read() async {        let ask = Ask(commit: SettingsAnswer.commit)        let core = core        // Whether the phone lets Comms notify at all: only the phone knows, so it is handed to `chat.you`.        let notifies = await SystemCapabilityAuthority().status(.notifications) == .authorized        notifying = notifies        // The profile asks the server (whether you can be found): it is asked        // beside the account, never after it, and until it answers You shows        // who it already knew.        async let account = try? core.call(CottonMethod.shellAccount, ask, as: AccountAnswer.self)        async let asked = try? core.call(ChatPeopleMethod.profile, EmptyRequest(), as: ChatProfileAnswer.self)        async let rows = Self.rows(core, notifies: notifies)        // The pages' parts (Storage, Help, About) are read beside the rest, never after it.        async let pages = SettingsAnswer.read(core)        async let blocking = try? core.call(ChatPeopleMethod.blocked, EmptyRequest(), as: ChatBlockedAnswer.self)        // The rows are this phone's own and land first; they never wait on the profile, which asks the server.        // A read that is refused leaves what stands: the rows never blink away during a sync.        if let read = await rows {            you = read            ChatYouRows.keep(read)        }        answer = await account        // Signed out, nobody is remembered (before a profile is kept: the seed's        // invented profile answers on a phone that is signed out).        if answer?.actions.contains(where: { $0.id == ChatYouRemembered.signIn }) == true { ChatYouRemembered.forget() }        if let read = await asked {            show(read)        } else if profile == nil {            // The profile cannot be read now (a copy being made again, a connect            // in flight: `not_connected`): You keeps who you were last seen as.            remembered = ChatYouRemembered.read() ?? remembered            if !naming, name.isEmpty { name = remembered?.name ?? "" }        }        if let read = try? await core.callJSON(ChatYouMethod.settings) {            signals = read.flag("offered")            receipts = read.flag("readReceipts")            typing = read.flag("typing")            linkPreviews = read["linkPreviews"]?.bool ?? true        }        if let read = await blocking { blocked = read }        if let read = await pages { settings = read }    }    private static func rows(_ core: any CottonCalling, notifies: Bool) async -> ChatYouAnswer? {        await SettingsRemembered.heldBack()        let post = await ChatYouAnswer.PostWay.onPhone        return try? await core.call(ChatYouMethod.you, YouAsk(notifications: notifies, post: post), as: ChatYouAnswer.self)    }    private func show(_ read: ChatProfileAnswer) {        profile = read        ChatYouRemembered.keep(read)        if !naming { name = read.name ?? answer?.card.title ?? "" }        if let path = read.picture?.path {            Task { picture = await ChatPictures.shared.image(URL(fileURLWithPath: path), side: 200) }        } else {            picture = nil        }    }    private func setName() async {        let named = name.trimmingCharacters(in: .whitespacesAndNewlines)        do {            show(try await core.call(ChatPeopleMethod.profileSet, ["name": named.isEmpty ? nil : named], as: ChatProfileAnswer.self))        } catch {            toasts?.show(ActionRefused.words(for: error), tone: .error)        }    }    /// A picture for the people you write to; nil takes it away.    private func setPicture(_ picked: URL?, mime: String?) async {        defer { if let picked { try? FileManager.default.removeItem(at: picked) } }        struct SetPicture: Encodable { var picture: String?; var mime: String?            func encode(to encoder: Encoder) throws {                var c = encoder.container(keyedBy: CodingKeys.self)                try c.encode(picture, forKey: .picture)   // null takes it away                try c.encodeIfPresent(mime, forKey: .mime)            }            enum CodingKeys: String, CodingKey { case picture, mime }        }        var path = picked?.path(percentEncoded: false)        if let picked, let square = AvatarStaging.square(atPath: picked.path(percentEncoded: false)) { path = square.path(percentEncoded: false) }        do {            show(try await core.call(ChatPeopleMethod.profileSet, SetPicture(picture: path, mime: path == nil ? nil : "image/jpeg"), as: ChatProfileAnswer.self))        } catch {            toasts?.show(ActionRefused.words(for: error), tone: .error)        }    }    private func unblock(_ number: String) {        Task {            _ = try? await core.callJSON(ChatPeopleMethod.unblock, ["number": number])            blocked = try? await core.call(ChatPeopleMethod.blocked, EmptyRequest(), as: ChatBlockedAnswer.self)            asked += 1        }    }    private func run(_ act: CardAction) async {        do {            switch try await DeckActs.ran(act, core: core) {            case .opens(let page): openURL(page)            case .platform(let effect): await RecordPlatformEffects.perform(effect, nativeFlow: nativeFlow, rekey: rekey)            case .said(let words), .receipt(let words, _): toasts?.show(words)            case .document(_, let said): if let said { toasts?.show(said) }            case .nothing: break            }        } catch {            toasts?.show(ActionRefused.words(for: error), tone: .error)        }        asked += 1    }}/// `chat.settings { linkPreviews }`: this phone fetching link cards, on or off.struct ChatYouLinkPreviews: Encodable, Sendable { let linkPreviews: Bool }/// What You asks beyond the people's methods.enum ChatYouMethod {    /// `{ notifications? }` → the seven rows, the Sync page, the muted chats.    static let you = "chat.you"    /// `{ readReceipts?, typing?, linkPreviews? }` → `{ readReceipts, typing, offered, linkPreviews }`.    static let settings = "chat.settings"    /// `{}` → what each chat keeps on this phone, largest first, each with its kinds and Free this chat.    static let storage = "chat.storage"    /// `{ thread, expected }` → `{ freed_bytes, said }`: that chat's files safe in the account taken off this phone.    static let storageFree = "chat.storage.free"}/// Your name and number as this phone last read them from `chat.profile`,/// remembered on this phone alone: while the profile cannot be read (the/// copy made again after an update, a connect in flight), You shows them/// rather than an empty name asking for one (owner's iPhone, Chat build 14).enum ChatYouRemembered {    struct Held: Codable, Equatable { var name: String?; var number: String? }    private static let key = "chat.you.remembered"    /// The account act a signed-out phone is offered (`tools.act`'s `account_sign_in`).    static let signIn = "account_sign_in"    static func read() -> Held? {        UserDefaults.standard.data(forKey: key).flatMap { try? JSONDecoder().decode(Held.self, from: $0) }    }    static func keep(_ read: ChatProfileAnswer) {        guard read.name != nil || read.number != nil, let data = try? JSONEncoder().encode(Held(name: read.name, number: read.number)) else { return }        UserDefaults.standard.set(data, forKey: key)    }    static func forget() { UserDefaults.standard.removeObject(forKey: key) }    /// Who You draws before `chat.profile` answers: the last profile read on    /// this phone, else who its Keychain says is signed in (their number at    /// once, their name when the sign-in knew it).    @MainActor    static func known(_ personal: PersonalObject?) -> Held? {        if let held = read() { return held }        #if COTTON_DEV        if ChatWarmSeed.asked { return ChatWarmSeed.signedIn }        #endif        guard let who = personal?.signedInWho, who.name != nil || who.number != nil else { return nil }        return Held(name: who.name, number: who.number)    }}@MainActorextension SettingsLook {    /// The shared settings parts in the Warm look: its small uppercase    /// headings, plain rows and accent acts, choices as its pills.    static func warm(_ look: ChatLook) -> SettingsLook {        var warm = SettingsLook(            ink: look.colours.text, quiet: look.colours.dim, rule: look.colours.rule, ground: look.colours.ground,            body: look.font(16), small: look.font(14),            heading: { AnyView(WarmHeading(words: $0)) },            act: { words, id, enabled, tap in                AnyView(Button(action: tap) {                    Text(verbatim: words)                        .font(look.font(16, .semibold))                        .foregroundStyle(look.colours.accent)                        .frame(minHeight: 44, alignment: .leading)                        .contentShape(Rectangle())                }                .buttonStyle(.plain).disabled(!enabled).opacity(enabled ? 1 : 0.45).accessibilityIdentifier(id))            },            choice: { words, on, id, enabled, tap in                AnyView(Button(action: tap) {                    Text(verbatim: words)                        .font(look.font(15, on ? .semibold : .regular))                        .foregroundStyle(on ? look.colours.onAccent : look.colours.text)                        .padding(.horizontal, 14).padding(.vertical, 8)                        .background(Capsule().fill(on ? look.colours.accent : look.colours.pill))                }                .buttonStyle(.plain).disabled(!enabled).accessibilityAddTraits(on ? .isSelected : []).accessibilityIdentifier(id))            }        )        warm.danger = look.colours.danger        return warm    }}#endif