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/

Commit f3ddc9ab3a

f3ddc9ab3ae0546aa490e3a40ffbe37123912f68

parent: a6bf527c92

Unsigned

cmc <hello@cleberg.net> · 2026-10-16 20:42 UTC

Part 1: foundation (!3)

Profiles with parent gate, on-device answer log (SwiftData), synthesized sound effects, celebration overlay, question engine with 5-question rounds, home Today banner with per-topic hubs, unit test target (45 tests).

Art/sound review: two rounds, all blocking items fixed (contrast >= 3:1 on all tiles, banner, avatars, Play again; no clicks when effects overlap). Advisory items left for later parts: roundComplete arpeggio quieter than its chord, effects overlap speech start, confetti pattern repeats, cheering mascot barely differs from idle, 11 tiles leave an orphan slot, Get Started button uses the 2.3:1 accent orange, existing Day/Month/Season cards still use lightening gradients.

Closes #1

Layout: unified · split

DayByDay.xcodeproj/project.pbxproj +142 −2
@@ -24,8 +24,19 @@
24 8B57F7382F63BBBB001F6F5E /* AnimalsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8B57F7372F63BBBB001F6F5E /* AnimalsView.swift */; }; 24 8B57F7382F63BBBB001F6F5E /* AnimalsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8B57F7372F63BBBB001F6F5E /* AnimalsView.swift */; };
25 8B57F73A2F63BBBD001F6F5E /* LetterCard.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8B57F7392F63BBBD001F6F5E /* LetterCard.swift */; }; 25 8B57F73A2F63BBBD001F6F5E /* LetterCard.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8B57F7392F63BBBD001F6F5E /* LetterCard.swift */; };
26 8B57F73C2F63BBBD001F6F5E /* AlphabetView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8B57F73B2F63BBBD001F6F5E /* AlphabetView.swift */; }; 26 8B57F73C2F63BBBD001F6F5E /* AlphabetView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8B57F73B2F63BBBD001F6F5E /* AlphabetView.swift */; };
27 D7D48193BA7AD2C64B212737 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = BA83A180D07BFACBA92AC03E /* Foundation.framework */; };
27/* End PBXBuildFile section */ 28/* End PBXBuildFile section */
28 29
30/* Begin PBXContainerItemProxy section */
31 1015CD2FFBC39F380BE3151E /* PBXContainerItemProxy */ = {
32 isa = PBXContainerItemProxy;
33 containerPortal = 8B7051AA2F5F908800491D58 /* Project object */;
34 proxyType = 1;
35 remoteGlobalIDString = 8B7051B12F5F908800491D58;
36 remoteInfo = DayByDay;
37 };
38/* End PBXContainerItemProxy section */
39
29/* Begin PBXFileReference section */ 40/* Begin PBXFileReference section */
30 8B1B4FF82F659AD1005C246F /* WeatherCard.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WeatherCard.swift; sourceTree = "<group>"; }; 41 8B1B4FF82F659AD1005C246F /* WeatherCard.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WeatherCard.swift; sourceTree = "<group>"; };
31 8B1B4FFA2F659AD1005C246F /* WeatherView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WeatherView.swift; sourceTree = "<group>"; }; 42 8B1B4FFA2F659AD1005C246F /* WeatherView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WeatherView.swift; sourceTree = "<group>"; };
@@ -45,6 +56,8 @@
45 8B57F7392F63BBBD001F6F5E /* LetterCard.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LetterCard.swift; sourceTree = "<group>"; }; 56 8B57F7392F63BBBD001F6F5E /* LetterCard.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LetterCard.swift; sourceTree = "<group>"; };
46 8B57F73B2F63BBBD001F6F5E /* AlphabetView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AlphabetView.swift; sourceTree = "<group>"; }; 57 8B57F73B2F63BBBD001F6F5E /* AlphabetView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AlphabetView.swift; sourceTree = "<group>"; };
47 8B7051B22F5F908800491D58 /* DayByDay.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = DayByDay.app; sourceTree = BUILT_PRODUCTS_DIR; }; 58 8B7051B22F5F908800491D58 /* DayByDay.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = DayByDay.app; sourceTree = BUILT_PRODUCTS_DIR; };
59 B6E74F699AA6EB7ADABD5F88 /* DayByDayTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = DayByDayTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
60 BA83A180D07BFACBA92AC03E /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS26.0.sdk/System/Library/Frameworks/Foundation.framework; sourceTree = DEVELOPER_DIR; };
48/* End PBXFileReference section */ 61/* End PBXFileReference section */
49 62
50/* Begin PBXFileSystemSynchronizedBuildFileExceptionSet section */ 63/* Begin PBXFileSystemSynchronizedBuildFileExceptionSet section */
@@ -58,6 +71,13 @@
58/* End PBXFileSystemSynchronizedBuildFileExceptionSet section */ 71/* End PBXFileSystemSynchronizedBuildFileExceptionSet section */
59 72
60/* Begin PBXFileSystemSynchronizedRootGroup section */ 73/* Begin PBXFileSystemSynchronizedRootGroup section */
74 4FDEBF44C97D137EF31F348A /* DayByDayTests */ = {
75 isa = PBXFileSystemSynchronizedRootGroup;
76 exceptions = (
77 );
78 path = DayByDayTests;
79 sourceTree = "<group>";
80 };
61 8B7051B42F5F908800491D58 /* DayByDay */ = { 81 8B7051B42F5F908800491D58 /* DayByDay */ = {
62 isa = PBXFileSystemSynchronizedRootGroup; 82 isa = PBXFileSystemSynchronizedRootGroup;
63 exceptions = ( 83 exceptions = (
@@ -76,9 +96,33 @@
76 ); 96 );
77 runOnlyForDeploymentPostprocessing = 0; 97 runOnlyForDeploymentPostprocessing = 0;
78 }; 98 };
99 B884B3379F811EC0ED47EBAC /* Frameworks */ = {
100 isa = PBXFrameworksBuildPhase;
101 buildActionMask = 2147483647;
102 files = (
103 D7D48193BA7AD2C64B212737 /* Foundation.framework in Frameworks */,
104 );
105 runOnlyForDeploymentPostprocessing = 0;
106 };
79/* End PBXFrameworksBuildPhase section */ 107/* End PBXFrameworksBuildPhase section */
80 108
81/* Begin PBXGroup section */ 109/* Begin PBXGroup section */
110 2D9AF70FED70833131ADAE0F /* iOS */ = {
111 isa = PBXGroup;
112 children = (
113 BA83A180D07BFACBA92AC03E /* Foundation.framework */,
114 );
115 name = iOS;
116 sourceTree = "<group>";
117 };
118 43AAA6C6355BFA1D8A629985 /* Frameworks */ = {
119 isa = PBXGroup;
120 children = (
121 2D9AF70FED70833131ADAE0F /* iOS */,
122 );
123 name = Frameworks;
124 sourceTree = "<group>";
125 };
82 8B7051A92F5F908800491D58 = { 126 8B7051A92F5F908800491D58 = {
83 isa = PBXGroup; 127 isa = PBXGroup;
84 children = ( 128 children = (
@@ -101,6 +145,8 @@
101 8B1B4FFE2F659AD2005C246F /* BodyPartsView.swift */, 145 8B1B4FFE2F659AD2005C246F /* BodyPartsView.swift */,
102 8B1B50002F659AD3005C246F /* FoodCard.swift */, 146 8B1B50002F659AD3005C246F /* FoodCard.swift */,
103 8B1B50022F659AD4005C246F /* FoodView.swift */, 147 8B1B50022F659AD4005C246F /* FoodView.swift */,
148 43AAA6C6355BFA1D8A629985 /* Frameworks */,
149 4FDEBF44C97D137EF31F348A /* DayByDayTests */,
104 ); 150 );
105 sourceTree = "<group>"; 151 sourceTree = "<group>";
106 }; 152 };
@@ -108,6 +154,7 @@
108 isa = PBXGroup; 154 isa = PBXGroup;
109 children = ( 155 children = (
110 8B7051B22F5F908800491D58 /* DayByDay.app */, 156 8B7051B22F5F908800491D58 /* DayByDay.app */,
157 B6E74F699AA6EB7ADABD5F88 /* DayByDayTests.xctest */,
111 ); 158 );
112 name = Products; 159 name = Products;
113 sourceTree = "<group>"; 160 sourceTree = "<group>";
@@ -115,6 +162,27 @@
115/* End PBXGroup section */ 162/* End PBXGroup section */
116 163
117/* Begin PBXNativeTarget section */ 164/* Begin PBXNativeTarget section */
165 62BDB36DEC1B9FC5E49D7819 /* DayByDayTests */ = {
166 isa = PBXNativeTarget;
167 buildConfigurationList = F99EE566298541D2131D7F82 /* Build configuration list for PBXNativeTarget "DayByDayTests" */;
168 buildPhases = (
169 36E9E05F598E19E3FD6C9FC2 /* Sources */,
170 B884B3379F811EC0ED47EBAC /* Frameworks */,
171 91240F12F11E2ED4F3B375A9 /* Resources */,
172 );
173 buildRules = (
174 );
175 dependencies = (
176 27E52B724540ED82493D45D6 /* PBXTargetDependency */,
177 );
178 fileSystemSynchronizedGroups = (
179 4FDEBF44C97D137EF31F348A /* DayByDayTests */,
180 );
181 name = DayByDayTests;
182 productName = DayByDayTests;
183 productReference = B6E74F699AA6EB7ADABD5F88 /* DayByDayTests.xctest */;
184 productType = "com.apple.product-type.bundle.unit-test";
185 };
118 8B7051B12F5F908800491D58 /* DayByDay */ = { 186 8B7051B12F5F908800491D58 /* DayByDay */ = {
119 isa = PBXNativeTarget; 187 isa = PBXNativeTarget;
120 buildConfigurationList = 8B7051BD2F5F908900491D58 /* Build configuration list for PBXNativeTarget "DayByDay" */; 188 buildConfigurationList = 8B7051BD2F5F908900491D58 /* Build configuration list for PBXNativeTarget "DayByDay" */;
@@ -131,8 +199,6 @@
131 8B7051B42F5F908800491D58 /* DayByDay */, 199 8B7051B42F5F908800491D58 /* DayByDay */,
132 ); 200 );
133 name = DayByDay; 201 name = DayByDay;
134 packageProductDependencies = (
135 );
136 productName = DayByDay; 202 productName = DayByDay;
137 productReference = 8B7051B22F5F908800491D58 /* DayByDay.app */; 203 productReference = 8B7051B22F5F908800491D58 /* DayByDay.app */;
138 productType = "com.apple.product-type.application"; 204 productType = "com.apple.product-type.application";
@@ -167,6 +233,7 @@
167 projectRoot = ""; 233 projectRoot = "";
168 targets = ( 234 targets = (
169 8B7051B12F5F908800491D58 /* DayByDay */, 235 8B7051B12F5F908800491D58 /* DayByDay */,
236 62BDB36DEC1B9FC5E49D7819 /* DayByDayTests */,
170 ); 237 );
171 }; 238 };
172/* End PBXProject section */ 239/* End PBXProject section */
@@ -179,9 +246,23 @@
179 ); 246 );
180 runOnlyForDeploymentPostprocessing = 0; 247 runOnlyForDeploymentPostprocessing = 0;
181 }; 248 };
249 91240F12F11E2ED4F3B375A9 /* Resources */ = {
250 isa = PBXResourcesBuildPhase;
251 buildActionMask = 2147483647;
252 files = (
253 );
254 runOnlyForDeploymentPostprocessing = 0;
255 };
182/* End PBXResourcesBuildPhase section */ 256/* End PBXResourcesBuildPhase section */
183 257
184/* Begin PBXSourcesBuildPhase section */ 258/* Begin PBXSourcesBuildPhase section */
259 36E9E05F598E19E3FD6C9FC2 /* Sources */ = {
260 isa = PBXSourcesBuildPhase;
261 buildActionMask = 2147483647;
262 files = (
263 );
264 runOnlyForDeploymentPostprocessing = 0;
265 };
185 8B7051AE2F5F908800491D58 /* Sources */ = { 266 8B7051AE2F5F908800491D58 /* Sources */ = {
186 isa = PBXSourcesBuildPhase; 267 isa = PBXSourcesBuildPhase;
187 buildActionMask = 2147483647; 268 buildActionMask = 2147483647;
@@ -208,7 +289,37 @@
208 }; 289 };
209/* End PBXSourcesBuildPhase section */ 290/* End PBXSourcesBuildPhase section */
210 291
292/* Begin PBXTargetDependency section */
293 27E52B724540ED82493D45D6 /* PBXTargetDependency */ = {
294 isa = PBXTargetDependency;
295 name = DayByDay;
296 target = 8B7051B12F5F908800491D58 /* DayByDay */;
297 targetProxy = 1015CD2FFBC39F380BE3151E /* PBXContainerItemProxy */;
298 };
299/* End PBXTargetDependency section */
300
211/* Begin XCBuildConfiguration section */ 301/* Begin XCBuildConfiguration section */
302 76F72CE42B474B4C420CFF4F /* Release */ = {
303 isa = XCBuildConfiguration;
304 buildSettings = {
305 BUNDLE_LOADER = "$(TEST_HOST)";
306 CLANG_ENABLE_OBJC_WEAK = NO;
307 CODE_SIGN_STYLE = Automatic;
308 DEVELOPMENT_TEAM = ZCNAX3VL9D;
309 GENERATE_INFOPLIST_FILE = YES;
310 IPHONEOS_DEPLOYMENT_TARGET = 17.5;
311 PRODUCT_BUNDLE_IDENTIFIER = net.cleberg.DayByDay.tests;
312 PRODUCT_NAME = "$(TARGET_NAME)";
313 SDKROOT = iphoneos;
314 SWIFT_APPROACHABLE_CONCURRENCY = YES;
315 SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor;
316 SWIFT_VERSION = 5.0;
317 TARGETED_DEVICE_FAMILY = "1,2";
318 TEST_HOST = "$(BUILT_PRODUCTS_DIR)/DayByDay.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/DayByDay";
319 VALIDATE_PRODUCT = YES;
320 };
321 name = Release;
322 };
212 8B7051BB2F5F908900491D58 /* Debug */ = { 323 8B7051BB2F5F908900491D58 /* Debug */ = {
213 isa = XCBuildConfiguration; 324 isa = XCBuildConfiguration;
214 buildSettings = { 325 buildSettings = {
@@ -400,6 +511,26 @@
400 }; 511 };
401 name = Release; 512 name = Release;
402 }; 513 };
514 8FA15E507003B7CC52053A3C /* Debug */ = {
515 isa = XCBuildConfiguration;
516 buildSettings = {
517 BUNDLE_LOADER = "$(TEST_HOST)";
518 CLANG_ENABLE_OBJC_WEAK = NO;
519 CODE_SIGN_STYLE = Automatic;
520 DEVELOPMENT_TEAM = ZCNAX3VL9D;
521 GENERATE_INFOPLIST_FILE = YES;
522 IPHONEOS_DEPLOYMENT_TARGET = 17.5;
523 PRODUCT_BUNDLE_IDENTIFIER = net.cleberg.DayByDay.tests;
524 PRODUCT_NAME = "$(TARGET_NAME)";
525 SDKROOT = iphoneos;
526 SWIFT_APPROACHABLE_CONCURRENCY = YES;
527 SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor;
528 SWIFT_VERSION = 5.0;
529 TARGETED_DEVICE_FAMILY = "1,2";
530 TEST_HOST = "$(BUILT_PRODUCTS_DIR)/DayByDay.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/DayByDay";
531 };
532 name = Debug;
533 };
403/* End XCBuildConfiguration section */ 534/* End XCBuildConfiguration section */
404 535
405/* Begin XCConfigurationList section */ 536/* Begin XCConfigurationList section */
@@ -421,6 +552,15 @@
421 defaultConfigurationIsVisible = 0; 552 defaultConfigurationIsVisible = 0;
422 defaultConfigurationName = Release; 553 defaultConfigurationName = Release;
423 }; 554 };
555 F99EE566298541D2131D7F82 /* Build configuration list for PBXNativeTarget "DayByDayTests" */ = {
556 isa = XCConfigurationList;
557 buildConfigurations = (
558 76F72CE42B474B4C420CFF4F /* Release */,
559 8FA15E507003B7CC52053A3C /* Debug */,
560 );
561 defaultConfigurationIsVisible = 0;
562 defaultConfigurationName = Release;
563 };
424/* End XCConfigurationList section */ 564/* End XCConfigurationList section */
425 }; 565 };
426 rootObject = 8B7051AA2F5F908800491D58 /* Project object */; 566 rootObject = 8B7051AA2F5F908800491D58 /* Project object */;
DayByDay.xcodeproj/xcshareddata/xcschemes/DayByDay.xcscheme added +83
@@ -0,0 +1,83 @@
1<?xml version="1.0" encoding="UTF-8"?>
2<Scheme
3 LastUpgradeVersion = "1600"
4 version = "1.3">
5 <BuildAction
6 parallelizeBuildables = "YES"
7 buildImplicitDependencies = "YES">
8 <BuildActionEntries>
9 <BuildActionEntry
10 buildForTesting = "YES"
11 buildForRunning = "YES"
12 buildForProfiling = "YES"
13 buildForArchiving = "YES"
14 buildForAnalyzing = "YES">
15 <BuildableReference
16 BuildableIdentifier = "primary"
17 BlueprintIdentifier = "8B7051B12F5F908800491D58"
18 BuildableName = "DayByDay.app"
19 BlueprintName = "DayByDay"
20 ReferencedContainer = "container:DayByDay.xcodeproj">
21 </BuildableReference>
22 </BuildActionEntry>
23 <BuildActionEntry
24 buildForTesting = "YES"
25 buildForRunning = "NO"
26 buildForProfiling = "NO"
27 buildForArchiving = "NO"
28 buildForAnalyzing = "NO">
29 <BuildableReference
30 BuildableIdentifier = "primary"
31 BlueprintIdentifier = "62BDB36DEC1B9FC5E49D7819"
32 BuildableName = "DayByDayTests.xctest"
33 BlueprintName = "DayByDayTests"
34 ReferencedContainer = "container:DayByDay.xcodeproj">
35 </BuildableReference>
36 </BuildActionEntry>
37 </BuildActionEntries>
38 </BuildAction>
39 <TestAction
40 buildConfiguration = "Debug"
41 selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
42 selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
43 shouldUseLaunchSchemeArgsEnv = "YES"
44 codeCoverageEnabled = "NO">
45 <Testables>
46 <TestableReference
47 skipped = "NO">
48 <BuildableReference
49 BuildableIdentifier = "primary"
50 BlueprintIdentifier = "62BDB36DEC1B9FC5E49D7819"
51 BuildableName = "DayByDayTests.xctest"
52 BlueprintName = "DayByDayTests"
53 ReferencedContainer = "container:DayByDay.xcodeproj">
54 </BuildableReference>
55 </TestableReference>
56 </Testables>
57 </TestAction>
58 <LaunchAction
59 buildConfiguration = "Debug"
60 selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
61 selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
62 launchStyle = "0"
63 useCustomWorkingDirectory = "NO"
64 ignoresPersistentStateOnLaunch = "NO"
65 debugDocumentVersioning = "YES"
66 debugServiceExtension = "internal"
67 allowLocationSimulation = "YES">
68 </LaunchAction>
69 <ProfileAction
70 buildConfiguration = "Release"
71 shouldUseLaunchSchemeArgsEnv = "YES"
72 savedToolIdentifier = ""
73 useCustomWorkingDirectory = "NO"
74 debugDocumentVersioning = "YES">
75 </ProfileAction>
76 <AnalyzeAction
77 buildConfiguration = "Debug">
78 </AnalyzeAction>
79 <ArchiveAction
80 buildConfiguration = "Release"
81 revealArchiveInOrganizer = "YES">
82 </ArchiveAction>
83</Scheme>
DayByDay/ContentView.swift +33 −75
@@ -5,6 +5,7 @@
5// Created by cmc on 2026-03-09. 5// Created by cmc on 2026-03-09.
6// 6//
7 7
8import SwiftData
8import SwiftUI 9import SwiftUI
9 10
10// MARK: - Category model 11// MARK: - Category model
@@ -49,20 +50,21 @@ enum Category: Int, CaseIterable, Identifiable {
49 } 50 }
50 } 51 }
51 52
53 /// Fixed colors with at least 3:1 contrast against white labels in light and dark mode.
52 var color: Color { 54 var color: Color {
53 switch self { 55 switch self {
54 case .today: .orange 56 case .today: Color(red: 0.84, green: 0.40, blue: 0.08)
55 case .days: .blue 57 case .days: Color(red: 0.0, green: 0.42, blue: 0.85)
56 case .months: .purple 58 case .months: Color(red: 0.62, green: 0.22, blue: 0.78)
57 case .seasons: .green 59 case .seasons: Color(red: 0.18, green: 0.56, blue: 0.28)
58 case .numbers: .red 60 case .numbers: Color(red: 0.86, green: 0.20, blue: 0.22)
59 case .colors: .pink 61 case .colors: Color(red: 0.82, green: 0.25, blue: 0.52)
60 case .shapes: .teal 62 case .shapes: Color(red: 0.0, green: 0.53, blue: 0.56)
61 case .animals: Color(red: 0.7, green: 0.45, blue: 0.2) 63 case .animals: Color(red: 0.63, green: 0.40, blue: 0.18)
62 case .alphabet: .indigo 64 case .alphabet: Color(red: 0.35, green: 0.34, blue: 0.84)
63 case .weather: Color(red: 0.4, green: 0.75, blue: 0.95) 65 case .weather: Color(red: 0.10, green: 0.48, blue: 0.78)
64 case .bodyParts: Color(red: 0.9, green: 0.5, blue: 0.6) 66 case .bodyParts: Color(red: 0.80, green: 0.30, blue: 0.46)
65 case .food: Color(red: 0.95, green: 0.6, blue: 0.2) 67 case .food: Color(red: 0.80, green: 0.42, blue: 0.08)
66 } 68 }
67 } 69 }
68 70
@@ -91,7 +93,7 @@ struct CategoryTile: View {
91 .shadow(color: category.color.opacity(0.4), radius: 8, y: 4) 93 .shadow(color: category.color.opacity(0.4), radius: 8, y: 4)
92 } else { 94 } else {
93 RoundedRectangle(cornerRadius: 32, style: .continuous) 95 RoundedRectangle(cornerRadius: 32, style: .continuous)
94 .fill(category.color.gradient) 96 .fill(category.color)
95 .shadow(color: category.color.opacity(0.4), radius: 8, y: 4) 97 .shadow(color: category.color.opacity(0.4), radius: 8, y: 4)
96 } 98 }
97 99
@@ -105,6 +107,7 @@ struct CategoryTile: View {
105 .font(.system(size: 24, weight: .bold, design: .rounded)) 107 .font(.system(size: 24, weight: .bold, design: .rounded))
106 .foregroundStyle(.white) 108 .foregroundStyle(.white)
107 } 109 }
110 .shadow(color: category.usesGradientBackground ? .black.opacity(0.6) : .clear, radius: 2)
108 } 111 }
109 .accessibilityLabel(category.label) 112 .accessibilityLabel(category.label)
110 } 113 }
@@ -112,73 +115,25 @@ struct CategoryTile: View {
112 115
113// MARK: - Content view 116// MARK: - Content view
114 117
118/// Routes between first-launch setup, the profile picker, and home.
115struct ContentView: View { 119struct ContentView: View {
116 @AppStorage("hasSeenVoiceTip") private var hasSeenVoiceTip = false 120 @Environment(ProfileSession.self) private var session
117 121 @Environment(\.scenePhase) private var scenePhase
118 private let columns = [
119 GridItem(.flexible(), spacing: 24),
120 GridItem(.flexible(), spacing: 24)
121 ]
122 122
123 var body: some View { 123 var body: some View {
124 NavigationStack { 124 Group {
125 ScrollView { 125 switch session.screen {
126 LazyVGrid(columns: columns, spacing: 24) { 126 case .setup: ProfileSetupView()
127 ForEach(Category.allCases) { category in 127 case .picker: ProfilePickerView()
128 NavigationLink(value: category) { 128 case .home: HomeView()
129 CategoryTile(category: category)
130 .aspectRatio(1, contentMode: .fit)
131 }
132 .buttonStyle(.plain)
133 }
134 }
135 .padding(24)
136
137 Button {
138 hasSeenVoiceTip = false
139 } label: {
140 Label("Voice Quality Tips", systemImage: "speaker.wave.2.fill")
141 .font(.system(size: 16, weight: .medium, design: .rounded))
142 .foregroundStyle(.secondary)
143 .frame(maxWidth: .infinity)
144 .padding(.vertical, 14)
145 .background(Color(.systemGray6))
146 .cornerRadius(16)
147 }
148 .buttonStyle(.plain)
149 .padding(.horizontal, 24)
150 .padding(.bottom, 24)
151 }
152 .navigationTitle("DayByDay")
153 .navigationDestination(for: Category.self) { category in
154 destinationView(for: category)
155 .navigationTitle(category.label)
156 }
157 .overlay {
158 if !hasSeenVoiceTip {
159 VoiceTipOverlay {
160 withAnimation { hasSeenVoiceTip = true }
161 }
162 }
163 } 129 }
164 } 130 }
165 } 131 .onChange(of: scenePhase) { _, phase in
166 132 switch phase {
167 @ViewBuilder 133 case .background: session.didEnterBackground(at: .now)
168 private func destinationView(for category: Category) -> some View { 134 case .active: session.willEnterForeground(at: .now)
169 switch category { 135 default: break
170 case .today: TodayView() 136 }
171 case .days: DaysOfWeekView()
172 case .months: MonthsOfYearView()
173 case .seasons: SeasonsView()
174 case .numbers: NumbersView()
175 case .colors: ColorsView()
176 case .shapes: ShapesView()
177 case .animals: AnimalsView()
178 case .alphabet: AlphabetView()
179 case .weather: WeatherView()
180 case .bodyParts: BodyPartsView()
181 case .food: FoodView()
182 } 137 }
183 } 138 }
184} 139}
@@ -224,5 +179,8 @@ struct VoiceTipOverlay: View {
224} 179}
225 180
226#Preview { 181#Preview {
182 let container = ProfileStore.makeContainer(inMemory: true)
227 ContentView() 183 ContentView()
184 .environment(ProfileSession(store: ProfileStore(context: container.mainContext)))
185 .modelContainer(container)
228} 186}
DayByDay/DayByDayApp.swift +8
@@ -6,11 +6,17 @@
6// 6//
7 7
8import AVFoundation 8import AVFoundation
9import SwiftData
9import SwiftUI 10import SwiftUI
10 11
11@main 12@main
12struct DayByDayApp: App { 13struct DayByDayApp: App {
14 private let container = ProfileStore.makeContainer(inMemory: false)
15 @State private var session: ProfileSession
16
13 init() { 17 init() {
18 _session = State(initialValue: ProfileSession(store: ProfileStore(context: container.mainContext)))
19
14 Task.detached(priority: .background) { 20 Task.detached(priority: .background) {
15 // Activate the audio session early so the first real tap doesn't block. 21 // Activate the audio session early so the first real tap doesn't block.
16 try? AVAudioSession.sharedInstance().setCategory(.playback, mode: .default) 22 try? AVAudioSession.sharedInstance().setCategory(.playback, mode: .default)
@@ -29,6 +35,8 @@ struct DayByDayApp: App {
29 var body: some Scene { 35 var body: some Scene {
30 WindowGroup { 36 WindowGroup {
31 ContentView() 37 ContentView()
38 .environment(session)
39 .modelContainer(container)
32 } 40 }
33 } 41 }
34} 42}
DayByDay/Home/CategoryHubView.swift added +65
@@ -0,0 +1,65 @@
1//
2// CategoryHubView.swift
3// DayByDay
4//
5
6import SwiftUI
7
8/// What a child can do with one topic. Same layout for every topic.
9struct CategoryHubView: View {
10 let category: Category
11
12 var body: some View {
13 ScrollView {
14 VStack(spacing: 24) {
15 activity("Look and listen", systemImage: "eye.fill", color: category.color) {
16 category.lookAndListenView
17 .navigationTitle(category.label)
18 }
19 }
20 .padding(32)
21 .frame(maxWidth: 640)
22 .frame(maxWidth: .infinity)
23 }
24 }
25
26 private func activity(_ title: String, systemImage: String, color: Color,
27 @ViewBuilder destination: @escaping () -> some View) -> some View {
28 NavigationLink(destination: destination) {
29 HStack(spacing: 20) {
30 Image(systemName: systemImage)
31 .font(.system(size: 44))
32 Text(title)
33 .font(.system(size: 32, weight: .bold, design: .rounded))
34 Spacer(minLength: 0)
35 }
36 .foregroundStyle(.white)
37 .padding(.horizontal, 32)
38 .frame(height: 120)
39 .background(RoundedRectangle(cornerRadius: 32, style: .continuous).fill(color))
40 }
41 .buttonStyle(.plain)
42 .simultaneousGesture(TapGesture().onEnded { SpeechSynthesizer.shared.speak(title) })
43 }
44}
45
46extension Category {
47 /// The existing card grid for this topic.
48 @ViewBuilder
49 var lookAndListenView: some View {
50 switch self {
51 case .today: TodayView()
52 case .days: DaysOfWeekView()
53 case .months: MonthsOfYearView()
54 case .seasons: SeasonsView()
55 case .numbers: NumbersView()
56 case .colors: ColorsView()
57 case .shapes: ShapesView()
58 case .animals: AnimalsView()
59 case .alphabet: AlphabetView()
60 case .weather: WeatherView()
61 case .bodyParts: BodyPartsView()
62 case .food: FoodView()
63 }
64 }
65}
DayByDay/Home/HomeView.swift added +94
@@ -0,0 +1,94 @@
1//
2// HomeView.swift
3// DayByDay
4//
5
6import SwiftUI
7
8/// Today banner on top, then the topic grid.
9struct HomeView: View {
10 @Environment(ProfileSession.self) private var session
11 @AppStorage("hasSeenVoiceTip") private var hasSeenVoiceTip = false
12 @State private var showingParentArea = false
13
14 private let columns = [
15 GridItem(.flexible(), spacing: 24),
16 GridItem(.flexible(), spacing: 24)
17 ]
18
19 var body: some View {
20 NavigationStack {
21 ScrollView {
22 VStack(spacing: 24) {
23 NavigationLink {
24 TodayView().navigationTitle(Category.today.label)
25 } label: {
26 TodayBanner()
27 }
28 .buttonStyle(.plain)
29
30 LazyVGrid(columns: columns, spacing: 24) {
31 ForEach(Category.gridCases) { category in
32 NavigationLink(value: category) {
33 CategoryTile(category: category)
34 .aspectRatio(1, contentMode: .fit)
35 }
36 .buttonStyle(.plain)
37 }
38 }
39
40 footerButton("Voice Quality Tips", systemImage: "speaker.wave.2.fill") {
41 hasSeenVoiceTip = false
42 }
43 footerButton("Grown-Ups", systemImage: "lock.fill") {
44 showingParentArea = true
45 }
46 }
47 .padding(24)
48 }
49 .navigationTitle("DayByDay")
50 .navigationDestination(for: Category.self) { category in
51 CategoryHubView(category: category)
52 .navigationTitle(category.label)
53 }
54 .toolbar {
55 if session.profiles.count > 1, let current = session.current {
56 ToolbarItem(placement: .topBarTrailing) {
57 Button {
58 session.current = nil
59 } label: {
60 AvatarBadge(avatar: current.avatar, color: current.color)
61 .frame(width: 40, height: 40)
62 }
63 .accessibilityLabel("Switch child")
64 }
65 }
66 }
67 .overlay {
68 if !hasSeenVoiceTip {
69 VoiceTipOverlay {
70 withAnimation { hasSeenVoiceTip = true }
71 }
72 }
73 }
74 .sheet(isPresented: $showingParentArea) {
75 GatedView(onCancel: { showingParentArea = false }) {
76 ParentAreaView(onDone: { showingParentArea = false })
77 }
78 }
79 }
80 }
81
82 private func footerButton(_ title: String, systemImage: String, action: @escaping () -> Void) -> some View {
83 Button(action: action) {
84 Label(title, systemImage: systemImage)
85 .font(.system(size: 16, weight: .medium, design: .rounded))
86 .foregroundStyle(.secondary)
87 .frame(maxWidth: .infinity)
88 .padding(.vertical, 14)
89 .background(Color(.systemGray6))
90 .cornerRadius(16)
91 }
92 .buttonStyle(.plain)
93 }
94}
DayByDay/Home/TodayBanner.swift added +36
@@ -0,0 +1,36 @@
1//
2// TodayBanner.swift
3// DayByDay
4//
5
6import SwiftUI
7
8/// The mascot and today's day and date, at the top of home.
9struct TodayBanner: View {
10 static let gradientColors: [Color] = [Color(red: 0.84, green: 0.40, blue: 0.05), Color(red: 0.80, green: 0.45, blue: 0.0)]
11
12 var body: some View {
13 HStack(spacing: 20) {
14 MascotView(mood: .idle)
15 .frame(width: 96, height: 96)
16 VStack(alignment: .leading, spacing: 6) {
17 Text("Today is \(DayOfWeek.current.name)!")
18 .font(.system(size: 30, weight: .heavy, design: .rounded))
19 Text(Date.now.formatted(.dateTime.month(.wide).day()))
20 .font(.system(size: 22, weight: .semibold, design: .rounded))
21 .opacity(0.9)
22 }
23 .foregroundStyle(.white)
24 Spacer(minLength: 0)
25 }
26 .padding(24)
27 .background(
28 RoundedRectangle(cornerRadius: 32, style: .continuous)
29 .fill(LinearGradient(colors: Self.gradientColors,
30 startPoint: .topLeading, endPoint: .bottomTrailing))
31 .shadow(color: Self.gradientColors[0].opacity(0.4), radius: 8, y: 4)
32 )
33 .accessibilityElement(children: .combine)
34 .accessibilityAddTraits(.isButton)
35 }
36}
DayByDay/Mascot/MascotView.swift added +58
@@ -0,0 +1,58 @@
1//
2// MascotView.swift
3// DayByDay
4//
5
6import SwiftUI
7
8/// Placeholder mascot: a round green face. Replaced in part 6.
9struct MascotView: View {
10 enum Mood { case idle, cheering }
11
12 let mood: Mood
13
14 init(mood: Mood) {
15 self.mood = mood
16 }
17
18 var body: some View {
19 GeometryReader { geo in
20 let s = min(geo.size.width, geo.size.height)
21 ZStack {
22 Circle().fill(Color(red: 0.35, green: 0.76, blue: 0.56).gradient)
23 HStack(spacing: s * 0.2) {
24 eye(s)
25 eye(s)
26 }
27 .offset(y: -s * 0.1)
28 smile(s)
29 .stroke(.black.opacity(0.8), style: StrokeStyle(lineWidth: s * 0.05, lineCap: .round))
30 .frame(width: s * (mood == .cheering ? 0.5 : 0.36), height: s * 0.2)
31 .offset(y: s * 0.17)
32 }
33 .frame(width: s, height: s)
34 .frame(maxWidth: .infinity, maxHeight: .infinity)
35 }
36 .aspectRatio(1, contentMode: .fit)
37 .accessibilityHidden(true)
38 }
39
40 private func eye(_ s: CGFloat) -> some View {
41 Capsule().fill(.black.opacity(0.85)).frame(width: s * 0.09, height: s * 0.14)
42 }
43
44 private func smile(_ s: CGFloat) -> Path {
45 Path { p in
46 p.move(to: CGPoint(x: 0, y: 0))
47 p.addQuadCurve(to: CGPoint(x: 1, y: 0), control: CGPoint(x: 0.5, y: 1.4))
48 }
49 .applying(CGAffineTransform(scaleX: s * (mood == .cheering ? 0.5 : 0.36), y: s * 0.2))
50 }
51}
52
53#Preview {
54 HStack {
55 MascotView(mood: .idle).frame(width: 120)
56 MascotView(mood: .cheering).frame(width: 120)
57 }
58}
DayByDay/Parent/GatedView.swift added +22
@@ -0,0 +1,22 @@
1//
2// GatedView.swift
3// DayByDay
4//
5
6import SwiftUI
7
8/// Shows the parent gate first, then `content` once it is passed.
9struct GatedView<Content: View>: View {
10 let onCancel: () -> Void
11 @ViewBuilder let content: () -> Content
12
13 @State private var passed = false
14
15 var body: some View {
16 if passed {
17 content()
18 } else {
19 ParentGateView(onPass: { passed = true }, onCancel: onCancel)
20 }
21 }
22}
DayByDay/Parent/ParentAreaView.swift added +72
@@ -0,0 +1,72 @@
1//
2// ParentAreaView.swift
3// DayByDay
4//
5
6import SwiftUI
7
8/// Grown-up screen for adding, editing, and deleting profiles.
9struct ParentAreaView: View {
10 let onDone: () -> Void
11
12 @Environment(ProfileSession.self) private var session
13 @State private var pendingDelete: Profile?
14
15 var body: some View {
16 NavigationStack {
17 List {
18 Section("Children") {
19 ForEach(session.profiles) { profile in
20 NavigationLink {
21 ProfileEditorView(profile: profile)
22 } label: {
23 ProfileRow(profile: profile)
24 }
25 .swipeActions {
26 Button("Delete", role: .destructive) { pendingDelete = profile }
27 }
28 }
29 NavigationLink {
30 ProfileEditorView(profile: nil)
31 } label: {
32 Label("Add a child", systemImage: "plus.circle.fill")
33 }
34 }
35 }
36 .navigationTitle("Grown-Ups")
37 .toolbar {
38 ToolbarItem(placement: .confirmationAction) {
39 Button("Done", action: onDone)
40 }
41 }
42 .confirmationDialog(
43 "Delete \(pendingDelete?.name ?? "")?",
44 isPresented: Binding(get: { pendingDelete != nil }, set: { if !$0 { pendingDelete = nil } }),
45 titleVisibility: .visible
46 ) {
47 Button("Delete Profile and Progress", role: .destructive) {
48 if let profile = pendingDelete {
49 session.store.delete(profile)
50 session.profilesChanged()
51 }
52 pendingDelete = nil
53 }
54 } message: {
55 Text("This removes their stickers and progress. It can't be undone.")
56 }
57 }
58 }
59}
60
61private struct ProfileRow: View {
62 let profile: Profile
63
64 var body: some View {
65 HStack(spacing: 14) {
66 AvatarBadge(avatar: profile.avatar, color: profile.color)
67 .frame(width: 44, height: 44)
68 Text(profile.name)
69 .font(.system(size: 20, weight: .semibold, design: .rounded))
70 }
71 }
72}
DayByDay/Parent/ParentGate.swift added +24
@@ -0,0 +1,24 @@
1//
2// ParentGate.swift
3// DayByDay
4//
5
6import Foundation
7
8/// A sum a 4–5 year old can't read or solve, asked before grown-up screens.
9nonisolated struct ParentGateChallenge: Equatable {
10 static let holdDuration: Double = 2
11
12 let a: Int
13 let b: Int
14
15 var answer: Int { a + b }
16
17 static func random(using rng: inout some RandomNumberGenerator) -> ParentGateChallenge {
18 ParentGateChallenge(a: Int.random(in: 6...9, using: &rng), b: Int.random(in: 6...9, using: &rng))
19 }
20
21 func accepts(_ input: String) -> Bool {
22 Int(input.trimmingCharacters(in: .whitespaces)) == answer
23 }
24}
DayByDay/Parent/ParentGateView.swift added +114
@@ -0,0 +1,114 @@
1//
2// ParentGateView.swift
3// DayByDay
4//
5
6import SwiftUI
7
8/// Press-and-hold, then a sum. Calls `onPass` when both are done.
9struct ParentGateView: View {
10 let onPass: () -> Void
11 let onCancel: () -> Void
12
13 @State private var holdProgress: CGFloat = 0
14 @State private var held = false
15 @State private var challenge = ParentGateView.newChallenge()
16 @State private var input = ""
17 @FocusState private var fieldFocused: Bool
18
19 init(onPass: @escaping () -> Void, onCancel: @escaping () -> Void) {
20 self.onPass = onPass
21 self.onCancel = onCancel
22 }
23
24 var body: some View {
25 VStack(spacing: 32) {
26 Text("For Grown-Ups")
27 .font(.system(size: 32, weight: .bold, design: .rounded))
28
29 if held {
30 sumStep
31 } else {
32 holdStep
33 }
34
35 Button("Cancel", action: onCancel)
36 .font(.system(size: 18, weight: .medium, design: .rounded))
37 .foregroundStyle(.secondary)
38 }
39 .padding(40)
40 .frame(maxWidth: 520)
41 }
42
43 private var holdStep: some View {
44 VStack(spacing: 16) {
45 ZStack {
46 Circle()
47 .stroke(Color(.systemGray5), lineWidth: 12)
48 Circle()
49 .trim(from: 0, to: holdProgress)
50 .stroke(Color.accentColor, style: StrokeStyle(lineWidth: 12, lineCap: .round))
51 .rotationEffect(.degrees(-90))
52 Image(systemName: "hand.tap.fill")
53 .font(.system(size: 44))
54 .foregroundStyle(Color.accentColor)
55 }
56 .frame(width: 140, height: 140)
57 .contentShape(Circle())
58 .onLongPressGesture(minimumDuration: ParentGateChallenge.holdDuration) {
59 held = true
60 fieldFocused = true
61 } onPressingChanged: { pressing in
62 if pressing {
63 withAnimation(.linear(duration: ParentGateChallenge.holdDuration)) { holdProgress = 1 }
64 } else if !held {
65 withAnimation(.easeOut(duration: 0.2)) { holdProgress = 0 }
66 }
67 }
68 .accessibilityLabel("Hold for grown-ups")
69 .accessibilityAddTraits(.isButton)
70
71 Text("Press and hold")
72 .font(.system(size: 18, design: .rounded))
73 .foregroundStyle(.secondary)
74 }
75 }
76
77 private var sumStep: some View {
78 VStack(spacing: 20) {
79 Text("What is \(challenge.a) + \(challenge.b)?")
80 .font(.system(size: 26, weight: .semibold, design: .rounded))
81 TextField("Answer", text: $input)
82 .keyboardType(.numberPad)
83 .focused($fieldFocused)
84 .multilineTextAlignment(.center)
85 .font(.system(size: 28, weight: .bold, design: .rounded))
86 .padding(12)
87 .frame(width: 160)
88 .background(Color(.systemGray6), in: RoundedRectangle(cornerRadius: 12))
89 Button("Continue", action: submit)
90 .buttonStyle(.borderedProminent)
91 .font(.system(size: 20, weight: .semibold, design: .rounded))
92 }
93 }
94
95 private func submit() {
96 if challenge.accepts(input) {
97 onPass()
98 } else {
99 challenge = Self.newChallenge()
100 input = ""
101 held = false
102 holdProgress = 0
103 }
104 }
105
106 private static func newChallenge() -> ParentGateChallenge {
107 var rng = SystemRandomNumberGenerator()
108 return .random(using: &rng)
109 }
110}
111
112#Preview {
113 ParentGateView(onPass: {}, onCancel: {})
114}
DayByDay/Profiles/AnswerRecord.swift added +25
@@ -0,0 +1,25 @@
1//
2// AnswerRecord.swift
3// DayByDay
4//
5
6import Foundation
7import SwiftData
8
9/// One answer a child gave to a question.
10@Model
11final class AnswerRecord {
12 var categoryRaw: Int
13 var itemID: String
14 var isCorrect: Bool
15 var timestamp: Date
16 var profile: Profile?
17
18 init(categoryRaw: Int, itemID: String, isCorrect: Bool, timestamp: Date, profile: Profile) {
19 self.categoryRaw = categoryRaw
20 self.itemID = itemID
21 self.isCorrect = isCorrect
22 self.timestamp = timestamp
23 self.profile = profile
24 }
25}
DayByDay/Profiles/Avatar.swift added +53
@@ -0,0 +1,53 @@
1//
2// Avatar.swift
3// DayByDay
4//
5
6import SwiftUI
7
8/// The animal a child picks to stand for their profile.
9enum AvatarAnimal: String, CaseIterable, Identifiable {
10 case cat, dog, bird, fish, teddybear, tortoise, ladybug, hare
11
12 var id: String { rawValue }
13
14 var symbol: String { "\(rawValue).fill" }
15
16 var spokenName: String {
17 switch self {
18 case .cat: "Cat"
19 case .dog: "Dog"
20 case .bird: "Bird"
21 case .fish: "Fish"
22 case .teddybear: "Teddy"
23 case .tortoise: "Turtle"
24 case .ladybug: "Ladybug"
25 case .hare: "Bunny"
26 }
27 }
28}
29
30/// The color a child picks for their profile tile.
31enum ProfileColor: Int, CaseIterable, Identifiable {
32 case red, orange, yellow, green, teal, blue, purple, pink
33
34 var id: Int { rawValue }
35
36 var color: Color {
37 switch self {
38 case .red: Color(red: 0.86, green: 0.20, blue: 0.22)
39 case .orange: Color(red: 0.84, green: 0.40, blue: 0.08)
40 case .yellow: Color(red: 0.95, green: 0.75, blue: 0.15)
41 case .green: Color(red: 0.18, green: 0.56, blue: 0.28)
42 case .teal: Color(red: 0.0, green: 0.53, blue: 0.56)
43 case .blue: Color(red: 0.0, green: 0.42, blue: 0.85)
44 case .purple: Color(red: 0.55, green: 0.4, blue: 0.85)
45 case .pink: Color(red: 0.82, green: 0.25, blue: 0.52)
46 }
47 }
48
49 /// Color for the avatar symbol drawn on `color`.
50 var symbolColor: Color {
51 self == .yellow ? Color(red: 0.19, green: 0.15, blue: 0.03) : .white
52 }
53}
DayByDay/Profiles/AvatarBadge.swift added +25
@@ -0,0 +1,25 @@
1//
2// AvatarBadge.swift
3// DayByDay
4//
5
6import SwiftUI
7
8/// A child's avatar animal on their color.
9struct AvatarBadge: View {
10 let avatar: AvatarAnimal
11 let color: ProfileColor
12
13 var body: some View {
14 GeometryReader { geo in
15 ZStack {
16 Circle().fill(color.color)
17 Image(systemName: avatar.symbol)
18 .font(.system(size: geo.size.width * 0.5))
19 .foregroundStyle(color.symbolColor)
20 }
21 }
22 .aspectRatio(1, contentMode: .fit)
23 .accessibilityHidden(true)
24 }
25}
DayByDay/Profiles/Profile.swift added +33
@@ -0,0 +1,33 @@
1//
2// Profile.swift
3// DayByDay
4//
5
6import Foundation
7import SwiftData
8
9@Model
10final class Profile {
11 var id: UUID
12 var name: String
13 var avatarRaw: String
14 var colorRaw: Int
15 var birthdayMonth: Int?
16 var birthdayDay: Int?
17 var createdAt: Date
18 @Relationship(deleteRule: .cascade, inverse: \AnswerRecord.profile)
19 var answers: [AnswerRecord] = []
20
21 init(name: String, avatar: AvatarAnimal, color: ProfileColor, birthdayMonth: Int?, birthdayDay: Int?, createdAt: Date = .now) {
22 self.id = UUID()
23 self.name = name
24 self.avatarRaw = avatar.rawValue
25 self.colorRaw = color.rawValue
26 self.birthdayMonth = birthdayMonth
27 self.birthdayDay = birthdayDay
28 self.createdAt = createdAt
29 }
30
31 var avatar: AvatarAnimal { AvatarAnimal(rawValue: avatarRaw) ?? .cat }
32 var color: ProfileColor { ProfileColor(rawValue: colorRaw) ?? .blue }
33}
DayByDay/Profiles/ProfileEditorView.swift added +119
@@ -0,0 +1,119 @@
1//
2// ProfileEditorView.swift
3// DayByDay
4//
5
6import SwiftUI
7
8/// Creates a profile (`profile == nil`) or edits an existing one.
9struct ProfileEditorView: View {
10 let profile: Profile?
11
12 @Environment(ProfileSession.self) private var session
13 @Environment(\.dismiss) private var dismiss
14 @State private var name = ""
15 @State private var avatar: AvatarAnimal = .cat
16 @State private var color: ProfileColor = .blue
17 @State private var hasBirthday = false
18 @State private var month = 1
19 @State private var day = 1
20 @State private var error: ProfileError?
21
22 private let avatarColumns = [GridItem(.adaptive(minimum: 64), spacing: 12)]
23
24 init(profile: Profile?) {
25 self.profile = profile
26 if let profile {
27 _name = State(initialValue: profile.name)
28 _avatar = State(initialValue: profile.avatar)
29 _color = State(initialValue: profile.color)
30 _hasBirthday = State(initialValue: profile.birthdayMonth != nil)
31 _month = State(initialValue: profile.birthdayMonth ?? 1)
32 _day = State(initialValue: profile.birthdayDay ?? 1)
33 }
34 }
35
36 var body: some View {
37 Form {
38 Section("Name") {
39 TextField("Child's name", text: $name)
40 .textInputAutocapitalization(.words)
41 if error == .blankName {
42 Text("Enter a name.").foregroundStyle(.red)
43 }
44 }
45
46 Section("Animal") {
47 LazyVGrid(columns: avatarColumns, spacing: 12) {
48 ForEach(AvatarAnimal.allCases) { option in
49 Button { avatar = option } label: {
50 AvatarBadge(avatar: option, color: color)
51 .overlay(Circle().strokeBorder(.primary, lineWidth: avatar == option ? 4 : 0))
52 }
53 .buttonStyle(.plain)
54 .accessibilityLabel(option.spokenName)
55 .accessibilityAddTraits(avatar == option ? .isSelected : [])
56 }
57 }
58 .padding(.vertical, 6)
59 }
60
61 Section("Color") {
62 LazyVGrid(columns: avatarColumns, spacing: 12) {
63 ForEach(ProfileColor.allCases) { option in
64 Button { color = option } label: {
65 Circle()
66 .fill(option.color)
67 .frame(width: 52, height: 52)
68 .overlay(Circle().strokeBorder(.primary, lineWidth: color == option ? 4 : 0))
69 }
70 .buttonStyle(.plain)
71 .accessibilityLabel(String(describing: option))
72 .accessibilityAddTraits(color == option ? .isSelected : [])
73 }
74 }
75 .padding(.vertical, 6)
76 }
77
78 Section("Birthday") {
79 Toggle("Add birthday", isOn: $hasBirthday)
80 if hasBirthday {
81 Picker("Month", selection: $month) {
82 ForEach(1...12, id: \.self) { m in
83 Text(Calendar.current.monthSymbols[m - 1]).tag(m)
84 }
85 }
86 Picker("Day", selection: $day) {
87 ForEach(1...ProfileStore.daysInMonth[month - 1], id: \.self) { d in
88 Text("\(d)").tag(d)
89 }
90 }
91 }
92 }
93 }
94 .navigationTitle(profile == nil ? "New Child" : "Edit \(profile!.name)")
95 .toolbar {
96 ToolbarItem(placement: .confirmationAction) {
97 Button("Save", action: save)
98 }
99 }
100 .onChange(of: month) {
101 day = min(day, ProfileStore.daysInMonth[month - 1])
102 }
103 }
104
105 private func save() {
106 let birthday = hasBirthday ? (month: month, day: day) : nil
107 do {
108 if let profile {
109 try session.store.update(profile, name: name, avatar: avatar, color: color, birthday: birthday)
110 } else {
111 try session.store.create(name: name, avatar: avatar, color: color, birthday: birthday)
112 }
113 session.profilesChanged()
114 dismiss()
115 } catch let profileError as ProfileError {
116 error = profileError
117 } catch {}
118 }
119}
DayByDay/Profiles/ProfilePickerView.swift added +79
@@ -0,0 +1,79 @@
1//
2// ProfilePickerView.swift
3// DayByDay
4//
5
6import SwiftUI
7
8/// "Who's playing?" Big avatar tiles; no reading needed.
9struct ProfilePickerView: View {
10 @Environment(ProfileSession.self) private var session
11 @State private var showingParentArea = false
12
13 private let columns = [GridItem(.adaptive(minimum: 140, maximum: 260), spacing: 28)]
14
15 var body: some View {
16 ScrollView {
17 LazyVGrid(columns: columns, spacing: 28) {
18 ForEach(session.profiles) { profile in
19 Button {
20 SpeechSynthesizer.shared.speak("Hi, \(profile.name)!")
21 session.select(profile)
22 } label: {
23 VStack(spacing: 12) {
24 AvatarBadge(avatar: profile.avatar, color: profile.color)
25 Text(profile.name)
26 .font(.system(size: 26, weight: .bold, design: .rounded))
27 .foregroundStyle(.primary)
28 }
29 }
30 .buttonStyle(.plain)
31 .accessibilityLabel(profile.name)
32 }
33 }
34 .padding(32)
35 }
36 .safeAreaInset(edge: .bottom) {
37 Button("Grown-Ups") { showingParentArea = true }
38 .font(.system(size: 16, weight: .medium, design: .rounded))
39 .foregroundStyle(.secondary)
40 .padding(.bottom, 12)
41 }
42 .onAppear { SpeechSynthesizer.shared.speak("Who's playing?") }
43 .sheet(isPresented: $showingParentArea) {
44 GatedView(onCancel: { showingParentArea = false }) {
45 ParentAreaView(onDone: { showingParentArea = false })
46 }
47 }
48 }
49}
50
51/// First launch: a grown-up creates the first profile.
52struct ProfileSetupView: View {
53 @State private var started = false
54
55 var body: some View {
56 if started {
57 GatedView(onCancel: { started = false }) {
58 NavigationStack {
59 ProfileEditorView(profile: nil)
60 }
61 }
62 } else {
63 VStack(spacing: 24) {
64 MascotView(mood: .idle)
65 .frame(width: 160, height: 160)
66 Text("Welcome to Day By Day")
67 .font(.system(size: 32, weight: .bold, design: .rounded))
68 Text("Set up a profile for your child.")
69 .font(.system(size: 20, design: .rounded))
70 .foregroundStyle(.secondary)
71 Button("Get Started") { started = true }
72 .buttonStyle(.borderedProminent)
73 .font(.system(size: 22, weight: .semibold, design: .rounded))
74 }
75 .padding(40)
76 .multilineTextAlignment(.center)
77 }
78 }
79}
DayByDay/Profiles/ProfileSession.swift added +61
@@ -0,0 +1,61 @@
1//
2// ProfileSession.swift
3// DayByDay
4//
5
6import Foundation
7import Observation
8import SwiftData
9
10enum SessionScreen: Equatable {
11 case setup, picker, home
12}
13
14/// Tracks which child is using the app and which top-level screen to show.
15@Observable
16final class ProfileSession {
17 /// Time in the background after which siblings pick again.
18 static let pickerAfterBackground: TimeInterval = 600
19
20 let store: ProfileStore
21 private(set) var profiles: [Profile] = []
22 var current: Profile?
23 private var backgroundedAt: Date?
24
25 init(store: ProfileStore) {
26 self.store = store
27 profilesChanged()
28 }
29
30 var screen: SessionScreen {
31 if profiles.isEmpty { return .setup }
32 return current == nil ? .picker : .home
33 }
34
35 func select(_ profile: Profile) {
36 current = profile
37 }
38
39 func didEnterBackground(at date: Date) {
40 backgroundedAt = date
41 }
42
43 func willEnterForeground(at date: Date) {
44 defer { backgroundedAt = nil }
45 guard let backgroundedAt, profiles.count > 1,
46 date.timeIntervalSince(backgroundedAt) >= Self.pickerAfterBackground
47 else { return }
48 current = nil
49 }
50
51 /// Call after any profile is added, edited, or deleted.
52 func profilesChanged() {
53 profiles = store.all()
54 if let current, !profiles.contains(where: { $0.persistentModelID == current.persistentModelID }) {
55 self.current = nil
56 }
57 if current == nil, profiles.count == 1 {
58 current = profiles[0]
59 }
60 }
61}
DayByDay/Profiles/ProfileStore.swift added +85
@@ -0,0 +1,85 @@
1//
2// ProfileStore.swift
3// DayByDay
4//
5
6import Foundation
7import SwiftData
8
9enum ProfileError: Error, Equatable {
10 case blankName
11 case invalidBirthday
12}
13
14final class ProfileStore {
15 let context: ModelContext
16
17 init(context: ModelContext) {
18 self.context = context
19 }
20
21 static func makeContainer(inMemory: Bool) -> ModelContainer {
22 let config = ModelConfiguration(isStoredInMemoryOnly: inMemory)
23 return try! ModelContainer(for: Profile.self, AnswerRecord.self, configurations: config)
24 }
25
26 func all() -> [Profile] {
27 let descriptor = FetchDescriptor<Profile>(sortBy: [SortDescriptor(\.createdAt)])
28 return (try? context.fetch(descriptor)) ?? []
29 }
30
31 @discardableResult
32 func create(name: String, avatar: AvatarAnimal, color: ProfileColor, birthday: (month: Int, day: Int)?) throws -> Profile {
33 let name = try Self.validName(name)
34 try Self.validate(birthday)
35 let profile = Profile(name: name, avatar: avatar, color: color,
36 birthdayMonth: birthday?.month, birthdayDay: birthday?.day)
37 context.insert(profile)
38 try? context.save()
39 return profile
40 }
41
42 func update(_ profile: Profile, name: String, avatar: AvatarAnimal, color: ProfileColor, birthday: (month: Int, day: Int)?) throws {
43 let name = try Self.validName(name)
44 try Self.validate(birthday)
45 profile.name = name
46 profile.avatarRaw = avatar.rawValue
47 profile.colorRaw = color.rawValue
48 profile.birthdayMonth = birthday?.month
49 profile.birthdayDay = birthday?.day
50 try? context.save()
51 }
52
53 func delete(_ profile: Profile) {
54 context.delete(profile)
55 try? context.save()
56 }
57
58 func record(_ item: QuizItem, correct: Bool, for profile: Profile, at date: Date = .now) {
59 context.insert(AnswerRecord(categoryRaw: item.category.rawValue, itemID: item.id,
60 isCorrect: correct, timestamp: date, profile: profile))
61 try? context.save()
62 }
63
64 func answers(for profile: Profile, category: Category?) -> [AnswerRecord] {
65 profile.answers
66 .filter { category == nil || $0.categoryRaw == category!.rawValue }
67 .sorted { $0.timestamp < $1.timestamp }
68 }
69
70 /// Days per month in a leap year, so February 29 birthdays are allowed.
71 static let daysInMonth = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
72
73 private static func validName(_ name: String) throws -> String {
74 let trimmed = name.trimmingCharacters(in: .whitespacesAndNewlines)
75 guard !trimmed.isEmpty else { throw ProfileError.blankName }
76 return trimmed
77 }
78
79 private static func validate(_ birthday: (month: Int, day: Int)?) throws {
80 guard let birthday else { return }
81 guard (1...12).contains(birthday.month),
82 (1...daysInMonth[birthday.month - 1]).contains(birthday.day)
83 else { throw ProfileError.invalidBirthday }
84 }
85}
DayByDay/Quiz/CelebrationOverlay.swift added +83
@@ -0,0 +1,83 @@
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}
DayByDay/Quiz/PraisePhrases.swift added +32
@@ -0,0 +1,32 @@
1//
2// PraisePhrases.swift
3// DayByDay
4//
5
6nonisolated struct PraisePhrases {
7 static let all = [
8 "Great job!",
9 "You got it!",
10 "Super!",
11 "Way to go!",
12 "Awesome!",
13 "Yes, that's right!",
14 "Nice work!",
15 "You did great!",
16 "Hooray!",
17 "Fantastic!",
18 ]
19
20 private var last: String?
21
22 /// A random phrase, never the same as the previous one.
23 mutating func next(using rng: inout some RandomNumberGenerator) -> String {
24 let phrase = Self.all.filter { $0 != last }.randomElement(using: &rng)!
25 last = phrase
26 return phrase
27 }
28
29 static func correction(for name: String) -> String {
30 "That's \(name)! Try again."
31 }
32}
DayByDay/Quiz/Question.swift added +27
@@ -0,0 +1,27 @@
1//
2// Question.swift
3// DayByDay
4//
5
6nonisolated struct Question: Equatable {
7 let prompt: String
8 let choices: [QuizItem]
9 let answer: QuizItem
10}
11
12nonisolated struct QuestionPicker {
13 var choiceCount: Int
14 var prompt: (QuizItem) -> String
15
16 /// Picks a random answer (never `previous` when there is an alternative)
17 /// plus distinct distractors, shuffled.
18 func next(from items: [QuizItem], excluding previous: QuizItem?, using rng: inout some RandomNumberGenerator) -> Question {
19 let candidates = items.count > 1 ? items.filter { $0 != previous } : items
20 let answer = candidates.randomElement(using: &rng)!
21 let distractors = items.filter { $0 != answer }
22 .shuffled(using: &rng)
23 .prefix(min(choiceCount, items.count) - 1)
24 let choices = ([answer] + distractors).shuffled(using: &rng)
25 return Question(prompt: prompt(answer), choices: choices, answer: answer)
26 }
27}
DayByDay/Quiz/QuizItem.swift added +56
@@ -0,0 +1,56 @@
1//
2// QuizItem.swift
3// DayByDay
4//
5
6/// One askable thing in a category, e.g. "Tuesday" in Days.
7nonisolated struct QuizItem: Identifiable, Hashable, Sendable {
8 let id: String
9 let name: String
10 let category: Category
11}
12
13extension Category {
14 /// Categories shown in the home grid. Today is reached from the banner.
15 static var gridCases: [Category] {
16 allCases.filter { $0 != .today }
17 }
18
19 var quizItems: [QuizItem] {
20 switch self {
21 case .today: []
22 case .days: items(DayOfWeek.allCases, \.name)
23 case .months: items(MonthOfYear.allCases, \.name)
24 case .seasons: items(Season.allCases, \.name)
25 case .numbers: items(LearnNumber.allCases, \.name)
26 case .colors: items(LearnColor.allCases, \.name)
27 case .shapes: items(LearnShape.allCases, \.name)
28 case .animals: items(LearnAnimal.allCases, \.name)
29 case .alphabet: items(LearnLetter.allCases, \.spokenName)
30 case .weather: items(LearnWeather.allCases, \.name)
31 case .bodyParts: items(LearnBodyPart.allCases, \.name)
32 case .food: items(LearnFood.allCases, \.name)
33 }
34 }
35
36 var key: String {
37 switch self {
38 case .today: "today"
39 case .days: "days"
40 case .months: "months"
41 case .seasons: "seasons"
42 case .numbers: "numbers"
43 case .colors: "colors"
44 case .shapes: "shapes"
45 case .animals: "animals"
46 case .alphabet: "alphabet"
47 case .weather: "weather"
48 case .bodyParts: "bodyParts"
49 case .food: "food"
50 }
51 }
52
53 private func items<T>(_ cases: [T], _ name: KeyPath<T, String>) -> [QuizItem] {
54 cases.map { QuizItem(id: "\(key).\($0)", name: $0[keyPath: name], category: self) }
55 }
56}
DayByDay/Quiz/Round.swift added +60
@@ -0,0 +1,60 @@
1//
2// Round.swift
3// DayByDay
4//
5
6nonisolated enum AnswerOutcome: Equatable {
7 case correct
8 case incorrect(correctName: String)
9 case ignored
10}
11
12/// A fixed-length run of questions. A wrong answer keeps the same question and
13/// waits for `resume()`; a correct one waits for `advance()`. Answers are
14/// ignored while either kind of feedback plays.
15nonisolated struct Round {
16 static let length = 5
17
18 private let items: [QuizItem]
19 private let picker: QuestionPicker
20 private var rng: any RandomNumberGenerator
21 private(set) var current: Question
22 private(set) var correctCount = 0
23 private(set) var isAwaitingNext = false
24 private(set) var isShowingCorrection = false
25
26 var isFinished: Bool { correctCount == Round.length }
27
28 /// True once the last correct answer's feedback is done.
29 var isComplete: Bool { isFinished && !isAwaitingNext }
30
31 init(items: [QuizItem], picker: QuestionPicker, rng: some RandomNumberGenerator = SystemRandomNumberGenerator()) {
32 var rng: any RandomNumberGenerator = rng
33 self.items = items
34 self.picker = picker
35 self.current = picker.next(from: items, excluding: nil, using: &rng)
36 self.rng = rng
37 }
38
39 mutating func answer(_ item: QuizItem) -> AnswerOutcome {
40 guard !isAwaitingNext, !isShowingCorrection, !isFinished else { return .ignored }
41 guard item == current.answer else {
42 isShowingCorrection = true
43 return .incorrect(correctName: current.answer.name)
44 }
45 correctCount += 1
46 isAwaitingNext = true
47 return .correct
48 }
49
50 mutating func resume() {
51 isShowingCorrection = false
52 }
53
54 mutating func advance() {
55 guard isAwaitingNext else { return }
56 isAwaitingNext = false
57 guard !isFinished else { return }
58 current = picker.next(from: items, excluding: current.answer, using: &rng)
59 }
60}
DayByDay/Quiz/RoundView.swift added +151
@@ -0,0 +1,151 @@
1//
2// RoundView.swift
3// DayByDay
4//
5
6import SwiftUI
7
8enum RoundStyle {
9 static let playAgainFill = Color(red: 0.18, green: 0.56, blue: 0.28)
10}
11
12/// Runs a round of questions. The caller supplies how each choice looks.
13struct RoundView<Choice: View>: View {
14 private let items: [QuizItem]
15 private let picker: QuestionPicker
16 private let choice: (QuizItem) -> Choice
17
18 @Environment(ProfileSession.self) private var session
19 @State private var round: Round
20 @State private var praise = PraisePhrases()
21 @State private var celebrating = false
22 @State private var dimmed: QuizItem?
23
24 private let columns = [GridItem(.adaptive(minimum: 150, maximum: 320), spacing: 20)]
25
26 init(items: [QuizItem], picker: QuestionPicker, @ViewBuilder choice: @escaping (QuizItem) -> Choice) {
27 self.items = items
28 self.picker = picker
29 self.choice = choice
30 _round = State(initialValue: Round(items: items, picker: picker))
31 }
32
33 var body: some View {
34 Group {
35 if round.isComplete {
36 finished
37 } else {
38 question
39 }
40 }
41 .onAppear { speakPrompt() }
42 .onChange(of: round.current) { speakPrompt() }
43 }
44
45 private var question: some View {
46 ScrollView {
47 VStack(spacing: 28) {
48 Button(action: speakPrompt) {
49 Label("Hear it again", systemImage: "speaker.wave.2.fill")
50 .font(.system(size: 24, weight: .bold, design: .rounded))
51 .padding(.horizontal, 28)
52 .padding(.vertical, 16)
53 .background(Capsule().fill(Color(.systemGray6)))
54 }
55 .buttonStyle(.plain)
56
57 ProgressDots(filled: round.correctCount, total: Round.length)
58
59 LazyVGrid(columns: columns, spacing: 24) {
60 ForEach(round.current.choices) { item in
61 Button { tap(item) } label: {
62 choice(item)
63 .frame(height: 160)
64 .opacity(dimmed == item ? 0.4 : 1)
65 }
66 .buttonStyle(.plain)
67 .accessibilityLabel(item.name)
68 }
69 }
70 }
71 .padding(32)
72 }
73 .overlay { CelebrationOverlay(isActive: celebrating) }
74 }
75
76 private var finished: some View {
77 VStack(spacing: 28) {
78 MascotView(mood: .cheering)
79 .frame(width: 180, height: 180)
80 Text("You did it!")
81 .font(.system(size: 48, weight: .heavy, design: .rounded))
82 Button {
83 round = Round(items: items, picker: picker)
84 } label: {
85 Label("Play again", systemImage: "arrow.clockwise")
86 .font(.system(size: 28, weight: .bold, design: .rounded))
87 .foregroundStyle(.white)
88 .padding(.horizontal, 40)
89 .padding(.vertical, 20)
90 .background(Capsule().fill(RoundStyle.playAgainFill))
91 }
92 .buttonStyle(.plain)
93 }
94 .padding(32)
95 .onAppear {
96 SoundEngine.shared.play(.roundComplete)
97 SpeechSynthesizer.shared.speak("You did it!")
98 }
99 }
100
101 private func tap(_ item: QuizItem) {
102 let outcome = round.answer(item)
103 guard outcome != .ignored else { return }
104 if let profile = session.current {
105 session.store.record(round.current.answer, correct: outcome == .correct, for: profile)
106 }
107 switch outcome {
108 case .correct:
109 SoundEngine.shared.play(.success)
110 var rng = SystemRandomNumberGenerator()
111 SpeechSynthesizer.shared.speak(praise.next(using: &rng))
112 celebrating = true
113 DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {
114 celebrating = false
115 round.advance()
116 }
117 case .incorrect(let correctName):
118 SoundEngine.shared.play(.gentleMiss)
119 SpeechSynthesizer.shared.speak(PraisePhrases.correction(for: correctName))
120 withAnimation(.easeOut(duration: 0.2)) { dimmed = item }
121 DispatchQueue.main.asyncAfter(deadline: .now() + 1.2) {
122 withAnimation { if dimmed == item { dimmed = nil } }
123 round.resume()
124 }
125 case .ignored:
126 break
127 }
128 }
129
130 private func speakPrompt() {
131 guard !round.isFinished else { return }
132 SpeechSynthesizer.shared.speak(round.current.prompt)
133 }
134}
135
136/// Filled dots showing how many correct answers are done in this round.
137private struct ProgressDots: View {
138 let filled: Int
139 let total: Int
140
141 var body: some View {
142 HStack(spacing: 12) {
143 ForEach(0..<total, id: \.self) { i in
144 Circle()
145 .fill(i < filled ? Color.yellow : Color(.systemGray5))
146 .frame(width: 22, height: 22)
147 }
148 }
149 .accessibilityHidden(true)
150 }
151}
DayByDay/Sound/SoundEngine.swift added +51
@@ -0,0 +1,51 @@
1//
2// SoundEngine.swift
3// DayByDay
4//
5
6import AVFoundation
7
8/// Plays pre-rendered sound effects. Buffers are rendered once at startup.
9/// Each effect has its own player node so effects overlap instead of cutting
10/// each other off mid-wave (which clicks). A repeat of an effect that is
11/// still playing is skipped for the same reason.
12final class SoundEngine {
13 static let shared = SoundEngine()
14
15 private let engine = AVAudioEngine()
16 private let format = AVAudioFormat(standardFormatWithSampleRate: SoundSynth.sampleRate, channels: 1)!
17 private var buffers: [SoundEffect: AVAudioPCMBuffer] = [:]
18 private var players: [SoundEffect: AVAudioPlayerNode] = [:]
19 private var busyUntil: [SoundEffect: Date] = [:]
20
21 private init() {
22 for effect in SoundEffect.allCases {
23 let samples = SoundSynth.render(effect)
24 let buffer = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: AVAudioFrameCount(samples.count))!
25 buffer.frameLength = buffer.frameCapacity
26 samples.withUnsafeBufferPointer { src in
27 buffer.floatChannelData![0].update(from: src.baseAddress!, count: samples.count)
28 }
29 buffers[effect] = buffer
30
31 let player = AVAudioPlayerNode()
32 engine.attach(player)
33 engine.connect(player, to: engine.mainMixerNode, format: format)
34 players[effect] = player
35 }
36 }
37
38 func play(_ effect: SoundEffect) {
39 guard let buffer = buffers[effect], let player = players[effect] else { return }
40 let now = Date()
41 if let busy = busyUntil[effect], busy > now { return }
42 if !engine.isRunning {
43 try? AVAudioSession.sharedInstance().setCategory(.playback, mode: .default)
44 try? AVAudioSession.sharedInstance().setActive(true)
45 try? engine.start()
46 }
47 busyUntil[effect] = now.addingTimeInterval(Double(buffer.frameLength) / SoundSynth.sampleRate)
48 player.scheduleBuffer(buffer, at: nil)
49 if !player.isPlaying { player.play() }
50 }
51}
DayByDay/Sound/SoundSynth.swift added +81
@@ -0,0 +1,81 @@
1//
2// SoundSynth.swift
3// DayByDay
4//
5
6import Foundation
7
8nonisolated enum SoundEffect: CaseIterable {
9 case success, gentleMiss, tap, roundComplete
10}
11
12/// Renders sound effects to mono sample buffers. Notes are sines with soft
13/// harmonics and smooth envelopes, so there are no clicks or harsh edges.
14nonisolated enum SoundSynth {
15 static let sampleRate: Double = 44_100
16
17 private struct Note {
18 let frequency: Double
19 let start: Double
20 let duration: Double
21 var harmonics: [Double] = [1, 0.3, 0.1]
22 }
23
24 /// Silence at each end so playback never starts or stops mid-wave.
25 private static let pad = 0.004
26
27 static func render(_ effect: SoundEffect) -> [Float] {
28 switch effect {
29 case .success:
30 mix([
31 Note(frequency: 523.25, start: 0, duration: 0.14),
32 Note(frequency: 659.25, start: 0.1, duration: 0.14),
33 Note(frequency: 783.99, start: 0.2, duration: 0.22),
34 ], peak: 0.6)
35 case .gentleMiss:
36 mix([
37 Note(frequency: 329.63, start: 0, duration: 0.17, harmonics: [1, 0.15]),
38 Note(frequency: 261.63, start: 0.15, duration: 0.18, harmonics: [1, 0.15]),
39 ], peak: 0.3)
40 case .tap:
41 mix([Note(frequency: 880, start: 0, duration: 0.05, harmonics: [1, 0.2])], peak: 0.4)
42 case .roundComplete:
43 mix([
44 Note(frequency: 523.25, start: 0, duration: 0.14),
45 Note(frequency: 659.25, start: 0.12, duration: 0.14),
46 Note(frequency: 783.99, start: 0.24, duration: 0.14),
47 Note(frequency: 523.25, start: 0.4, duration: 0.7),
48 Note(frequency: 659.25, start: 0.4, duration: 0.7),
49 Note(frequency: 783.99, start: 0.4, duration: 0.7),
50 Note(frequency: 1046.5, start: 0.4, duration: 0.7),
51 ], peak: 0.6)
52 }
53 }
54
55 private static func mix(_ notes: [Note], peak: Float) -> [Float] {
56 let end = notes.map { $0.start + $0.duration }.max()!
57 var out = [Float](repeating: 0, count: Int((end + 2 * pad) * sampleRate))
58 for note in notes {
59 let offset = Int((note.start + pad) * sampleRate)
60 let count = Int(note.duration * sampleRate)
61 for i in 0..<count {
62 let t = Double(i) / sampleRate
63 var v = 0.0
64 for (n, amp) in note.harmonics.enumerated() {
65 v += amp * sin(2 * .pi * note.frequency * Double(n + 1) * t)
66 }
67 out[offset + i] += Float(v * envelope(t, duration: note.duration))
68 }
69 }
70 let maxAbs = out.map(abs).max() ?? 1
71 return out.map { $0 / maxAbs * peak }
72 }
73
74 /// Smooth attack, gentle exponential decay, smooth release to zero.
75 private static func envelope(_ t: Double, duration: Double) -> Double {
76 let attack = 0.01, release = 0.03
77 let rise = t < attack ? pow(sin(.pi / 2 * t / attack), 2) : 1
78 let fall = t > duration - release ? pow(sin(.pi / 2 * (duration - t) / release), 2) : 1
79 return rise * fall * exp(-3 * t / max(duration, 0.1))
80 }
81}
DayByDayTests/AvatarTests.swift added +9
@@ -0,0 +1,9 @@
1import Testing
2import UIKit
3@testable import DayByDay
4
5struct AvatarTests {
6 @Test(arguments: AvatarAnimal.allCases) func symbolExists(_ avatar: AvatarAnimal) {
7 #expect(UIImage(systemName: avatar.symbol) != nil)
8 }
9}
DayByDayTests/ContrastTests.swift added +47
@@ -0,0 +1,47 @@
1import SwiftUI
2import Testing
3import UIKit
4@testable import DayByDay
5
6/// WCAG contrast for white or dark symbols and labels on the app's fills.
7struct ContrastTests {
8 static let styles: [UIUserInterfaceStyle] = [.light, .dark]
9
10 func luminance(_ color: Color, _ style: UIUserInterfaceStyle) -> Double {
11 let ui = UIColor(color).resolvedColor(with: UITraitCollection(userInterfaceStyle: style))
12 var r: CGFloat = 0, g: CGFloat = 0, b: CGFloat = 0, a: CGFloat = 0
13 ui.getRed(&r, green: &g, blue: &b, alpha: &a)
14 func lin(_ c: CGFloat) -> Double {
15 let c = Double(c)
16 return c <= 0.03928 ? c / 12.92 : pow((c + 0.055) / 1.055, 2.4)
17 }
18 return 0.2126 * lin(r) + 0.7152 * lin(g) + 0.0722 * lin(b)
19 }
20
21 func contrast(_ a: Color, _ b: Color, _ style: UIUserInterfaceStyle) -> Double {
22 let la = luminance(a, style), lb = luminance(b, style)
23 return (max(la, lb) + 0.05) / (min(la, lb) + 0.05)
24 }
25
26 @Test(arguments: DayByDay.Category.allCases) func categoryColorAgainstWhite(_ category: DayByDay.Category) {
27 for style in Self.styles {
28 #expect(contrast(category.color, .white, style) >= 3, "\(category) \(style.rawValue)")
29 }
30 }
31
32 @Test func todayBannerAgainstWhite() {
33 for color in TodayBanner.gradientColors {
34 #expect(contrast(color, .white, .light) >= 3)
35 }
36 }
37
38 @Test func playAgainAgainstWhite() {
39 #expect(contrast(RoundStyle.playAgainFill, .white, .light) >= 3)
40 }
41
42 @Test(arguments: ProfileColor.allCases) func avatarSymbolOnProfileColor(_ color: ProfileColor) {
43 for style in Self.styles {
44 #expect(contrast(color.symbolColor, color.color, style) >= 3, "\(color) \(style.rawValue)")
45 }
46 }
47}
DayByDayTests/ParentGateTests.swift added +27
@@ -0,0 +1,27 @@
1import Testing
2@testable import DayByDay
3
4struct ParentGateTests {
5 @Test func operandsInRange() {
6 var rng = SeededGenerator(seed: 9)
7 for _ in 0..<1000 {
8 let c = ParentGateChallenge.random(using: &rng)
9 #expect((6...9).contains(c.a))
10 #expect((6...9).contains(c.b))
11 }
12 }
13
14 @Test func acceptsCorrectSum() {
15 let c = ParentGateChallenge(a: 7, b: 8)
16 #expect(c.answer == 15)
17 #expect(c.accepts("15"))
18 #expect(c.accepts(" 15 "))
19 }
20
21 @Test func rejectsWrong() {
22 let c = ParentGateChallenge(a: 7, b: 8)
23 #expect(!c.accepts("14"))
24 #expect(!c.accepts(""))
25 #expect(!c.accepts("abc"))
26 }
27}
DayByDayTests/PraisePhrasesTests.swift added +24
@@ -0,0 +1,24 @@
1import Testing
2@testable import DayByDay
3
4struct PraisePhrasesTests {
5 @Test func neverRepeatsConsecutively() {
6 var rng = SeededGenerator(seed: 11)
7 var phrases = PraisePhrases()
8 var last = ""
9 for _ in 0..<500 {
10 let next = phrases.next(using: &rng)
11 #expect(next != last)
12 #expect(PraisePhrases.all.contains(next))
13 last = next
14 }
15 }
16
17 @Test func atLeastEightPhrases() {
18 #expect(Set(PraisePhrases.all).count >= 8)
19 }
20
21 @Test func correctionCopy() {
22 #expect(PraisePhrases.correction(for: "Thursday") == "That's Thursday! Try again.")
23 }
24}
DayByDayTests/ProfileSessionTests.swift added +91
@@ -0,0 +1,91 @@
1import Foundation
2import Testing
3@testable import DayByDay
4
5struct ProfileSessionTests {
6 let container = ProfileStore.makeContainer(inMemory: true)
7 var store: ProfileStore { ProfileStore(context: container.mainContext) }
8 let t0 = Date(timeIntervalSince1970: 1_000_000)
9
10 @discardableResult
11 func add(_ name: String) -> Profile {
12 try! store.create(name: name, avatar: .cat, color: .red, birthday: nil)
13 }
14
15 @Test func noProfilesShowsSetup() {
16 #expect(ProfileSession(store: store).screen == .setup)
17 }
18
19 @Test func singleProfileAutoSelects() {
20 let maya = add("Maya")
21 let session = ProfileSession(store: store)
22 #expect(session.screen == .home)
23 #expect(session.current?.id == maya.id)
24 }
25
26 @Test func multipleProfilesShowPicker() {
27 add("Maya"); add("Sam")
28 let session = ProfileSession(store: store)
29 #expect(session.screen == .picker)
30 session.select(store.all()[1])
31 #expect(session.screen == .home)
32 #expect(session.current?.name == "Sam")
33 }
34
35 @Test func shortBackgroundKeepsCurrent() {
36 add("Maya"); add("Sam")
37 let session = ProfileSession(store: store)
38 session.select(store.all()[0])
39 session.didEnterBackground(at: t0)
40 session.willEnterForeground(at: t0.addingTimeInterval(599))
41 #expect(session.screen == .home)
42 }
43
44 @Test func longBackgroundShowsPickerWithSiblings() {
45 add("Maya"); add("Sam")
46 let session = ProfileSession(store: store)
47 session.select(store.all()[0])
48 session.didEnterBackground(at: t0)
49 session.willEnterForeground(at: t0.addingTimeInterval(ProfileSession.pickerAfterBackground))
50 #expect(session.screen == .picker)
51 }
52
53 @Test func longBackgroundKeepsSoleProfile() {
54 add("Maya")
55 let session = ProfileSession(store: store)
56 session.didEnterBackground(at: t0)
57 session.willEnterForeground(at: t0.addingTimeInterval(3600))
58 #expect(session.screen == .home)
59 }
60
61 @Test func deletingCurrentClearsIt() {
62 add("Maya"); add("Sam"); add("Lee")
63 let session = ProfileSession(store: store)
64 session.select(store.all()[0])
65 store.delete(store.all()[0])
66 session.profilesChanged()
67 #expect(session.current == nil)
68 #expect(session.screen == .picker)
69 session.select(store.all()[0])
70 store.delete(store.all()[0])
71 session.profilesChanged()
72 #expect(session.screen == .home)
73 #expect(session.current?.name == "Lee")
74 }
75
76 @Test func deletingLastProfileShowsSetup() {
77 add("Maya")
78 let session = ProfileSession(store: store)
79 store.delete(store.all()[0])
80 session.profilesChanged()
81 #expect(session.current == nil)
82 #expect(session.screen == .setup)
83 }
84
85 @Test func addingFirstProfileSelectsIt() {
86 let session = ProfileSession(store: store)
87 add("Maya")
88 session.profilesChanged()
89 #expect(session.screen == .home)
90 }
91}
DayByDayTests/ProfileStoreTests.swift added +73
@@ -0,0 +1,73 @@
1import Foundation
2import SwiftData
3import Testing
4@testable import DayByDay
5
6struct ProfileStoreTests {
7 let container = ProfileStore.makeContainer(inMemory: true)
8 var store: ProfileStore { ProfileStore(context: container.mainContext) }
9
10 @Test func createTrimsName() throws {
11 let p = try store.create(name: " Maya ", avatar: .cat, color: .blue, birthday: nil)
12 #expect(p.name == "Maya")
13 #expect(p.avatar == .cat)
14 #expect(p.color == .blue)
15 }
16
17 @Test func blankNameThrows() {
18 #expect(throws: ProfileError.blankName) {
19 try store.create(name: " ", avatar: .dog, color: .red, birthday: nil)
20 }
21 }
22
23 @Test func birthdayValidation() throws {
24 let p = try store.create(name: "Leap", avatar: .dog, color: .red, birthday: (month: 2, day: 29))
25 #expect(p.birthdayMonth == 2 && p.birthdayDay == 29)
26 for bad in [(2, 30), (4, 31), (13, 1), (0, 5), (5, 0)] {
27 #expect(throws: ProfileError.invalidBirthday) {
28 try store.create(name: "X", avatar: .dog, color: .red, birthday: (month: bad.0, day: bad.1))
29 }
30 }
31 }
32
33 @Test func allSortedByCreation() throws {
34 let s = store
35 let a = try s.create(name: "A", avatar: .cat, color: .red, birthday: nil)
36 let b = try s.create(name: "B", avatar: .dog, color: .blue, birthday: nil)
37 #expect(s.all().map(\.id) == [a.id, b.id])
38 }
39
40 @Test func updateValidates() throws {
41 let s = store
42 let p = try s.create(name: "Maya", avatar: .cat, color: .red, birthday: nil)
43 try s.update(p, name: " Mae ", avatar: .bird, color: .green, birthday: (month: 5, day: 1))
44 #expect(p.name == "Mae" && p.avatar == .bird && p.birthdayMonth == 5)
45 #expect(throws: ProfileError.blankName) {
46 try s.update(p, name: "", avatar: .bird, color: .green, birthday: nil)
47 }
48 }
49
50 @Test func recordsAnswersPerProfile() throws {
51 let s = store
52 let maya = try s.create(name: "Maya", avatar: .cat, color: .red, birthday: nil)
53 let sam = try s.create(name: "Sam", avatar: .dog, color: .blue, birthday: nil)
54 s.record(Category.days.quizItems[0], correct: true, for: maya)
55 s.record(Category.months.quizItems[0], correct: false, for: maya)
56 s.record(Category.days.quizItems[1], correct: true, for: sam)
57 #expect(s.answers(for: maya, category: .days).count == 1)
58 #expect(s.answers(for: maya, category: nil).count == 2)
59 #expect(s.answers(for: sam, category: nil).first?.itemID == "days.monday")
60 }
61
62 @Test func deletingProfileDeletesAnswers() throws {
63 let s = store
64 let maya = try s.create(name: "Maya", avatar: .cat, color: .red, birthday: nil)
65 let sam = try s.create(name: "Sam", avatar: .dog, color: .blue, birthday: nil)
66 s.record(Category.days.quizItems[0], correct: true, for: maya)
67 s.record(Category.days.quizItems[1], correct: true, for: sam)
68 s.delete(maya)
69 let remaining = try container.mainContext.fetch(FetchDescriptor<AnswerRecord>())
70 #expect(remaining.count == 1)
71 #expect(s.all().map(\.name) == ["Sam"])
72 }
73}
DayByDayTests/QuizItemTests.swift added +25
@@ -0,0 +1,25 @@
1import Testing
2@testable import DayByDay
3
4struct QuizItemTests {
5 @Test func everyGridCategoryHasItems() {
6 for category in Category.gridCases {
7 #expect(!category.quizItems.isEmpty)
8 }
9 }
10
11 @Test func gridExcludesToday() {
12 #expect(!Category.gridCases.contains(.today))
13 #expect(Category.gridCases.count == 11)
14 }
15
16 @Test func idsAreUniqueAndStable() {
17 let all = Category.gridCases.flatMap(\.quizItems)
18 #expect(Set(all.map(\.id)).count == all.count)
19 #expect(Category.days.quizItems[2] == QuizItem(id: "days.tuesday", name: "Tuesday", category: .days))
20 }
21
22 @Test func lettersUseSpokenName() {
23 #expect(Category.alphabet.quizItems.first?.name == "a")
24 }
25}
DayByDayTests/RoundTests.swift added +93
@@ -0,0 +1,93 @@
1import Testing
2@testable import DayByDay
3
4struct RoundTests {
5 let days = Category.days.quizItems
6 let picker = QuestionPicker(choiceCount: 4) { "Can you find \($0.name)?" }
7
8 @Test func choicesIncludeAnswerAndAreDistinct() {
9 var rng = SeededGenerator(seed: 1)
10 for _ in 0..<50 {
11 let q = picker.next(from: days, excluding: nil, using: &rng)
12 #expect(q.choices.count == 4)
13 #expect(q.choices.contains(q.answer))
14 #expect(Set(q.choices).count == 4)
15 }
16 }
17
18 @Test func choiceCountClampsToItemCount() {
19 var rng = SeededGenerator(seed: 2)
20 let wide = QuestionPicker(choiceCount: 6) { $0.name }
21 let q = wide.next(from: Category.seasons.quizItems, excluding: nil, using: &rng)
22 #expect(q.choices.count == 4)
23 }
24
25 @Test func neverRepeatsPreviousAnswer() {
26 var rng = SeededGenerator(seed: 3)
27 let previous = days[0]
28 for _ in 0..<200 {
29 #expect(picker.next(from: days, excluding: previous, using: &rng).answer != previous)
30 }
31 }
32
33 @Test func promptUsesClosure() {
34 var rng = SeededGenerator(seed: 4)
35 let q = picker.next(from: days, excluding: nil, using: &rng)
36 #expect(q.prompt == "Can you find \(q.answer.name)?")
37 }
38
39 @Test func wrongAnswerRetriesSameQuestion() {
40 var round = Round(items: days, picker: picker, rng: SeededGenerator(seed: 5))
41 let question = round.current
42 let wrong = question.choices.first { $0 != question.answer }!
43 #expect(round.answer(wrong) == .incorrect(correctName: question.answer.name))
44 #expect(round.current == question)
45 #expect(round.correctCount == 0)
46 #expect(!round.isAwaitingNext)
47 }
48
49 @Test func tapsWhileAwaitingNextAreIgnored() {
50 var round = Round(items: days, picker: picker, rng: SeededGenerator(seed: 6))
51 let answer = round.current.answer
52 #expect(round.answer(answer) == .correct)
53 #expect(round.isAwaitingNext)
54 #expect(round.answer(answer) == .ignored)
55 #expect(round.answer(round.current.choices.first { $0 != answer }!) == .ignored)
56 #expect(round.correctCount == 1)
57 }
58
59 @Test func finishesAfterFiveCorrect() {
60 var round = Round(items: days, picker: picker, rng: SeededGenerator(seed: 7))
61 for _ in 0..<Round.length {
62 #expect(!round.isFinished)
63 _ = round.answer(round.current.answer)
64 round.advance()
65 }
66 #expect(round.isFinished)
67 #expect(round.correctCount == 5)
68 }
69
70 @Test func tapsDuringCorrectionAreIgnored() {
71 var round = Round(items: days, picker: picker, rng: SeededGenerator(seed: 8))
72 let question = round.current
73 let wrong = question.choices.filter { $0 != question.answer }
74 #expect(round.answer(wrong[0]) == .incorrect(correctName: question.answer.name))
75 #expect(round.answer(wrong[1]) == .ignored)
76 #expect(round.answer(question.answer) == .ignored)
77 round.resume()
78 #expect(round.answer(question.answer) == .correct)
79 }
80
81 @Test func finalAnswerCelebratesBeforeCompleting() {
82 var round = Round(items: days, picker: picker, rng: SeededGenerator(seed: 9))
83 for _ in 0..<(Round.length - 1) {
84 _ = round.answer(round.current.answer)
85 round.advance()
86 }
87 _ = round.answer(round.current.answer)
88 #expect(round.isFinished)
89 #expect(!round.isComplete)
90 round.advance()
91 #expect(round.isComplete)
92 }
93}
DayByDayTests/SeededGenerator.swift added +14
@@ -0,0 +1,14 @@
1/// Deterministic SplitMix64 generator for tests.
2nonisolated struct SeededGenerator: RandomNumberGenerator {
3 private var state: UInt64
4
5 init(seed: UInt64) { state = seed }
6
7 mutating func next() -> UInt64 {
8 state &+= 0x9E37_79B9_7F4A_7C15
9 var z = state
10 z = (z ^ (z >> 30)) &* 0xBF58_476D_1CE4_E5B9
11 z = (z ^ (z >> 27)) &* 0x94D0_49BB_1331_11EB
12 return z ^ (z >> 31)
13 }
14}
DayByDayTests/SoundSynthTests.swift added +33
@@ -0,0 +1,33 @@
1import Foundation
2import Testing
3@testable import DayByDay
4
5struct SoundSynthTests {
6 func seconds(_ samples: [Float]) -> Double { Double(samples.count) / SoundSynth.sampleRate }
7 func rms(_ s: [Float]) -> Float { (s.reduce(0) { $0 + $1 * $1 } / Float(s.count)).squareRoot() }
8
9 @Test(arguments: SoundEffect.allCases) func noClipping(_ e: SoundEffect) {
10 #expect(SoundSynth.render(e).map(abs).max()! <= 0.9)
11 }
12
13 @Test(arguments: SoundEffect.allCases) func noClicks(_ e: SoundEffect) {
14 let s = SoundSynth.render(e)
15 #expect(s.prefix(64).allSatisfy { abs($0) < 0.01 })
16 #expect(s.suffix(64).allSatisfy { abs($0) < 0.01 })
17 }
18
19 @Test(arguments: SoundEffect.allCases) func notSilent(_ e: SoundEffect) {
20 #expect(rms(SoundSynth.render(e)) > 0.02)
21 }
22
23 @Test func durations() {
24 #expect(seconds(SoundSynth.render(.tap)) < 0.08)
25 #expect((0.3...0.6).contains(seconds(SoundSynth.render(.success))))
26 #expect((0.25...0.5).contains(seconds(SoundSynth.render(.gentleMiss))))
27 #expect((0.9...1.6).contains(seconds(SoundSynth.render(.roundComplete))))
28 }
29
30 @Test func missIsQuieterThanSuccess() {
31 #expect(rms(SoundSynth.render(.gentleMiss)) < rms(SoundSynth.render(.success)))
32 }
33}
docs/superpowers/plans/2026-10-16-part1-foundation.md added +306
@@ -0,0 +1,306 @@
1# Part 1: Foundation Implementation Plan
2
3> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
4
5**Goal:** Profiles, parent gate, answer log, sound engine, celebration, question engine with rounds, and the option-C home/hub navigation, with a unit test target.
6
7**Architecture:** SwiftData models (`Profile`, `AnswerRecord`) behind a small `ProfileStore`. An `@Observable ProfileSession` holds the current child and decides when to show the picker. A pure question engine (`QuizItem`, `QuestionPicker`, `Round`) is driven by a generic `RoundView`. Sound effects are rendered to sample buffers by a pure `SoundSynth` and played by `SoundEngine` (AVAudioEngine). Home becomes a Today banner plus topic grid; each topic opens `CategoryHubView`.
8
9**Tech Stack:** SwiftUI, SwiftData, AVFoundation (AVAudioEngine), Swift Testing, Xcode 27, `xcodeproj` Ruby gem (1.28.1, installed) for adding the test target.
10
11**Spec:** `docs/superpowers/specs/2026-10-16-learning-games-design.md`
12
13Parts 2–7 get their own plans, each written after the previous part merges.
14
15## Global Constraints
16
17- Effective deployment target is iOS 17.5. Use only APIs available on 17.5.
18- Build settings: `SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor`, approachable concurrency on. Pure logic types that tests touch off the main actor must be `nonisolated`.
19- New app files go under `DayByDay/` (file-system-synchronized group). New test files go under `DayByDayTests/`.
20- No network, no analytics, no bundled image or audio files. All art in SwiftUI/SF Symbols, all sound synthesized at runtime.
21- Nothing requires reading. Every child-facing prompt is spoken through `SpeechSynthesizer.shared.speak(_:)`.
22- Wrong answers: soft sound plus spoken correction. No buzzer, no red X, no lost points.
23- Rounds end with "You did it!" after 5 correct answers.
24- Parent gate protects profile management. First-launch profile creation also goes through the gate.
25- Profile picker: shown at launch when more than one profile exists, and on return to foreground after 10 or more minutes in the background. Skipped with exactly one profile. Avatar button in the home corner opens it, ungated.
26- Weeks start on Sunday. The season is "Fall".
27- Every commit message references the part 1 issue (`Ref #N`; the final one `Closes #N`). No AI attribution anywhere.
28- Branch `feat/foundation` from `main`. Never push to `main`.
29
30## Review Focus
31
321. Deleting the profile that is currently selected → session clears `current`; picker (or setup, if none remain) shows; that profile's answers are deleted with it. Test in Task 3 and Task 4.
332. Deleting the last profile → app returns to first-launch setup. Test in Task 4.
343. A child tapping repeatedly while feedback plays → only the first tap per question is recorded; further taps are ignored until the next question appears. Test in Task 2 (`Round` rejects answers while `isAwaitingNext`).
354. Reduce Motion on → confetti does not animate particles; celebration uses a fade only. Checked in Task 7.
365. Category with fewer items than the requested choice count, or a blank/whitespace profile name → picker clamps to the item count; setup refuses blank names. Tests in Task 2 and Task 3.
37
38---
39
40### Task 0: Branch and issue
41
42- [ ] **Step 1:** `git checkout -b feat/foundation main`
43- [ ] **Step 2:** Create the issue and note its number as `N` for all commit messages:
44
45```bash
46gitbay issue create --title "Part 1: foundation (profiles, question engine, sound, home hubs)" --file - <<'EOF'
47Implements part 1 of docs/superpowers/specs/2026-10-16-learning-games-design.md.
48Plan: docs/superpowers/plans/2026-10-16-part1-foundation.md
49EOF
50```
51
52- [ ] **Step 3:** Commit the spec and this plan: `git add docs && git commit -m "docs: learning games design and part 1 plan" -m "Ref #N"`
53
54### Task 1: Test target and quiz items
55
56**Files:**
57- Create: `scripts/add-test-target.rb` (run once, committed for reproducibility)
58- Modify: `DayByDay.xcodeproj/project.pbxproj` (via script)
59- Create: `DayByDay.xcodeproj/xcshareddata/xcschemes/DayByDay.xcscheme` (via script)
60- Create: `DayByDay/Quiz/QuizItem.swift`
61- Test: `DayByDayTests/QuizItemTests.swift`
62
63**Interfaces:**
64- Produces: `struct QuizItem: Identifiable, Hashable, Sendable { let id: String; let name: String; let category: Category }`; `extension Category { var quizItems: [QuizItem]; static var gridCases: [Category] }`. `id` is `"<category>.<case>"`, e.g. `"days.tuesday"`, built with `String(describing:)` on the enum case. `name` is the spoken name (`LearnLetter` uses `spokenName`).
65
66- [ ] **Step 1:** Write `scripts/add-test-target.rb` using the `xcodeproj` gem: add a `DayByDayTests` unit-test bundle target (`com.apple.product-type.bundle.unit-test`) with `TEST_HOST`/`BUNDLE_LOADER` pointing at the app, deployment target 17.5, a file-system-synchronized root group for `DayByDayTests/`, and a shared `DayByDay` scheme whose test action includes `DayByDayTests`. If the gem cannot write a synchronized group for objectVersion 77, add the test files as regular file references instead.
67- [ ] **Step 2:** Write the failing test:
68
69```swift
70import Testing
71@testable import DayByDay
72
73struct QuizItemTests {
74 @Test func everyGridCategoryHasItems() {
75 for category in Category.gridCases { #expect(!category.quizItems.isEmpty) }
76 }
77 @Test func gridExcludesToday() {
78 #expect(!Category.gridCases.contains(.today))
79 #expect(Category.gridCases.count == 11)
80 }
81 @Test func idsAreUniqueAndStable() {
82 let all = Category.gridCases.flatMap(\.quizItems)
83 #expect(Set(all.map(\.id)).count == all.count)
84 #expect(Category.days.quizItems[2] == QuizItem(id: "days.tuesday", name: "Tuesday", category: .days))
85 }
86 @Test func lettersUseSpokenName() {
87 #expect(Category.alphabet.quizItems.first?.name == "a")
88 }
89}
90```
91
92- [ ] **Step 3:** Run `ruby scripts/add-test-target.rb`, then `xcodebuild test -project DayByDay.xcodeproj -scheme DayByDay -destination 'platform=iOS Simulator,name=iPhone 16 Pro' -only-testing:DayByDayTests/QuizItemTests`. Expected: build fails, `quizItems` not found.
93- [ ] **Step 4:** Implement `QuizItem.swift`: map each category to its enum (`DayOfWeek`, `MonthOfYear`, `Season`, `LearnNumber`, `LearnColor`, `LearnShape`, `LearnAnimal`, `LearnLetter`, `LearnWeather`, `LearnBodyPart`, `LearnFood`); `.today` returns `[]`.
94- [ ] **Step 5:** Run the same test command. Expected: PASS.
95- [ ] **Step 6:** Commit: `feat: add unit test target and quiz items` with `Ref #N`.
96
97### Task 2: Question picker and round
98
99**Files:**
100- Create: `DayByDay/Quiz/Question.swift`, `DayByDay/Quiz/Round.swift`
101- Test: `DayByDayTests/RoundTests.swift`
102
103**Interfaces:**
104- Consumes: `QuizItem`.
105- Produces:
106 - `struct Question: Equatable { let prompt: String; let choices: [QuizItem]; let answer: QuizItem }`
107 - `struct QuestionPicker { var choiceCount: Int; var prompt: (QuizItem) -> String; func next(from items: [QuizItem], excluding previous: QuizItem?, using rng: inout some RandomNumberGenerator) -> Question }`. It picks the answer uniformly at random, never equal to `previous` when `items.count > 1`. Choices are the answer plus `min(choiceCount, items.count) - 1` distinct others, shuffled.
108 - `enum AnswerOutcome: Equatable { case correct; case incorrect(correctName: String); case ignored }`
109 - `struct Round { static let length = 5; init(items: [QuizItem], picker: QuestionPicker, rng: some RandomNumberGenerator); private(set) var current: Question; private(set) var correctCount: Int; private(set) var isAwaitingNext: Bool; var isFinished: Bool; mutating func answer(_ item: QuizItem) -> AnswerOutcome; mutating func advance() }`. A wrong answer keeps the same question (retry). A correct answer sets `isAwaitingNext = true`; any answer while awaiting returns `.ignored`. `advance()` picks the next question. `isFinished` when `correctCount == Round.length`.
110 - Tests use a seeded generator: add `struct SeededGenerator: RandomNumberGenerator` (SplitMix64) in `DayByDayTests/SeededGenerator.swift`.
111
112- [ ] **Step 1:** Write the failing tests:
113
114```swift
115@Test func choicesIncludeAnswerAndAreDistinct() // 4 choices, contains answer, Set(choices).count == 4
116@Test func choiceCountClampsToItemCount() // Season (4 items), choiceCount 6 → 4 choices
117@Test func neverRepeatsPreviousAnswer() // 200 draws from days with previous set → answer != previous
118@Test func promptUsesClosure() // prompt { "Can you find \($0.name)?" } → "Can you find Tuesday?" when answer is Tuesday
119@Test func wrongAnswerRetriesSameQuestion() // outcome == .incorrect(correctName: answer.name); current unchanged; correctCount == 0
120@Test func tapsWhileAwaitingNextAreIgnored() // correct, then any answer → .ignored; correctCount == 1
121@Test func finishesAfterFiveCorrect() // 5 × (answer correct, advance) → isFinished
122```
123
124- [ ] **Step 2:** Run `xcodebuild test ... -only-testing:DayByDayTests/RoundTests`. Expected: FAIL (types not defined).
125- [ ] **Step 3:** Implement `Question.swift` and `Round.swift` per the interfaces. Mark both `nonisolated`.
126- [ ] **Step 4:** Run the same command. Expected: PASS.
127- [ ] **Step 5:** Commit: `feat: add question picker and round` with `Ref #N`.
128
129### Task 3: Profiles and answer log
130
131**Files:**
132- Create: `DayByDay/Profiles/Profile.swift`, `DayByDay/Profiles/AnswerRecord.swift`, `DayByDay/Profiles/ProfileStore.swift`, `DayByDay/Profiles/Avatar.swift`
133- Test: `DayByDayTests/ProfileStoreTests.swift`
134
135**Interfaces:**
136- Produces:
137 - `enum AvatarAnimal: String, CaseIterable { cat, dog, bird, fish, rabbit, tortoise, ladybug, hare }` with `var symbol: String` (`"cat.fill"`, `"dog.fill"`, `"bird.fill"`, `"fish.fill"`, `"rabbit.fill"`, `"tortoise.fill"`, `"ladybug.fill"`, `"hare.fill"`) and `var spokenName: String`.
138 - `enum ProfileColor: Int, CaseIterable` with 8 cases and `var color: Color`.
139 - `@Model final class Profile { var id: UUID; var name: String; var avatarRaw: String; var colorRaw: Int; var birthdayMonth: Int?; var birthdayDay: Int?; var createdAt: Date; @Relationship(deleteRule: .cascade, inverse: \AnswerRecord.profile) var answers: [AnswerRecord] }` with computed `avatar: AvatarAnimal` and `color: ProfileColor`.
140 - `@Model final class AnswerRecord { var categoryRaw: Int; var itemID: String; var isCorrect: Bool; var timestamp: Date; var profile: Profile? }`
141 - `enum ProfileError: Error, Equatable { case blankName; case invalidBirthday }`
142 - `final class ProfileStore { init(context: ModelContext); func all() -> [Profile]` (sorted by `createdAt`)`; func create(name: String, avatar: AvatarAnimal, color: ProfileColor, birthday: (month: Int, day: Int)?) throws -> Profile; func update(_ p: Profile, name: String, avatar: AvatarAnimal, color: ProfileColor, birthday: (month: Int, day: Int)?) throws; func delete(_ p: Profile); func record(_ item: QuizItem, correct: Bool, for p: Profile, at date: Date = .now); func answers(for p: Profile, category: Category?) -> [AnswerRecord] }`
143 - Names are trimmed; blank → `.blankName`. Birthday day must be valid for the month in a leap year (Feb allows 29) → else `.invalidBirthday`.
144 - `static func makeContainer(inMemory: Bool) -> ModelContainer` on `ProfileStore`.
145
146- [ ] **Step 1:** Write the failing tests (all on an in-memory container):
147
148```swift
149@Test func createTrimsName() // " Maya " → "Maya"
150@Test func blankNameThrows() // " " → ProfileError.blankName
151@Test func birthdayValidation() // (2, 29) ok; (2, 30) and (4, 31) and (13, 1) → .invalidBirthday
152@Test func allSortedByCreation()
153@Test func recordsAnswersPerProfile() // record for Maya and Sam; answers(for: maya, category: .days).count == 1
154@Test func deletingProfileDeletesAnswers() // delete(maya) → no AnswerRecord rows with profile == nil remain
155```
156
157- [ ] **Step 2:** Run `xcodebuild test ... -only-testing:DayByDayTests/ProfileStoreTests`. Expected: FAIL.
158- [ ] **Step 3:** Implement the files per the interfaces.
159- [ ] **Step 4:** Run the same command. Expected: PASS.
160- [ ] **Step 5:** Commit: `feat: add profiles and answer log` with `Ref #N`.
161
162### Task 4: Profile session
163
164**Files:**
165- Create: `DayByDay/Profiles/ProfileSession.swift`
166- Test: `DayByDayTests/ProfileSessionTests.swift`
167
168**Interfaces:**
169- Consumes: `Profile`, `ProfileStore`.
170- Produces: `@Observable final class ProfileSession { static let pickerAfterBackground: TimeInterval = 600; var current: Profile?; init(store: ProfileStore); var screen: SessionScreen; func select(_ p: Profile); func didEnterBackground(at: Date); func willEnterForeground(at: Date); func profilesChanged() }` and `enum SessionScreen: Equatable { case setup, picker, home }`.
171 - `screen`: no profiles → `.setup`; `current == nil` and one profile → auto-select it, `.home`; `current == nil` and several → `.picker`; otherwise `.home`.
172 - `willEnterForeground` clears `current` when profile count > 1 and the background interval ≥ 600 s.
173 - `profilesChanged()` clears `current` if it was deleted.
174
175- [ ] **Step 1:** Write the failing tests:
176
177```swift
178@Test func noProfilesShowsSetup()
179@Test func singleProfileAutoSelects() // screen == .home, current == only profile
180@Test func multipleProfilesShowPicker()
181@Test func shortBackgroundKeepsCurrent() // 599 s → .home
182@Test func longBackgroundShowsPickerWithSiblings() // 600 s, 2 profiles → .picker
183@Test func longBackgroundKeepsSoleProfile() // 600 s, 1 profile → .home
184@Test func deletingCurrentClearsIt() // delete current, profilesChanged() → .picker (2 left) / .home (1 left)
185@Test func deletingLastProfileShowsSetup()
186```
187
188- [ ] **Step 2:** Run `-only-testing:DayByDayTests/ProfileSessionTests`. Expected: FAIL.
189- [ ] **Step 3:** Implement `ProfileSession.swift`.
190- [ ] **Step 4:** Run it. Expected: PASS.
191- [ ] **Step 5:** Commit: `feat: add profile session` with `Ref #N`.
192
193### Task 5: Parent gate
194
195**Files:**
196- Create: `DayByDay/Parent/ParentGate.swift` (logic), `DayByDay/Parent/ParentGateView.swift`
197- Test: `DayByDayTests/ParentGateTests.swift`
198
199**Interfaces:**
200- Produces: `nonisolated struct ParentGateChallenge { let a: Int; let b: Int; var answer: Int { a + b }; static func random(using rng: inout some RandomNumberGenerator) -> ParentGateChallenge; func accepts(_ input: String) -> Bool }`. `a` and `b` in `6...9` (sums 12–18). `accepts` trims whitespace and compares as an integer. `static let holdDuration: TimeInterval = 2`.
201- Produces: `struct ParentGateView: View { init(onPass: @escaping () -> Void, onCancel: @escaping () -> Void) }`. Step 1: a "Hold for grown-ups" button that must be held for `holdDuration` (progress ring fills while held; release resets). Step 2: shows "What is a + b?" as text with a number-pad field; correct entry calls `onPass`, wrong entry shows a new challenge.
202
203- [ ] **Step 1:** Write failing tests: `operandsInRange` (1000 draws, both in 6...9), `acceptsCorrectSum` ("15", " 15 "), `rejectsWrong` ("14", "", "abc").
204- [ ] **Step 2:** Run `-only-testing:DayByDayTests/ParentGateTests`. Expected: FAIL.
205- [ ] **Step 3:** Implement `ParentGate.swift`, then `ParentGateView.swift`.
206- [ ] **Step 4:** Run it. Expected: PASS. Then check the view in an Xcode preview or the simulator: the hold resets on early release, and a correct sum passes.
207- [ ] **Step 5:** Commit: `feat: add parent gate` with `Ref #N`.
208
209### Task 6: Sound synthesis and engine
210
211**Files:**
212- Create: `DayByDay/Sound/SoundSynth.swift`, `DayByDay/Sound/SoundEngine.swift`
213- Test: `DayByDayTests/SoundSynthTests.swift`
214
215**Interfaces:**
216- Produces: `nonisolated enum SoundEffect: CaseIterable { case success, gentleMiss, tap, roundComplete }`; `nonisolated enum SoundSynth { static let sampleRate: Double = 44_100; static func render(_ effect: SoundEffect) -> [Float] }`; `final class SoundEngine { static let shared: SoundEngine; func play(_ effect: SoundEffect) }`.
217 - Shaping: `success` is a rising major arpeggio (about 3 notes, about 0.4 s); `gentleMiss` is a soft, low, two-note falling tone (about 0.35 s, quieter than success); `tap` is a short click-free blip (under 0.08 s); `roundComplete` is a longer fanfare (about 1.2 s). Use sine plus soft harmonics with an attack/release envelope.
218 - `SoundEngine` pre-renders every effect into an `AVAudioPCMBuffer` at init and plays it on an `AVAudioPlayerNode`. The audio session uses `.playback` like `SpeechSynthesizer`, plus `.mixWithOthers` so effects and speech overlap.
219
220- [ ] **Step 1:** Write the failing tests, one parameterized over `SoundEffect.allCases`:
221
222```swift
223@Test(arguments: SoundEffect.allCases) func noClipping(_ e: SoundEffect) // max(abs(sample)) <= 0.9
224@Test(arguments: SoundEffect.allCases) func noClicks(_ e: SoundEffect) // first and last 64 samples: abs < 0.01
225@Test(arguments: SoundEffect.allCases) func notSilent(_ e: SoundEffect) // RMS > 0.02
226@Test func durations() // tap < 0.08 s; success 0.3–0.6 s; gentleMiss 0.25–0.5 s; roundComplete 0.9–1.6 s
227@Test func missIsQuieterThanSuccess() // RMS(gentleMiss) < RMS(success)
228```
229
230- [ ] **Step 2:** Run `-only-testing:DayByDayTests/SoundSynthTests`. Expected: FAIL.
231- [ ] **Step 3:** Implement `SoundSynth.swift`, then `SoundEngine.swift`.
232- [ ] **Step 4:** Run it. Expected: PASS.
233- [ ] **Step 5:** Commit: `feat: add synthesized sound effects` with `Ref #N`.
234
235### Task 7: Celebration and round view
236
237**Files:**
238- Create: `DayByDay/Quiz/PraisePhrases.swift`, `DayByDay/Quiz/CelebrationOverlay.swift`, `DayByDay/Quiz/RoundView.swift`
239- Test: `DayByDayTests/PraisePhrasesTests.swift`
240
241**Interfaces:**
242- Consumes: `Round`, `QuestionPicker`, `QuizItem`, `SoundEngine`, `SpeechSynthesizer`, `ProfileStore.record`, `ProfileSession.current`.
243- Produces:
244 - `nonisolated struct PraisePhrases { static let all: [String]; mutating func next(using rng: inout some RandomNumberGenerator) -> String }`. At least 8 phrases ("Great job!", "You got it!", "Super!", "Way to go!", ...). Never returns the same phrase twice in a row. `static func correction(for name: String) -> String` returns `"That's \(name)! Try again."`.
245 - `struct CelebrationOverlay: View { init(isActive: Bool) }`: confetti burst in Canvas/TimelineView, about 1 s. With `accessibilityReduceMotion`, a static sparkle that fades instead.
246 - `struct RoundView<Choice: View>: View { init(items: [QuizItem], picker: QuestionPicker, @ViewBuilder choice: @escaping (QuizItem) -> Choice) }`. It speaks `current.prompt` on appear and on each new question, with a large replay-prompt button. On a tap it records via `ProfileStore.record` (skipped for `.ignored`). Correct: `SoundEngine.play(.success)`, overlay, speak praise, then `advance()` after 1.5 s. Incorrect: `.gentleMiss`, speak the correction, and that choice dims briefly. When finished it shows a "You did it!" screen with the mascot placeholder: it plays `.roundComplete`, speaks "You did it!", and offers a big "Play again" button plus back navigation.
247 - `struct MascotView: View { enum Mood { case idle, cheering }; init(mood: Mood) }`: placeholder (simple face in a circle), replaced in part 6.
248
249- [ ] **Step 1:** Write failing tests: `neverRepeatsConsecutively` (500 draws with seeded rng), `atLeastEightPhrases`, `correctionCopy` (`correction(for: "Thursday") == "That's Thursday! Try again."`).
250- [ ] **Step 2:** Run `-only-testing:DayByDayTests/PraisePhrasesTests`. Expected: FAIL.
251- [ ] **Step 3:** Implement `PraisePhrases.swift`, `CelebrationOverlay.swift`, `MascotView` (in `DayByDay/Mascot/MascotView.swift`), and `RoundView.swift`.
252- [ ] **Step 4:** Run it. Expected: PASS. In the simulator, with a temporary preview using `Category.days.quizItems` and `DayCard`-styled choices: rapid taps after a correct answer don't double-record; with Settings › Accessibility › Motion › Reduce Motion on, confetti doesn't fly.
253- [ ] **Step 5:** Commit: `feat: add celebration and round view` with `Ref #N`.
254
255### Task 8: Profile picker, setup, and parent area
256
257**Files:**
258- Create: `DayByDay/Profiles/ProfilePickerView.swift`, `DayByDay/Profiles/ProfileEditorView.swift`, `DayByDay/Parent/ParentAreaView.swift`
259
260**Interfaces:**
261- Consumes: `ProfileSession`, `ProfileStore`, `ParentGateView`, `AvatarAnimal`, `ProfileColor`.
262- Produces:
263 - `ProfilePickerView`: a grid of large avatar tiles on the profile color. Tapping one speaks "Hi, <name>!" and calls `session.select`. A small grown-ups button opens `ParentGateView` → `ParentAreaView`.
264 - `ProfileEditorView(profile: Profile?)`: name field, avatar grid, color swatches, optional birthday (month and day pickers, day range limited by month). Shows the `ProfileError` message inline.
265 - `ParentAreaView`: lists profiles with add, edit, and delete (delete asks for confirmation). Calls `session.profilesChanged()` after any change.
266 - The setup screen is `ParentGateView` → `ProfileEditorView(profile: nil)`, preceded by a short parent-facing line ("Set up a profile for your child").
267
268- [ ] **Step 1:** Build: `xcodebuild build -project DayByDay.xcodeproj -scheme DayByDay -destination 'platform=iOS Simulator,name=iPhone 16 Pro'`. Expected: `BUILD SUCCEEDED`.
269- [ ] **Step 2:** In the simulator, check: create two profiles; the picker speaks the name; delete the current profile from the parent area → picker; delete all → setup.
270- [ ] **Step 3:** Commit: `feat: add profile picker, editor, and parent area` with `Ref #N`.
271
272### Task 9: Home and topic hubs
273
274**Files:**
275- Create: `DayByDay/Home/HomeView.swift`, `DayByDay/Home/TodayBanner.swift`, `DayByDay/Home/CategoryHubView.swift`
276- Modify: `DayByDay/ContentView.swift` (routing by `session.screen`; keep `Category`, `CategoryTile`, `VoiceTipOverlay`), `DayByDay/DayByDayApp.swift` (model container, `ProfileSession` in the environment, scenePhase → `didEnterBackground`/`willEnterForeground`)
277
278**Interfaces:**
279- Consumes: everything above.
280- Produces:
281 - `TodayBanner`: `MascotView(mood: .idle)`, "Today is <day>!" and the date; tapping opens the existing `TodayView`.
282 - `HomeView`: `TodayBanner`, then a `LazyVGrid` of `CategoryTile` over `Category.gridCases`. Current avatar button in the top-trailing corner opens the picker. "Voice Quality Tips" button kept.
283 - `CategoryHubView(category:)`: large activity buttons, laid out the same way for every topic. Part 1 ships "Look and listen" (opens the existing per-category view). It has slots for "Find it!" (part 2) and the topic's special game (parts 3–4), hidden until those exist. Tapping a button also speaks its label.
284 - `ContentView` switches on `session.screen`: `.setup` → setup flow, `.picker` → `ProfilePickerView`, `.home` → `HomeView` in the existing `NavigationStack`.
285
286- [ ] **Step 1:** Build (same command as Task 8). Expected: `BUILD SUCCEEDED`.
287- [ ] **Step 2:** Run the full suite: `xcodebuild test -project DayByDay.xcodeproj -scheme DayByDay -destination 'platform=iOS Simulator,name=iPhone 16 Pro'`. Expected: `** TEST SUCCEEDED **`.
288- [ ] **Step 3:** In the simulator (iPhone, then an iPad simulator, portrait and landscape), check: home shows the banner and 11 topics; a topic opens the hub; "Look and listen" shows the old cards and they still speak. Background the app for more than 10 minutes (`xcrun simctl` to advance, or temporarily lower the constant) with two profiles → picker on return.
289- [ ] **Step 4:** Commit: `feat: add home banner and topic hubs` with `Ref #N`.
290
291### Task 10: Art/sound review, MR, merge
292
293- [ ] **Step 1:** Dispatch a fresh reviewer agent to review the art and sound in this branch: `SoundSynth` output (render each effect to a WAV in the scratchpad and inspect the waveform and spectrum), `CelebrationOverlay`, `MascotView` placeholder, avatars and colors, plus simulator screenshots. Block on clear defects (clipping, harsh or startling sound, unrecognizable drawing, poor contrast). Taste comments are advisory; after two rounds, note what's unresolved for the MR description.
294- [ ] **Step 2:** Fix blocking findings and rerun the full suite. Expected: `** TEST SUCCEEDED **`.
295- [ ] **Step 3:** Push and open the MR:
296
297```bash
298git push -u origin feat/foundation
299gitbay mr create --source feat/foundation --target main --title "Part 1: foundation" --file - <<'EOF'
300Profiles with parent gate, answer log, synthesized sound effects, celebration, question engine and rounds, home banner with topic hubs, unit test target.
301
302Closes #N
303EOF
304```
305
306- [ ] **Step 4:** Check CI with `gitbay build list` and `gitbay build log <n>` if present. When green, merge with `gitbay mr merge <mr> --strategy squash`, then `git checkout main && git pull && git branch -d feat/foundation && git push origin --delete feat/foundation`.
docs/superpowers/specs/2026-10-16-learning-games-design.md added +205
@@ -0,0 +1,205 @@
1# Learning games, Today routine, and profiles
2
3## Intent
4
5DayByDay is an offline iOS/iPadOS app for ages 4–5. Today every category is a
6grid of cards that speak one word when tapped. Children lose interest because
7nothing asks them anything, nothing reacts to what they do, and nothing changes
8between visits. This work turns each topic into something the child plays:
9questions with feedback, ordering games for the topics that are about sequence,
10richer cards, a daily routine with a sticker calendar, a mascot, and a review
11loop that favors what the child gets wrong.
12
13## Goals
14
15- Every topic (the 11 grid categories; Today moves to the banner) has a "Find it!" question game.
16- Days, months, seasons and numbers teach order and quantity, not just names.
17- Each card does more than say its label (sound, fact, or an interaction).
18- A short daily routine on Today that children want to repeat, with a visible
19 record (sticker calendar).
20- Separate profiles for siblings on one device.
21- Question selection adapts to each child's misses; parents can see progress.
22
23## Non-goals
24
25- Camera, microphone, speech recognition, or parent-recorded voice. Deferred to
26 a later round.
27- iCloud sync or any network use. Profiles and progress stay on the device.
28- Localization beyond en-US.
29- New categories.
30
31## Anti-goals
32
33These would make the work a failure even if it functions:
34
35- Streak loss, guilt messaging, timers, loot boxes, or any mechanic designed to
36 extend sessions. Rounds end with a clear "You did it!".
37- Punishing wrong answers: no buzzer, no red X, no lost points.
38- Anything that requires reading to use. Every prompt is spoken; every choice is
39 a picture, color, or symbol.
40- Ads, accounts, analytics, network calls.
41- Third-party assets with unclear licenses.
42
43## Constraints
44
45- SwiftUI. The app target's effective deployment target is iOS 17.5 (the
46 project-level setting is 26.2; the README says iOS 26). Use only APIs
47 available on 17.5, or raise the target in a separate, stated change.
48- Some sources live at the repo root and are added to the target individually;
49 `DayByDay/` is a file-system-synchronized group. New files go under
50 `DayByDay/` so they are picked up automatically.
51- Speech uses the existing `SpeechSynthesizer` (AVSpeechSynthesizer, best en-US
52 voice, rate 0.4). It triggers a haptic on every `speak()`.
53- Large tap targets; works in portrait and landscape on iPhone and iPad.
54- All art and sound is made in code: SwiftUI shapes and SF Symbols for visuals,
55 sounds synthesized at runtime (e.g. AVAudioEngine tone/noise generation). No
56 bundled image or audio files beyond the existing app icon.
57- Every MR that adds or changes art or sound gets a review by a separate
58 reviewer agent focused on art and sound quality, before the MR is opened.
59- Repo is on gitbay. One MR per part below, branched from `main`, never pushed
60 to `main` directly.
61
62## Decided by the user
63
64- All seven parts below are in scope (camera, microphone, and parent voice
65 excluded).
66- All art and sound is generated in code, with an art/sound reviewer agent.
67- Profiles per sibling.
68- Data stays on device; no sync.
69- Navigation option C: home shows the mascot and today's routine on top, then
70 the topic grid. Tapping a topic opens a hub with large activity buttons:
71 "Look and listen" (the existing cards), "Find it!", and that topic's special
72 game. Same hub layout for every topic.
73- Each part's MR is merged once its tests and the art/sound review pass; no
74 wait for a human review between parts.
75- Item sets in existing categories may be revised (added, removed, swapped)
76 where it makes the games work, e.g. Animals gains animals with recognizable
77 sounds (cow, duck, sheep, pig) in place of ones without (ant, lizard).
78
79## The parts, in build order
80
81### 1. Foundation
82
83- **Profiles.** SwiftData model on device. A profile has a display name, an
84 avatar (an animal drawn from SF Symbols / shapes), a color, an optional
85 birthday (month and day), and per-day pictures (step 5). At launch, if more
86 than one profile exists, show a picker of large avatar tiles; tapping one
87 speaks "Hi, <name>!". With exactly one profile, skip the picker. On first
88 launch, create one profile through a short parent-facing setup (behind the
89 parent gate). No cap on profile count.
90- **Parent gate.** Press-and-hold for about 2 seconds, then answer a simple sum
91 shown as text. Protects profile management and, later, the progress screen.
92- **Answer log.** Every answer a child gives is recorded: profile, category,
93 item identifier, correct or not, timestamp. All later progress features read
94 from this log.
95- **Celebration.** One reusable overlay for correct answers: confetti
96 animation, a generated cheerful sound, a spoken praise phrase chosen from a
97 varied list, and the existing haptic. Wrong answers get a soft generated sound
98 and a spoken correction ("That's Thursday! Try again.").
99- **Question engine.** A shared model: a spoken prompt, a set of choices, which
100 choice is correct, and a way to render a choice. Each category exposes its
101 items through a common protocol. The engine picks questions (uniformly at
102 random in this step) and runs a round of about 5 questions ending with a
103 "You did it!" screen.
104- **Sound engine.** Runtime-synthesized sound effects shared by everything that
105 follows.
106- **Home and hubs (option C).** Restructure `ContentView`: a Today banner with
107 the mascot placeholder at the top, then the topic grid. Each topic opens a
108 hub with "Look and listen", "Find it!", and a slot for the topic's special
109 game (hidden until that game exists). Today itself is reached via the banner,
110 not a grid tile.
111- **Tests.** Add a unit test target. Cover the question engine, answer logging,
112 and profile CRUD.
113
114### 2. Question games (all 12 categories)
115
116- **Find it!** "Can you find <item>?" with 3–4 choices on screen (number grows
117 with correct answers in a round).
118- **Odd one out.** Where items have a natural grouping (food: fruit vs
119 vegetable; animals: pets vs wild or land vs water; shapes: round vs pointy;
120 weather: hot vs cold). Only for categories where the grouping is unambiguous.
121- **Listen and pick.** A generated sound or a spoken clue, child picks the
122 card. Animals (animal sound), weather (rain, wind, thunder), letters (letter
123 sound), numbers (that many beeps).
124
125### 3. Ordering and quantity games
126
127- **Week train.** Seven train cars, shuffled; the child drags them into order.
128 Also "What comes after Monday?" as a single-question variant.
129- **Year wheel.** Months around a wheel with seasons as colored sections. Child
130 spins it and is asked to find a month or a season; or places a month in its
131 season.
132- **Yesterday / today / tomorrow.** Three slots, child drags day cards in.
133- **Counting.** Tap objects to count them aloud; show the numeral beside the
134 dots. "Which pile has more?" comparison.
135
136### 4. Richer cards
137
138Inside "Look and listen", tapping a card does more than say its name:
139
140- Animals: generated animal sound plus one short fact.
141- Letters: letter name, letter sound, and an example word ("B… buh… ball").
142- Colors: a mixing activity (red + yellow → orange) as the Colors special game.
143- Shapes and letters: finger tracing with a path check.
144- Weather: dress a character for the weather (special game); shake the device
145 on the weather screen to make it rain (Core Motion).
146- Food: build a plate, or sort into fruit and vegetable bins (special game).
147- Body: "Touch your nose!" movement prompts the child acts out; the app waits,
148 then cheers.
149
150### 5. Today routine
151
152- A short spoken script the child taps through: "Today is Friday. Yesterday was
153 Thursday. Tomorrow is Saturday. It's October. It's Fall." Then the child
154 picks today's weather from picture choices.
155- Finishing the routine places a sticker on that day in a month calendar page.
156 One sticker per day per profile. Past months are browsable.
157- Personal lines when they apply: the child's name in the greeting, "Your
158 birthday is in May!" in the birthday month, "Today is your birthday!" on the
159 day.
160- Day pictures: a parent assigns a symbol to a weekday for a child (swim,
161 grandma, school). It appears on that day's card and in the routine ("Today is
162 swim day!").
163
164### 6. Mascot
165
166A single character drawn in SwiftUI shapes, with a few states: idle, asking,
167cheering, puzzled (on wrong answers), waving. It hosts the Today banner, asks
168questions in games, and appears in the celebration overlay. Replace the
169placeholder from step 1.
170
171### 7. Adaptive review and parent screen
172
173- The question engine weights items by recent misses per profile, so missed
174 items come up more often until answered correctly a few times.
175- Parent screen (behind the gate): per child, per category, which items are
176 known and which are still being missed, in plain terms ("Knows all the days.
177 Still mixing up June, July, August.").
178
179## Calls made without the user
180
181- **Switching profiles.** The home screen shows the current child's avatar in
182 a corner; tapping it (no gate) opens the profile picker. The picker also
183 appears when the app returns to the foreground after 10 or more minutes in
184 the background. Answers and stickers always go to the profile shown in that
185 corner.
186- **Art/sound review.** A rejection for a clear defect (clipping, harsh or
187 startling sound, unrecognizable drawing, poor contrast) blocks the MR until
188 fixed. Taste-level comments are advisory; after two rounds, remaining
189 disagreements are noted in the MR description for the user.
190- **Week order and wording.** Weeks start on Sunday, matching `DayOfWeek`. The
191 season is "Fall", matching the existing code.
192- **Weather in the routine.** Any weather choice is accepted; it is
193 self-report, not a quiz.
194
195## Left to the builder
196
197- Exact SwiftData schema, protocol names, and file layout.
198- Confetti and mascot visual design, sound synthesis approach, praise phrase
199 list, and animal facts, subject to the art/sound review.
200- Exact number of choices and round length (start around 3–4 choices and 5
201 questions).
202- Which categories get odd-one-out and listen-and-pick, within the rules above.
203- How "known" is defined for the adaptive weighting and the parent screen.
204- Whether existing per-category card views are refactored onto a shared
205 card component, as long as each change stays within the step that needs it.
scripts/add-test-target.rb added +39
@@ -0,0 +1,39 @@
1# Adds the DayByDayTests unit test target and a shared DayByDay scheme.
2require 'xcodeproj'
3
4project_path = File.expand_path('../DayByDay.xcodeproj', __dir__)
5project = Xcodeproj::Project.open(project_path)
6app = project.targets.find { |t| t.name == 'DayByDay' }
7abort 'DayByDayTests already exists' if project.targets.any? { |t| t.name == 'DayByDayTests' }
8
9tests = project.new_target(:unit_test_bundle, 'DayByDayTests', :ios, '17.5')
10tests.add_dependency(app)
11
12group = project.new(Xcodeproj::Project::Object::PBXFileSystemSynchronizedRootGroup)
13group.path = 'DayByDayTests'
14group.source_tree = '<group>'
15project.main_group.children << group
16tests.file_system_synchronized_groups ||= []
17tests.file_system_synchronized_groups << group
18
19tests.build_configurations.each do |config|
20 s = config.build_settings
21 s['TEST_HOST'] = '$(BUILT_PRODUCTS_DIR)/DayByDay.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/DayByDay'
22 s['BUNDLE_LOADER'] = '$(TEST_HOST)'
23 s['PRODUCT_BUNDLE_IDENTIFIER'] = "#{app.build_configurations.first.build_settings['PRODUCT_BUNDLE_IDENTIFIER']}.tests"
24 s['PRODUCT_NAME'] = '$(TARGET_NAME)'
25 s['GENERATE_INFOPLIST_FILE'] = 'YES'
26 s['SWIFT_VERSION'] = '5.0'
27 s['TARGETED_DEVICE_FAMILY'] = '1,2'
28 s['SWIFT_APPROACHABLE_CONCURRENCY'] = 'YES'
29 s['SWIFT_DEFAULT_ACTOR_ISOLATION'] = 'MainActor'
30 s['DEVELOPMENT_TEAM'] = app.build_configurations.first.build_settings['DEVELOPMENT_TEAM']
31 s['CODE_SIGN_STYLE'] = 'Automatic'
32end
33
34project.save
35
36scheme = Xcodeproj::XCScheme.new
37scheme.configure_with_targets(app, tests)
38scheme.test_action.code_coverage_enabled = false
39scheme.save_as(project_path, 'DayByDay', true)