Sources/OrgstarMobile/ExportMenu.swift

cf8b29189934091d7dd0144ced479cc21c4ec764
orgstar/Sources/OrgstarMobile/ExportMenu.swift

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