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/

DayByDayTests/ReviewExport.swift

062549ad26607ce9e973ed2a9a7ef6f853885f83
daybyday/DayByDayTests/ReviewExport.swift history · blame · raw

193 lines · 10623 bytes

10 symbols in this file
  1import Foundation
  2import SwiftUI
  3import UIKit
  4import Testing
  5@testable import DayByDay
  6
  7/// Writes every sound as WAV and every choice tile as PNG for art and sound
  8/// review. Runs only when EXPORT_DIR is set, e.g.
  9/// `TEST_RUNNER_EXPORT_DIR=/tmp/review xcodebuild test ... -only-testing:DayByDayTests/ReviewExport`.
 10@MainActor
 11@Suite(.enabled(if: ProcessInfo.processInfo.environment["EXPORT_DIR"] != nil))
 12struct ReviewExport {
 13    let dir = URL(fileURLWithPath: ProcessInfo.processInfo.environment["EXPORT_DIR"] ?? NSTemporaryDirectory())
 14
 15    /// Every spoken sentence, one per line, for scripts/render-voice.py.
 16    @Test func lines() throws {
 17        try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
 18        try (SpokenLines.all.sorted().joined(separator: "\n") + "\n")
 19            .write(to: dir.appendingPathComponent("lines.txt"), atomically: true, encoding: .utf8)
 20    }
 21
 22    @Test func sounds() throws {
 23        try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
 24        for effect in SoundEffect.allCases {
 25            try wav(SoundSynth.render(effect)).write(to: dir.appendingPathComponent("\(effect).wav"))
 26        }
 27    }
 28
 29    @Test func tiles() throws {
 30        try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
 31        for category in DayByDay.Category.gridCases {
 32            for scheme in [ColorScheme.light, .dark] {
 33                let rows = stride(from: 0, to: category.quizItems.count, by: 4).map {
 34                    Array(category.quizItems[$0..<min($0 + 4, category.quizItems.count)])
 35                }
 36                let sheet = VStack(alignment: .leading, spacing: 20) {
 37                    ForEach(rows, id: \.self) { row in
 38                        HStack(spacing: 20) {
 39                            ForEach(row) { ChoiceTile(item: $0).frame(width: 170, height: 160) }
 40                        }
 41                    }
 42                }
 43                .padding(32)
 44                .background(Color(.systemBackground))
 45                .environment(\.colorScheme, scheme)
 46                try png(sheet).write(to: dir.appendingPathComponent("tiles-\(category.key)-\(scheme).png"))
 47            }
 48        }
 49        let drawn = HStack(spacing: 24) {
 50            ForEach([LearnAnimal.cow, .duck, .sheep, .pig, .cat]) { animal in
 51                AnimalIcon(animal: animal)
 52                    .font(.system(size: 200))
 53                    .frame(width: 260, height: 260)
 54                    .foregroundStyle(.white)
 55                    .padding(20)
 56                    .background(RoundedRectangle(cornerRadius: 32).fill(DayByDay.Category.animals.color))
 57            }
 58        }
 59        .padding(32)
 60        try png(drawn).write(to: dir.appendingPathComponent("animals-large.png"))
 61    }
 62
 63    /// Every mood's still pose at two sizes, then frames from its motion.
 64    @Test func mascotPoses() throws {
 65        try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
 66        let frames: [(MascotMood, Double)] = [(.idle, 3.75), (.asking, 0.11), (.cheering, 0.2), (.waving, 0.175), (.waving, 0.525)]
 67        for scheme in [ColorScheme.light, .dark] {
 68            let sheet = VStack(alignment: .leading, spacing: 24) {
 69                HStack(spacing: 16) {
 70                    ForEach(MascotMood.allCases, id: \.self) { OwlCanvas(mood: $0, pose: MascotMotion.still($0)).frame(width: 180, height: 180) }
 71                }
 72                HStack(spacing: 16) {
 73                    ForEach(MascotMood.allCases, id: \.self) { OwlCanvas(mood: $0, pose: MascotMotion.still($0)).frame(width: 64, height: 64) }
 74                }
 75                HStack(spacing: 16) {
 76                    ForEach(Array(frames.enumerated()), id: \.offset) { _, f in
 77                        OwlCanvas(mood: f.0, pose: MascotMotion.pose(f.0, at: f.1)).frame(width: 180, height: 180)
 78                    }
 79                }
 80            }
 81            .padding(32)
 82            .background(Color(.systemBackground))
 83            .environment(\.colorScheme, scheme)
 84            try png(sheet).write(to: dir.appendingPathComponent("mascot-\(scheme).png"))
 85        }
 86    }
 87
 88    @Test func games() async throws {
 89        try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
 90        let container = ProfileStore.makeContainer(inMemory: true)
 91        let session = ProfileSession(store: ProfileStore(context: container.mainContext))
 92        if let maya = try? session.store.create(name: "Maya", avatar: .cat, color: .pink, birthday: (month: 10, day: 30)) {
 93            session.store.setPicture(.swim, on: .friday, for: maya)
 94            session.store.setPicture(.school, on: .monday, for: maya)
 95            for (d, w) in [(1, LearnWeather.sunny), (2, .cloudy), (5, .rainy), (9, .windy), (12, .snowy), (15, .sunny)] {
 96                session.store.addSticker(for: maya, on: DateComponents(year: 2026, month: 10, day: d), weather: w)
 97            }
 98            let days = DayByDay.Category.days.quizItems, months = DayByDay.Category.months.quizItems
 99            let t = Date(timeIntervalSince1970: 1_800_000_000)
100            for (i, day) in days.enumerated() {
101                session.store.record(day, correct: true, for: maya, at: t + Double(i) * 300)
102                session.store.record(day, correct: true, for: maya, at: t + 5000 + Double(i) * 300)
103            }
104            for (i, month) in months.enumerated() where i < 5 {
105                session.store.record(month, correct: true, for: maya, at: t + Double(i) * 300)
106                session.store.record(month, correct: true, for: maya, at: t + 5000 + Double(i) * 300)
107            }
108            for month in months[5...7] { session.store.record(month, correct: false, for: maya, at: t + 9000) }
109            session.store.record(DayByDay.Category.alphabet.quizItems[1], correct: false, for: maya, at: t)
110            session.profilesChanged()
111        }
112        var rng = SeededGenerator(seed: 1)
113        var train = SequencePuzzle.weekTrain(using: &rng)
114        for d in [DayOfWeek.sunday, .monday, .tuesday] { _ = train.place(DayByDay.Category.days.item(d)) }
115        var slots = SequencePuzzle.yesterdayTomorrow(today: .friday, using: &rng)
116        _ = slots.place(DayByDay.Category.days.item(DayOfWeek.thursday))
117        let screens: [(String, AnyView)] = [
118            ("train-start", AnyView(SequencePuzzleView(game: .weekTrain) { .weekTrain(using: &rng) })),
119            ("train", AnyView(SequencePuzzleView(game: .weekTrain) { train })),
120            ("slots", AnyView(SequencePuzzleView(game: .yesterdayTomorrow) { slots })),
121            ("wheel", AnyView(YearWheelView())),
122            ("mix", AnyView(RoundView(source: MixColors(), game: .mixColors) { ChoiceTile(item: $0) })),
123            ("trace-shape", AnyView(TraceView(category: .shapes))),
124            ("trace-letter", AnyView(TraceView(category: .alphabet))),
125            ("dress", AnyView(RoundView(source: DressUp(), game: .dressUp) { ClothingTile(item: $0) })),
126            ("sort", AnyView(SortView())),
127            ("moves", AnyView(MovesView())),
128            ("weather", AnyView(WeatherView())),
129            ("rain", AnyView(RainOverlay(isActive: true).background(Color(.systemBackground)))),
130            ("days", AnyView(DaysOfWeekView())),
131            ("routine", AnyView(TodayRoutineView())),
132            ("calendar", AnyView(StickerCalendarView(profile: session.current, now: DateComponents(calendar: .current, year: 2026, month: 10, day: 16).date!))),
133            ("banner", AnyView(TodayBanner().padding())),
134            ("picker", AnyView(ProfilePickerView())),
135            ("parent-progress", AnyView(NavigationStack { ChildProgressView(profile: session.profiles[0]) })),
136            ("welcome", AnyView(ProfileSetupView())),
137            ("finished", AnyView(FinishedView {})),
138            ("find-days", AnyView(RoundView(source: DayByDay.Category.days.questionSource(for: .findIt), game: .findIt) { ChoiceTile(item: $0) })),
139            ("animals", AnyView(AnimalsView())),
140            ("alphabet", AnyView(AlphabetView())),
141            ("counting", AnyView(CountingView())),
142            ("piles", AnyView(HStack(spacing: 20) {
143                ForEach([3, 7, 10], id: \.self) { n in
144                    PileTile(item: DayByDay.Category.numbers.item(LearnNumber(rawValue: n)!)).frame(width: 170, height: 160)
145                }
146            })),
147        ]
148        for (name, view) in screens {
149            for scheme in [ColorScheme.light, .dark] {
150                let page = view
151                    .background(Color(.systemBackground))
152                    .environment(session)
153                    .environment(\.colorScheme, scheme)
154                try await windowPNG(page).write(to: dir.appendingPathComponent("game-\(name)-\(scheme).png"))
155            }
156        }
157    }
158
159    /// Renders through a real window, which draws scroll views (ImageRenderer does not).
160    private func windowPNG(_ view: some View, size: CGSize = CGSize(width: 402, height: 874)) async throws -> Data {
161        let scene = try #require(UIApplication.shared.connectedScenes.first as? UIWindowScene)
162        let window = UIWindow(windowScene: scene)
163        window.frame = CGRect(origin: .zero, size: size)
164        window.rootViewController = UIHostingController(rootView: view)
165        window.makeKeyAndVisible()
166        try await Task.sleep(for: .milliseconds(600))
167        let image = UIGraphicsImageRenderer(size: size).image { _ in
168            window.drawHierarchy(in: window.bounds, afterScreenUpdates: true)
169        }
170        window.isHidden = true
171        return try #require(image.pngData())
172    }
173
174    private func png(_ view: some View) throws -> Data {
175        let renderer = ImageRenderer(content: view)
176        renderer.scale = 2
177        return try #require(renderer.uiImage?.pngData())
178    }
179
180    /// 16-bit mono PCM.
181    private func wav(_ samples: [Float]) -> Data {
182        let rate = UInt32(SoundSynth.sampleRate)
183        var data = Data()
184        func append<T: FixedWidthInteger>(_ v: T) { withUnsafeBytes(of: v.littleEndian) { data.append(contentsOf: $0) } }
185        let bytes = UInt32(samples.count * 2)
186        data.append(contentsOf: Array("RIFF".utf8)); append(36 + bytes)
187        data.append(contentsOf: Array("WAVEfmt ".utf8)); append(UInt32(16)); append(UInt16(1)); append(UInt16(1))
188        append(rate); append(rate * 2); append(UInt16(2)); append(UInt16(16))
189        data.append(contentsOf: Array("data".utf8)); append(bytes)
190        for s in samples { append(Int16(max(-1, min(1, s)) * Float(Int16.max))) }
191        return data
192    }
193}