Cotton code
477 lines · 23.5 KB · SwiftRaw
// YOU (mail.html "You, Privacy and Look"): each row shows its current answer, so the page reads as a summary before// anything is tapped: Accounts, Signature, Notifications, Sorting rules, Undo send, Domains, Look; then Sync, Privacy,// Storage, Help and About, as in every Cotton app. `mail.you` answers the rows and their answers (CONTRACT "You");// until it does, the places Post can already open stand here (Accounts, Sorting rules, Domains, Look, Privacy), each// saying the core's words in place. Also here: Look (the shared `look {app: mail}` with Post's own preview), Sorting// rules (`mail.rules`), Privacy (the three promises), and the plain page an unanswered call stands on.#if os(iOS)import CottonKitimport SwiftUI/// `mail.you`: You's groups and rows, each with its current answer (`value`), and what a tap does (`open`): push a/// page, or offer its choices in place (`mail.set {name, value}`, which answers You again).struct PostYou: Decodable, Equatable, Sendable {    struct Choice: Decodable, Equatable, Sendable, Identifiable {        var value: JSONValue        var label: String        var on: Bool = false        var id: String { label }    }    struct Open: Decodable, Equatable, Sendable {        var page: String?        var name: String?        var choices: [Choice]?    }    struct Row: Decodable, Equatable, Sendable, Identifiable {        var id: String        var title: String        var value: String?        var open: Open?    }    struct Group: Decodable, Equatable, Sendable, Identifiable {        var id: String        var title: String?        var rows: [Row]    }    struct Card: Decodable, Equatable, Sendable { var line: String?; var count: String? }    var title: String?    var card: Card?    var groups: [Group]    var firstSync: PostFirstSync?}struct PostYouScreen: View {    let model: PostModel    @State private var you: PostRead<PostYou>?    @State private var look = LookModel.standing("mail")    /// Light or dark as the screen stands, for the Look row's words.    @Environment(\.colorScheme) private var scheme    var body: some View {        ScrollView {            VStack(alignment: .leading, spacing: 0) {                PostTitle(text: you?.answer?.title ?? PostWords.line("you.title")).padding(.top, 8)                if case .read(let answer)? = you {                    if let card = answer.card, card.line != nil || card.count != nil {                        VStack(alignment: .leading, spacing: 3) {                            if let line = card.line { Text(line).font(PostType.rowName).foregroundStyle(PostInk.ink) }                            if let count = card.count { Text(count).font(PostType.small).foregroundStyle(PostInk.quiet) }                        }                        .padding(.vertical, 12)                        .accessibilityElement(children: .combine)                    }                    // Cotton not answering is said once, here at the top; the rows keep what the phone holds.                    if let first = answer.firstSync, first.state == "unreached", answer.card?.count != first.line {                        PostNote(text: first.line)                    }                    // The first group is Post's own and needs no heading over it; the shared ones carry theirs.                    ForEach(Array(answer.groups.enumerated()), id: \.element.id) { gi, group in                        if gi > 0, let title = group.title, group.rows.count > 1 || group.rows.first?.title != title {                            PostSection(title: title)                        } else {                            Spacer().frame(height: gi == 0 ? 4 : 18)                        }                        if gi == 0 { PostRule() }                        ForEach(Array(group.rows.enumerated()), id: \.element.id) { index, row in                            rowView(row, last: index == group.rows.count - 1)                        }                    }                } else {                    // The places Post opens, until `mail.you` answers the whole page.                    PostRule().padding(.top, 8)                    PostLinkRow(title: PostWords.line("you.accounts"), id: "post-you-accounts") { open("accounts") }                    PostLinkRow(title: PostWords.line("you.rules"), id: "post-you-rules") { open("rules") }                    PostLinkRow(title: PostWords.line("you.domains"), id: "post-you-domains") { open("domains") }                    PostLinkRow(title: PostWords.line("you.look"), end: look.answer?.line(dark: scheme == .dark), last: true, id: "post-you-look") { open("look") }                    if let line = you?.refusal { PostNote(text: line) }                }            }            .padding(.horizontal, PostInk.side)            .padding(.bottom, 40)        }        .background(PostInk.ground)        .task(id: model.generation) { you = await model.read("mail.you", as: PostYou.self) }        .accessibilityIdentifier("post-you")    }    @ViewBuilder private func rowView(_ row: PostYou.Row, last: Bool) -> some View {        let end = row.id == "look" ? (look.answer?.line(dark: scheme == .dark) ?? row.value) : row.value        if let choices = row.open?.choices, let name = row.open?.name {            // Notifications and Undo send: chosen in place, the row's answer changing under his finger.            Menu {                ForEach(choices) { choice in                    Button { set(name, choice.value) } label: {                        if choice.on { Label(choice.label, systemImage: "checkmark") } else { Text(choice.label) }                    }                }            } label: {                PostLinkRow(title: row.title, end: end, last: last, chevron: false, id: "post-you-\(row.id)") {}                    .allowsHitTesting(false)            }            .accessibilityIdentifier("post-you-\(row.id)")        } else {            let page = row.open?.page ?? row.id            let opens = Self.pages.contains(page)            PostLinkRow(title: row.title, end: end, last: last, chevron: opens, id: "post-you-\(row.id)") { open(page, title: row.title) }                .disabled(!opens)        }    }    /// The pages Post draws today; a row whose page is not drawn yet shows its answer and opens nothing.    private static let pages: Set<String> = ["accounts", "rules", "domains", "look", "privacy", "sync", "storage", "help", "about"]    private func set(_ name: String, _ value: JSONValue) {        Task {            let again = await model.read("mail.set", ["name": .string(name), "value": value], as: PostYou.self)            if again.answer != nil { you = again }        }    }    private func open(_ id: String, title: String = "") {        switch id {        case "accounts": model.push(.accounts)        case "rules": model.push(.rules)        case "domains": model.push(.domains)        case "look": model.push(.look)        case "privacy": model.push(.privacy(title.isEmpty ? PostWords.line("you.privacy") : title))        case "sync", "storage", "help", "about": model.push(.shared(id, title))        default: break        }    }}/// A place whose call answers rows of words: its title, then the rows, or the core's words for why not yet.struct PostCallScreen: View {    struct Rows: Decodable, Equatable, Sendable {        struct Row: Decodable, Equatable, Sendable, Identifiable { var id: String; var title: String; var line: String?; var end: String? }        var title: String?        var line: String?        var rows: [Row]        var empty: String?    }    let model: PostModel    let title: String    let method: String    let id: String    @State private var read: PostRead<Rows>?    var body: some View {        VStack(spacing: 0) {            PostBar(back: PostWords.line("you.title"), onBack: { model.pop() }).padding(.horizontal, PostInk.side)            ScrollView {                VStack(alignment: .leading, spacing: 0) {                    PostTitle(text: read?.answer?.title ?? title)                    switch read {                    case .read(let answer)?:                        if let line = answer.line { PostLead(text: line) }                        if answer.rows.isEmpty, let empty = answer.empty { PostEmpty(line: empty) }                        ForEach(Array(answer.rows.enumerated()), id: \.element.id) { index, row in                            PostLinkRow(title: row.title, line: row.line, end: row.end, last: index == answer.rows.count - 1, id: "\(id)-\(row.id)") {}                        }                    case .refused(let line)?: PostRefused(line: line)                    case nil: EmptyView()                    }                }                .padding(.horizontal, PostInk.side)                .padding(.bottom, 30)            }        }        .background(PostInk.ground)        .task(id: model.generation) { read = await model.read(method, as: Rows.self) }        .accessibilityIdentifier(id)    }}/// SORTING RULES (`mail.rules`): the rules in words, in the order they run, the fallback, and his own word on/// senders, each changeable in place (`mail.verdict {address, who}`, which answers the rules again).struct PostRulesScreen: View {    struct Rules: Decodable, Equatable, Sendable {        struct Exception: Decodable, Equatable, Sendable, Identifiable { var address: String; var name: String; var who: String; var label: String; var id: String { address } }        struct Yours: Decodable, Equatable, Sendable { var title: String; var rows: [Exception] }        struct Choice: Decodable, Equatable, Sendable, Identifiable { var id: String; var label: String }        var title: String        var line: String        var rules: [String]        var fallback: String?        var yours: Yours?        var choices: [Choice]?    }    let model: PostModel    @State private var read: PostRead<Rules>?    @State private var said: String?    var body: some View {        VStack(spacing: 0) {            PostBar(back: PostWords.line("you.title"), onBack: { model.pop() }).padding(.horizontal, PostInk.side)            ScrollView {                VStack(alignment: .leading, spacing: 0) {                    PostTitle(text: read?.answer?.title ?? PostWords.line("rules.title"))                    PostLead(text: read?.answer?.line ?? PostWords.line("rules.line"))                    switch read {                    case .read(let rules)?:                        PostRule().padding(.top, 14)                        ForEach(Array(rules.rules.enumerated()), id: \.offset) { index, rule in                            HStack(alignment: .firstTextBaseline, spacing: 12) {                                Text("\(index + 1)").font(PostType.sans(12, .bold, relativeTo: .caption))                                    .foregroundStyle(PostInk.ink).frame(width: 24, height: 24).overlay(Circle().strokeBorder(PostInk.ink, lineWidth: 1.2))                                Text(rule).font(PostType.sans(16)).foregroundStyle(PostInk.ink).fixedSize(horizontal: false, vertical: true)                                Spacer(minLength: 0)                            }                            .padding(.vertical, 11)                            .overlay(alignment: .bottom) { PostRule() }                            .accessibilityElement(children: .combine)                        }                        PostNote(text: rules.fallback ?? PostWords.line("rules.fallback"))                        if let yours = rules.yours, !yours.rows.isEmpty {                            PostSection(title: yours.title, end: yours.rows.count.formatted())                            ForEach(Array(yours.rows.enumerated()), id: \.element.id) { index, item in                                Menu {                                    ForEach(rules.choices ?? []) { choice in                                        Button(choice.label) { verdict(item.address, choice.id) }                                    }                                } label: {                                    PostLinkRow(title: item.name, line: item.name == item.address ? nil : item.address, end: item.label,                                                last: index == yours.rows.count - 1, chevron: false, id: "post-rule-\(item.address)") {}                                        .allowsHitTesting(false)                                }                            }                        }                        if let said { PostNote(text: said) }                    case .refused(let line)?:                        PostNote(text: PostWords.line("rules.fallback"))                        PostRefused(line: line)                    case nil: EmptyView()                    }                }                .padding(.horizontal, PostInk.side)                .padding(.bottom, 30)            }        }        .background(PostInk.ground)        .task(id: model.generation) { read = await model.read("mail.rules", as: Rules.self) }        .accessibilityIdentifier("post-rules")    }    private func verdict(_ address: String, _ who: String) {        Task {            let again = await model.read("mail.verdict", ["address": .string(address), "who": .string(who)], as: Rules.self)            switch again {            case .read: read = again; said = nil; model.changed()            case .refused(let line): said = line            }        }    }}/// PRIVACY: three promises in three sentences, including the one every mail app should say and few do: email is/// readable on the way./// SYNC, STORAGE, HELP, ABOUT: the pages every Cotton app shares, drawn from the core's answers (`shell.settings`) in/// Post's look. Sync ends with Delete account, as on Android (SharedPages.kt) and in every other Cotton app.struct PostSharedScreen: View {    let model: PostModel    let page: String    let title: String    @State private var home = SettingsHome()    var body: some View {        VStack(spacing: 0) {            PostBar(back: PostWords.line("you.title"), onBack: { model.pop() }).padding(.horizontal, PostInk.side)            ScrollView {                VStack(alignment: .leading, spacing: 14) {                    PostTitle(text: title)                    if let place = SettingsPlace(row: page) {                        SettingsSharedPage(place: place, home: home, core: model.core, look: .post, said: { UIAccessibility.post(notification: .announcement, argument: $0) }) {                            Task { await home.read(model.core) }                        }                    }                    if page == "sync" {                        DeleteAccountPart(core: model.core, look: .post, onDeleted: { model.paths = [:]; model.tab = .mail })                            .padding(.top, 18)                    }                }                .padding(.horizontal, PostInk.side)                .padding(.bottom, 30)            }        }        .background(PostInk.ground)        .task { await home.read(model.core) }        .accessibilityIdentifier("post-\(page)")    }}/// The shared settings parts in Post's ink: quiet headings, plain rows, accent acts, the ink as danger.@MainActorextension SettingsLook {    static var post: SettingsLook {        SettingsLook(            ink: PostInk.ink, quiet: PostInk.quiet, rule: PostInk.rule, ground: PostInk.ground,            body: PostType.sans(16), small: PostType.sans(13),            heading: { words in                AnyView(Text(words).font(PostType.sans(13, .semibold)).foregroundStyle(PostInk.quiet)                    .padding(.top, 10).accessibilityAddTraits(.isHeader))            },            act: { words, id, enabled, tap in                AnyView(Button(action: tap) {                    Text(words).font(PostType.sans(16, .semibold)).foregroundStyle(PostInk.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) {                    HStack {                        Text(words).font(PostType.sans(16)).foregroundStyle(PostInk.ink)                        Spacer()                        if on { Image(systemName: "checkmark").foregroundStyle(PostInk.accent) }                    }                    .frame(minHeight: 44).contentShape(Rectangle())                }                .buttonStyle(.plain).disabled(!enabled).opacity(enabled ? 1 : 0.45)                .accessibilityAddTraits(on ? .isSelected : []).accessibilityIdentifier(id))            },            danger: PostInk.ink,            title: PostType.title        )    }}struct PostPrivacyScreen: View {    let model: PostModel    let title: String    var body: some View {        VStack(spacing: 0) {            PostBar(back: PostWords.line("you.title"), onBack: { model.pop() }).padding(.horizontal, PostInk.side)            ScrollView {                VStack(alignment: .leading, spacing: 14) {                    PostTitle(text: title)                    ForEach(["privacy.sealed", "privacy.way", "privacy.email"], id: \.self) { key in                        Text(PostWords.line(key))                            .font(PostType.sans(16))                            .foregroundStyle(PostInk.ink)                            .fixedSize(horizontal: false, vertical: true)                            .padding(.leading, 12)                            .overlay(alignment: .leading) { Rectangle().fill(PostInk.ink).frame(width: 1.5) }                    }                }                .padding(.horizontal, PostInk.side)                .padding(.bottom, 30)            }        }        .background(PostInk.ground)        .accessibilityIdentifier("post-privacy")    }}/// LOOK: the live preview (the app's own inbox and one open mail), then paper for light and for dark, ink, text and/// size, and Reset. Look changes colours and type only, never layout.struct PostLookPage: View {    let model: PostModel    @State private var look = LookModel.standing("mail")    @State private var asking = false    @State private var said: String?    var body: some View {        VStack(spacing: 0) {            PostBar(back: PostWords.line("you.title"), onBack: { model.pop() }).padding(.horizontal, PostInk.side)            ScrollView {                VStack(alignment: .leading, spacing: 0) {                    if let answer = look.answer {                        PostTitle(text: answer.word("title"))                        LookScreen(choices: LookChoices(answer), words: LookWords(answer), skin: Self.skin, gutter: PostInk.side,                                   choose: { pick in Task { await look.choose(pick, core: model.core); tell() } },                                   reset: { asking = true }) { dark in                            PostLookPreview(answer: answer, dark: dark)                        } more: { EmptyView() }                        .padding(.top, 8)                    }                    if let said { PostNote(text: said) }                }                .padding(.horizontal, PostInk.side)                .padding(.bottom, 40)            }        }        .background(PostInk.ground)        .task { await look.read(model.core) }        .confirmationDialog(look.answer?.word("reset_title") ?? "", isPresented: $asking, titleVisibility: .visible) {            if let answer = look.answer {                Button(answer.word("reset_yes"), role: .destructive) { Task { await look.reset(core: model.core); tell() } }                Button(answer.word("reset_no"), role: .cancel) {}            }        } message: {            if let answer = look.answer { Text(answer.word("reset_ask")) }        }        .accessibilityIdentifier("post-look")    }    private func tell() {        if let refused = look.refused { said = refused; look.refused = nil }    }    @MainActor static var skin: LookSkin {        LookSkin(ground: PostInk.ground, ink: PostInk.ink, quiet: PostInk.quiet, accent: PostInk.ink, onAccent: PostInk.ground, sheet: PostInk.ground, rule: PostInk.rule,                 font: { size, weight in                     PostType.sans(size, weight == .bold ? .bold : weight == .semibold ? .semibold : weight == .medium ? .medium : .regular)                 },                 face: { id, size in PostType.face(id, size: size) })    }}/// The preview: two inbox rows (a person round, a machine square) and one open mail in the reading face, in the paper/// of one appearance and the chosen ink.struct PostLookPreview: View {    let answer: LookAnswer    let dark: Bool    private func colour(_ token: String, _ fallback: Color) -> Color { answer.colour(token, dark: dark) ?? fallback }    var body: some View {        let ink = colour("ink", PostInk.ink), quiet = colour("quiet", PostInk.quiet), rule = colour("rule", PostInk.rule), faint = colour("faint", PostInk.faint)        VStack(alignment: .leading, spacing: 0) {            ForEach(Array((answer.preview?.mail ?? []).enumerated()), id: \.offset) { _, row in                HStack(spacing: 12) {                    let initials = String(row.from.split(separator: " ").prefix(2).compactMap(\.first)).uppercased()                    Text(initials).font(PostType.sans(12, .bold)).foregroundStyle(row.face == "person" ? ink : quiet)                        .frame(width: 30, height: 30)                        .background {                            if row.face == "person" { Circle().strokeBorder(ink, lineWidth: 1.2) }                            else { RoundedRectangle(cornerRadius: 8).strokeBorder(faint, lineWidth: 1.2) }                        }                    VStack(alignment: .leading, spacing: 2) {                        HStack(spacing: 6) {                            if row.unread { Circle().fill(ink).frame(width: 6, height: 6) }                            Text(row.from).font(PostType.sans(16, row.unread ? .semibold : .medium)).foregroundStyle(ink)                        }                        Text("\(row.subject) · \(row.line)").font(PostType.sans(13.5)).foregroundStyle(quiet).lineLimit(1)                    }                    Spacer()                    Text(row.when).font(PostType.sans(13)).foregroundStyle(quiet)                }                .padding(.vertical, 9)                .overlay(alignment: .bottom) { Rectangle().fill(rule).frame(height: 1) }            }            if let letter = answer.preview?.letter {                VStack(alignment: .leading, spacing: 4) {                    Text(letter.subject).font(PostType.serif(20, .medium)).foregroundStyle(ink)                    Text(letter.from).font(PostType.sans(13)).foregroundStyle(quiet)                    Text(letter.text).font(PostType.serif(16)).foregroundStyle(ink).fixedSize(horizontal: false, vertical: true)                    Text(PostWords.line("write.send")).font(PostType.sans(14, .bold)).foregroundStyle(colour("on_accent", PostInk.onAccent))                        .padding(.horizontal, 14).padding(.vertical, 6)                        .background(Capsule().fill(colour("accent", PostInk.accent)))                        .padding(.top, 4)                }                .padding(.top, 12)                .padding(.bottom, 2)            }        }        .padding(.horizontal, 14)        .padding(.top, 4)        .padding(.bottom, 12)        .frame(maxWidth: .infinity, alignment: .leading)        .background(RoundedRectangle(cornerRadius: 18).fill(colour("ground", PostInk.ground)))        .overlay(RoundedRectangle(cornerRadius: 18).strokeBorder(rule, lineWidth: 1))        .accessibilityElement(children: .combine)    }}#endif