// `/export` — Settings › Export: pick tables, write one Cotton package
// (`.cottonpkg`: a zip of `manifest.json`, one `
.jsonl` per table and
// `media/`), and hand it to the share sheet, where it is AirDropped or
// saved to Files. The core writes the file (`Packages.export`); this screen
// only chooses what goes in and passes the path on.
import CottonKit
import SwiftUI
struct ExportRoute: View {
@Environment(\.cottonCore) private var core
@Environment(\.tableDefinitions) private var definitions
@Environment(ToastCenter.self) private var toasts
@State private var chosen: Set = []
@State private var writing = false
/// The words the screen says, one place.
enum Words {
static var title: String { ShellLines.line("databases", "export.title") }
static var lead: String { ShellLines.line("databases", "export.lead") }
static var write: String { ShellLines.line("databases", "export.write") }
static var writing: String { ShellLines.line("databases", "export.writing") }
static var refused: String { ShellLines.line("databases", "export.refused") }
static func missing(_ count: Int) -> String {
ShellLines.line("databases", "export.missing_media", ["n": String(count)])
}
}
var body: some View {
let tables = Self.exportable(definitions.all)
PaperScreen(title: Words.title) {
VStack(alignment: .leading, spacing: RecordListSurfaceKnobs.paperGap) {
Text(writing ? Words.writing : Words.lead)
.paperBody(15, ink: .pencil)
.frame(maxWidth: .infinity, alignment: .leading)
VStack(spacing: 0) {
ForEach(tables) { table in
SettingsSwitchRow(
label: table.plural,
isOn: chosen.contains(table.id),
isLast: table.id == tables.last?.id,
identifier: "export-table-\(table.id)"
) { on in
if on { chosen.insert(table.id) } else { chosen.remove(table.id) }
}
}
}
PaperTypedButton(Words.write) { Task { await write(tables) } }
.disabled(chosen.isEmpty)
.accessibilityIdentifier("export-write")
}
.disabled(writing)
}
}
/// The tables a package can carry: those whose records the core reads by
/// kind — the stored ones — by their plural, as the person knows them.
static func exportable(_ all: [TableDefinition]) -> [TableDefinition] {
all.filter { $0.recordKind != nil }
.sorted { $0.plural.localizedStandardCompare($1.plural) == .orderedAscending }
}
/// Write the package in the order the tables are listed and hand the file
/// to the share sheet; say so when some files were not on this device.
private func write(_ tables: [TableDefinition]) async {
guard let core else {
toasts.show(Words.refused, tone: .error)
return
}
writing = true
defer { writing = false }
do {
let ids = tables.map(\.id).filter(chosen.contains)
let written = try await Packages(core: core).export(tables: ids)
if !written.missingMedia.isEmpty { toasts.show(Words.missing(written.missingMedia.count), tone: .error) }
ShareSheet.present(URL(fileURLWithPath: written.path))
} catch {
toasts.show((error as? CottonCallError)?.message ?? Words.refused, tone: .error)
}
}
}