Cotton code
607 lines · 25.5 KB · SwiftRaw
// Home's page, as a READER of the core's answer (`shell.today`; the shell// boundary, 7 Nov 2026): the deck, the bands' words, the notices, the tools'// arrangement and a failed read's line are the core's. This model holds the// answer per database (a switch draws the database's kept page in the frame// that turns it), asks again when the core says so — a data event of a family// the answer names, the core's own `{phase: home, stage: today}` after a read// that failed, the shown copy arriving — and hands a Done for you receipt's// Undo to the core (`shell.undo`). It decides nothing it draws.//// What stays here is the platform's: handing an exported file to the OS// (`FileSharing`), and the serving Mac's backup, a round trip Home's page// never waits on.import CottonKitimport CottonValuesimport Foundation#if canImport(AppKit)import AppKit#endif#if canImport(UIKit)import UIKit#endif/// Handing a file to the OS — the export's ONE platform call.////// A seam rather than a direct `UIActivityViewController`, for the reason every/// other seam in this app is one: the model is what a test drives, and a test/// that had to present a view controller could not assert the thing that/// matters — that the path the crate wrote is the path the person was offered.@MainActorprotocol FileSharing {    /// Present the share sheet over `url` and answer when it closes.    ///    /// **It answers when the sheet closes**: the share is awaited and only then    /// is the receipt shown, so "3 records exported" lands on the screen the    /// person comes back to rather than under a sheet they never saw it behind.    func share(title: String, url: URL) async}/// The system share sheet.#if os(iOS)struct SystemShareSheet: FileSharing {    public init() {}    public func share(title: String, url: URL) async {        guard let top = SystemShareSheet.topViewController() else { return }        let sheet = UIActivityViewController(            activityItems: [ExportActivityItem(url: url, subject: title)],            applicationActivities: nil        )        // An iPad presents this as a popover and CRASHES without an anchor.        // Centred on the presenting view, with a zero-size rect: there is no        // one control this came from — the button that started it is behind a        // second of work.        if let popover = sheet.popoverPresentationController {            popover.sourceView = top.view            popover.sourceRect = CGRect(                x: top.view.bounds.midX,                y: top.view.bounds.midY,                width: 0,                height: 0            )            popover.permittedArrowDirections = []        }        await withCheckedContinuation { (continuation: CheckedContinuation<Void, Never>) in            sheet.completionWithItemsHandler = { _, _, _, _ in continuation.resume() }            top.present(sheet, animated: true)        }    }    /// The frontmost scene's topmost presented controller. `nil` when there is    /// no foreground window at all, which is a share nobody could have asked    /// for.    static func topViewController() -> UIViewController? {        let scene = UIApplication.shared.connectedScenes            .compactMap { $0 as? UIWindowScene }            .first { $0.activationState == .foregroundActive }        guard var top = scene?.keyWindow?.rootViewController else { return nil }        while let presented = top.presentedViewController { top = presented }        return top    }}/// The file, and the SUBJECT that rides with it.////// `Share.share({ title, url })` on iOS puts the title in the sheet's subject —/// what Mail fills its subject line with. `UIActivityViewController` takes that/// from an item source rather than from a property, which is why the URL is/// wrapped rather than passed bare.private final class ExportActivityItem: NSObject, UIActivityItemSource {    private let url: URL    private let subject: String    init(url: URL, subject: String) {        self.url = url        self.subject = subject    }    func activityViewControllerPlaceholderItem(_ controller: UIActivityViewController) -> Any {        url    }    func activityViewController(        _ controller: UIActivityViewController,        itemForActivityType activityType: UIActivity.ActivityType?    ) -> Any? {        url    }    func activityViewController(        _ controller: UIActivityViewController,        subjectForActivityType activityType: UIActivity.ActivityType?    ) -> String {        subject    }}#else/// The Mac has no share sheet of this shape (until the Mac's own screens do,/// H3+): the exported file is revealed in the Finder, which is where a Mac/// user goes to do anything with a file.struct SystemShareSheet: FileSharing {    public init() {}    public func share(title: String, url: URL) async {        NSWorkspace.shared.activateFileViewerSelecting([url])    }}#endif/// Asked of you's rows, in the list's fixed order — the keys a board's/// `asked` part names (`asked.shows`).public enum AskedKey: String, Sendable, Hashable, CaseIterable {    case joinRequests    case assistantsAsked    case invites    case passwords    case aiAccess}/// One row of Asked of you, worded and addressed by the core (`shell.today`'s/// `parts.asked`): the band draws its label and opens its path.public struct AskedItem: Sendable, Equatable, Identifiable {    public let key: AskedKey    public let count: Int    public let label: String    /// A route PATH.    public let path: String    /// The database the row counts in, when the read answered across several.    public let database: FeedRowDatabase?    /// What the row asks one tile at a time, answered in place (arrivals):    /// each names the definition it is drawn by, so the app never names one.    public var tiles: [AskedTile] = []    /// The key, and the row's database before it: one key in two databases    /// is two rows.    public var id: String { FeedRowDatabase.key(database, id: key.rawValue) }    /// Where a tap opens: the row's path, in the row's own database. Nil for    /// a path no route reads.    public var link: DatabaseLink? {        Route.parse(path).map { FeedRowDatabase.link(database, route: $0) }    }    public init(key: AskedKey, count: Int, label: String, path: String, database: FeedRowDatabase? = nil) {        self.key = key        self.count = count        self.label = label        self.path = path        self.database = database    }    /// One answered row, or nil for a key this build does not know.    init?(_ item: TodayAnswer.Asked.Item) {        guard let key = AskedKey(rawValue: item.key) else { return nil }        self.init(key: key, count: item.count, label: item.label, path: item.path, database: item.database?.row)        tiles = item.tiles.compactMap(AskedTile.init)    }}/// One tile of an Asked of you row: a record to answer in place, by the/// definition the read named, with what arrived as records of their own.public struct AskedTile: Sendable, Hashable, Identifiable {    public struct Arrived: Sendable, Hashable {        public let table: String        public let id: String    }    public let table: String    public let id: String    /// The outcome as the core read it: a changed answer is a new tile value,    /// so the tile reads its record again.    public let outcome: String?    public let records: [Arrived]    /// The database the tile's record is in, when it is not the window's.    public var database: FeedRowDatabase?    public init(table: String, id: String, outcome: String? = nil, records: [Arrived] = [], database: FeedRowDatabase? = nil) {        self.table = table        self.id = id        self.outcome = outcome        self.records = records        self.database = database    }    init?(_ row: JSONValue) {        guard let table = row.text("table"), let id = row.text("id") else { return nil }        self.init(table: table, id: id, outcome: row.text("outcome"), records: row.list("records").compactMap { ref in            guard let table = ref.text("table"), let id = ref.text("id") else { return nil }            return Arrived(table: table, id: id)        })    }}/// One row of **Done for you** — something Cotton did by itself, as the core/// answered it (`parts.done`): its label, its text, its age and its one action.public struct DoneItem: Sendable, Equatable, Identifiable {    /// The kinds a board's `done` part names (`done.shows`).    public enum Kind: String, CaseIterable, Sendable {        case filed        case remembered        case couldNotRead        case cityFilled        case junkFiled        case removedFrom    }    /// The one action a row carries: `undo` is taken back by the core    /// (`shell.undo`), `change` opens the record, `open` is its words alone.    public enum Action: String, Sendable {        case undo        case change        case open    }    public let kind: Kind    public let recordId: String    public let label: String    public let text: String    /// When it happened, in the core's words.    public let when: String    public let action: Action    public let path: String    public var id: String { "\(kind.rawValue)-\(recordId)" }    public init(kind: Kind, recordId: String, label: String, text: String, when: String, action: Action, path: String) {        self.kind = kind        self.recordId = recordId        self.label = label        self.text = text        self.when = when        self.action = action        self.path = path    }    /// One answered row, or nil for a kind or action this build does not know.    init?(_ row: TodayAnswer.Done) {        guard let kind = Kind(rawValue: row.kind), let action = Action(rawValue: row.action) else { return nil }        self.init(kind: kind, recordId: row.id, label: row.label, text: row.text, when: row.when, action: action, path: row.path)    }}/// Home's page, as the core answers it (`shell.today`), held per database./// It asks when Home shows, on a data event of a family the answer names, on/// the core's own `{phase: home, stage: today}` (a read that failed, asked/// again on the core's backoff), on the shown copy arriving, and after a/// switch reads it before the window turns. It decides nothing it draws.@MainActor@Observablepublic final class HomeModel: Rereadable {    /// The last answer; nil until the first lands, and after a switch to a    /// database never read.    private(set) var answer: TodayAnswer?    /// Asked of you, worded and addressed.    public private(set) var askedItems: [AskedItem] = []    /// Done for you, newest first.    public private(set) var doneItems: [DoneItem] = []    /// Which read is the newest asked; an older one landing late is dropped.    @ObservationIgnored private var asking = 0    private let core: any CottonCalling    /// The core under the window's scope, for a read aimed at one database    /// without moving the window's calls (`prepare`).    private let unscoped: any CottonCalling    private let toasts: ToastCenter    /// How the export reaches the OS.    private let sharer: any FileSharing    init(        core: any CottonCalling,        unscoped: (any CottonCalling)? = nil,        toasts: ToastCenter,        sharer: any FileSharing = SystemShareSheet()    ) {        self.core = core        self.unscoped = unscoped ?? core        self.toasts = toasts        self.sharer = sharer    }    // ── Reading ──────────────────────────────────────────────────────────    /// Read now. SINGLE-FLIGHT per database: a burst of asks while a read of    /// the same database is out is one read and at most one more after it.    public func load() async {        let database = askingDatabase() ?? ""        if loading.contains(database) {            loadAgain.insert(database)            return        }        loading.insert(database)        defer { loading.remove(database) }        repeat {            loadAgain.remove(database)            await loadOnce()        } while loadAgain.contains(database) && (askingDatabase() ?? "") == database    }    @ObservationIgnored private var loading: Set<String> = []    @ObservationIgnored private var loadAgain: Set<String> = []    /// What `shell.today` is asked: the device's own day, in its zone, for    /// the database the window's calls name.    struct Ask: Encodable, Sendable {        let timezone: String        let today: String        let database: String?        let limit: Int        var board: String?        var size: String? = BoardScreen.size        static func of(_ database: String?, board: String? = nil, now: Date = Date(), calendar: Calendar = .current) -> Ask {            let day = calendar.dateComponents([.year, .month, .day], from: now)            let today = String(format: "%04d-%02d-%02d", day.year ?? 0, day.month ?? 0, day.day ?? 0)            return Ask(timezone: calendar.timeZone.identifier, today: today, database: database, limit: 200, board: board)        }    }    private func loadOnce() async {        asking += 1        let asked = asking        let askedFor = askingDatabase()        #if os(iOS)            SwitchClock.mark("home-asked", SwitchClock.launch)        #endif        outFor[askedFor ?? ""] = asked        defer { if outFor[askedFor ?? ""] == asked { outFor[askedFor ?? ""] = nil } }        do {            let answer = try await core.call(CottonMethod.shellToday, Ask.of(askedFor), as: TodayAnswer.self)            guard asked == asking else { return }            cameBack(for: askedFor)            answeredFor = askedFor            kept[askedFor ?? ""] = answer            answered(answer)        } catch {            guard asked == asking else { return }            cameBack(for: askedFor)            Log.write("shell.today did not answer: \(error)")        }    }    /// The window turned to another database: its kept answer is drawn at    /// once, and the read that follows brings it up to date.    public func turned() {        asking += 1        let shown = askingDatabase()        turnedFor = shown ?? ""        prepared = prepared.intersection([turnedFor])        let last = kept[turnedFor]        answeredFor = last == nil ? nil : shown        cameBackFor = last == nil ? nil : turnedFor        answered(last)    }    /// The database whose read last came back ("" the personal one).    public private(set) var cameBackFor: String?    private func cameBack(for database: String?) {        if cameBackFor != database ?? "" { cameBackFor = database ?? "" }    }    /// Whether `database`'s read has come back (nil, the personal one).    public func hasRead(_ database: String?) -> Bool {        answers(database) || cameBackFor == database ?? ""    }    /// The window's calls were aimed at another database: Home turns with them.    public func turnToAsked() {        guard (askingDatabase() ?? "") != turnedFor else { return }        turned()    }    @ObservationIgnored private var turnedFor = ""    // ── A switch: read before it turns ───────────────────────────────────    /// Read `id`'s page BEFORE the window turns to it, with its sync line, so    /// a switch is two frames: the old Home, then the new database's, whole.    public func prepare(shown id: String, calls database: String?) async {        let aimed = DatabaseScopedCore(underlying: unscoped, database: database)        async let sync: Void = HomeSync.prepare(aimed, database: id)        if let answer = try? await aimed.call(CottonMethod.shellToday, Ask.of(database), as: TodayAnswer.self) {            kept[database ?? ""] = answer            prepared.insert(database ?? "")        }        _ = await sync    }    @ObservationIgnored private var prepared: Set<String> = []    /// The shown copy replaced by another: read again from the new one.    func copyReplaced() async {        prepared.removeAll()        await load()    }    /// Read now — unless a switch has just read the shown database.    public func loadUnlessPrepared() async {        let database = askingDatabase() ?? ""        if prepared.remove(database) != nil, answers(database.isEmpty ? nil : database) { return }        await load()    }    @ObservationIgnored private var kept: [String: TodayAnswer] = [:]    private func answered(_ answer: TodayAnswer?) {        self.answer = answer        askedItems = answer?.parts.asked.items.compactMap(AskedItem.init) ?? []        doneItems = answer?.parts.done.compactMap(DoneItem.init) ?? []        projects = answer?.projects ?? []        switcherProjects = projects.compactMap { project in            guard let slug = project.text("slug") else { return nil }            return TableRecord(id: project.text("id") ?? slug, values: [                "name": .text(project.text("name") ?? slug), "slug": .text(slug),            ])        }        capColours = CapColour.assign(projects.compactMap { $0.text("slug") })        projectFactsMissing = answer?.project_facts_missing ?? false        homeTiles = HomeTiles(answer: answer?.arrangement)    }    // ── This device's card ───────────────────────────────────────────────    /// This device's own card, as the last read answered it.    var deviceCard: TodayAnswer.Card? { answer?.cards.first { $0.kind == "device" } }    /// Read this device's card again alone (`only: device`): it moves with    /// every sync pass, the page does not. A read that fails keeps the card.    func readDevice() async {        guard let read = try? await core.call(CottonMethod.shellToday, DeviceAsk(), as: DeviceRead.self),              let card = read.cards.first, let held = answer,              let at = held.cards.firstIndex(where: { $0.kind == "device" }), held.cards[at] != card        else { return }        var cards = held.cards        cards[at] = card        let next = held.with(cards: cards)        answer = next        kept[answeredFor ?? ""] = next    }    private struct DeviceAsk: Encodable, Sendable { let only = "device" }    private struct DeviceRead: Decodable, Sendable { let cards: [TodayAnswer.Card] }    // ── The serving Mac's backup ─────────────────────────────────────────    /// The serving Mac's off-Mac backup that is not getting through, as the    /// Mac last said it. A round trip Home's page never waits on.    public private(set) var backupNotice: BackupNotice?    public func readBackup() async {        guard let answer = try? await core.callJSON(CottonMethod.readServingBackup) else { return }        if case .answered(let notice) = BackupNotice.read(answer) {            backupNotice = notice        }    }    public func refresh() async { await load() }    // ── Events ───────────────────────────────────────────────────────────    /// The families whose `data` events mean Home reads again: the answer's own.    public var families: Set<ScreenFamily> { Set((answer?.families ?? []).compactMap(ScreenFamily.init(rawValue:))) }    /// Today's rows are every held database's: a write in any reads Home again.    public var readsAcrossDatabases: Bool { true }    @discardableResult    public func receive(_ event: ClientEvent) -> Task<Void, Never>? {        switch event {        case .data(let tables, let origin, _):            if event.isMovesDone, answer?.failed?.why == "moving" {                return Task { [weak self] in await self?.load() }            }            let moved = InvalidationMap.families(for: tables, origin: origin)            guard concerns(moved) else { return nil }            prepared.removeAll()            return Task { [weak self] in await self?.load() }        case .arrival(let stage, let database, _, _, _):            guard stage == "here", database == askingDatabase() else { return nil }            return Task { [weak self] in await self?.load() }        // The core asks again after a read that failed (its backoff).        case .home(let stage):            guard stage == "today" else { return nil }            return Task { [weak self] in await self?.load() }        case .migrate, .bootstrap, .cycle, .sync, .databaseSync, .removed, .personalSignedOut, .personalDeleted, .personalAdoptEnded:            return nil        }    }    // ── Done for you ─────────────────────────────────────────────────────    /// The receipts on their way back: a second tap sends nothing.    public private(set) var undoing: Set<String> = []    /// Take back what Cotton did (`shell.undo`): the core says the receipt's    /// words, and Home reads again so the row leaves because the file says so.    public func undo(_ item: DoneItem) async {        guard item.action == .undo, !undoing.contains(item.id) else { return }        undoing.insert(item.id)        defer { undoing.remove(item.id) }        do {            let said = try await core.call(CottonMethod.shellUndo, UndoAsk(kind: item.kind.rawValue, id: item.recordId), as: UndoSaid.self)            toasts.show(said.said, tone: .success)            await load()        } catch {            toasts.show((error as? CottonCallError)?.message ?? CottonStrings.somethingWentWrong, tone: .error)        }    }    private struct UndoAsk: Encodable, Sendable { let kind: String; let id: String }    private struct UndoSaid: Decodable, Sendable { let said: String }    /// A board pushed over Home (Tools, the database page), answered whole    /// for the database the window shows: `shell.today`'s `parts.board`.    func boardParts(_ board: String) async -> [BoardEntry]? {        try? await core.call(CottonMethod.shellToday, Ask.of(askingDatabase(), board: board), as: TodayAnswer.self).parts.board    }    // ── The rest of the page ─────────────────────────────────────────────    /// The page's notices that speak now, in the kit's order.    var notices: [TodayAnswer.Notice] { answer?.parts.notices ?? [] }    /// The notice of `kind` (`update`, `arriving`, `workingOn`, `readRefusal`, `attention`).    func notice(_ kind: String) -> TodayAnswer.Notice? { notices.first { $0.id == kind } }    /// The databases that could not be read, one line each.    var unreadable: [TodayAnswer.Notice] { notices.filter { $0.id.hasPrefix("unreadable/") } }    /// The page could not be read and has nothing to draw.    public var bandUnreadable: Bool { answer?.parts.asked.unreadable ?? false }    /// Active projects, in the order the core sorted them.    public private(set) var projects: [JSONValue] = []    /// The same projects as the cap's switcher draws them.    public private(set) var switcherProjects: [TableRecord] = []    public private(set) var capColours: [String: CapColour] = [:]    public private(set) var projectFactsMissing = false    /// The shown database's workspace, once read.    public var workspaceId: String? { answer?.workspace_id }    /// Whether the shown database's arrangement has been answered.    public var isArranged: Bool { answer != nil }    /// The tiles the board draws for `database` (nil, the personal one): its    /// answer when held, else its kept answer; none for neither.    public func drawnTiles(for database: String?) -> HomeTiles? {        if answers(database) { return homeTiles }        if let answer = kept[database ?? ""], let tiles = HomeTiles(arranged: answer.arrangement) { return tiles }        return nil    }    func shownDatabase(scene: DatabaseScene, in databases: DatabasesModel) -> (database: String?, known: Bool) {        if let shown = scene.shown(in: databases) { return (shown.isPersonal ? nil : shown.databaseId, true) }        return (askingDatabase(), databases.listed && databases.held.isEmpty)    }    func drawnTiles(scene: DatabaseScene?, in databases: DatabasesModel?) -> HomeTiles? {        guard let scene, let databases else { return isArranged ? homeTiles : nil }        let shown = shownDatabase(scene: scene, in: databases)        return shown.known ? drawnTiles(for: shown.database) : nil    }    func readShown(scene: DatabaseScene?, in databases: DatabasesModel?) -> Bool {        guard let scene, let databases else { return isArranged || cameBackFor != nil }        let shown = shownDatabase(scene: scene, in: databases)        return shown.known && hasRead(shown.database)    }    public private(set) var answeredFor: String?    @ObservationIgnored public var askingDatabase: () -> String? = { nil }    public func answers(_ database: String?) -> Bool { answer != nil && answeredFor == database }    func answersShown(scene: DatabaseScene?, in databases: DatabasesModel?) -> Bool {        guard let scene, let databases else { return isArranged }        let shown = shownDatabase(scene: scene, in: databases)        return shown.known && answers(shown.database)    }    public func readAgainIfAskedElsewhere(shown database: String?) async {        guard !answers(database), outFor[database ?? ""] != asking, askingDatabase() == database else { return }        await load()    }    @ObservationIgnored private var outFor: [String: Int] = [:]    /// Home's tiles as the core answered them, in draw order.    public private(set) var homeTiles = HomeTiles(tiles: [])}