krz/hutch

an ios client for sourcehut

clone: git clone https://gitbay.org/krz/hutch.git

v2.3.0: Hutch/Extensions/SRHTShareUI.swift · raw

 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    case paste = "paste"
13
14    var fallbackMessage: String {
15        "This \(rawValue) does not have a valid web URL to share."
16    }
17}
18
19struct SRHTShareButton<Label: View>: View {
20    let url: URL?
21    let target: SRHTShareTarget
22    @ViewBuilder let label: () -> Label
23
24    @State private var isShowingShareSheet = false
25    @State private var isShowingFallbackAlert = false
26
27    var body: some View {
28        Button {
29            if url != nil {
30                isShowingShareSheet = true
31            } else {
32                isShowingFallbackAlert = true
33            }
34        } label: {
35            label()
36        }
37        .sheet(isPresented: $isShowingShareSheet) {
38            if let url {
39                ShareSheet(activityItems: [url])
40            }
41        }
42        .alert("Share Unavailable", isPresented: $isShowingFallbackAlert) {
43            Button("OK", role: .cancel) {}
44        } message: {
45            Text(target.fallbackMessage)
46        }
47    }
48}
49
50private struct ShareSheet: UIViewControllerRepresentable {
51    let activityItems: [Any]
52
53    func makeUIViewController(context: Context) -> UIActivityViewController {
54        UIActivityViewController(activityItems: activityItems, applicationActivities: nil)
55    }
56
57    func updateUIViewController(_ uiViewController: UIActivityViewController, context: Context) {}
58}