Sources/OrgstarMobile/EmacsImportScreen.swift

67 lines · 2680 bytes

 1#if os(iOS)
 2import OrgApp
 3import OrgCore
 4import SwiftUI
 5
 6/// Import from Emacs: a configuration folder (a synced `~/.config/doom` or `~/.emacs.d`), read
 7/// and picked from before anything changes. Settings go into the configuration
 8/// folder's config.toml when there is one; agenda folders, which name the Mac's paths, are left
 9/// out.
10struct EmacsImportScreen: View {
11    let model: MobileModel
12    @State private var location: URL?
13    @State private var result: EmacsImport?
14    @State private var selected: Set<Int> = []
15    @State private var choosing = false
16    @State private var summary: String?
17    @State private var importing = false
18
19    var body: some View {
20        List {
21            Section {
22                Button(location == nil ? "Choose Folder…" : "Choose Another Folder…") { choosing = true }
23            } footer: {
24                Text(location.map { "Reading \($0.lastPathComponent)" + ((result?.isDoom ?? false) ? ", a Doom configuration" : "") + "." }
25                    ?? "The folder holding init.el, config.el or config.org.")
26            }
27            if let summary {
28                Section { Text(summary) }
29            } else if let result {
30                EmacsImportSections(result: result, groups: result.groups(folders: false), selected: $selected,
31                                    font: .system(.callout, design: .monospaced))
32            }
33        }
34        .navigationTitle("Import from Emacs")
35        .toolbar {
36            if result != nil, summary == nil {
37                Button("Import") { runImport() }.disabled(selected.isEmpty || importing)
38            }
39        }
40        .fileImporter(isPresented: $choosing, allowedContentTypes: [.folder]) { chosen in
41            if case .success(let url) = chosen { read(url) }
42        }
43    }
44
45    private func read(_ url: URL) {
46        let accessing = url.startAccessingSecurityScopedResource()
47        defer { if accessing { url.stopAccessingSecurityScopedResource() } }
48        location = url
49        let scanned = EmacsImport.scan(EmacsImport.files(in: url))
50        result = scanned
51        selected = Set(scanned.groups(folders: false).flatMap(\.1).map(\.id))
52        summary = nil
53    }
54
55    private func runImport() {
56        guard let result else { return }
57        importing = true
58        let chosen = result.items.filter { selected.contains($0.id) }
59        Task {
60            summary = await EmacsImport.apply(chosen, workspace: nil, directory: model.configFolder ?? UserConfig.directory,
61                                              writeConfig: model.configFolder != nil)
62            model.reloadConfig()
63            importing = false
64        }
65    }
66}
67#endif