Sources/Orgstar/MarkdownImportSheet.swift

801e496807e41f08001dbd99622e2fa686a34058
orgstar/Sources/Orgstar/MarkdownImportSheet.swift

192 lines · 9579 bytes

  1import AppKit
  2import OrgApp
  3import OrgCore
  4import SwiftUI
  5import UniformTypeIdentifiers
  6
  7/// File ▸ Import ▸ Markdown Files… and Obsidian Vault…: the sources, a folder to write into,
  8/// and what the import will write, before anything is written.
  9struct MarkdownImportSheet: View {
 10    let kind: MarkdownImport.Kind
 11    let workspace: WorkspaceModel
 12    /// The folder of the file shown, which the folder menu starts on.
 13    let folder: String?
 14    let done: (String) -> Void
 15    @Environment(\.dismiss) private var dismiss
 16    @State private var sources: [URL] = []
 17    @State private var destination = ""
 18    @State private var plan: MarkdownImport.Plan?
 19    @State private var planning = false
 20    @State private var importing = false
 21    @State private var failure: String?
 22
 23    var body: some View {
 24        let folders = SnippetLibrary.folders(in: workspace)
 25        VStack(alignment: .leading, spacing: 12) {
 26            HStack(alignment: .firstTextBaseline) {
 27                VStack(alignment: .leading, spacing: 2) {
 28                    Text(kind == .obsidian ? "Import Obsidian Vault" : "Import Markdown Files").font(.headline)
 29                    Text(sources.isEmpty ? String(localized: "Nothing chosen yet.", comment: "Markdown import with no source chosen")
 30                         : sources.map { OrgPaths.abbreviatingWithTilde($0.path) }.joined(separator: ", "))
 31                        .font(.caption).foregroundStyle(.secondary).lineLimit(2).truncationMode(.middle)
 32                }
 33                Spacer()
 34                Button("Choose…") { choose() }
 35            }
 36            if folders.isEmpty {
 37                Text("Add a folder first.").foregroundStyle(.secondary)
 38            } else {
 39                Picker("Import into", selection: $destination) {
 40                    ForEach(folders, id: \.path) { Text($0.title).tag($0.path) }
 41                }
 42            }
 43            preview
 44            if let failure {
 45                Text(failure).font(.caption).foregroundStyle(.red)
 46            }
 47            HStack {
 48                Text("New files only: nothing in the folder or the source is changed.")
 49                    .font(.caption).foregroundStyle(.secondary)
 50                Spacer()
 51                Button("Cancel") { dismiss() }.keyboardShortcut(.cancelAction)
 52                Button("Import") { runImport() }
 53                    .keyboardShortcut(.defaultAction)
 54                    .disabled(plan == nil || plan?.notes == 0 || planning || importing)
 55            }
 56        }
 57        .padding(20)
 58        .frame(width: 600, height: 480)
 59        .onAppear {
 60            destination = folders.first { $0.path == folder }?.path ?? folders.first?.path ?? ""
 61            #if !APPSTORE
 62            // Scripted runs give the source, and optionally the folder, for the snapshot.
 63            let answers = DevelopmentHooks.answers
 64            if let source = answers.first {
 65                if answers.count > 1, let chosen = folders.first(where: { $0.path == answers[1] || $0.title == answers[1] }) { destination = chosen.path }
 66                sources = [URL(fileURLWithPath: source)]
 67                return
 68            }
 69            #endif
 70            DispatchQueue.main.async { choose() }
 71        }
 72        .task(id: PlanKey(sources: sources, destination: destination)) { await makePlan() }
 73    }
 74
 75    private struct PlanKey: Equatable {
 76        let sources: [URL]
 77        let destination: String
 78    }
 79
 80    @ViewBuilder
 81    private var preview: some View {
 82        if planning {
 83            ProgressView("Reading…").frame(maxWidth: .infinity, maxHeight: .infinity)
 84        } else if let plan {
 85            VStack(alignment: .leading, spacing: 8) {
 86                Grid(alignment: .leading, horizontalSpacing: 16, verticalSpacing: 2) {
 87                    GridRow { Text("Files"); Text(plan.notes, format: .number).monospacedDigit() }
 88                    GridRow { Text("Headings"); Text(plan.headings, format: .number).monospacedDigit() }
 89                    GridRow { Text("Links"); Text(plan.links, format: .number).monospacedDigit() }
 90                    GridRow { Text("Attachments"); Text(plan.attachments, format: .number).monospacedDigit() }
 91                }
 92                if !plan.renamed.isEmpty {
 93                    Text("Already in the folder, so imported under another name:").font(.subheadline)
 94                    Text(plan.renamed.map { "\($0.from) → \($0.to)" }.joined(separator: "\n"))
 95                        .font(.caption).foregroundStyle(.secondary).lineLimit(4)
 96                }
 97                if plan.problems.isEmpty {
 98                    Text("Everything can be converted.").font(.subheadline).foregroundStyle(.secondary)
 99                } else {
100                    Text("Not converted, or converted with a loss (\(plan.problems.count)):").font(.subheadline)
101                    List(Array(plan.problems.enumerated()), id: \.offset) { _, problem in
102                        VStack(alignment: .leading, spacing: 1) {
103                            Text(Self.describe(problem.reason))
104                            Text(problem.file).font(.caption).foregroundStyle(.secondary).lineLimit(1).truncationMode(.middle)
105                        }
106                    }
107                    .listStyle(.bordered)
108                }
109            }
110            .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
111        } else {
112            Spacer()
113        }
114    }
115
116    static func describe(_ reason: MarkdownImport.Problem.Reason) -> String {
117        switch reason {
118        case .unreadable: String(localized: "Not UTF-8 text; not imported.", comment: "Markdown import problem")
119        case .notConverted: String(localized: "Canvas and base files have no org equivalent; not imported.", comment: "Markdown import problem")
120        case .converted(let issue):
121            switch issue {
122            case .unresolvedLink(let link): String(localized: "Link to \(link), which isn't among the files imported.", comment: "Markdown import problem")
123            case .missingHeading(let link): String(localized: "Link to \(link): no such heading or block, so the link goes to the file.", comment: "Markdown import problem")
124            case .frontMatter(let key): String(localized: "Front matter \(key) holds a nested map and was left out.", comment: "Markdown import problem")
125            case .recurrence: String(localized: "A task's 🔁 recurrence is kept as text.", comment: "Markdown import problem")
126            case .taskStatus(let status): String(localized: "Task status [\(status)] became an open checkbox.", comment: "Markdown import problem")
127            case .nestedHeading(let text): String(localized: "Heading \(text) inside a list or quote became a bold line.", comment: "Markdown import problem")
128            }
129        }
130    }
131
132    private func choose() {
133        let panel = NSOpenPanel()
134        panel.canChooseDirectories = true
135        panel.canChooseFiles = kind == .markdown
136        panel.allowsMultipleSelection = kind == .markdown
137        if kind == .markdown { panel.allowedContentTypes = [UTType(filenameExtension: "md") ?? .plainText, UTType(filenameExtension: "markdown") ?? .plainText, .folder] }
138        panel.prompt = String(localized: "Choose", comment: "Open panel button")
139        panel.message = kind == .obsidian ? String(localized: "Choose the vault's folder.", comment: "Open panel for importing an Obsidian vault")
140            : String(localized: "Choose Markdown files, or folders of them.", comment: "Open panel for importing Markdown files")
141        guard panel.runModal() == .OK, !panel.urls.isEmpty else {
142            if sources.isEmpty { dismiss() }
143            return
144        }
145        sources = panel.urls
146    }
147
148    private func makePlan() async {
149        plan = nil
150        failure = nil
151        guard !sources.isEmpty, !destination.isEmpty else { return }
152        planning = true
153        defer { planning = false }
154        let (kind, sources, destination) = (kind, sources, URL(fileURLWithPath: destination))
155        do {
156            let made = try await Task.detached { try MarkdownImport.plan(kind, sources: sources, into: destination) }.value
157            guard !Task.isCancelled else { return }
158            plan = made
159        } catch {
160            failure = error.localizedDescription
161        }
162    }
163
164    private func runImport() {
165        guard let plan else { return }
166        importing = true
167        Task {
168            defer { importing = false }
169            do {
170                let written = try await Task.detached { try MarkdownImport.write(plan) }.value
171                await workspace.filesChanged(written.paths.map { URL(fileURLWithPath: $0) }, rescan: [])
172                var message = String(localized: "Imported \(plan.notes) files and \(plan.attachments) attachments.", comment: "Message after a Markdown import")
173                if !written.renamed.isEmpty {
174                    message += " " + String(localized: "Taken since the preview, so renamed: \(written.renamed.map { "\($0.from) → \($0.to)" }.joined(separator: ", ")).",
175                                            comment: "Message after a Markdown import")
176                }
177                dismiss()
178                done(message)
179            } catch {
180                failure = error.localizedDescription
181            }
182        }
183    }
184}
185
186/// Which import sheet is showing.
187enum MarkdownImportKind: String, Identifiable {
188    case markdown, obsidian
189
190    var id: String { rawValue }
191    var kind: MarkdownImport.Kind { self == .obsidian ? .obsidian : .markdown }
192}
Keyboard shortcuts

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form