← All repositories

reportage

A life-logging app for iPhone

git clone https://code.inqk.net/reportage.git


Reportage/Services/Narrative/InlineCasing.swift (2200B)

1import NaturalLanguage
2import UIKit
3
4/// How a short answer reads in the middle of a sentence: 'Drinking coffee'
5/// becomes 'drinking coffee', while 'Watching Netflix', 'Studying Japanese'
6/// and 'TV' keep their capitals.
7@MainActor
8enum InlineCasing {
9    private static var cache: [String: String] = [:]
10    private static let checker = UITextChecker()
11
12    /// Lowercases the first letter only if the first word is capitalised just
13    /// at its start, its lowercase form is an ordinary English word, and it
14    /// isn't tagged as a name. Text in scripts without case is unchanged.
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    /// English dictionaries to check, so regional spellings such as
40    /// 'travelling' and 'traveling' both count as ordinary words.
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}