Reportage/Services/Narrative/InlineCasing.swift (2200B)
1import NaturalLanguage
2import UIKit
3
4
5
6
7@MainActor
8enum InlineCasing {
9 private static var cache: [String: String] = [:]
10 private static let checker = UITextChecker()
11
12
13
14
15 static func inline(_ text: String) -> String {
16 if let cached = cache[text] { return cached }
17 let result = compute(text)
18 cache[text] = result
19 return result
20 }
21
22 private static func compute(_ text: String) -> String {
23 guard let first = text.split(separator: " ").first.map(String.init),
24 let initial = first.first, initial.isUppercase,
25 first.dropFirst().allSatisfy({ !$0.isUppercase })
26 else { return text }
27
28 let lower = first.lowercased()
29 guard isDictionaryWord(lower) else { return text }
30
31 let tagger = NLTagger(tagSchemes: [.nameType])
32 tagger.string = text
33 let (tag, _) = tagger.tag(at: text.startIndex, unit: .word, scheme: .nameType)
34 if let tag, [.personalName, .placeName, .organizationName].contains(tag) { return text }
35
36 return lower + text.dropFirst(first.count)
37 }
38
39
40
41 private static let languages: [String] = {
42 let english = UITextChecker.availableLanguages.filter { $0.hasPrefix("en") }
43 return english.isEmpty ? ["en_US"] : english
44 }()
45
46 static func isDictionaryWord(_ word: String) -> Bool {
47 let range = NSRange(location: 0, length: (word as NSString).length)
48 return languages.contains { language in
49 checker.rangeOfMisspelledWord(
50 in: word, range: range, startingAt: 0, wrap: false, language: language
51 ).location == NSNotFound
52 }
53 }
54}