Hutch/Extensions/SRHTShareUI.swift
57 lines · 1567 bytes
1import SwiftUI
2import UIKit
3
4enum SRHTShareTarget: String {
5 case repository = "repository"
6 case commit = "commit"
7 case file = "file"
8 case build = "build"
9 case tracker = "tracker"
10 case ticket = "ticket"
11 case profile = "profile"
12
13 var fallbackMessage: String {
14 "This \(rawValue) does not have a valid web URL to share."
15 }
16}
17
18struct SRHTShareButton<Label: View>: View {
19 let url: URL?
20 let target: SRHTShareTarget
21 @ViewBuilder let label: () -> Label
22
23 @State private var isShowingShareSheet = false
24 @State private var isShowingFallbackAlert = false
25
26 var body: some View {
27 Button {
28 if url != nil {
29 isShowingShareSheet = true
30 } else {
31 isShowingFallbackAlert = true
32 }
33 } label: {
34 label()
35 }
36 .sheet(isPresented: $isShowingShareSheet) {
37 if let url {
38 ShareSheet(activityItems: [url])
39 }
40 }
41 .alert("Share Unavailable", isPresented: $isShowingFallbackAlert) {
42 Button("OK", role: .cancel) {}
43 } message: {
44 Text(target.fallbackMessage)
45 }
46 }
47}
48
49private struct ShareSheet: UIViewControllerRepresentable {
50 let activityItems: [Any]
51
52 func makeUIViewController(context: Context) -> UIActivityViewController {
53 UIActivityViewController(activityItems: activityItems, applicationActivities: nil)
54 }
55
56 func updateUIViewController(_ uiViewController: UIActivityViewController, context: Context) {}
57}