2018-09-30 01:16:45 +00:00
|
|
|
//
|
|
|
|
// CharacterCounter.swift
|
|
|
|
// Pachyderm
|
|
|
|
//
|
|
|
|
// Created by Shadowfacts on 9/29/18.
|
|
|
|
// Copyright © 2018 Shadowfacts. All rights reserved.
|
|
|
|
//
|
|
|
|
|
|
|
|
import Foundation
|
|
|
|
|
|
|
|
public struct CharacterCounter {
|
|
|
|
|
|
|
|
static let linkDetector = try! NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue)
|
|
|
|
static let mention = try! NSRegularExpression(pattern: "(@[a-z0-9_]+)(?:@[a-z0-9\\-\\.]+[a-z0-9]+)?", options: .caseInsensitive)
|
|
|
|
|
2021-11-11 18:44:24 +00:00
|
|
|
public static func count(text: String, for instance: Instance? = nil) -> Int {
|
2018-09-30 01:16:45 +00:00
|
|
|
let mentionsRemoved = removeMentions(in: text)
|
|
|
|
var count = mentionsRemoved.count
|
|
|
|
for match in linkDetector.matches(in: mentionsRemoved, options: [], range: NSRange(location: 0, length: mentionsRemoved.utf16.count)) {
|
|
|
|
count -= match.range.length
|
2021-11-11 18:44:24 +00:00
|
|
|
count += instance?.configuration?.statuses.charactersReservedPerURL ?? 23 // default Mastodon link length
|
2018-09-30 01:16:45 +00:00
|
|
|
}
|
|
|
|
return count
|
|
|
|
}
|
|
|
|
|
|
|
|
private static func removeMentions(in text: String) -> String {
|
|
|
|
var mut = text
|
|
|
|
for match in mention.matches(in: mut, options: [], range: NSRange(location: 0, length: mut.utf16.count)).reversed() {
|
|
|
|
let replacement = mut[Range(match.range(at: 1), in: mut)!]
|
|
|
|
mut.replaceSubrange(Range(match.range, in: mut)!, with: replacement)
|
|
|
|
}
|
|
|
|
return mut
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|