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