Cotton code
283 lines · 12.8 KB · SwiftRaw
// Settings, grouped as Comms' You (owner, 23 Nov 2026; SettingsGrouped.swift):// you first (your face, else your initial in blue; your name big; your number// small beneath, else who is signed in; how sync stands), a card that opens// Profile, where a tap on the face or the name changes it, with Getting back// in, Sign out and Delete account. Then Sync and Your Claude; Text size (the// phone's own setting) and Storage; Help and feedback (Share a report, Write// to us) and About, each its own page. No Appearance: Ink is one light look.#if os(iOS)import CottonKitimport PhotosUIimport SwiftUIimport UIKitstruct InkSettingsScreen: View {    let story: InkStory    @State private var answer: AccountAnswer?    @State private var you: YouRead?    /// Your number, from your own person's phones.    @State private var number: String?    @State private var naming = false    @State private var asking = false    @State private var library = false    @State private var camera = false    @State private var item: PhotosPickerItem?    @State private var home = SettingsHome()    @Environment(PersonalObject.self) private var personal: PersonalObject?    @Environment(\.dismiss) private var dismiss    @Environment(\.openURL) private var openURL    @Environment(\.cottonSync) private var sync    @Environment(\.cottonCapabilities) private var capabilities    private struct Ask: Encodable, Sendable { let commit: String }    /// Your own person, once this copy holds it.    private var person: String? { you?.personId.flatMap { $0.isEmpty ? nil : $0 } }    /// Your name: your person's, else who Settings names (the name held at sign-in, else the number).    private var name: String {        if let name = you?.name?.trimmingCharacters(in: .whitespacesAndNewlines), !name.isEmpty { return name }        return SettingsWho(home.answer, personal).name    }    /// The face's letter: a name's first, never a number's "+".    private var initial: String {        name.first.flatMap { $0.isLetter ? String($0) : nil } ?? ""    }    var body: some View {        VStack(spacing: 0) {            HStack(spacing: 10) {                InkGlyph(symbol: "chevron.left", label: InkWords.line("writer.back")) { home.back { dismiss() } }                    .accessibilityIdentifier("story-settings-back")                Text(home.title(own: { $0 == "look" ? LookModel.standing("story").answer?.word("title") : nil }) ?? InkWords.line("settings.title"))                    .font(InkType.barTitle)                    .foregroundStyle(Ink.ink)                    .frame(maxWidth: .infinity)                    .accessibilityAddTraits(.isHeader)                Color.clear.frame(width: 44, height: 44)            }            .padding(.horizontal, 8)            .padding(.top, 6)            ScrollView {                if let answer {                    VStack(alignment: .leading, spacing: 0) {                        switch home.place {                        case nil:                            // Grouped as Comms' You (SettingsGrouped.swift): you, then Sync and Your Claude, Text                            // size and Storage, then Help and feedback and About; each row opens its own page.                            SettingsHomeList(home: home, look: .ink, own: own) {                                SettingsYouCard(home: home, core: story.core, look: .ink, said: { story.notice = $0 }) {                                    InkPictureFace(initial: initial, picture: you?.print, size: 70)                                }                            }                        case .profile?:                            // Your face and name (tap either to change it), then Getting back in, Sign out and                            // Delete account; after, the first page.                            yours(answer, changes: true)                            SettingsProfileFoot(home: home, core: story.core, look: .ink, said: { story.notice = $0 }) { dismiss() }                        case .own("look")?:                            StoryLookPage(story: story)                        case .own?:                            EmptyView()                        case let shared?:                            SettingsSharedPage(place: shared, home: home, core: story.core, look: .ink, said: { story.notice = $0 },                                               help: AnyView(writeToUs)) { Task { await home.read(story.core) } }                        }                    }                    .padding(.horizontal, Ink.gutter)                    .padding(.top, 16)                    .padding(.bottom, 26)                }            }            .id(home.place)        }        .inkGround()        .toolbar(.hidden, for: .navigationBar)        .task(id: sync?.revision) {            await read()            await home.read(story.core)        }        .lookPanel(isPresented: $naming, style: Ink.panel) {            InkNameSheet(title: InkWords.line("ink.your_name"), hint: InkWords.line("ink.your_name_hint")) { named in                Task { await rename(named) }            }        }        .lookPanel(isPresented: $asking, style: Ink.panel) {            InkActsSheet(title: InkWords.line("ink.your_picture"), acts: sources)        }        .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 {                    story.notice = DockModel.pictureRefused                    return                }                await keepFace(staged.url)            }        }        .fullScreenCover(isPresented: $camera) {            CameraPicker(onTaken: { url in                camera = false                Task { await keepFace(url) }            }, onCancelled: { camera = false })        }    }    /// Your face, your name and who is signed in. Neither can change before    /// this copy holds your own person (`read.you` answers `none_yet`).    /// Write to us, under Share a report: Story's report sheet.    /// Drawn as Share a report is, an outlined pill: as a row it stood bold with nothing beside it, and read as the    /// heading of Privacy policy and Help and contact under it (the iPhone walk, 24 Nov 2026).    private var writeToUs: some View {        InkPill(words: InkWords.line("ink.help_line")) {            NotificationCenter.default.post(name: .cottonReportProblem, object: nil)        }        .padding(.top, 10)        .accessibilityIdentifier("story-settings-help")    }    /// Story's own row: Look (shared/DECISIONS.md "Look"), which holds the paper, the ink, the face and the size; the    /// phone's own text size still scales every size, as before.    private var own: [SettingsOwnRow] {        let look = LookModel.standing("story").answer        return [SettingsOwnRow(id: "look", label: look?.word("title") ?? "", line: look?.line)]    }    /// PROFILE's head: your face and your name, a tap on either changing it, then the number you sign in with.    private func yours(_ answer: AccountAnswer, changes: Bool) -> some View {        HStack(alignment: .center, spacing: 16) {            Button { asking = true } label: {                InkPictureFace(initial: initial, picture: you?.print, size: 70)            }            .buttonStyle(InkPress())            .disabled(person == nil)            .allowsHitTesting(changes)            .accessibilityLabel(InkWords.line("ink.your_picture"))            VStack(alignment: .leading, spacing: 4) {                Button { naming = true } label: {                    Text(name)                        .font(InkType.big)                        .foregroundStyle(Ink.ink)                        .multilineTextAlignment(.leading)                        .fixedSize(horizontal: false, vertical: true)                }                .buttonStyle(InkPress())                .disabled(person == nil)                .allowsHitTesting(changes)                .accessibilityLabel(name)                .accessibilityHint(InkWords.line("ink.your_name"))                .accessibilityAddTraits(.isHeader)                // The number you sign in with, and what it is for (Settings' Profile, as Comms').                SettingsProfileNumber(home: home, look: .ink, name: name)            }            .frame(maxWidth: .infinity, alignment: .leading)        }    }    /// The photo library, and the camera where this phone has one.    private var sources: [InkAct] {        var acts = [InkAct(words: InkWords.line("ink.picture_library")) {            asking = false            library = true        }]        if Camera.isAvailable {            acts.append(InkAct(words: InkWords.line("ink.picture_camera")) {                asking = false                Task {                    if let refusal = await Camera.refusal(capabilities) { story.notice = refusal } else { camera = true }                }            })        }        return acts    }    private func read() async {        let ask = Ask(commit: (Bundle.main.object(forInfoDictionaryKey: "CottonBuildCommit") as? String) ?? "")        await story.attempt {            answer = try await story.core.call(CottonMethod.shellAccount, ask, as: AccountAnswer.self)            you = try? await story.core.call(CottonMethod.readYou, EmptyRequest(), as: YouRead.self)        }        if let person {            let row = try? await story.core.callJSON(CottonMethod.recordsGet, ["table": RecordValue.text(InkYou.table), "id": .text(person)])            number = InkYou.number(row?["data"]?["phones"])        } else {            number = nil        }    }    /// Your name, written to your own person (the People table's name).    private func rename(_ named: String) async {        guard let person else { return }        await story.attempt {            _ = try await story.core.callJSON(StoryMethod.recordsUpdate, [                "table": RecordValue.text(InkYou.table), "id": .text(person), "patch": .object([InkYou.name: .text(named)]),            ])        }        await read()    }    /// Your picture, as People keeps a face: squared and small, then `capture.avatar`.    private func keepFace(_ picked: URL) async {        defer { try? FileManager.default.removeItem(at: picked) }        guard let person else { return }        guard let square = AvatarStaging.square(atPath: picked.path(percentEncoded: false)) else {            story.notice = DockModel.pictureRefused            return        }        defer { try? FileManager.default.removeItem(at: square) }        await story.attempt {            _ = try await story.core.call(CottonMethod.captureAvatar,                                          CaptureAvatarRequest(personId: person, path: square.path(percentEncoded: false), mime: "image/jpeg", filename: "you.jpg"),                                          as: CaptureAvatarAnswer.self)        }        await read()    }}/// Your own person, in the People table (`kits/personal/tables/person.json`).enum InkYou {    static let table = "person"    static let name = "full_name"    /// The first number in a person's `phones`: a list, or lines of text.    static func number(_ phones: JSONValue?) -> String? {        let all: [String]        switch phones {        case .array(let list)?: all = list.compactMap(\.string)        case .string(let text)?: all = text.components(separatedBy: .newlines)        default: all = []        }        return all.map { $0.trimmingCharacters(in: .whitespaces) }.first { !$0.isEmpty }    }}@MainActorextension SettingsLook {    /// The shared settings parts in Ink: its mono words, dotted rules, ghost    /// buttons and chips.    static var ink: SettingsLook {        SettingsLook(            ink: Ink.ink, quiet: Ink.quiet, rule: Ink.rule.opacity(0.5), ground: Ink.ground,            body: InkType.scenePreview, small: InkType.sceneLength,            heading: { title in                AnyView(Text(verbatim: title).font(InkType.sceneTitle).foregroundStyle(Ink.ink)                    .padding(.top, 18).padding(.bottom, 4).accessibilityAddTraits(.isHeader))            },            act: { words, id, enabled, tap in                AnyView(InkButton(words: words, ghost: true, action: tap).disabled(!enabled).opacity(enabled ? 1 : 0.4).accessibilityIdentifier(id))            },            choice: { words, on, id, enabled, tap in                AnyView(Button(action: tap) { InkChip(on: on) { Text(verbatim: words) } }                    .buttonStyle(InkPress()).disabled(!enabled)                    .accessibilityAddTraits(on ? .isSelected : []).accessibilityIdentifier(id))            },            // Story has one accent and no red: its danger is said in ink.            danger: Ink.ink,            title: InkType.big        )    }}#endif