summaryrefslogtreecommitdiff
path: root/Hutch/Extensions/SRHTShareUI.swift
blob: 01f3d919959c18cc548b9ae686802ab1eb46fd3f (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import SwiftUI
import UIKit

enum SRHTShareTarget: String {
    case repository = "repository"
    case commit = "commit"
    case file = "file"
    case build = "build"
    case tracker = "tracker"
    case ticket = "ticket"
    case profile = "profile"
    case paste = "paste"

    var fallbackMessage: String {
        "This \(rawValue) does not have a valid web URL to share."
    }
}

struct SRHTShareButton<Label: View>: View {
    let url: URL?
    let target: SRHTShareTarget
    @ViewBuilder let label: () -> Label

    @State private var isShowingShareSheet = false
    @State private var isShowingFallbackAlert = false

    var body: some View {
        Button {
            if url != nil {
                isShowingShareSheet = true
            } else {
                isShowingFallbackAlert = true
            }
        } label: {
            label()
        }
        .sheet(isPresented: $isShowingShareSheet) {
            if let url {
                ShareSheet(activityItems: [url])
            }
        }
        .alert("Share Unavailable", isPresented: $isShowingFallbackAlert) {
            Button("OK", role: .cancel) {}
        } message: {
            Text(target.fallbackMessage)
        }
    }
}

private struct ShareSheet: UIViewControllerRepresentable {
    let activityItems: [Any]

    func makeUIViewController(context: Context) -> UIActivityViewController {
        UIActivityViewController(activityItems: activityItems, applicationActivities: nil)
    }

    func updateUIViewController(_ uiViewController: UIActivityViewController, context: Context) {}
}