Cotton code
308 lines · 15.2 KB · SwiftRaw
// DOMAINS (mail CONTRACT row 15; DECISIONS question 12): his own domains under You. A domain's page says its records// in words, each marked done, checking, next or not right yet, with the record to copy when one is next; Check again;// its addresses (aliases say where they land) with New address and Remove (asked once, with what bounces after);// plus addresses; Anything else at the domain; People, later. Every refusal is the object's own words.// `mail.domains`, `mail.domain`, `mail.domain.add`, `mail.domain.check`, `mail.domain.catch_all`, `mail.address.add`,// `mail.address.remove`, `mail.domain.remove`.#if os(iOS)import CottonKitimport SwiftUIimport UIKitstruct PostDomains: Decodable, Equatable, Sendable {    struct Row: Decodable, Equatable, Sendable, Identifiable { var domain: String; var line: String?; var state: String?; var id: String { domain } }    struct Note: Decodable, Equatable, Sendable { var label: String; var line: String? }    var title: String    var rows: [Row]    var add: String    var server_reads: Note?    var empty: String?}struct PostDomain: Decodable, Equatable, Sendable {    struct Fix: Decodable, Equatable, Sendable { var type: String?; var name: String?; var value: String? }    struct Record: Decodable, Equatable, Sendable, Identifiable { var id: String; var name: String; var line: String?; var state: String; var fix: Fix? }    struct Address: Decodable, Equatable, Sendable, Identifiable { var address: String; var line: String?; var lands: String?; var id: String { address } }    struct Addresses: Decodable, Equatable, Sendable { var title: String; var rows: [Address] }    struct Note: Decodable, Equatable, Sendable { var label: String; var line: String? }    struct CatchAll: Decodable, Equatable, Sendable { var label: String; var on: Bool; var line: String? }    var domain: String    var line: String?    var records: [Record]    var keep_checking: String?    var addresses: Addresses    var new_address: String    var plus: Note?    var catch_all: CatchAll    var people_later: Note?    var server_reads: Note?    /// Remove the domain (`mail.domain.remove`): asked once, saying what bounces after.    var remove: Note?}/// `mail.domain.remove`: the question first; agreed, the domain goes and the list answers.struct PostDomainRemoved: Decodable, Sendable {    var ask: PostAddressRemoved.Ask?}/// `mail.address.remove`: the question first, then the page.struct PostAddressRemoved: Decodable, Sendable {    struct Ask: Decodable, Equatable, Sendable { var title: String; var line: String; var go: String; var cancel: String }    var ask: Ask?    var page: PostDomain?    init(from decoder: Decoder) throws {        enum K: String, CodingKey { case ask }        ask = try decoder.container(keyedBy: K.self).decodeIfPresent(Ask.self, forKey: .ask)        page = ask == nil ? try PostDomain(from: decoder) : nil    }}struct PostDomainsScreen: View {    let model: PostModel    @State private var read: PostRead<PostDomains>?    @State private var adding = false    @State private var name = ""    @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("domain.title"))                    switch read {                    case .read(let answer)?:                        if let empty = answer.empty { PostNote(text: empty) }                        ForEach(Array(answer.rows.enumerated()), id: \.element.id) { index, row in                            PostLinkRow(title: row.domain, line: row.line, last: index == answer.rows.count - 1, id: "post-domain-\(row.domain)") {                                model.push(.domain(row.domain))                            }                        }                        if let said { PostNote(text: said) }                        PostButton(label: answer.add, weight: .go, id: "post-domain-add") { name = ""; adding = true }.padding(.top, 18)                        if let reads = answer.server_reads {                            PostSection(title: reads.label)                            if let line = reads.line { PostNote(text: line) }                        }                    case .refused(let line)?: PostRefused(line: line)                    case nil: EmptyView()                    }                }                .padding(.horizontal, PostInk.side)                .padding(.bottom, 24)            }        }        .background(PostInk.ground)        .task(id: model.generation) { read = await model.read("mail.domains", as: PostDomains.self) }        .alert(read?.answer?.add ?? "", isPresented: $adding) {            TextField(PostWords.line("domain.domain"), text: $name).textInputAutocapitalization(.never).autocorrectionDisabled().keyboardType(.URL)            Button(PostWords.line("write.cancel"), role: .cancel) {}            Button(read?.answer?.add ?? "") {                Task {                    switch await model.read("mail.domain.add", ["domain": .string(name.trimmingCharacters(in: .whitespaces).lowercased())], as: PostDomain.self) {                    case .read(let page): model.changed(); model.push(.domain(page.domain))                    case .refused(let line): said = line                    }                }            }        }        .accessibilityIdentifier("post-domains")    }}struct PostDomainScreen: View {    let model: PostModel    let domain: String    @State private var read: PostRead<PostDomain>?    @State private var said: String?    @State private var naming = false    @State private var local = ""    @State private var asking: (address: String, ask: PostAddressRemoved.Ask)?    @State private var removingDomain: PostAddressRemoved.Ask?    @State private var checking = false    var body: some View {        VStack(spacing: 0) {            PostBar(back: PostWords.line("domain.title"), onBack: { model.pop() }).padding(.horizontal, PostInk.side)            ScrollView {                VStack(alignment: .leading, spacing: 0) {                    switch read {                    case .read(let page)?: content(page)                    case .refused(let line)?: PostRefused(line: line)                    case nil: EmptyView()                    }                }                .padding(.horizontal, PostInk.side)                .padding(.bottom, 24)            }            .refreshable { await check() }        }        .background(PostInk.ground)        .task(id: model.generation) { read = await model.read("mail.domain", ["domain": .string(domain)], as: PostDomain.self) }        // "Leave this, it'll keep checking": while a record is still to check and the page is open, the DNS is asked        // again every 30 seconds.        .task {            while !Task.isCancelled {                try? await Task.sleep(for: .seconds(30))                guard !Task.isCancelled, read?.answer?.records.contains(where: { $0.state != "done" }) == true else { continue }                await check()            }        }        .alert(read?.answer?.new_address ?? "", isPresented: $naming) {            TextField("name@\(domain)", text: $local).textInputAutocapitalization(.never).autocorrectionDisabled().keyboardType(.emailAddress)            Button(PostWords.line("write.cancel"), role: .cancel) {}            Button(read?.answer?.new_address ?? "") { Task { await addAddress() } }        }        .alert(asking?.ask.title ?? "", isPresented: Binding(get: { asking != nil }, set: { if !$0 { asking = nil } })) {            Button(asking?.ask.cancel ?? "", role: .cancel) {}            Button(asking?.ask.go ?? "", role: .destructive) { if let address = asking?.address { Task { await removeAddress(address, sure: true) } } }        } message: { Text(asking?.ask.line ?? "") }        .alert(removingDomain?.title ?? "", isPresented: Binding(get: { removingDomain != nil }, set: { if !$0 { removingDomain = nil } })) {            Button(removingDomain?.cancel ?? "", role: .cancel) {}            Button(removingDomain?.go ?? "", role: .destructive) { Task { await removeDomain(sure: true) } }        } message: { Text(removingDomain?.line ?? "") }        .accessibilityIdentifier("post-domain")    }    @ViewBuilder private func content(_ page: PostDomain) -> some View {        PostTitle(text: page.domain)        if let line = page.line { PostLead(text: line) }        VStack(alignment: .leading, spacing: 0) {            ForEach(Array(page.records.enumerated()), id: \.element.id) { index, record in                recordRow(record, last: index == page.records.count - 1)            }        }        .padding(.top, 10)        if let keep = page.keep_checking { PostNote(text: keep) }        if let said { PostNote(text: said) }        PostSection(title: page.addresses.title)        ForEach(Array(page.addresses.rows.enumerated()), id: \.element.id) { index, address in            HStack(spacing: 10) {                VStack(alignment: .leading, spacing: 2) {                    Text(address.address).font(PostType.rowRead).foregroundStyle(PostInk.ink).lineLimit(2)                    if let line = address.line { Text(line).font(PostType.small).foregroundStyle(PostInk.quiet) }                }                Spacer()                Button { Task { await removeAddress(address.address, sure: false) } } label: {                    Image(systemName: "minus.circle").font(.system(size: 18, weight: .light)).foregroundStyle(PostInk.quiet).frame(width: 44, height: 44)                }                .accessibilityLabel(Text(PostWords.line("domain.remove_address", ["address": address.address])))                .accessibilityIdentifier("post-address-remove-\(address.address)")            }            .padding(.vertical, 6)            .overlay(alignment: .bottom) { if index < page.addresses.rows.count - 1 { PostRule() } }        }        PostButton(label: page.new_address, weight: .outline, id: "post-address-add") { local = ""; naming = true }.padding(.top, 12)        if let plus = page.plus {            PostSection(title: plus.label)            if let line = plus.line { PostNote(text: line) }        }        Toggle(isOn: Binding(get: { page.catch_all.on }, set: { on in Task { await catchAll(on) } })) {            VStack(alignment: .leading, spacing: 2) {                Text(page.catch_all.label).font(PostType.rowRead).foregroundStyle(PostInk.ink)                if let line = page.catch_all.line { Text(line).font(PostType.small).foregroundStyle(PostInk.quiet) }            }        }        .tint(PostInk.accent)        .padding(.top, 18)        .accessibilityIdentifier("post-domain-catch-all")        if let later = page.people_later {            PostSection(title: later.label)            if let line = later.line { PostNote(text: line) }        }        if let reads = page.server_reads {            PostSection(title: reads.label)            if let line = reads.line { PostNote(text: line) }        }        if let remove = page.remove {            PostButton(label: remove.label, weight: .quiet, id: "post-domain-remove") { Task { await removeDomain(sure: false) } }                .padding(.top, 24)        }    }    /// A record: its name and state, its line, and when it is next the value to copy into the DNS.    private func recordRow(_ record: PostDomain.Record, last: Bool) -> some View {        VStack(alignment: .leading, spacing: 4) {            HStack {                Text(record.name).font(PostType.sans(15.5, .semibold)).foregroundStyle(PostInk.ink)                Spacer()                Text(PostWords.line("domain.state.\(record.state)")).font(PostType.small)                    .foregroundStyle(record.state == "done" ? PostInk.quiet : PostInk.ink)            }            if let line = record.line, !line.trimmingCharacters(in: .whitespaces).isEmpty, record.fix == nil {                Text(line).font(PostType.small).foregroundStyle(PostInk.quiet).fixedSize(horizontal: false, vertical: true)            }            if let fix = record.fix {                ForEach([fix.type, fix.name, fix.value].compactMap { $0 }, id: \.self) { part in                    Button { UIPasteboard.general.string = part } label: {                        HStack {                            Text(part).font(.system(size: 14, design: .monospaced)).foregroundStyle(PostInk.ink).lineLimit(3).multilineTextAlignment(.leading)                            Spacer(minLength: 8)                            Image(systemName: "doc.on.doc").font(.system(size: 13)).foregroundStyle(PostInk.quiet)                        }                        .padding(.vertical, 6)                        .contentShape(Rectangle())                    }                    .buttonStyle(PostPressStyle())                }            }        }        .padding(.vertical, 10)        .overlay(alignment: .bottom) { if !last { PostRule() } }        .accessibilityElement(children: .contain)        .accessibilityIdentifier("post-record-\(record.id)")    }    private func check() async {        checking = true        defer { checking = false }        switch await model.read("mail.domain.check", ["domain": .string(domain)], as: PostDomain.self) {        case .read(let page): read = .read(page); said = nil        case .refused(let line): said = line        }    }    private func catchAll(_ on: Bool) async {        switch await model.read("mail.domain.catch_all", ["domain": .string(domain), "on": .bool(on)], as: PostDomain.self) {        case .read(let page): read = .read(page)        case .refused(let line): said = line        }    }    private func addAddress() async {        let typed = local.trimmingCharacters(in: .whitespaces).lowercased()        let address = typed.contains("@") ? typed : "\(typed)@\(domain)"        switch await model.read("mail.address.add", ["address": .string(address)], as: PostDomain.self) {        case .read(let page): read = .read(page); model.changed()        case .refused(let line): said = line        }    }    /// Remove asks once (what bounces after, that mail here stays); agreed, the domain goes and Domains shows the list.    private func removeDomain(sure: Bool) async {        var request: [String: JSONValue] = ["domain": .string(domain)]        if sure { request["sure"] = .bool(true) }        switch await model.read("mail.domain.remove", request, as: PostDomainRemoved.self) {        case .read(let done):            if let ask = done.ask {                removingDomain = ask            } else {                model.changed()                model.pop()            }        case .refused(let line): said = line        }    }    private func removeAddress(_ address: String, sure: Bool) async {        var request: [String: JSONValue] = ["address": .string(address)]        if sure { request["sure"] = .bool(true) }        switch await model.read("mail.address.remove", request, as: PostAddressRemoved.self) {        case .read(let done):            if let ask = done.ask { asking = (address, ask) } else if let page = done.page { read = .read(page); model.changed() }        case .refused(let line): said = line        }    }}#endif