DayByDay/Quiz/TraceView.swift
180 lines · 6755 bytes
1//
2// TraceView.swift
3// DayByDay
4//
5
6import SwiftUI
7
8/// Trace five shapes or letters with a finger.
9struct TraceView: View {
10 static let length = 5
11
12 let category: Category
13
14 @Environment(ProfileSession.self) private var session
15 @State private var items: [QuizItem]
16 @State private var index = 0
17 @State private var strokes: [[CGPoint]] = []
18 @State private var celebrating = false
19 @State private var mascot = MascotState()
20 @State private var busy = false
21 @State private var speechToken = 0
22 /// Bumped when the screen goes away, so pending work does nothing.
23 @State private var generation = 0
24 /// Counts passes, so a backstop from an earlier pass does nothing.
25 @State private var passes = 0
26
27 init(category: Category) {
28 self.category = category
29 _items = State(initialValue: Self.pick(category))
30 }
31
32 private static func pick(_ category: Category) -> [QuizItem] {
33 Array(category.quizItems.shuffled().prefix(length))
34 }
35
36 private var item: QuizItem? { index < items.count ? items[index] : nil }
37
38 var body: some View {
39 ZStack {
40 if let item {
41 board(item)
42 } else {
43 FinishedView {
44 items = Self.pick(category)
45 index = 0
46 strokes = []
47 prompt()
48 }
49 }
50 }
51 .onAppear { prompt() }
52 .onDisappear {
53 generation += 1
54 speechToken += 1
55 SpeechSynthesizer.shared.stop()
56 }
57 }
58
59 private func board(_ item: QuizItem) -> some View {
60 VStack(spacing: 20) {
61 // Own row: beside both pills it would squeeze their labels on a phone.
62 GameMascot(state: $mascot)
63 // Stacked when side by side would cut the labels off.
64 ViewThatFits(in: .horizontal) {
65 HStack(spacing: 16) { pills }
66 VStack(spacing: 12) { pills }
67 }
68 GeometryReader { geo in
69 let size = min(geo.size.width, geo.size.height)
70 let region = Path(TraceGuide.region(for: item, size: size))
71 ZStack {
72 region.fill(category.color.opacity(0.4))
73 region.stroke(category.color, style: StrokeStyle(lineWidth: 3, dash: [10, 8]))
74 ForEach(Array(strokes.enumerated()), id: \.offset) { _, stroke in
75 Path { p in p.addLines(stroke) }
76 // Primary, not the topic color, so the ink shows on the guide in both modes.
77 .stroke(Color.primary, style: StrokeStyle(lineWidth: size * 0.08, lineCap: .round, lineJoin: .round))
78 }
79 }
80 .frame(width: size, height: size)
81 .contentShape(Rectangle())
82 .gesture(
83 DragGesture(minimumDistance: 0)
84 .onChanged { value in
85 guard !busy else { return }
86 if value.translation == .zero || strokes.isEmpty { strokes.append([]) }
87 strokes[strokes.count - 1].append(value.location)
88 }
89 .onEnded { _ in check(item, size: size) }
90 )
91 .frame(maxWidth: .infinity, maxHeight: .infinity)
92 // VoiceOver, Voice Control and Switch Control users trace by activating the guide.
93 .accessibilityElement()
94 .accessibilityLabel("Trace \(Lines.traceLabel(item))")
95 .accessibilityAddTraits(.isButton)
96 .accessibilityAction { succeed(item) }
97 }
98 .frame(maxWidth: 520)
99 }
100 .padding(24)
101 .overlay { CelebrationOverlay(isActive: celebrating) }
102 }
103
104 @ViewBuilder
105 private var pills: some View {
106 pill("Hear it again", "speaker.wave.2.fill", action: prompt)
107 pill("Start over", "eraser.fill") { strokes = [] }
108 }
109
110 private func pill(_ title: String, _ symbol: String, action: @escaping () -> Void) -> some View {
111 Button(action: action) {
112 Label(title, systemImage: symbol)
113 .font(.heading(19))
114 .fixedSize(horizontal: false, vertical: true)
115 .padding(.horizontal, 20)
116 .padding(.vertical, 14)
117 .background(RoundedRectangle(cornerRadius: 26, style: .continuous).fill(Color(.systemGray6)))
118 }
119 .buttonStyle(.plain)
120 }
121
122 private func check(_ item: QuizItem, size: CGFloat) {
123 guard !busy else { return }
124 let checker = TraceChecker(region: TraceGuide.region(for: item, size: size), size: size)
125 let drawn = strokes.flatMap { $0 }
126 let score = checker.score(drawn)
127 if checker.passes(drawn) {
128 succeed(item)
129 } else if score.accuracy < 0.5 && score.coverage > 0.4 {
130 record(item, correct: false)
131 SoundEngine.shared.play(.gentleMiss)
132 mascot.handle(.wrong)
133 strokes = []
134 say(Lines.traceMiss(item), after: RoundStyle.speechDelay)
135 }
136 }
137
138 private func succeed(_ item: QuizItem) {
139 guard !busy else { return }
140 record(item, correct: true)
141 busy = true
142 celebrating = true
143 SoundEngine.shared.play(.success)
144 mascot.handle(.correct)
145 passes += 1
146 let gen = generation, pass = passes
147 let advance = {
148 guard gen == generation, pass == passes, busy else { return }
149 busy = false
150 celebrating = false
151 strokes = []
152 index += 1
153 if self.item != nil { prompt() }
154 }
155 say(Lines.traceSuccess(item), after: RoundStyle.speechDelay, then: advance)
156 DispatchQueue.main.asyncAfter(deadline: .now() + 8, execute: advance)
157 }
158
159 private func record(_ item: QuizItem, correct: Bool) {
160 if let profile = session.current {
161 session.store.record(item, game: .trace, correct: correct, for: profile)
162 }
163 }
164
165 private func prompt() {
166 guard let item else { return }
167 let text = Lines.tracePrompt(item)
168 mascot.handle(.prompt(text))
169 say(text, after: 0)
170 }
171
172 private func say(_ text: String, after delay: TimeInterval, then completion: (() -> Void)? = nil) {
173 speechToken += 1
174 let token = speechToken, gen = generation
175 DispatchQueue.main.asyncAfter(deadline: .now() + delay) {
176 guard token == speechToken, gen == generation else { return }
177 SpeechSynthesizer.shared.speak(text, completion: completion)
178 }
179 }
180}