Sources/OrgstarMobile/ExportMenu.swift

09c5ecd551a0ae8f5078cb88c33958c92428d71f
orgstar/Sources/OrgstarMobile/ExportMenu.swift

300 lines · 15604 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        /// Whether it can leave out the title and the page around the text.
 35        var allowsBodyOnly: Bool { [.html, .markdown, .latex, .ascii].contains(self) }
 36
 37        var fileExtension: String {
 38            switch self {
 39            case .html: "html"
 40            case .markdown: "md"
 41            case .pdf: "pdf"
 42            case .docx: "docx"
 43            case .rtf: "rtf"
 44            case .plainText: "txt"
 45            case .odt: "odt"
 46            case .icalendar: "ics"
 47            case .latex: "tex"
 48            case .ascii: "txt"
 49            }
 50        }
 51    }
 52
 53    let text: String
 54    let path: String
 55    let format: Format
 56    let settings: OrgSettings
 57    /// Made on the main actor, where the editor's highlighter is.
 58    let codeStyle: HTMLCodeStyle
 59    /// The subtree at this offset exported alone.
 60    var subtree: Int?
 61    /// Without the title and the page around the text, in the formats that allow it.
 62    var bodyOnly = false
 63
 64    /// The subtree's `EXPORT_FILE_NAME`, `#+EXPORT_FILE_NAME`'s name, or the file's, with the
 65    /// format's extension.
 66    var fileName: String {
 67        ExportScope.output(for: URL(fileURLWithPath: path), name: ExportScope.fileName(text, subtreeAt: subtree, settings: settings),
 68                           extension: format.fileExtension)
 69            .lastPathComponent
 70    }
 71
 72    /// Posted with the message, for the screen's message line, when the LaTeX or ASCII export
 73    /// refuses the file: the share sheet shows no reason.
 74    static let refused = Notification.Name("OrgExportRefused")
 75
 76    static var transferRepresentation: some TransferRepresentation {
 77        FileRepresentation(exportedContentType: .html) { try await $0.write() }
 78            .exportingCondition { $0.format == .html }
 79        FileRepresentation(exportedContentType: UTType(filenameExtension: "md") ?? .plainText) { try await $0.write() }
 80            .exportingCondition { $0.format == .markdown }
 81        FileRepresentation(exportedContentType: .pdf) { try await $0.write() }
 82            .exportingCondition { $0.format == .pdf }
 83        FileRepresentation(exportedContentType: UTType(filenameExtension: "docx") ?? .data) { try await $0.write() }
 84            .exportingCondition { $0.format == .docx }
 85        FileRepresentation(exportedContentType: .rtf) { try await $0.write() }
 86            .exportingCondition { $0.format == .rtf }
 87        FileRepresentation(exportedContentType: .plainText) { try await $0.write() }
 88            .exportingCondition { $0.format == .plainText }
 89        FileRepresentation(exportedContentType: UTType(filenameExtension: "odt") ?? .data) { try await $0.write() }
 90            .exportingCondition { $0.format == .odt }
 91        FileRepresentation(exportedContentType: .calendarEvent) { try await $0.write() }
 92            .exportingCondition { $0.format == .icalendar }
 93        FileRepresentation(exportedContentType: UTType(filenameExtension: "tex") ?? .plainText) { try await $0.write() }
 94            .exportingCondition { $0.format == .latex }
 95        FileRepresentation(exportedContentType: .plainText) { try await $0.write() }
 96            .exportingCondition { $0.format == .ascii }
 97    }
 98
 99    /// The page HTML export makes of `text`, the file at `path`, with its setup files.
