DayByDay/Quiz/CelebrationOverlay.swift
83 lines · 2669 bytes
2 symbols in this file
1//
2// CelebrationOverlay.swift
3// DayByDay
4//
5
6import SwiftUI
7
8/// A short confetti burst for a correct answer. With Reduce Motion on,
9/// a few sparkles fade in and out instead.
10struct CelebrationOverlay: View {
11 let isActive: Bool
12
13 @Environment(\.accessibilityReduceMotion) private var reduceMotion
14 @State private var startDate = Date()
15
16 static let duration: Double = 1.1
17
18 var body: some View {
19 Group {
20 if isActive {
21 if reduceMotion {
22 sparkles
23 } else {
24 confetti
25 }
26 }
27 }
28 .allowsHitTesting(false)
29 .animation(.easeInOut(duration: 0.25), value: isActive)
30 .onChange(of: isActive) { _, active in
31 if active { startDate = Date() }
32 }
33 }
34
35 private var sparkles: some View {
36 HStack(spacing: 40) {
37 ForEach(0..<3, id: \.self) { _ in
38 Image(systemName: "sparkles")
39 .font(.system(size: 56))
40 .foregroundStyle(.yellow)
41 }
42 }
43 .transition(.opacity)
44 }
45
46 private var confetti: some View {
47 TimelineView(.animation) { timeline in
48 Canvas { context, size in
49 let t = timeline.date.timeIntervalSince(startDate)
50 guard t < Self.duration else { return }
51 let fade = 1 - max(0, (t - Self.duration * 0.6) / (Self.duration * 0.4))
52 for p in Self.particles {
53 let x = size.width * (0.5 + p.vx * t)
54 let y = size.height * (0.45 + p.vy * t + 0.9 * t * t)
55 var piece = context
56 piece.opacity = fade
57 piece.translateBy(x: x, y: y)
58 piece.rotate(by: .degrees(p.spin * t))
59 piece.fill(Path(roundedRect: CGRect(x: -6, y: -3, width: 12, height: 6), cornerRadius: 2),
60 with: .color(p.color))
61 }
62 }
63 }
64 }
65
66 private struct Particle {
67 let vx: Double
68 let vy: Double
69 let spin: Double
70 let color: Color
71 }
72
73 private static let particles: [Particle] = {
74 let colors: [Color] = [.red, .orange, .yellow, .green, .blue, .purple, .pink]
75 var rng = SystemRandomNumberGenerator()
76 return (0..<60).map { i in
77 Particle(vx: .random(in: -0.6...0.6, using: &rng),
78 vy: .random(in: -1.0 ... -0.3, using: &rng),
79 spin: .random(in: -540...540, using: &rng),
80 color: colors[i % colors.count])
81 }
82 }()
83}