krz/daybyday

iOS learning games for young children: days, months, seasons, numbers, letters, animals and more. education ios kids swift https://krz.sh/apps/daybyday/

DayByDay/Today/TodayRoutineView.swift

062549ad26607ce9e973ed2a9a7ef6f853885f83
daybyday/DayByDay/Today/TodayRoutineView.swift history · blame · raw

177 lines · 6491 bytes

9 symbols in this file
  1//
  2//  TodayRoutineView.swift
  3//  DayByDay
  4//
  5
  6import SwiftUI
  7
  8/// The morning routine: a few spoken lines about today, the child picks
  9/// today's weather, and a sticker goes on the calendar.
 10struct TodayRoutineView: View {
 11    static let weathers = Lines.stickerWeathers
 12
 13    private enum Phase: Equatable { case line(Int), weather, done }
 14
 15    @Environment(ProfileSession.self) private var session
 16    @Environment(\.dismiss) private var dismiss
 17    @State private var phase = Phase.line(0)
 18    @State private var lines: [RoutineScript.Line] = []
 19    @State private var celebrating = false
 20    @State private var mascot = MascotState()
 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
 25    private let columns = [GridItem(.adaptive(minimum: 140, maximum: 220), spacing: 16)]
 26
 27    var body: some View {
 28        ZStack {
 29            switch phase {
 30            case .line(let i) where i < lines.count:
 31                lineCard(lines[i])
 32            case .line:
 33                Color.clear
 34            case .weather:
 35                weatherPick
 36            case .done:
 37                ScrollView {
 38                    VStack(spacing: 20) {
 39                        GameMascot(state: $mascot)
 40                        StickerCalendarView(profile: session.current)
 41                            .frame(maxWidth: 560)
 42                            .padding(.top, 8)
 43                        Button { dismiss() } label: {
 44                            Label("Done", systemImage: "checkmark")
 45                                .font(.heading(28))
 46                                .foregroundStyle(.white)
 47                                .padding(.horizontal, 44)
 48                                .padding(.vertical, 20)
 49                                .background(Capsule().fill(RoundStyle.playAgainFill))
 50                        }
 51                        .buttonStyle(.plain)
 52                    }
 53                    .padding(.bottom, 24)
 54                }
 55            }
 56        }
 57        .overlay { CelebrationOverlay(isActive: celebrating) }
 58        .onAppear {
 59            if lines.isEmpty { lines = script().lines }
 60            speakCurrent()
 61        }
 62        .onDisappear {
 63            generation += 1
 64            speechToken += 1
 65            SpeechSynthesizer.shared.stop()
 66        }
 67    }
 68
 69    private func script() -> RoutineScript {
 70        let profile = session.current
 71        let birthday = profile.flatMap { p in p.birthdayMonth.flatMap { m in p.birthdayDay.map { (month: m, day: $0) } } }
 72        return RoutineScript(date: .now, calendar: AppCalendar.current, name: profile?.name, birthday: birthday,
 73                             picture: profile.flatMap { session.store.picture(on: .current, for: $0) })
 74    }
 75
 76    private func lineCard(_ line: RoutineScript.Line) -> some View {
 77        CenteredScrollView {
 78            VStack(spacing: 28) {
 79                hearAgain
 80                VStack(spacing: 20) {
 81                    Image(systemName: line.symbol)
 82                        .font(.system(size: 110))
 83                        .frame(height: 130)
 84                    Text(line.text)
 85                        .font(.heading(32, weight: .heavy))
 86                        .multilineTextAlignment(.center)
 87                        .minimumScaleFactor(0.6)
 88                }
 89                .foregroundStyle(.white)
 90                .padding(28)
 91                .frame(maxWidth: 520, minHeight: 300)
 92                .background(RoundedRectangle(cornerRadius: 36, style: .continuous).fill(TodayBanner.gradientColors[0]))
 93                .accessibilityElement(children: .combine)
 94
 95                Button(action: next) {
 96                    Image(systemName: "arrow.right")
 97                        .font(.system(size: 40, weight: .heavy))
 98                        .foregroundStyle(.white)
 99                        .frame(width: 96, height: 96)
100                        .background(Circle().fill(RoundStyle.playAgainFill))
101                }
102                .buttonStyle(.plain)
103                .accessibilityLabel("Next")
104            }
105            .padding(24)
106        }
107    }
108
109    private var weatherPick: some View {
110        ScrollView {
111            VStack(spacing: 24) {
112                hearAgain
113                LazyVGrid(columns: columns, spacing: 16) {
114                    ForEach(Self.weathers) { weather in
115                        Button { pick(weather) } label: {
116                            ChoiceTile(item: Category.weather.item(weather)).frame(height: 140)
117                        }
118                        .buttonStyle(.plain)
119                        .accessibilityLabel(weather.name)
120                    }
121                }
122            }
123            .padding(24)
124        }
125    }
126
127    private var hearAgain: some View {
128        PromptBar(mascot: $mascot, action: speakCurrent)
129    }
130
131    private func next() {
132        guard case .line(let i) = phase else { return }
133        phase = i + 1 < lines.count ? .line(i + 1) : .weather
134        speakCurrent()
135    }
136
137    private func speakCurrent() {
138        switch phase {
139        case .line(0) where !lines.isEmpty:
140            mascot.handle(.greet)
141            say(lines[0].spoken)
142        case .line(let i) where i < lines.count: ask(lines[i].spoken)
143        case .weather: ask(Lines.weatherQuestion)
144        default: break
145        }
146    }
147
148    private func pick(_ weather: LearnWeather) {
149        guard phase == .weather else { return }
150        let today = AppCalendar.current.dateComponents([.year, .month, .day], from: .now)
151        if let profile = session.current {
152            session.store.addSticker(for: profile, on: today, weather: weather)
153        }
154        SoundEngine.shared.play(.success)
155        mascot.handle(.correct)
156        celebrating = true
157        phase = .done
158        say(Lines.sticker(weather), after: RoundStyle.speechDelay)
159        let gen = generation
160        DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {
161            if gen == generation { celebrating = false }
162        }
163    }
164
165    private func ask(_ text: String) {
166        mascot.handle(.prompt(text))
167        say(text)
168    }
169
170    private func say(_ text: String, after delay: TimeInterval = 0) {
171        speechToken += 1
172        let token = speechToken, gen = generation
173        DispatchQueue.main.asyncAfter(deadline: .now() + delay) {
174            if token == speechToken, gen == generation { SpeechSynthesizer.shared.speak(text) }
175        }
176    }
177}