Reportage/Views/Survey/SurveyView.swift (14446B)
1import SwiftUI
2import UIKit
3
4
5
6struct SurveyRequest: Identifiable {
7 let id = UUID()
8 var kind: ReportKind
9 var date = Date()
10
11 var trigger: ReportTrigger = .app
12
13 var promptedAt: Date?
14
15 var reportID: UUID?
16
17
18
19 static func edit(_ id: UUID, kind: ReportKind) -> SurveyRequest {
20 SurveyRequest(kind: kind, reportID: id)
21 }
22}
23
24
25struct SurveySheet: View {
26 let request: SurveyRequest
27
28 @Environment(\.reportStore) private var store
29 @State private var model: SurveyModel?
30 @State private var loadError: String?
31
32 var body: some View {
33 Group {
34 if let model {
35 SurveyView(model: model)
36 } else if let loadError {
37 ContentUnavailableView(
38 "Couldn't Load Survey",
39 systemImage: "exclamationmark.triangle",
40 description: Text(loadError)
41 )
42 } else {
43 ProgressView()
44 }
45 }
46 .frame(maxWidth: .infinity, maxHeight: .infinity)
47 .presentationBackground(Theme.paper)
48 .task { await load() }
49 }
50
51 private func load() async {
52 guard model == nil, let store else { return }
53 do {
54 var existing: Report?
55 if let id = request.reportID {
56 guard let report = try await store.report(id: id) else {
57 loadError = String(localized: "This report no longer exists.")
58 return
59 }
60 existing = report
61 }
62
63
64
65 let questions =
66 if let existing, !existing.responses.isEmpty {
67 try await store.questions(ids: existing.responses.map(\.questionID))
68 } else {
69 try await store.surveyQuestions(for: existing?.kind ?? request.kind)
70 }
71 let tokenQuestions = questions.filter {
72 [QuestionKind.tokens, .people, .location].contains($0.kind)
73 }
74 let vocabulary = try await store.vocabulary(for: tokenQuestions.map(\.id))
75 let model: SurveyModel
76 if let existing {
77 let tokens = try await store.tokenEntries(ids: existing.responses.flatMap(\.tokenIDs))
78 model = SurveyModel(
79 editing: existing, questions: questions, vocabulary: vocabulary, tokens: tokens)
80 } else {
81 let previous = try await store.previousReport(
82 before: request.date, within: SurveyModel.carryInterval)
83 model = SurveyModel(
84 kind: request.kind,
85 date: request.date,
86 trigger: request.trigger,
87 promptedAt: request.promptedAt,
88 questions: questions,
89 vocabulary: vocabulary,
90 previous: previous
91 )
92 model.startCapture()
93 }
94 self.model = model
95 } catch {
96 loadError = error.localizedDescription
97 }
98 }
99}
100
101
102struct SurveyView: View {
103 let model: SurveyModel
104
105 @Environment(\.reportStore) private var store
106 @Environment(\.dismiss) private var dismiss
107 @State private var isConfirmingCancel = false
108 @State private var isSaving = false
109 @State private var saveError: String?
110 @State private var isShowingSaveError = false
111
112 var body: some View {
113 Group {
114 if model.questions.isEmpty {
115 NoQuestions()
116 } else {
117 QuestionPages(model: model, onAnswer: answered)
118 }
119 }
120 .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top)
121 .safeAreaInset(edge: .top) {
122 SurveyHeader(
123 kind: model.kind,
124 date: model.date,
125 position: model.index,
126 count: model.questions.count,
127 onCancel: cancel
128 )
129 .alert(
130 model.existing == nil ? "Discard this report?" : "Discard your changes?",
131 isPresented: $isConfirmingCancel
132 ) {
133 Button("Keep Editing", role: .cancel) {}
134 if model.existing == nil {
135 Button("Discard Report", role: .destructive) { dismiss() }
136 } else {
137 Button("Discard Changes", role: .destructive) { dismiss() }
138 }
139 } message: {
140 if model.existing != nil {
141 Text("The report stays as it was.")
142 }
143 }
144 }
145 .safeAreaInset(edge: .bottom) {
146 SurveyControls(
147 canGoBack: model.index > 0,
148 isLastQuestion: model.isLastQuestion,
149 isSaving: isSaving,
150 onBack: { withAnimation { model.goBack() } },
151 onNext: next
152 )
153 }
154 .background(Theme.paper)
155 .foregroundStyle(Theme.ink)
156 .alert("Couldn't Save Report", isPresented: $isShowingSaveError) {
157 Button("OK", role: .cancel) {}
158 } message: {
159 if let saveError { Text(saveError) }
160 }
161 .interactiveDismissDisabled(model.hasChanges)
162 }
163
164 private func cancel() {
165 if model.hasChanges {
166 isConfirmingCancel = true
167 } else {
168 dismiss()
169 }
170 }
171
172
173
174 private func answered() {
175 let index = model.index
176 guard !model.isLastQuestion else { return }
177 Task {
178 try? await Task.sleep(for: .milliseconds(250))
179 withAnimation { model.advance(from: index) }
180 }
181 }
182
183 private func next() {
184 if model.isLastQuestion {
185 save()
186 } else {
187 withAnimation { _ = model.advance() }
188 }
189 }
190
191 private func save() {
192 guard let store, !isSaving else { return }
193 isSaving = true
194 Task {
195 let context = await model.capturedContext()
196 let (report, newTokens) = model.makeReport(now: Date(), context: context)
197 do {
198 if model.existing == nil {
199 try await store.insert(report, newTokens: newTokens)
200 } else {
201 try await store.saveAnswers(report, newTokens: newTokens)
202 }
203 dismiss()
204 } catch {
205 saveError = error.localizedDescription
206 isShowingSaveError = true
207 isSaving = false
208 }
209 }
210 }
211}
212
213
214
215
216struct QuestionPages: View {
217 let model: SurveyModel
218 let onAnswer: () -> Void
219
220 var body: some View {
221 ScrollView(.horizontal) {
222 LazyHStack(spacing: 0) {
223 ForEach(Array(model.questions.enumerated()), id: \.element.id) { index, question in
224 QuestionPage(
225 question: question,
226 model: model,
227 isCurrent: index == model.index,
228 onAnswer: onAnswer
229 )
230 .containerRelativeFrame([.horizontal, .vertical])
231 }
232 }
233 .scrollTargetLayout()
234 }
235 .scrollTargetBehavior(.paging)
236 .scrollPosition($position)
237 .scrollIndicators(.hidden)
238 .onScrollGeometryChange(for: Double.self) { geometry in
239 let width = geometry.containerSize.width
240 return width > 0 ? geometry.contentOffset.x / width : 0
241 } action: { _, page in
242 self.page = page
243
244
245 if phase == .idle { turn(to: model.index) }
246 }
247 .onScrollPhaseChange { _, phase in
248 self.phase = phase
249 if phase == .interacting {
250 isSwiping = true
251 endEditing()
252 } else if phase == .idle {
253 settle()
254 isSwiping = false
255 }
256 }
257 .onChange(of: model.index) { turn(to: model.index) }
258 }
259
260 @State private var position = ScrollPosition(idType: String.self)
261
262 @State private var page = 0.0
263
264 @State private var isSwiping = false
265 @State private var phase = ScrollPhase.idle
266
267
268 private func turn(to index: Int) {
269 guard model.questions.indices.contains(index), !isShowing(index) else { return }
270 endEditing()
271 withAnimation { position.scrollTo(id: model.questions[index].id) }
272 }
273
274
275
276
277 private func endEditing() {
278 UIApplication.shared.sendAction(
279 #selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
280 }
281
282
283
284
285
286 private func settle() {
287 let nearest = Int(page.rounded())
288 if isSwiping, isShowing(nearest) {
289 model.show(nearest)
290 } else {
291 turn(to: model.index)
292 }
293 }
294
295
296 private func isShowing(_ index: Int) -> Bool {
297 abs(page - Double(index)) < 0.001
298 }
299}
300
301
302
303struct SurveyHeader: View {
304 let kind: ReportKind
305 let date: Date
306
307 let position: Int
308 let count: Int
309 let onCancel: () -> Void
310
311 var body: some View {
312 VStack(spacing: 14) {
313 HStack {
314 Button("Cancel", action: onCancel)
315 .frame(minHeight: 44)
316 Spacer()
317 Text("\(Text(kind.title)), \(date, format: .dateTime.hour().minute())",
318 comment: "Survey title: the report kind, then the time it describes.")
319 .font(Theme.serif(.headline, weight: .regular).italic())
320 Spacer()
321 Text(count > 0 ? "\(position + 1) / \(count)" : "",
322 comment: "Survey progress: the current question number, then the number of questions.")
323 .font(.footnote.weight(.semibold))
324 .monospacedDigit()
325 .foregroundStyle(Theme.muted)
326 .frame(minWidth: 44, alignment: .trailing)
327 }
328 if count > 1 {
329 SurveyProgress(position: position, count: count)
330 }
331 }
332 .padding(.horizontal, Theme.margin)
333 .padding(.top, 8)
334 .background(Theme.paper)
335 }
336}
337
338struct SurveyProgress: View {
339 let position: Int
340 let count: Int
341
342 var body: some View {
343 HStack(spacing: 4) {
344 ForEach(0..<count, id: \.self) { index in
345 Capsule()
346 .fill(color(at: index))
347 .frame(height: 2)
348 }
349 }
350 .accessibilityHidden(true)
351 }
352
353 private func color(at index: Int) -> Color {
354 if index == position { return Theme.accent }
355 return index < position ? Theme.ink : Theme.rule
356 }
357}
358
359struct NoQuestions: View {
360 var body: some View {
361 VStack(alignment: .leading, spacing: Theme.itemGap) {
362 Text("No questions")
363 .font(Theme.serif(.largeTitle, weight: .medium))
364 Text("This survey has no questions. The report will be saved with its time.")
365 .foregroundStyle(Theme.muted)
366 }
367 .frame(maxWidth: .infinity, alignment: .leading)
368 .padding(Theme.margin)
369 }
370}
371
372
373
374struct SurveyControls: View {
375 let canGoBack: Bool
376 let isLastQuestion: Bool
377 let isSaving: Bool
378 let onBack: () -> Void
379 let onNext: () -> Void
380
381 var body: some View {
382 HStack(spacing: 0) {
383 Button("Back", systemImage: "chevron.backward", action: onBack)
384 .labelStyle(.iconOnly)
385 .font(.body.weight(.semibold))
386 .frame(width: 52, height: 52)
387 .overlay(Circle().strokeBorder(Theme.ink, lineWidth: 1.5))
388 .opacity(canGoBack ? 1 : 0.3)
389 .disabled(!canGoBack)
390 Spacer(minLength: 24)
391 Button(action: onNext) {
392 Text(isLastQuestion ? "Done" : "Next")
393 .font(.body.weight(.semibold))
394 .foregroundStyle(Theme.onAccent)
395 .padding(.horizontal, 36)
396 .frame(minHeight: 52)
397 .background(Theme.accent, in: .capsule)
398 }
399 }
400 .buttonStyle(.plain)
401 .tint(Theme.ink)
402 .disabled(isSaving)
403 .padding(.horizontal, Theme.margin)
404 .padding(.vertical, 12)
405 .background(Theme.paper)
406 }
407}