Jotley / app / Shared / Views / LibraryBackupControls.swift
| 1 | import SwiftUI |
| 2 | import UniformTypeIdentifiers |
| 3 | |
| 4 | private struct LibraryBackupDocument: FileDocument { |
| 5 | static var readableContentTypes: [UTType] { [.json] } |
| 6 | var data: Data |
| 7 | init(data: Data) { self.data = data } |
| 8 | init(configuration: ReadConfiguration) throws { |
| 9 | guard let data = configuration.file.regularFileContents else { throw CocoaError(.fileReadCorruptFile) } |
| 10 | self.data = data |
| 11 | } |
| 12 | func fileWrapper(configuration: WriteConfiguration) throws -> FileWrapper { |
| 13 | FileWrapper(regularFileWithContents: data) |
| 14 | } |
| 15 | } |
| 16 | |
| 17 | /// Shared controls keep the platform's existing Settings layout and native |
| 18 | /// save/open sheets. No account or internet connection is needed. |
| 19 | struct LibraryBackupControls: View { |
| 20 | @EnvironmentObject private var store: SharedPersistenceController |
| 21 | @State private var document: LibraryBackupDocument? |
| 22 | @State private var showingExporter = false |
| 23 | @State private var showingImporter = false |
| 24 | @State private var pendingBackup: LibraryBackup? |
| 25 | @State private var message: String? |
| 26 | |
| 27 | var body: some View { |
| 28 | Button("Export Backup…", systemImage: "square.and.arrow.up") { exportBackup() } |
| 29 | .accessibilityIdentifier("settingsExportBackup") |
| 30 | Button("Import / Restore…", systemImage: "square.and.arrow.down") { showingImporter = true } |
| 31 | .accessibilityIdentifier("settingsImportBackup") |
| 32 | Text("Save all notes, transcripts, summaries, folders, tags, note chats, markers and custom templates in one JSON file. Restore adds missing items and keeps existing versions. No account or internet connection is needed.") |
| 33 | .font(.caption).foregroundStyle(.secondary) |
| 34 | Text("Backups contain your note text. Save them somewhere private. Support conversations and sign-in credentials are not included.") |
| 35 | .font(.caption).foregroundStyle(.secondary) |
| 36 | if let message { Text(message).font(.callout).textSelection(.enabled).accessibilityIdentifier("settingsBackupResult") } |
| 37 | Color.clear.frame(height: 0) |
| 38 | .fileExporter(isPresented: $showingExporter, document: document, contentType: .json, |
| 39 | defaultFilename: "Jotley Backup \(Date.now.formatted(.iso8601.year().month().day().dateSeparator(.dash)))") { result in |
| 40 | switch result { |
| 41 | case .success: message = "Backup saved. You can restore this file in Jotley on Mac, iPhone or iPad." |
| 42 | case .failure(let error): message = "The backup was not saved: \(error.localizedDescription)" |
| 43 | } |
| 44 | document = nil |
| 45 | } |
| 46 | .fileImporter(isPresented: $showingImporter, allowedContentTypes: [.json]) { result in |
| 47 | do { |
| 48 | let url = try result.get() |
| 49 | let access = url.startAccessingSecurityScopedResource() |
| 50 | defer { if access { url.stopAccessingSecurityScopedResource() } } |
| 51 | let size = try url.resourceValues(forKeys: [.fileSizeKey]).fileSize ?? 0 |
| 52 | guard size <= LibraryBackupService.byteLimit else { throw LocalError.message("Choose a Jotley backup smaller than 256 MB.") } |
| 53 | pendingBackup = try LibraryBackupService.decode(Data(contentsOf: url, options: .mappedIfSafe)) |
| 54 | } catch { message = error.localizedDescription } |
| 55 | } |
| 56 | .sheet(isPresented: Binding(get: { pendingBackup != nil }, set: { if !$0 { pendingBackup = nil } })) { |
| 57 | if let backup = pendingBackup { restorePreview(backup) } |
| 58 | } |
| 59 | } |
| 60 | |
| 61 | private func exportBackup() { |
| 62 | do { |
| 63 | let backup = try LibraryBackupService.export(from: store, templates: .shared) |
| 64 | document = LibraryBackupDocument(data: try LibraryBackupService.encode(backup)) |
| 65 | showingExporter = true |
| 66 | } catch { message = error.localizedDescription } |
| 67 | } |
| 68 | |
| 69 | private func restorePreview(_ backup: LibraryBackup) -> some View { |
| 70 | NavigationStack { |
| 71 | ScrollView { |
| 72 | VStack(alignment: .leading, spacing: 16) { |
| 73 | Text("Restore your library").font(.title2.bold()) |
| 74 | Text("Backup created \(backup.createdAt.formatted(date: .abbreviated, time: .shortened)).") |
| 75 | .foregroundStyle(.secondary) |
| 76 | Text("\(backup.noteCount) notes · \(backup.items.filter { $0.entity == "Folder" }.count) folders · \(backup.items.filter { $0.entity == "Tag" }.count) tags · \(backup.templates.count) custom templates") |
| 77 | Text("Saved note chats and markers are included. Existing notes and templates keep their current version. Folders and tags with matching names are reused. Missing items are added, and nothing is deleted. Restoring the same backup again does not duplicate its notes.") |
| 78 | Text("Restored notes will sync to your other devices if iCloud sync is enabled.") |
| 79 | .font(.callout).foregroundStyle(.secondary) |
| 80 | }.padding(24) |
| 81 | } |
| 82 | .navigationTitle("Restore Backup") |
| 83 | .toolbar { |
| 84 | ToolbarItem(placement: .cancellationAction) { |
| 85 | Button("Cancel") { pendingBackup = nil }.jotleyDismissButtonStyle(inToolbar: true) |
| 86 | } |
| 87 | .sharedBackgroundVisibility(.hidden) |
| 88 | ToolbarItem(placement: .confirmationAction) { |
| 89 | Button("Restore") { |
| 90 | do { |
| 91 | let result = try LibraryBackupService.restore(backup, to: store, templates: .shared) |
| 92 | #if os(macOS) |
| 93 | try? LocalAppModel.shared.reload() |
| 94 | #endif |
| 95 | message = "Restored \(result.notesAdded) notes and \(result.templatesAdded) templates. Kept \(result.recordsKept) existing items." |
| 96 | pendingBackup = nil |
| 97 | } catch { message = error.localizedDescription; pendingBackup = nil } |
| 98 | }.accessibilityIdentifier("confirmLibraryRestore") |
| 99 | } |
| 100 | } |
| 101 | } |
| 102 | #if os(macOS) |
| 103 | .frame(width: 560, height: 360) |
| 104 | #endif |
| 105 | } |
| 106 | } |