Sources/OrgstarMobile/ExportMenu.swift

136 lines · 6644 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
 47    /// `#+EXPORT_FILE_NAME`'s name, or the file's, with the format's extension.
 48    var fileName: String {
 49        ExportScope.output(for: URL(fileURLWithPath: path), name: ExportScope.fileName(text, settings: settings), extension: format.fileExtension)
 50            .lastPathComponent
 51    }
 52
 53    static var transferRepresentation: some TransferRepresentation {
 54        FileRepresentation(exportedContentType: .html) { try await $0.write() }
 55            .exportingCondition { $0.format == .html }
 56        FileRepresentation(exportedContentType: UTType(filenameExtension: "md") ?? .plainText) { try await $0.write() }
 57            .exportingCondition { $0.format == .markdown }
 58        FileRepresentation(exportedContentType: .pdf) { try await $0.write() }
 59            .exportingCondition { $0.format == .pdf }
 60        FileRepresentation(exportedContentType: UTType(filenameExtension: "docx") ?? .data) { try await $0.write() }
 61            .exportingCondition { $0.format == .docx }
 62        FileRepresentation(exportedContentType: .rtf) { try await $0.write() }
 63            .exportingCondition { $0.format == .rtf }
 64        FileRepresentation(exportedContentType: .plainText) { try await $0.write() }
 65            .exportingCondition { $0.format == .plainText }
 66        FileRepresentation(exportedContentType: .calendarEvent) { try await $0.write() }
 67            .exportingCondition { $0.format == .icalendar }
 68    }
 69
 70    private func write() async throws -> SentTransferredFile {
 71        let base = ((path as NSString).lastPathComponent as NSString).deletingPathExtension
 72        let settings = settings.resolvingSetupFiles(in: text, path: path, read: OrgSettings.readFile)
 73        let folder = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
 74        try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
 75        let url = folder.appendingPathComponent(fileName)
 76        switch format {
 77        case .html:
 78            try HTMLExport.page(text, fallbackTitle: base, settings: settings, path: path, codeStyle: codeStyle, language: OrgPreferences.exportLanguage())
 79                .write(to: url, atomically: true, encoding: .utf8)
 80        case .markdown:
 81            try MarkdownExport.document(text, settings: settings, path: path).write(to: url, atomically: true, encoding: .utf8)
 82        case .icalendar:
 83            try ICalendarFiles.export(text, path: path, settings: settings, options: OrgPreferences.icalendarOptions(), destination: url)
 84        case .docx:
 85            let html = HTMLExport.page(text, fallbackTitle: base, settings: settings, path: path, codeStyle: codeStyle, language: OrgPreferences.exportLanguage())
 86            try await RichTextExport.docx(html: html, directory: URL(fileURLWithPath: path).deletingLastPathComponent()).write(to: url, options: .atomic)
 87        case .pdf, .rtf, .plainText:
 88            let html = HTMLExport.page(text, fallbackTitle: base, settings: settings, path: path, codeStyle: codeStyle, language: OrgPreferences.exportLanguage())
 89            let directory = URL(fileURLWithPath: path).deletingLastPathComponent()
 90            let data: Data = switch format {
 91            case .pdf: try await PDFExport.pdf(html: html, directory: directory)
 92            case .rtf: try await RichTextExport.rtf(html: html, directory: directory)
 93            default: Data(try await RichTextExport.plain(html: html, directory: directory).utf8)
 94            }
 95            try data.write(to: url, options: .atomic)
 96        }
 97        return SentTransferredFile(url)
 98    }
 99}
100
101/// Sharing the file as HTML, Markdown, PDF, Word, RTF, plain text or iCalendar: to another app, or saved with
102/// Save to Files; or copying it as rich text.
103struct ExportMenu: View {
104    let path: String
105    let text: String
106    @Environment(MobileModel.self) private var model
107    /// Shows what happened, as the screen's message line does.
108    var report: (String) -> Void = { _ in }
109
110    var body: some View {
111        Menu("Export", systemImage: "square.and.arrow.up") {
112            ForEach(OrgExport.Format.allCases, id: \.self) { format in
113                let export = OrgExport(text: text, path: path, format: format, settings: OrgPreferences.orgSettings(),
114                                       codeStyle: HTMLCodeStyle(highlighter: MobileEditor.highlighter, theme: model.theme))
115                ShareLink(item: export, preview: SharePreview(export.fileName)) { Text(format.name) }
116            }
117            Divider()
118            Button("Copy as Rich Text", systemImage: "doc.on.doc") { copy() }
119        }
120    }
121
122    /// The file on the clipboard as HTML, RTF and plain text, to paste formatted.
123    private func copy() {
124        let base = ((path as NSString).lastPathComponent as NSString).deletingPathExtension
125        let settings = OrgPreferences.orgSettings().resolvingSetupFiles(in: text, path: path, read: OrgSettings.readFile)
126        let html = HTMLExport.page(text, fallbackTitle: base, settings: settings, path: path,
127                                   codeStyle: HTMLCodeStyle(highlighter: MobileEditor.highlighter, theme: model.theme), language: OrgPreferences.exportLanguage())
128        do {
129            try RichTextExport.copy(html: html, directory: URL(fileURLWithPath: path).deletingLastPathComponent())
130            report("Copied as rich text")
131        } catch {
132            report("\(error)")
133        }
134    }
135}
136#endif