Cotton code
514 lines · 24.2 KB · SwiftRaw
// THE WRITER (mail.html "Writing, replying, and saying what happened"): New, Reply, Reply all and Forward, all in// Post. From sits first, chosen by the core (the address he last used with that person, a reply from the address it// came to) and says why; To; Cc and Bcc folded into one line until tapped; Subject; the words in the reading face; the// quoted mail folded; attachments as rows with a cross, a file or a photo; the draft saves as he types and says so.// After Send the app says exactly where the mail is: sending in 5 seconds with Undo, waiting, sending, sent (the// franking mark draws itself when it truly leaves), or not sent and why, with Retry. `mail.compose`, `mail.save`,// `mail.discard`, `mail.attach`, `mail.unattach`, `mail.send`, `mail.unsend`, `mail.sending` (CONTRACT row 10).#if os(iOS)import CottonKitimport PhotosUIimport SwiftUIimport UniformTypeIdentifiers/// One address field's value as the core answers it: a line of addresses, or a list.struct PostAddresses: Decodable, Equatable, Sendable {    var line: String    init(from decoder: Decoder) throws {        let c = try decoder.singleValueContainer()        if let one = try? c.decode(String.self) {            line = one        } else if let many = try? c.decode([String].self) {            line = many.joined(separator: ", ")        } else {            line = ""        }    }    init(_ line: String) { self.line = line }}/// `mail.compose`: the draft as the core formed it. A new mail has no `draft` until its first save.struct PostDraft: Decodable, Equatable, Sendable {    struct Choice: Decodable, Equatable, Sendable, Identifiable { var address: String; var label: String?; var id: String { address } }    struct From: Decodable, Equatable, Sendable { var address: String; var choices: [Choice]?; var why: String? }    /// A file on the draft; a forward's files carry the mail and index they come from until the first save.    struct Attached: Decodable, Equatable, Sendable, Identifiable {        struct Carry: Decodable, Equatable, Sendable { var email: String; var index: Int }        var index: Int        var name: String        var size: String?        var carry: Carry?        var id: Int { index }    }    var draft: String?    var mode: String?    var title: String?    var from: From    var to: PostAddresses?    var cc: PostAddresses?    var bcc: PostAddresses?    var subject: String?    var body: String?    /// The quoted mail as text, its first line the fold's label ("On 25 Nov, Ada wrote:").    var quoted: String?    var thread: String?    var reply_to: String?    var attachments: [Attached]?    var signature: String?    var words: [String: String]?    var undo_seconds: Int?    /// Opened while it was held: taken back, an ordinary draft again, and said so (UNDO SEND 5).    var said: String?    func word(_ key: String) -> String { words?[key] ?? PostWords.line("write.\(key)") }    var quoteLabel: String? { quoted.flatMap { $0.split(separator: "\n", maxSplits: 1).first.map(String.init) } }    var quoteText: String? { quoted.flatMap { q in q.split(separator: "\n", maxSplits: 1).dropFirst().first.map(String.init) } }}/// `mail.save`: the draft's id, and the word the bar says.struct PostSaved: Decodable, Equatable, Sendable {    struct Said: Decodable, Equatable, Sendable { var said: String? }    var draft: String    var said: String?}/// `mail.attach` and `mail.unattach`: the draft's files now.struct PostAttachedFiles: Decodable, Equatable, Sendable { var draft: String; var attachments: [PostDraft.Attached] }/// A tool at the writer's foot: its mark over its word.struct PostTool: View {    let symbol: String    let label: String    @Environment(\.dynamicTypeSize) private var textSize    var body: some View {        VStack(spacing: 3) {            Image(systemName: symbol).font(.system(size: textSize.isAccessibilitySize ? 22 : 17, weight: .light))            // At the accessibility sizes the mark stands alone, as the system's toolbars do; the word is still what            // VoiceOver says and what a long press shows (the walk, 26 Nov 2026: "Atta…").            if !textSize.isAccessibilitySize {                Text(label).font(PostType.sans(12.5, relativeTo: .caption)).lineLimit(1).minimumScaleFactor(0.8)            }        }        .foregroundStyle(PostInk.ink)        .frame(minWidth: 44, minHeight: 44)        .accessibilityElement(children: .ignore)        .accessibilityLabel(Text(label))        .accessibilityShowsLargeContentViewer { Image(systemName: symbol); Text(label) }    }}/// `mail.send` and `mail.sending`: where the mail is now.struct PostSending: Decodable, Equatable, Sendable {    var state: String    var line: String    var undo: String?    var retry: String?    var fix: String?}struct PostWritePage: View {    let model: PostModel    let mode: String    let thread: String?    let email: String?    let draft: String?    @Environment(\.dynamicTypeSize) private var textSize    @State private var formed: PostRead<PostDraft>?    @State private var from = ""    @State private var to = ""    @State private var cc = ""    @State private var bcc = ""    @State private var subject = ""    @State private var words = ""    @State private var copies = false    @State private var quoteOpen = false    @State private var choosingFrom = false    @State private var attaching = false    @State private var photo: PhotosPickerItem?    @State private var saved: String?    @State private var said: String?    /// The act a refusal offers (Send with no account: Add an account).    @State private var addAccount: String?    @State private var sending: PostSending?    /// Send tapped: from then no autosave starts or lands (UNDO SEND 3: one landing after Send took the hold back).    @State private var sendTapped = false    /// The autosave on its way, which Send waits out so the hold never takes older words (UNDO SEND 4).    @State private var saving: Task<String?, Never>?    /// Retry is offered 2 seconds after a send ended, never at once (see `sendingBlock`).    @State private var retryOffered = false    @State private var attachments: [PostDraft.Attached] = []    /// The draft's id: the one opened, or the one the first save made.    @State private var draftID: String?    /// The fields as compose formed them, to tell a typed change from the form arriving.    @State private var untouched = ""    private var typed: String { [from, to, cc, bcc, subject, words].joined(separator: "\u{1F}") }    var body: some View {        VStack(spacing: 0) {            bar.padding(.horizontal, PostInk.side)            ScrollView {                VStack(alignment: .leading, spacing: 0) {                    if let sending { sendingBlock(sending) }                    switch formed {                    case .read(let draft)?: fields(draft)                    case .refused(let line)?: PostRefused(line: line)                    case nil: EmptyView()                    }                    if let said { PostNote(text: said) }                    if let addAccount {                        PostWordButton(label: addAccount, id: "post-write-add-account") {                            model.sheet = nil                            model.tab = .you                            model.paths[.you] = [.accounts]                        }                    }                }                .padding(.horizontal, PostInk.side)                .padding(.bottom, 24)            }            .scrollDismissesKeyboard(.interactively)            if formed?.answer != nil { tools.padding(.horizontal, PostInk.side) }        }        .background(PostInk.ground)        .task { await form() }        .task(id: "\(from)|\(to)|\(cc)|\(bcc)|\(subject)|\(words)") {            // The draft saves as he types, a moment after he stops, and says so in the bar.            try? await Task.sleep(for: .milliseconds(900))            // Nothing typed yet (as compose formed it): nothing to save, so a mail opened and left makes no draft            // (the walk, 26 Nov 2026: a blank New mail said "Draft saved" at once).            guard !Task.isCancelled, formed?.answer != nil, sending == nil, !sendTapped, typed != untouched else { return }            let autosave = Task { await save() }            saving = autosave            _ = await autosave.value        }        .fileImporter(isPresented: $attaching, allowedContentTypes: [.item], allowsMultipleSelection: true) { result in            guard case .success(let urls) = result else { return }            Task { for url in urls { await attach(url) } }        }        .onChange(of: photo) { _, item in            guard let item else { return }            Task {                if let data = try? await item.loadTransferable(type: Data.self) {                    let url = URL(fileURLWithPath: PostFilesDir.path).appendingPathComponent("photo-\(UUID().uuidString.prefix(8)).jpg")                    try? data.write(to: url)                    await attach(url)                }                photo = nil            }        }        .confirmationDialog(PostWords.line("write.from"), isPresented: $choosingFrom, titleVisibility: .visible) {            ForEach(formed?.answer?.from.choices ?? []) { choice in                Button(choice.label ?? choice.address) { from = choice.address }            }        }        .accessibilityIdentifier("post-write-page")    }    /// Cancel, the draft's word, and Send in the accent.    private var bar: some View {        HStack(spacing: 10) {            PostWordButton(label: formed?.answer?.word("cancel") ?? PostWords.line("write.cancel"), accent: false, id: "post-write-cancel") { model.sheet = nil }            Spacer()            if let saved { Text(saved).font(PostType.small).foregroundStyle(PostInk.quiet).lineLimit(1) }            Spacer()            Button { Task { await send() } } label: {                Text(formed?.answer?.word("send") ?? PostWords.line("write.send"))                    .font(PostType.sans(15.5, .bold))                    .foregroundStyle(PostInk.onAccent)                    .padding(.horizontal, 16)                    .frame(minHeight: 36)                    .background(RoundedRectangle(cornerRadius: 12, style: .continuous).fill(PostInk.accent))            }            .buttonStyle(PostPressStyle())            .disabled(formed?.answer == nil || sending != nil)            .opacity(formed?.answer == nil ? 0.45 : 1)            .accessibilityIdentifier("post-write-send")        }        .frame(minHeight: 52)    }    @ViewBuilder private func fields(_ draft: PostDraft) -> some View {        Button { if (draft.from.choices?.count ?? 0) > 1 { choosingFrom = true } } label: {            VStack(alignment: .leading, spacing: 2) {                labelled {                    Text(draft.word("from")).font(PostType.small).foregroundStyle(PostInk.quiet).frame(width: big ? nil : 56, alignment: .leading)                } value: {                    Text(from).font(PostType.sans(16)).foregroundStyle(PostInk.ink).lineLimit(big ? 2 : 1)                    if (draft.from.choices?.count ?? 0) > 1 { Image(systemName: "chevron.down").font(.system(size: 12)).foregroundStyle(PostInk.quiet) }                }                if let why = draft.from.why { Text(why).font(PostType.small).foregroundStyle(PostInk.quiet).padding(.leading, big ? 0 : 66) }            }            .padding(.vertical, 12)            .contentShape(Rectangle())        }        .buttonStyle(PostPressStyle())        .accessibilityIdentifier("post-write-from")        PostRule()        field(draft.word("to"), text: $to, id: "post-write-to", keyboard: .emailAddress)        if copies {            field(draft.word("cc"), text: $cc, id: "post-write-cc", keyboard: .emailAddress)            field(draft.word("bcc"), text: $bcc, id: "post-write-bcc", keyboard: .emailAddress)        } else {            Button { copies = true } label: {                Text(draft.word("cc_bcc")).font(PostType.small).foregroundStyle(PostInk.quiet)                    .frame(maxWidth: .infinity, minHeight: 44, alignment: .leading).contentShape(Rectangle())            }            .buttonStyle(PostPressStyle())            .accessibilityIdentifier("post-write-copies")            PostRule()        }        field(draft.word("subject"), text: $subject, id: "post-write-subject", keyboard: .default, bold: true)        TextField("", text: $words, prompt: Text(draft.word("body")).foregroundStyle(PostInk.faint), axis: .vertical)            .font(PostType.letter)            .foregroundStyle(PostInk.ink)            .lineSpacing(5)            .lineLimit(6...)            .padding(.vertical, 14)            .accessibilityIdentifier("post-write-body")        if let label = draft.quoteLabel {            Button { quoteOpen.toggle() } label: {                Text(label).font(PostType.sans(14)).foregroundStyle(PostInk.quiet).lineLimit(2)                    .padding(.horizontal, 10).padding(.vertical, 5)                    .overlay(Capsule().strokeBorder(PostInk.rule, lineWidth: 1))            }            .buttonStyle(PostPressStyle())            .accessibilityIdentifier("post-write-quoted")            if quoteOpen, let text = draft.quoteText {                Text(text).font(PostType.serif(16)).foregroundStyle(PostInk.quiet).fixedSize(horizontal: false, vertical: true)                    .padding(.leading, 12).padding(.top, 8)                    .overlay(alignment: .leading) { Rectangle().fill(PostInk.rule).frame(width: 1.5) }            }        }        ForEach(attachments) { file in            HStack(spacing: 12) {                PostFileMark(name: file.name)                VStack(alignment: .leading, spacing: 2) {                    Text(file.name).font(PostType.sans(15.5, .bold)).foregroundStyle(PostInk.ink).lineLimit(1)                    if let size = file.size { Text(size).font(PostType.small).foregroundStyle(PostInk.quiet) }                }                Spacer()                Button { Task { await unattach(file) } } label: {                    Image(systemName: "xmark").font(.system(size: 14)).foregroundStyle(PostInk.ink).frame(width: 44, height: 44)                }                .accessibilityLabel(Text(PostWords.line("write.remove_file", ["name": file.name])))            }            .padding(.vertical, 6)            .overlay(alignment: .top) { PostRule() }        }    }    /// A field's label beside its value at ordinary sizes; above it at the accessibility sizes, where a narrow    /// label column broke "Subject" a letter at a time (the walk, 26 Nov 2026).    private func labelled<L: View, V: View>(@ViewBuilder _ label: () -> L, @ViewBuilder value: () -> V) -> some View {        let layout = big ? AnyLayout(VStackLayout(alignment: .leading, spacing: 4)) : AnyLayout(HStackLayout(spacing: 10))        return layout {            label()            HStack(spacing: 6) { value(); Spacer(minLength: 0) }        }        .padding(.vertical, big ? 8 : 0)    }    private var big: Bool { textSize.isAccessibilitySize }    private func field(_ label: String, text: Binding<String>, id: String, keyboard: UIKeyboardType, bold: Bool = false) -> some View {        VStack(spacing: 0) {            labelled {                Text(label).font(PostType.small).foregroundStyle(PostInk.quiet).frame(width: big ? nil : 56, alignment: .leading)            } value: {                TextField("", text: text)                    .font(PostType.sans(16, bold ? .semibold : .regular))                    .foregroundStyle(PostInk.ink)                    .keyboardType(keyboard)                    .textInputAutocapitalization(keyboard == .emailAddress ? .never : .sentences)                    .autocorrectionDisabled(keyboard == .emailAddress)                    .accessibilityLabel(Text(label))                    .accessibilityIdentifier(id)            }            .frame(minHeight: 46)            PostRule()        }    }    /// File and Photo at the foot.    private var tools: some View {        VStack(spacing: 0) {            PostRule()            HStack(spacing: 24) {                Button { attaching = true } label: { PostTool(symbol: "paperclip", label: PostWords.line("write.attach")) }                    .buttonStyle(PostPressStyle())                    .accessibilityIdentifier("post-write-file")                PhotosPicker(selection: $photo, matching: .images) { PostTool(symbol: "photo", label: PostWords.line("write.photo")) }                    .accessibilityIdentifier("post-write-photo")                Spacer()                Button { Task { await discard() } } label: { PostTool(symbol: "trash", label: formed?.answer?.word("discard") ?? PostWords.line("write.discard")) }                    .buttonStyle(PostPressStyle())                    .accessibilityIdentifier("post-write-discard")            }            .padding(.vertical, 6)        }    }    /// Where the mail is, once Send is tapped: each state said once, in words.    private func sendingBlock(_ state: PostSending) -> some View {        VStack(alignment: .leading, spacing: 6) {            HStack(alignment: .center, spacing: 10) {                if state.state == "sent" { PostFranking(width: 34, draws: true) }                Text(state.line).font(PostType.sans(16, .bold)).foregroundStyle(PostInk.ink).fixedSize(horizontal: false, vertical: true)                Spacer()                if let undo = state.undo {                    PostWordButton(label: undo, id: "post-send-undo") { Task { await unsend() } }                }            }            if let fix = state.fix { Text(fix).font(PostType.small).foregroundStyle(PostInk.quiet).fixedSize(horizontal: false, vertical: true) }            // Retry never stands where Undo stood: its own line under the words, at the leading edge, offered 2 seconds            // after the send ended, so nothing can be tapped in Undo's place meanwhile. The Undo re-walk, 27 Nov 2026:            // Retry was drawn exactly where Undo had been, and a tap meant for a late Undo sent the mail again.            if let retry = state.retry, retryOffered {                PostWordButton(label: retry, id: "post-send-retry") { Task { await send() } }            }        }        .task(id: state.retry != nil) {            retryOffered = false            guard state.retry != nil else { return }            try? await Task.sleep(for: .seconds(2))            if !Task.isCancelled { retryOffered = true }        }        .padding(.vertical, 12)        .overlay(alignment: .bottom) { PostRule() }        .accessibilityElement(children: .combine)        .accessibilityLabel(Text(state.state == "sent" ? "\(PostWords.line("a11y.franked")), \(state.line)" : state.line))        .accessibilityIdentifier("post-sending")    }    // ── the core ───────────────────────────────────────────────────────    private func form() async {        var request: [String: JSONValue] = ["mode": .string(mode)]        if let thread { request["thread"] = .string(thread) }        if let email { request["email"] = .string(email) }        if let draft { request["draft"] = .string(draft) }        let read = await model.read("mail.compose", request, as: PostDraft.self)        formed = read        guard let d = read.answer else { return }        draftID = d.draft ?? draft        from = d.from.address        to = d.to?.line ?? ""        cc = d.cc?.line ?? ""        bcc = d.bcc?.line ?? ""        copies = !cc.isEmpty || !bcc.isEmpty        subject = d.subject ?? ""        words = d.body ?? ""        attachments = d.attachments ?? []        untouched = typed        if let line = d.said { saved = line }    }    /// What a save sends: the fields, and on the first save of a reply or forward what ties it to its mail.    private var request: [String: JSONValue] {        var r: [String: JSONValue] = ["from": .string(from), "to": .string(to), "cc": .string(cc), "bcc": .string(bcc),                                      "subject": .string(subject), "body": .string(words)]        if let draftID {            r["draft"] = .string(draftID)        } else if let d = formed?.answer {            r["mode"] = .string(d.mode ?? mode)            if let thread = d.thread { r["thread"] = .string(thread) }            if let reply = d.reply_to { r["reply_to"] = .string(reply) }            if let quoted = d.quoted { r["quoted"] = .string(quoted) }        }        let carried = attachments.compactMap(\.carry)        if !carried.isEmpty {            r["carry"] = .array(carried.map { .object(["email": .string($0.email), "index": .number(Double($0.index))]) })        }        return r    }    @discardableResult private func save() async -> String? {        switch await model.read("mail.save", request, as: PostSaved.self) {        case .read(let done):            if draftID == nil { draftID = done.draft; model.changed() }            attachments = attachments.map { var a = $0; a.carry = nil; return a }            saved = done.said ?? formed?.answer?.word("saved")            return done.draft        case .refused(let line):            said = line            return nil        }    }    private func attach(_ url: URL) async {        var made = draftID        if made == nil { made = await save() }        guard let draft = made else { return }        let scoped = url.startAccessingSecurityScopedResource()        defer { if scoped { url.stopAccessingSecurityScopedResource() } }        switch await model.read("mail.attach", ["draft": .string(draft), "path": .string(url.path), "name": .string(url.lastPathComponent)], as: PostAttachedFiles.self) {        case .read(let d): attachments = d.attachments        case .refused(let line): said = line        }    }    private func unattach(_ file: PostDraft.Attached) async {        guard let draft = draftID else { return }        switch await model.read("mail.unattach", ["draft": .string(draft), "index": .number(Double(file.index))], as: PostAttachedFiles.self) {        case .read(let d): attachments = d.attachments        case .refused(let line): said = line        }    }    /// Discard: the draft and its files go, and the writer closes.    private func discard() async {        if let draftID {            if case .refused(let line) = await model.read("mail.discard", ["draft": .string(draftID)], as: PostSaved.Said.self) {                said = line                return            }            model.changed()        }        model.sheet = nil    }    /// Send: saved first, then held for the Undo time, then sent by the account's way; the state is read until the    /// mail has left or said why not.    private func send() async {        said = nil        addAccount = nil        sendTapped = true        defer { sendTapped = false }        _ = await saving?.value        guard let draft = await save() else { return }        switch await model.read("mail.send", ["draft": .string(draft)], as: PostSending.self) {        case .read(let state):            sending = state            await follow(draft)        case .refused(let line):            said = line            // No account to send from: the refusal offers Add an account, and the draft stays saved.            if let refusal = model.lastRefusal, refusal.code == "no_sender", refusal.details?["act"]?["method"]?.string == "mail.account.plan" {                addAccount = refusal.details?["act"]?["label"]?.string            }        }    }    private func follow(_ draft: String) async {        for _ in 0..<120 {            guard let state = sending, ["holding", "waiting", "sending"].contains(state.state) else { break }            try? await Task.sleep(for: .seconds(1))            if case .read(let now) = await model.read("mail.sending", ["draft": .string(draft)], as: PostSending.self) { sending = now }        }        if sending?.state == "sent" {            model.changed()            try? await Task.sleep(for: .seconds(2))            model.sheet = nil        }    }    private func unsend() async {        guard let draft = draftID else { return }        switch await model.read("mail.unsend", ["draft": .string(draft)], as: PostSending.self) {        case .read(let state): sending = state.state == "holding" ? state : nil; saved = state.line        case .refused(let line): said = line        }    }}#endif