1 Commits

Author SHA1 Message Date
Trey t
5d39dcb66f Fix 28 issues from deep audit and UI audit + redesign changes
Some checks failed
Apple Platform CI / smoke-and-tests (push) Has been cancelled
Deep audit (issues 2-14):
- Add missing WCSession handlers for applicationContext and userInfo
- Fix BoundedFIFOQueue race condition with serial dispatch queue
- Fix timer race condition with main thread guarantee
- Fix watch pause state divergence — phone is now source of truth
- Fix wrong notification posted on logout (createdNewWorkout → userLoggedOut)
- Fix POST status check to accept any 2xx (was exact match)
- Fix @StateObject → @ObservedObject for injected viewModel
- Add pull-to-refresh to CompletedWorkoutsView
- Fix typos: RefreshUserInfoFetcable, defualtPackageModle
- Replace string concatenation with interpolation
- Replace 6 @StateObject with @ObservedObject for BridgeModule.shared
- Replace 7 hardcoded AVPlayer URLs with BaseURLs.currentBaseURL

UI audit (issues 1-15):
- Fix GeometryReader eating VStack space — replaced with .overlay
- Fix refreshable continuation resuming before fetch completes
- Remove duplicate @State workouts — derive from DataStore
- Decouple leaf views from BridgeModule (pass discrete values)
- Convert selectedIds from Array to Set for O(1) lookups
- Extract .sorted() from var body into computed properties
- Move search filter out of ForEach render loop
- Replace import SwiftUI with import Combine in non-UI classes
- Mark all @State properties private
- Extract L/R exercise auto-add logic to WorkoutViewModel
- Use enumerated() instead of .indices in ForEach
- Make AddSupersetView frame flexible instead of fixed 300pt
- Hoist Set construction out of per-exercise filter loop
- Move ViewModel network fetch from init to load()

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-23 10:24:52 -06:00
60 changed files with 1783 additions and 1346 deletions

View File

@@ -0,0 +1,14 @@
{
"permissions": {
"allow": [
"Bash(grep:*)",
"Bash(du -sh:*)",
"Bash(./scripts/smoke/build_ios.sh:*)",
"Bash(find .:*)",
"Bash(find:*)",
"Bash(ls:*)",
"Bash(tail:*)",
"Bash(head:*)"
]
}
}

View File

@@ -1,10 +1,10 @@
// swift-tools-version: 5.9 // swift-tools-version: 6.2
import PackageDescription import PackageDescription
let package = Package( let package = Package(
name: "SharedCore", name: "SharedCore",
platforms: [ platforms: [
.iOS(.v16), .iOS(.v26),
.watchOS(.v9), .watchOS(.v9),
.tvOS(.v16), .tvOS(.v16),
.macOS(.v13) .macOS(.v13)
@@ -31,5 +31,6 @@ let package = Package(
name: "SharedCoreTVOSTests", name: "SharedCoreTVOSTests",
dependencies: ["SharedCore"] dependencies: ["SharedCore"]
) )
] ],
swiftLanguageModes: [.v5]
) )

View File

@@ -2,5 +2,6 @@ import Foundation
public enum AppNotifications { public enum AppNotifications {
public static let createdNewWorkout = Notification.Name("CreatedNewWorkout") public static let createdNewWorkout = Notification.Name("CreatedNewWorkout")
public static let userLoggedOut = Notification.Name("UserLoggedOut")
} }

View File

@@ -15,7 +15,7 @@ struct ContentView: View {
@ObservedObject var dataStore = DataStore.shared @ObservedObject var dataStore = DataStore.shared
@State var nsfwVideos: [NSFWVideo]? @State var nsfwVideos: [NSFWVideo]?
@State private var showLoginView = false @State private var showLoginView = false
@State var avPlayer = AVPlayer(url: URL(string: "https://dev.werkout.fitness/media/exercise_videos/2_Dumbbell_Lateral_Lunges.mp4") ?? URL(fileURLWithPath: "/dev/null")) @State var avPlayer = AVPlayer(url: URL(string: BaseURLs.currentBaseURL + "/media/exercise_videos/2_Dumbbell_Lateral_Lunges.mp4") ?? URL(fileURLWithPath: "/dev/null"))
@State private var currentVideoURL: URL? @State private var currentVideoURL: URL?
let videoEnded = NotificationCenter.default.publisher(for: NSNotification.Name.AVPlayerItemDidPlayToEndTime) let videoEnded = NotificationCenter.default.publisher(for: NSNotification.Name.AVPlayerItemDidPlayToEndTime)

View File

@@ -323,13 +323,6 @@
}; };
/* End PBXTargetDependency section */ /* End PBXTargetDependency section */
/* Begin XCLocalSwiftPackageReference section */
D00100012E00000100000003 /* XCLocalSwiftPackageReference "../SharedCore" */ = {
isa = XCLocalSwiftPackageReference;
relativePath = ../SharedCore;
};
/* End XCLocalSwiftPackageReference section */
/* Begin XCBuildConfiguration section */ /* Begin XCBuildConfiguration section */
1CF65A342A3972850042FFBD /* Debug */ = { 1CF65A342A3972850042FFBD /* Debug */ = {
isa = XCBuildConfiguration; isa = XCBuildConfiguration;
@@ -461,9 +454,9 @@
ENABLE_APP_INTENTS_METADATA_GENERATION = NO; ENABLE_APP_INTENTS_METADATA_GENERATION = NO;
ENABLE_HARDENED_RUNTIME = YES; ENABLE_HARDENED_RUNTIME = YES;
ENABLE_PREVIEWS = YES; ENABLE_PREVIEWS = YES;
EXCLUDED_SOURCE_FILE_NAMES = "Werkout_ios/Resources/Werkout-ios-Info.plist"; EXCLUDED_SOURCE_FILE_NAMES = "Werkout_ios/Resources/Werkout-ios-Info.plist";
GENERATE_INFOPLIST_FILE = YES; GENERATE_INFOPLIST_FILE = YES;
INFOPLIST_FILE = "Werkout-ios-Info.plist"; INFOPLIST_FILE = "Werkout-ios-Info.plist";
INFOPLIST_KEY_NSHealthShareUsageDescription = "Read your heart rate"; INFOPLIST_KEY_NSHealthShareUsageDescription = "Read your heart rate";
INFOPLIST_KEY_NSHealthUpdateUsageDescription = "Read your heart rate"; INFOPLIST_KEY_NSHealthUpdateUsageDescription = "Read your heart rate";
"INFOPLIST_KEY_UIApplicationSceneManifest_Generation[sdk=iphoneos*]" = YES; "INFOPLIST_KEY_UIApplicationSceneManifest_Generation[sdk=iphoneos*]" = YES;
@@ -477,7 +470,7 @@
"INFOPLIST_KEY_UIStatusBarStyle[sdk=iphonesimulator*]" = UIStatusBarStyleDefault; "INFOPLIST_KEY_UIStatusBarStyle[sdk=iphonesimulator*]" = UIStatusBarStyleDefault;
INFOPLIST_KEY_UISupportedInterfaceOrientations_iPad = "UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight"; INFOPLIST_KEY_UISupportedInterfaceOrientations_iPad = "UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight";
INFOPLIST_KEY_UISupportedInterfaceOrientations_iPhone = "UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight"; INFOPLIST_KEY_UISupportedInterfaceOrientations_iPhone = "UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight";
IPHONEOS_DEPLOYMENT_TARGET = 16.4; IPHONEOS_DEPLOYMENT_TARGET = 26.0;
LD_RUNPATH_SEARCH_PATHS = "@executable_path/Frameworks"; LD_RUNPATH_SEARCH_PATHS = "@executable_path/Frameworks";
"LD_RUNPATH_SEARCH_PATHS[sdk=macosx*]" = "@executable_path/../Frameworks"; "LD_RUNPATH_SEARCH_PATHS[sdk=macosx*]" = "@executable_path/../Frameworks";
MACOSX_DEPLOYMENT_TARGET = 13.3; MACOSX_DEPLOYMENT_TARGET = 13.3;
@@ -507,9 +500,9 @@
ENABLE_APP_INTENTS_METADATA_GENERATION = NO; ENABLE_APP_INTENTS_METADATA_GENERATION = NO;
ENABLE_HARDENED_RUNTIME = YES; ENABLE_HARDENED_RUNTIME = YES;
ENABLE_PREVIEWS = YES; ENABLE_PREVIEWS = YES;
EXCLUDED_SOURCE_FILE_NAMES = "Werkout_ios/Resources/Werkout-ios-Info.plist"; EXCLUDED_SOURCE_FILE_NAMES = "Werkout_ios/Resources/Werkout-ios-Info.plist";
GENERATE_INFOPLIST_FILE = YES; GENERATE_INFOPLIST_FILE = YES;
INFOPLIST_FILE = "Werkout-ios-Info.plist"; INFOPLIST_FILE = "Werkout-ios-Info.plist";
INFOPLIST_KEY_NSHealthShareUsageDescription = "Read your heart rate"; INFOPLIST_KEY_NSHealthShareUsageDescription = "Read your heart rate";
INFOPLIST_KEY_NSHealthUpdateUsageDescription = "Read your heart rate"; INFOPLIST_KEY_NSHealthUpdateUsageDescription = "Read your heart rate";
"INFOPLIST_KEY_UIApplicationSceneManifest_Generation[sdk=iphoneos*]" = YES; "INFOPLIST_KEY_UIApplicationSceneManifest_Generation[sdk=iphoneos*]" = YES;
@@ -523,7 +516,7 @@
"INFOPLIST_KEY_UIStatusBarStyle[sdk=iphonesimulator*]" = UIStatusBarStyleDefault; "INFOPLIST_KEY_UIStatusBarStyle[sdk=iphonesimulator*]" = UIStatusBarStyleDefault;
INFOPLIST_KEY_UISupportedInterfaceOrientations_iPad = "UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight"; INFOPLIST_KEY_UISupportedInterfaceOrientations_iPad = "UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight";
INFOPLIST_KEY_UISupportedInterfaceOrientations_iPhone = "UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight"; INFOPLIST_KEY_UISupportedInterfaceOrientations_iPhone = "UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight";
IPHONEOS_DEPLOYMENT_TARGET = 16.4; IPHONEOS_DEPLOYMENT_TARGET = 26.0;
LD_RUNPATH_SEARCH_PATHS = "@executable_path/Frameworks"; LD_RUNPATH_SEARCH_PATHS = "@executable_path/Frameworks";
"LD_RUNPATH_SEARCH_PATHS[sdk=macosx*]" = "@executable_path/../Frameworks"; "LD_RUNPATH_SEARCH_PATHS[sdk=macosx*]" = "@executable_path/../Frameworks";
MACOSX_DEPLOYMENT_TARGET = 13.3; MACOSX_DEPLOYMENT_TARGET = 13.3;
@@ -613,14 +606,6 @@
}; };
/* End XCBuildConfiguration section */ /* End XCBuildConfiguration section */
/* Begin XCSwiftPackageProductDependency section */
D00100012E00000100000004 /* SharedCore */ = {
isa = XCSwiftPackageProductDependency;
package = D00100012E00000100000003 /* XCLocalSwiftPackageReference "../SharedCore" */;
productName = SharedCore;
};
/* End XCSwiftPackageProductDependency section */
/* Begin XCConfigurationList section */ /* Begin XCConfigurationList section */
1CF65A1D2A3972840042FFBD /* Build configuration list for PBXProject "Werkout_ios" */ = { 1CF65A1D2A3972840042FFBD /* Build configuration list for PBXProject "Werkout_ios" */ = {
isa = XCConfigurationList; isa = XCConfigurationList;
@@ -650,6 +635,21 @@
defaultConfigurationName = Release; defaultConfigurationName = Release;
}; };
/* End XCConfigurationList section */ /* End XCConfigurationList section */
/* Begin XCLocalSwiftPackageReference section */
D00100012E00000100000003 /* XCLocalSwiftPackageReference "../SharedCore" */ = {
isa = XCLocalSwiftPackageReference;
relativePath = ../SharedCore;
};
/* End XCLocalSwiftPackageReference section */
/* Begin XCSwiftPackageProductDependency section */
D00100012E00000100000004 /* SharedCore */ = {
isa = XCSwiftPackageProductDependency;
package = D00100012E00000100000003 /* XCLocalSwiftPackageReference "../SharedCore" */;
productName = SharedCore;
};
/* End XCSwiftPackageProductDependency section */
}; };
rootObject = 1CF65A1A2A3972840042FFBD /* Project object */; rootObject = 1CF65A1A2A3972840042FFBD /* Project object */;
} }

View File

@@ -2,8 +2,13 @@
"colors" : [ "colors" : [
{ {
"color" : { "color" : {
"platform" : "universal", "color-space" : "srgb",
"reference" : "systemPurpleColor" "components" : {
"alpha" : "1.000",
"blue" : "1.000",
"green" : "0.350",
"red" : "0.750"
}
}, },
"idiom" : "universal" "idiom" : "universal"
}, },
@@ -15,8 +20,13 @@
} }
], ],
"color" : { "color" : {
"platform" : "universal", "color-space" : "srgb",
"reference" : "systemPurpleColor" "components" : {
"alpha" : "1.000",
"blue" : "1.000",
"green" : "0.350",
"red" : "0.750"
}
}, },
"idiom" : "universal" "idiom" : "universal"
} }

View File

