682 lines · 29.0 KB · SwiftRaw
// SETTINGS, ORGANISED AS COMMS' YOU (owner, 23 Nov 2026: "Comms' settings are// well organised now; the other three are not"; shared/DECISIONS.md// "Settings" › "Organised as Comms' You"), for Words, Days and Story, each in// its own look (`SettingsLook`), from the one answer Android draws from://// the profile card → Profile: who, the number, Getting back in, Sign out, Delete account// the app's own rows → Days' Google calendars, Words' Look, Story's Text size// (gap) Sync · Your Claude// (gap) Privacy · Notifications · Storage// (gap) Help and feedback · About//// Which shared rows stand, their order, groups and words are the core's// (`shell.settings` `rows`, `profile`, `sync`, `pages`); the app's own rows// are the app's. A row opens its page; the app's header names the page and// its Back returns to the list (`SettingsHome.back`). Sign out stands on// Profile alone. The pages' words are Comms' own (`chat` `app.you.*`).#if os(iOS)import CottonKitimport SwiftUIimport UIKit/// The pages' words: Comms' You's own lines, as Android's `SettingsWords`.enum SettingsWords { static func line(_ key: String, _ fills: [String: String] = [:]) -> String { ShellLines.line("chat", "app.you.\(key)", fills) }}/// Where Settings stands: the list (nil), one of the shared pages, or one of the app's own.enum SettingsPlace: Hashable { case profile, sync, claude, privacy, notifications, storage, help, about case own(String) init?(row: String) { switch row { case "sync": self = .sync case "claude": self = .claude case "privacy": self = .privacy case "notifications": self = .notifications case "storage": self = .storage case "help": self = .help case "about": self = .about default: return nil } } var id: String { switch self { case .profile: "profile" case .sync: "sync" case .claude: "claude" case .privacy: "privacy" case .notifications: "notifications" case .storage: "storage" case .help: "help" case .about: "about" case .own(let id): id } }}/// One of the app's own rows (Days' Google calendars, Words' Look), drawn right after the card.struct SettingsOwnRow: Identifiable { let id: String let label: String var line: String? /// Where it goes: its own page, or straight out (Story's Text size opens the phone's settings). var tap: (() -> Void)?}/// `shell.settings` read whole for the organised list: the shared parts, the rows, the card, the Sync page,/// the pages' lines and the account.struct SettingsHomeAnswer: Decodable { struct Row: Decodable, Equatable, Sendable { let id: String let label: String var line: String? var group: String? } struct Profile: Decodable, Equatable, Sendable { var signedIn: Bool var name: String? var line: String? enum CodingKeys: String, CodingKey { case name, line case signedIn = "signed_in" } } struct Sync: Decodable, Equatable, Sendable { let title: String var last: String? var trouble: Bool? } struct Pages: Decodable, Equatable, Sendable { var storageKept: String? var notificationsPhoneLine: String? enum CodingKeys: String, CodingKey { case storageKept = "storage_kept" case notificationsPhoneLine = "notifications_phone_line" } } let parts: SettingsAnswer var rows: [Row] var profile: Profile? var sync: Sync? var pages: Pages? var account: AccountAnswer? private enum Keys: String, CodingKey { case rows, profile, sync, pages, account } init(from decoder: Decoder) throws { parts = try SettingsAnswer(from: decoder) let keyed = try decoder.container(keyedBy: Keys.self) rows = (try? keyed.decode([Row].self, forKey: .rows)) ?? [] profile = try? keyed.decode(Profile.self, forKey: .profile) sync = try? keyed.decode(Sync.self, forKey: .sync) pages = try? keyed.decode(Pages.self, forKey: .pages) account = try? keyed.decode(AccountAnswer.self, forKey: .account) } func row(_ place: SettingsPlace) -> Row? { rows.first { $0.id == place.id } } var signedIn: Bool { profile?.signedIn ?? (account?.people != nil) }}/// The last `shell.settings` answer, kept on this phone alone so Settings draws whole on its first frame (the/// signed-out card's Sign in is one of the account's acts). Your people are left out: Privacy waits for the read,/// the list never does./// Forgotten when the phone signs in or out, so a list for the other state is never drawn.enum SettingsRemembered { private static let key = "settings.remembered" static func decode(_ raw: JSONValue) -> SettingsHomeAnswer? { guard let data = try? JSONEncoder().encode(raw) else { return nil } return try? JSONDecoder().decode(SettingsHomeAnswer.self, from: data) } static func read() -> SettingsHomeAnswer? { guard let data = UserDefaults.standard.data(forKey: key) else { return nil } return try? JSONDecoder().decode(SettingsHomeAnswer.self, from: data) } static func keep(_ raw: JSONValue) { guard case .object(var fields) = raw else { return } if case .object(var account)? = fields["account"] { account["people"] = nil fields["account"] = .object(account) } guard let data = try? JSONEncoder().encode(JSONValue.object(fields)) else { return } UserDefaults.standard.set(data, forKey: key) } static func forget() { UserDefaults.standard.removeObject(forKey: key) } /// `-settings-held <seconds>` (development builds): the list's read waits that long, as a phone with much /// kept answers late, so a check sees what the first frames draw without it (SettingsInstantTests). static func heldBack() async { #if COTTON_DEV let seconds = UserDefaults.standard.double(forKey: "settings-held") if seconds > 0 { try? await Task.sleep(for: .seconds(seconds)) } #endif }}/// What the organised Settings holds while open: the answer, the page standing, whether the phone lets the/// app notify, and where Your Claude was opened from.@MainActor@Observablefinal class SettingsHome { var answer: SettingsHomeAnswer? var place: SettingsPlace? var notifying: Bool? /// Your Claude opened from Privacy: its Back returns there. var claudeFrom: SettingsPlace? private struct Ask: Encodable, Sendable { let commit: String; let notifications: Bool? } /// The list as this phone last read it, drawn on the first frame: every row stands at once, and the read /// below fills its values in place (owner, build 24: the card came first and the rows a second or two later). init() { answer = SettingsRemembered.read() // Opened from the home's sync line: it stands on Sync, the fuller status. if MainActor.assumeIsolated({ SyncSeenOpens.take() }) { place = .sync } } /// Read again on each sync; a read refused leaves what stands. func read(_ core: (any CottonCalling)?) async { guard let core else { return } let notifies = await SystemCapabilityAuthority().status(.notifications) == .authorized notifying = notifies await SettingsRemembered.heldBack() // A phone with no list remembered (a fresh install) draws it from this phone alone first, as Android does: // the whole answer asks the server and walks the app's folder, which on a big account took long enough // that You stood with its card alone (owner, Data build 1, 26 Nov). if answer == nil, let raw = try? await core.callJSON(CottonMethod.shellSettingsNow, Ask(commit: SettingsAnswer.commit, notifications: notifies)), let quick = SettingsRemembered.decode(raw), answer == nil { answer = quick } guard let raw = try? await core.callJSON(CottonMethod.shellSettings, Ask(commit: SettingsAnswer.commit, notifications: notifies)), let read = SettingsRemembered.decode(raw) else { return } answer = read SettingsRemembered.keep(raw) } /// Read once, a moment after the app opens, when this phone has no list remembered yet (a fresh install or /// update): the first Settings opened is drawn whole too. static func warm(_ core: (any CottonCalling)?) async { guard let core, SettingsRemembered.read() == nil else { return } try? await Task.sleep(for: .seconds(3)) guard SettingsRemembered.read() == nil else { return } await SettingsHome().read(core) } /// The header's Back: Your Claude opened from Privacy returns there; a page returns to the list; the list /// closes Settings. func back(close: () -> Void) { if place == .claude, let from = claudeFrom { claudeFrom = nil go(from) } else if place != nil { withAnimation(.easeOut(duration: 0.18)) { place = nil } } else { close() } } func go(_ place: SettingsPlace) { withAnimation(.easeOut(duration: 0.18)) { self.place = place } } /// The page's name for the app's header, or nil on the list (the header says Settings). func title(own: (String) -> String?) -> String? { switch place { case nil: nil case .profile?: answer?.account?.card.title case .own(let id)?: own(id) case let shared?: answer?.row(shared)?.label } }}// MARK: - The list/// A row that opens a page: its name, how it stands in a few words, what it says at the right (On, Off),/// a chevron; the rule under it.struct SettingsGoRow: View { let label: String let line: String? var said: String? = nil let look: SettingsLook let id: String let tap: () -> Void var body: some View { Button(action: tap) { VStack(spacing: 0) { HStack(alignment: .center, spacing: 12) { VStack(alignment: .leading, spacing: 2) { Text(verbatim: label).font(look.body).foregroundStyle(look.ink) .fixedSize(horizontal: false, vertical: true) if let line, !line.isEmpty { Text(verbatim: line).font(look.small).foregroundStyle(look.quiet) .fixedSize(horizontal: false, vertical: true) } } .frame(maxWidth: .infinity, alignment: .leading) if let said { Text(verbatim: said).font(look.small).foregroundStyle(look.quiet) } SettingsChevron(look: look) } .frame(minHeight: 48) .padding(.vertical, 6) Rectangle().fill(look.rule).frame(height: 0.5) } .contentShape(Rectangle()) } .buttonStyle(.plain) .accessibilityElement(children: .combine) .accessibilityAddTraits(.isButton) .accessibilityIdentifier(id) }}struct SettingsChevron: View { let look: SettingsLook var body: some View { Image(systemName: "chevron.right") .font(.system(size: 13, weight: .semibold)) .foregroundStyle(look.quiet) .accessibilityHidden(true) }}/// The card, the app's own rows, then the shared rows in the core's order with a gap between groups.struct SettingsHomeList<Card: View>: View { let home: SettingsHome let look: SettingsLook let own: [SettingsOwnRow] @ViewBuilder var card: () -> Card var body: some View { VStack(alignment: .leading, spacing: 0) { card() .padding(.bottom, 10) ForEach(own) { mine in SettingsGoRow(label: mine.label, line: mine.line, look: look, id: "settings-row-\(mine.id)") { if let tap = mine.tap { tap() } else { home.go(.own(mine.id)) } } } let rows = home.answer?.rows ?? [] ForEach(Array(rows.enumerated()), id: \.element.id) { at, row in if at == 0 ? !own.isEmpty : rows[at - 1].group != row.group { Spacer().frame(height: 18) } SettingsGoRow(label: row.label, line: row.line, look: look, id: "settings-row-\(row.id)") { if let place = SettingsPlace(row: row.id) { home.go(place) } } } } .accessibilityElement(children: .contain) .accessibilityIdentifier("settings-home") }}/// The account acts run as every tool act runs, from a settings page.@MainActorstruct SettingsActs { let core: (any CottonCalling)? let openURL: OpenURLAction let nativeFlow: (@MainActor (RecordKeptFlow) async -> Bool)? let rekey: (@MainActor () async -> Bool)? let said: (String) -> Void func run(_ act: CardAction) async { guard let core else { return } 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, _): said(words) case .document(_, let words): if let words { said(words) } case .nothing: break } } catch { said(ActionRefused.words(for: error)) } }}/// Who the card and Profile name: the copy's own name, else the name given at sign-in held on this phone,/// else the number; and the number this phone signed in with.@MainActorstruct SettingsWho { let name: String let number: String? init(_ answer: SettingsHomeAnswer?, _ personal: PersonalObject?) { let held = personal?.signedInWho let number = held?.number.flatMap { $0.isEmpty ? nil : $0 } self.name = answer?.profile?.name.flatMap { $0.isEmpty ? nil : $0 } ?? held?.name.flatMap { $0.isEmpty ? nil : $0 } ?? number ?? answer?.account?.card.subtitle ?? "" self.number = number }}/// The card. Signed in: the name large, the number beneath, a chevron to Profile. Signed out: Sign in, with/// what signing in does; a tap signs in. `face` is Story's picture.struct SettingsYouCard<Face: View>: View { let home: SettingsHome let core: (any CottonCalling)? let look: SettingsLook /// The page's own title over the card ("You"): an account with no name of its own comes back named that word, and /// the card then shows the number in its place rather than the title twice. var pageTitle: String? = nil let said: (String) -> Void @ViewBuilder var face: () -> Face @Environment(PersonalObject.self) private var personal: PersonalObject? @Environment(\.openURL) private var openURL @Environment(\.nativeKeptFlow) private var nativeFlow @Environment(\.rekeyThisDevice) private var rekey var body: some View { let signIn = home.answer?.account?.actions.first { $0.id == "account_sign_in" } let out = home.answer?.signedIn == false Button { if out, let signIn { Task { await SettingsActs(core: core, openURL: openURL, nativeFlow: nativeFlow, rekey: rekey, said: said).run(signIn) } } else { home.go(.profile) } } label: { HStack(alignment: .center, spacing: 14) { face() VStack(alignment: .leading, spacing: 3) { if out { Text(verbatim: signIn?.label ?? "").font(look.title ?? look.body).foregroundStyle(look.ink) .fixedSize(horizontal: false, vertical: true) if let line = home.answer?.profile?.line { Text(verbatim: line).font(look.small).foregroundStyle(look.quiet) .fixedSize(horizontal: false, vertical: true) } } else { let who = SettingsWho(home.answer, personal) let name = who.name == pageTitle ? (who.number ?? who.name) : who.name Text(verbatim: name).font(look.title ?? look.body).foregroundStyle(look.ink) .fixedSize(horizontal: false, vertical: true) if let number = who.number, number != name { Text(verbatim: number).font(look.small).foregroundStyle(look.quiet) } } } .frame(maxWidth: .infinity, alignment: .leading) SettingsChevron(look: look) } .frame(minHeight: 56) .contentShape(Rectangle()) } .buttonStyle(.plain) .accessibilityElement(children: .combine) .accessibilityAddTraits(.isButton) .accessibilityIdentifier("settings-card") }}extension SettingsYouCard where Face == EmptyView { init(home: SettingsHome, core: (any CottonCalling)?, look: SettingsLook, pageTitle: String? = nil, said: @escaping (String) -> Void) { self.init(home: home, core: core, look: look, pageTitle: pageTitle, said: said) { EmptyView() } }}// MARK: - The shared pages/// SYNC: how it stands, when it last synced, the out-of-reach line in a block, Sync now; signed out, Sign in.struct SettingsSyncPage: View { let home: SettingsHome let core: (any CottonCalling)? let look: SettingsLook let said: (String) -> Void @Environment(\.openURL) private var openURL @Environment(\.nativeKeptFlow) private var nativeFlow @Environment(\.rekeyThisDevice) private var rekey var body: some View { VStack(alignment: .leading, spacing: 6) { if let state = home.answer?.sync { Text(verbatim: state.title) .font(look.title ?? look.body).foregroundStyle(look.ink) .fixedSize(horizontal: false, vertical: true) .accessibilityIdentifier("settings-sync-state") if let last = state.last { Text(verbatim: last).font(look.small).foregroundStyle(look.quiet) .accessibilityIdentifier("settings-sync-last") } if state.trouble == true { Text(verbatim: SettingsWords.line("unreachable")) .font(look.body).foregroundStyle(look.ink) .fixedSize(horizontal: false, vertical: true) .padding(12) .frame(maxWidth: .infinity, alignment: .leading) .background(RoundedRectangle(cornerRadius: 10).fill(look.ink.opacity(0.06))) .padding(.top, 8) .accessibilityIdentifier("settings-sync-unreachable") } } let acts = home.answer?.account?.actions ?? [] if let act = acts.first(where: { $0.id == "account_back_up" }) ?? acts.first(where: { $0.id == "account_sign_in" }) { look.act(act.label, act.id == "account_back_up" ? "settings-sync-now" : "settings-sign-in", true) { Task { await SettingsActs(core: core, openURL: openURL, nativeFlow: nativeFlow, rekey: rekey, said: said).run(act) } } .padding(.top, 14) } } .frame(maxWidth: .infinity, alignment: .leading) }}/// PROFILE's head as Words and Days draw it: the name large, then the number.struct SettingsProfileHead: View { let home: SettingsHome let look: SettingsLook @Environment(PersonalObject.self) private var personal: PersonalObject? var body: some View { let name = SettingsWho(home.answer, personal).name VStack(alignment: .leading, spacing: 4) { Text(verbatim: name).font(look.title ?? look.body).foregroundStyle(look.ink) .fixedSize(horizontal: false, vertical: true) .accessibilityIdentifier("settings-profile-name") SettingsProfileNumber(home: home, look: look, name: name) } .frame(maxWidth: .infinity, alignment: .leading) }}/// The number you sign in with, and "You sign in with this number."; where the name above is the number,/// only the line; nothing where this phone holds none.struct SettingsProfileNumber: View { let home: SettingsHome let look: SettingsLook /// The name drawn above it. let name: String @Environment(PersonalObject.self) private var personal: PersonalObject? var body: some View { if let number = SettingsWho(home.answer, personal).number { VStack(alignment: .leading, spacing: 2) { if number != name { Text(verbatim: number).font(look.body).foregroundStyle(look.ink) .accessibilityIdentifier("settings-profile-number") } Text(verbatim: SettingsWords.line("number_line")).font(look.small).foregroundStyle(look.quiet) } .padding(.top, 6) } }}/// PROFILE's foot, under the app's own head: any account act but Sync now and Sign out (Sign in while a/// first sync stopped), Getting back in, Sign out with what coming back takes, then Delete account.struct SettingsProfileFoot: View { let home: SettingsHome let core: (any CottonCalling)? let look: SettingsLook let said: (String) -> Void /// After Delete account: the app's first page. let deleted: () -> Void @Environment(\.recoveryKeys) private var recovery @Environment(\.openURL) private var openURL @Environment(\.nativeKeptFlow) private var nativeFlow @Environment(\.rekeyThisDevice) private var rekey var body: some View { let acts = home.answer?.account?.actions ?? [] let run = SettingsActs(core: core, openURL: openURL, nativeFlow: nativeFlow, rekey: rekey, said: said) VStack(alignment: .leading, spacing: 0) { ForEach(acts.filter { $0.id != "account_back_up" && $0.id != "account_sign_out" }) { act in look.act(act.label, "settings-profile-\(act.id)", true) { Task { await run.run(act) } } .padding(.top, 14) } // Signed out in an app whose kit has no tool to carry the account acts (Data, Sites): Sign in is still // offered, the number-and-code sheet Home's card raises (`PersonalSessionFlows`). Found walking Data on a // fresh phone, 26 Nov 2026: its Account page stood with "Signed out" and nothing to do. if home.answer?.profile?.signedIn == false, !acts.contains(where: { $0.id == "account_sign_in" }), let nativeFlow { look.act(ShellLines.line("boot", "home.acts.sign_in"), "settings-profile-account_sign_in", true) { Task { _ = await nativeFlow(RecordKeptFlow(flow: .signIn, origin: .init(table: "device", id: "new"), database: nil)) } } .padding(.top, 14) } if recovery?.status?.flag("holdsVault") == true { look.heading(SettingsWords.line("getting_back")) RecoveryAccountPart(look: look) if let core { RecoveryCircleRows(core: core, look: look) } // Restore an earlier day (RESTORE PHONE 2): under Account, where the server's restore is on; after one, its line. if let core { RestoreRow(core: core, look: look) } } if let out = acts.first(where: { $0.id == "account_sign_out" }) { look.act(out.label, "settings-sign-out", true) { Task { await run.run(out) home.place = nil } } .padding(.top, 26) Text(verbatim: SettingsWords.line("sign_out_line")) .font(look.small).foregroundStyle(look.quiet) .fixedSize(horizontal: false, vertical: true) .padding(.top, 8) .accessibilityIdentifier("settings-sign-out-line") } DeleteAccountPart(core: core, look: look, onDeleted: deleted) } .frame(maxWidth: .infinity, alignment: .leading) }}/// PRIVACY: Your people (each with what can be done with them), then a row to Your Claude.struct SettingsPrivacyPage: View { let home: SettingsHome let core: (any CottonCalling)? let look: SettingsLook let said: (String) -> Void let again: () -> Void var body: some View { VStack(alignment: .leading, spacing: 0) { if let people = home.answer?.account?.people { look.heading(people.title) if let none = people.unreachable ?? (people.rows.isEmpty ? people.empty : nil) { Text(verbatim: none).font(look.small).foregroundStyle(look.quiet) .fixedSize(horizontal: false, vertical: true) .padding(.top, 8) .accessibilityIdentifier("settings-people-none") } ForEach(Array(people.rows.enumerated()), id: \.offset) { _, entry in VStack(alignment: .leading, spacing: 6) { Text(verbatim: entry.row.words).font(look.body).foregroundStyle(look.ink) if let detail = entry.row.detail { Text(verbatim: detail).font(look.small).foregroundStyle(look.quiet) } if let acts = entry.row.acts, !acts.isEmpty { SettingsFlow(spacing: 8) { ForEach(acts, id: \.id) { act in look.act(act.words, "settings-person-\(act.id)", true) { Task { await call(act) } } } } } Rectangle().fill(look.rule).frame(height: 0.5).padding(.top, 4) } .padding(.top, 10) .accessibilityElement(children: .contain) .accessibilityIdentifier("settings-person") } } if let claude = home.answer?.row(.claude) { Spacer().frame(height: 18) SettingsGoRow(label: claude.label, line: claude.line, look: look, id: "settings-privacy-claude") { home.claudeFrom = .privacy home.go(.claude) } } } .frame(maxWidth: .infinity, alignment: .leading) } private func call(_ act: AccountAnswer.People.Act) async { guard let core else { return } do { if let words = try await core.callJSON(act.call.method, act.call.request).text("said") { said(words) } } catch { said((error as? CottonCallError)?.message ?? ActionRefused.words(for: error)) } NotificationCenter.default.post(name: .cottonPeopleChanged, object: nil) again() }}/// The phone's own notification settings for this app, with On or Off: Days' Notifications page closes on it.struct SettingsPhoneNotifications: View { let home: SettingsHome let look: SettingsLook @Environment(\.openURL) private var openURL var body: some View { SettingsGoRow(label: SettingsWords.line("notifications_phone"), line: home.answer?.pages?.notificationsPhoneLine, said: home.notifying.map { ShellLines.line("chat", $0 ? "app.you.glance.notifications_on" : "app.you.glance.notifications_off") }, look: look, id: "settings-notifications-phone") { if let url = URL(string: UIApplication.openNotificationSettingsURLString) { openURL(url) } } }}/// The page a shared row opens, drawn under the app's header. Days draws Notifications itself (its Alerts).struct SettingsSharedPage: View { let place: SettingsPlace let home: SettingsHome let core: (any CottonCalling)? let look: SettingsLook let said: (String) -> Void /// The app's own ways to help, under Share a report (Story's Write to us). var help: AnyView? = nil /// After an act changed what the page shows (Your people): read again. var again: () -> Void = {} var body: some View { switch place { case .sync: SettingsSyncPage(home: home, core: core, look: look, said: said) case .claude: YourClaudePart(core: core, look: look, headed: false) case .privacy: SettingsPrivacyPage(home: home, core: core, look: look, said: said, again: again) case .notifications: SettingsPhoneNotifications(home: home, look: look) case .storage: SettingsParts(core: core, look: look, said: said, only: "storage", kept: home.answer?.pages?.storageKept) case .help: SettingsParts(core: core, look: look, said: said, only: "help") { help ?? AnyView(EmptyView()) } case .about: SettingsParts(core: core, look: look, said: said, only: "about") case .profile, .own: EmptyView() } }}#endif