Cotton code
149 lines · 6.8 KB · SwiftRaw
// The tables over the app's own sources (`SettingsRecords`): their bundled// definitions, and the kept flows run wherever one of them — or a native// table that names a kept flow — is drawn. Their lists and pages are the// routes every other table opens (`TableListRoute`, `TablePageRoute`, over// `SourceTableStore`).//// **The kept flows run here** (`\.keptFlow`): a token the vault refused// opens the vault before the page tries it once more, the city is chosen// from a search, and leaving a database hands the window back. Everything// else a record does is a column or an action of its page.import CottonKitimport SwiftUIextension SettingsTableEntry: Identifiable {    public var id: String { table }}extension View {    /// The kept flows, run wherever one of these tables' lists or pages is    /// drawn (Feedback's "Report a problem", this device's "Choose a city").    /// Without it `RecordActs` refuses a kept flow: "… was not done."    func settingsKeptFlows(table: String? = nil, record: String? = nil) -> some View {        modifier(SettingsKeptFlowHost(table: table, record: record))    }}/// The one runner of `\.keptFlow` for the Settings tables.struct SettingsKeptFlowHost: ViewModifier {    /// The table and record the page shows: a tool's page edits ITS table.    var table: String? = nil    var record: String? = nil    @Environment(\.cottonCore) private var core    @Environment(\.tableDefinitions) private var definitions    @Environment(ToastCenter.self) private var toasts    @Environment(Navigator.self) private var navigator: Navigator?    @Environment(BootModel.self) private var boot: BootModel?    @Environment(DatabasesModel.self) private var databases: DatabasesModel?    @Environment(DatabaseScene.self) private var scene: DatabaseScene?    /// The root's runner, read above this host's own: this device's Sign in,    /// Sign out and Erase are the root's to run (`PersonalSessionFlows`).    @Environment(\.nativeKeptFlow) private var rootFlows    /// The built-in table a tool's page is editing (`KeptFlow.editTable`).    @State private var editingTable: EditedTable?    struct EditedTable: Identifiable { let id: String }    func body(content: Content) -> some View {        content            .environment(\.keptFlow, { flow in await run(flow) })            .environment(\.nativeKeptFlow, { flow in await runCaptured(flow) })            .cottonCard(item: $editingTable, detents: [.tall]) { edited in                Hosted(unwired: { core, toasts in TableEditorModel(table: edited.id, core: core, toasts: toasts) }) { editor in                    TableEditorScreen(model: editor, onDone: { editingTable = nil })                }            }    }    private func runCaptured(_ request: RecordKeptFlow) async -> Bool {        if request.flow.session || request.flow.film { return await rootFlows?(request) ?? false }        guard request.matches(table: table, id: record) else { return false }        if request.flow == .leaveDatabase {            guard let target = request.database, target == request.origin.id else { return false }            return await DatabaseLeaving.leaveCaptured(target, databases: databases, scene: scene,                boot: boot, navigator: navigator, toasts: toasts)        }        return await run(request.flow.kept)    }    private func run(_ flow: KeptFlow) async -> Bool {        switch flow {        case .vaultUnlock:            guard let core else { return false }            return await SettingsKeptFlows.unlockVault(through: ScreenWriter(core: core), toasts: toasts)        case .reportProblem:            NotificationCenter.default.post(name: .cottonReportProblem, object: nil)            return true        case .leaveDatabase:            return await leaveShownDatabase()        case .leaveThisDevice:            guard let boot else { return false }            await boot.leave()            return true        case .editTable:            guard let record,                let edited = TableEditorModel.table(forTool: record, in: definitions.all)            else { return false }            editingTable = EditedTable(id: edited.id)            return true        // The root's, reached through `runCaptured` alone.        case .signIn, .signOut, .eraseThisDevice, .shareInk, .keepFilm, .removeFilmDownload, .keepEpisode, .removeEpisodeDownload, .keepBook, .removeBookDownload,             .addBookFile, .keepSong, .removeSongDownload, .keepAlbum, .removeAlbumDownload:            return false        }    }    /// The window's database, left (`DatabaseLeaving`).    private func leaveShownDatabase() async -> Bool {        await DatabaseLeaving.leaveShown(databases: databases, scene: scene, boot: boot, navigator: navigator, toasts: toasts)    }}/// The vault, opened before a write that seals a secret is tried again — or,/// on a password's page, before its value is shown or copied.enum SettingsKeptFlows {    /// What the flow says when it does not open, in its holder's words.    struct UnlockWords: Equatable, Sendable {        /// Said when the person cancelled the prompt; nil says nothing — a        /// cancelled Show is a decision, not a fault.        let cancelled: String?        let noPresence: String        /// A token typed on a connection's page.        static var settings: UnlockWords {            UnlockWords(cancelled: ShellLines.line("record", "unlock.cancelled"), noPresence: ShellLines.line("record", "unlock.no_presence_tokens"))        }        /// A password shown, copied, changed or made.        static var passwords: UnlockWords {            UnlockWords(cancelled: nil, noPresence: ShellLines.line("record", "unlock.no_presence_passwords"))        }    }    /// Whether it opened. When it did not, the sentence is the seam's own, so    /// no screen invents a wording for "your Mac has not shared the key yet".    @MainActor    static func unlockVault(        through writer: ScreenWriter, toasts: ToastCenter, vault: VaultAccess = VaultAccess(),        words: UnlockWords = .settings    ) async -> Bool {        switch await vault.unlock(through: writer) {        case .open:            return true        case .waitingForMac(let sentence), .refused(let sentence):            toasts.show(sentence, tone: .error)        case .cancelled:            if let cancelled = words.cancelled { toasts.show(cancelled, tone: .error) }        case .noPresence:            toasts.show(words.noPresence, tone: .error)        case .keyMismatch:            // The screen does the thing rather than naming it: publish the key            // this device is actually holding, so the Mac that holds the            // passwords wraps for it.            await vault.publish(through: writer)            toasts.show(PasswordFacts.waitingForTheKey, tone: .error)        }        return false    }}