// POST'S MODEL: where Post stands (the tab, each tab's pushed screens, the side page and the inbox it narrowed to, the // page risen over the app) and its one way to the core. It decides nothing: every list, word and act is the core's // (`mail.*`), and a refusal comes back in the core's words for the screen to say where it stands. #if os(iOS) import CottonKit import CottonMailbox import SwiftUI enum PostTab: String, CaseIterable, Sendable { case mail, senders, files, you } /// A screen pushed over a tab's first screen. enum PostRoute: Hashable, Sendable { /// A group, the Inbox, or a place from the side page (`mail.list {place}`). case list(String) case thread(String) case sender(String) /// The shared blocked list. case blocked case look case accounts /// Adding an account of this kind (gmail, icloud, fastmail, yahoo, imap, domain). case accountAdd(String) /// How mail arrives, for one account. case account(String) case domains case domain(String) case rules /// Privacy, under the title You's row gave it. case privacy(String) /// A page every Cotton app shares (Sync, Storage, Help, About), under the title You's row gave it; Sync ends with /// Delete account (Apple's rule: an app that makes accounts deletes them in the app). case shared(String, String) } /// A page risen over the whole app. enum PostSheet: Identifiable, Equatable, Sendable { /// The writer: `mail.compose {mode, thread?, email?, draft?}`. case write(mode: String, thread: String?, email: String?, draft: String?) case search /// An attachment, opened in Post; Back names where it was opened from (the thread's subject, Files). case file(path: String, name: String, back: String) /// A link in a mail, read in Post's own reader, which keeps nothing; Back names the thread. case reader(URL, back: String) var id: String { switch self { case .write(let mode, let thread, let email, let draft): "write/\(mode)/\(thread ?? "")/\(email ?? "")/\(draft ?? "")" case .search: "search" case .file(let path, _, _): "file/\(path)" case .reader(let url, _): "reader/\(url.absoluteString)" } } } @MainActor @Observable final class PostModel { @ObservationIgnored let core: any CottonCalling var tab: PostTab = .mail var paths: [PostTab: [PostRoute]] = [:] var sheet: PostSheet? /// The last refusal the core gave, with its details (a refusal that offers an act, as Send with no account does). @ObservationIgnored private(set) var lastRefusal: CottonCallError? /// The inbox the side page narrowed Mail to (its address, as the mail names the account it came to); nil is All /// inboxes. var account: String? /// Its title on the bar ("All inboxes" until one is chosen). var accountTitle: String? /// The side page is open, or going there; a change springs it the rest of the way. var sideOpen = false { didSet { if sideOpen != oldValue { drawer.go(sideOpen) } } } let drawer = NotesDrawer() /// Bumped when anything Post shows may have changed (an act, a sync from another device): every screen reads again. var generation = 0 /// The phone's network, for the offline line and an attachment's fetch. var online = true /// A round of This phone fetches is running. var fetching = false init(core: any CottonCalling) { self.core = core } // ── where it stands ──────────────────────────────────────────────── func push(_ route: PostRoute) { paths[tab, default: []].append(route) } func pop() { guard !(paths[tab]?.isEmpty ?? true) else { return } paths[tab]?.removeLast() } func changed() { generation += 1 } /// The side page's last answer, held here and asked at launch, so the page draws its rows the moment it slides in /// (the owner's bug on Post build 2: with 86,000 mails mid-sync the page was made on each open and asked only then, /// and stood empty 1 to 2 seconds while the core counted). var side: PostRead? /// The side page read again: the rows alone first when none are held (`counts: false` counts no mail), then the /// whole answer with its counts and labels. A refusal never takes away rows already standing. func readSide() async { if side == nil, case .read(let rows) = await read("mail.side", ["counts": .bool(false)], as: PostSide.self), side == nil { side = .read(rows) } let whole = await read("mail.side", as: PostSide.self) if case .refused = whole, case .read? = side { return } side = whole } /// The side page let go of: a tap (no speed) closes it; a drag goes where it was let go. func letGoOfSide(_ speed: CGFloat?) { guard let speed else { sideOpen = false return } let open = drawer.release(speed) if sideOpen != open { sideOpen = open } else { drawer.go(open) } } /// A row of the side page: an inbox narrows Mail to it; a place opens over Mail's first screen. func chooseSide(inbox id: String?, title: String?) { account = id == "all" ? nil : title?.lowercased() accountTitle = id == "all" ? nil : title paths[.mail] = [] tab = .mail sideOpen = false changed() } func chooseSide(place: String) { paths[.mail] = [.list(place)] tab = .mail sideOpen = false } // ── the core ─────────────────────────────────────────────────────── /// One answer; a refusal comes back in the core's words. func read(_ method: String, _ request: [String: JSONValue] = [:], as type: Answer.Type = Answer.self) async -> PostRead { do { return .read(try await core.call(method, JSONValue.object(request), as: type)) } catch let error as CottonCallError { Log.write("post: \(method) refused — \(error.code)") lastRefusal = error return .refused(error.message) } catch { Log.write("post: \(method) did not read — \(error)") return .refused(PostWords.line("fail.offline")) } } /// An act on mail: its after-state, which the screen keeps standing until he leaves it. Every list reads again. func act(_ method: String, _ request: [String: JSONValue]) async -> PostRead { let done = await read(method, request, as: PostAfter.self) if done.answer != nil { changed() } return done } /// `mail.act` on chosen mails: read, unread, archive, delete, restore. func act(_ act: String, emails: [String]) async -> PostRead { await self.act("mail.act", ["emails": .array(emails.map(JSONValue.string)), "act": .string(act)]) } /// `mail.act` on a whole conversation. func act(_ act: String, thread: String) async -> PostRead { await self.act("mail.act", ["thread": .string(thread), "act": .string(act)]) } /// Archive in one tap: every mail of the scope in the Inbox now (owner, 25 Nov 2026). func archive(scope: String, key: String? = nil, emails: [String] = []) async -> PostRead { var request: [String: JSONValue] = ["scope": .string(scope)] if let key { request["key"] = .string(key) } if !emails.isEmpty { request["emails"] = .array(emails.map(JSONValue.string)) } return await act("mail.archive", request) } func undo(_ after: PostAfter) async -> PostRead { await act("mail.undo", ["after": .string(after.after)]) } /// The same after-state, its mailbox line read again. func again(_ after: PostAfter) async -> PostAfter? { await read("mail.after", ["after": .string(after.after)], as: PostAfter.self).answer } /// The request's account, when the side page narrowed Mail to one. var accountRequest: [String: JSONValue] { account.map { ["account": .string($0)] } ?? [:] } } #endif