← All repositories

reportage

A life-logging app for iPhone

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


Reportage/Views/Survey/SurveyModel.swift (21093B)

1import Foundation
2import Observation
3
4/// One survey in progress: the questions it asks, one per page, and the
5/// answers given so far. Nothing is saved until `makeReport(now:)` is used.
6@MainActor
7@Observable
8final class SurveyModel {
9    let kind: ReportKind
10    /// The moment the report describes: when the survey was started, or
11    /// when the report being edited was made.
12    let date: Date
13    let timeZone: String
14    /// What started a new report, and when its prompt was sent, if one was.
15    let trigger: ReportTrigger
16    let promptedAt: Date?
17    let questions: [Question]
18    /// The report this survey edits, if any: an instant report being filled
19    /// in, or a finished one being changed. Its context was captured when it
20    /// was made, so none is captured now.
21    let existing: Report?
22    /// Pickers for `tokens` and `people` questions, and for `location`
23    /// questions, by question ID. They're created once so each page keeps its
24    /// search and selection.
25    let pickers: [String: TokenPicker]
26    let placePickers: [String: PlacePicker]
27
28    private(set) var index = 0
29    private var answers: [String: ResponseValue] = [:]
30    /// The existing report's responses, by question ID.
31    private let originalResponses: [String: Response]
32    /// Live context, captured from when the survey opens.
33    private var contextTask: Task<Context, Never>?
34    /// What a new report carries forward from the previous one: its place
35    /// answers and its people answers, by question ID.
36    private var carried: (places: [String: String], people: [String: [String]])?
37    /// For each place question, the ID each place reads as: see
38    /// `survivorIDs(_:)`.
39    private var placeIDs: [String: [String: String]] = [:]
40
41    /// How long after a report its people are carried into the next one
42    /// at the same place.
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    /// A survey that edits `report`, as of the moment it describes, starting
64    /// from its answers. `tokens` are entries for the tokens its answers use
65    /// that suggestions leave out, such as archived ones, so every answer
66    /// shows.
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    // MARK: Carrying forward
142
143    /// Sets up the people of `previous`, the last report, to be chosen
144    /// whenever this report's place is the same as its place. Tokens are
145    /// compared as the tokens they were merged into, and people that are
146    /// no longer suggested are left out.
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    /// Chooses the carried people when a place chosen is the previous
176    /// report's, or takes them away again when it changes, unless the user
177    /// has changed them.
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    /// The ID each of `entries` reads as, by its own ID and the IDs of the
195    /// tokens merged into it.
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    /// Whether anything has been answered, so cancelling would lose work.
212    var hasAnswers: Bool {
213        questions.contains { value(for: $0) != nil }
214    }
215
216    /// Whether cancelling would lose work: anything answered in a new
217    /// report, or any answer changed in an existing one.
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    /// Whether two answers are the same. A place answer is the same place
226    /// whatever coordinate it records.
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    // MARK: Answers
235
236    /// The chosen option of a `yesNo` or `choice` question.
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    /// The answer to `question`, or `nil` if it has none.
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    // MARK: Paging
283
284    /// Moves to the next question. Returns `false` on the last question.
285    @discardableResult
286    func advance() -> Bool {
287        guard !isLastQuestion else { return false }
288        index += 1
289        return true
290    }
291
292    /// Moves to the next question if `index` is still the current one, so an
293    /// answer tapped twice doesn't skip the question after it.
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    /// Shows the question at `index`, as when the user swipes to it.
305    func show(_ index: Int) {
306        guard questions.indices.contains(index) else { return }
307        self.index = index
308    }
309
310    /// Clears the current question's answer, so it's recorded as skipped.
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    // MARK: Context
319
320    /// Starts capturing the report's live context. Called when the survey
321    /// opens, so the context describes the moment the report is about. Place
322    /// pickers get the location as soon as there's a fix.
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    /// The captured context, waiting for the capture if it's still running.
338    /// It finishes within its budget of the survey opening. A report being
339    /// filled in keeps the context it was logged with.
340    func capturedContext() async -> Context {
341        if let existing { return existing.context }
342        return await contextTask?.value ?? Context()
343    }
344
345    // MARK: Saving
346
347    /// The finished report, with a response for every question in the
348    /// survey (skipped questions have no value), and the tokens created
349    /// while answering that the report uses.
350    ///
351    /// An existing report keeps its ID, trigger and context. An answer left
352    /// as it was keeps its response exactly, with the prompt it was given
353    /// under and where a place answer was given; responses to questions not
354    /// shown are kept too. An instant report becomes complete now; a
355    /// finished one keeps when it was completed.
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            // A place answer records where it was given.
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/// Searching, selecting and adding tokens for one `tokens` or `people`
412/// question.
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    /// The entries matching `query`, in rank order. With multiple selection,
424    /// selected entries are left out, as they show above the list.
425    private(set) var visibleEntries: [VocabularyEntry] = []
426    /// Whether `query` names no existing entry, so it can be added.
427    private(set) var canAddQuery = false
428    /// Selected token IDs, in the order they were chosen.
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    /// Texts of tokens added in this survey, by ID.
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    /// Whether the user has changed the selection, after which it's never
456    /// pre-filled.
457    private(set) var isEdited = false
458    /// Whether the selection is a pre-fill the user hasn't changed.
459    private(set) var isPrefilled = false
460
461    /// Selects or deselects `id`. Selecting clears the query.
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    /// Selects the entry `query` names, adding it as a new token if there's
477    /// none, and clears the query.
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    /// Selects `ids` as a guess the user can change, or clears an earlier
500    /// guess when `ids` is empty. Does nothing once the user has changed
501    /// the selection.
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    /// Selects `ids`, as an existing answer does, adding `entries` for any
514    /// the suggestions leave out so each selected token shows.
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    /// Tokens added in this survey that are still selected.
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    /// The token that typing `text` names: one with that name, or else one
536    /// that a token with that name was merged into.
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}