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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
import SafariServices
import SwiftUI
struct PostLinks: View {
let urls: [URL]
let openPost: (String) -> Void
var body: some View {
let _: Void = ViewUpdateMetrics.record(urls.isEmpty ? "PostLinks-empty" : "PostLinks-links")
return ForEach(urls, id: \.absoluteString) { url in
if let postID = internalPostID(for: url) {
Button {
openPost(postID)
} label: {
Text(url.absoluteString)
.foregroundStyle(.tint)
.multilineTextAlignment(.leading)
}
.accessibilityIdentifier("internalPostLink")
} else {
Link(destination: url) {
Text(url.absoluteString)
.foregroundStyle(.tint)
.multilineTextAlignment(.leading)
}
.accessibilityIdentifier("externalTextLink")
}
}
.buttonStyle(.plain)
.appFont(.subheadline)
.externalLinkBrowser()
}
private func internalPostID(for url: URL) -> String? {
var postID: String?
_ = PostTextFacets.openInternalURL(url, openActor: { _ in }, openPost: { postID = $0 })
return postID
}
}
struct ExternalLinkBrowserModifier: ViewModifier {
@AppStorage("openLinksInApp") private var openLinksInApp = true
@State private var presentedURL: BrowserURL?
let onInternalURL: ((URL) -> Bool)?
func body(content: Content) -> some View {
let _: Void = ViewUpdateMetrics.record("ExternalLinkBrowser")
return
content
.environment(
\.openURL,
OpenURLAction { url in
if onInternalURL?(url) == true { return .handled }
guard url.scheme?.lowercased() == "http" || url.scheme?.lowercased() == "https" else {
return .systemAction(url)
}
guard openLinksInApp else { return .systemAction(url) }
presentedURL = BrowserURL(url: url)
return .handled
}
)
.sheet(item: $presentedURL) { item in
SafariBrowserView(url: item.url)
}
}
private struct BrowserURL: Identifiable {
let url: URL
var id: String { url.absoluteString }
}
}
private struct SafariBrowserView: UIViewControllerRepresentable {
let url: URL
func makeUIViewController(context: Context) -> SFSafariViewController {
SFSafariViewController(url: url)
}
func updateUIViewController(_ controller: SFSafariViewController, context: Context) {}
}
extension View {
func externalLinkBrowser(onInternalURL: ((URL) -> Bool)? = nil) -> some View {
modifier(ExternalLinkBrowserModifier(onInternalURL: onInternalURL))
}
}
#if DEBUG
#Preview("Post links") {
VStack(alignment: .leading, spacing: 12) {
PostLinks(
urls: [
URL(string: "https://example.com/article")!,
URL(string: "https://bsky.app/profile/mae.example/post/123")!
], openPost: { _ in })
}
.padding()
}
#endif