DomainDig/ExportPresenter.swift

2ad5d8160338d289a65d6a4d1c214a02bf916f1f
domain-dig/DomainDig/ExportPresenter.swift history · blame · raw

64 lines · 2315 bytes

4 symbols in this file
 1import SwiftUI
 2import UIKit
 3
 4enum ExportPresenter {
 5    static func share(filename: String, contents: String) {
 6        share(filename: filename, data: Data(contents.utf8))
 7    }
 8
 9    static func share(filename: String, data: Data) {
10        let url = FileManager.default.temporaryDirectory.appendingPathComponent(filename)
11
12        do {
13            try data.write(to: url, options: .atomic)
14        } catch {
15            return
16        }
17
18        let activityController = UIActivityViewController(activityItems: [url], applicationActivities: nil)
19        guard let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene,
20              let rootViewController = windowScene.keyWindow?.rootViewController else {
21            return
22        }
23
24        var presenter = rootViewController
25        while let presentedViewController = presenter.presentedViewController {
26            presenter = presentedViewController
27        }
28
29        activityController.popoverPresentationController?.sourceView = presenter.view
30        presenter.present(activityController, animated: true)
31    }
32}
33
34/// The export menu's entries: text for everyone, the other formats with
35/// advanced exports, and otherwise disabled Pro upsells in their place.
36struct ExportFormatButtons: View {
37    let share: (DomainExportFormat) -> Void
38    /// Labels the entries as exporting a batch.
39    var batch = false
40
41    var body: some View {
42        let noun = batch ? " Batch" : ""
43        Button("Export\(noun) TXT") {
44            share(.text)
45        }
46        if FeatureAccessService.hasAccess(to: .advancedExports) {
47            ForEach(Self.advancedFormats, id: \.label) { format in
48                Button("Export\(noun) \(format.label)") {
49                    share(format.format)
50                }
51            }
52        } else {
53            ForEach(Self.advancedFormats, id: \.label) { format in
54                // Inert: disabled Pro upsell affordance.
55                Button(batch ? "Batch \(format.label) • Available in Pro" : "\(format.label) Export • Available in Pro") {}
56                    .disabled(true)
57            }
58        }
59    }
60
61    private static let advancedFormats: [(label: String, format: DomainExportFormat)] = [
62        ("CSV", .csv), ("JSON", .json), ("Markdown", .markdown), ("PDF", .pdf),
63    ]
64}