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

geesawra.industries/old-fella

Old people's social media app

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