Sources/Orgstar/ExportSheet.swift
73 lines · 3271 bytes
1import AppKit
2import SwiftUI
3
4/// Export… (`app.export-dialog`): the format, where the file goes, and whether to open it after.
5struct ExportSheet: View {
6 let source: URL
7 /// Whether the caret is in a subtree that can be exported alone.
8 let inSubtree: Bool
9 /// The default destination for an extension, with or without the subtree.
10 let target: (_ ext: String, _ subtree: Bool) -> URL
11 let export: (_ format: String, _ destination: URL, _ open: Bool, _ subtree: Bool, _ bodyOnly: Bool) -> Void
12 @AppStorage("exportFormat") private var format = "html"
13 @AppStorage("exportOpenAfter") private var openAfter = false
14 @AppStorage("exportBodyOnly") private var bodyOnly = false
15 @State private var subtree = false
16 @State private var destination: URL?
17 @Environment(\.dismiss) private var dismiss
18
19 static let formats: [(id: String, title: String, ext: String)] = [
20 ("html", "HTML", "html"), ("markdown", "Markdown", "md"), ("print-pdf", "PDF", "pdf"), ("pdf", "PDF via LaTeX (Emacs)", "pdf"),
21 ("odt", "ODT (Emacs)", "odt"), ("latex", "LaTeX (Emacs)", "tex"), ("text", "Plain text (Emacs)", "txt"),
22 ]
23
24 private var ext: String { Self.formats.first { $0.id == format }?.ext ?? "html" }
25 private var chosen: URL { destination ?? target(ext, subtree) }
26 /// PDF and ODT are whole documents.
27 private var allowsBodyOnly: Bool { !["pdf", "print-pdf", "odt"].contains(format) }
28
29 var body: some View {
30 Form {
31 Picker("Format", selection: $format) {
32 ForEach(Self.formats, id: \.id) { Text($0.title).tag($0.id) }
33 }
34 .onChange(of: format) { destination = destination.map { $0.deletingPathExtension().appendingPathExtension(ext) } }
35 Picker("Scope", selection: $subtree) {
36 Text("Whole file").tag(false)
37 Text("Subtree at the caret").tag(true)
38 }
39 .disabled(!inSubtree)
40 Toggle("Body only", isOn: $bodyOnly)
41 .disabled(!allowsBodyOnly)
42 .help("Leave out the title and page wrapper, as Org's body-only export")
43 LabeledContent("Destination") {
44 HStack {
45 Text(chosen.path(percentEncoded: false)).lineLimit(1).truncationMode(.middle).foregroundStyle(.secondary)
46 Button("Choose…") { choose() }
47 }
48 }
49 Toggle("Open after export", isOn: $openAfter)
50 }
51 .formStyle(.grouped)
52 .safeAreaInset(edge: .bottom) {
53 HStack {
54 Spacer()
55 Button("Cancel") { dismiss() }.keyboardShortcut(.cancelAction)
56 Button("Export") {
57 export(format, chosen, openAfter, subtree && inSubtree, bodyOnly && allowsBodyOnly)
58 dismiss()
59 }
60 .keyboardShortcut(.defaultAction)
61 }
62 .padding()
63 }
64 .frame(width: 520)
65 }
66
67 private func choose() {
68 let panel = NSSavePanel()
69 panel.directoryURL = chosen.deletingLastPathComponent()
70 panel.nameFieldStringValue = chosen.lastPathComponent
71 if panel.runModal() == .OK, let url = panel.url { destination = url }
72 }
73}