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
import Foundation
struct ComposerEmoji: Equatable, Hashable, Sendable {
let range: NSRange
let query: String
private static let expression = try? NSRegularExpression(
pattern: "(?<![\\p{L}\\p{N}._/@:+-]):([A-Za-z0-9_][A-Za-z0-9_+-]*|[+-][0-9][A-Za-z0-9_+-]*):?")
static func active(in text: String, selection: NSRange) -> ComposerEmoji? {
let nsText = text as NSString
guard selection.length == 0, selection.location > 0, selection.location <= nsText.length,
let expression
else { return nil }
let fullRange = NSRange(location: 0, length: nsText.length)
for match in expression.matches(in: text, range: fullRange) {
let body = match.range(at: 1)
guard selection.location > body.location, selection.location <= NSMaxRange(match.range) else { continue }
let queryEnd = min(selection.location, NSMaxRange(body))
let queryRange = NSRange(location: body.location, length: queryEnd - body.location)
guard queryRange.length <= 100, let swiftRange = Range(match.range, in: text) else { return nil }
let byteStart = text[..<swiftRange.lowerBound].utf8.count
let overlapsLink = ComposerText.facetCandidates(in: text).contains {
$0.kind == .link && byteStart >= $0.byteStart && byteStart < $0.byteEnd
}
guard !overlapsLink else { return nil }
return ComposerEmoji(range: match.range, query: nsText.substring(with: queryRange))
}
return nil
}
func inserting(emoji: String, in text: String) -> (text: String, selection: NSRange)? {
guard range.location >= 0, range.length >= 0, range.location <= text.utf16.count,
range.length <= text.utf16.count - range.location,
let swiftRange = Range(range, in: text)
else { return nil }
let separator = swiftRange.upperBound == text.endIndex ? " " : ""
let replacement = emoji + separator
let updated = text.replacingCharacters(in: swiftRange, with: replacement)
return (updated, NSRange(location: range.location + replacement.utf16.count, length: 0))
}
}