Sources/OrgstarMobile/ExportMenu.swift

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