Cotton code
61 lines · 2.6 KB · SwiftRaw
import CottonKitimport SwiftUI/// Leaving the window's database — one act, from the database page's Leave and/// from tray › Leave this database on its Home.@MainActorenum DatabaseLeaving {    /// A declared flow leaves its captured held file, even when the window    /// now shows another. Only a leave of the shown file resets that window.    static func leaveCaptured(_ target: String, databases: DatabasesModel?, scene: DatabaseScene?,                              boot: BootModel?, navigator: Navigator?, toasts: ToastCenter?) async -> Bool {        guard let databases, let scene else { return false }        if databases.held.isEmpty { await databases.refresh() }        guard let held = databases.held.first(where: { $0.databaseId == target }) else { return false }        if held.isPersonal {            guard let boot else { return false }            await boot.leave()            return true        }        if scene.shownId == target {            return await leaveShown(databases: databases, scene: scene, boot: boot, navigator: navigator, toasts: toasts)        }        do {            try await databases.leave(target)            await databases.refresh()            return true        } catch {            toasts?.show((error as? CottonCallError)?.message ?? error.localizedDescription, tone: .error)            return false        }    }    /// The window's database, left. A shared one is forgotten here and the    /// window goes back to the personal database; the personal one is this    /// device's own pairing, and leaving it sends the device back to Start.    static func leaveShown(        databases: DatabasesModel?, scene: DatabaseScene?, boot: BootModel?, navigator: Navigator?, toasts: ToastCenter?    ) async -> Bool {        guard let databases, let scene else { return false }        guard let shown = scene.shown(in: databases), !shown.isPersonal else {            guard let boot else { return false }            await boot.leave()            return true        }        do {            try await databases.leave(shown.databaseId)        } catch {            toasts?.show((error as? CottonCallError)?.message ?? error.localizedDescription, tone: .error)            return false        }        navigator?.resetForDatabaseChange()        scene.reset()        await databases.refresh()        if let personal = databases.ordered.first(where: \.isPersonal) {            await scene.pick(personal.databaseId, in: databases)        } else {            await scene.seed(from: databases)        }        return true    }}