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
import Foundation
enum ComposerText {
struct FacetCandidate: Equatable {
let byteStart: Int
let byteEnd: Int
let kind: Kind
let value: String
}
static func facetCandidates(in text: String) -> [FacetCandidate] {
let patterns: [(FacetCandidate.Kind, String)] = [
(.link, "https?://[^\\s<>()]+"),
(.mention, "(?<![A-Za-z0-9._-])@[A-Za-z0-9-]+(?:\\.[A-Za-z0-9-]+)+"),
(.tag, "(?<![\\p{L}\\p{N}_])#[\\p{L}\\p{N}_]+")
]
var candidates: [FacetCandidate] = []
for (kind, pattern) in patterns {
guard let regex = try? NSRegularExpression(pattern: pattern) else { continue }
let nsText = text as NSString
candidates += regex.matches(in: text, range: NSRange(location: 0, length: nsText.length)).compactMap {
candidate(in: text, match: $0, kind: kind)
}
}
var nonOverlapping: [FacetCandidate] = []
for candidate in candidates.sorted(by: {
if $0.byteStart != $1.byteStart { return $0.byteStart < $1.byteStart }
return $0.byteEnd > $1.byteEnd
}) {
guard
!nonOverlapping.contains(where: { candidate.byteStart < $0.byteEnd && $0.byteStart < candidate.byteEnd }
)
else { continue }
nonOverlapping.append(candidate)
}
return nonOverlapping
}
private static func candidate(in text: String, match: NSTextCheckingResult, kind: FacetCandidate.Kind)
-> FacetCandidate? {
guard let range = Range(match.range, in: text) else { return nil }
var matched = String(text[range])
if kind == .link {
let trailingPunctuation = CharacterSet(charactersIn: ".,!?;:\"'")
while let last = matched.unicodeScalars.last, trailingPunctuation.contains(last) {
matched.removeLast()
}
}
guard !matched.isEmpty, let utf8Start = range.lowerBound.samePosition(in: text.utf8),
let utf8End = text.utf8.index(utf8Start, offsetBy: matched.utf8.count, limitedBy: text.utf8.endIndex)
else { return nil }
let byteStart = text.utf8.distance(from: text.utf8.startIndex, to: utf8Start)
let byteEnd = text.utf8.distance(from: text.utf8.startIndex, to: utf8End)
let value = kind == .link ? matched : String(matched.dropFirst())
return FacetCandidate(byteStart: byteStart, byteEnd: byteEnd, kind: kind, value: value)
}
}
extension ComposerText.FacetCandidate {
enum Kind: Equatable { case link, mention, tag }
}