Cotton code
493 lines · 21.2 KB · SwiftRaw
import SwiftUI// The panel the menu bar opens (build/panel.html; MAC-PANEL.md, 22 Nov 2026): three screens that never mix, one// plain headline, one row per source with its pause switch, a page per source with its guided steps, and the// account at the foot. Every sentence is the core's (`crates/cotton-mac/src/panel.rs`, the `macpanel` lines)./// Signed in and able to open the person's things: the headline, the rows, or one source's page.struct WorkingView: View {    @Bindable var model: AppModel    let panel: CoreStatus.Panel    @AppStorage("CottonLaunchSaid") private var launchSaid = false    var body: some View {        if let source = model.page {            SourcePage(model: model, panel: panel, source: source)        } else {            VStack(alignment: .leading, spacing: 10) {                if let headline = panel.headline {                    HeadlineView(headline: headline)                }                // Said once, on the first working panel: Cotton opens at login and comes back by itself.                if !launchSaid, let line = panel.account.launchLine {                    HStack(alignment: .top, spacing: 6) {                        Text(line).font(Faces.small).foregroundStyle(Palette.quiet).fixedSize(horizontal: false, vertical: true)                        Button { launchSaid = true } label: { Image(systemName: "xmark") }                            .buttonStyle(.plain)                            .foregroundStyle(Palette.faint)                            .accessibilityLabel(panel.word("done"))                    }                    .padding(8)                    .background(RoundedRectangle(cornerRadius: 8, style: .continuous).fill(Palette.card))                }                ScrollView(.vertical) {                    VStack(spacing: 2) {                        ForEach(panel.rows ?? []) { row in                            RowView(model: model, row: row)                        }                    }                }                .scrollIndicators(.never)                .frame(maxHeight: .infinity)            }        }    }}private struct HeadlineView: View {    let headline: CoreStatus.Panel.Headline    var body: some View {        VStack(alignment: .leading, spacing: 3) {            Text(headline.line)                .font(Faces.title)                .foregroundStyle(headline.needs ? Palette.warnIcon : Palette.ink)                .fixedSize(horizontal: false, vertical: true)                .accessibilityIdentifier("panel-headline")            if let sub = headline.sub {                Text(sub)                    .font(Faces.small)                    .foregroundStyle(Palette.quiet)                    .fixedSize(horizontal: false, vertical: true)            }            if let progress = headline.progress, progress.total > 0 {                ProgressView(value: Double(min(progress.done, progress.total)), total: Double(progress.total))                    .progressViewStyle(.linear)                    .controlSize(.small)                    .padding(.top, 4)            }        }        .padding(.horizontal, 4)    }}/// One source: its mark, name and one line; on the right its act (Add, Link, Fix, Allow) or its pause switch./// A click opens its page.private struct RowView: View {    @Bindable var model: AppModel    let row: CoreStatus.Panel.Row    @State private var hover = false    private var source: Source? { Source(rawValue: row.source) }    var body: some View {        HStack(spacing: 10) {            if let source {                SourceIcon(source: source, color: row.kind == "problem" ? Palette.warnIcon : (row.kind == "add" || row.kind == "paused" ? Palette.quiet : Palette.ink))            }            VStack(alignment: .leading, spacing: 1) {                Text(row.title)                    .font(Faces.headline)                    .foregroundStyle(row.kind == "unavailable" ? Palette.quiet : Palette.ink)                Text(row.line)                    .font(Faces.small)                    .foregroundStyle(row.kind == "problem" ? Palette.warnText : Palette.quiet)                    .fixedSize(horizontal: false, vertical: true)                    .lineLimit(3)                if let history = row.history {                    Text(history)                        .font(Faces.small)                        .foregroundStyle(Palette.quiet)                        .fixedSize(horizontal: false, vertical: true)                        .lineLimit(2)                }            }            Spacer(minLength: 4)            if let act = row.act {                Button(act) { model.page = source }                    .controlSize(.small)                    .buttonStyle(.bordered)                    .accessibilityIdentifier("row-act-\(row.source)")            } else if row.kind != "unavailable", let source {                Toggle("", isOn: Binding(                    get: { !row.paused },                    set: { on in on ? model.resume(source) : model.pause(source) }                ))                .toggleStyle(.switch)                .controlSize(.mini)                .labelsHidden()                .accessibilityLabel(row.title)                .accessibilityIdentifier("row-switch-\(row.source)")            }        }        .padding(.vertical, 7)        .padding(.horizontal, 8)        .background(RoundedRectangle(cornerRadius: 8, style: .continuous).fill(hover ? Palette.cardHover : .clear))        .contentShape(Rectangle())        .onHover { hover = $0 && row.kind != "unavailable" }        .onTapGesture { if row.kind != "unavailable" { model.page = source } }        .accessibilityIdentifier("row-\(row.source)")    }}// MARK: A source's page/// A source's page: what it brought, its guided steps (link, add, test, allow), and what can be done with it/// (bring in now, bring everything in again, unlink or remove, which ask first). Nothing here erases anything.struct SourcePage: View {    @Bindable var model: AppModel    let panel: CoreStatus.Panel    let source: Source    private var row: CoreStatus.Panel.Row? { panel.rows?.first { $0.source == source.rawValue } }    private var status: SourceStatus? { model.row(source) }    private func w(_ key: String, _ fills: [String: String] = [:]) -> String { panel.word(key, fills) }    var body: some View {        VStack(alignment: .leading, spacing: 10) {            Button { model.page = nil } label: {                Label(w("back"), systemImage: "chevron.left").font(Faces.small)            }            .buttonStyle(.plain)            .foregroundStyle(Palette.link)            .accessibilityIdentifier("page-back")            ScrollView(.vertical) {                VStack(alignment: .leading, spacing: 12) {                    HStack(spacing: 8) {                        SourceIcon(source: source, color: Palette.ink)                        Text(row?.title ?? source.title).font(Faces.title)                    }                    if let confirming = model.confirming, confirming != .quit {                        ConfirmView(model: model, panel: panel, confirming: confirming)                    } else {                        content                    }                }                .frame(maxWidth: .infinity, alignment: .leading)            }            .scrollIndicators(.never)            .frame(maxHeight: .infinity)        }    }    @ViewBuilder    private var content: some View {        let need = status?.probe.need        if let need, status?.probe.ready == false {            switch need.kind {            case "pair": WhatsappLinkStep(model: model, panel: panel, need: need, detail: status?.probe.detail)            case "credentials": CredentialsStep(model: model, panel: panel, source: source)            case "fullDiskAccess": DiskStep(model: model, panel: panel)            default: EmptyView()            }        } else if source == .mail, let found = model.mailFound {            MailFound(panel: panel, found: found) { model.mailFound = nil }        } else if row?.kind == "unavailable" {            Text(row?.line ?? "").font(Faces.small).foregroundStyle(Palette.quiet)        } else {            facts            actions        }        if row?.again == true {            Text(w("again_done")).font(Faces.small).foregroundStyle(Palette.quiet).fixedSize(horizontal: false, vertical: true)        }        if let note = model.pageNote {            Text(note).font(Faces.small).foregroundStyle(Palette.quiet).fixedSize(horizontal: false, vertical: true)        }    }    @ViewBuilder    private var facts: some View {        VStack(alignment: .leading, spacing: 6) {            if source == .whatsapp, !model.linkedNumbers.isEmpty {                Fact(label: w("number_label"), value: model.linkedNumbers.map { Words.phone($0) ?? $0 }.joined(separator: ", "))            }            if source.takesCredentials, let address = model.accountAddress[source] {                Fact(label: w("account_label"), value: address)            }            if let row {                Fact(label: w("brought_label"), value: row.line)            }            if row?.paused == true {                Text(w("paused_line")).font(Faces.small).foregroundStyle(Palette.quiet)            }        }        .padding(10)        .background(RoundedRectangle(cornerRadius: 8, style: .continuous).fill(Palette.card))    }    @ViewBuilder    private var actions: some View {        VStack(alignment: .leading, spacing: 8) {            if row?.paused != true {                Button(w("new_now")) { model.runNow(source) }                    .accessibilityIdentifier("page-run-now")            }            Button(w("again")) { model.bringAgain(source) }                .accessibilityIdentifier("page-again")            Text(w("again_line")).font(Faces.small).foregroundStyle(Palette.quiet).fixedSize(horizontal: false, vertical: true)            if source == .whatsapp {                Divider()                Button(w("unlink")) { model.confirming = .unlink }                    .foregroundStyle(Palette.warnText)                    .accessibilityIdentifier("page-unlink")            }            if source.takesCredentials, model.accountAddress[source] != nil {                Divider()                Button(w("remove")) { model.confirming = .remove(source) }                    .foregroundStyle(Palette.warnText)                    .accessibilityIdentifier("page-remove")            }        }        .buttonStyle(.link)        .foregroundStyle(Palette.link)        .font(Faces.body)    }}private struct Fact: View {    let label: String    let value: String    var body: some View {        HStack(alignment: .firstTextBaseline) {            Text(label).foregroundStyle(Palette.quiet)            Spacer(minLength: 8)            Text(value).foregroundStyle(Palette.ink).multilineTextAlignment(.trailing).textSelection(.enabled)                .fixedSize(horizontal: false, vertical: true)        }        .font(Faces.small)    }}/// Unlink and Remove ask first, and say that what is in Cotton stays there.private struct ConfirmView: View {    @Bindable var model: AppModel    let panel: CoreStatus.Panel    let confirming: AppModel.Confirm    var body: some View {        VStack(alignment: .leading, spacing: 8) {            switch confirming {            case .unlink:                Text(panel.word("unlink_ask_title")).font(Faces.headline)                Text(panel.word("unlink_ask_line")).font(Faces.small).foregroundStyle(Palette.quiet).fixedSize(horizontal: false, vertical: true)                buttons(panel.word("unlink_do")) { model.unlinkWhatsapp() }            case .remove(let source):                Text(panel.word("remove_ask_title", ["address": model.accountAddress[source] ?? source.title])).font(Faces.headline)                Text(panel.word("remove_ask_line")).font(Faces.small).foregroundStyle(Palette.quiet).fixedSize(horizontal: false, vertical: true)                buttons(panel.word("remove_do")) { model.removeCredentials(source) }            case .quit:                EmptyView()            }        }        .padding(10)        .background(RoundedRectangle(cornerRadius: 8, style: .continuous).fill(Palette.warnCard))    }    private func buttons(_ title: String, _ action: @escaping () -> Void) -> some View {        HStack {            Button(panel.word("cancel")) { model.confirming = nil }                .keyboardShortcut(.cancelAction)            Button(title, role: .destructive, action: action)                .accessibilityIdentifier("confirm-do")        }        .padding(.top, 4)    }}// MARK: Guided steps/// Link WhatsApp: the number and the code to type in WhatsApp (or a QR to scan), WhatsApp's passkey step, and/// what was found once linked. The same pieces the card had, on the page.private struct WhatsappLinkStep: View {    @Bindable var model: AppModel    let panel: CoreStatus.Panel    let need: SourceStatus.Need    let detail: String?    var body: some View {        VStack(alignment: .leading, spacing: 10) {            Text(panel.word("whatsapp_add_title")).font(Faces.headline)            if need.passkey == nil {                Text(panel.word("whatsapp_add_line")).font(Faces.small).foregroundStyle(Palette.quiet).fixedSize(horizontal: false, vertical: true)            }            if let detail, !detail.isEmpty, need.by == nil, need.passkey == nil {                Text(detail).font(Faces.small).foregroundStyle(Palette.warnText).fixedSize(horizontal: false, vertical: true)            }            WhatsappPairing(model: model, panel: panel, need: need, signer: detail)        }    }}/// Mail: the address and app password, how to make one, the server when Cotton doesn't know it,/// then the test, which says what it found.private struct CredentialsStep: View {    @Bindable var model: AppModel    let panel: CoreStatus.Panel    let source: Source    var body: some View {        let busy = model.credentialBusy.contains(source)        VStack(alignment: .leading, spacing: 8) {            Text(panel.word("mail_add_title")).font(Faces.headline)            if let line = model.row(source)?.probe.detail, !line.isEmpty {                Text(line).font(Faces.small).foregroundStyle(Palette.warnText).fixedSize(horizontal: false, vertical: true)            }            TextField(panel.word("mail_address"), text: draft(\.address))                .textContentType(.emailAddress)                .textFieldStyle(.roundedBorder)                .accessibilityIdentifier("mail-address")            SecureField(panel.word("mail_password"), text: draft(\.password))                .textFieldStyle(.roundedBorder)                .onSubmit(save)                .accessibilityIdentifier("mail-password")            if model.askServer || !(model.credentialDrafts[source]?.server ?? "").isEmpty {                TextField(panel.word("mail_server"), text: server)                    .textContentType(.URL)                    .textFieldStyle(.roundedBorder)                    .onSubmit(save)                    .accessibilityIdentifier("mail-server")                if source == .mail {                    Text(panel.word("mail_server_hint")).font(Faces.small).foregroundStyle(Palette.quiet).fixedSize(horizontal: false, vertical: true)                }            }            Text(panel.word("mail_howto")).font(Faces.small).foregroundStyle(Palette.quiet).fixedSize(horizontal: false, vertical: true)            if let error = model.credentialErrors[source] {                Text(error).font(Faces.small).foregroundStyle(Palette.warnText).fixedSize(horizontal: false, vertical: true)                    .accessibilityIdentifier("mail-error")            }            Button(panel.word("mail_test"), action: save)                .buttonStyle(PrimaryButtonStyle(enabled: !busy))                .disabled(busy)                .accessibilityIdentifier("mail-test")            if busy { ProgressView().controlSize(.small).frame(maxWidth: .infinity) }        }    }    private func save() {        if source == .mail { model.testAndAddMail() } else { model.saveCredentials(source) }    }    private var server: Binding<String> {        Binding(            get: { model.credentialDrafts[source]?.server ?? "" },            set: { value in                var current = model.credentialDrafts[source] ?? Keychain.Credentials(address: "", password: "")                current.server = value                model.credentialDrafts[source] = current            }        )    }    private func draft(_ key: WritableKeyPath<Keychain.Credentials, String>) -> Binding<String> {        Binding(            get: { (model.credentialDrafts[source] ?? Keychain.Credentials(address: "", password: ""))[keyPath: key] },            set: { value in                var current = model.credentialDrafts[source] ?? Keychain.Credentials(address: "", password: "")                current[keyPath: key] = value                model.credentialDrafts[source] = current            }        )    }}/// What the mail test found, once the account is added.private struct MailFound: View {    let panel: CoreStatus.Panel    let found: AppModel.MailFound    let done: () -> Void    var body: some View {        VStack(alignment: .leading, spacing: 8) {            Label(panel.word("mail_found_title"), systemImage: "checkmark.circle.fill")                .font(Faces.headline)                .foregroundStyle(Palette.good)            Text(panel.word("mail_found_count", ["mailbox": found.mailbox, "count": found.count.formatted()]))                .font(Faces.body)            if let oldest = found.oldest {                Text(panel.word("mail_found_oldest", ["oldest": oldest.formatted(.dateTime.month(.wide).year())]))                    .font(Faces.body)            }            Text(panel.word("mail_found_line")).font(Faces.small).foregroundStyle(Palette.quiet).fixedSize(horizontal: false, vertical: true)            Button(panel.word("done"), action: done)                .buttonStyle(PrimaryButtonStyle())                .accessibilityIdentifier("mail-done")        }    }}/// Full Disk Access, asked when a source needs it: why, three steps, and the button to System Settings. The/// panel notices by itself once it is allowed.private struct DiskStep: View {    @Bindable var model: AppModel    let panel: CoreStatus.Panel    var body: some View {        VStack(alignment: .leading, spacing: 8) {            Text(panel.word("disk_title")).font(Faces.headline)            Text(panel.word("disk_line")).font(Faces.small).foregroundStyle(Palette.quiet).fixedSize(horizontal: false, vertical: true)            Text(panel.word("disk_steps")).font(Faces.small).foregroundStyle(Palette.quiet).fixedSize(horizontal: false, vertical: true)            Button(panel.word("disk_open")) { model.openFullDiskAccess() }                .buttonStyle(PrimaryButtonStyle())                .accessibilityIdentifier("disk-open")        }    }}// MARK: The account/// At the foot of every screen: who is signed in, Sign out, Check for updates, the version, Quit. Quit says once/// what it does before the first quit.struct AccountFooter: View {    @Bindable var model: AppModel    let account: CoreStatus.Panel.Account?    let signedIn: Bool    var body: some View {        VStack(alignment: .leading, spacing: 6) {            if model.confirming == .quit, let account {                VStack(alignment: .leading, spacing: 6) {                    Text(account.quitLine ?? "").font(Faces.small).fixedSize(horizontal: false, vertical: true)                    HStack {                        Button(account.cancel ?? "Cancel") { model.confirming = nil }                            .keyboardShortcut(.cancelAction)                        Button(account.quitAnyway ?? account.quit) { model.quitAfterSaying() }                            .accessibilityIdentifier("quit-anyway")                    }                    .controlSize(.small)                }                .padding(8)                .background(RoundedRectangle(cornerRadius: 8, style: .continuous).fill(Palette.card))            }            Divider()            if signedIn, let account {                HStack {                    Text(account.who ?? "").foregroundStyle(Palette.quiet).lineLimit(1)                    Spacer()                    Button(account.signOut) { model.signOut() }                        .accessibilityIdentifier("account-sign-out")                }                HStack {                    if model.updatesCheck != nil {                        Button(account.updates) { model.checkForUpdates() }                            .accessibilityIdentifier("account-updates")                    }                    Spacer()                    Text("Cotton \(model.version)").foregroundStyle(Palette.faint)                    Button(account.quit) { model.askQuit() }                        .accessibilityIdentifier("account-quit")                }            } else {                HStack {                    Text("Cotton \(model.version)").foregroundStyle(Palette.faint)                    Spacer()                    Button(account?.quit ?? "Quit") { model.askQuit() }                        .accessibilityIdentifier("account-quit")                }            }        }        .buttonStyle(.link)        .font(Faces.small)    }}