Sources/OrgstarMobile/ExportMenu.swift

19f9854b18b7152959f32c359db2d94fe4ad7f5a
orgstar/Sources/OrgstarMobile/ExportMenu.swift

195 lines · 9759 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    /// Posted with the message, for the screen's message line, when the LaTeX export refuses
 64    /// the file: the share sheet shows no reason.
 65    static let refused = Notification.Name("OrgExportRefused")
 66
 67    static var transferRepresentation: some TransferRepresentation {
 68        FileRepresentation(exportedContentType: .html) { try await $0.write() }
 69            .exportingCondition { $0.format == .html }
 70        FileRepresentation(exportedContentType: UTType(filenameExtension: "md") ?? .plainText) { try await $0.write() }
 71            .exportingCondition { $0.format == .markdown }
 72        FileRepresentation(exportedContentType: .pdf) { try await $0.write() }
 73            .exportingCondition { $0.format == .pdf }
 74        FileRepresentation(exportedContentType: UTType(filenameExtension: "docx") ?? .data) { try await $0.write() }
 75            .exportingCondition { $0.format == .docx }
 76        FileRepresentation(exportedContentType: .rtf) { try await $0.write() }
 77            .exportingCondition { $0.format == .rtf }
 78        FileRepresentation(exportedContentType: .plainText) { try await $0.write() }
 79            .exportingCondition { $0.format == .plainText }
 80        FileRepresentation(exportedContentType: .calendarEvent) { try await $0.write() }
 81            .exportingCondition { $0.format == .icalendar }
 82        FileRepresentation(exportedContentType: UTType(filenameExtension: "tex") ?? .plainText) { try await $0.write() }
 83            .exportingCondition { $0.format == .latex }
 84    }
 85
 86    private func write() async throws -> SentTransferredFile {
 87        let base = ((path as NSString).lastPathComponent as NSString).deletingPathExtension
 88        let settings = settings.resolvingSetupFiles(in: text, path: path, read: OrgSettings.readFile)
 89        let folder = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
 90        try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
 91        let url = folder.appendingPathComponent(fileName)
 92        let text = subtree.flatMap { ExportScope.subtree(self.text, at: $0, settings: settings) } ?? self.text
 93        switch format {
 94        case .html:
 95            try HTMLExport.page(text, fallbackTitle: base, settings: settings, path: path, codeStyle: codeStyle, language: OrgPreferences.exportLanguage())
 96                .write(to: url, atomically: true, encoding: .utf8)
 97        case .markdown:
 98            try MarkdownExport.document(text, settings: settings, path: path).write(to: url, atomically: true, encoding: .utf8)
 99        case .latex:
100            let content: String
101            do {
102                content = try LaTeXExport.document(text, settings: settings, path: path, language: OrgPreferences.exportLanguage(), file: true)
103            } catch let error as LaTeXExport.Unsupported {
104                let message = "Can't export to LaTeX: \(error.reason)"
105                await MainActor.run { NotificationCenter.default.post(name: Self.refused, object: message) }
106                throw error
107            }
108            try content.write(to: url, atomically: true, encoding: .utf8)
109        case .icalendar:
110            try ICalendarFiles.export(self.text, path: path, settings: settings, options: OrgPreferences.icalendarOptions(),
111                                      subtree: subtree, destination: url)
112        case .docx:
113            let html = HTMLExport.page(text, fallbackTitle: base, settings: settings, path: path, codeStyle: codeStyle, language: OrgPreferences.exportLanguage())
114            try await RichTextExport.docx(html: html, directory: URL(fileURLWithPath: path).deletingLastPathComponent()).write(to: url, options: .atomic)
115        case .pdf, .rtf, .plainText:
116            let html = HTMLExport.page(text, fallbackTitle: base, settings: settings, path: path, codeStyle: codeStyle, language: OrgPreferences.exportLanguage())
117            let directory = URL(fileURLWithPath: path).deletingLastPathComponent()
118            let data: Data = switch format {
119            case .pdf: try await PDFExport.pdf(html: html, directory: directory, options: OrgPreferences.pdfOptions())
120            case .rtf: try await RichTextExport.rtf(html: html, directory: directory)
121            default: Data(try await RichTextExport.plain(html: html, directory: directory).utf8)
122            }
123            try data.write(to: url, options: .atomic)
124        }
125        return SentTransferredFile(url)
126    }
127}
128
129/// Sharing the file as HTML, Markdown, PDF, Word, RTF, plain text, iCalendar or LaTeX: to another app, or saved with
130/// Save to Files; or copying it as rich text.
131struct ExportMenu: View {
132    let path: String
133    let text: String
134    @Environment(MobileModel.self) private var model
135    /// Shows what happened, as the screen's message line does.
136    var report: (String) -> Void = { _ in }
137    /// Offers the subtree at the caret alone, where there is a caret.
138    var exportSubtree: (() -> Void)?
139
140    var body: some View {
141        Menu("Export", systemImage: "square.and.arrow.up") {
142            ForEach(OrgExport.Format.allCases, id: \.self) { format in
143                if format.locked {
144                    Button("\(format.name) (orgstar+)") { ProAccess.shared.allows(.export) }
145                } else {
146                    let export = OrgExport(text: text, path: path, format: format, settings: OrgPreferences.orgSettings(),
147                                           codeStyle: HTMLCodeStyle(highlighter: MobileEditor.highlighter, theme: model.theme))
148                    ShareLink(item: export, preview: SharePreview(export.fileName)) { Text(format.name) }
149                }
150            }
151            if let exportSubtree {
152                Button("Export Subtree…", systemImage: "list.bullet.indent") { exportSubtree() }
153            }
154            Divider()
155            Button("Copy as Rich Text", systemImage: "doc.on.doc") { if ProAccess.shared.allows(.export) { copy() } }
156        }
157    }
158
159    /// The file on the clipboard as HTML, RTF and plain text, to paste formatted.
160    private func copy() {
161        let base = ((path as NSString).lastPathComponent as NSString).deletingPathExtension
162        let settings = OrgPreferences.orgSettings().resolvingSetupFiles(in: text, path: path, read: OrgSettings.readFile)
163        let html = HTMLExport.page(text, fallbackTitle: base, settings: settings, path: path,
164                                   codeStyle: HTMLCodeStyle(highlighter: MobileEditor.highlighter, theme: model.theme), language: OrgPreferences.exportLanguage())
165        do {
166            try RichTextExport.copy(html: html, directory: URL(fileURLWithPath: path).deletingLastPathComponent())
167            report("Copied as rich text")
168        } catch {
169            report("\(error)")
170        }
171    }
172}
173
174/// The subtree at `caret` shared alone, in each of the export formats.
175struct SubtreeExportScreen: View {
176    let path: String
177    let text: String
178    let caret: Int
179    @Environment(MobileModel.self) private var model
180    @Environment(\.dismiss) private var dismiss
181
182    var body: some View {
183        NavigationStack {
184            List(OrgExport.Format.allCases.filter { !$0.locked }, id: \.self) { format in
185                let export = OrgExport(text: text, path: path, format: format, settings: OrgPreferences.orgSettings(),
186                                       codeStyle: HTMLCodeStyle(highlighter: MobileEditor.highlighter, theme: model.theme), subtree: caret)
187                ShareLink(item: export, preview: SharePreview(export.fileName)) { Text(format.name) }
188            }
189            .navigationTitle("Export Subtree")
190            .navigationBarTitleDisplayMode(.inline)
191            .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Done") { dismiss() } } }
192        }
193    }
194}
195#endif
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