Cotton code
169 lines · 8.5 KB · SwiftRaw
// PLUS'S CHOICE TIER (`create.doors`; the coordinator, 4 Nov 2026): a table// with more than one way in has no screen of doors. Its "+" turns the fan at// the hub into one tile per door, the kit's word and picture on each, and its// empty deck, held, offers the same tier as its acts — the way an empty// Calendar offers Connect Google Calendar. Books' are Find a book, Add a file// and Bring Goodreads in.//// A door does one of three things, all the shell's own and named by the kit// (the third, pictures from the photo picker or the camera, is// `DeckPictureDoors.swift`'s):// words typed in the one short-text input and sent to an object act (as a// single-act "+" sends them: `find_book`), the deck standing on the record the// act's answer names; or files chosen in the system's picker, each staged// into the app group and handed to the share sheet's SAME intake// (`ShareIntake.intake`), which files it by what it is — an EPUB or PDF as a// book read from the file, a Goodreads export to the object — and lands where// a share of it lands. Passwords' Bring Apple Passwords in is the one door// that never reaches the intake: the CSV holds every password in the clear,// so it is read here and handed to `password.importCsv` alone, sealed on this// device, never staged into the app group.import CottonKitimport SwiftUIimport UniformTypeIdentifiersextension EnvironmentValues {    /// The share sheet's own intake, which a door's chosen files go through    /// (`ShareIntake.intake`); nil in a preview or a test.    @Entry var shareIntake: ShareIntake? = nil}enum DeckDoors {    /// The picker's types for a door's files, as this system names them. A    /// door naming OPML (Podcasts' Bring subscriptions in) also takes plain    /// XML and every type this system knows `.opml` by: Reeder and Overcast    /// claim the extension under types of their own, and a list saved as    /// `.xml` is one too, which the intake tells by its root (`isOpmlShare`).    static func types(_ files: DefinitionCreateFiles) -> [UTType] {        var types = files.types.compactMap { UTType($0) }        if files.types.contains(opmlType) {            types += [.xml] + UTType.types(tag: "opml", tagClass: .filenameExtension, conformingTo: nil)        }        return types.reduce(into: [UTType]()) { kept, type in if !kept.contains(type) { kept.append(type) } }    }    /// OPML's type as the kit names it (`project.yml` imports it).    static let opmlType = "org.opml.opml"    /// The chosen files staged into the app group exactly as the share    /// extension stages a share, and handed to the share sheet's intake:    /// each is filed by what it is and lands where a share of it lands. A    /// file that could not be staged is said. A film's door (`table` the    /// film table) brings its files in where they stand instead: a film is    /// gigabytes, copied once, into the store (`ShareIntake.films(inPlace:)`).    /// A book's door stages a folder whole, and the intake reads it as books.    @MainActor    static func bring(_ urls: [URL], for table: String?, through intake: ShareIntake?, toasts: ToastCenter?,                      core: (any CottonCalling)? = nil) async {        guard !urls.isEmpty else { return }        if table == secretTable { return await passwords(urls[0], core: core, toasts: toasts) }        if let table, healthTables.contains(table) { return await healthExport(urls[0], core: core, toasts: toasts) }        guard let intake else {            toasts?.show(ShellLines.line("databases", "bring_in.unreadable"), tone: .error)            return        }        if table == filmTable { return await intake.films(inPlace: urls) }        let staged = stageForIntake(urls, at: CottonDate.format(Date()))        if staged.count < urls.count { toasts?.show(ShellLines.line("databases", "bring_in.unreadable"), tone: .error) }        // Books' Add a folder: the tree staged whole and read as books, in        // every app (`ShareIntake.bookFolder`).        if table == bookTable { return await intake.intake(staged, foldersAreBooks: true) }        await intake.intake(staged)    }}extension DeckDoors {    /// The table whose door brings Apple Passwords' CSV in (`password.importCsv`).    static let secretTable = "secret"    /// Apple Passwords' CSV, read where it stands and sealed by the core    /// (`PasskeyImport.csv`: a locked vault asks Face ID once); the toast    /// says how many and each skip. The file is never copied.    @MainActor    static func passwords(_ url: URL, core: (any CottonCalling)?, toasts: ToastCenter?) async {        let scoped = url.startAccessingSecurityScopedResource()        let read = try? String(contentsOf: url, encoding: .utf8)        if scoped { url.stopAccessingSecurityScopedResource() }        guard let core, let text = read else {            toasts?.show(ShellLines.line("databases", "bring_in.unreadable"), tone: .error)            return        }        let outcome = await PasskeyImport(core: core).csv(text)        let failed = outcome.refused != nil || outcome.locked        toasts?.show(KeysImport.said(outcome), tone: failed ? .error : .success, window: ToastWindow.untilTap)    }    /// The tables whose door brings Apple Health's export in (`health.readExport`).    static let healthTables: Set<String> = ["health_day", "health_workout", "health_measurement"]    /// Apple Health's export.zip (or its export.xml), read where it stands    /// by the core and landed sealed (`health.readExport`); the toast says    /// how many rows came in. The file is never copied: it can be gigabytes.    @MainActor    static func healthExport(_ url: URL, core: (any CottonCalling)?, toasts: ToastCenter?) async {        guard let core else {            toasts?.show(ShellLines.line("databases", "bring_in.unreadable"), tone: .error)            return        }        struct Ask: Encodable { let path: String }        let scoped = url.startAccessingSecurityScopedResource()        defer { if scoped { url.stopAccessingSecurityScopedResource() } }        do {            let read = try await core.callJSON(CottonMethod.healthReadExport, Ask(path: url.path))            let put = read["put"]?.int ?? 0            toasts?.show(ShellLines.line("cards", "health.export.landed", ["n": "\(put)"]), tone: .success, window: ToastWindow.untilTap)        } catch let error as CottonCallError where error.code == "seal_key_missing" {            toasts?.show(ShellLines.line("cards", "health.read.locked"), tone: .error, window: ToastWindow.untilTap)        } catch {            let why = (error as? CottonCallError)?.message ?? error.localizedDescription            toasts?.show(ShellLines.line("cards", "health.export.failed", ["why": why]), tone: .error, window: ToastWindow.untilTap)        }    }    /// The table whose doors bring films in, read where they stand.    static let filmTable = "film"    /// The table whose folder door brings books in.    static let bookTable = "book"}extension View {    /// A door's files (`create.doors`): while `choosing` holds one, the    /// system's picker for its types, and what is chosen handed to the share    /// sheet's intake (`DeckDoors.bring`).    func doorFiles(_ choosing: Binding<DefinitionCreateFiles?>, for table: String?) -> some View {        modifier(DoorFiles(choosing: choosing, table: table))    }}struct DoorFiles: ViewModifier {    @Binding var choosing: DefinitionCreateFiles?    /// The table whose door is open.    let table: String?    @Environment(\.shareIntake) private var shareIntake    @Environment(\.cottonCore) private var core    @Environment(ToastCenter.self) private var toasts: ToastCenter?    func body(content: Content) -> some View {        content            .fileImporter(isPresented: Binding(get: { choosing != nil }, set: { if !$0 { choosing = nil } }),                          allowedContentTypes: choosing.map(DeckDoors.types) ?? [],                          allowsMultipleSelection: choosing?.many ?? false) { result in                choosing = nil                guard case .success(let urls) = result else { return }                Task { await DeckDoors.bring(urls, for: table, through: shareIntake, toasts: toasts, core: core) }            }    }}/// The files a book is: an EPUB or a PDF (a book's Add file).enum BookFileTypes {    static let all: [UTType] = [UTType("org.idpf.epub-container"), .pdf].compactMap { $0 }}extension DefinitionCreateAct {    public init(name: String, argument: String, lands: String? = nil) {        self.init(_generated: (), name: name, argument: argument)        self.lands = lands    }}