Sources/OrgstarMobile/ExportMenu.swift
169 lines · 8219 bytes
1#if os(iOS)
2import CoreTransferable
3import OrgApp
4import OrgCore
5import OrgPresentation
6import SwiftUI
7import UniformTypeIdentifiers
8
9/// A file exported as HTML, Markdown, PDF, Word, RTF, plain text or iCalendar, written when the
10/// share sheet takes it.
11struct OrgExport: Transferable {
12 enum Format: CaseIterable {
13 case html, markdown, pdf, docx, rtf, plainText, icalendar
14
15 var name: String {
16 switch self {
17 case .html: "HTML"
18 case .markdown: "Markdown"
19 case .pdf: "PDF"
20 case .docx: "Word"
21 case .rtf: "Rich Text (RTF)"
22 case .plainText: "Plain Text"
23 case .icalendar: "iCalendar"
24 }
25 }
26
27 var fileExtension: String {
28 switch self {
29 case .html: "html"
30 case .markdown: "md"
31 case .pdf: "pdf"
32 case .docx: "docx"
33 case .rtf: "rtf"
34 case .plainText: "txt"
35 case .icalendar: "ics"
36 }
37 }
38 }
39
40 let text: String
41 let path: String
42 let format: Format
43 let settings: OrgSettings
44 /// Made on the main actor, where the editor's highlighter is.
45 let codeStyle: HTMLCodeStyle
46 /// The subtree at this offset exported alone.
47 var subtree: Int?
48
49 /// The subtree's `EXPORT_FILE_NAME`, `#+EXPORT_FILE_NAME`'s name, or the file's, with the
50 /// format's extension.
51 var fileName: String {
52 ExportScope.output(for: URL(fileURLWithPath: path), name: ExportScope.fileName(text, subtreeAt: subtree, settings: settings),
53 extension: format.fileExtension)
54 .lastPathComponent
55 }
56
57 static var transferRepresentation: some TransferRepresentation {
58 FileRepresentation(exportedContentType: .html) { try await $0.write() }
59 .exportingCondition { $0.format == .html }
60 FileRepresentation(exportedContentType: UTType(filenameExtension: "md") ?? .plainText) { try await $0.write() }
61 .exportingCondition { $0.format == .markdown }
62 FileRepresentation(exportedContentType: .pdf) { try await $0.write() }
63 .exportingCondition { $0.format == .pdf }
64 FileRepresentation(exportedContentType: UTType(filenameExtension: "docx") ?? .data) { try await $0.write() }
65 .exportingCondition { $0.format == .docx }
66 FileRepresentation(exportedContentType: .rtf) { try await $0.write() }
67 .exportingCondition { $0.format == .rtf }
68 FileRepresentation(exportedContentType: .plainText) { try await $0.write() }
69 .exportingCondition { $0.format == .plainText }
70 FileRepresentation(exportedContentType: .calendarEvent) { try await $0.write() }
71 .exportingCondition { $0.format == .icalendar }
72 }
73
74 private func write() async throws -> SentTransferredFile {
75 let base = ((path as NSString).lastPathComponent as NSString).deletingPathExtension
76 let settings = settings.resolvingSetupFiles(in: text, path: path, read: OrgSettings.readFile)
77 let folder = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
78 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
79 let url = folder.appendingPathComponent(fileName)
80 let text = subtree.flatMap { ExportScope.subtree(self.text, at: $0, settings: settings) } ?? self.text
81 switch format {
82 case .html:
83 try HTMLExport.page(text, fallbackTitle: base, settings: settings, path: path, codeStyle: codeStyle, language: OrgPreferences.exportLanguage())
84 .write(to: url, atomically: true, encoding: .utf8)
85 case .markdown:
86 try MarkdownExport.document(text, settings: settings, path: path).write(to: url, atomically: true, encoding: .utf8)
87 case .icalendar:
88 try ICalendarFiles.export(self.text, path: path, settings: settings, options: OrgPreferences.icalendarOptions(),
89 subtree: subtree, destination: url)
90 case .docx:
91 let html = HTMLExport.page(text, fallbackTitle: base, settings: settings, path: path, codeStyle: codeStyle, language: OrgPreferences.exportLanguage())
92 try await RichTextExport.docx(html: html, directory: URL(fileURLWithPath: path).deletingLastPathComponent()).write(to: url, options: .atomic)
93 case .pdf, .rtf, .plainText:
94 let html = HTMLExport.page(text, fallbackTitle: base, settings: settings, path: path, codeStyle: codeStyle, language: OrgPreferences.exportLanguage())
95 let directory = URL(fileURLWithPath: path).deletingLastPathComponent()
96 let data: Data = switch format {
97 case .pdf: try await PDFExport.pdf(html: html, directory: directory)
98 case .rtf: try await RichTextExport.rtf(html: html, directory: directory)
99 default: Data(try await RichTextExport.plain(html: html, directory: directory).utf8)
100 }
101 try data.write(to: url, options: .atomic)
102 }
103 return SentTransferredFile(url)
104 }
105}
106
107/// Sharing the file as HTML, Markdown, PDF, Word, RTF, plain text or iCalendar: to another app, or saved with
108/// Save to Files; or copying it as rich text.
109struct ExportMenu: View {
110 let path: String
111 let text: String
112 @Environment(MobileModel.self) private var model
113 /// Shows what happened, as the screen's message line does.
114 var report: (String) -> Void = { _ in }
115 /// Offers the subtree at the caret alone, where there is a caret.
116 var exportSubtree: (() -> Void)?
117
118 var body: some View {
119 Menu("Export", systemImage: "square.and.arrow.up") {
120 ForEach(OrgExport.Format.allCases, id: \.self) { format in
121 let export = OrgExport(text: text, path: path, format: format, settings: OrgPreferences.orgSettings(),
122 codeStyle: HTMLCodeStyle(highlighter: MobileEditor.highlighter, theme: model.theme))
123 ShareLink(item: export, preview: SharePreview(export.fileName)) { Text(format.name) }
124 }
125 if let exportSubtree {
126 Button("Export Subtree…", systemImage: "list.bullet.indent") { exportSubtree() }
127 }
128 Divider()
129 Button("Copy as Rich Text", systemImage: "doc.on.doc") { copy() }
130 }
131 }
132
133 /// The file on the clipboard as HTML, RTF and plain text, to paste formatted.
134 private func copy() {
135 let base = ((path as NSString).lastPathComponent as NSString).deletingPathExtension
136 let settings = OrgPreferences.orgSettings().resolvingSetupFiles(in: text, path: path, read: OrgSettings.readFile)
137 let html = HTMLExport.page(text, fallbackTitle: base, settings: settings, path: path,
138 codeStyle: HTMLCodeStyle(highlighter: MobileEditor.highlighter, theme: model.theme), language: OrgPreferences.exportLanguage())
139 do {
140 try RichTextExport.copy(html: html, directory: URL(fileURLWithPath: path).deletingLastPathComponent())
141 report("Copied as rich text")
142 } catch {
143 report("\(error)")
144 }
145 }
146}
147
148/// The subtree at `caret` shared alone, in each of the export formats.
149struct SubtreeExportScreen: View {
150 let path: String
151 let text: String
152 let caret: Int
153 @Environment(MobileModel.self) private var model
154 @Environment(\.dismiss) private var dismiss
155
156 var body: some View {
157 NavigationStack {
158 List(OrgExport.Format.allCases, id: \.self) { format in
159 let export = OrgExport(text: text, path: path, format: format, settings: OrgPreferences.orgSettings(),
160 codeStyle: HTMLCodeStyle(highlighter: MobileEditor.highlighter, theme: model.theme), subtree: caret)
161 ShareLink(item: export, preview: SharePreview(export.fileName)) { Text(format.name) }
162 }
163 .navigationTitle("Export Subtree")
164 .navigationBarTitleDisplayMode(.inline)
165 .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Done") { dismiss() } } }
166 }
167 }
168}
169#endif