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