~ knotless Search/
↑↓ move↵ open⇧↵ all results

geesawra.industries/old-fella

Old people's social media app

0
1
main
42 lines · 2.1 KB Raw History
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))
    }
}