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
import SwiftUI
enum PostTextFacets {
static let openContainingPostURL = URL(string: "oldfella-post-action://open")!
static func render(_ text: String, facets: [PostFacet], defaultLink: URL? = nil, linksEnabled: Bool = true)
-> AttributedString {
var result = AttributedString(text)
if let defaultLink {
result.link = defaultLink
result.foregroundColor = .primary
}
let utf8 = text.utf8
var upperByteLimit = utf8.count
// Expand URLs from the end so earlier byte offsets stay valid.
for facet in facets.sorted(by: { $0.byteStart > $1.byteStart }) {
guard facet.byteStart >= 0, facet.byteEnd > facet.byteStart, facet.byteEnd <= upperByteLimit,
let start = utf8.index(utf8.startIndex, offsetBy: facet.byteStart, limitedBy: utf8.endIndex),
let end = utf8.index(utf8.startIndex, offsetBy: facet.byteEnd, limitedBy: utf8.endIndex),
let stringStart = String.Index(start, within: text),
let stringEnd = String.Index(end, within: text),
let lower = AttributedString.Index(stringStart, within: result),
let upper = AttributedString.Index(stringEnd, within: result)
else { continue }
upperByteLimit = facet.byteStart
switch facet.feature {
case .link(let url):
var link = AttributedString(url.absoluteString)
link.link = url
link.foregroundColor = AppPalette.accent
result.replaceSubrange(lower..<upper, with: link)
case .mention(let did):
var components = URLComponents()
components.scheme = "oldfella-mention"
components.host = "profile"
components.queryItems = [URLQueryItem(name: "did", value: did)]
result[lower..<upper].link = components.url
result[lower..<upper].foregroundColor = AppPalette.accent
case .tag:
result[lower..<upper].foregroundColor = AppPalette.accent
}
}
if !linksEnabled {
result.link = nil
}
return result
}
static func openInternalURL(_ url: URL, openActor: (String) -> Void, openPost: (String) -> Void) -> Bool {
if url.scheme == "oldfella-mention", url.host == "profile",
let did = URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems?.first(where: {
$0.name == "did"
})?.value {
openActor(did)
return true
}
guard ["http", "https"].contains(url.scheme?.lowercased() ?? "") else { return false }
if url.host?.lowercased() == "oldsky.app", url.path == "/post",
let uri = URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems?.first(where: {
$0.name == "uri"
})?.value {
openPost(uri)
return true
}
guard url.host?.lowercased() == "bsky.app" else { return false }
let parts = url.pathComponents.filter { $0 != "/" }
guard parts.count >= 2, parts[0] == "profile" else { return false }
if parts.count == 2 {
openActor(parts[1])
return true
}
if parts.count == 4, parts[2] == "post" {
openPost("at://\(parts[1])/app.bsky.feed.post/\(parts[3])")
return true
}
return false
}
}