Sources/OrgstarMobile/ExportMenu.swift

791ada4f3c5c635a1aebb4eb90edc01a1ba96a8a
orgstar/Sources/OrgstarMobile/ExportMenu.swift

61 lines · 2326 bytes

 1#if os(iOS)
 2import CoreTransferable
 3import OrgApp
 4import OrgCore
 5import SwiftUI
 6import UniformTypeIdentifiers
 7
 8/// A file exported as HTML or Markdown, written when the share sheet takes it.
 9struct OrgExport: Transferable {
10    enum Format { case html, markdown }
11
12    let text: String
13    let path: String
14    let format: Format
15    let settings: OrgSettings
16
17    var fileName: String {
18        let base = ((path as NSString).lastPathComponent as NSString).deletingPathExtension
19        return base + (format == .html ? ".html" : ".md")
20    }
21
22    static var transferRepresentation: some TransferRepresentation {
23        FileRepresentation(exportedContentType: .html) { export in
24            try export.write()
25        }
26        .exportingCondition { $0.format == .html }
27        FileRepresentation(exportedContentType: UTType(filenameExtension: "md") ?? .plainText) { export in
28            try export.write()
29        }
30        .exportingCondition { $0.format == .markdown }
31    }
32
33    private func write() throws -> SentTransferredFile {
34        let base = ((path as NSString).lastPathComponent as NSString).deletingPathExtension
35        let content = switch format {
36        case .html: HTMLExport.page(text, fallbackTitle: base, settings: settings, path: path)
37        case .markdown: MarkdownExport.document(text, settings: settings)
38        }
39        let folder = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
40        try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
41        let url = folder.appendingPathComponent(fileName)
42        try content.write(to: url, atomically: true, encoding: .utf8)
43        return SentTransferredFile(url)
44    }
45}
46
47/// Sharing the file as HTML or Markdown: to another app, or saved with Save to Files.
48struct ExportMenu: View {
49    let path: String
50    let text: String
51
52    var body: some View {
53        Menu("Export", systemImage: "square.and.arrow.up") {
54            ForEach([(OrgExport.Format.html, "HTML"), (.markdown, "Markdown")], id: \.1) { format, name in
55                let export = OrgExport(text: text, path: path, format: format, settings: OrgPreferences.orgSettings())
56                ShareLink(item: export, preview: SharePreview(export.fileName)) { Text(name) }
57            }
58        }
59    }
60}
61#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