@@ -9,7 +9,7 @@ import Foundation
enum BaseURLs: String { enum BaseURLs: String {
case local = "http://127.0.0.1:8000" case local = "http://127.0.0.1:8000"
case dev = "https://dev.werkout.fitness" case dev = "https://werkout.treytartt.com"
static var currentBaseURL: String { static var currentBaseURL: String {
return BaseURLs.dev.rawValue return BaseURLs.dev.rawValue

View File

@@ -9,15 +9,18 @@ import Foundation
extension BridgeModule { extension BridgeModule {
func startWorkoutTimer() { func startWorkoutTimer() {
currentWorkoutRunTimer?.invalidate() DispatchQueue.main.async {
currentWorkoutRunTimer = nil self.currentWorkoutRunTimer?.invalidate()
currentWorkoutRunTimer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true, block: { [weak self] _ in self.currentWorkoutRunTimer = nil
guard let self else { return } self.currentWorkoutRunTimer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true, block: { [weak self] _ in
self.currentWorkoutRunTimeInSeconds += 1 guard let self else { return }
self.sendCurrentExerciseToWatch() dispatchPrecondition(condition: .onQueue(.main))
}) self.currentWorkoutRunTimeInSeconds += 1
currentWorkoutRunTimer?.tolerance = 0.1 self.sendCurrentExerciseToWatch()
currentWorkoutRunTimer?.fire() })
self.currentWorkoutRunTimer?.tolerance = 0.1
self.currentWorkoutRunTimer?.fire()
}
} }
func startExerciseTimerWith(duration: Int) { func startExerciseTimerWith(duration: Int) {

View File

@@ -39,17 +39,21 @@ extension BridgeModule: WCSessionDelegate {
} }
private func flushQueuedWatchMessages() { private func flushQueuedWatchMessages() {
let queuedMessages = queuedWatchMessages.dequeueAll() watchMessageQueue.sync {
guard queuedMessages.isEmpty == false else { let queuedMessages = queuedWatchMessages.dequeueAll()
return guard queuedMessages.isEmpty == false else {
return
}
queuedMessages.forEach { send($0) }
} }
queuedMessages.forEach { send($0) }
} }
private func enqueueWatchMessage(_ data: Data) { private func enqueueWatchMessage(_ data: Data) {
let droppedCount = queuedWatchMessages.enqueue(data) watchMessageQueue.sync {
if droppedCount > 0 { let droppedCount = queuedWatchMessages.enqueue(data)
watchBridgeLogger.warning("Dropping oldest queued watch message to enforce queue cap") if droppedCount > 0 {
watchBridgeLogger.warning("Dropping oldest queued watch message to enforce queue cap")
}
} }
} }
@@ -90,7 +94,7 @@ extension BridgeModule: WCSessionDelegate {
} }
} }
func session(_ session: WCSession, didReceiveMessageData messageData: Data) { func dataToAction(messageData: Data) {
do { do {
let model = try WatchPayloadValidation.decode(WatchActions.self, from: messageData) let model = try WatchPayloadValidation.decode(WatchActions.self, from: messageData)
DispatchQueue.main.async { DispatchQueue.main.async {
@@ -119,6 +123,10 @@ extension BridgeModule: WCSessionDelegate {
watchBridgeLogger.error("Rejected WatchActions payload: \(error.localizedDescription, privacy: .public)") watchBridgeLogger.error("Rejected WatchActions payload: \(error.localizedDescription, privacy: .public)")
} }
} }
func session(_ session: WCSession, didReceiveMessageData messageData: Data) {
dataToAction(messageData: messageData)
}
func session(_ session: WCSession, func session(_ session: WCSession,
@@ -158,6 +166,22 @@ extension BridgeModule: WCSessionDelegate {
func sessionDidDeactivate(_ session: WCSession) { func sessionDidDeactivate(_ session: WCSession) {
session.activate() session.activate()
} }
func session(_ session: WCSession, didReceiveApplicationContext applicationContext: [String : Any]) {
if let messageData = applicationContext["package"] as? Data {
DispatchQueue.main.async {
self.dataToAction(messageData: messageData)
}
}
}
func session(_ session: WCSession, didReceiveUserInfo userInfo: [String : Any] = [:]) {
if let messageData = userInfo["package"] as? Data {
DispatchQueue.main.async {
self.dataToAction(messageData: messageData)
}
}
}
#endif #endif
func send(_ data: Data) { func send(_ data: Data) {
guard WCSession.isSupported() else { guard WCSession.isSupported() else {

View File

@@ -55,6 +55,7 @@ class BridgeModule: NSObject, ObservableObject {
@Published var isPaused = false @Published var isPaused = false
let session: WCSession = WCSession.default let session: WCSession = WCSession.default
let watchMessageQueue = DispatchQueue(label: "com.werkout.watchMessageQueue")
var queuedWatchMessages = BoundedFIFOQueue<Data>(maxCount: 100) var queuedWatchMessages = BoundedFIFOQueue<Data>(maxCount: 100)
var lastSentInExercisePayload: Data? var lastSentInExercisePayload: Data?
} }

View File

@@ -6,7 +6,7 @@
// //
import Foundation import Foundation
import SwiftUI import Combine
import SharedCore import SharedCore
class DataStore: ObservableObject { class DataStore: ObservableObject {

View File

@@ -17,7 +17,7 @@ class WorkoutDetailFetchable: Fetchable {
var endPoint: String var endPoint: String
init(workoutID: Int) { init(workoutID: Int) {
self.endPoint = "/workout/"+String(workoutID)+"/details/" self.endPoint = "/workout/\(workoutID)/details/"
} }
} }
@@ -103,7 +103,7 @@ class AllNSFWVideosFetchable: Fetchable {
var endPoint: String = "/videos/nsfw_videos/" var endPoint: String = "/videos/nsfw_videos/"
} }
class RefreshUserInfoFetcable: Fetchable { class RefreshUserInfoFetchable: Fetchable {
typealias Response = RegisteredUser typealias Response = RegisteredUser
var endPoint: String = "/registered_user/refresh/" var endPoint: String = "/registered_user/refresh/"
} }

View File

@@ -173,7 +173,7 @@ extension Postable {
} }
if let httpResponse = response as? HTTPURLResponse, if let httpResponse = response as? HTTPURLResponse,
httpResponse.statusCode != successStatus { !(200...299).contains(httpResponse.statusCode) {
let responseBody = data.flatMap { String(data: $0, encoding: .utf8) } let responseBody = data.flatMap { String(data: $0, encoding: .utf8) }
handleHTTPFailure(statusCode: httpResponse.statusCode, handleHTTPFailure(statusCode: httpResponse.statusCode,
responseBody: responseBody, responseBody: responseBody,

View File

@@ -148,7 +148,7 @@ class UserStore: ObservableObject {
} }
public func refreshUserData() { public func refreshUserData() {
RefreshUserInfoFetcable().fetch(completion: { result in RefreshUserInfoFetchable().fetch(completion: { result in
switch result { switch result {
case .success(let registeredUser): case .success(let registeredUser):
let sanitizedModel = self.userByReplacingToken(registeredUser, token: self.normalizedToken(from: registeredUser.token)) let sanitizedModel = self.userByReplacingToken(registeredUser, token: self.normalizedToken(from: registeredUser.token))
@@ -179,7 +179,7 @@ class UserStore: ObservableObject {
runtimeReporter.recordInfo("User logged out", metadata: ["reason": reason]) runtimeReporter.recordInfo("User logged out", metadata: ["reason": reason])
DispatchQueue.main.async { DispatchQueue.main.async {
NotificationCenter.default.post(name: AppNotifications.createdNewWorkout, object: nil, userInfo: nil) NotificationCenter.default.post(name: AppNotifications.userLoggedOut, object: nil, userInfo: nil)
} }
} }

View File

@@ -10,32 +10,34 @@ import SwiftUI
struct AccountView: View { struct AccountView: View {
@ObservedObject var userStore = UserStore.shared @ObservedObject var userStore = UserStore.shared
var body: some View { var body: some View {
VStack(alignment: .leading) { VStack(alignment: .leading) {
NameView() NameView()
CompletedWorkoutsView() CompletedWorkoutsView()
Divider() Divider()
.overlay(WerkoutTheme.divider)
ThotPreferenceView() ThotPreferenceView()
ShowNextUpView() ShowNextUpView()
Spacer() Spacer()
Logoutview() Logoutview()
} }
.padding() .padding()
.background(WerkoutTheme.background)
} }
} }
//struct AccountView_Previews: PreviewProvider { //struct AccountView_Previews: PreviewProvider {
// static let userStore = UserStore.shared // static let userStore = UserStore.shared
// static let completedWorkouts = PreviewData.parseCompletedWorkouts() // static let completedWorkouts = PreviewData.parseCompletedWorkouts()
// //
// static var previews: some View { // static var previews: some View {
// AccountView(completedWorkouts: completedWorkouts) // AccountView(completedWorkouts: completedWorkouts)
// .onAppear{ // .onAppear{

View File

@@ -14,77 +14,63 @@ struct AddExerciseView: View {
case muscles case muscles
case equipment case equipment
} }
@State var selectedMuscles = [Muscle]() @State var selectedMuscles = [Muscle]()
@State var selectedEquipment = [Equipment]() @State var selectedEquipment = [Equipment]()
@State var filteredExercises = [Exercise]() @State var filteredExercises = [Exercise]()
@StateObject var bridgeModule = BridgeModule.shared @ObservedObject var bridgeModule = BridgeModule.shared
let selectedExercise: ((Exercise) -> Void) let selectedExercise: ((Exercise) -> Void)
var body: some View { var body: some View {
VStack { VStack(spacing: 0) {
AllExerciseView(filteredExercises: $filteredExercises, AllExerciseView(filteredExercises: $filteredExercises,
selectedExercise: { excercise in selectedExercise: { excercise in
selectedExercise(excercise) selectedExercise(excercise)
}) })
.padding(.top) .padding(.top, WerkoutTheme.md)
Divider()
.overlay(WerkoutTheme.divider)
HStack { HStack {
AllMusclesView(selectedMuscles: $selectedMuscles) AllMusclesView(selectedMuscles: $selectedMuscles)
.frame(maxWidth: .infinity) .frame(maxWidth: .infinity)
Divider() Divider()
.overlay(WerkoutTheme.divider)
AllEquipmentView(selectedEquipment: $selectedEquipment) AllEquipmentView(selectedEquipment: $selectedEquipment)
.frame(maxWidth: .infinity) .frame(maxWidth: .infinity)
} }
.padding(.top) .padding(.top, WerkoutTheme.sm)
.frame(height: 44) .frame(height: 44)
} }
.onChange(of: selectedMuscles, perform: { _ in .background(WerkoutTheme.background)
.onChange(of: selectedMuscles) { _, _ in
filterExercises() filterExercises()
}) .onChange(of: selectedEquipment, perform: { _ in }
.onChange(of: selectedEquipment) { _, _ in
filterExercises() filterExercises()
}) }
} }
func filterExercises() { func filterExercises() {
guard let exercises = DataStore.shared.allExercise else { guard let exercises = DataStore.shared.allExercise else {
filteredExercises = [] filteredExercises = []
return return
} }
let filtered = exercises.filter({ exercise in let selectedMuscleIds = Set(selectedMuscles.map { $0.id })
var hasCorrectMuscles = false let selectedEquipmentIds = Set(selectedEquipment.map { $0.id })
if selectedMuscles.count == 0 {
hasCorrectMuscles = true filteredExercises = exercises.filter { exercise in
} else { let muscleOK = selectedMuscleIds.isEmpty ||
let exerciseMuscleIds = exercise.muscles.map({ $0.muscle ?? -1 }) exercise.muscles.contains(where: { selectedMuscleIds.contains($0.muscle ?? -1) })
let selctedMuscleIds = selectedMuscles.map({ $0.id }) let equipmentOK = selectedEquipmentIds.isEmpty ||
// if one items match exercise.equipment.contains(where: { selectedEquipmentIds.contains($0.equipment ?? -1) })
if exerciseMuscleIds.contains(where: selctedMuscleIds.contains) { return muscleOK && equipmentOK
// if all items match }
hasCorrectMuscles = true
}
}
var hasCorrectEquipment = false
if selectedEquipment.count == 0 {
hasCorrectEquipment = true
} else {
let exerciseEquipmentIds = exercise.equipment.map({ $0.equipment ?? -1 })
let selctedEquipmentIds = selectedEquipment.map({ $0.id })
// if one items match
if exerciseEquipmentIds.contains(where: selctedEquipmentIds.contains) {
// if all items match
hasCorrectEquipment = true
}
}
return hasCorrectMuscles && hasCorrectEquipment
})
filteredExercises = filtered
} }
} }

View File

@@ -13,88 +13,88 @@ enum SortType: String, CaseIterable {
} }
struct AllWorkoutsListView: View { struct AllWorkoutsListView: View {
@State var searchNameString: String = ""
@State var selectedMuscles: Set<String> = []
@State var selectedEquipment: Set<String> = []
@Binding var uniqueWorkoutUsers: [RegisteredUser]?
@State private var filteredRegisterdUser: RegisteredUser?
let workouts: [Workout] let workouts: [Workout]
@Binding var searchText: String
@Binding var selectedMuscles: Set<String>
@Binding var selectedEquipment: Set<String>
@Binding var filteredRegisterdUser: RegisteredUser?
@Binding var currentSort: SortType?
@Binding var sortAscending: Bool
let selectedWorkout: ((Workout) -> Void) let selectedWorkout: ((Workout) -> Void)
@State var filteredWorkouts = [Workout]()
var refresh: (() -> Void) var refresh: (() -> Void)
@State var currentSort: SortType?
@State private var filteredWorkouts = [Workout]()
var body: some View { var body: some View {
VStack { ScrollView {
VStack { LazyVStack(spacing: WerkoutTheme.sm) {
if let filteredRegisterdUser = filteredRegisterdUser { ForEach(filteredWorkouts, id: \.id) { workout in
Text((filteredRegisterdUser.firstName ?? "NA") + "'s Workouts") Button(action: {
} selectedWorkout(workout)
}, label: {
FilterAllView(selectedMuscles: $selectedMuscles, WorkoutOverviewView(workout: workout)
selectedEquipment: $selectedEquipment, .padding(.horizontal, WerkoutTheme.sm)
searchNameString: $searchNameString, .contentShape(Rectangle())
uniqueWorkoutUsers: $uniqueWorkoutUsers, })
filteredRegisterdUser: $filteredRegisterdUser, .buttonStyle(.plain)
filteredWorkouts: $filteredWorkouts, .accessibilityLabel("Open \(workout.name)")
workouts: .constant(workouts), .accessibilityHint("Shows workout details")
currentSort: $currentSort)
}
ScrollView {
LazyVStack(spacing: 10) {
ForEach(filteredWorkouts, id:\.id) { workout in
Button(action: {
selectedWorkout(workout)
}, label: {
WorkoutOverviewView(workout: workout)
.padding([.leading, .trailing], 4)
.contentShape(Rectangle())
})
.buttonStyle(.plain)
.accessibilityLabel("Open \(workout.name)")
.accessibilityHint("Shows workout details")
}
} }
} }
.background(Color(uiColor: .systemBackground)) .padding(.top, WerkoutTheme.sm)
.refreshable {
refresh()
}
} }
.onChange(of: searchNameString) { newValue in .scrollEdgeEffectStyle(.soft, for: .top)
filterWorkouts() .background(WerkoutTheme.background)
.refreshable {
refresh()
} }
.onChange(of: selectedMuscles) { newValue in .onAppear {
filterWorkouts() applyFilters()
}
.onChange(of: selectedEquipment) { newValue in
filterWorkouts()
}
.onAppear{
filterWorkouts()
}
.onChange(of: workouts) { _ in
filterWorkouts()
} }
.onChange(of: searchText) { applyFilters() }
.onChange(of: selectedMuscles) { applyFilters() }
.onChange(of: selectedEquipment) { applyFilters() }
.onChange(of: filteredRegisterdUser) { applyFilters() }
.onChange(of: currentSort) { applyFilters() }
.onChange(of: sortAscending) { applyFilters() }
.onChange(of: workouts) { applyFilters() }
} }
func filterWorkouts() { private func applyFilters() {
filteredWorkouts = workouts.filterWorkouts( var results = workouts.filterWorkouts(
nameSearchString: searchNameString, nameSearchString: searchText,
musclesSearchString: selectedMuscles, musclesSearchString: selectedMuscles,
equipmentSearchString: selectedEquipment, equipmentSearchString: selectedEquipment,
filteredRegisterdUser: filteredRegisterdUser filteredRegisterdUser: filteredRegisterdUser
) )
if let sort = currentSort {
switch sort {
case .name:
results.sort { $0.name < $1.name }
case .createdDate:
results.sort { ($0.createdAt ?? Date()) < ($1.createdAt ?? Date()) }
}
if !sortAscending {
results.reverse()
}
}
filteredWorkouts = results
} }
} }
struct AllWorkoutsListView_Previews: PreviewProvider { struct AllWorkoutsListView_Previews: PreviewProvider {
static var previews: some View { static var previews: some View {
AllWorkoutsListView(uniqueWorkoutUsers: .constant([]), AllWorkoutsListView(workouts: PreviewData.allWorkouts(),
workouts: PreviewData.allWorkouts(), searchText: .constant(""),
selectedWorkout: { workout in }, selectedMuscles: .constant([]),
refresh: { }) selectedEquipment: .constant([]),
filteredRegisterdUser: .constant(nil),
currentSort: .constant(nil),
sortAscending: .constant(true),
selectedWorkout: { _ in },
refresh: {})
} }
} }

View File

@@ -13,88 +13,142 @@ import SharedCore
enum MainViewTypes: Int, CaseIterable { enum MainViewTypes: Int, CaseIterable {
case AllWorkout = 0 case AllWorkout = 0
case MyWorkouts case MyWorkouts
var title: String { var title: String {
switch self { switch self {
case .AllWorkout: case .AllWorkout:
return "All Workouts" return "All Workouts"
case .MyWorkouts: case .MyWorkouts:
return "Planned Workouts" return "Planned"
} }
} }
} }
struct AllWorkoutsView: View { struct AllWorkoutsView: View {
@State var isUpdating = false @State private var isUpdating = false
@State var workouts: [Workout]?
@State var uniqueWorkoutUsers: [RegisteredUser]? private var workouts: [Workout]? {
dataStore.allWorkouts?.sorted(by: { $0.createdAt ?? Date() < $1.createdAt ?? Date() })
}
private var uniqueWorkoutUsers: [RegisteredUser]? {
dataStore.workoutsUniqueUsers
}
let healthStore = HKHealthStore() let healthStore = HKHealthStore()
var bridgeModule = BridgeModule.shared var bridgeModule = BridgeModule.shared
@State public var needsUpdating: Bool = true @State private var needsUpdating: Bool = true
@ObservedObject var dataStore = DataStore.shared @ObservedObject var dataStore = DataStore.shared
@ObservedObject var userStore = UserStore.shared @ObservedObject var userStore = UserStore.shared
@State private var showWorkoutDetail = false @State private var showWorkoutDetail = false
@State private var selectedWorkout: Workout? { @State private var selectedWorkout: Workout? {
didSet { didSet {
bridgeModule.currentWorkoutInfo.workout = selectedWorkout bridgeModule.currentWorkoutInfo.workout = selectedWorkout
} }
} }
@State private var selectedPlannedWorkout: Workout? { @State private var selectedPlannedWorkout: Workout? {
didSet { didSet {
bridgeModule.currentWorkoutInfo.workout = selectedPlannedWorkout bridgeModule.currentWorkoutInfo.workout = selectedPlannedWorkout
} }
} }
@State private var showLoginView = false @State private var showLoginView = false
@State private var selectedSegment: MainViewTypes = .AllWorkout @State private var selectedSegment: MainViewTypes = .AllWorkout
@State var selectedDate: Date = Date() @State private var selectedDate: Date = Date()
private let runtimeReporter = RuntimeReporter.shared private let runtimeReporter = RuntimeReporter.shared
// MARK: - Hoisted filter state
@State private var searchText = ""
@State private var selectedMuscles: Set<String> = []
@State private var selectedEquipment: Set<String> = []
@State private var filteredRegisterdUser: RegisteredUser?
@State private var currentSort: SortType?
@State private var sortAscending: Bool = true
let pub = NotificationCenter.default.publisher(for: AppNotifications.createdNewWorkout) let pub = NotificationCenter.default.publisher(for: AppNotifications.createdNewWorkout)
var body: some View { private var hasActiveFilters: Bool {
ZStack { !selectedMuscles.isEmpty || !selectedEquipment.isEmpty || filteredRegisterdUser != nil
if let workouts = workouts { }
VStack {
AllWorkoutPickerView(mainViews: MainViewTypes.allCases,
selectedSegment: $selectedSegment,
showCurrentWorkout: {
selectedWorkout = bridgeModule.currentWorkoutInfo.workout
})
switch selectedSegment {
case .AllWorkout:
if isUpdating {
ProgressView()
.progressViewStyle(.circular)
}
AllWorkoutsListView(uniqueWorkoutUsers: $uniqueWorkoutUsers,
workouts: workouts,
selectedWorkout: { workout in
selectedWorkout = workout
}, refresh: {
self.needsUpdating = true
maybeRefreshData()
})
Divider() var body: some View {
case .MyWorkouts: NavigationStack {
PlannedWorkoutView(workouts: userStore.plannedWorkouts, ZStack {
selectedPlannedWorkout: $selectedPlannedWorkout) WerkoutTheme.background.ignoresSafeArea()
if let workouts = workouts {
VStack(spacing: 0) {
// Active filter chips
if hasActiveFilters {
filterChipsRow
}
switch selectedSegment {
case .AllWorkout:
if isUpdating {
ProgressView()
.progressViewStyle(.circular)
.tint(WerkoutTheme.accent)
}
AllWorkoutsListView(workouts: workouts,
searchText: $searchText,
selectedMuscles: $selectedMuscles,
selectedEquipment: $selectedEquipment,
filteredRegisterdUser: $filteredRegisterdUser,
currentSort: $currentSort,
sortAscending: $sortAscending,
selectedWorkout: { workout in
selectedWorkout = workout
}, refresh: {
self.needsUpdating = true
maybeRefreshData()
})
case .MyWorkouts:
PlannedWorkoutView(workouts: userStore.plannedWorkouts,
selectedPlannedWorkout: $selectedPlannedWorkout)
}
}
} else {
ProgressView()
.progressViewStyle(.circular)
.tint(WerkoutTheme.accent)
}
}
.navigationTitle("Workouts")
.searchable(text: $searchText, prompt: "Search workouts")
.toolbar {
ToolbarItem(placement: .principal) {
Picker("View", selection: $selectedSegment) {
ForEach(MainViewTypes.allCases, id: \.self) { viewType in
Text(viewType.title).tag(viewType)
}
}
.pickerStyle(.segmented)
.frame(width: 200)
}
ToolbarItem(placement: .topBarTrailing) {
HStack(spacing: WerkoutTheme.sm) {
if bridgeModule.isInWorkout {
Button(action: {
selectedWorkout = bridgeModule.currentWorkoutInfo.workout
}) {
Image(systemName: "figure.strengthtraining.traditional")
}
.tint(WerkoutTheme.accent)
}
filterMenu
} }
} }
} else {
ProgressView("Updating")
} }
} }
.background(Color(uiColor: .systemGray5)) .onAppear {
.onAppear{
// UserStore.shared.logout()
authorizeHealthKit() authorizeHealthKit()
maybeRefreshData() maybeRefreshData()
} }
@@ -114,31 +168,171 @@ struct AllWorkoutsView: View {
}) })
.interactiveDismissDisabled() .interactiveDismissDisabled()
} }
.onReceive(pub) { (output) in .onReceive(pub) { _ in
self.needsUpdating = true self.needsUpdating = true
maybeRefreshData() maybeRefreshData()
} }
} }
// MARK: - Filter Menu
private var filterMenu: some View {
Menu {
// Sort section
Section("Sort") {
ForEach(SortType.allCases, id: \.self) { sortType in
Button(action: {
if currentSort == sortType {
sortAscending.toggle()
} else {
currentSort = sortType
sortAscending = true
}
}) {
Label {
Text(sortType.rawValue)
} icon: {
if currentSort == sortType {
Image(systemName: sortAscending ? "chevron.up" : "chevron.down")
}
}
}
}
}
// Creator filter
if let users = uniqueWorkoutUsers, !users.isEmpty {
Section("Creator") {
ForEach(users, id: \.self) { user in
Button(action: {
filteredRegisterdUser = user
}) {
Label {
Text("\(user.firstName ?? "") \(user.lastName ?? "")")
} icon: {
if filteredRegisterdUser == user {
Image(systemName: "checkmark")
}
}
}
}
Button("All Creators") {
filteredRegisterdUser = nil
}
}
}
// Muscles filter
if let muscles = DataStore.shared.allMuscles {
Section("Muscles") {
ForEach(muscles, id: \.id) { muscle in
Button(action: {
if selectedMuscles.contains(muscle.name) {
selectedMuscles.remove(muscle.name)
} else {
selectedMuscles.insert(muscle.name)
}
}) {
Label {
Text(muscle.name)
} icon: {
if selectedMuscles.contains(muscle.name) {
Image(systemName: "checkmark")
}
}
}
}
}
}
// Equipment filter
if let equipments = DataStore.shared.allEquipment {
Section("Equipment") {
ForEach(equipments, id: \.id) { equipment in
Button(action: {
if selectedEquipment.contains(equipment.name) {
selectedEquipment.remove(equipment.name)
} else {
selectedEquipment.insert(equipment.name)
}
}) {
Label {
Text(equipment.name)
} icon: {
if selectedEquipment.contains(equipment.name) {
Image(systemName: "checkmark")
}
}
}
}
}
}
// Clear all
if hasActiveFilters || currentSort != nil {
Divider()
Button(role: .destructive) {
clearAllFilters()
} label: {
Label("Clear All Filters", systemImage: "xmark.circle")
}
}
} label: {
Image(systemName: hasActiveFilters ? "line.3.horizontal.decrease.circle.fill" : "line.3.horizontal.decrease.circle")
}
.tint(hasActiveFilters ? WerkoutTheme.accent : nil)
}
// MARK: - Filter Chips Row
private var filterChipsRow: some View {
ScrollView(.horizontal, showsIndicators: false) {
HStack(spacing: WerkoutTheme.sm) {
ForEach(Array(selectedMuscles), id: \.self) { muscle in
FilterChip(label: muscle, color: WerkoutTheme.accent) {
selectedMuscles.remove(muscle)
}
}
ForEach(Array(selectedEquipment), id: \.self) { equipment in
FilterChip(label: equipment, color: WerkoutTheme.textSecondary) {
selectedEquipment.remove(equipment)
}
}
if let user = filteredRegisterdUser {
FilterChip(label: user.firstName ?? "User", color: WerkoutTheme.accentNeon) {
filteredRegisterdUser = nil
}
}
}
.padding(.horizontal, WerkoutTheme.md)
.padding(.vertical, WerkoutTheme.xs)
}
}
// MARK: - Actions
private func clearAllFilters() {
selectedMuscles.removeAll()
selectedEquipment.removeAll()
filteredRegisterdUser = nil
currentSort = nil
sortAscending = true
}
func maybeRefreshData() { func maybeRefreshData() {
if userStore.token != nil{ if userStore.token != nil {
if userStore.plannedWorkouts.isEmpty { if userStore.plannedWorkouts.isEmpty {
userStore.fetchPlannedWorkouts() userStore.fetchPlannedWorkouts()
} }
if needsUpdating { if needsUpdating {
self.isUpdating = true self.isUpdating = true
dataStore.fetchAllData(completion: { dataStore.fetchAllData(completion: {
DispatchQueue.main.async { DispatchQueue.main.async {
guard let allWorkouts = dataStore.allWorkouts else {
self.isUpdating = false
return
}
self.workouts = allWorkouts.sorted(by: {
$0.createdAt ?? Date() < $1.createdAt ?? Date()
})
self.isUpdating = false self.isUpdating = false
self.uniqueWorkoutUsers = dataStore.workoutsUniqueUsers
self.needsUpdating = false self.needsUpdating = false
} }
}) })
@@ -148,7 +342,7 @@ struct AllWorkoutsView: View {
showLoginView = true showLoginView = true
} }
} }
func authorizeHealthKit() { func authorizeHealthKit() {
let quantityTypes = [ let quantityTypes = [
HKObjectType.quantityType(forIdentifier: .heartRate), HKObjectType.quantityType(forIdentifier: .heartRate),
@@ -162,7 +356,7 @@ struct AllWorkoutsView: View {
HKQuantityType.workoutType() HKQuantityType.workoutType()
] ]
) )
healthStore.requestAuthorization(toShare: nil, read: healthKitTypes) { (success, error) in healthStore.requestAuthorization(toShare: nil, read: healthKitTypes) { (success, error) in
if success == false { if success == false {
runtimeReporter.recordWarning( runtimeReporter.recordWarning(
@@ -176,6 +370,6 @@ struct AllWorkoutsView: View {
struct AllWorkoutsView_Previews: PreviewProvider { struct AllWorkoutsView_Previews: PreviewProvider {
static var previews: some View { static var previews: some View {
AllWorkoutsView(workouts: PreviewData.allWorkouts()) AllWorkoutsView()
} }
} }

View File

@@ -11,15 +11,15 @@ import SharedCore
struct CompletedWorkoutView: View { struct CompletedWorkoutView: View {
@ObservedObject var bridgeModule = BridgeModule.shared @ObservedObject var bridgeModule = BridgeModule.shared
@State var healthKitWorkoutData: HealthKitWorkoutData? @State private var healthKitWorkoutData: HealthKitWorkoutData?
@State var difficulty: Float = 0 @State private var difficulty: Float = 0
@State var notes: String = "" @State private var notes: String = ""
@State var isUploading: Bool = false @State private var isUploading: Bool = false
@State var gettingHealthKitData: Bool = false @State private var gettingHealthKitData: Bool = false
@State private var hasError = false @State private var hasError = false
@State private var errorMessage = "" @State private var errorMessage = ""
private let runtimeReporter = RuntimeReporter.shared private let runtimeReporter = RuntimeReporter.shared
var postData: [String: Any] var postData: [String: Any]
let healthKitHelper = HealthKitHelper() let healthKitHelper = HealthKitHelper()
let workout: Workout let workout: Workout
@@ -29,48 +29,65 @@ struct CompletedWorkoutView: View {
var body: some View { var body: some View {
ZStack { ZStack {
WerkoutTheme.background
.ignoresSafeArea()
if isUploading { if isUploading {
ProgressView("Uploading") ProgressView("Uploading")
.foregroundStyle(WerkoutTheme.textPrimary)
.progressViewStyle(CircularProgressViewStyle(tint: WerkoutTheme.accent))
} }
VStack { VStack {
WorkoutInfoView(workout: workout) WorkoutInfoView(workout: workout)
Divider() Divider()
.overlay(WerkoutTheme.divider)
HStack { HStack {
if let calsBurned = healthKitWorkoutData?.caloriesBurned { if let calsBurned = healthKitWorkoutData?.caloriesBurned {
CaloriesBurnedView(healthKitWorkoutData: $healthKitWorkoutData, CaloriesBurnedView(healthKitWorkoutData: $healthKitWorkoutData,
calsBurned: calsBurned) calsBurned: calsBurned)
} }
} }
RateWorkoutView(difficulty: $difficulty) RateWorkoutView(difficulty: $difficulty)
.frame(maxHeight: 88) .frame(maxHeight: 88)
Divider() Divider()
.overlay(WerkoutTheme.divider)
TextField("Notes", text: $notes) TextField("Notes", text: $notes)
.font(WerkoutTheme.bodyText)
.foregroundStyle(WerkoutTheme.textPrimary)
.frame(height: 55) .frame(height: 55)
.textFieldStyle(PlainTextFieldStyle()) .textFieldStyle(PlainTextFieldStyle())
.padding([.horizontal], 4) .padding([.horizontal], 4)
.overlay(RoundedRectangle(cornerRadius: 16).stroke(Color(uiColor: .clear))).background(Color(uiColor: .init(red: 200/255, green: 200/255, blue: 200/255, alpha: 0.2))) .background(WerkoutTheme.surfaceElevated)
.cornerRadius(8) .overlay(
RoundedRectangle(cornerRadius: WerkoutTheme.buttonRadius, style: .continuous)
.strokeBorder(WerkoutTheme.divider, lineWidth: 1)
)
.clipShape(RoundedRectangle(cornerRadius: WerkoutTheme.buttonRadius, style: .continuous))
if gettingHealthKitData { if gettingHealthKitData {
ProgressView("Getting HealthKit data") ProgressView("Getting HealthKit data")
.foregroundStyle(WerkoutTheme.textPrimary)
.progressViewStyle(CircularProgressViewStyle(tint: WerkoutTheme.accent))
.padding() .padding()
} }
Spacer() Spacer()
Button("Upload", action: { Button("Upload", action: {
upload(postBody: postData) upload(postBody: postData)
}) })
.font(.system(size: 16, weight: .bold))
.foregroundStyle(WerkoutTheme.textPrimary)
.frame(maxWidth: .infinity, alignment: .center) .frame(maxWidth: .infinity, alignment: .center)
.frame(height: 44) .frame(height: 44)
.foregroundColor(.blue) .glassEffect(.regular.interactive())
.background(.yellow) .tint(WerkoutTheme.success)
.cornerRadius(Constants.buttonRadius) .clipShape(RoundedRectangle(cornerRadius: WerkoutTheme.buttonRadius, style: .continuous))
.padding() .padding()
.frame(maxWidth: .infinity) .frame(maxWidth: .infinity)
.disabled(isUploading || gettingHealthKitData) .disabled(isUploading || gettingHealthKitData)
@@ -82,19 +99,6 @@ struct CompletedWorkoutView: View {
} message: { } message: {
Text(errorMessage) Text(errorMessage)
} }
// .onChange(of: bridgeModule.healthKitUUID, perform: { healthKitUUID in
// if let healthKitUUID = healthKitUUID {
// gettingHealthKitData = true
// healthKitHelper.getDetails(forHealthKitUUID: healthKitUUID,
// completion: { healthKitWorkoutData in
// guard let healthStore = healthKitWorkoutData else {
// return
// }
// self.healthKitWorkoutData = healthKitWorkoutData
// gettingHealthKitData = false
// })
// }
// })
} }
func upload(postBody: [String: Any]) { func upload(postBody: [String: Any]) {
@@ -143,9 +147,9 @@ struct CompletedWorkoutView_Previews: PreviewProvider {
"total_calories": Float(120.0), "total_calories": Float(120.0),
"heart_rates": [65,65,4,54,232,12] "heart_rates": [65,65,4,54,232,12]
] as [String : Any] ] as [String : Any]
static let workout = PreviewData.workout() static let workout = PreviewData.workout()
static var previews: some View { static var previews: some View {
CompletedWorkoutView(postData: CompletedWorkoutView_Previews.postBody, CompletedWorkoutView(postData: CompletedWorkoutView_Previews.postBody,
workout: workout, workout: workout,

View File

@@ -12,8 +12,8 @@ struct CreateExerciseActionsView: View {
@ObservedObject var workoutExercise: CreateWorkoutExercise @ObservedObject var workoutExercise: CreateWorkoutExercise
@ObservedObject var superset: CreateWorkoutSuperSet @ObservedObject var superset: CreateWorkoutSuperSet
var viewModel: WorkoutViewModel var viewModel: WorkoutViewModel
@State var avPlayer = AVPlayer(url: URL(string: "https://dev.werkout.fitness/media/exercise_videos/2_Dumbbell_Lateral_Lunges.mp4") ?? URL(fileURLWithPath: "/dev/null")) @State var avPlayer = AVPlayer(url: URL(string: BaseURLs.currentBaseURL + "/media/exercise_videos/2_Dumbbell_Lateral_Lunges.mp4") ?? URL(fileURLWithPath: "/dev/null"))
@State private var currentVideoURL: URL? @State private var currentVideoURL: URL?
@State var videoExercise: Exercise? { @State var videoExercise: Exercise? {
didSet { didSet {
@@ -23,90 +23,103 @@ struct CreateExerciseActionsView: View {
} }
} }
} }
var body: some View { var body: some View {
VStack { VStack(spacing: WerkoutTheme.sm) {
VStack { VStack(spacing: WerkoutTheme.xs) {
HStack { HStack {
Text("Reps: ") Text("Reps: ")
.font(WerkoutTheme.bodyText)
.foregroundStyle(WerkoutTheme.textSecondary)
Text("\(workoutExercise.reps)") Text("\(workoutExercise.reps)")
.foregroundColor(workoutExercise.reps == 0 && workoutExercise.duration == 0 ? .red : Color(uiColor: .label)) .foregroundColor(workoutExercise.reps == 0 && workoutExercise.duration == 0 ? WerkoutTheme.danger : WerkoutTheme.textPrimary)
.font(WerkoutTheme.bodyText)
.bold() .bold()
Stepper("", onIncrement: { Stepper("", onIncrement: {
workoutExercise.increaseReps() workoutExercise.increaseReps()
}, onDecrement: { }, onDecrement: {
workoutExercise.decreaseReps() workoutExercise.decreaseReps()
}) })
.tint(WerkoutTheme.accent)
.accessibilityLabel("Reps") .accessibilityLabel("Reps")
} }
} }
HStack { HStack {
Text("Weight: ") Text("Weight: ")
.font(WerkoutTheme.bodyText)
.foregroundStyle(WerkoutTheme.textSecondary)
Text("\(workoutExercise.weight)") Text("\(workoutExercise.weight)")
.font(WerkoutTheme.bodyText)
.foregroundStyle(WerkoutTheme.textPrimary)
Stepper("", onIncrement: { Stepper("", onIncrement: {
workoutExercise.increaseWeight() workoutExercise.increaseWeight()
}, onDecrement: { }, onDecrement: {
workoutExercise.decreaseWeight() workoutExercise.decreaseWeight()
}) })
.tint(WerkoutTheme.accent)
.accessibilityLabel("Weight") .accessibilityLabel("Weight")
} }
HStack { HStack {
Text("Duration: ") Text("Duration: ")
.font(WerkoutTheme.bodyText)
.foregroundStyle(WerkoutTheme.textSecondary)
Text("\(workoutExercise.duration)") Text("\(workoutExercise.duration)")
.foregroundColor( .foregroundColor(
workoutExercise.reps == 0 && workoutExercise.duration == 0 ? .red : Color( workoutExercise.reps == 0 && workoutExercise.duration == 0 ? WerkoutTheme.danger : WerkoutTheme.textPrimary
uiColor: .label
)
) )
.font(WerkoutTheme.bodyText)
.bold() .bold()
Stepper("", onIncrement: { Stepper("", onIncrement: {
workoutExercise.increaseDuration() workoutExercise.increaseDuration()
}, onDecrement: { }, onDecrement: {
workoutExercise.decreaseDuration() workoutExercise.decreaseDuration()
}) })
.tint(WerkoutTheme.accent)
.accessibilityLabel("Duration") .accessibilityLabel("Duration")
} }
HStack { GlassEffectContainer {
Spacer() HStack {
Button(action: { Spacer()
videoExercise = workoutExercise.exercise Button(action: {
}) { videoExercise = workoutExercise.exercise
Image(systemName: "video.fill") }) {
Image(systemName: "video.fill")
.foregroundStyle(WerkoutTheme.textPrimary)
}
.frame(width: 88, height: 44)
.glassEffect(.regular.interactive())
.tint(WerkoutTheme.accent)
.buttonStyle(BorderlessButtonStyle())
.accessibilityLabel("Preview exercise video")
.accessibilityHint("Opens a video preview for this exercise")
Spacer()
Spacer()
Button(action: {
superset
.deleteExerciseForChosenSuperset(exercise: workoutExercise)
viewModel.increaseRandomNumberForUpdating()
}) {
Image(systemName: "trash.fill")
.foregroundStyle(WerkoutTheme.textPrimary)
}
.frame(width: 88, height: 44)
.glassEffect(.regular.interactive())
.tint(WerkoutTheme.danger)
.buttonStyle(BorderlessButtonStyle())
.accessibilityLabel("Delete exercise")
.accessibilityHint("Removes this exercise from the superset")
Spacer()
} }
.frame(width: 88, height: 44)
.foregroundColor(.white)
.background(.blue)
.cornerRadius(Constants.buttonRadius)
.buttonStyle(BorderlessButtonStyle())
.accessibilityLabel("Preview exercise video")
.accessibilityHint("Opens a video preview for this exercise")
Spacer()
Spacer()
Button(action: {
superset
.deleteExerciseForChosenSuperset(exercise: workoutExercise)
viewModel.increaseRandomNumberForUpdating()
}) {
Image(systemName: "trash.fill")
}
.frame(width: 88, height: 44)
.foregroundColor(.white)
.background(.red)
.cornerRadius(Constants.buttonRadius)
.buttonStyle(BorderlessButtonStyle())
.accessibilityLabel("Delete exercise")
.accessibilityHint("Removes this exercise from the superset")
Spacer()
} }
} }
.sheet(item: $videoExercise) { exercise in .sheet(item: $videoExercise) { exercise in

View File

@@ -5,7 +5,8 @@
// Created by Trey Tartt on 6/18/23. // Created by Trey Tartt on 6/18/23.
// //
import SwiftUI import Combine
import Foundation
import SharedCore import SharedCore
class CreateWorkoutExercise: ObservableObject, Identifiable { class CreateWorkoutExercise: ObservableObject, Identifiable {
@@ -93,6 +94,9 @@ class WorkoutViewModel: ObservableObject {
@Published var description = String() @Published var description = String()
@Published var validationError: String? @Published var validationError: String?
@Published var isUploading = false @Published var isUploading = false
// MARK: - Manual Invalidation
// Workaround: nested ObservableObject changes don't propagate to parent.
// Remove when migrating to @Observable (iOS 17+).
@Published var randomValueForUpdatingValue = 0 @Published var randomValueForUpdatingValue = 0
func increaseRandomNumberForUpdating() { func increaseRandomNumberForUpdating() {
@@ -112,7 +116,32 @@ class WorkoutViewModel: ObservableObject {
increaseRandomNumberForUpdating() increaseRandomNumberForUpdating()
} }
} }
func addExercise(_ exercise: Exercise, to superset: CreateWorkoutSuperSet) {
let workoutExercise = CreateWorkoutExercise(exercise: exercise)
superset.exercises.append(workoutExercise)
if exercise.side?.isEmpty == false {
autoAddSiblingExercises(for: exercise, to: superset)
}
increaseRandomNumberForUpdating()
}
private func autoAddSiblingExercises(for exercise: Exercise, to superset: CreateWorkoutSuperSet) {
guard let allExercises = DataStore.shared.allExercise else { return }
let siblings = allExercises.filter { $0.name == exercise.name }
guard siblings.count == 2,
let recover = allExercises.first(where: { $0.name.lowercased() == "recover" }) else { return }
let recoverExercise = CreateWorkoutExercise(exercise: recover)
superset.exercises.append(recoverExercise)
for sibling in siblings where sibling.id != exercise.id {
let otherSideExercise = CreateWorkoutExercise(exercise: sibling)
superset.exercises.append(otherSideExercise)
}
}
func showRoundsError() { func showRoundsError() {
validationError = "Each superset must have at least one round." validationError = "Each superset must have at least one round."
} }

View File

@@ -15,16 +15,16 @@ struct CreateWorkoutItemPickerModel {
class CreateWorkoutItemPickerViewModel: Identifiable, ObservableObject { class CreateWorkoutItemPickerViewModel: Identifiable, ObservableObject {
let allValues: [CreateWorkoutItemPickerModel] let allValues: [CreateWorkoutItemPickerModel]
@Published var selectedIds: [Int] @Published var selectedIds: Set<Int>
init(allValues: [CreateWorkoutItemPickerModel], selectedIds: [Int]) { init(allValues: [CreateWorkoutItemPickerModel], selectedIds: [Int]) {
self.allValues = allValues self.allValues = allValues
self.selectedIds = selectedIds self.selectedIds = Set(selectedIds)
} }
func toggleAll() { func toggleAll() {
if selectedIds.isEmpty { if selectedIds.isEmpty {
selectedIds.append(contentsOf: allValues.map({ $0.id })) selectedIds = Set(allValues.map({ $0.id }))
} else { } else {
selectedIds.removeAll() selectedIds.removeAll()
} }
@@ -38,65 +38,71 @@ struct CreateWorkoutItemPickerView: View {
@State var searchString: String = "" @State var searchString: String = ""
var body: some View { var body: some View {
VStack { VStack(spacing: 0) {
List() { List() {
ForEach(viewModel.allValues, id:\.self.id) { value in ForEach(viewModel.allValues, id:\.self.id) { value in
if searchString.isEmpty || value.name.lowercased().contains(searchString.lowercased()) { if searchString.isEmpty || value.name.lowercased().contains(searchString.lowercased()) {
HStack { HStack(spacing: WerkoutTheme.sm) {
Circle() Circle()
.stroke(.blue, lineWidth: 1) .stroke(WerkoutTheme.accent, lineWidth: 1.5)
.background(Circle().fill(viewModel.selectedIds.contains(value.id) ? .blue :.clear)) .background(Circle().fill(viewModel.selectedIds.contains(value.id) ? WerkoutTheme.accent : Color.clear))
.frame(width: 33, height: 33) .frame(width: 33, height: 33)
Text(value.name) Text(value.name)
.font(WerkoutTheme.bodyText)
.foregroundStyle(WerkoutTheme.textPrimary)
} }
.contentShape(Rectangle()) .contentShape(Rectangle())
.onTapGesture { .onTapGesture {
if viewModel.selectedIds.contains(value.id) { if viewModel.selectedIds.contains(value.id) {
if let idx = viewModel.selectedIds.firstIndex(of: value.id){ viewModel.selectedIds.remove(value.id)
viewModel.selectedIds.remove(at: idx)
}
} else { } else {
viewModel.selectedIds.append(value.id) viewModel.selectedIds.insert(value.id)
} }
} }
.listRowBackground(WerkoutTheme.surfaceCard)
} }
} }
} }
.scrollContentBackground(.hidden)
TextField("Filter", text: $searchString) .background(WerkoutTheme.background)
.padding()
HStack {
Button(action: {
viewModel.toggleAll()
}, label: {
Image(systemName: "checklist")
.font(.title)
})
.frame(maxWidth: 44, alignment: .center)
.frame(height: 44)
.foregroundColor(.green)
.background(.white)
.cornerRadius(Constants.buttonRadius)
.padding()
Button(action: { TextField("Filter", text: $searchString)
completed(viewModel.selectedIds) .werkoutTextField()
dismiss() .padding(.horizontal, WerkoutTheme.md)
}, label: { .padding(.vertical, WerkoutTheme.sm)
Text("done")
}) GlassEffectContainer {
.frame(maxWidth: .infinity, alignment: .center) HStack(spacing: WerkoutTheme.md) {
.frame(height: 44) Button(action: {
.foregroundColor(.blue) viewModel.toggleAll()
.background(.yellow) }, label: {
.cornerRadius(Constants.buttonRadius) Image(systemName: "checklist")
.padding() .font(.title)
.frame(maxWidth: .infinity) .foregroundStyle(WerkoutTheme.textPrimary)
})
.frame(width: 44, height: 44)
.glassEffect(.regular.interactive())
.tint(WerkoutTheme.success)
Button(action: {
completed(Array(viewModel.selectedIds))
dismiss()
}, label: {
Text("Done")
.font(.system(size: 16, weight: .bold))
.foregroundStyle(WerkoutTheme.textPrimary)
.frame(maxWidth: .infinity)
.frame(height: 44)
})
.glassEffect(.regular.interactive())
.tint(WerkoutTheme.accent)
}
.padding(.horizontal, WerkoutTheme.md)
.padding(.vertical, WerkoutTheme.sm)
} }
} }
.background(WerkoutTheme.background)
} }
} }
@@ -104,10 +110,10 @@ struct CreateWorkoutItemPickerView_Previews: PreviewProvider {
static let fakeValues = [CreateWorkoutItemPickerModel(id: 1, name: "one"), static let fakeValues = [CreateWorkoutItemPickerModel(id: 1, name: "one"),
CreateWorkoutItemPickerModel(id: 2, name: "two"), CreateWorkoutItemPickerModel(id: 2, name: "two"),
CreateWorkoutItemPickerModel(id: 3, name: "three")] CreateWorkoutItemPickerModel(id: 3, name: "three")]
static var previews: some View { static var previews: some View {
CreateWorkoutItemPickerView(viewModel: CreateWorkoutItemPickerViewModel(allValues: fakeValues, selectedIds: [1]), completed: { selectedIds in CreateWorkoutItemPickerView(viewModel: CreateWorkoutItemPickerViewModel(allValues: fakeValues, selectedIds: [1]), completed: { selectedIds in
}) })
} }
} }

View File

@@ -16,21 +16,21 @@ struct CreateWorkoutMainView: View {
viewModel.title.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty == false && viewModel.title.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty == false &&
viewModel.isUploading == false viewModel.isUploading == false
} }
var body: some View { var body: some View {
VStack { VStack(spacing: 0) {
VStack { VStack(spacing: WerkoutTheme.sm) {
TextField("Title", text: $viewModel.title) TextField("Title", text: $viewModel.title)
.padding(.horizontal) .werkoutTextField()
.textFieldStyle(.roundedBorder) .padding(.horizontal, WerkoutTheme.md)
TextField("Description", text: $viewModel.description) TextField("Description", text: $viewModel.description)
.padding(.horizontal) .werkoutTextField()
.textFieldStyle(.roundedBorder) .padding(.horizontal, WerkoutTheme.md)
} }
.padding(.bottom) .padding(.vertical, WerkoutTheme.md)
.background(Color(uiColor: .systemGray5)) .background(WerkoutTheme.surfaceCard)
ScrollViewReader { proxy in ScrollViewReader { proxy in
List() { List() {
ForEach(viewModel.superSets) { superset in ForEach(viewModel.superSets) { superset in
@@ -40,6 +40,7 @@ struct CreateWorkoutMainView: View {
superset: superset, superset: superset,
viewModel: viewModel) viewModel: viewModel)
} }
.listRowBackground(WerkoutTheme.surfaceCard)
// after adding new exercise we have to scroll to the bottom // after adding new exercise we have to scroll to the bottom
// where the new exercise is sooo keep this so we can scroll // where the new exercise is sooo keep this so we can scroll
// to id 999 // to id 999
@@ -48,91 +49,70 @@ struct CreateWorkoutMainView: View {
.accessibilityHidden(true) .accessibilityHidden(true)
.id(999) .id(999)
.listRowSeparator(.hidden) .listRowSeparator(.hidden)
.listRowBackground(Color.clear)
} }
.onChange(of: viewModel.randomValueForUpdatingValue, perform: { newValue in .scrollContentBackground(.hidden)
.background(WerkoutTheme.background)
.onChange(of: viewModel.randomValueForUpdatingValue) { _, _ in
withAnimation { withAnimation {
proxy.scrollTo(999, anchor: .bottom) proxy.scrollTo(999, anchor: .bottom)
} }
}) }
} }
.sheet(isPresented: $showAddExercise) { .sheet(isPresented: $showAddExercise) {
AddExerciseView(selectedExercise: { exercise in AddExerciseView(selectedExercise: { exercise in
let workoutExercise = CreateWorkoutExercise(exercise: exercise) if let superset = selectedCreateWorkoutSuperSet {
selectedCreateWorkoutSuperSet?.exercises.append(workoutExercise) viewModel.addExercise(exercise, to: superset)
// if left or right auto add the other side
// with a recover in between b/c its
// eaiser to delete a recover than add one
if exercise.side?.isEmpty == false {
let exercises = DataStore.shared.allExercise?.filter({
$0.name == exercise.name
})
let recover = DataStore.shared.allExercise?.first(where: {
$0.name.lowercased() == "recover"
})
if let exercises = exercises, let recover = recover {
if exercises.count == 2 {
let recoverWorkoutExercise = CreateWorkoutExercise(exercise: recover)
selectedCreateWorkoutSuperSet?.exercises.append(recoverWorkoutExercise)
for LRExercise in exercises {
if LRExercise.id != exercise.id {
let otherSideExercise = CreateWorkoutExercise(exercise: LRExercise)
selectedCreateWorkoutSuperSet?.exercises.append(otherSideExercise)
}
}
}
}
} }
viewModel.increaseRandomNumberForUpdating()
selectedCreateWorkoutSuperSet = nil selectedCreateWorkoutSuperSet = nil
}) })
} }
HStack {
Button("Add Superset", action: {
viewModel.addNewSuperset()
})
.frame(maxWidth: .infinity, alignment: .center)
.frame(height: 44)
.foregroundColor(.white)
.background(.blue)
.cornerRadius(Constants.buttonRadius)
.padding()
.frame(maxWidth: .infinity)
.accessibilityLabel("Add superset")
.accessibilityHint("Adds a new superset section to this workout")
Divider()
Button(action: {
viewModel.uploadWorkout()
}, label: {
if viewModel.isUploading {
ProgressView()
.progressViewStyle(.circular)
.tint(.white)
} else {
Text("Done")
}
})
.frame(maxWidth: .infinity, alignment: .center)
.frame(height: 44)
.foregroundColor(.white)
.background(.green)
.cornerRadius(Constants.buttonRadius)
.padding()
.frame(maxWidth: .infinity)
.disabled(canSubmit == false)
.accessibilityLabel("Upload workout")
.accessibilityHint("Uploads this workout to your account")
}
.frame(height: 44)
Divider() Divider()
.overlay(WerkoutTheme.divider)
GlassEffectContainer {
HStack(spacing: WerkoutTheme.md) {
Button(action: {
viewModel.addNewSuperset()
}) {
Label("Add Superset", systemImage: "plus.circle.fill")
.font(.system(size: 15, weight: .bold))
.foregroundStyle(WerkoutTheme.textPrimary)
.frame(maxWidth: .infinity)
.frame(height: 44)
}
.glassEffect(.regular.interactive())
.tint(WerkoutTheme.accent)
.accessibilityLabel("Add superset")
.accessibilityHint("Adds a new superset section to this workout")
Button(action: {
viewModel.uploadWorkout()
}, label: {
if viewModel.isUploading {
ProgressView()
.progressViewStyle(.circular)
.tint(WerkoutTheme.textPrimary)
} else {
Text("Done")
.font(.system(size: 15, weight: .bold))
.foregroundStyle(WerkoutTheme.textPrimary)
}
})
.frame(maxWidth: .infinity)
.frame(height: 44)
.glassEffect(.regular.interactive())
.tint(WerkoutTheme.success)
.disabled(canSubmit == false)
.accessibilityLabel("Upload workout")
.accessibilityHint("Uploads this workout to your account")
}
.padding(.horizontal, WerkoutTheme.md)
.padding(.vertical, WerkoutTheme.sm)
}
} }
.background(Color(uiColor: .systemGray5)) .background(WerkoutTheme.background)
.alert("Create Workout", isPresented: Binding<Bool>( .alert("Create Workout", isPresented: Binding<Bool>(
get: { viewModel.validationError != nil }, get: { viewModel.validationError != nil },
set: { _ in viewModel.validationError = nil } set: { _ in viewModel.validationError = nil }

View File

@@ -12,32 +12,38 @@ struct CreateWorkoutSupersetActionsView: View {
@Binding var showAddExercise: Bool @Binding var showAddExercise: Bool
var viewModel: WorkoutViewModel var viewModel: WorkoutViewModel
@Binding var selectedCreateWorkoutSuperSet: CreateWorkoutSuperSet? @Binding var selectedCreateWorkoutSuperSet: CreateWorkoutSuperSet?
var body: some View { var body: some View {
HStack { GlassEffectContainer {
Button(action: { HStack(spacing: WerkoutTheme.md) {
selectedCreateWorkoutSuperSet = workoutSuperSet Button(action: {
showAddExercise.toggle() selectedCreateWorkoutSuperSet = workoutSuperSet
}) { showAddExercise.toggle()
Text("Add exercise") }) {
.padding() Text("Add exercise")
} .font(.system(size: 15, weight: .bold))
.foregroundColor(.white) .foregroundStyle(WerkoutTheme.textPrimary)
.background(.green) .padding()
.frame(maxWidth: .infinity, alignment: .center) }
.glassEffect(.regular.interactive())
Button(action: { .tint(WerkoutTheme.success)
.frame(maxWidth: .infinity, alignment: .center)
Button(action: {
// viewModel.delete(superset: workoutSuperSet) // viewModel.delete(superset: workoutSuperSet)
// viewModel.increaseRandomNumberForUpdating() // viewModel.increaseRandomNumberForUpdating()
// viewModel.objectWillChange.send() // viewModel.objectWillChange.send()
}) { }) {
Text("Delete superset") Text("Delete superset")
.padding() .font(.system(size: 15, weight: .bold))
.foregroundStyle(WerkoutTheme.textPrimary)
.padding()
}
.glassEffect(.regular.interactive())
.tint(WerkoutTheme.danger)
.frame(maxWidth: .infinity, alignment: .center)
} }
.foregroundColor(.white)
.background(.red)
.frame(maxWidth: .infinity, alignment: .center)
} }
} }
} }

View File

@@ -9,9 +9,9 @@ import SwiftUI
import AVKit import AVKit
struct ExternalWorkoutDetailView: View { struct ExternalWorkoutDetailView: View {
@StateObject var bridgeModule = BridgeModule.shared @ObservedObject var bridgeModule = BridgeModule.shared
@State var avPlayer = AVPlayer(url: URL(string: "https://dev.werkout.fitness/media/exercise_videos/2_Dumbbell_Lateral_Lunges.mp4") ?? URL(fileURLWithPath: "/dev/null")) @State var avPlayer = AVPlayer(url: URL(string: BaseURLs.currentBaseURL + "/media/exercise_videos/2_Dumbbell_Lateral_Lunges.mp4") ?? URL(fileURLWithPath: "/dev/null"))
@State var smallAVPlayer = AVPlayer(url: URL(string: "https://dev.werkout.fitness/media/exercise_videos/2_Dumbbell_Lateral_Lunges.mp4") ?? URL(fileURLWithPath: "/dev/null")) @State var smallAVPlayer = AVPlayer(url: URL(string: BaseURLs.currentBaseURL + "/media/exercise_videos/2_Dumbbell_Lateral_Lunges.mp4") ?? URL(fileURLWithPath: "/dev/null"))
@State private var currentVideoURL: URL? @State private var currentVideoURL: URL?
@State private var currentSmallVideoURL: URL? @State private var currentSmallVideoURL: URL?
@AppStorage(Constants.extThotStyle) private var extThotStyle: ThotStyle = .never @AppStorage(Constants.extThotStyle) private var extThotStyle: ThotStyle = .never
@@ -32,23 +32,23 @@ struct ExternalWorkoutDetailView: View {
avPlayer.play() avPlayer.play()
} }
} }
VStack { VStack {
ExtExerciseList(workout: workout, ExtExerciseList(workout: workout,
allSupersetExecerciseIndex: bridgeModule.currentWorkoutInfo.allSupersetExecerciseIndex) allSupersetExecerciseIndex: bridgeModule.currentWorkoutInfo.allSupersetExecerciseIndex)
} }
.frame(width: metrics.size.width * 0.4, height: metrics.size.height * 0.8) .frame(width: metrics.size.width * 0.4, height: metrics.size.height * 0.8)
.padding([.top, .bottom], 20) .padding([.top, .bottom], WerkoutTheme.lg)
} }
HStack { HStack {
ExtCountdownView() ExtCountdownView()
.padding(.leading, 50) .padding(.leading, 50)
.padding(.bottom, 20) .padding(.bottom, WerkoutTheme.lg)
if extShowNextVideo && extThotStyle != .off { if extShowNextVideo && extThotStyle != .off {
PlayerView(player: $smallAVPlayer) PlayerView(player: $smallAVPlayer)
.frame(width: metrics.size.width * 0.2, .frame(width: metrics.size.width * 0.2,
height: metrics.size.height * 0.2) height: metrics.size.height * 0.2)
.onAppear{ .onAppear{
smallAVPlayer.isMuted = true smallAVPlayer.isMuted = true
@@ -56,7 +56,7 @@ struct ExternalWorkoutDetailView: View {
} }
} }
} }
.background(Color(uiColor: .tertiarySystemGroupedBackground)) .background(WerkoutTheme.surfaceCard)
} }
} }
} else { } else {
@@ -65,43 +65,34 @@ struct ExternalWorkoutDetailView: View {
.edgesIgnoringSafeArea(.all) .edgesIgnoringSafeArea(.all)
.scaledToFill() .scaledToFill()
} }
VStack { VStack {
HStack { HStack {
if bridgeModule.currentWorkoutRunTimeInSeconds > -1 { if bridgeModule.currentWorkoutRunTimeInSeconds > -1 {
Text(" \(Double(bridgeModule.currentWorkoutRunTimeInSeconds).asString(style: .positional)) ") Text(" \(Double(bridgeModule.currentWorkoutRunTimeInSeconds).asString(style: .positional)) ")
.font(Font.system(size: 120)) .font(WerkoutTheme.stat)
.minimumScaleFactor(0.01) .minimumScaleFactor(0.01)
.lineLimit(1) .lineLimit(1)
.padding() .padding()
.bold() .foregroundColor(WerkoutTheme.textPrimary)
.foregroundColor(.white) .glassEffect(.regular.interactive())
.background( .tint(WerkoutTheme.accent)
Capsule()
.strokeBorder(Color.black, lineWidth: 0.8)
.background(Color(uiColor: UIColor(red: 148/255,
green: 0,
blue: 211/255,
alpha: 0.5)))
.clipped()
)
.clipShape(Capsule())
} }
Spacer() Spacer()
} }
.padding(.leading, 50) .padding(.leading, 50)
Spacer() Spacer()
} }
} }
.onChange(of: bridgeModule.isInWorkout, perform: { _ in .onChange(of: bridgeModule.isInWorkout) {
playVideos() playVideos()
}) }
.onChange(of: bridgeModule.currentWorkoutInfo.allSupersetExecerciseIndex, perform: { _ in .onChange(of: bridgeModule.currentWorkoutInfo.allSupersetExecerciseIndex) {
playVideos() playVideos()
}) }
.frame(maxWidth: .infinity, maxHeight: .infinity) .frame(maxWidth: .infinity, maxHeight: .infinity)
.background(bridgeModule.currentWorkoutInfo.workout == nil ? Color(red: 157/255, green: 138/255, blue: 255/255) : Color(uiColor: .systemBackground)) .background(bridgeModule.currentWorkoutInfo.workout == nil ? WerkoutTheme.accent : WerkoutTheme.background)
.onReceive(NotificationCenter.default.publisher( .onReceive(NotificationCenter.default.publisher(
for: UIScene.willEnterForegroundNotification)) { _ in for: UIScene.willEnterForegroundNotification)) { _ in
avPlayer.play() avPlayer.play()
@@ -112,7 +103,7 @@ struct ExternalWorkoutDetailView: View {
smallAVPlayer.pause() smallAVPlayer.pause()
} }
} }
func playVideos() { func playVideos() {
if let currentExtercise = bridgeModule.currentWorkoutInfo.currentExercise { if let currentExtercise = bridgeModule.currentWorkoutInfo.currentExercise {
if let videoURL = VideoURLCreator.videoURL( if let videoURL = VideoURLCreator.videoURL(
@@ -123,7 +114,7 @@ struct ExternalWorkoutDetailView: View {
workout: bridgeModule.currentWorkoutInfo.workout) { workout: bridgeModule.currentWorkoutInfo.workout) {
updateMainPlayer(for: videoURL) updateMainPlayer(for: videoURL)
} }
if let smallVideoURL = VideoURLCreator.videoURL( if let smallVideoURL = VideoURLCreator.videoURL(
thotStyle: .never, thotStyle: .never,
gender: thotGenderOption, gender: thotGenderOption,
@@ -163,7 +154,7 @@ struct ExternalWorkoutDetailView: View {
//struct ExternalWorkoutDetailView_Previews: PreviewProvider { //struct ExternalWorkoutDetailView_Previews: PreviewProvider {
// static var bridge = BridgeModule.shared // static var bridge = BridgeModule.shared
// //
// static var previews: some View { // static var previews: some View {
// ExternalWorkoutDetailView().environmentObject({ () -> BridgeModule in // ExternalWorkoutDetailView().environmentObject({ () -> BridgeModule in
// let envObj = BridgeModule.shared // let envObj = BridgeModule.shared

View File

@@ -13,12 +13,12 @@ struct LoginView: View {
@Environment(\.dismiss) var dismiss @Environment(\.dismiss) var dismiss
let completion: (() -> Void) let completion: (() -> Void)
@State var isLoggingIn: Bool = false @State var isLoggingIn: Bool = false
@State var errorTitle = "" @State var errorTitle = ""
@State var errorMessage = "" @State var errorMessage = ""
@State var hasError: Bool = false @State var hasError: Bool = false
var body: some View { var body: some View {
VStack { VStack {
TextField("Email", text: $email) TextField("Email", text: $email)
@@ -27,65 +27,87 @@ struct LoginView: View {
.autocorrectionDisabled(true) .autocorrectionDisabled(true)
.keyboardType(.emailAddress) .keyboardType(.emailAddress)
.padding() .padding()
.background(Color.white) .background(WerkoutTheme.surfaceCard.opacity(0.8))
.cornerRadius(8) .clipShape(RoundedRectangle(cornerRadius: WerkoutTheme.buttonRadius, style: .continuous))
.overlay(
RoundedRectangle(cornerRadius: WerkoutTheme.buttonRadius, style: .continuous)
.strokeBorder(WerkoutTheme.textSecondary.opacity(0.4), lineWidth: 1)
)
.foregroundStyle(WerkoutTheme.textPrimary)
.padding(.horizontal) .padding(.horizontal)
.padding(.top, 25) .padding(.top, 25)
.foregroundStyle(.black)
.accessibilityLabel("Email") .accessibilityLabel("Email")
.submitLabel(.next) .submitLabel(.next)
SecureField("Password", text: $password) SecureField("Password", text: $password)
.textContentType(.password) .textContentType(.password)
.padding() .padding()
.background(Color.white) .background(WerkoutTheme.surfaceCard.opacity(0.8))
.cornerRadius(8) .clipShape(RoundedRectangle(cornerRadius: WerkoutTheme.buttonRadius, style: .continuous))
.overlay(
RoundedRectangle(cornerRadius: WerkoutTheme.buttonRadius, style: .continuous)
.strokeBorder(WerkoutTheme.textSecondary.opacity(0.4), lineWidth: 1)
)
.foregroundStyle(WerkoutTheme.textPrimary)
.padding(.horizontal) .padding(.horizontal)
.textInputAutocapitalization(.never) .textInputAutocapitalization(.never)
.autocorrectionDisabled(true) .autocorrectionDisabled(true)
.foregroundStyle(.black)
.accessibilityLabel("Password") .accessibilityLabel("Password")
.submitLabel(.go) .submitLabel(.go)
if isLoggingIn { if isLoggingIn {
ProgressView("Logging In") ProgressView("Logging In")
.padding() .padding()
.foregroundColor(.white) .foregroundStyle(WerkoutTheme.textPrimary)
.progressViewStyle(CircularProgressViewStyle(tint: .white)) .progressViewStyle(CircularProgressViewStyle(tint: WerkoutTheme.accent))
.scaleEffect(1.5, anchor: .center) .scaleEffect(1.5, anchor: .center)
} else { } else {
Button("Login", action: { Button("Login", action: {
login() login()
}) })
.font(.system(size: 16, weight: .bold))
.foregroundStyle(WerkoutTheme.textPrimary)
.frame(maxWidth: .infinity, alignment: .center) .frame(maxWidth: .infinity, alignment: .center)
.frame(height: 44) .frame(height: 44)
.foregroundColor(.blue) .glassEffect(.regular.interactive())
.background(.yellow) .tint(WerkoutTheme.accent)
.cornerRadius(16) .clipShape(RoundedRectangle(cornerRadius: WerkoutTheme.buttonRadius, style: .continuous))
.padding() .padding()
.frame(maxWidth: .infinity) .frame(maxWidth: .infinity)
.disabled(password.isEmpty || email.isEmpty) .disabled(password.isEmpty || email.isEmpty)
.accessibilityLabel("Log in") .accessibilityLabel("Log in")
.accessibilityHint("Logs in using the entered email and password") .accessibilityHint("Logs in using the entered email and password")
} }
Spacer() Spacer()
} }
.padding() .padding()
.background( .background(
Image("icon") ZStack {
.resizable() Image("icon")
.resizable()
.edgesIgnoringSafeArea(.all)
.scaledToFill()
.accessibilityHidden(true)
LinearGradient(
colors: [
Color.black.opacity(0.0),
Color.black.opacity(0.6)
],
startPoint: .top,
endPoint: .bottom
)
.edgesIgnoringSafeArea(.all) .edgesIgnoringSafeArea(.all)
.scaledToFill() }
.accessibilityHidden(true)
) )
.alert(errorTitle, isPresented: $hasError, actions: { .alert(errorTitle, isPresented: $hasError, actions: {
}, message: { }, message: {
Text(errorMessage) Text(errorMessage)
}) })
} }
func login() { func login() {
let postData = [ let postData = [
"email": email, "email": email,
@@ -109,7 +131,7 @@ struct LoginView: View {
struct LoginView_Previews: PreviewProvider { struct LoginView_Previews: PreviewProvider {
static var previews: some View { static var previews: some View {
LoginView(completion: { LoginView(completion: {
}) })
} }
} }

View File

@@ -10,7 +10,7 @@ import CoreData
struct MainView: View { struct MainView: View {
@State var workout: Workout? @State var workout: Workout?
@StateObject var bridgeModule = BridgeModule.shared @ObservedObject var bridgeModule = BridgeModule.shared
var body: some View { var body: some View {
ZStack { ZStack {

View File

@@ -14,78 +14,89 @@ struct PlanWorkoutView: View {
let workout: Workout let workout: Workout
@Environment(\.dismiss) var dismiss @Environment(\.dismiss) var dismiss
var addedPlannedWorkout: (() -> Void)? var addedPlannedWorkout: (() -> Void)?
var body: some View { var body: some View {
VStack() { VStack() {
Text(workout.name) Text(workout.name)
.font(.title) .font(WerkoutTheme.heroTitle)
.foregroundStyle(WerkoutTheme.textPrimary)
.frame(maxWidth: .infinity, alignment: .leading) .frame(maxWidth: .infinity, alignment: .leading)
Text(selectedDate.formatted(date: .abbreviated, time: .omitted)) Text(selectedDate.formatted(date: .abbreviated, time: .omitted))
.font(.system(size: 28)) .font(.system(size: 28))
.bold() .bold()
.foregroundColor(Color.accentColor) .foregroundStyle(WerkoutTheme.accent)
.padding() .padding()
.animation(.spring(), value: selectedDate) .animation(.spring(), value: selectedDate)
Divider().frame(height: 1) Divider()
.overlay(WerkoutTheme.divider)
.frame(height: 1)
DatePicker("Select Date", selection: $selectedDate, displayedComponents: [.date]) DatePicker("Select Date", selection: $selectedDate, displayedComponents: [.date])
.padding(.horizontal) .padding(.horizontal)
.datePickerStyle(.graphical) .datePickerStyle(.graphical)
.tint(WerkoutTheme.accent)
.foregroundStyle(WerkoutTheme.textPrimary)
Divider() Divider()
.overlay(WerkoutTheme.divider)
HStack {
Button(action: { GlassEffectContainer {
dismiss() HStack {
}, label: { Button(action: {
Image(systemName: "xmark.octagon.fill") dismiss()
.font(.title) }, label: {
.frame(maxWidth: .infinity, maxHeight: .infinity) Image(systemName: "xmark.octagon.fill")
}) .font(.title)
.frame(maxWidth: .infinity, alignment: .center) .frame(maxWidth: .infinity, maxHeight: .infinity)
.frame(height: 44) })
.foregroundColor(.white) .foregroundStyle(WerkoutTheme.textPrimary)
.background(.red) .frame(maxWidth: .infinity, alignment: .center)
.cornerRadius(Constants.buttonRadius) .frame(height: 44)
.padding() .glassEffect(.regular.interactive())
.accessibilityLabel("Cancel planning") .tint(WerkoutTheme.danger)
.accessibilityHint("Closes this screen without planning a workout") .clipShape(RoundedRectangle(cornerRadius: WerkoutTheme.buttonRadius, style: .continuous))
.padding()
Button(action: { .accessibilityLabel("Cancel planning")
planWorkout() .accessibilityHint("Closes this screen without planning a workout")
}, label: {
Image(systemName: "plus.app") Button(action: {
.font(.title) planWorkout()
.frame(maxWidth: .infinity, maxHeight: .infinity) }, label: {
}) Image(systemName: "plus.app")
.frame(maxWidth: .infinity, alignment: .center) .font(.title)
.frame(height: 44) .frame(maxWidth: .infinity, maxHeight: .infinity)
.foregroundColor(.blue) })
.background(.yellow) .foregroundStyle(WerkoutTheme.textPrimary)
.cornerRadius(Constants.buttonRadius) .frame(maxWidth: .infinity, alignment: .center)
.padding() .frame(height: 44)
.accessibilityLabel("Plan workout") .glassEffect(.regular.interactive())
.accessibilityHint("Adds this workout to your selected date") .tint(WerkoutTheme.accent)
.clipShape(RoundedRectangle(cornerRadius: WerkoutTheme.buttonRadius, style: .continuous))
.padding()
.accessibilityLabel("Plan workout")
.accessibilityHint("Adds this workout to your selected date")
}
} }
Spacer() Spacer()
} }
.padding() .padding()
.background(WerkoutTheme.background)
.alert("Unable to Plan Workout", isPresented: $hasError) { .alert("Unable to Plan Workout", isPresented: $hasError) {
Button("OK", role: .cancel) {} Button("OK", role: .cancel) {}
} message: { } message: {
Text(errorMessage) Text(errorMessage)
} }
} }
func planWorkout() { func planWorkout() {
let postData = [ let postData = [
"on_date": selectedDate.formatForPlannedWorkout, "on_date": selectedDate.formatForPlannedWorkout,
"workout": workout.id "workout": workout.id
] as [String : Any] ] as [String : Any]
PlanWorkoutFetchable(postData: postData).fetch(completion: { result in PlanWorkoutFetchable(postData: postData).fetch(completion: { result in
switch result { switch result {
case .success(_): case .success(_):

View File

@@ -8,13 +8,14 @@
import SwiftUI import SwiftUI
struct CurrentWorkoutElapsedTimeView: View { struct CurrentWorkoutElapsedTimeView: View {
@ObservedObject var bridgeModule = BridgeModule.shared let currentWorkoutRunTimeInSeconds: Int
var body: some View { var body: some View {
if bridgeModule.currentWorkoutRunTimeInSeconds > -1 { if currentWorkoutRunTimeInSeconds > -1 {
VStack { VStack {
Text("\(Double(bridgeModule.currentWorkoutRunTimeInSeconds).asString(style: .positional))") Text("\(Double(currentWorkoutRunTimeInSeconds).asString(style: .positional))")
.font(.title2) .font(.system(size: 20, weight: .black, design: .monospaced))
.foregroundStyle(WerkoutTheme.accent)
} }
} }
} }

View File

@@ -10,138 +10,138 @@ import AVKit
struct ExerciseListView: View { struct ExerciseListView: View {
@AppStorage(Constants.phoneThotStyle) private var phoneThotStyle: ThotStyle = .never @AppStorage(Constants.phoneThotStyle) private var phoneThotStyle: ThotStyle = .never
@ObservedObject var bridgeModule = BridgeModule.shared @State private var avPlayer = AVPlayer(url: URL(string: BaseURLs.currentBaseURL + "/media/exercise_videos/2_Dumbbell_Lateral_Lunges.mp4") ?? URL(fileURLWithPath: "/dev/null"))
@State var avPlayer = AVPlayer(url: URL(string: "https://dev.werkout.fitness/media/exercise_videos/2_Dumbbell_Lateral_Lunges.mp4") ?? URL(fileURLWithPath: "/dev/null"))
@State private var previewVideoURL: URL? @State private var previewVideoURL: URL?
var workout: Workout var workout: Workout
@Binding var showExecersizeInfo: Bool @Binding var showExecersizeInfo: Bool
@AppStorage(Constants.thotGenderOption) private var thotGenderOption: String = "female" @AppStorage(Constants.thotGenderOption) private var thotGenderOption: String = "female"
@State var videoExercise: Exercise? { let isInWorkout: Bool
let currentSupersetIndex: Int
let currentExerciseIndex: Int
let allSupersetExecerciseIndex: Int
let currentExercise: SupersetExercise?
let currentWorkout: Workout?
let goToExerciseAt: (Int, Int) -> Void
@State private var videoExercise: Exercise? {
didSet { didSet {
if let videoURL = VideoURLCreator.videoURL( if let videoURL = VideoURLCreator.videoURL(
thotStyle: phoneThotStyle, thotStyle: phoneThotStyle,
gender: thotGenderOption, gender: thotGenderOption,
defaultVideoURLStr: self.videoExercise?.videoURL, defaultVideoURLStr: self.videoExercise?.videoURL,
exerciseName: self.videoExercise?.name, exerciseName: self.videoExercise?.name,
workout: bridgeModule.currentWorkoutInfo.workout) { workout: currentWorkout) {
updatePreviewPlayer(for: videoURL) updatePreviewPlayer(for: videoURL)
} }
} }
} }
var body: some View { var body: some View {
let supersets = workout.supersets?.sorted(by: { $0.order < $1.order }) ?? [] let supersets = workout.supersets?.sorted(by: { $0.order < $1.order }) ?? []
if supersets.isEmpty == false { if supersets.isEmpty == false {
ScrollViewReader { proxy in ScrollViewReader { proxy in
List() { List() {
ForEach(supersets.indices, id: \.self) { supersetIndex in ForEach(Array(supersets.enumerated()), id: \.offset) { supersetIndex, superset in
let superset = supersets[supersetIndex]
Section(content: { Section(content: {
ForEach(superset.exercises.indices, id: \.self) { exerciseIndex in ForEach(Array(superset.exercises.enumerated()), id: \.offset) { exerciseIndex, supersetExecercise in
let supersetExecercise = superset.exercises[exerciseIndex]
let rowID = rowIdentifier( let rowID = rowIdentifier(
supersetIndex: supersetIndex, supersetIndex: supersetIndex,
exerciseIndex: exerciseIndex, exerciseIndex: exerciseIndex,
exercise: supersetExecercise exercise: supersetExecercise
) )
let isCurrentExercise = isInWorkout &&
supersetIndex == currentSupersetIndex &&
exerciseIndex == currentExerciseIndex
VStack { VStack {
Button(action: { Button(action: {
if bridgeModule.isInWorkout { if isInWorkout {
bridgeModule.currentWorkoutInfo.goToExerciseAt( goToExerciseAt(supersetIndex, exerciseIndex)
supersetIndex: supersetIndex,
exerciseIndex: exerciseIndex)
} else { } else {
videoExercise = supersetExecercise.exercise videoExercise = supersetExecercise.exercise
} }
}, label: { }, label: {
HStack { HStack {
if bridgeModule.isInWorkout && if isCurrentExercise {
supersetIndex == bridgeModule.currentWorkoutInfo.supersetIndex &&
exerciseIndex == bridgeModule.currentWorkoutInfo.exerciseIndex {
Image(systemName: "figure.run") Image(systemName: "figure.run")
.foregroundColor(Color("appColor")) .foregroundStyle(WerkoutTheme.accent)
} }
Text(supersetExecercise.exercise.extName) Text(supersetExecercise.exercise.extName)
.foregroundStyle(WerkoutTheme.textPrimary)
Spacer() Spacer()
if let reps = supersetExecercise.reps, if let reps = supersetExecercise.reps,
reps > 0 { reps > 0 {
HStack { HStack(spacing: 4) {
Image(systemName: "number") Image(systemName: "number")
.foregroundColor(.white)
.frame(width: 20, alignment: .leading)
Text("\(reps)") Text("\(reps)")
.foregroundColor(.white)
.frame(width: 30, alignment: .trailing)
} }
.padding([.top, .bottom], 5) .font(WerkoutTheme.caption)
.padding([.leading], 10) .foregroundStyle(.white)
.padding([.trailing], 15) .padding(.horizontal, WerkoutTheme.sm)
.background(.blue) .padding(.vertical, WerkoutTheme.xs)
.cornerRadius(5, corners: [.topLeft, .bottomLeft]) .background(WerkoutTheme.accent)
.frame(alignment: .trailing) .clipShape(Capsule())
} }
if let duration = supersetExecercise.duration, if let duration = supersetExecercise.duration,
duration > 0 { duration > 0 {
HStack { HStack(spacing: 4) {
Image(systemName: "stopwatch") Image(systemName: "stopwatch")
.foregroundColor(.white)
.frame(width: 20, alignment: .leading)
Text("\(duration)") Text("\(duration)")
.foregroundColor(.white)
.frame(width: 30, alignment: .trailing)
} }
.padding([.top, .bottom], 5) .font(WerkoutTheme.caption)
.padding([.leading], 10) .foregroundStyle(.white)
.padding([.trailing], 15) .padding(.horizontal, WerkoutTheme.sm)
.background(.green) .padding(.vertical, WerkoutTheme.xs)
.cornerRadius(5, corners: [.topLeft, .bottomLeft]) .background(WerkoutTheme.success)
.clipShape(Capsule())
} }
} }
.padding(.trailing, -20)
.contentShape(Rectangle()) .contentShape(Rectangle())
}) })
.buttonStyle(.plain) .buttonStyle(.plain)
.accessibilityLabel("Exercise \(supersetExecercise.exercise.extName)") .accessibilityLabel("Exercise \(supersetExecercise.exercise.extName)")
.accessibilityHint(bridgeModule.isInWorkout ? "Jump to this exercise in the workout" : "Preview exercise video") .accessibilityHint(isInWorkout ? "Jump to this exercise in the workout" : "Preview exercise video")
if bridgeModule.isInWorkout && if isCurrentExercise && showExecersizeInfo {
supersetIndex == bridgeModule.currentWorkoutInfo.supersetIndex &&
exerciseIndex == bridgeModule.currentWorkoutInfo.exerciseIndex &&
showExecersizeInfo {
detailView(forExercise: supersetExecercise) detailView(forExercise: supersetExecercise)
} }
}.id(rowID) }
.listRowBackground(
isCurrentExercise
? WerkoutTheme.accent.opacity(0.1)
: WerkoutTheme.surfaceCard
)
.id(rowID)
} }
}, header: { }, header: {
HStack { HStack {
Text(superset.name ?? "--") Text(superset.name ?? "--")
.foregroundColor(Color("appColor")) .font(WerkoutTheme.sectionTitle)
.bold() .foregroundStyle(WerkoutTheme.accent)
Spacer() Spacer()
Text("\(superset.rounds) rounds") Text("\(superset.rounds) rounds")
.foregroundColor(Color("appColor")) .font(WerkoutTheme.caption)
.bold() .foregroundStyle(WerkoutTheme.accent)
if let estimatedTime = superset.estimatedTime { if let estimatedTime = superset.estimatedTime {
Text("@ " + estimatedTime.asString(style: .abbreviated)) Text("@ " + estimatedTime.asString(style: .abbreviated))
.foregroundColor(Color("appColor")) .font(WerkoutTheme.caption)
.bold() .foregroundStyle(WerkoutTheme.accent)
} }
} }
}) })
} }
} }
.onChange(of: bridgeModule.currentWorkoutInfo.allSupersetExecerciseIndex, perform: { newValue in .scrollContentBackground(.hidden)
if let newCurrentExercise = bridgeModule.currentWorkoutInfo.currentExercise { .background(WerkoutTheme.background)
.onChange(of: allSupersetExecerciseIndex) { _, _ in
if let newCurrentExercise = currentExercise {
withAnimation { withAnimation {
let currentSupersetIndex = bridgeModule.currentWorkoutInfo.supersetIndex
let currentExerciseIndex = bridgeModule.currentWorkoutInfo.exerciseIndex
proxy.scrollTo( proxy.scrollTo(
rowIdentifier( rowIdentifier(
supersetIndex: currentSupersetIndex, supersetIndex: currentSupersetIndex,
@@ -152,7 +152,7 @@ struct ExerciseListView: View {
) )
} }
} }
}) }
.sheet(item: $videoExercise) { exercise in .sheet(item: $videoExercise) { exercise in
PlayerView(player: $avPlayer) PlayerView(player: $avPlayer)
.onAppear{ .onAppear{
@@ -190,20 +190,34 @@ struct ExerciseListView: View {
avPlayer.isMuted = true avPlayer.isMuted = true
avPlayer.play() avPlayer.play()
} }
func detailView(forExercise supersetExecercise: SupersetExercise) -> some View { func detailView(forExercise supersetExecercise: SupersetExercise) -> some View {
VStack { VStack(spacing: WerkoutTheme.sm) {
Text(supersetExecercise.exercise.description) Text(supersetExecercise.exercise.description)
.frame(alignment: .leading) .font(WerkoutTheme.bodyText)
Divider() .foregroundStyle(WerkoutTheme.textSecondary)
.frame(maxWidth: .infinity, alignment: .leading)
WerkoutTheme.divider.frame(height: 0.5)
Text(supersetExecercise.exercise.muscles.map({ $0.name }).joined(separator: ", ")) Text(supersetExecercise.exercise.muscles.map({ $0.name }).joined(separator: ", "))
.frame(alignment: .leading) .font(WerkoutTheme.caption)
.foregroundStyle(WerkoutTheme.accent)
.frame(maxWidth: .infinity, alignment: .leading)
} }
} }
} }
struct ExerciseListView_Previews: PreviewProvider { struct ExerciseListView_Previews: PreviewProvider {
static var previews: some View { static var previews: some View {
ExerciseListView(workout: PreviewData.workout(), showExecersizeInfo: .constant(true)) ExerciseListView(
workout: PreviewData.workout(),
showExecersizeInfo: .constant(true),
isInWorkout: false,
currentSupersetIndex: 0,
currentExerciseIndex: 0,
allSupersetExecerciseIndex: 0,
currentExercise: nil,
currentWorkout: nil,
goToExerciseAt: { _, _ in }
)
} }
} }

View File

@@ -9,11 +9,11 @@ import SwiftUI
import AVKit import AVKit
struct WorkoutDetailView: View { struct WorkoutDetailView: View {
@StateObject var viewModel: WorkoutDetailViewModel @ObservedObject var viewModel: WorkoutDetailViewModel
@State var avPlayer = AVPlayer(url: URL(string: "https://dev.werkout.fitness/media/exercise_videos/2_Dumbbell_Lateral_Lunges.mp4") ?? URL(fileURLWithPath: "/dev/null")) @State private var avPlayer = AVPlayer(url: URL(string: BaseURLs.currentBaseURL + "/media/exercise_videos/2_Dumbbell_Lateral_Lunges.mp4") ?? URL(fileURLWithPath: "/dev/null"))
@State private var currentVideoURL: URL? @State private var currentVideoURL: URL?
@StateObject var bridgeModule = BridgeModule.shared @ObservedObject var bridgeModule = BridgeModule.shared
@Environment(\.dismiss) var dismiss @Environment(\.dismiss) var dismiss
@AppStorage(Constants.phoneThotStyle) private var phoneThotStyle: ThotStyle = .never @AppStorage(Constants.phoneThotStyle) private var phoneThotStyle: ThotStyle = .never
@AppStorage(Constants.thotGenderOption) private var thotGenderOption: String = "female" @AppStorage(Constants.thotGenderOption) private var thotGenderOption: String = "female"
@@ -22,45 +22,50 @@ struct WorkoutDetailView: View {
case completedWorkout([String: Any]) case completedWorkout([String: Any])
var id: String { return "completedWorkoutSheet" } var id: String { return "completedWorkoutSheet" }
} }
@State var workoutComplete: Sheet? @State private var workoutComplete: Sheet?
@State var workoutToPlan: Workout? @State private var workoutToPlan: Workout?
@State var showExecersizeInfo: Bool = false @State private var showExecersizeInfo: Bool = false
var body: some View { var body: some View {
ZStack { ZStack {
WerkoutTheme.background.ignoresSafeArea()
switch viewModel.status { switch viewModel.status {
case .loading: case .loading:
Text("Loading") ProgressView()
.tint(WerkoutTheme.accent)
case .failed(let errorMessage): case .failed(let errorMessage):
VStack(spacing: 16) { VStack(spacing: WerkoutTheme.md) {
Text("Unable to load workout") Text("Unable to load workout")
.font(.headline) .font(WerkoutTheme.sectionTitle)
.foregroundStyle(WerkoutTheme.textPrimary)
Text(errorMessage) Text(errorMessage)
.font(.footnote) .font(WerkoutTheme.bodyText)
.multilineTextAlignment(.center) .multilineTextAlignment(.center)
.foregroundStyle(.secondary) .foregroundStyle(WerkoutTheme.textSecondary)
} }
.padding() .padding()
case .showWorkout(let workout): case .showWorkout(let workout):
VStack(spacing: 0) { VStack(spacing: 0) {
if bridgeModule.isInWorkout { if bridgeModule.isInWorkout {
HStack { HStack {
CountdownView() CountdownView(
currentExerciseDuration: bridgeModule.currentWorkoutInfo.currentExercise?.duration,
currentExerciseTimeLeft: bridgeModule.currentExerciseTimeLeft
)
} }
.padding() .padding()
.frame(maxWidth: .infinity) .frame(maxWidth: .infinity)
if phoneThotStyle != .off { if phoneThotStyle != .off {
GeometryReader { metrics in PlayerView(player: $avPlayer)
ZStack { .frame(height: 220)
PlayerView(player: $avPlayer) .onAppear{
.frame(width: metrics.size.width * 1, height: metrics.size.height * 1) avPlayer.isMuted = true
.onAppear{ avPlayer.play()
avPlayer.isMuted = true }
avPlayer.play() .overlay(alignment: .bottomTrailing) {
}
Button(action: { Button(action: {
if let assetURL = ((avPlayer.currentItem?.asset) as? AVURLAsset)?.url, if let assetURL = ((avPlayer.currentItem?.asset) as? AVURLAsset)?.url,
let currentExtercise = bridgeModule.currentWorkoutInfo.currentExercise, let currentExtercise = bridgeModule.currentWorkoutInfo.currentExercise,
@@ -72,73 +77,86 @@ struct WorkoutDetailView: View {
workout: bridgeModule.currentWorkoutInfo.workout) { workout: bridgeModule.currentWorkoutInfo.workout) {
updatePlayer(for: otherVideoURL) updatePlayer(for: otherVideoURL)
} }
}, label: { }) {
Image(systemName: "arrow.triangle.2.circlepath.camera.fill") Image(systemName: "arrow.triangle.2.circlepath.camera.fill")
.frame(width: 44, height: 44) .font(.title2)
.foregroundColor(Color("appColor")) .padding(WerkoutTheme.sm)
}) }
.foregroundColor(.blue) .glassEffect(.regular.interactive())
.cornerRadius(Constants.buttonRadius) .tint(WerkoutTheme.accent)
.frame(width: 160, height: 120) .padding(WerkoutTheme.sm)
.position(x: metrics.size.width - 22, y: metrics.size.height - 30)
.accessibilityLabel("Switch video style") .accessibilityLabel("Switch video style")
.accessibilityHint("Toggles between alternate and default exercise videos") .accessibilityHint("Toggles between alternate and default exercise videos")
}
.overlay(alignment: .bottomLeading) {
Button(action: { Button(action: {
showExecersizeInfo.toggle() showExecersizeInfo.toggle()
}, label: { }) {
Image(systemName: "info.circle.fill") Image(systemName: "info.circle.fill")
.frame(width: 44, height: 44) .font(.title2)
.foregroundColor(Color("appColor")) .padding(WerkoutTheme.sm)
}) }
.foregroundColor(.blue) .glassEffect(.regular.interactive())
.cornerRadius(Constants.buttonRadius) .tint(WerkoutTheme.accent)
.frame(width: 120, height: 120) .padding(WerkoutTheme.sm)
.position(x: 22, y: metrics.size.height - 30)
.accessibilityLabel(showExecersizeInfo ? "Hide exercise info" : "Show exercise info") .accessibilityLabel(showExecersizeInfo ? "Hide exercise info" : "Show exercise info")
.accessibilityHint("Shows exercise description and target muscles") .accessibilityHint("Shows exercise description and target muscles")
} }
} .padding([.top, .bottom])
.padding([.top, .bottom]) .background(WerkoutTheme.background)
.background(Color(uiColor: .tertiarySystemBackground))
} }
} }
if !bridgeModule.isInWorkout { if !bridgeModule.isInWorkout {
InfoView(workout: workout) InfoView(workout: workout)
.padding(.bottom) .padding(.bottom)
} }
if bridgeModule.isInWorkout { if bridgeModule.isInWorkout {
Divider() WerkoutTheme.divider.frame(height: 0.5)
.background(Color(uiColor: .secondaryLabel))
HStack { HStack {
Text("\(bridgeModule.currentWorkoutInfo.currentRound) of \(bridgeModule.currentWorkoutInfo.numberOfRoundsInCurrentSuperSet)") Text("\(bridgeModule.currentWorkoutInfo.currentRound) of \(bridgeModule.currentWorkoutInfo.numberOfRoundsInCurrentSuperSet)")
.font(.title3) .font(.system(size: 17, weight: .bold, design: .monospaced))
.bold() .foregroundStyle(WerkoutTheme.accent)
.frame(maxWidth: .infinity, alignment: .leading) .frame(maxWidth: .infinity, alignment: .leading)
.padding(.leading, 10) .padding(.leading, 10)
CurrentWorkoutElapsedTimeView() CurrentWorkoutElapsedTimeView(
currentWorkoutRunTimeInSeconds: bridgeModule.currentWorkoutRunTimeInSeconds
)
.frame(maxWidth: .infinity, alignment: .center) .frame(maxWidth: .infinity, alignment: .center)
Text(progressText) Text(progressText)
.font(.title3) .font(.system(size: 17, weight: .bold, design: .monospaced))
.bold() .foregroundStyle(WerkoutTheme.textPrimary)
.frame(maxWidth: .infinity, alignment: .trailing) .frame(maxWidth: .infinity, alignment: .trailing)
.padding(.trailing, 10) .padding(.trailing, 10)
} }
.padding([.top, .bottom]) .padding([.top, .bottom])
.background(Color(uiColor: .tertiarySystemBackground)) .background(WerkoutTheme.surfaceCard)
} }
Divider() WerkoutTheme.divider.frame(height: 0.5)
.background(Color(uiColor: .secondaryLabel))
ExerciseListView(
ExerciseListView(workout: workout, showExecersizeInfo: $showExecersizeInfo) workout: workout,
showExecersizeInfo: $showExecersizeInfo,
isInWorkout: bridgeModule.isInWorkout,
currentSupersetIndex: bridgeModule.currentWorkoutInfo.supersetIndex,
currentExerciseIndex: bridgeModule.currentWorkoutInfo.exerciseIndex,
allSupersetExecerciseIndex: bridgeModule.currentWorkoutInfo.allSupersetExecerciseIndex,
currentExercise: bridgeModule.currentWorkoutInfo.currentExercise,
currentWorkout: bridgeModule.currentWorkoutInfo.workout,
goToExerciseAt: { supersetIndex, exerciseIndex in
bridgeModule.currentWorkoutInfo.goToExerciseAt(
supersetIndex: supersetIndex,
exerciseIndex: exerciseIndex
)
}
)
.padding([.top, .bottom], 10) .padding([.top, .bottom], 10)
.background(Color(uiColor: .systemGroupedBackground)) .background(WerkoutTheme.background)
ActionsView(completedWorkout: { ActionsView(completedWorkout: {
bridgeModule.completeWorkout() bridgeModule.completeWorkout()
}, planWorkout: { workout in }, planWorkout: { workout in
@@ -146,8 +164,8 @@ struct WorkoutDetailView: View {
}, workout: workout, showAddToCalendar: viewModel.isPreview, startWorkoutAction: { }, workout: workout, showAddToCalendar: viewModel.isPreview, startWorkoutAction: {
startWorkout(workout: workout) startWorkout(workout: workout)
}) })
.frame(height: 44) .frame(height: 56)
} }
.sheet(item: $workoutComplete) { item in .sheet(item: $workoutComplete) { item in
switch item { switch item {
@@ -169,15 +187,16 @@ struct WorkoutDetailView: View {
} }
} }
} }
.onChange(of: bridgeModule.currentWorkoutInfo.allSupersetExecerciseIndex, perform: { _ in .onChange(of: bridgeModule.currentWorkoutInfo.allSupersetExecerciseIndex) { _, _ in
playVideos() playVideos()
}) }
.onChange(of: bridgeModule.isInWorkout, perform: { _ in .onChange(of: bridgeModule.isInWorkout) { _, _ in
playVideos() playVideos()
}) }
.onAppear{ .onAppear{
viewModel.load()
playVideos() playVideos()
bridgeModule.completedWorkout = { bridgeModule.completedWorkout = {
if let workoutData = createWorkoutData() { if let workoutData = createWorkoutData() {
workoutComplete = .completedWorkout(workoutData) workoutComplete = .completedWorkout(workoutData)
@@ -194,7 +213,7 @@ struct WorkoutDetailView: View {
bridgeModule.completedWorkout = nil bridgeModule.completedWorkout = nil
} }
} }
func playVideos() { func playVideos() {
if let currentExtercise = bridgeModule.currentWorkoutInfo.currentExercise { if let currentExtercise = bridgeModule.currentWorkoutInfo.currentExercise {
if let videoURL = VideoURLCreator.videoURL( if let videoURL = VideoURLCreator.videoURL(
@@ -221,7 +240,7 @@ struct WorkoutDetailView: View {
avPlayer.isMuted = true avPlayer.isMuted = true
avPlayer.play() avPlayer.play()
} }
func startWorkout(workout: Workout) { func startWorkout(workout: Workout) {
bridgeModule.start(workout: workout) bridgeModule.start(workout: workout)
} }
@@ -235,7 +254,7 @@ struct WorkoutDetailView: View {
let current = min(totalExercises, max(1, bridgeModule.currentWorkoutInfo.allSupersetExecerciseIndex + 1)) let current = min(totalExercises, max(1, bridgeModule.currentWorkoutInfo.allSupersetExecerciseIndex + 1))
return "\(current)/\(totalExercises)" return "\(current)/\(totalExercises)"
} }
func createWorkoutData() -> [String:Any]? { func createWorkoutData() -> [String:Any]? {
guard let workoutid = bridgeModule.currentWorkoutInfo.workout?.id, guard let workoutid = bridgeModule.currentWorkoutInfo.workout?.id,
let startTime = bridgeModule.workoutStartDate?.timeFormatForUpload, let startTime = bridgeModule.workoutStartDate?.timeFormatForUpload,
@@ -249,7 +268,7 @@ struct WorkoutDetailView: View {
"workout": workoutid, "workout": workoutid,
"total_time": bridgeModule.currentWorkoutRunTimeInSeconds "total_time": bridgeModule.currentWorkoutRunTimeInSeconds
] as [String : Any] ] as [String : Any]
return postBody return postBody
} }
} }

View File

@@ -17,26 +17,32 @@ class WorkoutDetailViewModel: ObservableObject {
@Published var status: WorkoutDetailViewModelStatus @Published var status: WorkoutDetailViewModelStatus
let isPreview: Bool let isPreview: Bool
let workout: Workout
init(workout: Workout, status: WorkoutDetailViewModelStatus? = nil, isPreview: Bool) { init(workout: Workout, status: WorkoutDetailViewModelStatus? = nil, isPreview: Bool) {
self.status = .loading self.workout = workout
self.isPreview = isPreview self.isPreview = isPreview
if let passedStatus = status { if let passedStatus = status {
self.status = passedStatus self.status = passedStatus
} else { } else {
WorkoutDetailFetchable(workoutID: workout.id).fetch(completion: { result in self.status = .loading
switch result {
case .success(let model):
DispatchQueue.main.async {
self.status = .showWorkout(model)
}
case .failure(let failure):
DispatchQueue.main.async {
self.status = .failed("Failed to load workout details: \(failure.localizedDescription)")
}
}
})
} }
} }
func load() {
guard case .loading = status else { return }
WorkoutDetailFetchable(workoutID: workout.id).fetch(completion: { result in
switch result {
case .success(let model):
DispatchQueue.main.async {
self.status = .showWorkout(model)
}
case .failure(let failure):
DispatchQueue.main.async {
self.status = .failed("Failed to load workout details: \(failure.localizedDescription)")
}
}
})
}
} }

View File

@@ -14,10 +14,10 @@ struct WorkoutHistoryView: View {
case average case average
case hard case hard
case death case death
var stringValue: String { var stringValue: String {
switch self { switch self {
case .easy: case .easy:
return "Easy" return "Easy"
case .moderate: case .moderate:
@@ -30,43 +30,81 @@ struct WorkoutHistoryView: View {
return "Death" return "Death"
} }
} }
var color: Color {
switch self {
case .easy:
return WerkoutTheme.success
case .moderate:
return Color(red: 0.4, green: 0.8, blue: 0.2)
case .average:
return WerkoutTheme.warning
case .hard:
return Color(red: 1.0, green: 0.5, blue: 0.2)
case .death:
return WerkoutTheme.danger
}
}
} }
let completedWorkouts: [CompletedWorkout] let completedWorkouts: [CompletedWorkout]
@State private var selectedPlannedWorkout: Workout? @State private var selectedPlannedWorkout: Workout?
private var sortedWorkouts: [CompletedWorkout] {
completedWorkouts.sorted(by: { $0.createdAt > $1.createdAt })
}
var body: some View { var body: some View {
List { List {
ForEach(completedWorkouts.sorted(by: { $0.createdAt > $1.createdAt }), id:\.self.id) { completedWorkout in ForEach(sortedWorkouts, id: \.id) { completedWorkout in
HStack { HStack {
VStack { VStack {
if let date = completedWorkout.workoutStartTime.dateFromServerDate { if let date = completedWorkout.workoutStartTime.dateFromServerDate {
Text(date.monthString) Text(date.monthString)
.font(WerkoutTheme.caption)
.foregroundStyle(WerkoutTheme.textSecondary)
Text("\(date.get(.day))") Text("\(date.get(.day))")
.font(WerkoutTheme.stat.monospacedDigit())
.foregroundStyle(WerkoutTheme.accent)
Text("\(date.get(.hour))") Text("\(date.get(.hour))")
.font(WerkoutTheme.caption)
.foregroundStyle(WerkoutTheme.textMuted)
} }
} }
.frame(minWidth: 60)
VStack(alignment: .leading) { VStack(alignment: .leading) {
Text(completedWorkout.workout.name) Text(completedWorkout.workout.name)
.font(.title3) .font(WerkoutTheme.cardTitle)
.foregroundStyle(WerkoutTheme.textPrimary)
if let desc = completedWorkout.workout.description { if let desc = completedWorkout.workout.description {
Text(desc) Text(desc)
.font(.footnote) .font(WerkoutTheme.caption)
.foregroundStyle(WerkoutTheme.textSecondary)
} }
Divider() Divider()
.overlay(WerkoutTheme.divider)
if let difficulty = completedWorkout.difficulty, if let difficulty = completedWorkout.difficulty,
let string = DifficltyString.init(rawValue: difficulty)?.stringValue { let difficultyEnum = DifficltyString(rawValue: difficulty) {
Text(string) Text(difficultyEnum.stringValue)
.font(WerkoutTheme.caption)
.foregroundStyle(difficultyEnum.color)
.padding(.horizontal, WerkoutTheme.sm)
.padding(.vertical, WerkoutTheme.xs)
.background(difficultyEnum.color.opacity(0.15))
.clipShape(RoundedRectangle(cornerRadius: WerkoutTheme.badgeRadius, style: .continuous))
} }
if let notes = completedWorkout.notes { if let notes = completedWorkout.notes {
Text(notes) Text(notes)
.font(WerkoutTheme.bodyText)
.foregroundStyle(WerkoutTheme.textSecondary)
} }
} }
.padding(.leading) .padding(.leading)
@@ -74,10 +112,14 @@ struct WorkoutHistoryView: View {
.onTapGesture { .onTapGesture {
selectedPlannedWorkout = completedWorkout.workout selectedPlannedWorkout = completedWorkout.workout
} }
} }
.listRowBackground(WerkoutTheme.surfaceCard)
} }
} }
.listStyle(.plain)
.background(WerkoutTheme.background)
.scrollContentBackground(.hidden)
.sheet(item: $selectedPlannedWorkout) { item in .sheet(item: $selectedPlannedWorkout) { item in
let viewModel = WorkoutDetailViewModel(workout: item, isPreview: true) let viewModel = WorkoutDetailViewModel(workout: item, isPreview: true)
WorkoutDetailView(viewModel: viewModel) WorkoutDetailView(viewModel: viewModel)

View File

@@ -0,0 +1,127 @@
//
// WerkoutTheme.swift
// Werkout_ios
//
// Design system: iOS 26 Liquid Glass + Industrial Gym Aesthetic
//
import SwiftUI
// MARK: - Design Tokens
enum WerkoutTheme {
// MARK: Colors
static let background = Color.black
static let surfaceCard = Color(white: 0.09)
static let surfaceElevated = Color(white: 0.12)
static let accent = Color("appColor")
static let accentNeon = Color(red: 0.75, green: 0.35, blue: 1.0)
static let success = Color(red: 0.0, green: 0.9, blue: 0.5)
static let danger = Color(red: 1.0, green: 0.25, blue: 0.3)
static let warning = Color(red: 1.0, green: 0.75, blue: 0.0)
static let textPrimary = Color.white
static let textSecondary = Color(white: 0.55)
static let textMuted = Color(white: 0.35)
static let divider = Color(white: 0.15)
// MARK: Typography
static let heroTitle = Font.system(size: 34, weight: .black, design: .rounded)
static let sectionTitle = Font.system(size: 20, weight: .heavy, design: .rounded)
static let cardTitle = Font.system(size: 17, weight: .bold)
static let bodyText = Font.system(size: 15, weight: .medium)
static let caption = Font.system(size: 12, weight: .semibold)
static let stat = Font.system(size: 48, weight: .black, design: .monospaced)
// MARK: Spacing
static let xs: CGFloat = 4
static let sm: CGFloat = 8
static let md: CGFloat = 16
static let lg: CGFloat = 24
static let xl: CGFloat = 32
// MARK: Corner Radius
static let cardRadius: CGFloat = 16
static let buttonRadius: CGFloat = 12
static let badgeRadius: CGFloat = 8
static let pillRadius: CGFloat = 20
}
// MARK: - Reusable View Modifiers
struct WerkoutCardModifier: ViewModifier {
func body(content: Content) -> some View {
content
.padding(WerkoutTheme.md)
.background(WerkoutTheme.surfaceCard)
.clipShape(RoundedRectangle(cornerRadius: WerkoutTheme.cardRadius, style: .continuous))
.overlay(
RoundedRectangle(cornerRadius: WerkoutTheme.cardRadius, style: .continuous)
.strokeBorder(WerkoutTheme.divider, lineWidth: 0.5)
)
}
}
struct WerkoutButtonModifier: ViewModifier {
var color: Color = WerkoutTheme.accent
func body(content: Content) -> some View {
content
.font(.system(size: 16, weight: .bold))
.foregroundStyle(.white)
.padding(.horizontal, WerkoutTheme.lg)
.padding(.vertical, WerkoutTheme.sm + 4)
.background(color)
.clipShape(RoundedRectangle(cornerRadius: WerkoutTheme.buttonRadius, style: .continuous))
}
}
struct WerkoutTextFieldModifier: ViewModifier {
func body(content: Content) -> some View {
content
.padding(12)
.background(WerkoutTheme.surfaceCard)
.clipShape(RoundedRectangle(cornerRadius: WerkoutTheme.buttonRadius, style: .continuous))
.overlay(
RoundedRectangle(cornerRadius: WerkoutTheme.buttonRadius, style: .continuous)
.strokeBorder(WerkoutTheme.accent.opacity(0.3), lineWidth: 1)
)
.foregroundStyle(WerkoutTheme.textPrimary)
}
}
extension View {
func werkoutCard() -> some View {
modifier(WerkoutCardModifier())
}
func werkoutButton(color: Color = WerkoutTheme.accent) -> some View {
modifier(WerkoutButtonModifier(color: color))
}
func werkoutTextField() -> some View {
modifier(WerkoutTextFieldModifier())
}
}
// MARK: - Button Style
struct WerkoutActionButtonStyle: ButtonStyle {
var color: Color = WerkoutTheme.accent
func makeBody(configuration: Configuration) -> some View {
configuration.label
.font(.system(size: 16, weight: .bold))
.foregroundStyle(.white)
.padding(.horizontal, WerkoutTheme.lg)
.padding(.vertical, WerkoutTheme.sm + 4)
.background(color)
.clipShape(RoundedRectangle(cornerRadius: WerkoutTheme.buttonRadius, style: .continuous))
.scaleEffect(configuration.isPressed ? 0.95 : 1.0)
.animation(.easeInOut(duration: 0.15), value: configuration.isPressed)
}
}

View File

@@ -17,7 +17,7 @@ struct Constants {
static let extShowNextVideo = "extShowNextVideo" static let extShowNextVideo = "extShowNextVideo"
static let thotGenderOption = "thotGenderOption" static let thotGenderOption = "thotGenderOption"
static let buttonRadius: CGFloat = 4 static let buttonRadius: CGFloat = 12
} }
@main @main
@@ -28,21 +28,21 @@ struct Werkout_iosApp: App {
@Environment(\.scenePhase) private var scenePhase @Environment(\.scenePhase) private var scenePhase
let pub = NotificationCenter.default.publisher(for: AppNotifications.createdNewWorkout) let pub = NotificationCenter.default.publisher(for: AppNotifications.createdNewWorkout)
let logoutPub = NotificationCenter.default.publisher(for: AppNotifications.userLoggedOut)
private var screenDidConnectPublisher: AnyPublisher<UIScreen, Never> { private var screenDidConnectPublisher: AnyPublisher<UIWindowScene, Never> {
NotificationCenter.default NotificationCenter.default
.publisher(for: UIScene.willConnectNotification) .publisher(for: UIScene.willConnectNotification)
.compactMap { ($0.object as? UIWindowScene)?.screen } .compactMap { $0.object as? UIWindowScene }
.filter { $0 != UIScreen.main } .filter { $0.screen != UIApplication.shared.connectedScenes.compactMap { ($0 as? UIWindowScene)?.screen }.first }
.receive(on: RunLoop.main) .receive(on: RunLoop.main)
.eraseToAnyPublisher() .eraseToAnyPublisher()
} }
private var screenDidDisconnectPublisher: AnyPublisher<UIScreen, Never> { private var screenDidDisconnectPublisher: AnyPublisher<UIWindowScene, Never> {
NotificationCenter.default NotificationCenter.default
.publisher(for: UIScene.didDisconnectNotification) .publisher(for: UIScene.didDisconnectNotification)
.compactMap { ($0.object as? UIWindowScene)?.screen } .compactMap { $0.object as? UIWindowScene }
.filter { $0 != UIScreen.main }
.receive(on: RunLoop.main) .receive(on: RunLoop.main)
.eraseToAnyPublisher() .eraseToAnyPublisher()
} }
@@ -51,14 +51,12 @@ struct Werkout_iosApp: App {
WindowGroup { WindowGroup {
TabView(selection: $tabSelection) { TabView(selection: $tabSelection) {
AllWorkoutsView() AllWorkoutsView()
.onReceive( .onReceive(screenDidConnectPublisher) { scene in
screenDidConnectPublisher, screenDidConnect(scene)
perform: screenDidConnect }
) .onReceive(screenDidDisconnectPublisher) { scene in
.onReceive( screenDidDisconnect(scene)
screenDidDisconnectPublisher, }
perform: screenDidDisconnect
)
.tabItem { .tabItem {
Label("All Workouts", systemImage: "figure.strengthtraining.traditional") Label("All Workouts", systemImage: "figure.strengthtraining.traditional")
} }
@@ -76,33 +74,33 @@ struct Werkout_iosApp: App {
} }
.tag(3) .tag(3)
} }
.accentColor(Color("appColor")) .tint(WerkoutTheme.accent)
.tabBarMinimizeBehavior(.onScrollDown)
.preferredColorScheme(.dark)
.onAppear{ .onAppear{
UIApplication.shared.isIdleTimerDisabled = scenePhase == .active UIApplication.shared.isIdleTimerDisabled = scenePhase == .active
_ = try? AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playback, mode: .default, options: .mixWithOthers) _ = try? AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playback, mode: .default, options: .mixWithOthers)
// UserStore.shared.logout()
} }
.onChange(of: scenePhase) { phase in .onChange(of: scenePhase) { _, phase in
UIApplication.shared.isIdleTimerDisabled = phase == .active UIApplication.shared.isIdleTimerDisabled = phase == .active
} }
.onReceive(pub) { (output) in .onReceive(pub) { _ in
self.tabSelection = 1
}
.onReceive(logoutPub) { _ in
self.tabSelection = 1 self.tabSelection = 1
} }
} }
} }
private func screenDidDisconnect(_ screen: UIScreen) { private func screenDidDisconnect(_ scene: UIWindowScene) {
additionalWindows.removeAll { $0.screen == screen } additionalWindows.removeAll { $0.windowScene == scene }
BridgeModule.shared.isShowingOnExternalDisplay = false BridgeModule.shared.isShowingOnExternalDisplay = false
} }
private func screenDidConnect(_ screen: UIScreen) { private func screenDidConnect(_ scene: UIWindowScene) {
let window = UIWindow(frame: screen.bounds) let window = UIWindow(windowScene: scene)
window.windowScene = UIApplication.shared.connectedScenes
.first { ($0 as? UIWindowScene)?.screen == screen }
as? UIWindowScene
let view = ExternalWorkoutDetailView() let view = ExternalWorkoutDetailView()
.preferredColorScheme(.dark) .preferredColorScheme(.dark)
let controller = UIHostingController(rootView: view) let controller = UIHostingController(rootView: view)

View File

@@ -11,98 +11,90 @@ struct ActionsView: View {
@ObservedObject var bridgeModule = BridgeModule.shared @ObservedObject var bridgeModule = BridgeModule.shared
var completedWorkout: (() -> Void)? var completedWorkout: (() -> Void)?
var planWorkout: ((Workout) -> Void)? var planWorkout: ((Workout) -> Void)?
var workout: Workout var workout: Workout
@Environment(\.dismiss) var dismiss @Environment(\.dismiss) var dismiss
var showAddToCalendar: Bool var showAddToCalendar: Bool
var startWorkoutAction: (() -> Void) var startWorkoutAction: (() -> Void)
@State var showCompleteSheet: Bool = false @State var showCompleteSheet: Bool = false
var body: some View { var body: some View {
HStack { GlassEffectContainer {
if bridgeModule.isInWorkout == false { HStack(spacing: WerkoutTheme.sm) {
Button(action: { if bridgeModule.isInWorkout == false {
bridgeModule.resetCurrentWorkout()
dismiss()
}, label: {
Image(systemName: "xmark.octagon.fill")
.font(.title)
.frame(maxWidth: .infinity, maxHeight: .infinity)
})
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(.red)
.foregroundColor(.white)
.accessibilityLabel("Close workout")
if showAddToCalendar {
Button(action: { Button(action: {
planWorkout?(workout) bridgeModule.resetCurrentWorkout()
dismiss()
}, label: { }, label: {
Image(systemName: "calendar.badge.plus") Image(systemName: "xmark.octagon.fill")
.font(.title) .font(.title)
.frame(maxWidth: .infinity, maxHeight: .infinity) .frame(maxWidth: .infinity, maxHeight: .infinity)
}) })
.frame(maxWidth: .infinity, maxHeight: .infinity) .glassEffect(.regular.interactive())
.background(.blue) .tint(WerkoutTheme.danger)
.foregroundColor(.white) .accessibilityLabel("Close workout")
.accessibilityLabel("Plan workout")
if showAddToCalendar {
Button(action: {
planWorkout?(workout)
}, label: {
Image(systemName: "calendar.badge.plus")
.font(.title)
.frame(maxWidth: .infinity, maxHeight: .infinity)
})
.glassEffect(.regular.interactive())
.tint(WerkoutTheme.accent)
.accessibilityLabel("Plan workout")
}
Button(action: {
startWorkoutAction()
}, label: {
Image(systemName: "arrowtriangle.forward.fill")
.font(.title)
.frame(maxWidth: .infinity, maxHeight: .infinity)
})
.glassEffect(.regular.interactive())
.tint(WerkoutTheme.success)
.accessibilityLabel("Start workout")
} else {
Button(action: {
showCompleteSheet.toggle()
}, label: {
Image(systemName: "checkmark")
.font(.title)
.frame(maxWidth: .infinity, maxHeight: .infinity)
})
.glassEffect(.regular.interactive())
.tint(WerkoutTheme.accent)
.accessibilityLabel("Complete workout")
Button(action: {
AudioEngine.shared.playFinished()
bridgeModule.pauseWorkout()
}, label: {
Image(systemName: bridgeModule.isPaused ? "play.circle.fill" : "pause.circle.fill")
.font(.title)
.frame(maxWidth: .infinity, maxHeight: .infinity)
})
.glassEffect(.regular.interactive())
.tint(bridgeModule.isPaused ? WerkoutTheme.success : WerkoutTheme.warning)
.accessibilityLabel(bridgeModule.isPaused ? "Resume workout" : "Pause workout")
Button(action: {
AudioEngine.shared.playFinished()
nextExercise()
}, label: {
Image(systemName: "arrow.forward")
.font(.title)
.frame(maxWidth: .infinity, maxHeight: .infinity)
})
.glassEffect(.regular.interactive())
.tint(WerkoutTheme.success)
.accessibilityLabel("Next exercise")
} }
Button(action: {
startWorkoutAction()
}, label: {
Image(systemName: "arrowtriangle.forward.fill")
.font(.title)
.frame(maxWidth: .infinity, maxHeight: .infinity)
})
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(.green)
.foregroundColor(.white)
.accessibilityLabel("Start workout")
} else {
Button(action: {
showCompleteSheet.toggle()
}, label: {
Image(systemName: "checkmark")
.font(.title)
.frame(maxWidth: .infinity, maxHeight: .infinity)
})
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(.blue)
.foregroundColor(.white)
.accessibilityLabel("Complete workout")
Button(action: {
AudioEngine.shared.playFinished()
bridgeModule.pauseWorkout()
}, label: {
bridgeModule.isPaused ?
Image(systemName: "play.circle.fill")
.font(.title)
.frame(maxWidth: .infinity, maxHeight: .infinity)
:
Image(systemName: "pause.circle.fill")
.font(.title)
.frame(maxWidth: .infinity, maxHeight: .infinity)
})
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(bridgeModule.isPaused ? .mint : .yellow)
.foregroundColor(.white)
.accessibilityLabel(bridgeModule.isPaused ? "Resume workout" : "Pause workout")
Button(action: {
AudioEngine.shared.playFinished()
nextExercise()
}, label: {
Image(systemName: "arrow.forward")
.font(.title)
.frame(maxWidth: .infinity, maxHeight: .infinity)
})
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(.green)
.foregroundColor(.white)
.accessibilityLabel("Next exercise")
} }
.padding(.horizontal, WerkoutTheme.sm)
} }
.alert("Complete Workout", isPresented: $showCompleteSheet) { .alert("Complete Workout", isPresented: $showCompleteSheet) {
Button("Complete Workout", role: .destructive) { Button("Complete Workout", role: .destructive) {
@@ -112,13 +104,12 @@ struct ActionsView: View {
Button("Back to workout", role: .cancel) { } Button("Back to workout", role: .cancel) { }
} }
} }
func nextExercise() { func nextExercise() {
bridgeModule.nextExercise() bridgeModule.nextExercise()
} }
} }
struct ActionsView_Previews: PreviewProvider { struct ActionsView_Previews: PreviewProvider {
static var previews: some View { static var previews: some View {
ActionsView(workout: PreviewData.workout(), showAddToCalendar: true, startWorkoutAction: {}) ActionsView(workout: PreviewData.workout(), showAddToCalendar: true, startWorkoutAction: {})

View File

@@ -10,37 +10,41 @@ struct AddSupersetView: View {
@ObservedObject var createWorkoutSuperSet: CreateWorkoutSuperSet @ObservedObject var createWorkoutSuperSet: CreateWorkoutSuperSet
var viewModel: WorkoutViewModel var viewModel: WorkoutViewModel
@Binding var selectedCreateWorkoutSuperSet: CreateWorkoutSuperSet? @Binding var selectedCreateWorkoutSuperSet: CreateWorkoutSuperSet?
var body: some View { var body: some View {
TabView { TabView {
ForEach(createWorkoutSuperSet.exercises, id: \.id) { createWorkoutExercise in ForEach(createWorkoutSuperSet.exercises, id: \.id) { createWorkoutExercise in
VStack { VStack(spacing: WerkoutTheme.sm) {
Text(createWorkoutExercise.exercise.name) Text(createWorkoutExercise.exercise.name)
.font(.title2) .font(WerkoutTheme.cardTitle)
.foregroundStyle(WerkoutTheme.textPrimary)
.frame(maxWidth: .infinity) .frame(maxWidth: .infinity)
if let side = createWorkoutExercise.exercise.side, if let side = createWorkoutExercise.exercise.side,
side.isEmpty == false { side.isEmpty == false {
Text(side) Text(side)
.font(.title3) .font(WerkoutTheme.bodyText)
.foregroundStyle(WerkoutTheme.textSecondary)
.frame(maxWidth: .infinity, alignment: .center) .frame(maxWidth: .infinity, alignment: .center)
} }
CreateExerciseActionsView(workoutExercise: createWorkoutExercise, CreateExerciseActionsView(workoutExercise: createWorkoutExercise,
superset: createWorkoutSuperSet, superset: createWorkoutSuperSet,
viewModel: viewModel) viewModel: viewModel)
} }
.frame(width: 300.0) .frame(maxWidth: .infinity)
.padding(.horizontal, WerkoutTheme.md)
.padding(.bottom, 40) .padding(.bottom, 40)
} }
} }
.frame(height: 300) .frame(minHeight: 220, maxHeight: 320)
.tabViewStyle(.page) .tabViewStyle(.page)
.background(WerkoutTheme.background)
.onAppear { .onAppear {
setupAppearance() setupAppearance()
} }
} }
func setupAppearance() { func setupAppearance() {
UIPageControl.appearance().currentPageIndicatorTintColor = .black UIPageControl.appearance().currentPageIndicatorTintColor = UIColor(WerkoutTheme.accent)
UIPageControl.appearance().pageIndicatorTintColor = UIColor.black.withAlphaComponent(0.2) UIPageControl.appearance().pageIndicatorTintColor = UIColor(WerkoutTheme.accent).withAlphaComponent(0.25)
} }
} }

View File

@@ -12,11 +12,14 @@ struct AllEquipmentView: View {
@State var createWorkoutItemPickerViewModel: CreateWorkoutItemPickerViewModel? @State var createWorkoutItemPickerViewModel: CreateWorkoutItemPickerViewModel?
var body: some View { var body: some View {
VStack { VStack(spacing: WerkoutTheme.xs) {
if let _ = DataStore.shared.allEquipment { if let _ = DataStore.shared.allEquipment {
Text("Select Equipment") Text("Select Equipment")
.foregroundColor(.cyan) .font(WerkoutTheme.caption)
.foregroundStyle(WerkoutTheme.accent)
Text("\(selectedEquipment.count) Selected") Text("\(selectedEquipment.count) Selected")
.font(WerkoutTheme.caption)
.foregroundStyle(WerkoutTheme.textSecondary)
} }
} }
.onTapGesture { .onTapGesture {

View File

@@ -12,9 +12,10 @@ struct AllExerciseView: View {
@Environment(\.dismiss) var dismiss @Environment(\.dismiss) var dismiss
@State var searchString: String = "" @State var searchString: String = ""
@Binding var filteredExercises: [Exercise] @Binding var filteredExercises: [Exercise]
@State private var displayedExercises: [Exercise] = []
var selectedExercise: ((Exercise) -> Void) var selectedExercise: ((Exercise) -> Void)
@State var avPlayer = AVPlayer(url: URL(string: "https://dev.werkout.fitness/media/exercise_videos/2_Dumbbell_Lateral_Lunges.mp4") ?? URL(fileURLWithPath: "/dev/null")) @State var avPlayer = AVPlayer(url: URL(string: BaseURLs.currentBaseURL + "/media/exercise_videos/2_Dumbbell_Lateral_Lunges.mp4") ?? URL(fileURLWithPath: "/dev/null"))
@State private var currentVideoURL: URL? @State private var currentVideoURL: URL?
@State var videoExercise: Exercise? { @State var videoExercise: Exercise? {
didSet { didSet {
@@ -24,62 +25,68 @@ struct AllExerciseView: View {
} }
} }
} }
var body: some View { var body: some View {
VStack { VStack(spacing: WerkoutTheme.sm) {
TextField("Filter", text: $searchString) TextField("Filter", text: $searchString)
.padding(.horizontal) .werkoutTextField()
.textFieldStyle(.roundedBorder) .padding(.horizontal, WerkoutTheme.md)
List() { List() {
ForEach(filteredExercises, id: \.self) { exercise in ForEach(displayedExercises, id: \.self) { exercise in
if searchString.isEmpty || exercise.name.lowercased().contains(searchString.lowercased()) { HStack {
HStack { VStack(spacing: WerkoutTheme.xs) {
VStack { Text(exercise.name)
Text(exercise.name) .font(WerkoutTheme.bodyText)
.foregroundStyle(WerkoutTheme.textPrimary)
.frame(maxWidth: .infinity, alignment: .leading)
if let side = exercise.side,
side.isEmpty == false {
Text(side)
.font(WerkoutTheme.caption)
.foregroundStyle(WerkoutTheme.textSecondary)
.frame(maxWidth: .infinity, alignment: .leading) .frame(maxWidth: .infinity, alignment: .leading)
if let side = exercise.side,
side.isEmpty == false {
Text(side)
.font(.footnote)
.frame(maxWidth: .infinity, alignment: .leading)
}
if exercise.equipmentRequired?.isEmpty == false {
Text(exercise.spacedEquipmentRequired)
.font(.footnote)
.frame(maxWidth: .infinity, alignment: .leading)
}
if exercise.muscleGroups?.isEmpty == false {
Text(exercise.spacedMuscleGroups)
.font(.footnote)
.frame(maxWidth: .infinity, alignment: .leading)
}
} }
.contentShape(Rectangle())
.onTapGesture { if exercise.equipmentRequired?.isEmpty == false {
selectedExercise(exercise) Text(exercise.spacedEquipmentRequired)
dismiss() .font(WerkoutTheme.caption)
.foregroundStyle(WerkoutTheme.textSecondary)
.frame(maxWidth: .infinity, alignment: .leading)
} }
Button(action: {
videoExercise = exercise if exercise.muscleGroups?.isEmpty == false {
}) { Text(exercise.spacedMuscleGroups)
ZStack { .font(WerkoutTheme.caption)
Circle() .foregroundStyle(WerkoutTheme.textSecondary)
.fill(.blue) .frame(maxWidth: .infinity, alignment: .leading)
.frame(width: 33, height: 33)
Image(systemName: "video.fill")
.frame(width: 33, height: 33)
.foregroundColor(.white )
}
} }
.frame(width: 33, height: 33)
} }
.contentShape(Rectangle())
.onTapGesture {
selectedExercise(exercise)
dismiss()
}
Button(action: {
videoExercise = exercise
}) {
ZStack {
Circle()
.fill(WerkoutTheme.accent)
.frame(width: 33, height: 33)
Image(systemName: "video.fill")
.frame(width: 33, height: 33)
.foregroundStyle(WerkoutTheme.textPrimary)
}
}
.frame(width: 33, height: 33)
} }
.listRowBackground(WerkoutTheme.surfaceCard)
} }
} }
.scrollContentBackground(.hidden)
.background(WerkoutTheme.background)
} }
.sheet(item: $videoExercise) { exercise in .sheet(item: $videoExercise) { exercise in
PlayerView(player: $avPlayer) PlayerView(player: $avPlayer)
@@ -88,11 +95,23 @@ struct AllExerciseView: View {
avPlayer.play() avPlayer.play()
} }
} }
.onAppear { applySearch() }
.onChange(of: searchString) { _, _ in applySearch() }
.onChange(of: filteredExercises) { _, _ in applySearch() }
.onDisappear { .onDisappear {
avPlayer.pause() avPlayer.pause()
} }
} }
private func applySearch() {
if searchString.isEmpty {
displayedExercises = filteredExercises
} else {
let query = searchString.lowercased()
displayedExercises = filteredExercises.filter { $0.name.lowercased().contains(query) }
}
}
private func updatePlayer(for url: URL) { private func updatePlayer(for url: URL) {
if currentVideoURL == url { if currentVideoURL == url {
avPlayer.seek(to: .zero) avPlayer.seek(to: .zero)

View File

@@ -12,11 +12,14 @@ struct AllMusclesView: View {
@State var createWorkoutItemPickerViewModel: CreateWorkoutItemPickerViewModel? @State var createWorkoutItemPickerViewModel: CreateWorkoutItemPickerViewModel?
var body: some View { var body: some View {
VStack { VStack(spacing: WerkoutTheme.xs) {
if let _ = DataStore.shared.allMuscles { if let _ = DataStore.shared.allMuscles {
Text("Select Muscles") Text("Select Muscles")
.foregroundColor(.cyan) .font(WerkoutTheme.caption)
.foregroundStyle(WerkoutTheme.accent)
Text("\(selectedMuscles.count) Selected") Text("\(selectedMuscles.count) Selected")
.font(WerkoutTheme.caption)
.foregroundStyle(WerkoutTheme.textSecondary)
} }
} }
.onTapGesture { .onTapGesture {

View File

@@ -1,37 +0,0 @@
//
// AllWorkoutPickerView.swift
// Werkout_ios
//
// Created by Trey Tartt on 7/7/23.
//
import SwiftUI
struct AllWorkoutPickerView: View {
var mainViews: [MainViewTypes]
@Binding var selectedSegment: MainViewTypes
@StateObject var bridgeModule = BridgeModule.shared
var showCurrentWorkout: (() -> Void)
var body: some View {
HStack {
Picker("", selection: $selectedSegment) {
ForEach(mainViews, id: \.self) { viewType in
Text(viewType.title)
}
}
.pickerStyle(.segmented)
.padding([.top, .leading, .trailing])
if bridgeModule.isInWorkout {
Button(action: {
showCurrentWorkout()
}, label: {
Image(systemName: "figure.strengthtraining.traditional")
.padding(.trailing)
})
.tint(Color("appColor"))
}
}
}
}

View File

@@ -10,45 +10,47 @@ import SwiftUI
struct CaloriesBurnedView: View { struct CaloriesBurnedView: View {
@Binding var healthKitWorkoutData: HealthKitWorkoutData? @Binding var healthKitWorkoutData: HealthKitWorkoutData?
let calsBurned: Double let calsBurned: Double
var body: some View { var body: some View {
VStack { VStack(spacing: WerkoutTheme.sm) {
HStack { HStack {
HStack { HStack(spacing: WerkoutTheme.sm) {
Image(systemName: "flame.fill") Image(systemName: "flame.fill")
.foregroundColor(.orange) .foregroundStyle(.orange)
.font(.title) .font(.title)
VStack { Text("\(calsBurned, specifier: "%.0f")")
Text("\(calsBurned, specifier: "%.0f")") .font(.system(size: 28, weight: .black, design: .monospaced))
} .foregroundStyle(WerkoutTheme.textPrimary)
} }
.frame(maxWidth: .infinity) .frame(maxWidth: .infinity)
} }
if let minHeart = healthKitWorkoutData?.minHeartRate, if let minHeart = healthKitWorkoutData?.minHeartRate,
let maxHeart = healthKitWorkoutData?.maxHeartRate, let maxHeart = healthKitWorkoutData?.maxHeartRate,
let avgHeart = healthKitWorkoutData?.avgHeartRate { let avgHeart = healthKitWorkoutData?.avgHeartRate {
VStack { VStack(spacing: WerkoutTheme.xs) {
HStack { HStack(spacing: WerkoutTheme.sm) {
Image(systemName: "heart") Image(systemName: "heart.fill")
.foregroundColor(.red) .foregroundStyle(WerkoutTheme.danger)
.font(.title) .font(.title)
VStack { VStack {
HStack { HStack {
Text("\(minHeart, specifier: "%.0f")") Text("\(minHeart, specifier: "%.0f")")
Text("-") Text("-")
.foregroundStyle(WerkoutTheme.textMuted)
Text("\(maxHeart, specifier: "%.0f")") Text("\(maxHeart, specifier: "%.0f")")
} }
Text("\(avgHeart, specifier: "%.0f")") .font(.system(size: 20, weight: .bold, design: .monospaced))
.foregroundStyle(WerkoutTheme.textPrimary)
Text("avg \(avgHeart, specifier: "%.0f")")
.font(WerkoutTheme.caption)
.foregroundStyle(WerkoutTheme.textSecondary)
} }
} }
} }
.frame(maxWidth: .infinity) .frame(maxWidth: .infinity)
} }
} }
.werkoutCard()
} }
} }
//#Preview {
// CaloriesBurnedView()
//}

View File

@@ -8,57 +8,95 @@
import SwiftUI import SwiftUI
struct CompletedWorkoutsView: View { struct CompletedWorkoutsView: View {
@State var completedWorkouts: [CompletedWorkout]? @State private var completedWorkouts: [CompletedWorkout]?
@State var showCompletedWorkouts: Bool = false @State private var showCompletedWorkouts: Bool = false
@State private var loadError: String? @State private var loadError: String?
var body: some View { var body: some View {
VStack(alignment: .leading) { VStack(alignment: .leading) {
if let completedWorkouts = completedWorkouts { if let completedWorkouts = completedWorkouts {
Divider() Divider()
.overlay(WerkoutTheme.divider)
Text("Workout History:") Text("Workout History:")
.font(WerkoutTheme.sectionTitle)
.foregroundStyle(WerkoutTheme.textPrimary)
HStack { HStack {
Text("Number of workouts:") Text("Number of workouts:")
.font(WerkoutTheme.bodyText)
.foregroundStyle(WerkoutTheme.textSecondary)
Text("\(completedWorkouts.count)") Text("\(completedWorkouts.count)")
.font(WerkoutTheme.bodyText)
.foregroundStyle(WerkoutTheme.accent)
} }
if let lastWorkout = completedWorkouts.last { if let lastWorkout = completedWorkouts.last {
HStack { HStack {
Text("Last workout:") Text("Last workout:")
.font(WerkoutTheme.bodyText)
.foregroundStyle(WerkoutTheme.textSecondary)
Text(lastWorkout.workoutStartTime) Text(lastWorkout.workoutStartTime)
.font(WerkoutTheme.bodyText)
.foregroundStyle(WerkoutTheme.accent)
} }
Button("View All Workouts", action: { Button("View All Workouts", action: {
showCompletedWorkouts = true showCompletedWorkouts = true
}) })
.font(.system(size: 16, weight: .bold))
.foregroundStyle(WerkoutTheme.textPrimary)
.frame(maxWidth: .infinity, alignment: .center) .frame(maxWidth: .infinity, alignment: .center)
.frame(height: 44) .frame(height: 44)
.foregroundColor(.blue) .glassEffect(.regular.interactive())
.background(.yellow) .tint(WerkoutTheme.accent)
.cornerRadius(Constants.buttonRadius) .clipShape(RoundedRectangle(cornerRadius: WerkoutTheme.buttonRadius, style: .continuous))
.padding() .padding()
.frame(maxWidth: .infinity) .frame(maxWidth: .infinity)
} }
} else { } else {
if let loadError = loadError { if let loadError = loadError {
Text(loadError) Text(loadError)
.font(WerkoutTheme.bodyText)
.foregroundStyle(WerkoutTheme.danger)
} else { } else {
Text("loading completed workouts") Text("loading completed workouts")
.font(WerkoutTheme.bodyText)
.foregroundStyle(WerkoutTheme.textMuted)
} }
} }
} }
.padding(WerkoutTheme.md)
.background(WerkoutTheme.surfaceCard)
.clipShape(RoundedRectangle(cornerRadius: WerkoutTheme.cardRadius, style: .continuous))
.onAppear{ .onAppear{
fetchCompletedWorkouts() fetchCompletedWorkouts()
} }
.refreshable {
await withCheckedContinuation { continuation in
CompletedWorkoutFetchable().fetch(completion: { result in
DispatchQueue.main.async {
switch result {
case .success(let model):
self.completedWorkouts = model
self.loadError = nil
case .failure(let failure):
self.loadError = "Unable to load workout history: \(failure.localizedDescription)"
}
continuation.resume()
}
})
}
}
.sheet(isPresented: $showCompletedWorkouts) { .sheet(isPresented: $showCompletedWorkouts) {
if let completedWorkouts = completedWorkouts { if let completedWorkouts = completedWorkouts {
WorkoutHistoryView(completedWorkouts: completedWorkouts) WorkoutHistoryView(completedWorkouts: completedWorkouts)
} }
} }
} }
func fetchCompletedWorkouts() { func fetchCompletedWorkouts() {
CompletedWorkoutFetchable().fetch(completion: { result in CompletedWorkoutFetchable().fetch(completion: { result in
switch result { switch result {

View File

@@ -8,15 +8,17 @@
import SwiftUI import SwiftUI
struct CountdownView: View { struct CountdownView: View {
@StateObject var bridgeModule = BridgeModule.shared let currentExerciseDuration: Int?
let currentExerciseTimeLeft: Int
var body: some View { var body: some View {
if let duration = bridgeModule.currentWorkoutInfo.currentExercise?.duration, if let duration = currentExerciseDuration,
duration > 0 { duration > 0 {
HStack { HStack {
if bridgeModule.currentExerciseTimeLeft >= 0 && duration > bridgeModule.currentExerciseTimeLeft { if currentExerciseTimeLeft >= 0 && duration > currentExerciseTimeLeft {
ProgressView(value: Float(bridgeModule.currentExerciseTimeLeft), total: Float(duration)) ProgressView(value: Float(currentExerciseTimeLeft), total: Float(duration))
.tint(Color("appColor")) .tint(currentExerciseTimeLeft < 5 ? WerkoutTheme.danger : WerkoutTheme.accent)
.animation(.easeInOut, value: currentExerciseTimeLeft < 5)
} }
} }
} }
@@ -25,6 +27,6 @@ struct CountdownView: View {
struct CountdownView_Previews: PreviewProvider { struct CountdownView_Previews: PreviewProvider {
static var previews: some View { static var previews: some View {
CountdownView() CountdownView(currentExerciseDuration: 30, currentExerciseTimeLeft: 15)
} }
} }

View File

@@ -11,7 +11,7 @@ struct CreateWorkoutSupersetView: View {
@Binding var showAddExercise: Bool @Binding var showAddExercise: Bool
@ObservedObject var superset: CreateWorkoutSuperSet @ObservedObject var superset: CreateWorkoutSuperSet
@ObservedObject var viewModel: WorkoutViewModel @ObservedObject var viewModel: WorkoutViewModel
var body: some View { var body: some View {
Section(content: { Section(content: {
AddSupersetView( AddSupersetView(
@@ -19,50 +19,58 @@ struct CreateWorkoutSupersetView: View {
viewModel: viewModel, viewModel: viewModel,
selectedCreateWorkoutSuperSet: $selectedCreateWorkoutSuperSet) selectedCreateWorkoutSuperSet: $selectedCreateWorkoutSuperSet)
}, header: { }, header: {
VStack { VStack(spacing: WerkoutTheme.sm) {
HStack { HStack {
TextField("Superset Title", text: $superset.title) TextField("Superset Title", text: $superset.title)
.font(.title2) .font(WerkoutTheme.sectionTitle)
.foregroundStyle(WerkoutTheme.accent)
} }
VStack { VStack(spacing: WerkoutTheme.sm) {
HStack { HStack {
Text("Exercises: \(superset.exercises.count)") Text("Exercises: \(superset.exercises.count)")
.font(.subheadline) .font(WerkoutTheme.caption)
.bold() .foregroundStyle(WerkoutTheme.textSecondary)
Spacer() Spacer()
Button(action: { Button(action: {
selectedCreateWorkoutSuperSet = superset selectedCreateWorkoutSuperSet = superset
showAddExercise = true showAddExercise = true
}, label: { }, label: {
Image(systemName: "dumbbell.fill") Image(systemName: "dumbbell.fill")
.font(.title2) .font(.title2)
.foregroundStyle(WerkoutTheme.accent)
}) })
.accessibilityLabel("Add exercise") .accessibilityLabel("Add exercise")
.accessibilityHint("Adds an exercise to this superset") .accessibilityHint("Adds an exercise to this superset")
Divider() Divider()
.overlay(WerkoutTheme.divider)
Button(action: { Button(action: {
viewModel.delete(superset: superset) viewModel.delete(superset: superset)
}, label: { }, label: {
Image(systemName: "trash") Image(systemName: "trash")
.font(.title2) .font(.title2)
.foregroundStyle(WerkoutTheme.danger)
}) })
.accessibilityLabel("Delete superset") .accessibilityLabel("Delete superset")
.accessibilityHint("Removes this superset") .accessibilityHint("Removes this superset")
} }
Divider() Divider()
.overlay(WerkoutTheme.divider)
Stepper(label: { Stepper(label: {
HStack { HStack {
Text("Rounds: ") Text("Rounds: ")
.font(WerkoutTheme.bodyText)
.foregroundStyle(WerkoutTheme.textPrimary)
Text("\(superset.numberOfRounds)") Text("\(superset.numberOfRounds)")
.foregroundColor(superset.numberOfRounds > 0 ? Color(uiColor: .label) : .red) .foregroundColor(superset.numberOfRounds > 0 ? WerkoutTheme.textPrimary : WerkoutTheme.danger)
.font(WerkoutTheme.bodyText)
.bold() .bold()
} }
}, onIncrement: { }, onIncrement: {
@@ -70,8 +78,10 @@ struct CreateWorkoutSupersetView: View {
}, onDecrement: { }, onDecrement: {
superset.decreaseNumberOfRounds() superset.decreaseNumberOfRounds()
}) })
.tint(WerkoutTheme.accent)
} }
} }
.padding(.vertical, WerkoutTheme.xs)
}) })
} }
} }

View File

@@ -8,50 +8,55 @@
import SwiftUI import SwiftUI
struct ExtCountdownView: View { struct ExtCountdownView: View {
@StateObject var bridgeModule = BridgeModule.shared @ObservedObject var bridgeModule = BridgeModule.shared
var body: some View { var body: some View {
GeometryReader { metrics in GeometryReader { metrics in
VStack { VStack {
if let currenExercise = bridgeModule.currentWorkoutInfo.currentExercise { if let currenExercise = bridgeModule.currentWorkoutInfo.currentExercise {
HStack { HStack {
Text(currenExercise.exercise.extName) Text(currenExercise.exercise.extName)
.font(.system(size: 200)) .font(.system(size: 200, weight: .black, design: .rounded))
.foregroundColor(WerkoutTheme.textPrimary)
.scaledToFit() .scaledToFit()
.minimumScaleFactor(0.01) .minimumScaleFactor(0.01)
.lineLimit(1) .lineLimit(1)
.frame(maxWidth: .infinity, alignment: .leading) .frame(maxWidth: .infinity, alignment: .leading)
} }
.frame(height: metrics.size.height * 0.5) .frame(height: metrics.size.height * 0.5)
HStack { HStack {
if let duration = currenExercise.duration, if let duration = currenExercise.duration,
duration > 0 { duration > 0 {
ProgressView(value: Float(bridgeModule.currentExerciseTimeLeft), total: Float(duration)) ProgressView(value: Float(bridgeModule.currentExerciseTimeLeft), total: Float(duration))
.scaleEffect(x: 1, y: 6, anchor: .center) .scaleEffect(x: 1, y: 6, anchor: .center)
.tint(WerkoutTheme.accent)
Text("\(bridgeModule.currentExerciseTimeLeft)") Text("\(bridgeModule.currentExerciseTimeLeft)")
.font(Font.system(size: 100)) .font(WerkoutTheme.stat)
.foregroundColor(WerkoutTheme.accent)
.scaledToFit() .scaledToFit()
.minimumScaleFactor(0.01) .minimumScaleFactor(0.01)
.lineLimit(1) .lineLimit(1)
.padding(.leading) .padding(.leading)
.padding(.trailing, 100) .padding(.trailing, 100)
} }
if let reps = currenExercise.reps, if let reps = currenExercise.reps,
reps > 0 { reps > 0 {
Text(" X \(reps)") Text(" X \(reps)")
.font(Font.system(size: 100)) .font(.system(size: 100, weight: .heavy, design: .monospaced))
.foregroundColor(WerkoutTheme.textPrimary)
.scaledToFit() .scaledToFit()
.minimumScaleFactor(0.01) .minimumScaleFactor(0.01)
.lineLimit(1) .lineLimit(1)
.frame(maxWidth: .infinity, alignment: .leading) .frame(maxWidth: .infinity, alignment: .leading)
} }
if let weight = currenExercise.weight, if let weight = currenExercise.weight,
weight > 0 { weight > 0 {
Text(" @ \(weight)") Text(" @ \(weight)")
.font(Font.system(size: 100)) .font(.system(size: 100, weight: .heavy, design: .monospaced))
.foregroundColor(WerkoutTheme.textSecondary)
.scaledToFit() .scaledToFit()
.minimumScaleFactor(0.01) .minimumScaleFactor(0.01)
.lineLimit(1) .lineLimit(1)

View File

@@ -10,7 +10,7 @@ import SwiftUI
struct ExtExerciseList: View { struct ExtExerciseList: View {
var workout: Workout var workout: Workout
var allSupersetExecerciseIndex: Int var allSupersetExecerciseIndex: Int
var body: some View { var body: some View {
if let allSupersetExecercise = workout.allSupersetExecercise { if let allSupersetExecercise = workout.allSupersetExecercise {
ZStack { ZStack {
@@ -21,49 +21,41 @@ struct ExtExerciseList: View {
HStack { HStack {
if supersetExecerciseIdx == allSupersetExecerciseIndex { if supersetExecerciseIdx == allSupersetExecerciseIndex {
Image(systemName: "figure.run") Image(systemName: "figure.run")
.foregroundColor(Color("appColor")) .foregroundColor(WerkoutTheme.accent)
.font(Font.system(size: 55)) .font(Font.system(size: 55))
.minimumScaleFactor(0.01) .minimumScaleFactor(0.01)
.lineLimit(1) .lineLimit(1)
} }
Text(supersetExecercise.exercise.name) Text(supersetExecercise.exercise.name)
.font(Font.system(size: 55)) .font(Font.system(size: 55, weight: supersetExecerciseIdx == allSupersetExecerciseIndex ? .bold : .medium))
.foregroundColor(supersetExecerciseIdx == allSupersetExecerciseIndex ? WerkoutTheme.textPrimary : WerkoutTheme.textSecondary)
.minimumScaleFactor(0.01) .minimumScaleFactor(0.01)
.lineLimit(3) .lineLimit(3)
.padding() .padding()
Spacer() Spacer()
} }
.id(supersetExecerciseIdx) .id(supersetExecerciseIdx)
} }
} }
.onChange(of: allSupersetExecerciseIndex, perform: { newValue in .onChange(of: allSupersetExecerciseIndex) {
withAnimation { withAnimation {
proxy.scrollTo(allSupersetExecerciseIndex, anchor: .top) proxy.scrollTo(allSupersetExecerciseIndex, anchor: .top)
} }
}) }
} }
VStack { VStack {
Text("\(allSupersetExecerciseIndex+1)/\(workout.allSupersetExecercise?.count ?? 0)") Text("\(allSupersetExecerciseIndex+1)/\(workout.allSupersetExecercise?.count ?? 0)")
.font(Font.system(size: 55)) .font(Font.system(size: 55, weight: .bold, design: .monospaced))
.minimumScaleFactor(0.01) .minimumScaleFactor(0.01)
.lineLimit(1) .lineLimit(1)
.padding() .padding()
.bold() .foregroundColor(WerkoutTheme.textPrimary)
.foregroundColor(.white) .glassEffect(.regular.interactive())
.background( .tint(WerkoutTheme.accent)
Capsule()
.strokeBorder(Color.black, lineWidth: 0.8)
.background(Color(uiColor: UIColor(red: 148/255,
green: 0,
blue: 211/255,
alpha: 0.5)))
.clipped()
)
.clipShape(Capsule())
Spacer() Spacer()
} }
} }

View File

@@ -1,5 +1,5 @@
// //
// FilterAllView.swift // FilterChip.swift
// Werkout_ios // Werkout_ios
// //
// Created by Trey Tartt on 11/25/24. // Created by Trey Tartt on 11/25/24.
@@ -7,153 +7,26 @@
import SwiftUI import SwiftUI
struct FilterAllView: View { struct FilterChip: View {
@Binding var selectedMuscles: Set<String> let label: String
@Binding var selectedEquipment: Set<String> let color: Color
@Binding var searchNameString: String let onRemove: () -> Void
@Binding var uniqueWorkoutUsers: [RegisteredUser]?
@Binding var filteredRegisterdUser: RegisteredUser?
@Binding var filteredWorkouts: [Workout]
@Binding var workouts: [Workout]
@Binding var currentSort: SortType?
var body: some View {
VStack {
TextField("Search by name" ,text: $searchNameString)
.padding(.horizontal)
.textFieldStyle(.roundedBorder)
HStack { var body: some View {
if let uniqueWorkoutUsers = uniqueWorkoutUsers { HStack(spacing: WerkoutTheme.xs) {
Menu(content: { Text(label)
ForEach(uniqueWorkoutUsers, id: \.self) { index in .font(WerkoutTheme.caption)
Button(action: { .foregroundStyle(color)
filteredRegisterdUser = index
filteredWorkouts = workouts.filterWorkouts( Button(action: onRemove) {
nameSearchString: searchNameString, Image(systemName: "xmark")
musclesSearchString: selectedMuscles, .font(.system(size: 10, weight: .bold))
equipmentSearchString: selectedEquipment, .foregroundStyle(color.opacity(0.7))
filteredRegisterdUser: filteredRegisterdUser
)
}, label: {
Text((index.firstName ?? "") + " -" + (index.lastName ?? ""))
})
}
Button(action: {
filteredRegisterdUser = nil
filteredWorkouts = workouts.filterWorkouts(
nameSearchString: searchNameString,
musclesSearchString: selectedMuscles,
equipmentSearchString: selectedEquipment,
filteredRegisterdUser: filteredRegisterdUser
)
}, label: {
Text("All")
})
}, label: {
Image(systemName: filteredRegisterdUser == nil ? "person.2" : "person.2.fill")
.padding(.trailing)
})
}
Menu(content: {
ForEach(SortType.allCases, id: \.self) { index in
Button(action: {
sortWorkouts(sortType: index)
}, label: {
Text(index.rawValue)
})
}
}, label: {
Image(systemName: "list.number")
.padding(.trailing)
})
if let equipments = DataStore.shared.allEquipment {
Menu(content: {
ForEach(equipments, id: \.id) { equipment in
Button(action: {
if selectedEquipment.contains(equipment.name) {
selectedEquipment.remove(equipment.name)
} else {
selectedEquipment.insert(equipment.name)
}
}, label: {
if selectedEquipment.contains(equipment.name) {
Image(systemName: "checkmark")
}
Text(equipment.name)
})
}
}, label: {
Image(systemName: "scalemass")
.padding(.trailing)
})
}
if let muscles = DataStore.shared.allMuscles {
Menu(content: {
ForEach(muscles, id: \.id) { muscle in
Button(action: {
if selectedMuscles.contains(muscle.name) {
selectedMuscles.remove(muscle.name)
} else {
selectedMuscles.insert(muscle.name)
}
}, label: {
if selectedMuscles.contains(muscle.name) {
Image(systemName: "checkmark")
}
Text(muscle.name)
})
}
}, label: {
Image(systemName: "brain.head.profile")
.padding(.trailing)
})
}
Button(action: {
selectedMuscles.removeAll()
selectedEquipment.removeAll()
searchNameString = ""
filteredRegisterdUser = nil
}, label: {
Image(systemName: "xmark.circle")
.padding(.trailing)
})
} }
} }
} .padding(.horizontal, WerkoutTheme.sm + 2)
.padding(.vertical, WerkoutTheme.xs + 2)
func sortWorkouts(sortType: SortType) { .background(color.opacity(0.12))
if currentSort == sortType { .clipShape(Capsule())
filteredWorkouts = filteredWorkouts.reversed()
return
}
switch sortType {
case .name:
filteredWorkouts = filteredWorkouts.sorted(by: {
$0.name < $1.name
})
case .createdDate:
filteredWorkouts = filteredWorkouts.sorted(by: {
$0.createdAt ?? Date() < $1.createdAt ?? Date()
})
}
currentSort = sortType
} }
} }
#Preview {
FilterAllView(selectedMuscles: .constant([]),
selectedEquipment: .constant([]),
searchNameString: .constant(""),
uniqueWorkoutUsers: .constant(nil),
filteredRegisterdUser: .constant(nil),
filteredWorkouts: .constant(PreviewData.allWorkouts()),
workouts: .constant(PreviewData.allWorkouts()),
currentSort: .constant(nil))
}

View File

@@ -10,28 +10,27 @@ import SwiftUI
struct InfoView: View { struct InfoView: View {
@ObservedObject var bridgeModule = BridgeModule.shared @ObservedObject var bridgeModule = BridgeModule.shared
var workout: Workout var workout: Workout
var body: some View { var body: some View {
VStack { VStack(alignment: .leading, spacing: WerkoutTheme.sm) {
Text(workout.name) Text(workout.name)
.frame(maxWidth: .infinity, alignment: .leading) .font(WerkoutTheme.sectionTitle)
.font(.title3) .foregroundStyle(WerkoutTheme.textPrimary)
.padding()
if let desc = workout.description { if let desc = workout.description {
Text(desc) Text(desc)
.frame(maxWidth: .infinity, alignment: .leading) .font(WerkoutTheme.bodyText)
.font(.body) .foregroundStyle(WerkoutTheme.textSecondary)
.padding([.leading, .trailing])
} }
if let estimatedTime = workout.estimatedTime { if let estimatedTime = workout.estimatedTime {
Text(estimatedTime.asString(style: .abbreviated)) Text(estimatedTime.asString(style: .abbreviated))
.frame(maxWidth: .infinity, alignment: .leading) .font(WerkoutTheme.bodyText)
.font(.body) .foregroundStyle(WerkoutTheme.accent)
.padding([.leading, .trailing])
} }
} }
.padding()
.frame(maxWidth: .infinity, alignment: .leading)
} }
} }

View File

@@ -9,31 +9,37 @@ import SwiftUI
struct Logoutview: View { struct Logoutview: View {
@ObservedObject var userStore = UserStore.shared @ObservedObject var userStore = UserStore.shared
var body: some View { var body: some View {
HStack { GlassEffectContainer {
Button("Logout", action: { HStack {
userStore.logout() Button("Logout", action: {
}) userStore.logout()
.frame(maxWidth: .infinity, alignment: .center) })
.frame(height: 44) .font(.system(size: 16, weight: .bold))
.foregroundColor(.white) .foregroundStyle(WerkoutTheme.textPrimary)
.background(.red) .frame(maxWidth: .infinity, alignment: .center)
.cornerRadius(Constants.buttonRadius) .frame(height: 44)
.padding() .glassEffect(.regular.interactive())
.frame(maxWidth: .infinity) .tint(WerkoutTheme.danger)
.clipShape(RoundedRectangle(cornerRadius: WerkoutTheme.buttonRadius, style: .continuous))
Button(action: { .padding()
userStore.refreshUserData() .frame(maxWidth: .infinity)
}, label: {
Image(systemName: "arrow.triangle.2.circlepath") Button(action: {
}) userStore.refreshUserData()
.frame(width: 44, height: 44) }, label: {
.foregroundColor(.white) Image(systemName: "arrow.triangle.2.circlepath")
.background(.green) })
.cornerRadius(Constants.buttonRadius) .font(.title)
.padding() .foregroundStyle(WerkoutTheme.textPrimary)
.frame(maxWidth: .infinity) .frame(width: 44, height: 44)
.glassEffect(.regular.interactive())
.tint(WerkoutTheme.success)
.clipShape(RoundedRectangle(cornerRadius: WerkoutTheme.buttonRadius, style: .continuous))
.padding()
.frame(maxWidth: .infinity)
}
} }
} }
} }

View File

@@ -9,21 +9,26 @@ import SwiftUI
struct NameView: View { struct NameView: View {
@ObservedObject var userStore = UserStore.shared @ObservedObject var userStore = UserStore.shared
var body: some View { var body: some View {
if let registeredUser = userStore.registeredUser { if let registeredUser = userStore.registeredUser {
if let nickName = registeredUser.nickName { if let nickName = registeredUser.nickName {
Text(nickName) Text(nickName)
.font(.title) .font(WerkoutTheme.heroTitle)
.foregroundStyle(WerkoutTheme.accent)
} }
HStack { HStack {
Text(registeredUser.firstName ?? "-") Text(registeredUser.firstName ?? "-")
Text(registeredUser.lastName ?? "-") Text(registeredUser.lastName ?? "-")
} }
.font(WerkoutTheme.bodyText)
.foregroundStyle(WerkoutTheme.textSecondary)
if let email = registeredUser.email { if let email = registeredUser.email {
Text(email) Text(email)
.font(WerkoutTheme.caption)
.foregroundStyle(WerkoutTheme.textSecondary)
} }
} }
} }

View File

@@ -10,9 +10,12 @@ import SwiftUI
struct OvalTextFieldStyle: TextFieldStyle { struct OvalTextFieldStyle: TextFieldStyle {
func _body(configuration: TextField<Self._Label>) -> some View { func _body(configuration: TextField<Self._Label>) -> some View {
configuration configuration
.padding(10) .padding(12)
.background(LinearGradient(gradient: Gradient(colors: [Color(uiColor: .secondarySystemBackground), Color(uiColor: .secondarySystemBackground)]), startPoint: .topLeading, endPoint: .bottomTrailing)) .background(WerkoutTheme.surfaceCard)
.cornerRadius(20) .clipShape(RoundedRectangle(cornerRadius: WerkoutTheme.buttonRadius, style: .continuous))
.shadow(color: Color(red: 120/255, green: 120/255, blue: 120/255, opacity: 1), radius: 5) .overlay(
RoundedRectangle(cornerRadius: WerkoutTheme.buttonRadius, style: .continuous)
.strokeBorder(WerkoutTheme.accent.opacity(0.3), lineWidth: 1)
)
} }
} }

View File

@@ -10,46 +10,56 @@ import SwiftUI
struct PlannedWorkoutView: View { struct PlannedWorkoutView: View {
let workouts: [PlannedWorkout] let workouts: [PlannedWorkout]
@Binding var selectedPlannedWorkout: Workout? @Binding var selectedPlannedWorkout: Workout?
private var sortedWorkouts: [PlannedWorkout] {
workouts.sorted(by: { $0.onDate < $1.onDate })
}
var body: some View { var body: some View {
List { ScrollView {
ForEach(workouts.sorted(by: { $0.onDate < $1.onDate }), id: \.id) { plannedWorkout in LazyVStack(spacing: WerkoutTheme.sm) {
Button(action: { ForEach(sortedWorkouts, id: \.id) { plannedWorkout in
selectedPlannedWorkout = plannedWorkout.workout Button(action: {
}, label: { selectedPlannedWorkout = plannedWorkout.workout
HStack { }, label: {
VStack(alignment: .leading) { HStack(spacing: WerkoutTheme.md) {
Text(plannedWorkout.onDate.plannedDate?.weekDay ?? "-") VStack(spacing: WerkoutTheme.xs) {
.font(.title) Text(plannedWorkout.onDate.plannedDate?.weekDay ?? "-")
.font(WerkoutTheme.caption)
Text(plannedWorkout.onDate.plannedDate?.monthString ?? "-") .foregroundStyle(WerkoutTheme.accent)
.font(.title)
Text(plannedWorkout.onDate.plannedDate?.dateString ?? "-")
Text(plannedWorkout.onDate.plannedDate?.dateString ?? "-") .font(.system(size: 28, weight: .black, design: .monospaced))
.font(.title) .foregroundStyle(WerkoutTheme.accent)
Text(plannedWorkout.onDate.plannedDate?.monthString ?? "-")
.font(WerkoutTheme.caption)
.foregroundStyle(WerkoutTheme.textSecondary)
}
.frame(width: 60)
WerkoutTheme.divider.frame(width: 0.5)
VStack(alignment: .leading, spacing: WerkoutTheme.xs) {
Text(plannedWorkout.workout.name)
.font(WerkoutTheme.cardTitle)
.foregroundStyle(WerkoutTheme.textPrimary)
Text(plannedWorkout.workout.description ?? "")
.font(WerkoutTheme.bodyText)
.foregroundStyle(WerkoutTheme.textSecondary)
}
.frame(maxWidth: .infinity, alignment: .leading)
} }
.werkoutCard()
Divider() })
.buttonStyle(.plain)
VStack { .accessibilityLabel("Open planned workout \(plannedWorkout.workout.name)")
Text(plannedWorkout.workout.name) .accessibilityHint("Shows workout details")
.font(.title) }
.frame(maxWidth: .infinity, alignment: .leading)
Text(plannedWorkout.workout.description ?? "")
.font(.body)
.frame(maxWidth: .infinity, alignment: .leading)
}
}
})
.buttonStyle(.plain)
.accessibilityLabel("Open planned workout \(plannedWorkout.workout.name)")
.accessibilityHint("Shows workout details")
} }
.padding(.horizontal, WerkoutTheme.sm)
} }
.scrollEdgeEffectStyle(.soft, for: .top)
} }
} }
//#Preview {
// PlannedWorkoutView()
//}

View File

@@ -9,23 +9,28 @@ import SwiftUI
struct RateWorkoutView: View { struct RateWorkoutView: View {
@Binding var difficulty: Float @Binding var difficulty: Float
var body: some View { var body: some View {
VStack { VStack {
Divider() Divider()
.overlay(WerkoutTheme.divider)
HStack { HStack {
Text("No Rate") Text("No Rate")
.foregroundColor(.black) .font(WerkoutTheme.caption)
.foregroundStyle(WerkoutTheme.textMuted)
Text("Easy") Text("Easy")
.foregroundColor(.green) .font(WerkoutTheme.caption)
.foregroundStyle(WerkoutTheme.success)
Spacer() Spacer()
Text("Death") Text("Death")
.foregroundColor(.red) .font(WerkoutTheme.caption)
.foregroundStyle(WerkoutTheme.danger)
} }
ZStack { ZStack {
Slider(value: $difficulty, in: 0...5, step: 1) Slider(value: $difficulty, in: 0...5, step: 1)
.tint(WerkoutTheme.accent)
} }
} }
} }

View File

@@ -13,7 +13,10 @@ struct ShowNextUpView: View {
var body: some View { var body: some View {
Toggle(isOn: $extShowNextVideo, label: { Toggle(isOn: $extShowNextVideo, label: {
Text("Show next up video") Text("Show next up video")
.font(WerkoutTheme.bodyText)
.foregroundStyle(WerkoutTheme.textPrimary)
}) })
.tint(WerkoutTheme.accent)
} }
} }

View File

@@ -12,11 +12,13 @@ struct ThotPreferenceView: View {
@AppStorage(Constants.phoneThotStyle) private var phoneThotStyle: ThotStyle = .never @AppStorage(Constants.phoneThotStyle) private var phoneThotStyle: ThotStyle = .never
@AppStorage(Constants.extThotStyle) private var extThotStyle: ThotStyle = .never @AppStorage(Constants.extThotStyle) private var extThotStyle: ThotStyle = .never
@AppStorage(Constants.thotGenderOption) private var thotGenderOption: String = "female" @AppStorage(Constants.thotGenderOption) private var thotGenderOption: String = "female"
var body: some View { var body: some View {
if userStore.registeredUser?.NSFWValue ?? false { if userStore.registeredUser?.NSFWValue ?? false {
Group { Group {
Text("Phone THOT Style:") Text("Phone THOT Style:")
.font(WerkoutTheme.bodyText)
.foregroundStyle(WerkoutTheme.textSecondary)
Picker("Phone THOT Style:", selection: $phoneThotStyle) { Picker("Phone THOT Style:", selection: $phoneThotStyle) {
ForEach(ThotStyle.allCases, id: \.self) { style in ForEach(ThotStyle.allCases, id: \.self) { style in
Text(style.stringValue()) Text(style.stringValue())
@@ -24,10 +26,14 @@ struct ThotPreferenceView: View {
} }
} }
.pickerStyle(.segmented) .pickerStyle(.segmented)
.tint(WerkoutTheme.accent)
Divider() Divider()
.overlay(WerkoutTheme.divider)
Text("External THOT Style:") Text("External THOT Style:")
.font(WerkoutTheme.bodyText)
.foregroundStyle(WerkoutTheme.textSecondary)
Picker("External THOT Style:", selection: $extThotStyle) { Picker("External THOT Style:", selection: $extThotStyle) {
ForEach(ThotStyle.allCases, id: \.self) { style in ForEach(ThotStyle.allCases, id: \.self) { style in
Text(style.stringValue()) Text(style.stringValue())
@@ -35,10 +41,14 @@ struct ThotPreferenceView: View {
} }
} }
.pickerStyle(.segmented) .pickerStyle(.segmented)
.tint(WerkoutTheme.accent)
if let genderOptions = DataStore.shared.nsfwGenderOptions { if let genderOptions = DataStore.shared.nsfwGenderOptions {
Divider() Divider()
.overlay(WerkoutTheme.divider)
Text("Video Gender:") Text("Video Gender:")
.font(WerkoutTheme.bodyText)
.foregroundStyle(WerkoutTheme.textSecondary)
Picker("Video Gender:", selection: $thotGenderOption) { Picker("Video Gender:", selection: $thotGenderOption) {
ForEach(genderOptions, id: \.self) { option in ForEach(genderOptions, id: \.self) { option in
Text(option.capitalized) Text(option.capitalized)
@@ -46,6 +56,7 @@ struct ThotPreferenceView: View {
} }
} }
.pickerStyle(.segmented) .pickerStyle(.segmented)
.tint(WerkoutTheme.accent)
} }
} }
} }

View File

@@ -9,18 +9,20 @@ import SwiftUI
struct TitleView: View { struct TitleView: View {
@ObservedObject var bridgeModule = BridgeModule.shared @ObservedObject var bridgeModule = BridgeModule.shared
var body: some View { var body: some View {
HStack { HStack {
if let workout = bridgeModule.currentWorkoutInfo.workout { if let workout = bridgeModule.currentWorkoutInfo.workout {
Text(workout.name) Text(workout.name)
.font(Font.system(size: 100)) .font(.system(size: 100, weight: .black, design: .rounded))
.foregroundColor(WerkoutTheme.textPrimary)
.frame(maxWidth: .infinity, alignment: .leading) .frame(maxWidth: .infinity, alignment: .leading)
} }
if bridgeModule.currentWorkoutRunTimeInSeconds > -1 { if bridgeModule.currentWorkoutRunTimeInSeconds > -1 {
Text("\(bridgeModule.currentWorkoutRunTimeInSeconds)") Text("\(bridgeModule.currentWorkoutRunTimeInSeconds)")
.font(Font.system(size: 100)) .font(WerkoutTheme.stat)
.foregroundColor(WerkoutTheme.accent)
.frame(maxWidth: .infinity, alignment: .trailing) .frame(maxWidth: .infinity, alignment: .trailing)
.padding(.trailing, 100) .padding(.trailing, 100)
} }

View File

@@ -9,25 +9,20 @@ import SwiftUI
struct WorkoutInfoView: View { struct WorkoutInfoView: View {
let workout: Workout let workout: Workout
var body: some View { var body: some View {
VStack { VStack(alignment: .leading, spacing: WerkoutTheme.sm) {
Text(workout.name) Text(workout.name)
.frame(maxWidth: .infinity, alignment: .leading) .font(WerkoutTheme.sectionTitle)
.font(.title3) .foregroundStyle(WerkoutTheme.textPrimary)
.padding(.top
)
if let desc = workout.description { if let desc = workout.description {
Text(desc) Text(desc)
.frame(maxWidth: .infinity, alignment: .leading) .font(WerkoutTheme.bodyText)
.font(.body) .foregroundStyle(WerkoutTheme.textSecondary)
.padding(.top)
} }
} }
.padding()
.frame(maxWidth: .infinity, alignment: .leading)
} }
} }
//#Preview {
// WorkoutInfoView()
//}

View File

@@ -9,58 +9,47 @@ import SwiftUI
struct WorkoutOverviewView: View { struct WorkoutOverviewView: View {
let workout: Workout let workout: Workout
var body: some View { var body: some View {
VStack { VStack(alignment: .leading, spacing: WerkoutTheme.xs) {
HStack { Text(workout.name)
VStack { .font(WerkoutTheme.cardTitle)
Text(workout.name) .foregroundStyle(WerkoutTheme.textPrimary)
.font(.title2) .lineLimit(1)
.frame(maxWidth: .infinity, alignment: .leading)
if let description = workout.description, !description.isEmpty {
Text(workout.description ?? "") Text(description)
.frame(maxWidth: .infinity, alignment: .leading) .font(WerkoutTheme.bodyText)
.foregroundStyle(WerkoutTheme.textSecondary)
if let estimatedTime = workout.estimatedTime { .lineLimit(2)
Text("Time: " + estimatedTime.asString(style: .abbreviated)) }
.frame(maxWidth: .infinity, alignment: .leading)
} HStack(spacing: 12) {
if let estimatedTime = workout.estimatedTime {
if let createdAt = workout.createdAt { Label(estimatedTime.asString(style: .abbreviated), systemImage: "clock")
Text(createdAt, style: .date)
.font(.footnote)
.frame(maxWidth: .infinity, alignment: .leading)
}
} }
if let exerciseCount = workout.exercise_count { if let exerciseCount = workout.exercise_count {
VStack { Label("\(exerciseCount) exercises", systemImage: "list.bullet")
Text("\(exerciseCount)") }
.font(.body.bold())
Text("exercises") if let muscles = workout.muscles, !muscles.isEmpty {
.font(.footnote) Label(muscleSummary(muscles), systemImage: "figure.strengthtraining.traditional")
.foregroundColor(Color(uiColor: .systemGray2))
}
} }
} }
.font(WerkoutTheme.caption)
if let muscles = workout.muscles, .foregroundStyle(WerkoutTheme.textMuted)
muscles.joined(separator: ", ").count > 0{
Divider()
Text(muscles.joined(separator: ", "))
.font(.footnote)
.frame(maxWidth: .infinity, alignment: .leading)
}
if let equipment = workout.equipment,
equipment.joined(separator: ", ").count > 0 {
Divider()
Text(equipment.joined(separator: ", "))
.font(.footnote)
.frame(maxWidth: .infinity, alignment: .leading)
}
} }
.padding() .frame(maxWidth: .infinity, alignment: .leading)
.background(Color(uiColor: .secondarySystemBackground)) .werkoutCard()
.cornerRadius(2) }
private func muscleSummary(_ muscles: [String]) -> String {
guard let first = muscles.first else { return "" }
if muscles.count <= 2 {
return muscles.joined(separator: ", ")
}
return "\(first), \(muscles[1]) +\(muscles.count - 2)"
} }
} }

View File

@@ -18,9 +18,9 @@ class WatchMainViewModel: NSObject, ObservableObject {
var session: WCSession var session: WCSession
@Published var watchPackageModel = WatchMainViewModel.defualtPackageModle @Published var watchPackageModel = WatchMainViewModel.defaultPackageModel
static var defualtPackageModle: WatchPackageModel { static var defaultPackageModel: WatchPackageModel {
WatchPackageModel(currentExerciseName: "", currentExerciseID: -1, currentTimeLeft: -1, workoutStartDate: Date()) WatchPackageModel(currentExerciseName: "", currentExerciseID: -1, currentTimeLeft: -1, workoutStartDate: Date())
} }
@@ -66,7 +66,6 @@ class WatchMainViewModel: NSObject, ObservableObject {
func pauseWorkout() { func pauseWorkout() {
send(.pauseWorkout) send(.pauseWorkout)
WKInterfaceDevice.current().play(.start) WKInterfaceDevice.current().play(.start)
WatchWorkout.shared.togglePaused()
} }
func dataToAction(messageData: Data) { func dataToAction(messageData: Data) {
@@ -81,10 +80,10 @@ class WatchMainViewModel: NSObject, ObservableObject {
} }
self.watchPackageModel = newWatchPackageModel self.watchPackageModel = newWatchPackageModel
case .reset: case .reset:
self.watchPackageModel = WatchMainViewModel.defualtPackageModle self.watchPackageModel = WatchMainViewModel.defaultPackageModel
WatchWorkout.shared.stopWorkout(sendDetails: false) WatchWorkout.shared.stopWorkout(sendDetails: false)
case .endWorkout: case .endWorkout:
self.watchPackageModel = WatchMainViewModel.defualtPackageModle self.watchPackageModel = WatchMainViewModel.defaultPackageModel
WatchWorkout.shared.stopWorkout(sendDetails: true) WatchWorkout.shared.stopWorkout(sendDetails: true)
case .startWorkout: case .startWorkout:
WatchWorkout.shared.startWorkout() WatchWorkout.shared.startWorkout()