Open source CapCut alternative.
TypeScript
feat(ios): Donkey Cut iOS app for recording and viewing on iPhone and iPad
David Le257e37972646
diff --git a/.gitignore b/.gitignoreindex d6b65b0f..8f513855 100644--- a/.gitignore+++ b/.gitignore@@ -24,3 +24,6 @@ __pycache__/## Project policy# Keep Package.resolved tracked for reproducible dependency resolution.++# iOS app local build config (deployment OAuth ids)+apps/ios/Config/Donkey.local.xcconfigdiff --git a/apps/ios/Config/Donkey.local.xcconfig.example b/apps/ios/Config/Donkey.local.xcconfig.examplenew file mode 100644index 00000000..1b4e7675--- /dev/null+++ b/apps/ios/Config/Donkey.local.xcconfig.example@@ -0,0 +1,5 @@+// Copy this file to Donkey.local.xcconfig and fill in the iOS OAuth client+// from your Google Cloud project. The reversed id is the same value with its+// dot-segments reversed, as shown on the client's detail page.+GOOGLE_IOS_CLIENT_ID = 1234567890-abcdef.apps.googleusercontent.com+GOOGLE_IOS_REVERSED_CLIENT_ID = com.googleusercontent.apps.1234567890-abcdefdiff --git a/apps/ios/Config/Donkey.xcconfig b/apps/ios/Config/Donkey.xcconfignew file mode 100644index 00000000..90cf2574--- /dev/null+++ b/apps/ios/Config/Donkey.xcconfig@@ -0,0 +1,10 @@+// Build-time configuration for the Donkey iOS app.+//+// The Google iOS OAuth client id identifies a deployment, so it stays out of+// the open-source tree: copy Donkey.local.xcconfig.example to+// Donkey.local.xcconfig (gitignored) and fill in your values. Without it the+// app builds and runs; the Google button reports sign-in as not configured.+GOOGLE_IOS_CLIENT_ID =+GOOGLE_IOS_REVERSED_CLIENT_ID = donkey-google-signin-unset++#include? "Donkey.local.xcconfig"diff --git a/apps/ios/Donkey.xcodeproj/project.pbxproj b/apps/ios/Donkey.xcodeproj/project.pbxprojnew file mode 100644index 00000000..141552af--- /dev/null+++ b/apps/ios/Donkey.xcodeproj/project.pbxproj@@ -0,0 +1,346 @@+// !$*UTF8*$!+{+ archiveVersion = 1;+ classes = {+ };+ objectVersion = 77;+ objects = {++/* Begin PBXBuildFile section */+ A100000100000000000000B1 /* DonkeyKitModels in Frameworks */ = {isa = PBXBuildFile; productRef = A100001100000000000000B1 /* DonkeyKitModels */; };+ A100000200000000000000B1 /* DonkeyKitUI in Frameworks */ = {isa = PBXBuildFile; productRef = A100001200000000000000B1 /* DonkeyKitUI */; };+ A100000300000000000000B1 /* GoogleSignIn in Frameworks */ = {isa = PBXBuildFile; productRef = A100001300000000000000B1 /* GoogleSignIn */; };+/* End PBXBuildFile section */++/* Begin PBXFileReference section */+ A100002100000000000000B1 /* Donkey.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Donkey.app; sourceTree = BUILT_PRODUCTS_DIR; };+ A100002200000000000000B1 /* Donkey.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = Donkey.xcconfig; path = Config/Donkey.xcconfig; sourceTree = "<group>"; };+/* End PBXFileReference section */++/* Begin PBXFileSystemSynchronizedBuildFileExceptionSet section */+ A100003100000000000000B1 /* Exceptions for "Donkey" folder in "Donkey" target */ = {+ isa = PBXFileSystemSynchronizedBuildFileExceptionSet;+ membershipExceptions = (+ Info.plist,+ );+ target = A100004100000000000000B1 /* Donkey */;+ };+/* End PBXFileSystemSynchronizedBuildFileExceptionSet section */++/* Begin PBXFileSystemSynchronizedRootGroup section */+ A100003200000000000000B1 /* Donkey */ = {+ isa = PBXFileSystemSynchronizedRootGroup;+ exceptions = (+ A100003100000000000000B1 /* Exceptions for "Donkey" folder in "Donkey" target */,+ );+ path = Donkey;+ sourceTree = "<group>";+ };+/* End PBXFileSystemSynchronizedRootGroup section */++/* Begin PBXFrameworksBuildPhase section */+ A100005100000000000000B1 /* Frameworks */ = {+ isa = PBXFrameworksBuildPhase;+ buildActionMask = 2147483647;+ files = (+ A100000100000000000000B1 /* DonkeyKitModels in Frameworks */,+ A100000200000000000000B1 /* DonkeyKitUI in Frameworks */,+ A100000300000000000000B1 /* GoogleSignIn in Frameworks */,+ );+ runOnlyForDeploymentPostprocessing = 0;+ };+/* End PBXFrameworksBuildPhase section */++/* Begin PBXGroup section */+ A100006100000000000000B1 = {+ isa = PBXGroup;+ children = (+ A100003200000000000000B1 /* Donkey */,+ A100002200000000000000B1 /* Donkey.xcconfig */,+ A100006200000000000000B1 /* Products */,+ );+ sourceTree = "<group>";+ };+ A100006200000000000000B1 /* Products */ = {+ isa = PBXGroup;+ children = (+ A100002100000000000000B1 /* Donkey.app */,+ );+ name = Products;+ sourceTree = "<group>";+ };+/* End PBXGroup section */++/* Begin PBXNativeTarget section */+ A100004100000000000000B1 /* Donkey */ = {+ isa = PBXNativeTarget;+ buildConfigurationList = A100007100000000000000B1 /* Build configuration list for PBXNativeTarget "Donkey" */;+ buildPhases = (+ A100005200000000000000B1 /* Sources */,+ A100005100000000000000B1 /* Frameworks */,+ A100005300000000000000B1 /* Resources */,+ );+ buildRules = (+ );+ dependencies = (+ );+ fileSystemSynchronizedGroups = (+ A100003200000000000000B1 /* Donkey */,+ );+ name = Donkey;+ packageProductDependencies = (+ A100001100000000000000B1 /* DonkeyKitModels */,+ A100001200000000000000B1 /* DonkeyKitUI */,+ A100001300000000000000B1 /* GoogleSignIn */,+ );+ productName = Donkey;+ productReference = A100002100000000000000B1 /* Donkey.app */;+ productType = "com.apple.product-type.application";+ };+/* End PBXNativeTarget section */++/* Begin PBXProject section */+ A100008100000000000000B1 /* Project object */ = {+ isa = PBXProject;+ attributes = {+ BuildIndependentTargetsInParallel = 1;+ LastSwiftUpdateCheck = 2600;+ LastUpgradeCheck = 2600;+ TargetAttributes = {+ A100004100000000000000B1 = {+ CreatedOnToolsVersion = 26.0;+ };+ };+ };+ buildConfigurationList = A100007200000000000000B1 /* Build configuration list for PBXProject "Donkey" */;+ developmentRegion = en;+ hasScannedForEncodings = 0;+ knownRegions = (+ en,+ Base,+ );+ mainGroup = A100006100000000000000B1;+ minimizedProjectReferenceProxies = 1;+ packageReferences = (+ A100009100000000000000B1 /* XCLocalSwiftPackageReference "DonkeyKit" */,+ A100009200000000000000B1 /* XCRemoteSwiftPackageReference "GoogleSignIn-iOS" */,+ );+ preferredProjectObjectVersion = 77;+ productRefGroup = A100006200000000000000B1 /* Products */;+ projectDirPath = "";+ projectRoot = "";+ targets = (+ A100004100000000000000B1 /* Donkey */,+ );+ };+/* End PBXProject section */++/* Begin PBXResourcesBuildPhase section */+ A100005300000000000000B1 /* Resources */ = {+ isa = PBXResourcesBuildPhase;+ buildActionMask = 2147483647;+ files = (+ );+ runOnlyForDeploymentPostprocessing = 0;+ };+/* End PBXResourcesBuildPhase section */++/* Begin PBXSourcesBuildPhase section */+ A100005200000000000000B1 /* Sources */ = {+ isa = PBXSourcesBuildPhase;+ buildActionMask = 2147483647;+ files = (+ );+ runOnlyForDeploymentPostprocessing = 0;+ };+/* End PBXSourcesBuildPhase section */++/* Begin XCBuildConfiguration section */+ A10000A100000000000000B1 /* Debug */ = {+ isa = XCBuildConfiguration;+ buildSettings = {+ ALWAYS_SEARCH_USER_PATHS = NO;+ COPY_PHASE_STRIP = NO;+ DEBUG_INFORMATION_FORMAT = dwarf;+ ENABLE_STRICT_OBJC_MSGSEND = YES;+ ENABLE_TESTABILITY = YES;+ ENABLE_USER_SCRIPT_SANDBOXING = YES;+ GCC_C_LANGUAGE_STANDARD = gnu17;+ GCC_DYNAMIC_NO_PIC = NO;+ GCC_NO_COMMON_BLOCKS = YES;+ GCC_OPTIMIZATION_LEVEL = 0;+ GCC_PREPROCESSOR_DEFINITIONS = (+ "DEBUG=1",+ "$(inherited)",+ );+ IPHONEOS_DEPLOYMENT_TARGET = 26.0;+ LOCALIZATION_PREFERS_STRING_CATALOGS = YES;+ MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;+ MTL_FAST_MATH = YES;+ ONLY_ACTIVE_ARCH = YES;+ SDKROOT = iphoneos;+ SWIFT_ACTIVE_COMPILATION_CONDITIONS = "DEBUG $(inherited)";+ SWIFT_APPROACHABLE_CONCURRENCY = YES;+ SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor;+ SWIFT_OPTIMIZATION_LEVEL = "-Onone";+ SWIFT_VERSION = 6.0;+ };+ name = Debug;+ };+ A10000A200000000000000B1 /* Release */ = {+ isa = XCBuildConfiguration;+ buildSettings = {+ ALWAYS_SEARCH_USER_PATHS = NO;+ COPY_PHASE_STRIP = NO;+ DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";+ ENABLE_NS_ASSERTIONS = NO;+ ENABLE_STRICT_OBJC_MSGSEND = YES;+ ENABLE_USER_SCRIPT_SANDBOXING = YES;+ GCC_C_LANGUAGE_STANDARD = gnu17;+ GCC_NO_COMMON_BLOCKS = YES;+ IPHONEOS_DEPLOYMENT_TARGET = 26.0;+ LOCALIZATION_PREFERS_STRING_CATALOGS = YES;+ MTL_ENABLE_DEBUG_INFO = NO;+ MTL_FAST_MATH = YES;+ SDKROOT = iphoneos;+ SWIFT_APPROACHABLE_CONCURRENCY = YES;+ SWIFT_COMPILATION_MODE = wholemodule;+ SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor;+ SWIFT_VERSION = 6.0;+ VALIDATE_PRODUCT = YES;+ };+ name = Release;+ };+ A10000A300000000000000B1 /* Debug */ = {+ isa = XCBuildConfiguration;+ baseConfigurationReference = A100002200000000000000B1 /* Donkey.xcconfig */;+ buildSettings = {+ ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;+ ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;+ CODE_SIGN_ENTITLEMENTS = Donkey/Donkey.entitlements;+ CODE_SIGN_STYLE = Automatic;+ CURRENT_PROJECT_VERSION = 1;+ DEVELOPMENT_TEAM = Q593LLEXEN;+ GENERATE_INFOPLIST_FILE = YES;+ INFOPLIST_FILE = Donkey/Info.plist;+ INFOPLIST_KEY_CFBundleDisplayName = Donkey;+ INFOPLIST_KEY_ITSAppUsesNonExemptEncryption = NO;+ INFOPLIST_KEY_NSCameraUsageDescription = "Donkey Cut uses the camera to record your videos.";+ INFOPLIST_KEY_NSMicrophoneUsageDescription = "Donkey Cut uses the microphone to record audio with your videos.";+ INFOPLIST_KEY_NSPhotoLibraryAddUsageDescription = "Donkey saves videos you choose to your photo library.";+ INFOPLIST_KEY_UIApplicationSceneManifest_Generation = YES;+ INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents = YES;+ INFOPLIST_KEY_UILaunchScreen_Generation = YES;+ INFOPLIST_KEY_UISupportedInterfaceOrientations = "UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight";+ "INFOPLIST_KEY_UISupportedInterfaceOrientations[sdk=iphoneos*]" = "UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight";+ INFOPLIST_KEY_UISupportedInterfaceOrientations_iPad = "UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight";+ LD_RUNPATH_SEARCH_PATHS = (+ "$(inherited)",+ "@executable_path/Frameworks",+ );+ MARKETING_VERSION = 0.1.0;+ PRODUCT_BUNDLE_IDENTIFIER = com.donkeycut.donkeycut;+ PRODUCT_NAME = "$(TARGET_NAME)";+ SUPPORTED_PLATFORMS = "iphoneos iphonesimulator";+ SUPPORTS_MACCATALYST = NO;+ SWIFT_EMIT_LOC_STRINGS = YES;+ TARGETED_DEVICE_FAMILY = "1,2";+ };+ name = Debug;+ };+ A10000A400000000000000B1 /* Release */ = {+ isa = XCBuildConfiguration;+ baseConfigurationReference = A100002200000000000000B1 /* Donkey.xcconfig */;+ buildSettings = {+ ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;+ ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;+ CODE_SIGN_ENTITLEMENTS = Donkey/Donkey.entitlements;+ CODE_SIGN_STYLE = Automatic;+ CURRENT_PROJECT_VERSION = 1;+ DEVELOPMENT_TEAM = Q593LLEXEN;+ GENERATE_INFOPLIST_FILE = YES;+ INFOPLIST_FILE = Donkey/Info.plist;+ INFOPLIST_KEY_CFBundleDisplayName = Donkey;+ INFOPLIST_KEY_ITSAppUsesNonExemptEncryption = NO;+ INFOPLIST_KEY_NSCameraUsageDescription = "Donkey Cut uses the camera to record your videos.";+ INFOPLIST_KEY_NSMicrophoneUsageDescription = "Donkey Cut uses the microphone to record audio with your videos.";+ INFOPLIST_KEY_NSPhotoLibraryAddUsageDescription = "Donkey saves videos you choose to your photo library.";+ INFOPLIST_KEY_UIApplicationSceneManifest_Generation = YES;+ INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents = YES;+ INFOPLIST_KEY_UILaunchScreen_Generation = YES;+ INFOPLIST_KEY_UISupportedInterfaceOrientations = "UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight";+ "INFOPLIST_KEY_UISupportedInterfaceOrientations[sdk=iphoneos*]" = "UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight";+ INFOPLIST_KEY_UISupportedInterfaceOrientations_iPad = "UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight";+ LD_RUNPATH_SEARCH_PATHS = (+ "$(inherited)",+ "@executable_path/Frameworks",+ );+ MARKETING_VERSION = 0.1.0;+ PRODUCT_BUNDLE_IDENTIFIER = com.donkeycut.donkeycut;+ PRODUCT_NAME = "$(TARGET_NAME)";+ SUPPORTED_PLATFORMS = "iphoneos iphonesimulator";+ SUPPORTS_MACCATALYST = NO;+ SWIFT_EMIT_LOC_STRINGS = YES;+ TARGETED_DEVICE_FAMILY = "1,2";+ };+ name = Release;+ };+/* End XCBuildConfiguration section */++/* Begin XCConfigurationList section */+ A100007100000000000000B1 /* Build configuration list for PBXNativeTarget "Donkey" */ = {+ isa = XCConfigurationList;+ buildConfigurations = (+ A10000A300000000000000B1 /* Debug */,+ A10000A400000000000000B1 /* Release */,+ );+ defaultConfigurationIsVisible = 0;+ defaultConfigurationName = Release;+ };+ A100007200000000000000B1 /* Build configuration list for PBXProject "Donkey" */ = {+ isa = XCConfigurationList;+ buildConfigurations = (+ A10000A100000000000000B1 /* Debug */,+ A10000A200000000000000B1 /* Release */,+ );+ defaultConfigurationIsVisible = 0;+ defaultConfigurationName = Release;+ };+/* End XCConfigurationList section */++/* Begin XCLocalSwiftPackageReference section */+ A100009100000000000000B1 /* XCLocalSwiftPackageReference "DonkeyKit" */ = {+ isa = XCLocalSwiftPackageReference;+ relativePath = DonkeyKit;+ };+/* End XCLocalSwiftPackageReference section */++/* Begin XCRemoteSwiftPackageReference section */+ A100009200000000000000B1 /* XCRemoteSwiftPackageReference "GoogleSignIn-iOS" */ = {+ isa = XCRemoteSwiftPackageReference;+ repositoryURL = "https://github.com/google/GoogleSignIn-iOS";+ requirement = {+ kind = upToNextMajorVersion;+ minimumVersion = 8.0.0;+ };+ };+/* End XCRemoteSwiftPackageReference section */++/* Begin XCSwiftPackageProductDependency section */+ A100001100000000000000B1 /* DonkeyKitModels */ = {+ isa = XCSwiftPackageProductDependency;+ productName = DonkeyKitModels;+ };+ A100001200000000000000B1 /* DonkeyKitUI */ = {+ isa = XCSwiftPackageProductDependency;+ productName = DonkeyKitUI;+ };+ A100001300000000000000B1 /* GoogleSignIn */ = {+ isa = XCSwiftPackageProductDependency;+ package = A100009200000000000000B1 /* XCRemoteSwiftPackageReference "GoogleSignIn-iOS" */;+ productName = GoogleSignIn;+ };+/* End XCSwiftPackageProductDependency section */+ };+ rootObject = A100008100000000000000B1 /* Project object */;+}diff --git a/apps/ios/Donkey.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/apps/ios/Donkey.xcodeproj/project.xcworkspace/contents.xcworkspacedatanew file mode 100644index 00000000..919434a6--- /dev/null+++ b/apps/ios/Donkey.xcodeproj/project.xcworkspace/contents.xcworkspacedata@@ -0,0 +1,7 @@+<?xml version="1.0" encoding="UTF-8"?>+<Workspace+ version = "1.0">+ <FileRef+ location = "self:">+ </FileRef>+</Workspace>diff --git a/apps/ios/Donkey.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/apps/ios/Donkey.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolvednew file mode 100644index 00000000..6312368a--- /dev/null+++ b/apps/ios/Donkey.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved@@ -0,0 +1,78 @@+{+ "originHash" : "11dd482ce2f2037fe7863a62eca421b9a7c46f9619339fe207982150a07fca36",+ "pins" : [+ {+ "identity" : "app-check",+ "kind" : "remoteSourceControl",+ "location" : "https://github.com/google/app-check.git",+ "state" : {+ "revision" : "3e33dd27dd4c69bd81c7c81fe61d8ccf58846902",+ "version" : "11.3.1"+ }+ },+ {+ "identity" : "appauth-ios",+ "kind" : "remoteSourceControl",+ "location" : "https://github.com/openid/AppAuth-iOS.git",+ "state" : {+ "revision" : "2781038865a80e2c425a1da12cc1327bcd56501f",+ "version" : "1.7.6"+ }+ },+ {+ "identity" : "googlesignin-ios",+ "kind" : "remoteSourceControl",+ "location" : "https://github.com/google/GoogleSignIn-iOS",+ "state" : {+ "revision" : "65fb3f1aa6ffbfdc79c4e22178a55cd91561f5e9",+ "version" : "8.0.0"+ }+ },+ {+ "identity" : "googleutilities",+ "kind" : "remoteSourceControl",+ "location" : "https://github.com/google/GoogleUtilities.git",+ "state" : {+ "revision" : "9f183ae842be978784f2963a343682e0c46d8fb3",+ "version" : "8.1.2"+ }+ },+ {+ "identity" : "gtm-session-fetcher",+ "kind" : "remoteSourceControl",+ "location" : "https://github.com/google/gtm-session-fetcher.git",+ "state" : {+ "revision" : "a2ab612cb980066ee56d90d60d8462992c07f24b",+ "version" : "3.5.0"+ }+ },+ {+ "identity" : "gtmappauth",+ "kind" : "remoteSourceControl",+ "location" : "https://github.com/google/GTMAppAuth.git",+ "state" : {+ "revision" : "5d7d66f647400952b1758b230e019b07c0b4b22a",+ "version" : "4.1.1"+ }+ },+ {+ "identity" : "interop-ios-for-google-sdks",+ "kind" : "remoteSourceControl",+ "location" : "https://github.com/google/interop-ios-for-google-sdks.git",+ "state" : {+ "revision" : "040d087ac2267d2ddd4cca36c757d1c6a05fdbfe",+ "version" : "101.0.0"+ }+ },+ {+ "identity" : "promises",+ "kind" : "remoteSourceControl",+ "location" : "https://github.com/google/promises.git",+ "state" : {+ "revision" : "f4a19a3c313dc2616c70bb49d29a799fb16be837",+ "version" : "2.4.1"+ }+ }+ ],+ "version" : 3+}diff --git a/apps/ios/Donkey.xcodeproj/xcshareddata/xcschemes/Donkey.xcscheme b/apps/ios/Donkey.xcodeproj/xcshareddata/xcschemes/Donkey.xcschemenew file mode 100644index 00000000..8a12da02--- /dev/null+++ b/apps/ios/Donkey.xcodeproj/xcshareddata/xcschemes/Donkey.xcscheme@@ -0,0 +1,77 @@+<?xml version="1.0" encoding="UTF-8"?>+<Scheme+ LastUpgradeVersion = "2600"+ version = "1.7">+ <BuildAction+ parallelizeBuildables = "YES"+ buildImplicitDependencies = "YES">+ <BuildActionEntries>+ <BuildActionEntry+ buildForTesting = "YES"+ buildForRunning = "YES"+ buildForProfiling = "YES"+ buildForArchiving = "YES"+ buildForAnalyzing = "YES">+ <BuildableReference+ BuildableIdentifier = "primary"+ BlueprintIdentifier = "A100004100000000000000B1"+ BuildableName = "Donkey.app"+ BlueprintName = "Donkey"+ ReferencedContainer = "container:Donkey.xcodeproj">+ </BuildableReference>+ </BuildActionEntry>+ </BuildActionEntries>+ </BuildAction>+ <TestAction+ buildConfiguration = "Debug"+ selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"+ selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"+ shouldUseLaunchSchemeArgsEnv = "YES"+ shouldAutocreateTestPlan = "YES">+ </TestAction>+ <LaunchAction+ buildConfiguration = "Debug"+ selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"+ selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"+ launchStyle = "0"+ useCustomWorkingDirectory = "NO"+ ignoresPersistentStateOnLaunch = "NO"+ debugDocumentVersioning = "YES"+ debugServiceExtension = "internal"+ allowLocationSimulation = "YES">+ <BuildableProductRunnable+ runnableDebuggingMode = "0">+ <BuildableReference+ BuildableIdentifier = "primary"+ BlueprintIdentifier = "A100004100000000000000B1"+ BuildableName = "Donkey.app"+ BlueprintName = "Donkey"+ ReferencedContainer = "container:Donkey.xcodeproj">+ </BuildableReference>+ </BuildableProductRunnable>+ </LaunchAction>+ <ProfileAction+ buildConfiguration = "Release"+ shouldUseLaunchSchemeArgsEnv = "YES"+ savedToolIdentifier = ""+ useCustomWorkingDirectory = "NO"+ debugDocumentVersioning = "YES">+ <BuildableProductRunnable+ runnableDebuggingMode = "0">+ <BuildableReference+ BuildableIdentifier = "primary"+ BlueprintIdentifier = "A100004100000000000000B1"+ BuildableName = "Donkey.app"+ BlueprintName = "Donkey"+ ReferencedContainer = "container:Donkey.xcodeproj">+ </BuildableReference>+ </BuildableProductRunnable>+ </ProfileAction>+ <AnalyzeAction+ buildConfiguration = "Debug">+ </AnalyzeAction>+ <ArchiveAction+ buildConfiguration = "Release"+ revealArchiveInOrganizer = "YES">+ </ArchiveAction>+</Scheme>diff --git a/apps/ios/Donkey/Assets.xcassets/AccentColor.colorset/Contents.json b/apps/ios/Donkey/Assets.xcassets/AccentColor.colorset/Contents.jsonnew file mode 100644index 00000000..c6f897e1--- /dev/null+++ b/apps/ios/Donkey/Assets.xcassets/AccentColor.colorset/Contents.json@@ -0,0 +1,12 @@+{+ "colors" : [+ {+ "color" : {+ "color-space" : "srgb",+ "components" : { "alpha" : "1.000", "blue" : "0x60", "green" : "0x1B", "red" : "0xD8" }+ },+ "idiom" : "universal"+ }+ ],+ "info" : { "author" : "xcode", "version" : 1 }+}diff --git a/apps/ios/Donkey/Assets.xcassets/AppIcon.appiconset/AppIcon.png b/apps/ios/Donkey/Assets.xcassets/AppIcon.appiconset/AppIcon.pngnew file mode 100644index 00000000..1f9c8987Binary files /dev/null and b/apps/ios/Donkey/Assets.xcassets/AppIcon.appiconset/AppIcon.png differdiff --git a/apps/ios/Donkey/Assets.xcassets/AppIcon.appiconset/Contents.json b/apps/ios/Donkey/Assets.xcassets/AppIcon.appiconset/Contents.jsonnew file mode 100644index 00000000..6ee0f251--- /dev/null+++ b/apps/ios/Donkey/Assets.xcassets/AppIcon.appiconset/Contents.json@@ -0,0 +1,11 @@+{+ "images" : [+ {+ "filename" : "AppIcon.png",+ "idiom" : "universal",+ "platform" : "ios",+ "size" : "1024x1024"+ }+ ],+ "info" : { "author" : "xcode", "version" : 1 }+}diff --git a/apps/ios/Donkey/Assets.xcassets/Contents.json b/apps/ios/Donkey/Assets.xcassets/Contents.jsonnew file mode 100644index 00000000..d8b757af--- /dev/null+++ b/apps/ios/Donkey/Assets.xcassets/Contents.json@@ -0,0 +1,3 @@+{+ "info" : { "author" : "xcode", "version" : 1 }+}diff --git a/apps/ios/Donkey/Assets.xcassets/GoogleG.imageset/Contents.json b/apps/ios/Donkey/Assets.xcassets/GoogleG.imageset/Contents.jsonnew file mode 100644index 00000000..668f5a6e--- /dev/null+++ b/apps/ios/Donkey/Assets.xcassets/GoogleG.imageset/Contents.json@@ -0,0 +1,6 @@+{+ "images" : [+ { "filename" : "GoogleG.png", "idiom" : "universal" }+ ],+ "info" : { "author" : "xcode", "version" : 1 }+}diff --git a/apps/ios/Donkey/Assets.xcassets/GoogleG.imageset/GoogleG.png b/apps/ios/Donkey/Assets.xcassets/GoogleG.imageset/GoogleG.pngnew file mode 100644index 00000000..6044f159Binary files /dev/null and b/apps/ios/Donkey/Assets.xcassets/GoogleG.imageset/GoogleG.png differdiff --git a/apps/ios/Donkey/Controllers/AuthController.swift b/apps/ios/Donkey/Controllers/AuthController.swiftnew file mode 100644index 00000000..13dae224--- /dev/null+++ b/apps/ios/Donkey/Controllers/AuthController.swift@@ -0,0 +1,245 @@+import AuthenticationServices+import DonkeyKitModels+import Foundation+import GoogleSignIn+import UIKit++enum AuthBackend {+ static let baseURL = URL(string: "https://donkeycut.com")!+ /// The iOS Google OAuth client id, injected at build time from+ /// Config/Donkey.local.xcconfig through Info.plist so the open-source+ /// tree carries no deployment ids. Empty when unconfigured.+ static var googleClientID: String {+ Bundle.main.object(forInfoDictionaryKey: "GIDClientID") as? String ?? ""+ }+}++enum AuthError: LocalizedError {+ case googleNotConfigured+ case missingIdentityToken+ case noPresenter+ case server(String)++ var errorDescription: String? {+ switch self {+ case .googleNotConfigured:+ "Google sign-in isn't configured in this build yet."+ case .missingIdentityToken:+ "The sign-in didn't return an identity token."+ case .noPresenter:+ "No window to present sign-in from."+ case .server(let message):+ message+ }+ }+}++/// Runs the native provider flows and exchanges their ID tokens for a Donkey+/// Cut session (better-auth with the bearer plugin). The session token and+/// profile live in the keychain.+final class AuthController: NSObject, AuthServicing {+ private static let tokenKey = "session-token"+ private static let profileKey = "session-profile"++ private var appleContinuation: CheckedContinuation<(token: String, nonce: String), any Error>?+ private var appleNonce = ""++ // MARK: AuthServicing++ func signIn(with provider: AuthProvider) async throws -> UserProfile {+ let credential: (token: String, nonce: String?)+ switch provider {+ case .google:+ credential = (try await googleIdToken(), nil)+ case .apple:+ let apple = try await appleIdToken()+ credential = (apple.token, apple.nonce)+ }+ let token = try await exchange(provider: provider, idToken: credential.token, nonce: credential.nonce)+ let profile = try await fetchProfile(token: token)+ KeychainStore.save(Data(token.utf8), for: Self.tokenKey)+ if let data = try? JSONEncoder().encode(profile) {+ KeychainStore.save(data, for: Self.profileKey)+ }+ return profile+ }++ func restoreSession() async -> UserProfile? {+ guard let tokenData = KeychainStore.read(Self.tokenKey),+ let token = String(data: tokenData, encoding: .utf8) else { return nil }+ let cached = KeychainStore.read(Self.profileKey)+ .flatMap { try? JSONDecoder().decode(UserProfile.self, from: $0) }+ do {+ let profile = try await fetchProfile(token: token)+ if let data = try? JSONEncoder().encode(profile) {+ KeychainStore.save(data, for: Self.profileKey)+ }+ return profile+ } catch AuthError.server {+ // The backend rejected the session: signed out for real.+ KeychainStore.delete(Self.tokenKey)+ KeychainStore.delete(Self.profileKey)+ return nil+ } catch {+ // Offline: recording and viewing are local, so the cached+ // profile keeps the app usable.+ return cached+ }+ }++ func signOut() async {+ if let tokenData = KeychainStore.read(Self.tokenKey),+ let token = String(data: tokenData, encoding: .utf8) {+ var request = URLRequest(url: AuthBackend.baseURL.appending(path: "/api/auth/sign-out"))+ request.httpMethod = "POST"+ request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")+ request.setValue("application/json", forHTTPHeaderField: "Content-Type")+ request.httpBody = Data("{}".utf8)+ _ = try? await URLSession.shared.data(for: request)+ }+ GIDSignIn.sharedInstance.signOut()+ KeychainStore.delete(Self.tokenKey)+ KeychainStore.delete(Self.profileKey)+ }++ // MARK: Backend exchange++ private func exchange(provider: AuthProvider, idToken: String, nonce: String?) async throws -> String {+ var request = URLRequest(url: AuthBackend.baseURL.appending(path: "/api/auth/sign-in/social"))+ request.httpMethod = "POST"+ request.setValue("application/json", forHTTPHeaderField: "Content-Type")+ var idTokenBody: [String: Any] = ["token": idToken]+ if let nonce { idTokenBody["nonce"] = nonce }+ let body: [String: Any] = [+ "provider": provider.rawValue,+ "idToken": idTokenBody,+ "disableRedirect": true,+ ]+ request.httpBody = try JSONSerialization.data(withJSONObject: body)+ let (data, response) = try await URLSession.shared.data(for: request)+ guard let http = response as? HTTPURLResponse else { throw URLError(.badServerResponse) }+ guard (200..<300).contains(http.statusCode) else {+ throw AuthError.server(Self.serverMessage(from: data, status: http.statusCode))+ }+ guard let token = http.value(forHTTPHeaderField: "set-auth-token"), !token.isEmpty else {+ throw AuthError.server("Sign-in succeeded but no session token was returned.")+ }+ return token+ }++ private func fetchProfile(token: String) async throws -> UserProfile {+ var request = URLRequest(url: AuthBackend.baseURL.appending(path: "/api/auth/get-session"))+ request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")+ let (data, response) = try await URLSession.shared.data(for: request)+ guard let http = response as? HTTPURLResponse else { throw URLError(.badServerResponse) }+ guard (200..<300).contains(http.statusCode) else {+ throw AuthError.server(Self.serverMessage(from: data, status: http.statusCode))+ }+ struct SessionResponse: Decodable {+ struct User: Decodable {+ var id: String+ var name: String?+ var email: String+ }+ var user: User?+ }+ guard let user = try? JSONDecoder().decode(SessionResponse.self, from: data).user else {+ throw AuthError.server("Your session has expired. Sign in again.")+ }+ return UserProfile(id: user.id, name: user.name ?? "", email: user.email)+ }++ private static func serverMessage(from data: Data, status: Int) -> String {+ struct ErrorBody: Decodable { var message: String? }+ if let message = (try? JSONDecoder().decode(ErrorBody.self, from: data))?.message {+ return message+ }+ return "Sign-in failed (\(status))."+ }++ // MARK: Google++ private func googleIdToken() async throws -> String {+ guard !AuthBackend.googleClientID.isEmpty else {+ throw AuthError.googleNotConfigured+ }+ guard let presenter = Self.presentingViewController() else {+ throw AuthError.noPresenter+ }+ GIDSignIn.sharedInstance.configuration = GIDConfiguration(clientID: AuthBackend.googleClientID)+ let result = try await GIDSignIn.sharedInstance.signIn(withPresenting: presenter)+ guard let token = result.user.idToken?.tokenString else {+ throw AuthError.missingIdentityToken+ }+ return token+ }++ private static func presentingViewController() -> UIViewController? {+ UIApplication.shared.connectedScenes+ .compactMap { $0 as? UIWindowScene }+ .flatMap(\.windows)+ .first(where: \.isKeyWindow)?+ .rootViewController+ }++ // MARK: Apple++ private func appleIdToken() async throws -> (token: String, nonce: String) {+ // The backend compares this string to the token's nonce claim, so the+ // request carries it verbatim.+ let nonce = Self.randomNonce()+ appleNonce = nonce+ let request = ASAuthorizationAppleIDProvider().createRequest()+ request.requestedScopes = [.fullName, .email]+ request.nonce = nonce++ return try await withCheckedThrowingContinuation { continuation in+ appleContinuation = continuation+ let controller = ASAuthorizationController(authorizationRequests: [request])+ controller.delegate = self+ controller.presentationContextProvider = self+ controller.performRequests()+ }+ }++ private static func randomNonce() -> String {+ var bytes = [UInt8](repeating: 0, count: 32)+ _ = SecRandomCopyBytes(kSecRandomDefault, bytes.count, &bytes)+ return bytes.map { String(format: "%02x", $0) }.joined()+ }+}++extension AuthController: ASAuthorizationControllerDelegate, ASAuthorizationControllerPresentationContextProviding {+ func authorizationController(+ controller: ASAuthorizationController,+ didCompleteWithAuthorization authorization: ASAuthorization+ ) {+ defer { appleContinuation = nil }+ guard let credential = authorization.credential as? ASAuthorizationAppleIDCredential,+ let tokenData = credential.identityToken,+ let token = String(data: tokenData, encoding: .utf8) else {+ appleContinuation?.resume(throwing: AuthError.missingIdentityToken)+ return+ }+ appleContinuation?.resume(returning: (token, appleNonce))+ }++ func authorizationController(controller: ASAuthorizationController, didCompleteWithError error: any Error) {+ defer { appleContinuation = nil }+ if let authError = error as? ASAuthorizationError, authError.code == .canceled {+ appleContinuation?.resume(throwing: CancellationError())+ } else {+ appleContinuation?.resume(throwing: error)+ }+ }++ func presentationAnchor(for controller: ASAuthorizationController) -> ASPresentationAnchor {+ if let window = Self.presentingViewController()?.view.window {+ return window+ }+ guard let scene = UIApplication.shared.connectedScenes.compactMap({ $0 as? UIWindowScene }).first else {+ preconditionFailure("Sign-in requires a window scene")+ }+ return scene.keyWindow ?? UIWindow(windowScene: scene)+ }+}diff --git a/apps/ios/Donkey/Controllers/CameraController.swift b/apps/ios/Donkey/Controllers/CameraController.swiftnew file mode 100644index 00000000..e86a0bf4--- /dev/null+++ b/apps/ios/Donkey/Controllers/CameraController.swift@@ -0,0 +1,324 @@+import AVFoundation+import DonkeyKitModels+import UIKit++/// Owns the capture side of the camera feature: permission prompts, the+/// engine, and routing engine events into CameraModel state.+final class CameraController: CameraControlling {+ let session: AVCaptureSession+ weak var model: CameraModel?+ var onRecordingFinished: ((URL, TimeInterval, Data?) -> Void)?++ private let engine = CaptureEngine()++ init() {+ session = engine.session+ engine.events = { [weak self] event in+ Task { @MainActor in self?.handle(event) }+ }+ }++ func activate() {+ Task {+ let cameraGranted = await AVCaptureDevice.requestAccess(for: .video)+ _ = await AVCaptureDevice.requestAccess(for: .audio)+ guard cameraGranted else {+ model?.sessionFailed(reason: "Camera access is off.\nAllow camera access in Settings to record.")+ return+ }+ engine.start(facing: model?.facing ?? .front, settings: model?.settings ?? CameraSettings())+ }+ }++ func deactivate() { engine.stop() }+ func setFacing(_ facing: CameraFacing) { engine.set(facing: facing) }+ func setZoom(display: Double) { engine.setZoom(display: display) }+ func setTorch(_ on: Bool) { engine.setTorch(on) }+ func apply(_ settings: CameraSettings) { engine.apply(settings) }+ func startRecording() { engine.startRecording() }+ func stopRecording() { engine.stopRecording() }++ private func handle(_ event: CaptureEngine.Event) {+ switch event {+ case .running(let mapping, let hasTorch, let effective):+ model?.sessionDidStart(zoomMapping: mapping, hasTorch: hasTorch, effective: effective)+ case .failed(let reason):+ model?.sessionFailed(reason: reason)+ case .recordingStarted:+ model?.recordingDidStart()+ case .recordingFinished(let url, let duration, let thumbnail):+ model?.recordingDidFinish()+ onRecordingFinished?(url, duration, thumbnail)+ case .recordingFailed:+ model?.recordingDidFinish()+ }+ }+}++/// All AVFoundation state, confined to one serial queue per Apple's capture+/// guidance. `@unchecked Sendable` is the queue-confinement contract: nothing+/// here is touched off `queue` after init.+private nonisolated final class CaptureEngine: NSObject, AVCaptureFileOutputRecordingDelegate, @unchecked Sendable {+ enum Event: Sendable {+ case running(ZoomMapping, hasTorch: Bool, effective: CameraSettings)+ case failed(reason: String)+ case recordingStarted+ case recordingFinished(URL, TimeInterval, Data?)+ case recordingFailed+ }++ let session = AVCaptureSession()+ var events: (@Sendable (Event) -> Void)?++ private let queue = DispatchQueue(label: "com.donkeycut.donkeycut.capture")+ private let movieOutput = AVCaptureMovieFileOutput()+ private var videoInput: AVCaptureDeviceInput?+ private var facing: CameraFacing = .front+ private var settings = CameraSettings()+ private var zoomMapping = ZoomMapping(wideBase: 1, minDisplay: 1, maxDisplay: 1)++ private static let recordableDimensions: Set<String> = [+ "1280x720", "1920x1080", "2560x1440", "3840x2160",+ ]++ override init() {+ super.init()+ let center = NotificationCenter.default+ center.addObserver(self, selector: #selector(sessionInterrupted), name: AVCaptureSession.wasInterruptedNotification, object: session)+ center.addObserver(self, selector: #selector(sessionResumed), name: AVCaptureSession.interruptionEndedNotification, object: session)+ }++ @objc private func sessionInterrupted() {+ events?(.failed(reason: "Camera paused.\nAnother app is using the camera."))+ }++ @objc private func sessionResumed() {+ queue.async { self.emitRunning() }+ }++ func start(facing: CameraFacing, settings: CameraSettings) {+ queue.async {+ self.settings = settings+ if self.session.inputs.isEmpty {+ self.session.beginConfiguration()+ self.session.sessionPreset = .inputPriority+ if let microphone = AVCaptureDevice.default(for: .audio),+ let input = try? AVCaptureDeviceInput(device: microphone),+ self.session.canAddInput(input) {+ self.session.addInput(input)+ }+ if self.session.canAddOutput(self.movieOutput) {+ self.session.addOutput(self.movieOutput)+ }+ self.session.commitConfiguration()+ }+ self.installCamera(facing: facing)+ if !self.session.isRunning {+ self.session.startRunning()+ }+ self.emitRunning()+ }+ }++ func stop() {+ queue.async {+ if self.movieOutput.isRecording {+ self.movieOutput.stopRecording()+ }+ self.session.stopRunning()+ }+ }++ func set(facing: CameraFacing) {+ queue.async {+ self.installCamera(facing: facing)+ self.emitRunning()+ }+ }++ func setZoom(display: Double) {+ queue.async {+ guard let device = self.videoInput?.device else { return }+ let factor = self.zoomMapping.videoZoomFactor(forDisplay: display)+ do {+ try device.lockForConfiguration()+ device.ramp(toVideoZoomFactor: factor, withRate: 8)+ device.unlockForConfiguration()+ } catch {}+ }+ }++ func setTorch(_ on: Bool) {+ queue.async {+ guard let device = self.videoInput?.device, device.hasTorch else { return }+ do {+ try device.lockForConfiguration()+ device.torchMode = on ? .on : .off+ device.unlockForConfiguration()+ } catch {}+ }+ }++ func apply(_ settings: CameraSettings) {+ queue.async {+ self.settings = settings+ self.applyFormat()+ self.emitRunning()+ }+ }++ func startRecording() {+ queue.async {+ guard !self.movieOutput.isRecording else { return }+ let url = FileManager.default.temporaryDirectory+ .appending(path: UUID().uuidString + ".mov")+ self.movieOutput.startRecording(to: url, recordingDelegate: self)+ }+ }++ func stopRecording() {+ queue.async {+ guard self.movieOutput.isRecording else { return }+ self.movieOutput.stopRecording()+ }+ }++ // MARK: Queue-confined configuration++ private func installCamera(facing: CameraFacing) {+ self.facing = facing+ guard let device = Self.camera(for: facing) else {+ events?(.failed(reason: "No camera available."))+ return+ }+ session.beginConfiguration()+ if let videoInput {+ session.removeInput(videoInput)+ self.videoInput = nil+ }+ guard let input = try? AVCaptureDeviceInput(device: device), session.canAddInput(input) else {+ session.commitConfiguration()+ events?(.failed(reason: "The camera could not be opened."))+ return+ }+ session.addInput(input)+ videoInput = input+ zoomMapping = Self.zoomMapping(for: device)+ session.commitConfiguration()+ applyFormat()+ setZoomImmediate(display: 1)+ }++ private static func camera(for facing: CameraFacing) -> AVCaptureDevice? {+ let position: AVCaptureDevice.Position = facing == .front ? .front : .back+ let types: [AVCaptureDevice.DeviceType] = position == .back+ ? [.builtInTripleCamera, .builtInDualWideCamera, .builtInDualCamera, .builtInWideAngleCamera]+ : [.builtInTrueDepthCamera, .builtInWideAngleCamera]+ return AVCaptureDevice.DiscoverySession(+ deviceTypes: types,+ mediaType: .video,+ position: position+ ).devices.first+ }++ private static func zoomMapping(for device: AVCaptureDevice) -> ZoomMapping {+ let hasUltraWide = device.constituentDevices.contains { $0.deviceType == .builtInUltraWideCamera }+ let wideBase = hasUltraWide+ ? (device.virtualDeviceSwitchOverVideoZoomFactors.first.map { Double(truncating: $0) } ?? 2)+ : 1+ let maxDisplay = min(Double(device.maxAvailableVideoZoomFactor) / wideBase, 8)+ return ZoomMapping(wideBase: wideBase, minDisplay: hasUltraWide ? 0.5 : 1, maxDisplay: max(maxDisplay, 1))+ }++ private func applyFormat() {+ guard let device = videoInput?.device else { return }+ let specs = device.formats.enumerated().compactMap { index, format -> CaptureFormatSpec? in+ let dimensions = CMVideoFormatDescriptionGetDimensions(format.formatDescription)+ guard Self.recordableDimensions.contains("\(dimensions.width)x\(dimensions.height)") else { return nil }+ let maxFrameRate = format.videoSupportedFrameRateRanges.map(\.maxFrameRate).max() ?? 0+ return CaptureFormatSpec(+ index: index,+ width: Int(dimensions.width),+ height: Int(dimensions.height),+ maxFrameRate: maxFrameRate,+ supportsHLG: format.supportedColorSpaces.contains(.HLG_BT2020)+ )+ }+ guard let choice = chooseFormat(from: specs, settings: settings) else { return }+ session.beginConfiguration()+ session.automaticallyConfiguresCaptureDeviceForWideColor = false+ do {+ try device.lockForConfiguration()+ device.activeFormat = device.formats[choice.index]+ let frameDuration = CMTime(value: 1, timescale: CMTimeScale(choice.effective.frameRate.rawValue))+ device.activeVideoMinFrameDuration = frameDuration+ device.activeVideoMaxFrameDuration = frameDuration+ device.activeColorSpace = choice.effective.colorMode == .hdr ? .HLG_BT2020 : .sRGB+ device.unlockForConfiguration()+ } catch {}+ session.commitConfiguration()+ if let connection = movieOutput.connection(with: .video) {+ connection.preferredVideoStabilizationMode = .auto+ let codecs = movieOutput.availableVideoCodecTypes+ if codecs.contains(.hevc) {+ movieOutput.setOutputSettings([AVVideoCodecKey: AVVideoCodecType.hevc], for: connection)+ }+ }+ effectiveSettings = choice.effective+ }++ private var effectiveSettings = CameraSettings()++ private func setZoomImmediate(display: Double) {+ guard let device = videoInput?.device else { return }+ do {+ try device.lockForConfiguration()+ device.videoZoomFactor = zoomMapping.videoZoomFactor(forDisplay: display)+ device.unlockForConfiguration()+ } catch {}+ }++ private func emitRunning() {+ let hasTorch = videoInput?.device.hasTorch ?? false+ events?(.running(zoomMapping, hasTorch: hasTorch, effective: effectiveSettings))+ }++ // MARK: AVCaptureFileOutputRecordingDelegate++ func fileOutput(+ _ output: AVCaptureFileOutput,+ didStartRecordingTo fileURL: URL,+ from connections: [AVCaptureConnection]+ ) {+ events?(.recordingStarted)+ }++ func fileOutput(+ _ output: AVCaptureFileOutput,+ didFinishRecordingTo outputFileURL: URL,+ from connections: [AVCaptureConnection],+ error: (any Error)?+ ) {+ // A stop can report a benign error while still writing a usable file.+ let wroteFile = FileManager.default.fileExists(atPath: outputFileURL.path())+ guard wroteFile else {+ events?(.recordingFailed)+ return+ }+ let events = events+ Task.detached {+ let asset = AVURLAsset(url: outputFileURL)+ let duration = (try? await asset.load(.duration).seconds) ?? 0+ let thumbnail = await Self.thumbnail(for: asset)+ events?(.recordingFinished(outputFileURL, duration, thumbnail))+ }+ }++ private static func thumbnail(for asset: AVURLAsset) async -> Data? {+ let generator = AVAssetImageGenerator(asset: asset)+ generator.appliesPreferredTrackTransform = true+ generator.maximumSize = CGSize(width: 720, height: 720)+ guard let cgImage = try? await generator.image(at: .zero).image else { return nil }+ return UIImage(cgImage: cgImage).jpegData(compressionQuality: 0.8)+ }+}diff --git a/apps/ios/Donkey/Donkey.entitlements b/apps/ios/Donkey/Donkey.entitlementsnew file mode 100644index 00000000..a812db50--- /dev/null+++ b/apps/ios/Donkey/Donkey.entitlements@@ -0,0 +1,10 @@+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>com.apple.developer.applesignin</key>+ <array>+ <string>Default</string>+ </array>+</dict>+</plist>diff --git a/apps/ios/Donkey/DonkeyApp.swift b/apps/ios/Donkey/DonkeyApp.swiftnew file mode 100644index 00000000..2be3ab38--- /dev/null+++ b/apps/ios/Donkey/DonkeyApp.swift@@ -0,0 +1,57 @@+import DonkeyKitModels+import DonkeyKitUI+import SwiftUI++@main+struct DonkeyApp: App {+ @State private var wiring = AppWiring()++ var body: some Scene {+ WindowGroup {+ RootView(+ app: wiring.app,+ ideas: wiring.ideas,+ camera: wiring.camera,+ media: wiring.media,+ projects: wiring.projects,+ auth: wiring.auth+ ) {+ CameraPreviewView(session: wiring.cameraController.session) {+ wiring.camera.toggleRecording()+ }+ }+ }+ }+}++/// Builds the models and controllers once and wires controller events back+/// into model state. App entry stays this thin per docs/guides/swift.md.+@Observable+final class AppWiring {+ let app: AppModel+ let ideas: IdeasModel+ let camera: CameraModel+ let media: MediaModel+ let projects: ProjectsModel+ let auth: AuthModel+ let cameraController: CameraController++ init() {+ // A store that cannot open is a programmer error worth crashing on.+ let store = try! DonkeyStore()+ app = AppModel()+ ideas = IdeasModel(store: store)+ camera = CameraModel()+ media = MediaModel(store: store)+ projects = ProjectsModel()+ auth = AuthModel(service: AuthController())+ cameraController = CameraController()++ cameraController.model = camera+ camera.controller = cameraController+ cameraController.onRecordingFinished = { [media, app] url, duration, thumbnail in+ media.ingest(movieAt: url, duration: duration, thumbnail: thumbnail)+ app.show(toast: "Saved to Library")+ }+ }+}diff --git a/apps/ios/Donkey/Info.plist b/apps/ios/Donkey/Info.plistnew file mode 100644index 00000000..d533d744--- /dev/null+++ b/apps/ios/Donkey/Info.plist@@ -0,0 +1,17 @@+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>GIDClientID</key>+ <string>$(GOOGLE_IOS_CLIENT_ID)</string>+ <key>CFBundleURLTypes</key>+ <array>+ <dict>+ <key>CFBundleURLSchemes</key>+ <array>+ <string>$(GOOGLE_IOS_REVERSED_CLIENT_ID)</string>+ </array>+ </dict>+ </array>+</dict>+</plist>diff --git a/apps/ios/Donkey/PrivacyInfo.xcprivacy b/apps/ios/Donkey/PrivacyInfo.xcprivacynew file mode 100644index 00000000..729308f0--- /dev/null+++ b/apps/ios/Donkey/PrivacyInfo.xcprivacy@@ -0,0 +1,60 @@+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>NSPrivacyTracking</key>+ <false/>+ <key>NSPrivacyTrackingDomains</key>+ <array/>+ <key>NSPrivacyCollectedDataTypes</key>+ <array>+ <dict>+ <key>NSPrivacyCollectedDataType</key>+ <string>NSPrivacyCollectedDataTypeEmailAddress</string>+ <key>NSPrivacyCollectedDataTypeLinked</key>+ <true/>+ <key>NSPrivacyCollectedDataTypeTracking</key>+ <false/>+ <key>NSPrivacyCollectedDataTypePurposes</key>+ <array>+ <string>NSPrivacyCollectedDataTypePurposeAppFunctionality</string>+ </array>+ </dict>+ <dict>+ <key>NSPrivacyCollectedDataType</key>+ <string>NSPrivacyCollectedDataTypeName</string>+ <key>NSPrivacyCollectedDataTypeLinked</key>+ <true/>+ <key>NSPrivacyCollectedDataTypeTracking</key>+ <false/>+ <key>NSPrivacyCollectedDataTypePurposes</key>+ <array>+ <string>NSPrivacyCollectedDataTypePurposeAppFunctionality</string>+ </array>+ </dict>+ <dict>+ <key>NSPrivacyCollectedDataType</key>+ <string>NSPrivacyCollectedDataTypeUserID</string>+ <key>NSPrivacyCollectedDataTypeLinked</key>+ <true/>+ <key>NSPrivacyCollectedDataTypeTracking</key>+ <false/>+ <key>NSPrivacyCollectedDataTypePurposes</key>+ <array>+ <string>NSPrivacyCollectedDataTypePurposeAppFunctionality</string>+ </array>+ </dict>+ </array>+ <key>NSPrivacyAccessedAPITypes</key>+ <array>+ <dict>+ <key>NSPrivacyAccessedAPIType</key>+ <string>NSPrivacyAccessedAPICategoryUserDefaults</string>+ <key>NSPrivacyAccessedAPITypeReasons</key>+ <array>+ <string>CA92.1</string>+ </array>+ </dict>+ </array>+</dict>+</plist>diff --git a/apps/ios/Donkey/Support/CameraPreviewView.swift b/apps/ios/Donkey/Support/CameraPreviewView.swiftnew file mode 100644index 00000000..41d3646c--- /dev/null+++ b/apps/ios/Donkey/Support/CameraPreviewView.swift@@ -0,0 +1,50 @@+import AVFoundation+import AVKit+import DonkeyKitModels+import SwiftUI+import UIKit++/// SwiftUI has no native capture preview; this hosts an+/// AVCaptureVideoPreviewLayer and attaches the hardware capture events+/// (volume buttons, Camera Control) to the record action.+struct CameraPreviewView: UIViewRepresentable {+ let session: AVCaptureSession+ let onCaptureEvent: () -> Void++ func makeUIView(context: Context) -> PreviewHostView {+ let view = PreviewHostView()+ view.previewLayer.session = session+ view.previewLayer.videoGravity = .resizeAspectFill++ let interaction = AVCaptureEventInteraction { event in+ guard event.phase == .ended else { return }+ context.coordinator.onCaptureEvent()+ }+ view.addInteraction(interaction)+ return view+ }++ func updateUIView(_ uiView: PreviewHostView, context: Context) {+ context.coordinator.onCaptureEvent = onCaptureEvent+ }++ func makeCoordinator() -> Coordinator {+ Coordinator(onCaptureEvent: onCaptureEvent)+ }++ final class Coordinator {+ var onCaptureEvent: () -> Void++ init(onCaptureEvent: @escaping () -> Void) {+ self.onCaptureEvent = onCaptureEvent+ }+ }++ final class PreviewHostView: UIView {+ override static var layerClass: AnyClass { AVCaptureVideoPreviewLayer.self }++ var previewLayer: AVCaptureVideoPreviewLayer {+ layer as! AVCaptureVideoPreviewLayer+ }+ }+}diff --git a/apps/ios/Donkey/Support/KeychainStore.swift b/apps/ios/Donkey/Support/KeychainStore.swiftnew file mode 100644index 00000000..cd5e928c--- /dev/null+++ b/apps/ios/Donkey/Support/KeychainStore.swift@@ -0,0 +1,43 @@+import Foundation+import Security++/// Minimal generic-password keychain access for the session token and the+/// cached profile.+enum KeychainStore {+ private static let service = "com.donkeycut.donkeycut"++ static func save(_ data: Data, for key: String) {+ let query: [String: Any] = [+ kSecClass as String: kSecClassGenericPassword,+ kSecAttrService as String: service,+ kSecAttrAccount as String: key,+ ]+ SecItemDelete(query as CFDictionary)+ var attributes = query+ attributes[kSecValueData as String] = data+ attributes[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlock+ SecItemAdd(attributes as CFDictionary, nil)+ }++ static func read(_ key: String) -> Data? {+ let query: [String: Any] = [+ kSecClass as String: kSecClassGenericPassword,+ kSecAttrService as String: service,+ kSecAttrAccount as String: key,+ kSecReturnData as String: true,+ kSecMatchLimit as String: kSecMatchLimitOne,+ ]+ var result: AnyObject?+ guard SecItemCopyMatching(query as CFDictionary, &result) == errSecSuccess else { return nil }+ return result as? Data+ }++ static func delete(_ key: String) {+ let query: [String: Any] = [+ kSecClass as String: kSecClassGenericPassword,+ kSecAttrService as String: service,+ kSecAttrAccount as String: key,+ ]+ SecItemDelete(query as CFDictionary)+ }+}diff --git a/apps/ios/DonkeyKit/Package.swift b/apps/ios/DonkeyKit/Package.swiftnew file mode 100644index 00000000..78f984ad--- /dev/null+++ b/apps/ios/DonkeyKit/Package.swift@@ -0,0 +1,31 @@+// swift-tools-version: 6.2+import PackageDescription++// DonkeyKitModels holds observable product state, repositories, and pure+// capture math; it imports Foundation and SwiftData only. DonkeyKitUI renders+// that state and emits typed intents; it never reaches into the app target's+// controllers. Both default to main-actor isolation per docs/guides/swift.md.+let package = Package(+ name: "DonkeyKit",+ platforms: [.iOS(.v26), .macOS(.v26)],+ products: [+ .library(name: "DonkeyKitModels", targets: ["DonkeyKitModels"]),+ .library(name: "DonkeyKitUI", targets: ["DonkeyKitUI"]),+ ],+ targets: [+ .target(+ name: "DonkeyKitModels",+ swiftSettings: [.defaultIsolation(MainActor.self)]+ ),+ .target(+ name: "DonkeyKitUI",+ dependencies: ["DonkeyKitModels"],+ swiftSettings: [.defaultIsolation(MainActor.self)]+ ),+ .testTarget(+ name: "DonkeyKitModelsTests",+ dependencies: ["DonkeyKitModels"],+ swiftSettings: [.defaultIsolation(MainActor.self)]+ ),+ ]+)diff --git a/apps/ios/DonkeyKit/Sources/DonkeyKitModels/AppModel.swift b/apps/ios/DonkeyKit/Sources/DonkeyKitModels/AppModel.swiftnew file mode 100644index 00000000..fd8a93a7--- /dev/null+++ b/apps/ios/DonkeyKit/Sources/DonkeyKitModels/AppModel.swift@@ -0,0 +1,34 @@+import Foundation++nonisolated public enum AppTab: Hashable, Sendable {+ case ideas, media, projects, camera+}++nonisolated public enum AppearancePreference: String, CaseIterable, Sendable {+ case system, light, dark+}++@Observable+public final class AppModel {+ public var selectedTab: AppTab = .ideas++ public var appearance: AppearancePreference {+ didSet { defaults.set(appearance.rawValue, forKey: Self.appearanceKey) }+ }++ /// A transient confirmation message ("Note saved"), cleared by the UI.+ public var toast: String?++ private let defaults: UserDefaults+ private static let appearanceKey = "appearancePreference"++ public init(defaults: UserDefaults = .standard) {+ self.defaults = defaults+ appearance = defaults.string(forKey: Self.appearanceKey)+ .flatMap(AppearancePreference.init(rawValue:)) ?? .system+ }++ public func show(toast message: String) {+ toast = message+ }+}diff --git a/apps/ios/DonkeyKit/Sources/DonkeyKitModels/AuthModel.swift b/apps/ios/DonkeyKit/Sources/DonkeyKitModels/AuthModel.swiftnew file mode 100644index 00000000..b91cd5b4--- /dev/null+++ b/apps/ios/DonkeyKit/Sources/DonkeyKitModels/AuthModel.swift@@ -0,0 +1,87 @@+import Foundation++nonisolated public struct UserProfile: Equatable, Codable, Sendable {+ public var id: String+ public var name: String+ public var email: String++ public init(id: String, name: String, email: String) {+ self.id = id+ self.name = name+ self.email = email+ }++ public var initial: String {+ let source = name.isEmpty ? email : name+ return source.first.map { String($0).uppercased() } ?? "?"+ }+}++nonisolated public enum AuthProvider: String, Sendable {+ case google, apple+}++/// Native sign-in and session exchange, implemented by the app target's+/// AuthController against the Donkey Cut backend.+public protocol AuthServicing: AnyObject {+ /// Runs the provider's native sign-in flow, exchanges the identity token+ /// for a backend session, and returns the signed-in user.+ func signIn(with provider: AuthProvider) async throws -> UserProfile+ /// The user restored from the stored session, if one exists.+ func restoreSession() async -> UserProfile?+ func signOut() async+}++nonisolated public enum AuthState: Equatable, Sendable {+ case restoring+ case signedOut+ case signingIn(AuthProvider)+ case signedIn(UserProfile)+}++@Observable+public final class AuthModel {+ public private(set) var state: AuthState = .restoring+ public private(set) var lastError: String?++ private let service: any AuthServicing++ public init(service: any AuthServicing) {+ self.service = service+ }++ public var user: UserProfile? {+ if case .signedIn(let profile) = state { return profile }+ return nil+ }++ public var isSignedIn: Bool { user != nil }++ public func restore() async {+ if let profile = await service.restoreSession() {+ state = .signedIn(profile)+ } else {+ state = .signedOut+ }+ }++ public func signIn(with provider: AuthProvider) async {+ guard case .signedOut = state else { return }+ state = .signingIn(provider)+ lastError = nil+ do {+ let profile = try await service.signIn(with: provider)+ state = .signedIn(profile)+ } catch is CancellationError {+ state = .signedOut+ } catch {+ lastError = error.localizedDescription+ state = .signedOut+ }+ }++ public func signOut() async {+ await service.signOut()+ state = .signedOut+ }+}diff --git a/apps/ios/DonkeyKit/Sources/DonkeyKitModels/CameraModel.swift b/apps/ios/DonkeyKit/Sources/DonkeyKitModels/CameraModel.swiftnew file mode 100644index 00000000..fb0aaaec--- /dev/null+++ b/apps/ios/DonkeyKit/Sources/DonkeyKitModels/CameraModel.swift@@ -0,0 +1,118 @@+import Foundation++/// Commands the camera model sends to whatever owns the capture session.+/// The app target's CameraController conforms; the model never imports+/// AVFoundation.+public protocol CameraControlling: AnyObject {+ func activate()+ func deactivate()+ func setFacing(_ facing: CameraFacing)+ func setZoom(display: Double)+ func setTorch(_ on: Bool)+ func apply(_ settings: CameraSettings)+ func startRecording()+ func stopRecording()+}++nonisolated public enum CameraAvailability: Equatable, Sendable {+ case idle+ case starting+ case running+ case unavailable(reason: String)+}++@Observable+public final class CameraModel {+ public internal(set) var availability: CameraAvailability = .idle+ public private(set) var facing: CameraFacing = .front+ public private(set) var settings = CameraSettings()+ /// What the device could honor for the current request, shown in the badge.+ public private(set) var effectiveSettings = CameraSettings()+ public internal(set) var zoomMapping = ZoomMapping(wideBase: 1, minDisplay: 1, maxDisplay: 1)+ public private(set) var zoom: Double = 1+ public private(set) var isTorchOn = false+ public internal(set) var hasTorch = false+ public internal(set) var recordingStartedAt: Date?+ public var teleprompter = TeleprompterState()++ public var isRecording: Bool { recordingStartedAt != nil }++ public var controller: (any CameraControlling)?++ public init() {}++ // MARK: Intents++ public func appeared() {+ availability = .starting+ controller?.activate()+ }++ public func disappeared() {+ controller?.deactivate()+ availability = .idle+ }++ public func flip() {+ facing = facing.flipped+ zoom = 1+ isTorchOn = false+ controller?.setFacing(facing)+ }++ public func select(zoom display: Double) {+ zoom = display+ controller?.setZoom(display: display)+ }++ public func toggleTorch() {+ isTorchOn.toggle()+ controller?.setTorch(isTorchOn)+ }++ public func update(_ transform: (inout CameraSettings) -> Void) {+ transform(&settings)+ controller?.apply(settings)+ }++ public func toggleRecording() {+ if isRecording {+ controller?.stopRecording()+ } else {+ controller?.startRecording()+ }+ }++ /// Loads a note into the teleprompter and shows the card.+ public func loadTeleprompter(script: String) {+ teleprompter.script = script+ teleprompter.isCardShown = true+ }++ // MARK: Controller events++ public func sessionDidStart(zoomMapping: ZoomMapping, hasTorch: Bool, effective: CameraSettings) {+ self.zoomMapping = zoomMapping+ self.hasTorch = hasTorch+ effectiveSettings = effective+ availability = .running+ }++ public func sessionFailed(reason: String) {+ availability = .unavailable(reason: reason)+ }++ public func recordingDidStart() {+ recordingStartedAt = .now+ }++ public func recordingDidFinish() {+ recordingStartedAt = nil+ }+}++/// Formats a duration as m:ss for the recording timer and duration badges.+nonisolated public func formattedDuration(_ seconds: TimeInterval) -> String {+ let whole = max(0, Int(seconds.rounded(.down)))+ return "\(whole / 60):" + String(format: "%02d", whole % 60)+}diff --git a/apps/ios/DonkeyKit/Sources/DonkeyKitModels/CameraSettings.swift b/apps/ios/DonkeyKit/Sources/DonkeyKitModels/CameraSettings.swiftnew file mode 100644index 00000000..ce03b5f6--- /dev/null+++ b/apps/ios/DonkeyKit/Sources/DonkeyKitModels/CameraSettings.swift@@ -0,0 +1,135 @@+import Foundation++nonisolated public enum CaptureResolution: String, CaseIterable, Codable, Sendable {+ case hd = "HD"+ case qhd = "2K"+ case uhd = "4K"++ public var pixelArea: Int {+ switch self {+ case .hd: 1920 * 1080+ case .qhd: 2560 * 1440+ case .uhd: 3840 * 2160+ }+ }+}++nonisolated public enum CaptureFrameRate: Int, CaseIterable, Codable, Sendable {+ case fps24 = 24+ case fps30 = 30+ case fps60 = 60+}++nonisolated public enum CaptureColorMode: String, CaseIterable, Codable, Sendable {+ case sdr = "SDR"+ case hdr = "HDR"+}++nonisolated public struct CameraSettings: Equatable, Codable, Sendable {+ public var resolution: CaptureResolution+ public var frameRate: CaptureFrameRate+ public var colorMode: CaptureColorMode++ public init(resolution: CaptureResolution = .hd, frameRate: CaptureFrameRate = .fps30, colorMode: CaptureColorMode = .sdr) {+ self.resolution = resolution+ self.frameRate = frameRate+ self.colorMode = colorMode+ }+}++nonisolated public enum CameraFacing: Sendable, Equatable {+ case front, back++ public var flipped: CameraFacing { self == .front ? .back : .front }+}++/// A capture format reduced to the facts selection needs, so the choice is+/// pure and testable. `index` points back into the device's format array.+nonisolated public struct CaptureFormatSpec: Equatable, Sendable {+ public var index: Int+ public var width: Int+ public var height: Int+ public var maxFrameRate: Double+ public var supportsHLG: Bool++ public init(index: Int, width: Int, height: Int, maxFrameRate: Double, supportsHLG: Bool) {+ self.index = index+ self.width = width+ self.height = height+ self.maxFrameRate = maxFrameRate+ self.supportsHLG = supportsHLG+ }++ var area: Int { width * height }+}++nonisolated public struct FormatChoice: Equatable, Sendable {+ public var index: Int+ /// What the device could actually honor, after fallbacks.+ public var effective: CameraSettings+}++/// Picks the device format closest to the requested settings, relaxing one+/// axis at a time when the device can't honor the request: HDR falls back to+/// SDR, an unavailable frame rate falls back through 30 to 24, and resolution+/// snaps to the nearest available area.+nonisolated public func chooseFormat(from specs: [CaptureFormatSpec], settings: CameraSettings) -> FormatChoice? {+ guard !specs.isEmpty else { return nil }++ let frameRateFallbacks: [CaptureFrameRate] = switch settings.frameRate {+ case .fps60: [.fps60, .fps30, .fps24]+ case .fps30: [.fps30, .fps24]+ case .fps24: [.fps24]+ }+ let colorFallbacks: [CaptureColorMode] = settings.colorMode == .hdr ? [.hdr, .sdr] : [.sdr]++ for color in colorFallbacks {+ for frameRate in frameRateFallbacks {+ let candidates = specs.filter { spec in+ spec.maxFrameRate >= Double(frameRate.rawValue)+ && (color == .sdr || spec.supportsHLG)+ }+ guard let best = candidates.min(by: { lhs, rhs in+ let lhsDiff = abs(lhs.area - settings.resolution.pixelArea)+ let rhsDiff = abs(rhs.area - settings.resolution.pixelArea)+ if lhsDiff != rhsDiff { return lhsDiff < rhsDiff }+ return lhs.area < rhs.area+ }) else { continue }+ return FormatChoice(+ index: best.index,+ effective: CameraSettings(resolution: settings.resolution, frameRate: frameRate, colorMode: color)+ )+ }+ }+ return nil+}++/// Maps user-facing zoom factors (0.5×, 1×, 2×…) onto a device's+/// `videoZoomFactor` scale, where 1.0 is the widest constituent camera.+nonisolated public struct ZoomMapping: Equatable, Sendable {+ /// videoZoomFactor that renders the user's 1× (the main wide camera).+ public var wideBase: Double+ public var minDisplay: Double+ public var maxDisplay: Double++ public init(wideBase: Double, minDisplay: Double, maxDisplay: Double) {+ self.wideBase = wideBase+ self.minDisplay = minDisplay+ self.maxDisplay = maxDisplay+ }++ public var options: [Double] {+ [0.5, 1, 2, 3].filter { $0 >= minDisplay && $0 <= maxDisplay }+ }++ public func videoZoomFactor(forDisplay display: Double) -> Double {+ min(max(display, minDisplay), maxDisplay) * wideBase+ }+}++nonisolated public func zoomLabel(_ display: Double) -> String {+ let formatted = display == display.rounded()+ ? String(Int(display))+ : String(display)+ return formatted + "×"+}diff --git a/apps/ios/DonkeyKit/Sources/DonkeyKitModels/DonkeyStore.swift b/apps/ios/DonkeyKit/Sources/DonkeyKitModels/DonkeyStore.swiftnew file mode 100644index 00000000..57f978f9--- /dev/null+++ b/apps/ios/DonkeyKit/Sources/DonkeyKitModels/DonkeyStore.swift@@ -0,0 +1,205 @@+import Foundation+import SwiftData++// Persistence stays at the edge: these SwiftData records never leave this+// file, and the rest of the app talks to the plain structs the repository+// methods return.++@Model+final class NoteRecord {+ @Attribute(.unique) var id: UUID+ var title: String+ var body: String+ var colorIndex: Int+ var createdAt: Date++ init(_ note: Note) {+ id = note.id+ title = note.title+ body = note.body+ colorIndex = note.color.rawValue+ createdAt = note.createdAt+ }++ var note: Note {+ Note(id: id, title: title, body: body, color: NoteColor(rawValue: colorIndex) ?? .butter, createdAt: createdAt)+ }+}++@Model+final class InspirationRecord {+ @Attribute(.unique) var id: UUID+ var linkURL: String?+ var mediaFileName: String?+ var isVideo: Bool+ var createdAt: Date++ init(id: UUID, linkURL: String?, mediaFileName: String?, isVideo: Bool, createdAt: Date) {+ self.id = id+ self.linkURL = linkURL+ self.mediaFileName = mediaFileName+ self.isVideo = isVideo+ self.createdAt = createdAt+ }++ var item: InspirationItem? {+ if let linkURL, let url = URL(string: linkURL) {+ return InspirationItem(id: id, kind: .link(url), createdAt: createdAt)+ }+ if let mediaFileName {+ return InspirationItem(id: id, kind: .media(fileName: mediaFileName, isVideo: isVideo), createdAt: createdAt)+ }+ return nil+ }+}++@Model+final class RecordingRecord {+ @Attribute(.unique) var id: UUID+ var fileName: String+ var thumbnailFileName: String?+ var duration: TimeInterval+ var createdAt: Date++ init(_ recording: Recording) {+ id = recording.id+ fileName = recording.fileName+ thumbnailFileName = recording.thumbnailFileName+ duration = recording.duration+ createdAt = recording.createdAt+ }++ var recording: Recording {+ Recording(id: id, fileName: fileName, thumbnailFileName: thumbnailFileName, duration: duration, createdAt: createdAt)+ }+}++/// One store behind both repository seams: SwiftData for metadata, plain+/// files under Application Support for movie/media bytes.+public final class DonkeyStore: IdeasStoring, RecordingStoring {+ private let container: ModelContainer+ private let context: ModelContext+ private let mediaDirectory: URL+ private let recordingsDirectory: URL++ public init(inMemory: Bool = false) throws {+ let root = try FileManager.default.url(+ for: .applicationSupportDirectory,+ in: .userDomainMask,+ appropriateFor: nil,+ create: true+ )+ mediaDirectory = root.appending(path: "Inspiration", directoryHint: .isDirectory)+ recordingsDirectory = root.appending(path: "Recordings", directoryHint: .isDirectory)+ for directory in [mediaDirectory, recordingsDirectory] {+ try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)+ }+ let schema = Schema([NoteRecord.self, InspirationRecord.self, RecordingRecord.self])+ let configuration = ModelConfiguration(schema: schema, isStoredInMemoryOnly: inMemory)+ container = try ModelContainer(for: schema, configurations: [configuration])+ context = ModelContext(container)+ }++ // MARK: IdeasStoring++ public func loadNotes() throws -> [Note] {+ let descriptor = FetchDescriptor<NoteRecord>(sortBy: [SortDescriptor(\.createdAt, order: .reverse)])+ return try context.fetch(descriptor).map(\.note)+ }++ public func upsert(_ note: Note) throws {+ let id = note.id+ let descriptor = FetchDescriptor<NoteRecord>(predicate: #Predicate { $0.id == id })+ if let existing = try context.fetch(descriptor).first {+ existing.title = note.title+ existing.body = note.body+ existing.colorIndex = note.color.rawValue+ } else {+ context.insert(NoteRecord(note))+ }+ try context.save()+ }++ public func deleteNote(id: UUID) throws {+ try context.delete(model: NoteRecord.self, where: #Predicate { $0.id == id })+ try context.save()+ }++ public func loadInspiration() throws -> [InspirationItem] {+ let descriptor = FetchDescriptor<InspirationRecord>(sortBy: [SortDescriptor(\.createdAt, order: .reverse)])+ return try context.fetch(descriptor).compactMap(\.item)+ }++ public func addLink(_ url: URL) throws -> InspirationItem {+ let record = InspirationRecord(id: UUID(), linkURL: url.absoluteString, mediaFileName: nil, isVideo: false, createdAt: .now)+ context.insert(record)+ try context.save()+ return InspirationItem(id: record.id, kind: .link(url), createdAt: record.createdAt)+ }++ public func addMedia(data: Data, isVideo: Bool) throws -> InspirationItem {+ let id = UUID()+ let fileName = id.uuidString + (isVideo ? ".mov" : ".jpg")+ try data.write(to: mediaDirectory.appending(path: fileName), options: .atomic)+ let record = InspirationRecord(id: id, linkURL: nil, mediaFileName: fileName, isVideo: isVideo, createdAt: .now)+ context.insert(record)+ try context.save()+ return InspirationItem(id: id, kind: .media(fileName: fileName, isVideo: isVideo), createdAt: record.createdAt)+ }++ public func deleteInspiration(id: UUID) throws {+ let descriptor = FetchDescriptor<InspirationRecord>(predicate: #Predicate { $0.id == id })+ if let record = try context.fetch(descriptor).first {+ if let fileName = record.mediaFileName {+ try? FileManager.default.removeItem(at: mediaDirectory.appending(path: fileName))+ }+ context.delete(record)+ try context.save()+ }+ }++ public func mediaURL(fileName: String) -> URL {+ mediaDirectory.appending(path: fileName)+ }++ // MARK: RecordingStoring++ public func loadRecordings() throws -> [Recording] {+ let descriptor = FetchDescriptor<RecordingRecord>(sortBy: [SortDescriptor(\.createdAt, order: .reverse)])+ return try context.fetch(descriptor).map(\.recording)+ }++ public func ingest(movieAt url: URL, duration: TimeInterval, thumbnail: Data?) throws -> Recording {+ let id = UUID()+ let fileName = id.uuidString + "." + (url.pathExtension.isEmpty ? "mov" : url.pathExtension)+ try FileManager.default.moveItem(at: url, to: recordingsDirectory.appending(path: fileName))+ var thumbnailFileName: String?+ if let thumbnail {+ let name = id.uuidString + ".thumb.jpg"+ try thumbnail.write(to: recordingsDirectory.appending(path: name), options: .atomic)+ thumbnailFileName = name+ }+ let recording = Recording(id: id, fileName: fileName, thumbnailFileName: thumbnailFileName, duration: duration)+ context.insert(RecordingRecord(recording))+ try context.save()+ return recording+ }++ public func deleteRecording(_ recording: Recording) throws {+ try? FileManager.default.removeItem(at: movieURL(for: recording))+ if let thumbnailURL = thumbnailURL(for: recording) {+ try? FileManager.default.removeItem(at: thumbnailURL)+ }+ let id = recording.id+ try context.delete(model: RecordingRecord.self, where: #Predicate { $0.id == id })+ try context.save()+ }++ public func movieURL(for recording: Recording) -> URL {+ recordingsDirectory.appending(path: recording.fileName)+ }++ public func thumbnailURL(for recording: Recording) -> URL? {+ recording.thumbnailFileName.map { recordingsDirectory.appending(path: $0) }+ }+}diff --git a/apps/ios/DonkeyKit/Sources/DonkeyKitModels/Ideas.swift b/apps/ios/DonkeyKit/Sources/DonkeyKitModels/Ideas.swiftnew file mode 100644index 00000000..825119e1--- /dev/null+++ b/apps/ios/DonkeyKit/Sources/DonkeyKitModels/Ideas.swift@@ -0,0 +1,191 @@+import Foundation++/// The five note paper colors. Values are sRGB hex strings so models stay+/// Foundation-only; DonkeyKitUI converts them to Colors.+nonisolated public enum NoteColor: Int, CaseIterable, Codable, Sendable {+ case butter, blush, sky, mint, lilac++ public var background: String {+ switch self {+ case .butter: "#faefb6"+ case .blush: "#fbd8d4"+ case .sky: "#d5e8fb"+ case .mint: "#d9f3d6"+ case .lilac: "#e6dcf7"+ }+ }++ public var accent: String {+ switch self {+ case .butter: "#f2c94c"+ case .blush: "#ef8b80"+ case .sky: "#7fb2ef"+ case .mint: "#82cf7a"+ case .lilac: "#a988e0"+ }+ }++ public var next: NoteColor {+ NoteColor(rawValue: (rawValue + 1) % Self.allCases.count) ?? .butter+ }+}++nonisolated public struct Note: Identifiable, Equatable, Sendable {+ public var id: UUID+ public var title: String+ public var body: String+ public var color: NoteColor+ public var createdAt: Date++ public init(id: UUID = UUID(), title: String, body: String, color: NoteColor, createdAt: Date = .now) {+ self.id = id+ self.title = title+ self.body = body+ self.color = color+ self.createdAt = createdAt+ }++ /// The text a teleprompter reads for this note.+ public var script: String { body.isEmpty ? title : body }+}++nonisolated public enum InspirationKind: Equatable, Sendable {+ case link(URL)+ /// Media imported from the photo library, stored as a file the repository owns.+ case media(fileName: String, isVideo: Bool)+}++nonisolated public struct InspirationItem: Identifiable, Equatable, Sendable {+ public var id: UUID+ public var kind: InspirationKind+ public var createdAt: Date++ public init(id: UUID = UUID(), kind: InspirationKind, createdAt: Date = .now) {+ self.id = id+ self.kind = kind+ self.createdAt = createdAt+ }+}++/// Normalizes user-typed inspiration input into a URL, defaulting to https.+nonisolated public func normalizedInspirationURL(_ raw: String) -> URL? {+ let trimmed = raw.trimmingCharacters(in: .whitespacesAndNewlines)+ guard !trimmed.isEmpty else { return nil }+ let withScheme = trimmed.range(of: "^https?://", options: [.regularExpression, .caseInsensitive]) != nil+ ? trimmed+ : "https://" + trimmed+ guard let url = URL(string: withScheme), url.host() != nil else { return nil }+ return url+}++public protocol IdeasStoring: AnyObject {+ func loadNotes() throws -> [Note]+ func upsert(_ note: Note) throws+ func deleteNote(id: UUID) throws+ func loadInspiration() throws -> [InspirationItem]+ func addLink(_ url: URL) throws -> InspirationItem+ func addMedia(data: Data, isVideo: Bool) throws -> InspirationItem+ func deleteInspiration(id: UUID) throws+ /// Absolute location of a stored media file.+ func mediaURL(fileName: String) -> URL+}++nonisolated public enum IdeasFilter: String, CaseIterable, Sendable {+ case all, notes, inspiration+}++@Observable+public final class IdeasModel {+ public private(set) var notes: [Note] = []+ public private(set) var inspiration: [InspirationItem] = []+ public var filter: IdeasFilter = .all++ /// The note open in the editor; nil when the editor is closed.+ public var draft: NoteDraft?++ private let store: any IdeasStoring++ public init(store: any IdeasStoring) {+ self.store = store+ notes = (try? store.loadNotes()) ?? []+ inspiration = (try? store.loadInspiration()) ?? []+ }++ nonisolated public struct NoteDraft: Identifiable, Equatable {+ public var id: UUID+ public var title: String+ public var body: String+ public var color: NoteColor+ public var isNew: Bool++ public var hasContent: Bool {+ !title.trimmingCharacters(in: .whitespaces).isEmpty+ || !body.trimmingCharacters(in: .whitespaces).isEmpty+ }+ }++ public func openEditor(for note: Note? = nil) {+ if let note {+ draft = NoteDraft(id: note.id, title: note.title, body: note.body, color: note.color, isNew: false)+ } else {+ draft = NoteDraft(id: UUID(), title: "", body: "", color: .butter, isNew: true)+ }+ }++ public func cycleDraftColor() {+ guard var draft else { return }+ draft.color = draft.color.next+ self.draft = draft+ }++ /// Saves the open draft. Returns the saved note, or nil when the draft was empty.+ @discardableResult+ public func saveDraft() -> Note? {+ guard let draft, draft.hasContent else { return nil }+ let title = draft.title.trimmingCharacters(in: .whitespaces)+ let body = draft.body.trimmingCharacters(in: .whitespaces)+ let existing = notes.first(where: { $0.id == draft.id })+ let note = Note(+ id: draft.id,+ title: title.isEmpty ? "Untitled" : title,+ body: body,+ color: draft.color,+ createdAt: existing?.createdAt ?? .now+ )+ try? store.upsert(note)+ if let index = notes.firstIndex(where: { $0.id == note.id }) {+ notes[index] = note+ } else {+ notes.insert(note, at: 0)+ }+ self.draft = nil+ return note+ }++ public func closeEditor() { draft = nil }++ public func deleteNote(id: UUID) {+ try? store.deleteNote(id: id)+ notes.removeAll { $0.id == id }+ }++ @discardableResult+ public func addInspiration(urlText: String) -> Bool {+ guard let url = normalizedInspirationURL(urlText),+ let item = try? store.addLink(url) else { return false }+ inspiration.insert(item, at: 0)+ return true+ }++ public func addInspiration(mediaData: Data, isVideo: Bool) {+ guard let item = try? store.addMedia(data: mediaData, isVideo: isVideo) else { return }+ inspiration.insert(item, at: 0)+ }++ public func deleteInspiration(id: UUID) {+ try? store.deleteInspiration(id: id)+ inspiration.removeAll { $0.id == id }+ }++ public func mediaURL(fileName: String) -> URL { store.mediaURL(fileName: fileName) }+}diff --git a/apps/ios/DonkeyKit/Sources/DonkeyKitModels/MediaModel.swift b/apps/ios/DonkeyKit/Sources/DonkeyKitModels/MediaModel.swiftnew file mode 100644index 00000000..e8a62782--- /dev/null+++ b/apps/ios/DonkeyKit/Sources/DonkeyKitModels/MediaModel.swift@@ -0,0 +1,81 @@+import Foundation++nonisolated public struct Recording: Identifiable, Equatable, Sendable {+ public var id: UUID+ public var fileName: String+ public var thumbnailFileName: String?+ public var duration: TimeInterval+ public var createdAt: Date++ public init(id: UUID = UUID(), fileName: String, thumbnailFileName: String?, duration: TimeInterval, createdAt: Date = .now) {+ self.id = id+ self.fileName = fileName+ self.thumbnailFileName = thumbnailFileName+ self.duration = duration+ self.createdAt = createdAt+ }+}++/// Where a clip's bytes live relative to the cloud. Upload is simulated+/// until the cloud clip endpoint exists; the states and badge UI are the+/// supported shape.+nonisolated public enum RecordingSyncState: Equatable, Sendable {+ case onDevice+ case uploading(percent: Int)+ case synced+}++public protocol RecordingStoring: AnyObject {+ func loadRecordings() throws -> [Recording]+ /// Moves a finished movie into the store and persists its metadata.+ func ingest(movieAt url: URL, duration: TimeInterval, thumbnail: Data?) throws -> Recording+ func deleteRecording(_ recording: Recording) throws+ func movieURL(for recording: Recording) -> URL+ func thumbnailURL(for recording: Recording) -> URL?+}++@Observable+public final class MediaModel {+ public private(set) var recordings: [Recording] = []+ private var syncStates: [UUID: RecordingSyncState] = [:]++ private let store: any RecordingStoring++ public init(store: any RecordingStoring) {+ self.store = store+ recordings = (try? store.loadRecordings()) ?? []+ }++ public func syncState(for recording: Recording) -> RecordingSyncState {+ syncStates[recording.id] ?? .onDevice+ }++ public func ingest(movieAt url: URL, duration: TimeInterval, thumbnail: Data?) {+ guard let recording = try? store.ingest(movieAt: url, duration: duration, thumbnail: thumbnail) else { return }+ recordings.insert(recording, at: 0)+ beginUpload(of: recording)+ }++ public func delete(_ recording: Recording) {+ try? store.deleteRecording(recording)+ recordings.removeAll { $0.id == recording.id }+ syncStates[recording.id] = nil+ }++ private func beginUpload(of recording: Recording) {+ syncStates[recording.id] = .uploading(percent: 0)+ Task {+ var percent = 0.0+ while percent < 100 {+ try? await Task.sleep(for: .seconds(0.6))+ guard recordings.contains(where: { $0.id == recording.id }) else { return }+ percent = min(percent + .random(in: 6 ... 22), 100)+ syncStates[recording.id] = .uploading(percent: Int(percent))+ }+ syncStates[recording.id] = .synced+ }+ }++ public func movieURL(for recording: Recording) -> URL { store.movieURL(for: recording) }+ public func thumbnailURL(for recording: Recording) -> URL? { store.thumbnailURL(for: recording) }+}diff --git a/apps/ios/DonkeyKit/Sources/DonkeyKitModels/Projects.swift b/apps/ios/DonkeyKit/Sources/DonkeyKitModels/Projects.swiftnew file mode 100644index 00000000..b5675223--- /dev/null+++ b/apps/ios/DonkeyKit/Sources/DonkeyKitModels/Projects.swift@@ -0,0 +1,54 @@+import Foundation++nonisolated public enum ProjectExport: Equatable, Sendable {+ case none+ case exporting(percent: Int)+ case ready(renderedOn: String)++ public var isExporting: Bool {+ if case .exporting = self { true } else { false }+ }+}++nonisolated public struct Project: Identifiable, Equatable, Sendable {+ public var id: UUID+ public var name: String+ public var duration: TimeInterval+ public var export: ProjectExport++ public init(id: UUID = UUID(), name: String, duration: TimeInterval, export: ProjectExport) {+ self.id = id+ self.name = name+ self.duration = duration+ self.export = export+ }+}++@Observable+public final class ProjectsModel {+ public private(set) var projects: [Project]++ /// Sample projects and a simulated export: the cloud projects API is not+ /// wired up yet, so the tab shows every card state on realistic data.+ public init() {+ projects = [+ Project(name: "6: End of Week Demo", duration: 108, export: .ready(renderedOn: "Aug 18")),+ Project(name: "Pizza", duration: 27, export: .ready(renderedOn: "Aug 15")),+ Project(name: "Animation", duration: 158, export: .exporting(percent: 48)),+ Project(name: "Local project", duration: 0, export: .none),+ ]+ advanceExports()+ }++ private func advanceExports() {+ Task {+ while let index = projects.firstIndex(where: { $0.export.isExporting }) {+ try? await Task.sleep(for: .seconds(0.9))+ guard case .exporting(let percent) = projects[index].export else { continue }+ projects[index].export = percent + 2 >= 100+ ? .ready(renderedOn: "Today")+ : .exporting(percent: percent + 2)+ }+ }+ }+}diff --git a/apps/ios/DonkeyKit/Sources/DonkeyKitModels/Teleprompter.swift b/apps/ios/DonkeyKit/Sources/DonkeyKitModels/Teleprompter.swiftnew file mode 100644index 00000000..cc20d6d5--- /dev/null+++ b/apps/ios/DonkeyKit/Sources/DonkeyKitModels/Teleprompter.swift@@ -0,0 +1,34 @@+import Foundation++nonisolated public struct TeleprompterSettings: Equatable, Codable, Sendable {+ /// Scroll speed in points per second.+ public var speed: Double+ /// Body text size in points.+ public var textSize: Double++ public static let speedRange: ClosedRange<Double> = 10...100+ public static let textSizeRange: ClosedRange<Double> = 16...40++ public init(speed: Double = 40, textSize: Double = 24) {+ self.speed = speed+ self.textSize = textSize+ }+}++nonisolated public struct TeleprompterState: Equatable, Sendable {+ public var script: String = ""+ public var isCardShown = false+ public var settings = TeleprompterSettings()++ public init() {}++ public var hasScript: Bool {+ !script.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty+ }++ /// Vertical offset of the script at `elapsed` seconds into a recording:+ /// text starts 60% down the overlay and scrolls up at the set speed.+ public func scrollOffset(elapsed: TimeInterval, overlayHeight: Double) -> Double {+ overlayHeight * 0.6 - settings.speed * elapsed+ }+}diff --git a/apps/ios/DonkeyKit/Sources/DonkeyKitUI/CameraScreen.swift b/apps/ios/DonkeyKit/Sources/DonkeyKitUI/CameraScreen.swiftnew file mode 100644index 00000000..9d75bde5--- /dev/null+++ b/apps/ios/DonkeyKit/Sources/DonkeyKitUI/CameraScreen.swift@@ -0,0 +1,401 @@+#if os(iOS)+import SwiftUI+import DonkeyKitModels++struct CameraScreen<CameraPreview: View>: View {+ @Bindable var camera: CameraModel+ var ideas: IdeasModel+ let cameraPreview: () -> CameraPreview++ @State private var showsZoomPicker = false+ @State private var showsQualityPopover = false+ @State private var showsTeleSettings = false+ @State private var showsNotePicker = false++ var body: some View {+ ZStack {+ stage+ if camera.isRecording, camera.teleprompter.hasScript {+ TeleprompterOverlay(camera: camera)+ }+ controls+ }+ .background(.black, ignoresSafeAreaEdges: .all)+ .preferredColorScheme(.dark)+ .sheet(isPresented: $showsNotePicker) {+ NotePickerSheet(ideas: ideas) { note in+ camera.loadTeleprompter(script: note.script)+ showsNotePicker = false+ }+ }+ }++ @ViewBuilder private var stage: some View {+ switch camera.availability {+ case .running, .starting:+ cameraPreview()+ .ignoresSafeArea()+ case .idle:+ Color.black.ignoresSafeArea()+ case .unavailable(let reason):+ VStack(spacing: 8) {+ Image(systemName: "video.slash")+ .font(.largeTitle)+ Text(reason)+ .font(.subheadline)+ .multilineTextAlignment(.center)+ }+ .foregroundStyle(.secondary)+ .padding(.horizontal, 40)+ }+ }++ private var controls: some View {+ VStack {+ if camera.isRecording {+ RecordingTimer(camera: camera)+ }+ if camera.teleprompter.isCardShown, !camera.isRecording {+ TeleprompterCard(+ camera: camera,+ showsSettings: $showsTeleSettings,+ onUseNote: { showsNotePicker = true }+ )+ .padding(.horizontal, 16)+ .padding(.top, 4)+ }+ Spacer()+ }+ .overlay(alignment: .leading) { rail }+ .overlay(alignment: .bottom) { recordButton }+ .padding(.top, 8)+ }++ private var rail: some View {+ GlassEffectContainer {+ VStack(spacing: 16) {+ Button {+ showsZoomPicker.toggle()+ showsQualityPopover = false+ } label: {+ Text(zoomLabel(camera.zoom))+ .font(.footnote.weight(.bold))+ .frame(width: 40, height: 40)+ }+ .glassEffect(.regular.interactive())+ .popover(isPresented: $showsZoomPicker, arrowEdge: .leading) {+ zoomPicker.presentationCompactAdaptation(.popover)+ }++ Button {+ camera.teleprompter.isCardShown.toggle()+ } label: {+ Image(systemName: "text.viewfinder")+ .frame(width: 40, height: 40)+ }+ .glassEffect(camera.teleprompter.isCardShown ? .regular.tint(.white.opacity(0.25)).interactive() : .regular.interactive())++ Spacer().frame(height: 10)++ Button {+ camera.toggleTorch()+ } label: {+ Image(systemName: camera.isTorchOn ? "bolt.fill" : "bolt.slash")+ .foregroundStyle(camera.isTorchOn ? .yellow : .white)+ .frame(width: 40, height: 40)+ }+ .glassEffect(.regular.interactive())+ .disabled(!camera.hasTorch)+ .opacity(camera.hasTorch ? 1 : 0.4)++ Button {+ camera.flip()+ } label: {+ Image(systemName: "arrow.trianglehead.2.clockwise.rotate.90.camera")+ .frame(width: 40, height: 40)+ }+ .glassEffect(.regular.interactive())++ Button {+ showsQualityPopover.toggle()+ showsZoomPicker = false+ } label: {+ VStack(spacing: 0) {+ Text(camera.effectiveSettings.resolution.rawValue)+ Text("\(camera.effectiveSettings.frameRate.rawValue)")+ }+ .font(.caption2.weight(.bold))+ .frame(width: 40, height: 40)+ }+ .glassEffect(.regular.interactive())+ .popover(isPresented: $showsQualityPopover, arrowEdge: .leading) {+ qualityPopover.presentationCompactAdaptation(.popover)+ }+ .disabled(camera.isRecording)+ }+ .foregroundStyle(.white)+ }+ .padding(.leading, 14)+ }++ private var zoomPicker: some View {+ VStack(spacing: 4) {+ ForEach(camera.zoomMapping.options.reversed(), id: \.self) { option in+ Button {+ camera.select(zoom: option)+ showsZoomPicker = false+ } label: {+ Text(zoomLabel(option))+ .font(.headline.weight(.bold))+ .frame(width: 72, height: 44)+ .background(+ camera.zoom == option ? AnyShapeStyle(.white) : AnyShapeStyle(.clear),+ in: RoundedRectangle(cornerRadius: 14)+ )+ .foregroundStyle(camera.zoom == option ? .black : .primary)+ }+ .buttonStyle(.plain)+ }+ }+ .padding(10)+ }++ private var qualityPopover: some View {+ VStack(alignment: .leading, spacing: 12) {+ Text("Resolution")+ .font(.footnote)+ .foregroundStyle(.secondary)+ Picker("Resolution", selection: resolutionBinding) {+ ForEach(CaptureResolution.allCases, id: \.self) { Text($0.rawValue).tag($0) }+ }+ .pickerStyle(.segmented)++ Text("Frame Rate")+ .font(.footnote)+ .foregroundStyle(.secondary)+ Picker("Frame Rate", selection: frameRateBinding) {+ ForEach(CaptureFrameRate.allCases, id: \.self) { Text("\($0.rawValue)").tag($0) }+ }+ .pickerStyle(.segmented)++ Text("Color")+ .font(.footnote)+ .foregroundStyle(.secondary)+ Picker("Color", selection: colorBinding) {+ ForEach(CaptureColorMode.allCases, id: \.self) { Text($0.rawValue).tag($0) }+ }+ .pickerStyle(.segmented)+ }+ .padding(16)+ .frame(minWidth: 280)+ }++ private var resolutionBinding: Binding<CaptureResolution> {+ Binding(+ get: { camera.settings.resolution },+ set: { value in camera.update { $0.resolution = value } }+ )+ }++ private var frameRateBinding: Binding<CaptureFrameRate> {+ Binding(+ get: { camera.settings.frameRate },+ set: { value in camera.update { $0.frameRate = value } }+ )+ }++ private var colorBinding: Binding<CaptureColorMode> {+ Binding(+ get: { camera.settings.colorMode },+ set: { value in camera.update { $0.colorMode = value } }+ )+ }++ private var recordButton: some View {+ Button {+ camera.toggleRecording()+ } label: {+ ZStack {+ Circle()+ .fill(.white)+ .frame(width: 84, height: 84)+ RoundedRectangle(cornerRadius: camera.isRecording ? 9 : 34)+ .fill(Color.recordPink)+ .frame(+ width: camera.isRecording ? 34 : 68,+ height: camera.isRecording ? 34 : 68+ )+ }+ .animation(.snappy(duration: 0.2), value: camera.isRecording)+ }+ .buttonStyle(.plain)+ .disabled(camera.availability != .running)+ .opacity(camera.availability == .running ? 1 : 0.5)+ .padding(.bottom, 30)+ .accessibilityLabel(camera.isRecording ? "Stop recording" : "Record")+ }+}++struct RecordingTimer: View {+ var camera: CameraModel++ var body: some View {+ TimelineView(.periodic(from: .now, by: 0.5)) { context in+ if let startedAt = camera.recordingStartedAt {+ Text(formattedDuration(context.date.timeIntervalSince(startedAt)))+ .font(.footnote.weight(.bold))+ .monospacedDigit()+ .foregroundStyle(.white)+ .padding(.horizontal, 14)+ .padding(.vertical, 6)+ .background(Color.recordPink.opacity(0.9), in: Capsule())+ }+ }+ }+}++struct TeleprompterCard: View {+ @Bindable var camera: CameraModel+ @Binding var showsSettings: Bool+ let onUseNote: () -> Void++ var body: some View {+ VStack(alignment: .leading, spacing: 8) {+ HStack {+ Spacer()+ Button {+ camera.teleprompter.isCardShown = false+ } label: {+ Image(systemName: "xmark")+ .font(.subheadline.weight(.bold))+ }+ }+ TextEditor(text: $camera.teleprompter.script)+ .font(.system(size: 19, weight: .semibold))+ .scrollContentBackground(.hidden)+ .frame(minHeight: 96, maxHeight: 160)+ .overlay(alignment: .topLeading) {+ if camera.teleprompter.script.isEmpty {+ Text("Add your script here...")+ .font(.system(size: 19, weight: .semibold))+ .foregroundStyle(.secondary)+ .padding(.top, 8)+ .padding(.leading, 5)+ .allowsHitTesting(false)+ }+ }+ HStack(spacing: 14) {+ Button {+ showsSettings.toggle()+ } label: {+ Image(systemName: "slider.horizontal.3")+ }+ .popover(isPresented: $showsSettings, arrowEdge: .top) {+ TeleprompterSettingsView(camera: camera)+ .presentationCompactAdaptation(.popover)+ }+ Button(action: onUseNote) {+ Image(systemName: "note.text")+ }+ Spacer()+ }+ .font(.body.weight(.semibold))+ }+ .foregroundStyle(.white)+ .padding(14)+ .glassEffect(.regular, in: RoundedRectangle(cornerRadius: 22))+ }+}++struct TeleprompterSettingsView: View {+ @Bindable var camera: CameraModel++ var body: some View {+ VStack(alignment: .leading, spacing: 14) {+ VStack(alignment: .leading, spacing: 6) {+ Text("Teleprompter speed")+ .font(.footnote)+ .foregroundStyle(.secondary)+ Slider(value: $camera.teleprompter.settings.speed, in: TeleprompterSettings.speedRange)+ }+ VStack(alignment: .leading, spacing: 6) {+ Text("Text size")+ .font(.footnote)+ .foregroundStyle(.secondary)+ Slider(value: $camera.teleprompter.settings.textSize, in: TeleprompterSettings.textSizeRange)+ }+ }+ .padding(16)+ .frame(minWidth: 260)+ }+}++struct TeleprompterOverlay: View {+ var camera: CameraModel++ var body: some View {+ GeometryReader { geometry in+ let height = geometry.size.height * 0.42+ TimelineView(.animation) { context in+ let elapsed = camera.recordingStartedAt.map { context.date.timeIntervalSince($0) } ?? 0+ Text(camera.teleprompter.script)+ .font(.system(size: camera.teleprompter.settings.textSize, weight: .heavy))+ .foregroundStyle(.white)+ .lineSpacing(4)+ .frame(maxWidth: .infinity, alignment: .leading)+ .offset(y: camera.teleprompter.scrollOffset(elapsed: elapsed, overlayHeight: height))+ .padding(.horizontal, 24)+ }+ .frame(height: height, alignment: .top)+ .clipped()+ .background(+ LinearGradient(+ colors: [.black.opacity(0.75), .black.opacity(0)],+ startPoint: .top,+ endPoint: .bottom+ )+ .frame(height: height),+ alignment: .top+ )+ }+ .ignoresSafeArea()+ .allowsHitTesting(false)+ }+}++struct NotePickerSheet: View {+ var ideas: IdeasModel+ let onPick: (Note) -> Void++ private let columns = [GridItem(.adaptive(minimum: 150, maximum: 240), spacing: 12)]++ var body: some View {+ NavigationStack {+ Group {+ if ideas.notes.isEmpty {+ Text("No notes yet. Write one in Ideas first.")+ .foregroundStyle(.secondary)+ .padding(24)+ } else {+ ScrollView {+ LazyVGrid(columns: columns, spacing: 12) {+ ForEach(ideas.notes) { note in+ Button {+ onPick(note)+ } label: {+ NoteCard(note: note)+ }+ .buttonStyle(.plain)+ }+ }+ .padding(20)+ }+ }+ }+ .navigationTitle("Use a note")+ .navigationBarTitleDisplayMode(.inline)+ }+ .presentationDetents([.medium, .large])+ }+}+#endifdiff --git a/apps/ios/DonkeyKit/Sources/DonkeyKitUI/Components.swift b/apps/ios/DonkeyKit/Sources/DonkeyKitUI/Components.swiftnew file mode 100644index 00000000..12dc2630--- /dev/null+++ b/apps/ios/DonkeyKit/Sources/DonkeyKitUI/Components.swift@@ -0,0 +1,89 @@+#if os(iOS)+import SwiftUI+import DonkeyKitModels++struct AvatarMenu: View {+ @Bindable var app: AppModel+ var auth: AuthModel++ var body: some View {+ Menu {+ Picker("Appearance", selection: $app.appearance) {+ Text("System").tag(AppearancePreference.system)+ Text("Light").tag(AppearancePreference.light)+ Text("Dark").tag(AppearancePreference.dark)+ }+ .pickerStyle(.menu)+ Divider()+ Button("Log Out", systemImage: "rectangle.portrait.and.arrow.right", role: .destructive) {+ Task { await auth.signOut() }+ }+ } label: {+ Circle()+ .fill(LinearGradient(+ colors: [Color(hex: "#7b8cff"), Color(hex: "#d86bd1")],+ startPoint: .topLeading,+ endPoint: .bottomTrailing+ ))+ .frame(width: 34, height: 34)+ .overlay {+ Text(auth.user?.initial ?? "?")+ .font(.footnote.weight(.bold))+ .foregroundStyle(.white)+ }+ }+ .accessibilityLabel("Profile")+ }+}++struct EmptyState: View {+ let title: String+ let message: String+ var actionTitle: String?+ var action: (() -> Void)?++ var body: some View {+ VStack(spacing: 8) {+ Text(title)+ .font(.title2.weight(.bold))+ Text(message)+ .font(.subheadline)+ .foregroundStyle(.secondary)+ .multilineTextAlignment(.center)+ if let actionTitle, let action {+ Button(actionTitle, action: action)+ .buttonStyle(.borderedProminent)+ .buttonBorderShape(.roundedRectangle(radius: 14))+ .padding(.top, 14)+ }+ }+ .frame(maxWidth: .infinity, minHeight: 320)+ .padding(.horizontal, 36)+ }+}++struct ToastOverlay: View {+ @Bindable var app: AppModel++ var body: some View {+ VStack {+ Spacer()+ if let toast = app.toast {+ Text(toast)+ .font(.footnote.weight(.bold))+ .padding(.horizontal, 18)+ .padding(.vertical, 10)+ .glassEffect()+ .padding(.bottom, 8)+ .transition(.move(edge: .bottom).combined(with: .opacity))+ .task(id: toast) {+ try? await Task.sleep(for: .seconds(1.8))+ app.toast = nil+ }+ }+ }+ .animation(.snappy, value: app.toast)+ .allowsHitTesting(false)+ }+}+#endifdiff --git a/apps/ios/DonkeyKit/Sources/DonkeyKitUI/IdeasScreen.swift b/apps/ios/DonkeyKit/Sources/DonkeyKitUI/IdeasScreen.swiftnew file mode 100644index 00000000..ef8963de--- /dev/null+++ b/apps/ios/DonkeyKit/Sources/DonkeyKitUI/IdeasScreen.swift@@ -0,0 +1,300 @@+#if os(iOS)+import AVKit+import PhotosUI+import SwiftUI+import DonkeyKitModels++struct IdeasScreen: View {+ @Bindable var app: AppModel+ @Bindable var ideas: IdeasModel+ var auth: AuthModel+ let onRecordNote: (Note) -> Void++ @State private var showsInspirationSheet = false++ private let columns = [GridItem(.adaptive(minimum: 160, maximum: 260), spacing: 14)]++ var body: some View {+ NavigationStack {+ ScrollView {+ VStack(alignment: .leading, spacing: 18) {+ filterChips+ content+ }+ .padding(.horizontal, 20)+ .padding(.bottom, 24)+ }+ .navigationTitle("Ideas")+ .toolbar {+ ToolbarItem(placement: .topBarTrailing) {+ AvatarMenu(app: app, auth: auth)+ }+ }+ .overlay(alignment: .bottomTrailing) { fab }+ .fullScreenCover(item: $ideas.draft) { _ in+ NoteEditorView(app: app, ideas: ideas, onRecordNote: onRecordNote)+ }+ .sheet(isPresented: $showsInspirationSheet) {+ InspirationSheet(app: app, ideas: ideas)+ .presentationDetents([.height(240)])+ }+ }+ }++ private var filterChips: some View {+ HStack(spacing: 10) {+ ForEach(IdeasFilter.allCases, id: \.self) { filter in+ Button {+ ideas.filter = filter+ } label: {+ Text(filter.rawValue.capitalized)+ .font(.subheadline.weight(.semibold))+ .padding(.horizontal, 16)+ .padding(.vertical, 9)+ }+ .buttonStyle(.plain)+ .background(+ Capsule().fill(ideas.filter == filter ? Color.primary.opacity(0.12) : Color.clear)+ )+ .overlay(+ Capsule().strokeBorder(+ ideas.filter == filter ? Color.primary : Color.secondary.opacity(0.35),+ lineWidth: 1.5+ )+ )+ }+ Spacer()+ }+ }++ @ViewBuilder private var content: some View {+ switch ideas.filter {+ case .all:+ if ideas.notes.isEmpty && ideas.inspiration.isEmpty {+ EmptyState(+ title: "Nothing here yet",+ message: "Add a note or save some inspiration to get started."+ )+ } else {+ if !ideas.notes.isEmpty {+ sectionLabel("Notes")+ notesGrid+ }+ if !ideas.inspiration.isEmpty {+ sectionLabel("Inspiration")+ inspirationGrid+ }+ }+ case .notes:+ if ideas.notes.isEmpty {+ EmptyState(title: "No notes yet", message: "Tap the note button to capture an idea.")+ } else {+ notesGrid+ }+ case .inspiration:+ if ideas.inspiration.isEmpty {+ EmptyState(+ title: "Nothing saved yet",+ message: "Save posts and clips you like and they'll show up here."+ )+ } else {+ inspirationGrid+ }+ }+ }++ private func sectionLabel(_ text: String) -> some View {+ Text(text)+ .font(.footnote.weight(.bold))+ .foregroundStyle(.secondary)+ }++ private var notesGrid: some View {+ LazyVGrid(columns: columns, spacing: 14) {+ ForEach(ideas.notes) { note in+ Button {+ ideas.openEditor(for: note)+ } label: {+ NoteCard(note: note)+ }+ .buttonStyle(.plain)+ .contextMenu {+ Button("Delete", systemImage: "trash", role: .destructive) {+ ideas.deleteNote(id: note.id)+ }+ }+ }+ }+ }++ private var inspirationGrid: some View {+ LazyVGrid(columns: columns, spacing: 14) {+ ForEach(ideas.inspiration) { item in+ InspirationCard(item: item, ideas: ideas)+ .contextMenu {+ Button("Delete", systemImage: "trash", role: .destructive) {+ ideas.deleteInspiration(id: item.id)+ }+ }+ }+ }+ }++ private var fab: some View {+ Button {+ if ideas.filter == .inspiration {+ showsInspirationSheet = true+ } else {+ ideas.openEditor()+ }+ } label: {+ Image(systemName: "plus")+ .font(.title2.weight(.bold))+ .frame(width: 60, height: 60)+ }+ .glassEffect(.regular.interactive())+ .padding(.trailing, 20)+ .padding(.bottom, 20)+ .accessibilityLabel(ideas.filter == .inspiration ? "Save inspiration" : "New note")+ }+}++struct NoteCard: View {+ let note: Note++ var body: some View {+ VStack(alignment: .leading, spacing: 6) {+ Text(note.title)+ .font(.subheadline.weight(.bold))+ Text(note.body)+ .font(.footnote)+ .opacity(0.75)+ .lineLimit(8)+ Spacer(minLength: 0)+ }+ .foregroundStyle(Color.notePaperInk)+ .padding(14)+ .frame(maxWidth: .infinity, minHeight: 180, alignment: .topLeading)+ .background(note.color.backgroundColor)+ .overlay(alignment: .bottomTrailing) {+ FoldCorner()+ .fill(note.color.accentColor)+ .frame(width: 30, height: 30)+ }+ .clipShape(RoundedRectangle(cornerRadius: 16))+ }+}++struct FoldCorner: Shape {+ func path(in rect: CGRect) -> Path {+ var path = Path()+ path.move(to: CGPoint(x: rect.maxX, y: rect.minY))+ path.addLine(to: CGPoint(x: rect.maxX, y: rect.maxY))+ path.addLine(to: CGPoint(x: rect.minX, y: rect.maxY))+ path.closeSubpath()+ return path+ }+}++struct InspirationCard: View {+ let item: InspirationItem+ var ideas: IdeasModel++ var body: some View {+ switch item.kind {+ case .link(let url):+ Link(destination: url) {+ VStack(alignment: .leading, spacing: 8) {+ Label(url.host()?.replacingOccurrences(of: "www.", with: "") ?? "link", systemImage: "link")+ .font(.footnote.weight(.bold))+ .lineLimit(1)+ Text(url.absoluteString)+ .font(.caption)+ .foregroundStyle(.secondary)+ .lineLimit(4)+ .multilineTextAlignment(.leading)+ Spacer(minLength: 0)+ }+ .padding(14)+ .frame(maxWidth: .infinity, minHeight: 120, alignment: .topLeading)+ .background(.fill.tertiary)+ .clipShape(RoundedRectangle(cornerRadius: 16))+ }+ .buttonStyle(.plain)+ case .media(let fileName, let isVideo):+ let url = ideas.mediaURL(fileName: fileName)+ Group {+ if isVideo {+ VideoPlayer(player: AVPlayer(url: url))+ } else if let image = UIImage(contentsOfFile: url.path()) {+ Image(uiImage: image)+ .resizable()+ .scaledToFill()+ } else {+ Rectangle().fill(.fill.tertiary)+ }+ }+ .aspectRatio(3 / 4, contentMode: .fit)+ .frame(maxWidth: .infinity)+ .clipShape(RoundedRectangle(cornerRadius: 16))+ }+ }+}++struct InspirationSheet: View {+ @Bindable var app: AppModel+ var ideas: IdeasModel++ @State private var urlText = ""+ @State private var pickerItems: [PhotosPickerItem] = []+ @FocusState private var urlFocused: Bool+ @Environment(\.dismiss) private var dismiss++ var body: some View {+ VStack(alignment: .leading, spacing: 16) {+ Text("Save inspiration")+ .font(.headline)+ TextField("TikTok, Reels, YouTube, link...", text: $urlText)+ .textFieldStyle(.roundedBorder)+ .keyboardType(.URL)+ .textInputAutocapitalization(.never)+ .autocorrectionDisabled()+ .focused($urlFocused)+ .onSubmit(saveURL)+ HStack(spacing: 10) {+ PhotosPicker(selection: $pickerItems, matching: .any(of: [.images, .videos])) {+ Label("Camera roll", systemImage: "photo.on.rectangle")+ .frame(maxWidth: .infinity)+ }+ .buttonStyle(.bordered)+ Button("Save", action: saveURL)+ .buttonStyle(.borderedProminent)+ .frame(maxWidth: .infinity)+ .disabled(urlText.trimmingCharacters(in: .whitespaces).isEmpty)+ }+ }+ .padding(20)+ .presentationDragIndicator(.visible)+ .task { urlFocused = true }+ .onChange(of: pickerItems) { _, items in+ guard !items.isEmpty else { return }+ Task {+ for item in items {+ guard let data = try? await item.loadTransferable(type: Data.self) else { continue }+ let isVideo = item.supportedContentTypes.contains { $0.conforms(to: .movie) }+ ideas.addInspiration(mediaData: data, isVideo: isVideo)+ }+ pickerItems = []+ dismiss()+ app.show(toast: "Saved to Inspiration")+ }+ }+ }++ private func saveURL() {+ guard ideas.addInspiration(urlText: urlText) else { return }+ dismiss()+ app.show(toast: "Saved to Inspiration")+ }+}+#endifdiff --git a/apps/ios/DonkeyKit/Sources/DonkeyKitUI/LoggedOutView.swift b/apps/ios/DonkeyKit/Sources/DonkeyKitUI/LoggedOutView.swiftnew file mode 100644index 00000000..042df186--- /dev/null+++ b/apps/ios/DonkeyKit/Sources/DonkeyKitUI/LoggedOutView.swift@@ -0,0 +1,110 @@+#if os(iOS)+import SwiftUI+import DonkeyKitModels++struct LoggedOutView: View {+ var auth: AuthModel++ @Environment(\.colorScheme) private var colorScheme++ var body: some View {+ VStack(spacing: 8) {+ RoundedRectangle(cornerRadius: 24)+ .fill(LinearGradient(+ colors: [Color(hex: "#ff8a3d"), Color.recordPink],+ startPoint: .topLeading,+ endPoint: .bottomTrailing+ ))+ .frame(width: 84, height: 84)+ .overlay {+ Image(systemName: "record.circle")+ .font(.system(size: 40, weight: .semibold))+ .foregroundStyle(.white)+ }+ .shadow(color: Color.recordPink.opacity(0.35), radius: 20, y: 14)+ .padding(.bottom, 18)++ Text("Turn ideas into videos")+ .font(.title2.weight(.bold))+ Text("Write a note, load it into the teleprompter, and record. Everything lives in one place.")+ .font(.subheadline)+ .foregroundStyle(.secondary)+ .multilineTextAlignment(.center)++ VStack(spacing: 12) {+ signInButton(provider: .google) {+ HStack(spacing: 11) {+ Image("GoogleG", bundle: .main)+ .resizable()+ .scaledToFit()+ .frame(width: 20, height: 20)+ Text("Log in with Google")+ }+ }+ .foregroundStyle(colorScheme == .dark ? .black : .primary)+ .background(.white, in: RoundedRectangle(cornerRadius: 16))+ .overlay(RoundedRectangle(cornerRadius: 16).strokeBorder(.quaternary))++ signInButton(provider: .apple) {+ HStack(spacing: 11) {+ Image(systemName: "apple.logo")+ Text("Log in with Apple")+ }+ }+ .foregroundStyle(colorScheme == .dark ? Color.black : .white)+ .background(colorScheme == .dark ? Color.white : .black, in: RoundedRectangle(cornerRadius: 16))+ }+ .frame(maxWidth: 300)+ .padding(.top, 24)++ if let error = auth.lastError {+ Text(error)+ .font(.footnote)+ .foregroundStyle(.red)+ .multilineTextAlignment(.center)+ .padding(.top, 10)+ }++ Text("By continuing you agree to the Terms and Privacy Policy.")+ .font(.caption2)+ .foregroundStyle(.secondary)+ .padding(.top, 18)+ }+ .padding(.horizontal, 40)+ .frame(maxWidth: .infinity, maxHeight: .infinity)+ .background(Color(.systemBackground))+ .overlay {+ if case .restoring = auth.state {+ ZStack {+ Color(.systemBackground)+ ProgressView()+ }+ .ignoresSafeArea()+ }+ }+ }++ private func signInButton(provider: AuthProvider, @ViewBuilder label: () -> some View) -> some View {+ Button {+ Task { await auth.signIn(with: provider) }+ } label: {+ ZStack {+ label().opacity(isSigningIn(provider) ? 0 : 1)+ if isSigningIn(provider) {+ ProgressView()+ }+ }+ .font(.body.weight(.bold))+ .frame(maxWidth: .infinity)+ .padding(.vertical, 14)+ .contentShape(RoundedRectangle(cornerRadius: 16))+ }+ .buttonStyle(.plain)+ .disabled(auth.state != .signedOut)+ }++ private func isSigningIn(_ provider: AuthProvider) -> Bool {+ auth.state == .signingIn(provider)+ }+}+#endifdiff --git a/apps/ios/DonkeyKit/Sources/DonkeyKitUI/MediaScreen.swift b/apps/ios/DonkeyKit/Sources/DonkeyKitUI/MediaScreen.swiftnew file mode 100644index 00000000..a113d1c7--- /dev/null+++ b/apps/ios/DonkeyKit/Sources/DonkeyKitUI/MediaScreen.swift@@ -0,0 +1,163 @@+#if os(iOS)+import AVKit+import SwiftUI+import DonkeyKitModels++struct MediaScreen: View {+ @Bindable var app: AppModel+ var media: MediaModel+ var auth: AuthModel++ @State private var playing: Recording?++ private let columns = [GridItem(.adaptive(minimum: 150, maximum: 240), spacing: 12)]++ var body: some View {+ NavigationStack {+ Group {+ if media.recordings.isEmpty {+ EmptyState(+ title: "No clips yet",+ message: "Anything you record with the camera lands here.",+ actionTitle: "Open camera"+ ) {+ app.selectedTab = .camera+ }+ .frame(maxHeight: .infinity)+ } else {+ ScrollView {+ LazyVGrid(columns: columns, spacing: 12) {+ ForEach(media.recordings) { recording in+ RecordingCard(recording: recording, media: media)+ .onTapGesture { playing = recording }+ .contextMenu {+ ShareLink(item: media.movieURL(for: recording))+ Button("Delete", systemImage: "trash", role: .destructive) {+ media.delete(recording)+ }+ }+ }+ }+ .padding(.horizontal, 20)+ .padding(.bottom, 24)+ }+ }+ }+ .navigationTitle("Library")+ .toolbar {+ ToolbarItem(placement: .topBarTrailing) {+ AvatarMenu(app: app, auth: auth)+ }+ }+ .fullScreenCover(item: $playing) { recording in+ RecordingPlayerView(url: media.movieURL(for: recording))+ }+ }+ }+}++struct RecordingCard: View {+ let recording: Recording+ var media: MediaModel++ var body: some View {+ ZStack {+ if let url = media.thumbnailURL(for: recording),+ let image = UIImage(contentsOfFile: url.path()) {+ Image(uiImage: image)+ .resizable()+ .scaledToFill()+ } else {+ Rectangle().fill(.fill.secondary)+ Image(systemName: "play.fill")+ .foregroundStyle(.secondary)+ }+ }+ .aspectRatio(9 / 14, contentMode: .fit)+ .frame(maxWidth: .infinity)+ .clipShape(RoundedRectangle(cornerRadius: 16))+ .overlay(alignment: .bottomTrailing) {+ Text(formattedDuration(recording.duration))+ .font(.caption2.weight(.bold))+ .foregroundStyle(.white)+ .padding(.horizontal, 8)+ .padding(.vertical, 3)+ .background(.black.opacity(0.65), in: RoundedRectangle(cornerRadius: 8))+ .padding(8)+ }+ .overlay(alignment: .bottomLeading) {+ SyncBadge(state: media.syncState(for: recording))+ .padding(8)+ }+ }+}++struct SyncBadge: View {+ let state: RecordingSyncState++ var body: some View {+ Text(label)+ .font(.caption2.weight(.bold))+ .foregroundStyle(.white)+ .padding(.horizontal, 8)+ .padding(.vertical, 3)+ .background(background, in: RoundedRectangle(cornerRadius: 8))+ }++ private var label: String {+ switch state {+ case .onDevice: "On this phone"+ case .uploading(let percent): "Uploading \(percent)%"+ case .synced: "Synced ✓"+ }+ }++ private var background: Color {+ switch state {+ case .synced: Color(hex: "#168c4b").opacity(0.85)+ default: .black.opacity(0.65)+ }+ }+}++struct RecordingPlayerView: View {+ let url: URL++ @State private var player: AVPlayer?+ @Environment(\.dismiss) private var dismiss++ var body: some View {+ ZStack(alignment: .topLeading) {+ Color.black.ignoresSafeArea()+ if let player {+ VideoPlayer(player: player)+ .ignoresSafeArea()+ }+ HStack {+ Button {+ dismiss()+ } label: {+ Image(systemName: "xmark")+ .font(.title3.weight(.bold))+ .frame(width: 40, height: 40)+ }+ .glassEffect(.regular.interactive())+ Spacer()+ ShareLink(item: url) {+ Image(systemName: "square.and.arrow.up")+ .font(.title3.weight(.bold))+ .frame(width: 40, height: 40)+ }+ .glassEffect(.regular.interactive())+ }+ .padding(16)+ }+ .task {+ let player = AVPlayer(url: url)+ self.player = player+ player.play()+ }+ .onDisappear { player?.pause() }+ }+}+#endifdiff --git a/apps/ios/DonkeyKit/Sources/DonkeyKitUI/NoteEditorView.swift b/apps/ios/DonkeyKit/Sources/DonkeyKitUI/NoteEditorView.swiftnew file mode 100644index 00000000..1dcd1747--- /dev/null+++ b/apps/ios/DonkeyKit/Sources/DonkeyKitUI/NoteEditorView.swift@@ -0,0 +1,111 @@+#if os(iOS)+import SwiftUI+import DonkeyKitModels++struct NoteEditorView: View {+ @Bindable var app: AppModel+ @Bindable var ideas: IdeasModel+ let onRecordNote: (Note) -> Void++ @FocusState private var bodyFocused: Bool++ var body: some View {+ let color = ideas.draft?.color ?? .butter+ VStack(spacing: 0) {+ HStack {+ Button {+ ideas.closeEditor()+ } label: {+ Image(systemName: "xmark")+ .font(.title3.weight(.bold))+ }+ Spacer()+ Button {+ ideas.cycleDraftColor()+ } label: {+ Circle()+ .fill(color.accentColor)+ .strokeBorder(Color.notePaperInk.opacity(0.75), lineWidth: 3)+ .frame(width: 28, height: 28)+ }+ .accessibilityLabel("Note color")+ }+ .padding(.horizontal, 20)+ .padding(.top, 16)++ TextField("Untitled", text: titleBinding)+ .font(.system(size: 32, weight: .bold))+ .padding(.horizontal, 22)+ .padding(.top, 12)++ TextEditor(text: bodyBinding)+ .font(.system(size: 20, weight: .medium))+ .scrollContentBackground(.hidden)+ .padding(.horizontal, 18)+ .focused($bodyFocused)+ .overlay(alignment: .topLeading) {+ if (ideas.draft?.body ?? "").isEmpty {+ Text("Write down an idea...")+ .font(.system(size: 20, weight: .medium))+ .opacity(0.4)+ .padding(.horizontal, 23)+ .padding(.top, 8)+ .allowsHitTesting(false)+ }+ }++ HStack {+ Button {+ guard let note = ideas.saveDraft() else { return }+ onRecordNote(note)+ } label: {+ Label("Record", systemImage: "record.circle")+ .font(.body.weight(.bold))+ .padding(.horizontal, 8)+ .padding(.vertical, 6)+ }+ .buttonStyle(.bordered)+ .buttonBorderShape(.roundedRectangle(radius: 14))+ .disabled(!(ideas.draft?.hasContent ?? false))++ Spacer()++ Button {+ let wasNew = ideas.draft?.isNew ?? true+ guard ideas.saveDraft() != nil else { return }+ app.show(toast: wasNew ? "Note saved" : "Note updated")+ } label: {+ Text("Save")+ .font(.body.weight(.bold))+ .padding(.horizontal, 14)+ .padding(.vertical, 6)+ }+ .buttonStyle(.borderedProminent)+ .buttonBorderShape(.roundedRectangle(radius: 14))+ .disabled(!(ideas.draft?.hasContent ?? false))+ }+ .padding(.horizontal, 20)+ .padding(.vertical, 14)+ }+ .foregroundStyle(Color.notePaperInk)+ .tint(Color.notePaperInk)+ .background(color.backgroundColor, ignoresSafeAreaEdges: .all)+ .task { bodyFocused = true }+ .animation(.easeInOut(duration: 0.2), value: color)+ }++ private var titleBinding: Binding<String> {+ Binding(+ get: { ideas.draft?.title ?? "" },+ set: { ideas.draft?.title = $0 }+ )+ }++ private var bodyBinding: Binding<String> {+ Binding(+ get: { ideas.draft?.body ?? "" },+ set: { ideas.draft?.body = $0 }+ )+ }+}+#endifdiff --git a/apps/ios/DonkeyKit/Sources/DonkeyKitUI/ProjectsScreen.swift b/apps/ios/DonkeyKit/Sources/DonkeyKitUI/ProjectsScreen.swiftnew file mode 100644index 00000000..03dc8ed2--- /dev/null+++ b/apps/ios/DonkeyKit/Sources/DonkeyKitUI/ProjectsScreen.swift@@ -0,0 +1,220 @@+#if os(iOS)+import SwiftUI+import DonkeyKitModels++struct ProjectsScreen: View {+ @Bindable var app: AppModel+ var projects: ProjectsModel+ var auth: AuthModel++ @State private var playing: Project?++ private let columns = [GridItem(.flexible(), spacing: 12), GridItem(.flexible(), spacing: 12)]++ var body: some View {+ NavigationStack {+ ScrollView {+ LazyVGrid(columns: columns, spacing: 12) {+ ForEach(projects.projects) { project in+ ProjectCard(project: project) { playing = project }+ }+ }+ .padding(.horizontal, 20)+ .padding(.bottom, 24)+ }+ .navigationTitle("Projects")+ .toolbar {+ ToolbarItem(placement: .topBarTrailing) {+ AvatarMenu(app: app, auth: auth)+ }+ }+ .fullScreenCover(item: $playing) { project in+ ProjectPlayerView(project: project)+ }+ }+ }+}++struct ProjectCard: View {+ let project: Project+ let onPlay: () -> Void++ var body: some View {+ Group {+ switch project.export {+ case .ready(let renderedOn):+ Button(action: onPlay) {+ ZStack {+ RoundedRectangle(cornerRadius: 16).fill(.fill.secondary)+ Circle()+ .fill(.white.opacity(0.14))+ .frame(width: 46, height: 46)+ .overlay {+ Image(systemName: "play.fill")+ .font(.body.weight(.bold))+ .foregroundStyle(.primary)+ .offset(x: 2)+ }+ }+ .overlay(alignment: .topLeading) {+ ProjectTag(text: formattedDuration(project.duration))+ .padding(8)+ }+ .overlay(alignment: .bottomLeading) {+ ProjectTag(text: "\(project.name) · \(renderedOn)")+ .padding(8)+ }+ }+ .buttonStyle(.plain)+ case .exporting(let percent):+ GhostCard(title: project.name, subtitle: "Exporting \(percent)%")+ .overlay(alignment: .bottom) {+ ProgressView(value: Double(percent), total: 100)+ .tint(.recordPink)+ .padding(.horizontal, 12)+ .padding(.bottom, 12)+ }+ case .none:+ GhostCard(title: project.name, subtitle: "No export yet")+ }+ }+ .aspectRatio(9 / 13, contentMode: .fit)+ .frame(maxWidth: .infinity)+ }+}++struct ProjectTag: View {+ let text: String++ var body: some View {+ Text(text)+ .font(.caption2.weight(.bold))+ .foregroundStyle(.white)+ .lineLimit(1)+ .padding(.horizontal, 8)+ .padding(.vertical, 3)+ .background(.black.opacity(0.55), in: RoundedRectangle(cornerRadius: 8))+ }+}++struct GhostCard: View {+ let title: String+ let subtitle: String++ var body: some View {+ RoundedRectangle(cornerRadius: 16)+ .strokeBorder(.secondary.opacity(0.4), style: StrokeStyle(lineWidth: 1.5, dash: [6, 5]))+ .overlay {+ VStack(spacing: 4) {+ Text(title)+ Text(subtitle)+ }+ .font(.caption.weight(.semibold))+ .foregroundStyle(.secondary)+ .multilineTextAlignment(.center)+ .padding(.horizontal, 12)+ }+ }+}++/// Plays the project's latest render. Playback is a clock over the render's+/// duration until renders stream from the cloud.+struct ProjectPlayerView: View {+ let project: Project++ @State private var time: TimeInterval = 0+ @State private var isPlaying = false+ @Environment(\.dismiss) private var dismiss++ var body: some View {+ VStack(spacing: 0) {+ HStack(spacing: 12) {+ Button {+ dismiss()+ } label: {+ Image(systemName: "xmark")+ .font(.title3.weight(.bold))+ .frame(width: 40, height: 40)+ }+ Text(project.name)+ .font(.subheadline.weight(.bold))+ .lineLimit(1)+ .frame(maxWidth: .infinity)+ Spacer().frame(width: 40)+ }+ .padding(.horizontal, 16)+ .padding(.top, 8)++ Spacer()++ Button {+ isPlaying.toggle()+ } label: {+ Image(systemName: isPlaying ? "pause.fill" : "play.fill")+ .font(.title.weight(.bold))+ .frame(width: 76, height: 76)+ .background(.white.opacity(0.15), in: Circle())+ }++ Spacer()++ VStack(alignment: .leading, spacing: 8) {+ scrubber+ HStack {+ Text(formattedDuration(time))+ Spacer()+ Text(formattedDuration(project.duration))+ }+ .font(.caption.weight(.semibold))+ .foregroundStyle(.white.opacity(0.75))+ if case .ready(let renderedOn) = project.export {+ Text("Latest render · \(renderedOn)")+ .font(.caption2.weight(.bold))+ .padding(.horizontal, 10)+ .padding(.vertical, 4)+ .background(.white.opacity(0.14), in: Capsule())+ .padding(.top, 4)+ }+ }+ .padding(.horizontal, 16)+ .padding(.bottom, 24)+ }+ .foregroundStyle(.white)+ .background(Color.black.ignoresSafeArea())+ .task(id: isPlaying) {+ guard isPlaying else { return }+ while !Task.isCancelled {+ try? await Task.sleep(for: .seconds(0.1))+ time = min(time + 0.1, project.duration)+ if time >= project.duration {+ isPlaying = false+ return+ }+ }+ }+ }++ private var scrubber: some View {+ GeometryReader { proxy in+ ZStack(alignment: .leading) {+ Capsule().fill(.white.opacity(0.22))+ Capsule()+ .fill(.white)+ .frame(width: max(0, proxy.size.width * progress))+ }+ .contentShape(Rectangle())+ .gesture(+ DragGesture(minimumDistance: 0).onChanged { value in+ let fraction = min(max(value.location.x / proxy.size.width, 0), 1)+ time = fraction * project.duration+ }+ )+ }+ .frame(height: 5)+ }++ private var progress: Double {+ project.duration > 0 ? time / project.duration : 0+ }+}+#endifdiff --git a/apps/ios/DonkeyKit/Sources/DonkeyKitUI/RootView.swift b/apps/ios/DonkeyKit/Sources/DonkeyKitUI/RootView.swiftnew file mode 100644index 00000000..4ee1c3d8--- /dev/null+++ b/apps/ios/DonkeyKit/Sources/DonkeyKitUI/RootView.swift@@ -0,0 +1,83 @@+#if os(iOS)+import SwiftUI+import DonkeyKitModels++/// The app shell: four tabs, the logged-out gate, and the toast layer.+/// The app target injects the camera preview so this package never touches+/// the capture session.+public struct RootView<CameraPreview: View>: View {+ @Bindable var app: AppModel+ var ideas: IdeasModel+ var camera: CameraModel+ var media: MediaModel+ var projects: ProjectsModel+ var auth: AuthModel+ let cameraPreview: () -> CameraPreview++ @Environment(\.scenePhase) private var scenePhase++ public init(+ app: AppModel,+ ideas: IdeasModel,+ camera: CameraModel,+ media: MediaModel,+ projects: ProjectsModel,+ auth: AuthModel,+ @ViewBuilder cameraPreview: @escaping () -> CameraPreview+ ) {+ self.app = app+ self.ideas = ideas+ self.camera = camera+ self.media = media+ self.projects = projects+ self.auth = auth+ self.cameraPreview = cameraPreview+ }++ public var body: some View {+ ZStack {+ TabView(selection: $app.selectedTab) {+ Tab("Ideas", systemImage: "lightbulb", value: .ideas) {+ IdeasScreen(app: app, ideas: ideas, auth: auth, onRecordNote: recordNote)+ }+ Tab("Library", systemImage: "books.vertical", value: .media) {+ MediaScreen(app: app, media: media, auth: auth)+ }+ Tab("Projects", systemImage: "play.rectangle", value: .projects) {+ ProjectsScreen(app: app, projects: projects, auth: auth)+ }+ Tab("Camera", systemImage: "camera", value: .camera) {+ CameraScreen(camera: camera, ideas: ideas, cameraPreview: cameraPreview)+ }+ }+ .tabViewStyle(.sidebarAdaptable)++ if !auth.isSignedIn {+ LoggedOutView(auth: auth)+ .transition(.opacity)+ }++ ToastOverlay(app: app)+ }+ .animation(.default, value: auth.isSignedIn)+ .preferredColorScheme(app.appearance.colorScheme)+ .task { await auth.restore() }+ .onChange(of: cameraShouldRun) { _, run in+ if run {+ camera.appeared()+ } else {+ camera.disappeared()+ }+ }+ }++ private var cameraShouldRun: Bool {+ app.selectedTab == .camera && auth.isSignedIn && scenePhase == .active+ }++ private func recordNote(_ note: Note) {+ camera.loadTeleprompter(script: note.script)+ app.selectedTab = .camera+ }+}+#endifdiff --git a/apps/ios/DonkeyKit/Sources/DonkeyKitUI/Theme.swift b/apps/ios/DonkeyKit/Sources/DonkeyKitUI/Theme.swiftnew file mode 100644index 00000000..5b1b5f4f--- /dev/null+++ b/apps/ios/DonkeyKit/Sources/DonkeyKitUI/Theme.swift@@ -0,0 +1,35 @@+#if os(iOS)+import SwiftUI+import DonkeyKitModels++extension Color {+ /// Parses "#rrggbb" strings; the note palette lives in DonkeyKitModels as hex.+ init(hex: String) {+ var value: UInt64 = 0+ Scanner(string: String(hex.dropFirst())).scanHexInt64(&value)+ self.init(+ red: Double((value >> 16) & 0xff) / 255,+ green: Double((value >> 8) & 0xff) / 255,+ blue: Double(value & 0xff) / 255+ )+ }++ static let recordPink = Color(hex: "#d81b60")+ static let notePaperInk = Color(hex: "#201a0d")+}++extension NoteColor {+ var backgroundColor: Color { Color(hex: background) }+ var accentColor: Color { Color(hex: accent) }+}++extension AppearancePreference {+ public var colorScheme: ColorScheme? {+ switch self {+ case .system: nil+ case .light: .light+ case .dark: .dark+ }+ }+}+#endifdiff --git a/apps/ios/DonkeyKit/Tests/DonkeyKitModelsTests/DonkeyKitModelsTests.swift b/apps/ios/DonkeyKit/Tests/DonkeyKitModelsTests/DonkeyKitModelsTests.swiftnew file mode 100644index 00000000..acebedc7--- /dev/null+++ b/apps/ios/DonkeyKit/Tests/DonkeyKitModelsTests/DonkeyKitModelsTests.swift@@ -0,0 +1,252 @@+import Foundation+import Testing+@testable import DonkeyKitModels++@Suite struct FormatSelectionTests {+ // iPhone-shaped format table: 1080p60 HLG, 1080p30 SDR, 4K60 HLG, 720p30.+ let specs = [+ CaptureFormatSpec(index: 0, width: 1280, height: 720, maxFrameRate: 30, supportsHLG: false),+ CaptureFormatSpec(index: 1, width: 1920, height: 1080, maxFrameRate: 30, supportsHLG: false),+ CaptureFormatSpec(index: 2, width: 1920, height: 1080, maxFrameRate: 60, supportsHLG: true),+ CaptureFormatSpec(index: 3, width: 3840, height: 2160, maxFrameRate: 60, supportsHLG: true),+ ]++ @Test func exactMatchWins() {+ let choice = chooseFormat(from: specs, settings: CameraSettings(resolution: .uhd, frameRate: .fps60, colorMode: .hdr))+ #expect(choice?.index == 3)+ #expect(choice?.effective == CameraSettings(resolution: .uhd, frameRate: .fps60, colorMode: .hdr))+ }++ @Test func missing2KSnapsToNearestArea() {+ let choice = chooseFormat(from: specs, settings: CameraSettings(resolution: .qhd, frameRate: .fps30, colorMode: .sdr))+ #expect(choice?.index == 1)+ }++ @Test func hdrFallsBackToSDR() {+ let sdrOnly = [CaptureFormatSpec(index: 0, width: 1920, height: 1080, maxFrameRate: 60, supportsHLG: false)]+ let choice = chooseFormat(from: sdrOnly, settings: CameraSettings(resolution: .hd, frameRate: .fps60, colorMode: .hdr))+ #expect(choice?.effective.colorMode == .sdr)+ #expect(choice?.index == 0)+ }++ @Test func unavailableFrameRateFallsBack() {+ let slow = [CaptureFormatSpec(index: 0, width: 1920, height: 1080, maxFrameRate: 30, supportsHLG: false)]+ let choice = chooseFormat(from: slow, settings: CameraSettings(resolution: .hd, frameRate: .fps60, colorMode: .sdr))+ #expect(choice?.effective.frameRate == .fps30)+ }++ @Test func emptySpecsChooseNothing() {+ #expect(chooseFormat(from: [], settings: CameraSettings()) == nil)+ }+}++@Suite struct ZoomTests {+ @Test func tripleCameraOffersUltraWide() {+ let mapping = ZoomMapping(wideBase: 2, minDisplay: 0.5, maxDisplay: 8)+ #expect(mapping.options == [0.5, 1, 2, 3])+ #expect(mapping.videoZoomFactor(forDisplay: 1) == 2)+ #expect(mapping.videoZoomFactor(forDisplay: 0.5) == 1)+ }++ @Test func singleCameraClampsToOne() {+ let mapping = ZoomMapping(wideBase: 1, minDisplay: 1, maxDisplay: 1)+ #expect(mapping.options == [1])+ #expect(mapping.videoZoomFactor(forDisplay: 3) == 1)+ }++ @Test func labels() {+ #expect(zoomLabel(0.5) == "0.5×")+ #expect(zoomLabel(2) == "2×")+ }+}++@Suite struct TeleprompterTests {+ @Test func scrollStartsLowAndMovesUp() {+ var state = TeleprompterState()+ state.settings.speed = 40+ let start = state.scrollOffset(elapsed: 0, overlayHeight: 300)+ #expect(start == 180)+ #expect(state.scrollOffset(elapsed: 2, overlayHeight: 300) == 100)+ }++ @Test func hasScriptIgnoresWhitespace() {+ var state = TeleprompterState()+ state.script = " \n"+ #expect(!state.hasScript)+ state.script = "Hello"+ #expect(state.hasScript)+ }+}++@Suite struct DurationTests {+ @Test func formatting() {+ #expect(formattedDuration(0) == "0:00")+ #expect(formattedDuration(65) == "1:05")+ #expect(formattedDuration(600) == "10:00")+ }+}++@Suite struct InspirationURLTests {+ @Test func addsHTTPS() {+ #expect(normalizedInspirationURL("tiktok.com/@donkey")?.absoluteString == "https://tiktok.com/@donkey")+ }++ @Test func keepsExplicitScheme() {+ #expect(normalizedInspirationURL("http://example.com")?.absoluteString == "http://example.com")+ }++ @Test func rejectsEmpty() {+ #expect(normalizedInspirationURL(" ") == nil)+ }+}++@MainActor+@Suite struct IdeasModelTests {+ func makeModel() throws -> IdeasModel {+ IdeasModel(store: try DonkeyStore(inMemory: true))+ }++ @Test func saveDraftCreatesNote() throws {+ let model = try makeModel()+ model.openEditor()+ model.draft?.body = "Hey there this is cool"+ let note = model.saveDraft()+ #expect(note?.title == "Untitled")+ #expect(model.notes.count == 1)+ #expect(model.draft == nil)+ }++ @Test func emptyDraftDoesNotSave() throws {+ let model = try makeModel()+ model.openEditor()+ #expect(model.saveDraft() == nil)+ #expect(model.notes.isEmpty)+ }++ @Test func editKeepsIdentityAndPosition() throws {+ let model = try makeModel()+ model.openEditor()+ model.draft?.title = "First"+ let first = model.saveDraft()+ model.openEditor()+ model.draft?.title = "Second"+ model.saveDraft()++ model.openEditor(for: model.notes[1])+ model.draft?.body = "edited"+ model.cycleDraftColor()+ let edited = model.saveDraft()+ #expect(edited?.id == first?.id)+ #expect(edited?.color == .blush)+ #expect(model.notes.count == 2)+ #expect(model.notes[1].body == "edited")+ }++ @Test func scriptPrefersBody() {+ let note = Note(title: "Title", body: "Body", color: .butter)+ #expect(note.script == "Body")+ let titleOnly = Note(title: "Title", body: "", color: .butter)+ #expect(titleOnly.script == "Title")+ }++ @Test func inspirationLinkRoundTrips() throws {+ let model = try makeModel()+ #expect(model.addInspiration(urlText: "youtube.com/watch?v=1"))+ #expect(!model.addInspiration(urlText: " "))+ #expect(model.inspiration.count == 1)+ guard case .link(let url) = model.inspiration[0].kind else {+ Issue.record("expected link")+ return+ }+ #expect(url.host() == "youtube.com")+ }+}++@MainActor+@Suite struct AuthModelTests {+ final class FakeAuth: AuthServicing {+ var stored: UserProfile?+ var result: Result<UserProfile, any Error> = .failure(CancellationError())++ func signIn(with provider: AuthProvider) async throws -> UserProfile {+ try result.get()+ }++ func restoreSession() async -> UserProfile? { stored }+ func signOut() async { stored = nil }+ }++ @Test func restoreWithoutSessionSignsOut() async {+ let model = AuthModel(service: FakeAuth())+ await model.restore()+ #expect(model.state == .signedOut)+ }++ @Test func successfulSignIn() async {+ let service = FakeAuth()+ let profile = UserProfile(id: "1", name: "David", email: "[email protected]")+ service.result = .success(profile)+ let model = AuthModel(service: service)+ await model.restore()+ await model.signIn(with: .google)+ #expect(model.state == .signedIn(profile))+ #expect(profile.initial == "D")+ }++ @Test func failureReturnsToSignedOutWithError() async {+ let service = FakeAuth()+ service.result = .failure(URLError(.notConnectedToInternet))+ let model = AuthModel(service: service)+ await model.restore()+ await model.signIn(with: .apple)+ #expect(model.state == .signedOut)+ #expect(model.lastError != nil)+ }++ @Test func cancellationLeavesNoError() async {+ let model = AuthModel(service: FakeAuth())+ await model.restore()+ await model.signIn(with: .apple)+ #expect(model.state == .signedOut)+ #expect(model.lastError == nil)+ }+}++@MainActor+@Suite struct CameraModelTests {+ final class FakeController: CameraControlling {+ var recorded: [String] = []+ func activate() { recorded.append("activate") }+ func deactivate() { recorded.append("deactivate") }+ func setFacing(_ facing: CameraFacing) { recorded.append("facing") }+ func setZoom(display: Double) { recorded.append("zoom \(display)") }+ func setTorch(_ on: Bool) { recorded.append("torch \(on)") }+ func apply(_ settings: CameraSettings) { recorded.append("apply") }+ func startRecording() { recorded.append("start") }+ func stopRecording() { recorded.append("stop") }+ }++ @Test func recordToggleRoutesThroughController() {+ let model = CameraModel()+ let controller = FakeController()+ model.controller = controller+ model.toggleRecording()+ model.recordingDidStart()+ #expect(model.isRecording)+ model.toggleRecording()+ model.recordingDidFinish()+ #expect(!model.isRecording)+ #expect(controller.recorded == ["start", "stop"])+ }++ @Test func flipResetsZoomAndTorch() {+ let model = CameraModel()+ model.controller = FakeController()+ model.select(zoom: 2)+ model.toggleTorch()+ model.flip()+ #expect(model.facing == .back)+ #expect(model.zoom == 1)+ #expect(!model.isTorchOn)+ }+}diff --git a/scripts/ship-ios-testflight.sh b/scripts/ship-ios-testflight.shnew file mode 100755index 00000000..cb63b638--- /dev/null+++ b/scripts/ship-ios-testflight.sh@@ -0,0 +1,66 @@+#!/usr/bin/env bash+# Ships the iOS app to TestFlight: archives apps/ios and uploads the build to+# App Store Connect. Requires Xcode 26+ with the team signed in (Xcode →+# Settings → Accounts). Signing stays automatic; Xcode manages the build+# number against App Store Connect so repeat uploads never collide.+#+# Auth uses the Apple ID session stored by Xcode. To run unattended (CI),+# provide an App Store Connect API key instead:+# DONKEY_ASC_KEY_P8_PATH=/path/AuthKey_XXXX.p8+# DONKEY_ASC_KEY_ID=XXXX+# DONKEY_ASC_ISSUER_ID=uuid+set -euo pipefail++ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"+export DEVELOPER_DIR="${DEVELOPER_DIR:-/Applications/Xcode.app/Contents/Developer}"++ARCHIVE="$ROOT/dist/DonkeyIOS.xcarchive"+EXPORT_PLIST="$(mktemp -t donkey-ios-export.XXXXXX).plist"+trap 'rm -f "$EXPORT_PLIST"' EXIT++cat > "$EXPORT_PLIST" <<'PLIST'+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>method</key>+ <string>app-store-connect</string>+ <key>destination</key>+ <string>upload</string>+ <key>signingStyle</key>+ <string>automatic</string>+ <key>manageAppVersionAndBuildNumber</key>+ <true/>+</dict>+</plist>+PLIST++AUTH_ARGS=()+if [[ -n "${DONKEY_ASC_KEY_P8_PATH:-}" ]]; then+ AUTH_ARGS=(+ -authenticationKeyPath "$DONKEY_ASC_KEY_P8_PATH"+ -authenticationKeyID "$DONKEY_ASC_KEY_ID"+ -authenticationKeyIssuerID "$DONKEY_ASC_ISSUER_ID"+ )+fi++echo "==> Archiving"+rm -rf "$ARCHIVE"+xcodebuild archive \+ -project "$ROOT/apps/ios/Donkey.xcodeproj" \+ -scheme Donkey \+ -configuration Release \+ -destination 'generic/platform=iOS' \+ -archivePath "$ARCHIVE" \+ -allowProvisioningUpdates \+ ${AUTH_ARGS[@]+"${AUTH_ARGS[@]}"} \+ -quiet++echo "==> Uploading to App Store Connect"+xcodebuild -exportArchive \+ -archivePath "$ARCHIVE" \+ -exportOptionsPlist "$EXPORT_PLIST" \+ -allowProvisioningUpdates \+ ${AUTH_ARGS[@]+"${AUTH_ARGS[@]}"}++echo "==> Uploaded. The build appears in App Store Connect → TestFlight after processing."