100    @MainActor
101    static func html(_ text: String, path: String, theme: ThemeSpec, bodyOnly: Bool = false) -> String {
102        let base = ((path as NSString).lastPathComponent as NSString).deletingPathExtension
103        let settings = OrgPreferences.orgSettings().resolvingSetupFiles(in: text, path: path, read: OrgSettings.readFile)
104        return HTMLExport.page(text, fallbackTitle: base, settings: settings, path: path, bodyOnly: bodyOnly,
105                               codeStyle: HTMLCodeStyle(highlighter: MobileEditor.highlighter, theme: theme), language: OrgPreferences.exportLanguage())
106    }
107
108    private func write() async throws -> SentTransferredFile {
109        let base = ((path as NSString).lastPathComponent as NSString).deletingPathExtension
110        let settings = settings.resolvingSetupFiles(in: text, path: path, read: OrgSettings.readFile)
111        let folder = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
112        try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
113        let url = folder.appendingPathComponent(fileName)
114        let text = subtree.flatMap { ExportScope.subtree(self.text, at: $0, settings: settings) } ?? self.text
115        switch format {
116        case .html:
117            try HTMLExport.page(text, fallbackTitle: base, settings: settings, path: path, bodyOnly: bodyOnly, codeStyle: codeStyle, language: OrgPreferences.exportLanguage())
118                .write(to: url, atomically: true, encoding: .utf8)
119        case .markdown:
120            try MarkdownExport.document(text, settings: settings, path: path, bodyOnly: bodyOnly).write(to: url, atomically: true, encoding: .utf8)
121        case .latex:
122            let content: String
123            do {
124                content = try LaTeXExport.document(text, settings: settings, path: path, bodyOnly: bodyOnly, language: OrgPreferences.exportLanguage(), file: true)
125            } catch let error as LaTeXExport.Unsupported {
126                let message = "Can't export to LaTeX: \(error.reason)"
127                await MainActor.run { NotificationCenter.default.post(name: Self.refused, object: message) }
128                throw error
129            }
130            try content.write(to: url, atomically: true, encoding: .utf8)
131        case .ascii:
132            let content: String
133            do {
134                content = try ASCIIExport.document(text, settings: settings, path: path, bodyOnly: bodyOnly, language: OrgPreferences.exportLanguage(), file: true)
135            } catch let error as ASCIIExport.Unsupported {
136                let message = "Can't export to plain text: \(error.reason)"
137                await MainActor.run { NotificationCenter.default.post(name: Self.refused, object: message) }
138                throw error
139            }
140            try content.write(to: url, atomically: true, encoding: .utf8)
141        case .odt:
142            try ODTExport.document(text, settings: settings, path: path, language: OrgPreferences.exportLanguage())
143                .write(to: url, options: .atomic)
144        case .icalendar:
145            try ICalendarFiles.export(self.text, path: path, settings: settings, options: OrgPreferences.icalendarOptions(),
146                                      subtree: subtree, destination: url)
147        case .docx:
148            let html = HTMLExport.page(text, fallbackTitle: base, settings: settings, path: path, codeStyle: codeStyle, language: OrgPreferences.exportLanguage())
149            try await RichTextExport.docx(html: html, directory: URL(fileURLWithPath: path).deletingLastPathComponent()).write(to: url, options: .atomic)
150        case .pdf, .rtf, .plainText:
151            let html = HTMLExport.page(text, fallbackTitle: base, settings: settings, path: path, codeStyle: codeStyle, language: OrgPreferences.exportLanguage())
152            let directory = URL(fileURLWithPath: path).deletingLastPathComponent()
153            let data: Data = switch format {
154            case .pdf: try await PDFExport.pdf(html: html, directory: directory, options: OrgPreferences.pdfOptions())
155            case .rtf: try await RichTextExport.rtf(html: html, directory: directory)
156            default: Data(try await RichTextExport.plain(html: html, directory: directory).utf8)
157            }
158            try data.write(to: url, options: .atomic)
159        }
160        return SentTransferredFile(url)
161    }
162}
163
164/// Sharing the file as HTML, Markdown, PDF, Word, RTF, plain text, ODT, iCalendar, LaTeX or ASCII: to another app, or saved with
165/// Save to Files; or copying it as rich text.
166struct ExportMenu: View {
167    let path: String
168    let text: String
169    @Environment(MobileModel.self) private var model
170    /// Shows what happened, as the screen's message line does.
171    var report: (String) -> Void = { _ in }
172    /// Offers the subtree at the caret alone, where there is a caret.
173    var exportSubtree: (() -> Void)?
174    /// Every file's export settings as kept, so the menu follows a change to this file's.
175    @AppStorage(ExportSettings.key) private var kept = Data()
176
177    var body: some View {
178        let bodyOnly = kept.isEmpty ? false : ExportSettings.saved(for: path).bodyOnly
179        Menu("Export", systemImage: "square.and.arrow.up") {
180            ForEach(OrgExport.Format.allCases, id: \.self) { format in
181                if format.locked {
182                    Button("\(format.name) (orgstar+)") { ProAccess.shared.allows(.export) }
183                } else if bodyOnly, !format.allowsBodyOnly {
184                    Button(format.name) { report(ExportSettings.noBodyOnly) }
185                } else {
186                    let export = OrgExport(text: text, path: path, format: format, settings: OrgPreferences.orgSettings(),
187                                           codeStyle: HTMLCodeStyle(highlighter: MobileEditor.highlighter, theme: model.theme), bodyOnly: bodyOnly)
188                    ShareLink(item: export, preview: SharePreview(export.fileName)) { Text(format.name) }
189                }
190            }
191            Toggle("Body Only", isOn: Binding(get: { bodyOnly }, set: { ExportMenu.setBodyOnly($0, path: path) }))
192            if let exportSubtree {
193                Button("Export Subtree…", systemImage: "list.bullet.indent") { exportSubtree() }
194            }
195            if let calendars = AgendaCalendars(model: model) {
196                Divider()
197                if OrgExport.Format.icalendar.locked {
198                    Button("Agenda Files to iCalendar (orgstar+)") { ProAccess.shared.allows(.export) }
199                } else {
200                    Button("Export Agenda Files to iCalendar", systemImage: "calendar") { report(calendars.exportEach()) }
201                    ShareLink(item: calendars, preview: SharePreview(calendars.fileName)) {
202                        Label("Combine Agenda Files into iCalendar", systemImage: "calendar.badge.plus")
203                    }
204                }
205            }
206            Divider()
207            Button("Copy as Rich Text", systemImage: "doc.on.doc") { if ProAccess.shared.allows(.export) { report(Self.copy(path: path, text: text, theme: model.theme)) } }
208        }
209    }
210
211    /// Keeps the body-only choice for the file at `path`.
212    static func setBodyOnly(_ on: Bool, path: String) {
213        var settings = ExportSettings.saved(for: path)
214        settings.bodyOnly = on
215        settings.save(for: path)
216    }
217
218    /// The file on the clipboard as HTML, RTF and plain text, to paste formatted. Returns a message.
219    @MainActor
220    static func copy(path: String, text: String, theme: ThemeSpec) -> String {
221        let html = OrgExport.html(text, path: path, theme: theme)
222        do {
223            try RichTextExport.copy(html: html, directory: URL(fileURLWithPath: path).deletingLastPathComponent())
224            return "Copied as rich text"
225        } catch {
226            return "\(error)"
227        }
228    }
229}
230
231/// The agenda files as iCalendar: each to a calendar beside it
232/// (`org-icalendar-export-agenda-files`), or all in one calendar to share
233/// (`org-icalendar-combine-agenda-files`), named as `org-icalendar-combined-agenda-file` is.
234struct AgendaCalendars: Transferable {
235    let paths: [String]
236    /// The open files' text, which may not be saved yet.
237    let open: [String: String]
238
239    /// Nil without agenda files.
240    @MainActor init?(model: MobileModel) {
241        guard let paths = model.workspace?.agendaFilePaths(), !paths.isEmpty else { return nil }
242        self.paths = paths
243        open = Dictionary(model.session.openDocuments.map { ($0.path, $0.document.text) }, uniquingKeysWith: { first, _ in first })
244    }
245
246    var fileName: String { (OrgPreferences.icalendarCombinedFile() as NSString).lastPathComponent }
247
248    private func read(_ path: String) -> (text: String, settings: OrgSettings)? {
249        guard let text = open[path] ?? (try? String(contentsOfFile: path, encoding: .utf8)) else { return nil }
250        return (text, OrgPreferences.orgSettings().resolvingSetupFiles(in: text, path: path, read: OrgSettings.readFile))
251    }
252
253    /// Writes each agenda file's calendar beside it. Returns a message.
254    func exportEach() -> String {
255        do {
256            let written = try ICalendarFiles.exportEach(paths, options: OrgPreferences.icalendarOptions(), read: read)
257            return "Exported \(written.count) agenda files to iCalendar"
258        } catch {
259            return "Can't export: \(error.localizedDescription)"
260        }
261    }
262
263    /// The combined calendar, in a new temporary folder.
264    func combined() throws -> URL {
265        let folder = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
266        return try ICalendarFiles.combine(paths, to: folder.appendingPathComponent(fileName).path, options: OrgPreferences.icalendarOptions(), read: read)
267    }
268
269    static var transferRepresentation: some TransferRepresentation {
270        FileRepresentation(exportedContentType: .calendarEvent) { SentTransferredFile(try $0.combined()) }
271    }
272}
273
274/// The subtree at `caret` shared alone, in each of the export formats.
275struct SubtreeExportScreen: View {
276    let path: String
277    let text: String
278    let caret: Int
279    @Environment(MobileModel.self) private var model
280    @Environment(\.dismiss) private var dismiss
281
282    var body: some View {
283        NavigationStack {
284            let bodyOnly = ExportSettings.saved(for: path).bodyOnly
285            List(OrgExport.Format.allCases.filter { !$0.locked }, id: \.self) { format in
286                if bodyOnly, !format.allowsBodyOnly {
287                    LabeledContent(format.name) { Text("No body-only export") }.foregroundStyle(.secondary)
288                } else {
289                    let export = OrgExport(text: text, path: path, format: format, settings: OrgPreferences.orgSettings(),
290                                           codeStyle: HTMLCodeStyle(highlighter: MobileEditor.highlighter, theme: model.theme), subtree: caret, bodyOnly: bodyOnly)
291                    ShareLink(item: export, preview: SharePreview(export.fileName)) { Text(format.name) }
292                }
293            }
294            .navigationTitle("Export Subtree")
295            .navigationBarTitleDisplayMode(.inline)
296            .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Done") { dismiss() } } }
297        }
298    }
299}
300#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