Reportage/Services/Narrative/NarrativeBuilder.swift (8836B)
1import Foundation
2
3
4struct AnswerDetail: Equatable, Identifiable, Sendable {
5 var id: String { questionID }
6 var questionID: String
7 var prompt: String
8 var answer: String
9}
10
11
12
13@MainActor
14enum NarrativeBuilder {
15 static func build(
16 responses: [Response],
17 lookup: SummaryLookup
18 ) -> (narrative: String?, details: [AnswerDetail]) {
19 var sentences: [Sentence] = []
20 var details: [AnswerDetail] = []
21 var activities: [String] = []
22 var people: [String] = []
23 var place: String?
24
25 var clauseIndex: Int?
26
27
28 let ordered = responses.enumerated().sorted { a, b in
29 let orders = (lookup.questionOrder[a.element.questionID], lookup.questionOrder[b.element.questionID])
30 return (orders.0 ?? .max, a.offset) < (orders.1 ?? .max, b.offset)
31 }.map(\.element)
32
33 for response in ordered {
34 guard let value = response.value, !lookup.hiddenQuestions.contains(response.questionID)
35 else { continue }
36 switch (lookup.questionRules[response.questionID], value) {
37 case (.activities, .tokens(let ids)):
38 activities += distinct(ids, lookup).compactMap { form(of: $0, rule: .activities, lookup: lookup) }
39 clauseIndex = clauseIndex ?? sentences.count
40 case (.people, .tokens(let ids)):
41 people += distinct(ids, lookup).compactMap { form(of: $0, rule: .people, lookup: lookup) }
42 clauseIndex = clauseIndex ?? sentences.count
43 case (.place, .place(let answer)):
44 place = place ?? form(of: answer.tokenID, rule: .place, lookup: lookup)
45 clauseIndex = clauseIndex ?? sentences.count
46 case (.phrases(let yes, let no), .options(let options)):
47 let phrases = [ResponseValue.yesOption: yes, ResponseValue.noOption: no]
48 if let phrase = options.lazy.compactMap({ phrases[$0] }).first(where: { !$0.isBlank }) {
49 sentences.append(Sentence(phrase))
50 } else {
51 details.append(detail(for: response, answer: displayOptions(options)))
52 }
53 case (.template(let format), .options(let options)) where !format.isBlank:
54 let answer = joined(options.map(InlineCasing.inline))
55 sentences.append(Sentence(format.replacingOccurrences(of: "%@", with: answer)))
56 case (.template(let format), .tokens(let ids)) where !format.isBlank:
57 let answers = distinct(ids, lookup).compactMap { form(of: $0, rule: .activities, lookup: lookup) }
58 guard !answers.isEmpty else { continue }
59 sentences.append(Sentence(format.replacingOccurrences(of: "%@", with: joined(answers))))
60 case (.count(let singular, let plural), .number(let number))
61 where !singular.isBlank && !plural.isBlank:
62 let noun = number == 1 ? singular : plural
63 sentences.append(Sentence("\(number.formatted()) \(noun)"))
64 case (.quote(let lead), .text(let note)) where !lead.isBlank:
65 let note = note.trimmingCharacters(in: .whitespacesAndNewlines)
66 let ended = note.last.map { ".!?".contains($0) } ?? false
67 sentences.append(Sentence("\(lead): '\(note)'", isEnded: ended))
68 default:
69 details.append(detail(for: response, answer: describe(value, lookup: lookup)))
70 }
71 }
72
73 if let clause = mainClause(activities: activities, place: place, people: people) {
74 sentences.insert(clause, at: min(clauseIndex ?? 0, sentences.count))
75 }
76 guard !sentences.isEmpty else { return (nil, details) }
77
78 let narrative = sentences.map { sentence in
79 sentence.capitalised + (sentence.isEnded ? "" : ".")
80 }
81 return (narrative.joined(separator: " "), details)
82 }
83
84 private struct Sentence {
85 var text: String
86 var isEnded = false
87
88 init(_ text: String, isEnded: Bool = false) {
89 self.text = text
90 self.isEnded = isEnded
91 }
92
93 var capitalised: String {
94 guard let initial = text.first else { return text }
95 return initial.uppercased() + text.dropFirst()
96 }
97 }
98
99
100 private static func mainClause(activities: [String], place: String?, people: [String]) -> Sentence? {
101 var text = ""
102 if !activities.isEmpty {
103 text += joined(activities)
104 }
105 if let place {
106 text += (text.isEmpty ? "At " : " at ") + place
107 }
108 if !people.isEmpty {
109 text += (text.isEmpty ? "With " : ", with ") + joined(people)
110 }
111 return text.isEmpty ? nil : Sentence(text)
112 }
113
114
115
116
117 static func form(of id: String, rule: NarrativeRule, lookup: SummaryLookup) -> String? {
118 if let form = lookup.narrativeForms[id] { return form }
119 guard let text = lookup.tokenTexts[id] else { return nil }
120 switch rule {
121 case .activities: return InlineCasing.inline(text)
122 case .people: return shortName(text)
123 case .place: return lookup.directoryPlaces.contains(id) ? text : PlacePhrase.phrase(for: text)
124 default: return text
125 }
126 }
127
128
129
130
131
132 static func shortName(_ name: String) -> String {
133 let isCJK = name.unicodeScalars.contains { scalar in
134 scalar.properties.isIdeographic
135 || (0x3040...0x30FF).contains(scalar.value)
136 || (0xAC00...0xD7AF).contains(scalar.value)
137 }
138 guard !isCJK, let first = name.split(separator: " ", maxSplits: 1).first else { return name }
139 return String(first)
140 }
141
142
143
144 static func distinct(_ ids: [String], _ lookup: SummaryLookup) -> [String] {
145 var seen: Set<String> = []
146 return ids.filter { seen.insert(lookup.mergedIDs[$0] ?? $0).inserted }
147 }
148
149
150 private static func joined(_ items: [String]) -> String {
151 guard items.count > 2 else { return items.joined(separator: " and ") }
152 return items.dropLast().joined(separator: ", ") + " and " + items[items.count - 1]
153 }
154
155 private static func detail(for response: Response, answer: String) -> AnswerDetail {
156 AnswerDetail(questionID: response.questionID, prompt: response.prompt, answer: answer)
157 }
158
159
160 static func describe(_ value: ResponseValue, lookup: SummaryLookup) -> String {
161 switch value {
162 case .options(let options): displayOptions(options)
163 case .tokens(let ids): joined(distinct(ids, lookup).compactMap { lookup.tokenTexts[$0] })
164 case .place(let answer): lookup.tokenTexts[answer.tokenID] ?? ""
165 case .number(let number): number.formatted()
166 case .text(let text): text
167 }
168 }
169
170
171
172 private static func displayOptions(_ options: [String]) -> String {
173 joined(
174 options.map { option in
175 switch option {
176 case ResponseValue.yesOption:
177 String(localized: "Yes", comment: "Answer to a yes/no question")
178 case ResponseValue.noOption:
179 String(localized: "No", comment: "Answer to a yes/no question")
180 default: option
181 }
182 })
183 }
184}
185
186extension String {
187
188
189 fileprivate var isBlank: Bool {
190 trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
191 }
192}