Sources/OrgstarMobile/ExportMenu.swift
70 lines · 2904 bytes
1#if os(iOS)
2import CoreTransferable
3import OrgApp
4import OrgCore
5import OrgPresentation
6import SwiftUI
7import UniformTypeIdentifiers
8
9/// A file exported as HTML or Markdown, written when the share sheet takes it.
10struct OrgExport: Transferable {
11 enum Format { case html, markdown }
12
13 let text: String
14 let path: String
15 let format: Format
16 let settings: OrgSettings
17 /// Made on the main actor, where the editor's highlighter is.
18 let codeStyle: HTMLCodeStyle
19
20 /// `#+EXPORT_FILE_NAME`'s name, or the file's, with the format's extension.
21 var fileName: String {
22 ExportScope.output(for: URL(fileURLWithPath: path), name: ExportScope.fileName(text, settings: settings), extension: format == .html ? "html" : "md")
23 .lastPathComponent
24 }
25
26 static var transferRepresentation: some TransferRepresentation {
27 FileRepresentation(exportedContentType: .html) { export in
28 try export.write()
29 }
30 .exportingCondition { $0.format == .html }
31 FileRepresentation(exportedContentType: UTType(filenameExtension: "md") ?? .plainText) { export in
32 try export.write()
33 }
34 .exportingCondition { $0.format == .markdown }
35 }
36
37 private func write() throws -> SentTransferredFile {
38 let base = ((path as NSString).lastPathComponent as NSString).deletingPathExtension
39 let settings = settings.resolvingSetupFiles(in: text, path: path, read: OrgSettings.readFile)
40 let content = switch format {
41 case .html: HTMLExport.page(
42 text, fallbackTitle: base, settings: settings, path: path, codeStyle: codeStyle
43 )
44 case .markdown: MarkdownExport.document(text, settings: settings, path: path)
45 }
46 let folder = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
47 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
48 let url = folder.appendingPathComponent(fileName)
49 try content.write(to: url, atomically: true, encoding: .utf8)
50 return SentTransferredFile(url)
51 }
52}
53
54/// Sharing the file as HTML or Markdown: to another app, or saved with Save to Files.
55struct ExportMenu: View {
56 let path: String
57 let text: String
58 @Environment(MobileModel.self) private var model
59
60 var body: some View {
61 Menu("Export", systemImage: "square.and.arrow.up") {
62 ForEach([(OrgExport.Format.html, "HTML"), (.markdown, "Markdown")], id: \.1) { format, name in
63 let export = OrgExport(text: text, path: path, format: format, settings: OrgPreferences.orgSettings(),
64 codeStyle: HTMLCodeStyle(highlighter: MobileEditor.highlighter, theme: model.theme))
65 ShareLink(item: export, preview: SharePreview(export.fileName)) { Text(name) }
66 }
67 }
68 }
69}
70#endif