← All repositories

reportage

A life-logging app for iPhone

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


Reportage/Views/Settings/QuestionsView.swift (18580B)

1import OSLog
2import SwiftUI
3
4/// The surveys a question can be asked in, as the Questions screen names
5/// them. Manual reports ask the prompted survey's questions.
6enum Survey: CaseIterable, Hashable {
7    case prompted
8    case wake
9    case bedtime
10
11    var kinds: SurveyKinds {
12        switch self {
13        case .prompted: .random
14        case .wake: .wake
15        case .bedtime: .bedtime
16        }
17    }
18
19    var title: LocalizedStringKey {
20        switch self {
21        case .prompted: "Prompted"
22        case .wake: "Wake"
23        case .bedtime: "Bedtime"
24        }
25    }
26}
27
28extension Question {
29    /// Whether the question is asked in `survey`. An archived question isn't
30    /// asked anywhere, whatever surveys it was last in.
31    func isAsked(in survey: Survey) -> Bool {
32        archivedAt == nil && askOn.contains(survey.kinds)
33    }
34
35    /// Asks or stops asking the question in `survey`. Asking an archived
36    /// question brings it back in that survey alone.
37    mutating func setAsked(_ isAsked: Bool, in survey: Survey) {
38        if isAsked {
39            if archivedAt != nil {
40                archivedAt = nil
41                askOn = []
42            }
43            askOn.insert(survey.kinds)
44        } else {
45            askOn.remove(survey.kinds)
46        }
47    }
48}
49
50/// Every question in order, for reordering and editing on the Questions
51/// screen. Each change is saved as it's made.
52@MainActor
53@Observable
54final class QuestionList {
55    /// Every question, archived or not, in survey order.
56    private(set) var questions: [Question] = [] {
57        didSet { group() }
58    }
59    private(set) var bySurvey: [Survey: [Question]] = [:]
60    /// Questions not asked in any survey, archived ones aside.
61    private(set) var notAsked: [Question] = []
62    /// Questions with answers that were removed, kept so their answers keep
63    /// their meaning.
64    private(set) var archived: [Question] = []
65    private(set) var isLoaded = false
66
67    private var store: ReportStore?
68    private var saving: Task<Void, Never>?
69    private let logger = Logger(subsystem: "net.inqk.reportage", category: "Questions")
70
71    func load(from store: ReportStore?) async {
72        guard let store, let questions = try? await store.allQuestions() else { return }
73        self.store = store
74        self.questions = questions
75        isLoaded = true
76    }
77
78    func question(id: String) -> Question? {
79        questions.first { $0.id == id }
80    }
81
82    /// A list question other than the one with `id` whose answers start
83    /// the opening sentence, archived ones included, since past narratives
84    /// still read with them. A report has one opening sentence.
85    func sentenceOpener(otherThan id: String) -> Question? {
86        questions.first { $0.kind == .tokens && $0.id != id && $0.resolvedNarrativeRule == .activities }
87    }
88
89    /// Saves an edited question. Renamed answers, by old text, are renamed
90    /// in past reports too.
91    func update(_ question: Question, renamingOptions renames: [String: String] = [:]) {
92        guard let index = questions.firstIndex(where: { $0.id == question.id }),
93            questions[index] != question || !renames.isEmpty
94        else { return }
95        var question = question
96        question.modifiedAt = Date()
97        questions[index] = question
98        enqueue { [question] in try await $0.save(question, renamingOptions: renames) }
99    }
100
101    /// Deletes a question with no answers. One that has been answered since
102    /// is left in the store; it shows again when the list next loads.
103    func delete(id: String) {
104        questions.removeAll { $0.id == id }
105        enqueue { try await $0.deleteQuestion(id: id) }
106    }
107
108    /// Merges the question with `id` into `target`, then reloads, since
109    /// the merge can add choice answers to `target`.
110    func merge(_ id: String, into target: String) {
111        questions.removeAll { $0.id == id }
112        enqueue { try await $0.mergeQuestion(id, into: target) }
113        let saved = saving
114        Task {
115            await saved?.value
116            await load(from: store)
117        }
118    }
119
120    /// Adds a question at the end of the order.
121    func add(_ question: Question) {
122        var question = question
123        question.order = (questions.map(\.order).max() ?? -1) + 1
124        question.modifiedAt = Date()
125        questions.append(question)
126        save([question])
127    }
128
129    /// Moves questions within `survey`, keeping every other question where
130    /// it was in the order.
131    func move(in survey: Survey, from offsets: IndexSet, to destination: Int) {
132        let orders = Dictionary(uniqueKeysWithValues: questions.map { ($0.id, $0.order) })
133        var moved = Self.reordered(questions, in: survey, from: offsets, to: destination)
134        let now = Date()
135        var changed: [Question] = []
136        for index in moved.indices where moved[index].order != orders[moved[index].id] {
137            moved[index].modifiedAt = now
138            changed.append(moved[index])
139        }
140        questions = moved
141        save(changed)
142    }
143
144    /// `questions` with those asked in `survey` moved among themselves into
145    /// the places they held, then numbered in order.
146    static func reordered(
147        _ questions: [Question], in survey: Survey, from offsets: IndexSet, to destination: Int
148    ) -> [Question] {
149        let places = questions.indices.filter { questions[$0].isAsked(in: survey) }
150        var group = places.map { questions[$0] }
151        group.move(fromOffsets: offsets, toOffset: destination)
152        var result = questions
153        for (place, question) in zip(places, group) {
154            result[place] = question
155        }
156        for index in result.indices {
157            result[index].order = index
158        }
159        return result
160    }
161
162    private func group() {
163        bySurvey = Dictionary(
164            uniqueKeysWithValues: Survey.allCases.map { survey in
165                (survey, questions.filter { $0.isAsked(in: survey) })
166            })
167        notAsked = questions.filter { question in
168            question.archivedAt == nil && !Survey.allCases.contains { question.isAsked(in: $0) }
169        }
170        archived = questions.filter { $0.archivedAt != nil }
171    }
172
173    private func save(_ questions: [Question]) {
174        guard !questions.isEmpty else { return }
175        enqueue { try await $0.save(questions) }
176    }
177
178    /// Runs saves one after another, so a later edit can't be overwritten
179    /// by an earlier one finishing after it.
180    private func enqueue(_ save: @escaping @Sendable (ReportStore) async throws -> Void) {
181        guard let store else { return }
182        let previous = saving
183        saving = Task { [logger] in
184            await previous?.value
185            do {
186                try await save(store)
187                await MainActor.run { NotificationCenter.default.post(name: .summaryLookupChanged, object: nil) }
188            } catch {
189                logger.error("Couldn't save questions: \(error)")
190            }
191        }
192    }
193}
194
195/// The questions in each survey, in the order they're asked and read in the
196/// timeline. Questions are moved by dragging, opened to edit, and added
197/// with the add button.
198struct QuestionsView: View {
199    @Environment(\.reportStore) private var store
200    @State private var list = QuestionList()
201    @State private var isAdding = false
202
203    var body: some View {
204        List {
205            SettingsNote {
206                Text(
207                    "Questions are asked in this order, and their answers read in this order in the timeline. Manual reports ask the prompted questions."
208                )
209            }
210            ForEach(Survey.allCases, id: \.self) { survey in
211                Section {
212                    ForEach(list.bySurvey[survey] ?? [], id: \.id) { question in
213                        QuestionRow(question: question, list: list)
214                    }
215                    .onMove { offsets, destination in
216                        list.move(in: survey, from: offsets, to: destination)
217                    }
218                    if list.isLoaded, list.bySurvey[survey]?.isEmpty ?? true {
219                        SettingsNote { Text("No questions are asked.") }
220                    }
221                } header: {
222                    SettingsHeading(survey.title)
223                }
224            }
225            if !list.notAsked.isEmpty {
226                Section {
227                    ForEach(list.notAsked, id: \.id) { question in
228                        QuestionRow(question: question, list: list)
229                    }
230                } header: {
231                    SettingsHeading("Not Asked")
232                }
233            }
234            if !list.archived.isEmpty {
235                Section {
236                    SettingsNote {
237                        Text(
238                            "These questions have answers in past reports, so they're kept rather than deleted, and their answers still show in those reports. Open one and turn on a survey to ask it again."
239                        )
240                    }
241                    ForEach(list.archived, id: \.id) { question in
242                        QuestionRow(question: question, list: list)
243                    }
244                } header: {
245                    SettingsHeading("Archived")
246                }
247            }
248        }
249        .listStyle(.plain)
250        .scrollContentBackground(.hidden)
251        .tabBarClearance()
252        .background(Theme.paper)
253        .foregroundStyle(Theme.ink)
254        .navigationTitle("Questions")
255        .navigationBarTitleDisplayMode(.inline)
256        .toolbar(.visible, for: .navigationBar)
257        .toolbar {
258            ToolbarItem(placement: .primaryAction) {
259                EditButton()
260            }
261            ToolbarItem(placement: .primaryAction) {
262                Button("Add Question", systemImage: "plus") { isAdding = true }
263                    .disabled(!list.isLoaded)
264            }
265        }
266        .sheet(isPresented: $isAdding) {
267            AddQuestionView(list: list)
268        }
269        .task { await list.load(from: store) }
270    }
271}
272
273/// The questions one can be merged into. Choosing one asks for
274/// confirmation, since a merge can't be undone.
275private struct MergeQuestionView: View {
276    let source: Question
277    /// How many reports answered `source`.
278    let count: Int
279    let targets: [Question]
280    let onMerge: (Question) -> Void
281    @State private var chosen: Question?
282    @Environment(\.dismiss) private var dismiss
283
284    var body: some View {
285        NavigationStack {
286            List {
287                ForEach(targets, id: \.id) { question in
288                    Button {
289                        chosen = question
290                    } label: {
291                        VStack(alignment: .leading, spacing: Theme.lineGap) {
292                            Text(question.prompt)
293                                .font(Theme.serif(.body))
294                            if question.archivedAt != nil {
295                                Text("Archived")
296                                    .font(.footnote)
297                                    .foregroundStyle(Theme.muted)
298                            }
299                        }
300                        .frame(maxWidth: .infinity, alignment: .leading)
301                        .contentShape(Rectangle())
302                    }
303                    .buttonStyle(.plain)
304                    .settingsRow()
305                }
306            }
307            .listStyle(.plain)
308            .scrollContentBackground(.hidden)
309            .background(Theme.paper)
310            .foregroundStyle(Theme.ink)
311            .navigationTitle("Merge Into")
312            .navigationBarTitleDisplayMode(.inline)
313            .toolbar {
314                ToolbarItem(placement: .cancellationAction) {
315                    Button("Cancel") { dismiss() }
316                }
317            }
318            .alert(
319                "Merge into '\(chosen?.prompt ?? "")'?",
320                isPresented: Binding(get: { chosen != nil }, set: { if !$0 { chosen = nil } }),
321                presenting: chosen
322            ) { target in
323                Button("Cancel", role: .cancel) {}
324                Button("Merge") { onMerge(target) }
325            } message: { _ in
326                Text(
327                    "Answers in ^[\(count) report](inflect: true) move to that question, and '\(source.prompt)' is deleted. This can't be undone."
328                )
329            }
330        }
331    }
332}
333
334/// A question's prompt, noting when its answers are left out of the
335/// timeline.
336private struct QuestionRow: View {
337    let question: Question
338    let list: QuestionList
339
340    var body: some View {
341        NavigationLink {
342            QuestionDetailView(question: question, list: list)
343        } label: {
344            VStack(alignment: .leading, spacing: Theme.lineGap) {
345                Text(question.prompt)
346                    .font(Theme.serif(.body))
347                if !question.showsInTimeline {
348                    Text("Not shown in timeline")
349                        .font(.footnote)
350                        .foregroundStyle(Theme.muted)
351                }
352            }
353        }
354        .settingsRow()
355    }
356}
357
358/// One question, edited in place. Each field is saved when it's finished.
359/// A question with no answers can be deleted; one with answers can only be
360/// archived, so its answers keep their meaning.
361private struct QuestionDetailView: View {
362    let list: QuestionList
363    @State private var editor: QuestionEditor
364    /// `nil` until counted.
365    @State private var answerCount: Int?
366    @State private var isConfirmingDelete = false
367    @State private var isChoosingTarget = false
368    @Environment(\.reportStore) private var store
369    @Environment(\.dismiss) private var dismiss
370
371    init(question: Question, list: QuestionList) {
372        self.list = list
373        _editor = State(initialValue: QuestionEditor(question: question))
374    }
375
376    var body: some View {
377        QuestionForm(
378            editor: editor, onCommit: commit,
379            sentenceOpener: list.sentenceOpener(otherThan: editor.question.id)
380        ) {
381            removal
382        }
383        .navigationBarTitleDisplayMode(.inline)
384        .task {
385            answerCount = try? await store?.answerCount(questionID: editor.question.id)
386        }
387        .alert("Delete this question?", isPresented: $isConfirmingDelete) {
388            Button("Cancel", role: .cancel) {}
389            Button("Delete Question", role: .destructive) {
390                list.delete(id: editor.question.id)
391                dismiss()
392            }
393        } message: {
394            Text("It hasn't been answered, so no reports change. This can't be undone.")
395        }
396        .sheet(isPresented: $isChoosingTarget) {
397            MergeQuestionView(source: editor.question, count: answerCount ?? 0, targets: targets) { target in
398                isChoosingTarget = false
399                list.merge(editor.question.id, into: target.id)
400                dismiss()
401            }
402        }
403    }
404
405    /// The other questions of this kind, which this one can be merged into.
406    private var targets: [Question] {
407        list.questions.filter { $0.kind == editor.question.kind && $0.id != editor.question.id }
408    }
409
410    /// Merging, for a question with answers and another of its kind.
411    @ViewBuilder private var merge: some View {
412        if let answerCount, answerCount > 0, !targets.isEmpty {
413            removeButton("Merge Into…", role: nil) { isChoosingTarget = true }
414        }
415    }
416
417    @ViewBuilder private var removal: some View {
418        // An unanswered question can be deleted even when archived, as the
419        // default questions are when a Reporter import replaces them.
420        if answerCount == 0 {
421            Section {
422                removeButton("Delete Question", role: .destructive) { isConfirmingDelete = true }
423            }
424        } else if editor.archivedAt != nil {
425            Section {
426                merge
427                SettingsNote {
428                    Text(
429                        "This question is archived. It has answers in past reports, so it's kept rather than deleted. Turn on a survey above to ask it again."
430                    )
431                }
432            }
433        } else if let answerCount {
434            Section {
435                removeButton("Archive Question", role: nil) {
436                    editor.archive()
437                    commit()
438                    dismiss()
439                }
440                merge
441                SettingsNote {
442                    Text(
443                        "This question can't be deleted because it's been answered in ^[\(answerCount) report](inflect: true). Archiving it stops it being asked and keeps those answers."
444                    )
445                }
446            }
447        }
448    }
449
450    private func removeButton(
451        _ title: LocalizedStringKey, role: ButtonRole?, action: @escaping () -> Void
452    ) -> some View {
453        Button(title, role: role, action: action)
454            .font(.body.weight(.semibold))
455            .foregroundStyle(role == .destructive ? Color.red : Theme.accent)
456            .frame(maxWidth: .infinity, minHeight: 44)
457            .listRowBackground(Theme.paper)
458            .listRowSeparator(.hidden)
459    }
460
461    private func commit() {
462        let (question, renames) = editor.drafted()
463        guard question != editor.question || !renames.isEmpty else { return }
464        list.update(question, renamingOptions: renames)
465        if let saved = list.question(id: question.id) {
466            editor.saved(saved)
467        }
468    }
469}
470
471/// A new question's fields, its type among them, added to the end of the
472/// order.
473private struct AddQuestionView: View {
474    let list: QuestionList
475    @State private var editor = QuestionEditor(adding: .tokens)
476    @Environment(\.dismiss) private var dismiss
477
478    var body: some View {
479        NavigationStack {
480            QuestionForm(editor: editor, sentenceOpener: list.sentenceOpener(otherThan: editor.question.id))
481                .navigationTitle("New Question")
482                .navigationBarTitleDisplayMode(.inline)
483                .toolbar {
484                    ToolbarItem(placement: .cancellationAction) {
485                        Button("Cancel") { dismiss() }
486                    }
487                    ToolbarItem(placement: .confirmationAction) {
488                        Button("Add") {
489                            list.add(editor.drafted().question)
490                            dismiss()
491                        }
492                        .disabled(!editor.isComplete)
493                    }
494                }
495        }
496    }
497}