Sources/OrgstarMobile/ExportMenu.swift

848c7b130274052f194a17fccd4e33e6bb30851d
orgstar/Sources/OrgstarMobile/ExportMenu.swift history · blame · raw

122 lines · 5484 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 or PDF, written when the share sheet takes it.
 10struct OrgExport: Transferable {
 11    enum Format: CaseIterable {
 12        case html, markdown, pdf, rtf, plainText
 13
 14        var name: String {
 15            switch self {
 16            case .html: "HTML"
 17            case .markdown: "Markdown"
 18            case .pdf: "PDF"
 19            case .rtf: "Rich Text (RTF)"
 20            case .plainText: "Plain Text"
 21            }
 22        }
 23
 24        var fileExtension: String {
 25            switch self {
 26            case .html: "html"
 27            case .markdown: "md"
 28            case .pdf: "pdf"
 29            case .rtf: "rtf"
 30            case .plainText: "txt"
 31            }
 32        }
 33    }
 34
 35    let text: String
 36    let path: String
 37    let format: Format
 38    let settings: OrgSettings
 39    /// Made on the main actor, where the editor's highlighter is.
 40    let codeStyle: HTMLCodeStyle
 41
 42    /// `#+EXPORT_FILE_NAME`'s name, or the file's, with the format's extension.
 43    var fileName: String {
 44        ExportScope.output(for: URL(fileURLWithPath: path), name: ExportScope.fileName(text, settings: settings), extension: format.fileExtension)
 45            .lastPathComponent
 46    }
 47
 48    static var transferRepresentation: some TransferRepresentation {
 49        FileRepresentation(exportedContentType: .html) { try await $0.write() }
 50            .exportingCondition { $0.format == .html }
 51        FileRepresentation(exportedContentType: UTType(filenameExtension: "md") ?? .plainText) { try await $0.write() }
 52            .exportingCondition { $0.format == .markdown }
 53        FileRepresentation(exportedContentType: .pdf) { try await $0.write() }
 54            .exportingCondition { $0.format == .pdf }
 55        FileRepresentation(exportedContentType: .rtf) { try await $0.write() }
 56            .exportingCondition { $0.format == .rtf }
 57        FileRepresentation(exportedContentType: .plainText) { try await $0.write() }
 58            .exportingCondition { $0.format == .plainText }
 59    }
 60
 61    private func write() async throws -> SentTransferredFile {
 62        let base = ((path as NSString).lastPathComponent as NSString).deletingPathExtension
 63        let settings = settings.resolvingSetupFiles(in: text, path: path, read: OrgSettings.readFile)
 64        let folder = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
 65        try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
 66        let url = folder.appendingPathComponent(fileName)
 67        switch format {
 68        case .html:
 69            try HTMLExport.page(text, fallbackTitle: base, settings: settings, path: path, codeStyle: codeStyle)
 70                .write(to: url, atomically: true, encoding: .utf8)
 71        case .markdown:
 72            try MarkdownExport.document(text, settings: settings, path: path).write(to: url, atomically: true, encoding: .utf8)
 73        case .pdf, .rtf, .plainText:
 74            let html = HTMLExport.page(text, fallbackTitle: base, settings: settings, path: path, codeStyle: codeStyle)
 75            let directory = URL(fileURLWithPath: path).deletingLastPathComponent()
 76            let data: Data = switch format {
 77            case .pdf: try await PDFExport.pdf(html: html, directory: directory)
 78            case .rtf: try await RichTextExport.rtf(html: html, directory: directory)
 79            default: Data(try await RichTextExport.plain(html: html, directory: directory).utf8)
 80            }
 81            try data.write(to: url, options: .atomic)
 82        }
 83        return SentTransferredFile(url)
 84    }
 85}
 86
 87/// Sharing the file as HTML, Markdown, PDF, RTF or plain text: to another app, or saved with
 88/// Save to Files; or copying it as rich text.
 89struct ExportMenu: View {
 90    let path: String
 91    let text: String
 92    @Environment(MobileModel.self) private var model
 93    /// Shows what happened, as the screen's message line does.
 94    var report: (String) -> Void = { _ in }
 95
 96    var body: some View {
 97        Menu("Export", systemImage: "square.and.arrow.up") {
 98            ForEach(OrgExport.Format.allCases, id: \.self) { format in
 99                let export = OrgExport(text: text, path: path, format: format, settings: OrgPreferences.orgSettings(),
100                                       codeStyle: HTMLCodeStyle(highlighter: MobileEditor.highlighter, theme: model.theme))
101                ShareLink(item: export, preview: SharePreview(export.fileName)) { Text(format.name) }
102            }
103            Divider()
104            Button("Copy as Rich Text", systemImage: "doc.on.doc") { copy() }
105        }
106    }
107
108    /// The file on the clipboard as HTML, RTF and plain text, to paste formatted.
109    private func copy() {
110        let base = ((path as NSString).lastPathComponent as NSString).deletingPathExtension
111        let settings = OrgPreferences.orgSettings().resolvingSetupFiles(in: text, path: path, read: OrgSettings.readFile)
112        let html = HTMLExport.page(text, fallbackTitle: base, settings: settings, path: path,
113                                   codeStyle: HTMLCodeStyle(highlighter: MobileEditor.highlighter, theme: model.theme))
114        do {
115            try RichTextExport.copy(html: html, directory: URL(fileURLWithPath: path).deletingLastPathComponent())
116            report("Copied as rich text")
117        } catch {
118            report("\(error)")
119        }
120    }
121}
122#endif