Reportage/Views/Survey/SurveyModel.swift (21093B)
1import Foundation
2import Observation
3
4
5
6@MainActor
7@Observable
8final class SurveyModel {
9 let kind: ReportKind
10
11
12 let date: Date
13 let timeZone: String
14
15 let trigger: ReportTrigger
16 let promptedAt: Date?
17 let questions: [Question]
18
19
20
21 let existing: Report?
22
23
24
25 let pickers: [String: TokenPicker]
26 let placePickers: [String: PlacePicker]
27
28 private(set) var index = 0
29 private var answers: [String: ResponseValue] = [:]
30
31 private let originalResponses: [String: Response]
32
33 private var contextTask: Task<Context, Never>?
34
35
36 private var carried: (places: [String: String], people: [String: [String]])?
37
38
39 private var placeIDs: [String: [String: String]] = [:]
40
41
42
43 static let carryInterval: TimeInterval = 2 * 60 * 60
44
45 convenience init(
46 kind: ReportKind,
47 date: Date,
48 timeZone: TimeZone = .current,
49 trigger: ReportTrigger = .app,
50 promptedAt: Date? = nil,
51 questions: [Question],
52 vocabulary: [String: [VocabularyEntry]],
53 previous: Report? = nil,
54 directory: any PlaceDirectory = MapKitPlaceDirectory()
55 ) {
56 self.init(
57 kind: kind, date: date, timeZone: timeZone.identifier, trigger: trigger,
58 promptedAt: promptedAt, existing: nil, questions: questions, vocabulary: vocabulary,
59 directory: directory)
60 if let previous { carry(from: previous, vocabulary: vocabulary) }
61 }
62
63
64
65
66
67 convenience init(
68 editing report: Report,
69 questions: [Question],
70 vocabulary: [String: [VocabularyEntry]],
71 tokens: [String: VocabularyEntry] = [:],
72 directory: any PlaceDirectory = MapKitPlaceDirectory()
73 ) {
74 self.init(
75 kind: report.kind, date: report.date, timeZone: report.timeZone,
76 trigger: report.trigger, promptedAt: report.promptedAt, existing: report,
77 questions: questions, vocabulary: vocabulary, directory: directory)
78 for picker in placePickers.values {
79 picker.setLocation(report.context.location)
80 }
81 for question in questions {
82 guard let value = originalResponses[question.id]?.value else { continue }
83 switch value {
84 case .options, .number, .text:
85 answers[question.id] = value
86 case .tokens(let ids):
87 pickers[question.id]?.preselect(ids, entries: ids.compactMap { tokens[$0] })
88 case .place(let place):
89 placePickers[question.id]?.preselect(place.tokenID, entry: tokens[place.tokenID])
90 }
91 }
92 }
93
94 private init(
95 kind: ReportKind,
96 date: Date,
97 timeZone: String,
98 trigger: ReportTrigger,
99 promptedAt: Date?,
100 existing: Report?,
101 questions: [Question],
102 vocabulary: [String: [VocabularyEntry]],
103 directory: any PlaceDirectory
104 ) {
105 self.kind = kind
106 self.date = date
107 self.timeZone = timeZone
108 self.trigger = trigger
109 self.promptedAt = promptedAt
110 self.existing = existing
111 self.questions = questions
112 self.originalResponses = Dictionary(
113 (existing?.responses ?? []).map { ($0.questionID, $0) },
114 uniquingKeysWith: { first, _ in first })
115 var pickers: [String: TokenPicker] = [:]
116 var placePickers: [String: PlacePicker] = [:]
117 for question in questions {
118 switch question.kind {
119 case .tokens, .people:
120 pickers[question.id] = TokenPicker(
121 questionID: question.id,
122 allowsMultiple: true,
123 entries: vocabulary[question.id] ?? []
124 )
125 case .location:
126 let picker = PlacePicker(
127 questionID: question.id,
128 entries: vocabulary[question.id] ?? [],
129 directory: directory
130 )
131 picker.prefills = existing == nil
132 placePickers[question.id] = picker
133 case .yesNo, .choice, .number, .note:
134 continue
135 }
136 }
137 self.pickers = pickers
138 self.placePickers = placePickers
139 }
140
141
142
143
144
145
146
147 private func carry(from previous: Report, vocabulary: [String: [VocabularyEntry]]) {
148 var places: [String: String] = [:]
149 var people: [String: [String]] = [:]
150 for response in previous.responses {
151 let id = Self.survivorIDs(vocabulary[response.questionID] ?? [])
152 switch response.value {
153 case .place(let answer) where placePickers[response.questionID] != nil:
154 places[response.questionID] = id[answer.tokenID] ?? answer.tokenID
155 case .tokens(let ids) where peopleQuestionIDs.contains(response.questionID):
156 var seen: Set<String> = []
157 let ids = ids.compactMap { id[$0] }.filter { seen.insert($0).inserted }
158 if !ids.isEmpty { people[response.questionID] = ids }
159 default:
160 continue
161 }
162 }
163 guard !places.isEmpty, !people.isEmpty else { return }
164 carried = (places, people)
165 for (questionID, picker) in placePickers {
166 placeIDs[questionID] = Self.survivorIDs(vocabulary[questionID] ?? [])
167 picker.onSelectionChange = { [weak self] in self?.placeChanged() }
168 }
169 }
170
171 private var peopleQuestionIDs: Set<String> {
172 Set(questions.filter { $0.kind == .people }.map(\.id))
173 }
174
175
176
177
178 private func placeChanged() {
179 guard let carried else { return }
180 let isSame = placePickers.contains { questionID, picker in
181 guard let chosen = picker.selectedTokenID else { return false }
182 return (placeIDs[questionID]?[chosen] ?? chosen) == carried.places[questionID]
183 }
184 for (questionID, ids) in carried.people {
185 guard let picker = pickers[questionID] else { continue }
186 if isSame {
187 picker.prefill(ids)
188 } else if picker.isPrefilled {
189 picker.prefill([])
190 }
191 }
192 }
193
194
195
196 private static func survivorIDs(_ entries: [VocabularyEntry]) -> [String: String] {
197 var ids: [String: String] = [:]
198 for entry in entries {
199 ids[entry.id] = entry.id
200 for merged in entry.merged { ids[merged.id] = entry.id }
201 }
202 return ids
203 }
204
205 var currentQuestion: Question? {
206 questions.indices.contains(index) ? questions[index] : nil
207 }
208
209 var isLastQuestion: Bool { index >= questions.count - 1 }
210
211
212 var hasAnswers: Bool {
213 questions.contains { value(for: $0) != nil }
214 }
215
216
217
218 var hasChanges: Bool {
219 guard existing != nil else { return hasAnswers }
220 return questions.contains { question in
221 !Self.isSameAnswer(originalResponses[question.id]?.value, value(for: question))
222 }
223 }
224
225
226
227 private static func isSameAnswer(_ lhs: ResponseValue?, _ rhs: ResponseValue?) -> Bool {
228 if case .place(let lhs) = lhs, case .place(let rhs) = rhs {
229 return lhs.tokenID == rhs.tokenID
230 }
231 return lhs == rhs
232 }
233
234
235
236
237 subscript(optionFor questionID: String) -> String? {
238 get {
239 guard case .options(let options) = answers[questionID] else { return nil }
240 return options.first
241 }
242 set { answers[questionID] = newValue.map { .options([$0]) } }
243 }
244
245 subscript(numberFor questionID: String) -> Decimal? {
246 get {
247 guard case .number(let number) = answers[questionID] else { return nil }
248 return number
249 }
250 set { answers[questionID] = newValue.map { .number($0) } }
251 }
252
253 subscript(textFor questionID: String) -> String {
254 get {
255 guard case .text(let text) = answers[questionID] else { return "" }
256 return text
257 }
258 set { answers[questionID] = newValue.isEmpty ? nil : .text(newValue) }
259 }
260
261
262 func value(for question: Question) -> ResponseValue? {
263 switch question.kind {
264 case .yesNo, .choice, .number:
265 return answers[question.id]
266 case .note:
267 guard case .text(let text) = answers[question.id],
268 !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
269 else { return nil }
270 return .text(text)
271 case .tokens, .people:
272 guard let selection = pickers[question.id]?.selection, !selection.isEmpty else {
273 return nil
274 }
275 return .tokens(selection)
276 case .location:
277 guard let tokenID = placePickers[question.id]?.selectedTokenID else { return nil }
278 return .place(PlaceAnswer(tokenID: tokenID))
279 }
280 }
281
282
283
284
285 @discardableResult
286 func advance() -> Bool {
287 guard !isLastQuestion else { return false }
288 index += 1
289 return true
290 }
291
292
293
294 func advance(from index: Int) {
295 guard index == self.index else { return }
296 advance()
297 }
298
299 func goBack() {
300 guard index > 0 else { return }
301 index -= 1
302 }
303
304
305 func show(_ index: Int) {
306 guard questions.indices.contains(index) else { return }
307 self.index = index
308 }
309
310
311 func clearCurrent() {
312 guard let question = currentQuestion else { return }
313 answers[question.id] = nil
314 pickers[question.id]?.clear()
315 placePickers[question.id]?.clear()
316 }
317
318
319
320
321
322
323 func startCapture(_ capture: ContextCapture = ContextCapture()) {
324 guard contextTask == nil, existing == nil else { return }
325 let placePickers = Array(placePickers.values)
326 contextTask = Task {
327 let context = await capture.capture { location in
328 Task { @MainActor in
329 for picker in placePickers { picker.setLocation(location) }
330 }
331 }
332 for picker in placePickers { picker.setLocation(context.location) }
333 return context
334 }
335 }
336
337
338
339
340 func capturedContext() async -> Context {
341 if let existing { return existing.context }
342 return await contextTask?.value ?? Context()
343 }
344
345
346
347
348
349
350
351
352
353
354
355
356 func makeReport(
357 id: UUID = UUID(),
358 now: Date,
359 context: Context = Context()
360 ) -> (report: Report, newTokens: [Token]) {
361 var responses = questions.map { question in
362 var value = value(for: question)
363
364 if case .place(var answer) = value, let location = context.location {
365 answer.coordinate = location.coordinate
366 answer.accuracy = location.horizontalAccuracy
367 value = .place(answer)
368 }
369 if let original = originalResponses[question.id] {
370 return Self.isSameAnswer(original.value, value)
371 ? original
372 : Response(questionID: question.id, prompt: original.prompt, value: value)
373 }
374 return Response(questionID: question.id, prompt: question.prompt, value: value)
375 }
376 if let existing, !existing.responses.isEmpty {
377 let edited = Dictionary(
378 responses.map { ($0.questionID, $0) }, uniquingKeysWith: { first, _ in first })
379 responses = existing.responses.map { edited[$0.questionID] ?? $0 }
380 }
381 let newTokens = questions.flatMap { question in
382 pickers[question.id]?.usedNewTokens(now: now)
383 ?? placePickers[question.id]?.usedNewTokens(now: now) ?? []
384 }
385 if var report = existing {
386 if report.state == .passive {
387 report.state = .complete
388 report.completedAt = now
389 }
390 report.responses = responses
391 report.modifiedAt = now
392 return (report, newTokens)
393 }
394 let report = Report(
395 id: id,
396 date: date,
397 timeZone: timeZone,
398 kind: kind,
399 trigger: trigger,
400 state: .complete,
401 promptedAt: promptedAt,
402 completedAt: now,
403 context: context,
404 responses: responses,
405 modifiedAt: now
406 )
407 return (report, newTokens)
408 }
409}
410
411
412
413@MainActor
414@Observable
415final class TokenPicker {
416 let questionID: String
417 let allowsMultiple: Bool
418
419 var query = "" {
420 didSet { updateVisibleEntries() }
421 }
422
423
424
425 private(set) var visibleEntries: [VocabularyEntry] = []
426
427 private(set) var canAddQuery = false
428
429 private(set) var selection: [String] = [] {
430 didSet {
431 updateVisibleEntries()
432 updateSelectedEntries()
433 }
434 }
435 private(set) var selectedEntries: [VocabularyEntry] = []
436
437 private var entries: [VocabularyEntry] {
438 didSet {
439 updateVisibleEntries()
440 updateSelectedEntries()
441 }
442 }
443
444 private var newTokenTexts: [String: String] = [:]
445
446 init(questionID: String, allowsMultiple: Bool, entries: [VocabularyEntry]) {
447 self.questionID = questionID
448 self.allowsMultiple = allowsMultiple
449 self.entries = entries
450 updateVisibleEntries()
451 }
452
453 func isSelected(_ id: String) -> Bool { selection.contains(id) }
454
455
456
457 private(set) var isEdited = false
458
459 private(set) var isPrefilled = false
460
461
462 func toggle(_ id: String) {
463 markEdited()
464 if let position = selection.firstIndex(of: id) {
465 selection.remove(at: position)
466 return
467 }
468 if allowsMultiple {
469 selection.append(id)
470 } else {
471 selection = [id]
472 }
473 query = ""
474 }
475
476
477
478 func addQuery() {
479 let text = query.trimmingCharacters(in: .whitespacesAndNewlines)
480 guard !text.isEmpty else { return }
481 markEdited()
482 if let existing = entry(named: text) {
483 if !isSelected(existing.id) { toggle(existing.id) }
484 } else {
485 let id = UUID().uuidString
486 newTokenTexts[id] = text
487 entries.insert(VocabularyEntry(id: id, text: text, useCount: 0), at: 0)
488 toggle(id)
489 }
490 query = ""
491 }
492
493 func clear() {
494 markEdited()
495 selection = []
496 query = ""
497 }
498
499
500
501
502 func prefill(_ ids: [String]) {
503 guard !isEdited, isPrefilled || selection.isEmpty else { return }
504 selection = ids
505 isPrefilled = !ids.isEmpty
506 }
507
508 private func markEdited() {
509 isEdited = true
510 isPrefilled = false
511 }
512
513
514
515 func preselect(_ ids: [String], entries extra: [VocabularyEntry]) {
516 let known = Set(entries.map(\.id))
517 entries += extra.filter { !known.contains($0.id) }
518 selection = ids
519 }
520
521
522 func usedNewTokens(now: Date) -> [Token] {
523 selection.compactMap { id in
524 newTokenTexts[id].map { text in
525 Token(
526 id: id,
527 questionID: questionID,
528 text: text,
529 modifiedAt: now
530 )
531 }
532 }
533 }
534
535
536
537 private func entry(named text: String) -> VocabularyEntry? {
538 func same(_ name: String) -> Bool {
539 name.compare(text, options: [.caseInsensitive, .diacriticInsensitive]) == .orderedSame
540 }
541 return entries.first { same($0.text) } ?? entries.first { $0.merged.contains { same($0.text) } }
542 }
543
544 private func updateVisibleEntries() {
545 let text = query.trimmingCharacters(in: .whitespacesAndNewlines)
546 let matching = text.isEmpty ? entries : entries.filter { $0.matches(text) }
547 visibleEntries = allowsMultiple ? matching.filter { !selection.contains($0.id) } : matching
548 canAddQuery = !text.isEmpty && entry(named: text) == nil
549 }
550
551 private func updateSelectedEntries() {
552 let byID = Dictionary(entries.map { ($0.id, $0) }, uniquingKeysWith: { first, _ in first })
553 selectedEntries = selection.compactMap { byID[$0] }
554 }
555}