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>
This commit is contained in:
Trey t
2026-02-23 10:24:06 -06:00
parent 921829f2c3
commit 5d39dcb66f
60 changed files with 1783 additions and 1346 deletions

View File

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

View File

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

View File

@@ -13,88 +13,88 @@ enum SortType: String, CaseIterable {
}
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]
@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)
@State var filteredWorkouts = [Workout]()
var refresh: (() -> Void)
@State var currentSort: SortType?
@State private var filteredWorkouts = [Workout]()
var body: some View {
VStack {
VStack {
if let filteredRegisterdUser = filteredRegisterdUser {
Text((filteredRegisterdUser.firstName ?? "NA") + "'s Workouts")
}
FilterAllView(selectedMuscles: $selectedMuscles,
selectedEquipment: $selectedEquipment,
searchNameString: $searchNameString,
uniqueWorkoutUsers: $uniqueWorkoutUsers,
filteredRegisterdUser: $filteredRegisterdUser,
filteredWorkouts: $filteredWorkouts,
workouts: .constant(workouts),
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")
}
ScrollView {
LazyVStack(spacing: WerkoutTheme.sm) {
ForEach(filteredWorkouts, id: \.id) { workout in
Button(action: {
selectedWorkout(workout)
}, label: {
WorkoutOverviewView(workout: workout)
.padding(.horizontal, WerkoutTheme.sm)
.contentShape(Rectangle())
})
.buttonStyle(.plain)
.accessibilityLabel("Open \(workout.name)")
.accessibilityHint("Shows workout details")
}
}
.background(Color(uiColor: .systemBackground))
.refreshable {
refresh()
}
.padding(.top, WerkoutTheme.sm)
}
.onChange(of: searchNameString) { newValue in
filterWorkouts()
.scrollEdgeEffectStyle(.soft, for: .top)
.background(WerkoutTheme.background)
.refreshable {
refresh()
}
.onChange(of: selectedMuscles) { newValue in
filterWorkouts()
}
.onChange(of: selectedEquipment) { newValue in
filterWorkouts()
}
.onAppear{
filterWorkouts()
}
.onChange(of: workouts) { _ in
filterWorkouts()
.onAppear {
applyFilters()
}
.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() {
filteredWorkouts = workouts.filterWorkouts(
nameSearchString: searchNameString,
private func applyFilters() {
var results = workouts.filterWorkouts(
nameSearchString: searchText,
musclesSearchString: selectedMuscles,
equipmentSearchString: selectedEquipment,
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 {
static var previews: some View {
AllWorkoutsListView(uniqueWorkoutUsers: .constant([]),
workouts: PreviewData.allWorkouts(),
selectedWorkout: { workout in },
refresh: { })
AllWorkoutsListView(workouts: PreviewData.allWorkouts(),
searchText: .constant(""),
selectedMuscles: .constant([]),
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 {
case AllWorkout = 0
case MyWorkouts
var title: String {
switch self {
case .AllWorkout:
return "All Workouts"
case .MyWorkouts:
return "Planned Workouts"
return "Planned"
}
}
}
struct AllWorkoutsView: View {
@State var isUpdating = false
@State var workouts: [Workout]?
@State var uniqueWorkoutUsers: [RegisteredUser]?
@State private var isUpdating = false
private var workouts: [Workout]? {
dataStore.allWorkouts?.sorted(by: { $0.createdAt ?? Date() < $1.createdAt ?? Date() })
}
private var uniqueWorkoutUsers: [RegisteredUser]? {
dataStore.workoutsUniqueUsers
}
let healthStore = HKHealthStore()
var bridgeModule = BridgeModule.shared
@State public var needsUpdating: Bool = true
@State private var needsUpdating: Bool = true
@ObservedObject var dataStore = DataStore.shared
@ObservedObject var userStore = UserStore.shared
@State private var showWorkoutDetail = false
@State private var selectedWorkout: Workout? {
didSet {
bridgeModule.currentWorkoutInfo.workout = selectedWorkout
}
}
@State private var selectedPlannedWorkout: Workout? {
didSet {
bridgeModule.currentWorkoutInfo.workout = selectedPlannedWorkout
}
}
@State private var showLoginView = false
@State private var selectedSegment: MainViewTypes = .AllWorkout
@State var selectedDate: Date = Date()
@State private var selectedDate: Date = Date()
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)
var body: some View {
ZStack {
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()
})
private var hasActiveFilters: Bool {
!selectedMuscles.isEmpty || !selectedEquipment.isEmpty || filteredRegisterdUser != nil
}
Divider()
case .MyWorkouts:
PlannedWorkoutView(workouts: userStore.plannedWorkouts,
selectedPlannedWorkout: $selectedPlannedWorkout)
var body: some View {
NavigationStack {
ZStack {
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{
// UserStore.shared.logout()
.onAppear {
authorizeHealthKit()
maybeRefreshData()
}
@@ -114,31 +168,171 @@ struct AllWorkoutsView: View {
})
.interactiveDismissDisabled()
}
.onReceive(pub) { (output) in
.onReceive(pub) { _ in
self.needsUpdating = true
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() {
if userStore.token != nil{
if userStore.token != nil {
if userStore.plannedWorkouts.isEmpty {
userStore.fetchPlannedWorkouts()
}
if needsUpdating {
self.isUpdating = true
dataStore.fetchAllData(completion: {
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.uniqueWorkoutUsers = dataStore.workoutsUniqueUsers
self.needsUpdating = false
}
})
@@ -148,7 +342,7 @@ struct AllWorkoutsView: View {
showLoginView = true
}
}
func authorizeHealthKit() {
let quantityTypes = [
HKObjectType.quantityType(forIdentifier: .heartRate),
@@ -162,7 +356,7 @@ struct AllWorkoutsView: View {
HKQuantityType.workoutType()
]
)
healthStore.requestAuthorization(toShare: nil, read: healthKitTypes) { (success, error) in
if success == false {
runtimeReporter.recordWarning(
@@ -176,6 +370,6 @@ struct AllWorkoutsView: View {
struct AllWorkoutsView_Previews: PreviewProvider {
static var previews: some View {
AllWorkoutsView(workouts: PreviewData.allWorkouts())
AllWorkoutsView()
}
}

View File

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

View File

@@ -12,8 +12,8 @@ struct CreateExerciseActionsView: View {
@ObservedObject var workoutExercise: CreateWorkoutExercise
@ObservedObject var superset: CreateWorkoutSuperSet
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 var videoExercise: Exercise? {
didSet {
@@ -23,90 +23,103 @@ struct CreateExerciseActionsView: View {
}
}
}
var body: some View {
VStack {
VStack {
VStack(spacing: WerkoutTheme.sm) {
VStack(spacing: WerkoutTheme.xs) {
HStack {
Text("Reps: ")
.font(WerkoutTheme.bodyText)
.foregroundStyle(WerkoutTheme.textSecondary)
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()
Stepper("", onIncrement: {
workoutExercise.increaseReps()
}, onDecrement: {
workoutExercise.decreaseReps()
})
.tint(WerkoutTheme.accent)
.accessibilityLabel("Reps")
}
}
HStack {
Text("Weight: ")
.font(WerkoutTheme.bodyText)
.foregroundStyle(WerkoutTheme.textSecondary)
Text("\(workoutExercise.weight)")
.font(WerkoutTheme.bodyText)
.foregroundStyle(WerkoutTheme.textPrimary)
Stepper("", onIncrement: {
workoutExercise.increaseWeight()
}, onDecrement: {
workoutExercise.decreaseWeight()
})
.tint(WerkoutTheme.accent)
.accessibilityLabel("Weight")
}
HStack {
Text("Duration: ")
.font(WerkoutTheme.bodyText)
.foregroundStyle(WerkoutTheme.textSecondary)
Text("\(workoutExercise.duration)")
.foregroundColor(
workoutExercise.reps == 0 && workoutExercise.duration == 0 ? .red : Color(
uiColor: .label
)
workoutExercise.reps == 0 && workoutExercise.duration == 0 ? WerkoutTheme.danger : WerkoutTheme.textPrimary
)
.font(WerkoutTheme.bodyText)
.bold()
Stepper("", onIncrement: {
workoutExercise.increaseDuration()
}, onDecrement: {
workoutExercise.decreaseDuration()
})
.tint(WerkoutTheme.accent)
.accessibilityLabel("Duration")
}
HStack {
Spacer()
Button(action: {
videoExercise = workoutExercise.exercise
}) {
Image(systemName: "video.fill")
GlassEffectContainer {
HStack {
Spacer()
Button(action: {
videoExercise = workoutExercise.exercise
}) {
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

View File

@@ -5,7 +5,8 @@
// Created by Trey Tartt on 6/18/23.
//
import SwiftUI
import Combine
import Foundation
import SharedCore
class CreateWorkoutExercise: ObservableObject, Identifiable {
@@ -93,6 +94,9 @@ class WorkoutViewModel: ObservableObject {
@Published var description = String()
@Published var validationError: String?
@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
func increaseRandomNumberForUpdating() {
@@ -112,7 +116,32 @@ class WorkoutViewModel: ObservableObject {
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() {
validationError = "Each superset must have at least one round."
}

View File

@@ -15,16 +15,16 @@ struct CreateWorkoutItemPickerModel {
class CreateWorkoutItemPickerViewModel: Identifiable, ObservableObject {
let allValues: [CreateWorkoutItemPickerModel]
@Published var selectedIds: [Int]
@Published var selectedIds: Set<Int>
init(allValues: [CreateWorkoutItemPickerModel], selectedIds: [Int]) {
self.allValues = allValues
self.selectedIds = selectedIds
self.selectedIds = Set(selectedIds)
}
func toggleAll() {
if selectedIds.isEmpty {
selectedIds.append(contentsOf: allValues.map({ $0.id }))
selectedIds = Set(allValues.map({ $0.id }))
} else {
selectedIds.removeAll()
}
@@ -38,65 +38,71 @@ struct CreateWorkoutItemPickerView: View {
@State var searchString: String = ""
var body: some View {
VStack {
VStack(spacing: 0) {
List() {
ForEach(viewModel.allValues, id:\.self.id) { value in
if searchString.isEmpty || value.name.lowercased().contains(searchString.lowercased()) {
HStack {
HStack(spacing: WerkoutTheme.sm) {
Circle()
.stroke(.blue, lineWidth: 1)
.background(Circle().fill(viewModel.selectedIds.contains(value.id) ? .blue :.clear))
.stroke(WerkoutTheme.accent, lineWidth: 1.5)
.background(Circle().fill(viewModel.selectedIds.contains(value.id) ? WerkoutTheme.accent : Color.clear))
.frame(width: 33, height: 33)
Text(value.name)
.font(WerkoutTheme.bodyText)
.foregroundStyle(WerkoutTheme.textPrimary)
}
.contentShape(Rectangle())
.onTapGesture {
if viewModel.selectedIds.contains(value.id) {
if let idx = viewModel.selectedIds.firstIndex(of: value.id){
viewModel.selectedIds.remove(at: idx)
}
viewModel.selectedIds.remove(value.id)
} else {
viewModel.selectedIds.append(value.id)
viewModel.selectedIds.insert(value.id)
}
}
.listRowBackground(WerkoutTheme.surfaceCard)
}
}
}
TextField("Filter", text: $searchString)
.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()
.scrollContentBackground(.hidden)
.background(WerkoutTheme.background)
Button(action: {
completed(viewModel.selectedIds)
dismiss()
}, label: {
Text("done")
})
.frame(maxWidth: .infinity, alignment: .center)
.frame(height: 44)
.foregroundColor(.blue)
.background(.yellow)
.cornerRadius(Constants.buttonRadius)
.padding()
.frame(maxWidth: .infinity)
TextField("Filter", text: $searchString)
.werkoutTextField()
.padding(.horizontal, WerkoutTheme.md)
.padding(.vertical, WerkoutTheme.sm)
GlassEffectContainer {
HStack(spacing: WerkoutTheme.md) {
Button(action: {
viewModel.toggleAll()
}, label: {
Image(systemName: "checklist")
.font(.title)
.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"),
CreateWorkoutItemPickerModel(id: 2, name: "two"),
CreateWorkoutItemPickerModel(id: 3, name: "three")]
static var previews: some View {
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.isUploading == false
}
var body: some View {
VStack {
VStack {
VStack(spacing: 0) {
VStack(spacing: WerkoutTheme.sm) {
TextField("Title", text: $viewModel.title)
.padding(.horizontal)
.textFieldStyle(.roundedBorder)
.werkoutTextField()
.padding(.horizontal, WerkoutTheme.md)
TextField("Description", text: $viewModel.description)
.padding(.horizontal)
.textFieldStyle(.roundedBorder)
.werkoutTextField()
.padding(.horizontal, WerkoutTheme.md)
}
.padding(.bottom)
.background(Color(uiColor: .systemGray5))
.padding(.vertical, WerkoutTheme.md)
.background(WerkoutTheme.surfaceCard)
ScrollViewReader { proxy in
List() {
ForEach(viewModel.superSets) { superset in
@@ -40,6 +40,7 @@ struct CreateWorkoutMainView: View {
superset: superset,
viewModel: viewModel)
}
.listRowBackground(WerkoutTheme.surfaceCard)
// after adding new exercise we have to scroll to the bottom
// where the new exercise is sooo keep this so we can scroll
// to id 999
@@ -48,91 +49,70 @@ struct CreateWorkoutMainView: View {
.accessibilityHidden(true)
.id(999)
.listRowSeparator(.hidden)
.listRowBackground(Color.clear)
}
.onChange(of: viewModel.randomValueForUpdatingValue, perform: { newValue in
.scrollContentBackground(.hidden)
.background(WerkoutTheme.background)
.onChange(of: viewModel.randomValueForUpdatingValue) { _, _ in
withAnimation {
proxy.scrollTo(999, anchor: .bottom)
}
})
}
}
.sheet(isPresented: $showAddExercise) {
AddExerciseView(selectedExercise: { exercise in
let workoutExercise = CreateWorkoutExercise(exercise: exercise)
selectedCreateWorkoutSuperSet?.exercises.append(workoutExercise)
// 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)
}
}
}
}
if let superset = selectedCreateWorkoutSuperSet {
viewModel.addExercise(exercise, to: superset)
}
viewModel.increaseRandomNumberForUpdating()
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()
.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>(
get: { viewModel.validationError != nil },
set: { _ in viewModel.validationError = nil }

View File

@@ -12,32 +12,38 @@ struct CreateWorkoutSupersetActionsView: View {
@Binding var showAddExercise: Bool
var viewModel: WorkoutViewModel
@Binding var selectedCreateWorkoutSuperSet: CreateWorkoutSuperSet?
var body: some View {
HStack {
Button(action: {
selectedCreateWorkoutSuperSet = workoutSuperSet
showAddExercise.toggle()
}) {
Text("Add exercise")
.padding()
}
.foregroundColor(.white)
.background(.green)
.frame(maxWidth: .infinity, alignment: .center)
Button(action: {
GlassEffectContainer {
HStack(spacing: WerkoutTheme.md) {
Button(action: {
selectedCreateWorkoutSuperSet = workoutSuperSet
showAddExercise.toggle()
}) {
Text("Add exercise")
.font(.system(size: 15, weight: .bold))
.foregroundStyle(WerkoutTheme.textPrimary)
.padding()
}
.glassEffect(.regular.interactive())
.tint(WerkoutTheme.success)
.frame(maxWidth: .infinity, alignment: .center)
Button(action: {
// viewModel.delete(superset: workoutSuperSet)
// viewModel.increaseRandomNumberForUpdating()
// viewModel.objectWillChange.send()
}) {
Text("Delete superset")
.padding()
}) {
Text("Delete superset")
.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
struct ExternalWorkoutDetailView: View {
@StateObject 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 smallAVPlayer = AVPlayer(url: URL(string: "https://dev.werkout.fitness/media/exercise_videos/2_Dumbbell_Lateral_Lunges.mp4") ?? URL(fileURLWithPath: "/dev/null"))
@ObservedObject var bridgeModule = BridgeModule.shared
@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: BaseURLs.currentBaseURL + "/media/exercise_videos/2_Dumbbell_Lateral_Lunges.mp4") ?? URL(fileURLWithPath: "/dev/null"))
@State private var currentVideoURL: URL?
@State private var currentSmallVideoURL: URL?
@AppStorage(Constants.extThotStyle) private var extThotStyle: ThotStyle = .never
@@ -32,23 +32,23 @@ struct ExternalWorkoutDetailView: View {
avPlayer.play()
}
}
VStack {
ExtExerciseList(workout: workout,
allSupersetExecerciseIndex: bridgeModule.currentWorkoutInfo.allSupersetExecerciseIndex)
}
.frame(width: metrics.size.width * 0.4, height: metrics.size.height * 0.8)
.padding([.top, .bottom], 20)
.padding([.top, .bottom], WerkoutTheme.lg)
}
HStack {
ExtCountdownView()
.padding(.leading, 50)
.padding(.bottom, 20)
.padding(.bottom, WerkoutTheme.lg)
if extShowNextVideo && extThotStyle != .off {
PlayerView(player: $smallAVPlayer)
.frame(width: metrics.size.width * 0.2,
.frame(width: metrics.size.width * 0.2,
height: metrics.size.height * 0.2)
.onAppear{
smallAVPlayer.isMuted = true
@@ -56,7 +56,7 @@ struct ExternalWorkoutDetailView: View {
}
}
}
.background(Color(uiColor: .tertiarySystemGroupedBackground))
.background(WerkoutTheme.surfaceCard)
}
}
} else {
@@ -65,43 +65,34 @@ struct ExternalWorkoutDetailView: View {
.edgesIgnoringSafeArea(.all)
.scaledToFill()
}
VStack {
HStack {
if bridgeModule.currentWorkoutRunTimeInSeconds > -1 {
Text(" \(Double(bridgeModule.currentWorkoutRunTimeInSeconds).asString(style: .positional)) ")
.font(Font.system(size: 120))
.font(WerkoutTheme.stat)
.minimumScaleFactor(0.01)
.lineLimit(1)
.padding()
.bold()
.foregroundColor(.white)
.background(
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())
.foregroundColor(WerkoutTheme.textPrimary)
.glassEffect(.regular.interactive())
.tint(WerkoutTheme.accent)
}
Spacer()
}
.padding(.leading, 50)
Spacer()
}
}
.onChange(of: bridgeModule.isInWorkout, perform: { _ in
.onChange(of: bridgeModule.isInWorkout) {
playVideos()
})
.onChange(of: bridgeModule.currentWorkoutInfo.allSupersetExecerciseIndex, perform: { _ in
}
.onChange(of: bridgeModule.currentWorkoutInfo.allSupersetExecerciseIndex) {
playVideos()
})
}
.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(
for: UIScene.willEnterForegroundNotification)) { _ in
avPlayer.play()
@@ -112,7 +103,7 @@ struct ExternalWorkoutDetailView: View {
smallAVPlayer.pause()
}
}
func playVideos() {
if let currentExtercise = bridgeModule.currentWorkoutInfo.currentExercise {
if let videoURL = VideoURLCreator.videoURL(
@@ -123,7 +114,7 @@ struct ExternalWorkoutDetailView: View {
workout: bridgeModule.currentWorkoutInfo.workout) {
updateMainPlayer(for: videoURL)
}
if let smallVideoURL = VideoURLCreator.videoURL(
thotStyle: .never,
gender: thotGenderOption,
@@ -163,7 +154,7 @@ struct ExternalWorkoutDetailView: View {
//struct ExternalWorkoutDetailView_Previews: PreviewProvider {
// static var bridge = BridgeModule.shared
//
//
// static var previews: some View {
// ExternalWorkoutDetailView().environmentObject({ () -> BridgeModule in
// let envObj = BridgeModule.shared

View File

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

View File

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

View File

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

View File

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

View File

@@ -10,138 +10,138 @@ import AVKit
struct ExerciseListView: View {
@AppStorage(Constants.phoneThotStyle) private var phoneThotStyle: ThotStyle = .never
@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 private var avPlayer = AVPlayer(url: URL(string: BaseURLs.currentBaseURL + "/media/exercise_videos/2_Dumbbell_Lateral_Lunges.mp4") ?? URL(fileURLWithPath: "/dev/null"))
@State private var previewVideoURL: URL?
var workout: Workout
@Binding var showExecersizeInfo: Bool
@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 {
if let videoURL = VideoURLCreator.videoURL(
thotStyle: phoneThotStyle,
gender: thotGenderOption,
defaultVideoURLStr: self.videoExercise?.videoURL,
exerciseName: self.videoExercise?.name,
workout: bridgeModule.currentWorkoutInfo.workout) {
workout: currentWorkout) {
updatePreviewPlayer(for: videoURL)
}
}
}
var body: some View {
let supersets = workout.supersets?.sorted(by: { $0.order < $1.order }) ?? []
if supersets.isEmpty == false {
ScrollViewReader { proxy in
List() {
ForEach(supersets.indices, id: \.self) { supersetIndex in
let superset = supersets[supersetIndex]
ForEach(Array(supersets.enumerated()), id: \.offset) { supersetIndex, superset in
Section(content: {
ForEach(superset.exercises.indices, id: \.self) { exerciseIndex in
let supersetExecercise = superset.exercises[exerciseIndex]
ForEach(Array(superset.exercises.enumerated()), id: \.offset) { exerciseIndex, supersetExecercise in
let rowID = rowIdentifier(
supersetIndex: supersetIndex,
exerciseIndex: exerciseIndex,
exercise: supersetExecercise
)
let isCurrentExercise = isInWorkout &&
supersetIndex == currentSupersetIndex &&
exerciseIndex == currentExerciseIndex
VStack {
Button(action: {
if bridgeModule.isInWorkout {
bridgeModule.currentWorkoutInfo.goToExerciseAt(
supersetIndex: supersetIndex,
exerciseIndex: exerciseIndex)
if isInWorkout {
goToExerciseAt(supersetIndex, exerciseIndex)
} else {
videoExercise = supersetExecercise.exercise
}
}, label: {
HStack {
if bridgeModule.isInWorkout &&
supersetIndex == bridgeModule.currentWorkoutInfo.supersetIndex &&
exerciseIndex == bridgeModule.currentWorkoutInfo.exerciseIndex {
if isCurrentExercise {
Image(systemName: "figure.run")
.foregroundColor(Color("appColor"))
.foregroundStyle(WerkoutTheme.accent)
}
Text(supersetExecercise.exercise.extName)
.foregroundStyle(WerkoutTheme.textPrimary)
Spacer()
if let reps = supersetExecercise.reps,
reps > 0 {
HStack {
HStack(spacing: 4) {
Image(systemName: "number")
.foregroundColor(.white)
.frame(width: 20, alignment: .leading)
Text("\(reps)")
.foregroundColor(.white)
.frame(width: 30, alignment: .trailing)
}
.padding([.top, .bottom], 5)
.padding([.leading], 10)
.padding([.trailing], 15)
.background(.blue)
.cornerRadius(5, corners: [.topLeft, .bottomLeft])
.frame(alignment: .trailing)
.font(WerkoutTheme.caption)
.foregroundStyle(.white)
.padding(.horizontal, WerkoutTheme.sm)
.padding(.vertical, WerkoutTheme.xs)
.background(WerkoutTheme.accent)
.clipShape(Capsule())
}
if let duration = supersetExecercise.duration,
duration > 0 {
HStack {
HStack(spacing: 4) {
Image(systemName: "stopwatch")
.foregroundColor(.white)
.frame(width: 20, alignment: .leading)
Text("\(duration)")
.foregroundColor(.white)
.frame(width: 30, alignment: .trailing)
}
.padding([.top, .bottom], 5)
.padding([.leading], 10)
.padding([.trailing], 15)
.background(.green)
.cornerRadius(5, corners: [.topLeft, .bottomLeft])
.font(WerkoutTheme.caption)
.foregroundStyle(.white)
.padding(.horizontal, WerkoutTheme.sm)
.padding(.vertical, WerkoutTheme.xs)
.background(WerkoutTheme.success)
.clipShape(Capsule())
}
}
.padding(.trailing, -20)
.contentShape(Rectangle())
})
.buttonStyle(.plain)
.accessibilityLabel("Exercise \(supersetExecercise.exercise.extName)")
.accessibilityHint(bridgeModule.isInWorkout ? "Jump to this exercise in the workout" : "Preview exercise video")
if bridgeModule.isInWorkout &&
supersetIndex == bridgeModule.currentWorkoutInfo.supersetIndex &&
exerciseIndex == bridgeModule.currentWorkoutInfo.exerciseIndex &&
showExecersizeInfo {
.accessibilityHint(isInWorkout ? "Jump to this exercise in the workout" : "Preview exercise video")
if isCurrentExercise && showExecersizeInfo {
detailView(forExercise: supersetExecercise)
}
}.id(rowID)
}
.listRowBackground(
isCurrentExercise
? WerkoutTheme.accent.opacity(0.1)
: WerkoutTheme.surfaceCard
)
.id(rowID)
}
}, header: {
HStack {
Text(superset.name ?? "--")
.foregroundColor(Color("appColor"))
.bold()
.font(WerkoutTheme.sectionTitle)
.foregroundStyle(WerkoutTheme.accent)
Spacer()
Text("\(superset.rounds) rounds")
.foregroundColor(Color("appColor"))
.bold()
.font(WerkoutTheme.caption)
.foregroundStyle(WerkoutTheme.accent)
if let estimatedTime = superset.estimatedTime {
Text("@ " + estimatedTime.asString(style: .abbreviated))
.foregroundColor(Color("appColor"))
.bold()
.font(WerkoutTheme.caption)
.foregroundStyle(WerkoutTheme.accent)
}
}
})
}
}
.onChange(of: bridgeModule.currentWorkoutInfo.allSupersetExecerciseIndex, perform: { newValue in
if let newCurrentExercise = bridgeModule.currentWorkoutInfo.currentExercise {
.scrollContentBackground(.hidden)
.background(WerkoutTheme.background)
.onChange(of: allSupersetExecerciseIndex) { _, _ in
if let newCurrentExercise = currentExercise {
withAnimation {
let currentSupersetIndex = bridgeModule.currentWorkoutInfo.supersetIndex
let currentExerciseIndex = bridgeModule.currentWorkoutInfo.exerciseIndex
proxy.scrollTo(
rowIdentifier(
supersetIndex: currentSupersetIndex,
@@ -152,7 +152,7 @@ struct ExerciseListView: View {
)
}
}
})
}
.sheet(item: $videoExercise) { exercise in
PlayerView(player: $avPlayer)
.onAppear{
@@ -190,20 +190,34 @@ struct ExerciseListView: View {
avPlayer.isMuted = true
avPlayer.play()
}
func detailView(forExercise supersetExecercise: SupersetExercise) -> some View {
VStack {
VStack(spacing: WerkoutTheme.sm) {
Text(supersetExecercise.exercise.description)
.frame(alignment: .leading)
Divider()
.font(WerkoutTheme.bodyText)
.foregroundStyle(WerkoutTheme.textSecondary)
.frame(maxWidth: .infinity, alignment: .leading)
WerkoutTheme.divider.frame(height: 0.5)
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 {
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
struct WorkoutDetailView: View {
@StateObject 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"))
@ObservedObject var viewModel: WorkoutDetailViewModel
@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?
@StateObject var bridgeModule = BridgeModule.shared
@ObservedObject var bridgeModule = BridgeModule.shared
@Environment(\.dismiss) var dismiss
@AppStorage(Constants.phoneThotStyle) private var phoneThotStyle: ThotStyle = .never
@AppStorage(Constants.thotGenderOption) private var thotGenderOption: String = "female"
@@ -22,45 +22,50 @@ struct WorkoutDetailView: View {
case completedWorkout([String: Any])
var id: String { return "completedWorkoutSheet" }
}
@State var workoutComplete: Sheet?
@State var workoutToPlan: Workout?
@State var showExecersizeInfo: Bool = false
@State private var workoutComplete: Sheet?
@State private var workoutToPlan: Workout?
@State private var showExecersizeInfo: Bool = false
var body: some View {
ZStack {
WerkoutTheme.background.ignoresSafeArea()
switch viewModel.status {
case .loading:
Text("Loading")
ProgressView()
.tint(WerkoutTheme.accent)
case .failed(let errorMessage):
VStack(spacing: 16) {
VStack(spacing: WerkoutTheme.md) {
Text("Unable to load workout")
.font(.headline)
.font(WerkoutTheme.sectionTitle)
.foregroundStyle(WerkoutTheme.textPrimary)
Text(errorMessage)
.font(.footnote)
.font(WerkoutTheme.bodyText)
.multilineTextAlignment(.center)
.foregroundStyle(.secondary)
.foregroundStyle(WerkoutTheme.textSecondary)
}
.padding()
case .showWorkout(let workout):
VStack(spacing: 0) {
if bridgeModule.isInWorkout {
HStack {
CountdownView()
CountdownView(
currentExerciseDuration: bridgeModule.currentWorkoutInfo.currentExercise?.duration,
currentExerciseTimeLeft: bridgeModule.currentExerciseTimeLeft
)
}
.padding()
.frame(maxWidth: .infinity)
if phoneThotStyle != .off {
GeometryReader { metrics in
ZStack {
PlayerView(player: $avPlayer)
.frame(width: metrics.size.width * 1, height: metrics.size.height * 1)
.onAppear{
avPlayer.isMuted = true
avPlayer.play()
}
PlayerView(player: $avPlayer)
.frame(height: 220)
.onAppear{
avPlayer.isMuted = true
avPlayer.play()
}
.overlay(alignment: .bottomTrailing) {
Button(action: {
if let assetURL = ((avPlayer.currentItem?.asset) as? AVURLAsset)?.url,
let currentExtercise = bridgeModule.currentWorkoutInfo.currentExercise,
@@ -72,73 +77,86 @@ struct WorkoutDetailView: View {
workout: bridgeModule.currentWorkoutInfo.workout) {
updatePlayer(for: otherVideoURL)
}
}, label: {
}) {
Image(systemName: "arrow.triangle.2.circlepath.camera.fill")
.frame(width: 44, height: 44)
.foregroundColor(Color("appColor"))
})
.foregroundColor(.blue)
.cornerRadius(Constants.buttonRadius)
.frame(width: 160, height: 120)
.position(x: metrics.size.width - 22, y: metrics.size.height - 30)
.font(.title2)
.padding(WerkoutTheme.sm)
}
.glassEffect(.regular.interactive())
.tint(WerkoutTheme.accent)
.padding(WerkoutTheme.sm)
.accessibilityLabel("Switch video style")
.accessibilityHint("Toggles between alternate and default exercise videos")
}
.overlay(alignment: .bottomLeading) {
Button(action: {
showExecersizeInfo.toggle()
}, label: {
}) {
Image(systemName: "info.circle.fill")
.frame(width: 44, height: 44)
.foregroundColor(Color("appColor"))
})
.foregroundColor(.blue)
.cornerRadius(Constants.buttonRadius)
.frame(width: 120, height: 120)
.position(x: 22, y: metrics.size.height - 30)
.font(.title2)
.padding(WerkoutTheme.sm)
}
.glassEffect(.regular.interactive())
.tint(WerkoutTheme.accent)
.padding(WerkoutTheme.sm)
.accessibilityLabel(showExecersizeInfo ? "Hide exercise info" : "Show exercise info")
.accessibilityHint("Shows exercise description and target muscles")
}
}
.padding([.top, .bottom])
.background(Color(uiColor: .tertiarySystemBackground))
.padding([.top, .bottom])
.background(WerkoutTheme.background)
}
}
if !bridgeModule.isInWorkout {
InfoView(workout: workout)
.padding(.bottom)
}
if bridgeModule.isInWorkout {
Divider()
.background(Color(uiColor: .secondaryLabel))
WerkoutTheme.divider.frame(height: 0.5)
HStack {
Text("\(bridgeModule.currentWorkoutInfo.currentRound) of \(bridgeModule.currentWorkoutInfo.numberOfRoundsInCurrentSuperSet)")
.font(.title3)
.bold()
.font(.system(size: 17, weight: .bold, design: .monospaced))
.foregroundStyle(WerkoutTheme.accent)
.frame(maxWidth: .infinity, alignment: .leading)
.padding(.leading, 10)
CurrentWorkoutElapsedTimeView()
CurrentWorkoutElapsedTimeView(
currentWorkoutRunTimeInSeconds: bridgeModule.currentWorkoutRunTimeInSeconds
)
.frame(maxWidth: .infinity, alignment: .center)
Text(progressText)
.font(.title3)
.bold()
.font(.system(size: 17, weight: .bold, design: .monospaced))
.foregroundStyle(WerkoutTheme.textPrimary)
.frame(maxWidth: .infinity, alignment: .trailing)
.padding(.trailing, 10)
}
.padding([.top, .bottom])
.background(Color(uiColor: .tertiarySystemBackground))
.background(WerkoutTheme.surfaceCard)
}
Divider()
.background(Color(uiColor: .secondaryLabel))
ExerciseListView(workout: workout, showExecersizeInfo: $showExecersizeInfo)
WerkoutTheme.divider.frame(height: 0.5)
ExerciseListView(
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)
.background(Color(uiColor: .systemGroupedBackground))
.background(WerkoutTheme.background)
ActionsView(completedWorkout: {
bridgeModule.completeWorkout()
}, planWorkout: { workout in
@@ -146,8 +164,8 @@ struct WorkoutDetailView: View {
}, workout: workout, showAddToCalendar: viewModel.isPreview, startWorkoutAction: {
startWorkout(workout: workout)
})
.frame(height: 44)
.frame(height: 56)
}
.sheet(item: $workoutComplete) { item in
switch item {
@@ -169,15 +187,16 @@ struct WorkoutDetailView: View {
}
}
}
.onChange(of: bridgeModule.currentWorkoutInfo.allSupersetExecerciseIndex, perform: { _ in
.onChange(of: bridgeModule.currentWorkoutInfo.allSupersetExecerciseIndex) { _, _ in
playVideos()
})
.onChange(of: bridgeModule.isInWorkout, perform: { _ in
}
.onChange(of: bridgeModule.isInWorkout) { _, _ in
playVideos()
})
}
.onAppear{
viewModel.load()
playVideos()
bridgeModule.completedWorkout = {
if let workoutData = createWorkoutData() {
workoutComplete = .completedWorkout(workoutData)
@@ -194,7 +213,7 @@ struct WorkoutDetailView: View {
bridgeModule.completedWorkout = nil
}
}
func playVideos() {
if let currentExtercise = bridgeModule.currentWorkoutInfo.currentExercise {
if let videoURL = VideoURLCreator.videoURL(
@@ -221,7 +240,7 @@ struct WorkoutDetailView: View {
avPlayer.isMuted = true
avPlayer.play()
}
func startWorkout(workout: Workout) {
bridgeModule.start(workout: workout)
}
@@ -235,7 +254,7 @@ struct WorkoutDetailView: View {
let current = min(totalExercises, max(1, bridgeModule.currentWorkoutInfo.allSupersetExecerciseIndex + 1))
return "\(current)/\(totalExercises)"
}
func createWorkoutData() -> [String:Any]? {
guard let workoutid = bridgeModule.currentWorkoutInfo.workout?.id,
let startTime = bridgeModule.workoutStartDate?.timeFormatForUpload,
@@ -249,7 +268,7 @@ struct WorkoutDetailView: View {
"workout": workoutid,
"total_time": bridgeModule.currentWorkoutRunTimeInSeconds
] as [String : Any]
return postBody
}
}

View File

@@ -17,26 +17,32 @@ class WorkoutDetailViewModel: ObservableObject {
@Published var status: WorkoutDetailViewModelStatus
let isPreview: Bool
let workout: Workout
init(workout: Workout, status: WorkoutDetailViewModelStatus? = nil, isPreview: Bool) {
self.status = .loading
self.workout = workout
self.isPreview = isPreview
if let passedStatus = status {
self.status = passedStatus
} else {
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)")
}
}
})
self.status = .loading
}
}
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 hard
case death
var stringValue: String {
switch self {
case .easy:
return "Easy"
case .moderate:
@@ -30,43 +30,81 @@ struct WorkoutHistoryView: View {
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]
@State private var selectedPlannedWorkout: Workout?
private var sortedWorkouts: [CompletedWorkout] {
completedWorkouts.sorted(by: { $0.createdAt > $1.createdAt })
}
var body: some View {
List {
ForEach(completedWorkouts.sorted(by: { $0.createdAt > $1.createdAt }), id:\.self.id) { completedWorkout in
ForEach(sortedWorkouts, id: \.id) { completedWorkout in
HStack {
VStack {
if let date = completedWorkout.workoutStartTime.dateFromServerDate {
Text(date.monthString)
.font(WerkoutTheme.caption)
.foregroundStyle(WerkoutTheme.textSecondary)
Text("\(date.get(.day))")
.font(WerkoutTheme.stat.monospacedDigit())
.foregroundStyle(WerkoutTheme.accent)
Text("\(date.get(.hour))")
.font(WerkoutTheme.caption)
.foregroundStyle(WerkoutTheme.textMuted)
}
}
.frame(minWidth: 60)
VStack(alignment: .leading) {
Text(completedWorkout.workout.name)
.font(.title3)
.font(WerkoutTheme.cardTitle)
.foregroundStyle(WerkoutTheme.textPrimary)
if let desc = completedWorkout.workout.description {
Text(desc)
.font(.footnote)
.font(WerkoutTheme.caption)
.foregroundStyle(WerkoutTheme.textSecondary)
}
Divider()
.overlay(WerkoutTheme.divider)
if let difficulty = completedWorkout.difficulty,
let string = DifficltyString.init(rawValue: difficulty)?.stringValue {
Text(string)
let difficultyEnum = DifficltyString(rawValue: difficulty) {
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 {
Text(notes)
.font(WerkoutTheme.bodyText)
.foregroundStyle(WerkoutTheme.textSecondary)
}
}
.padding(.leading)
@@ -74,10 +112,14 @@ struct WorkoutHistoryView: View {
.onTapGesture {
selectedPlannedWorkout = completedWorkout.workout
}
}
.listRowBackground(WerkoutTheme.surfaceCard)
}
}
.listStyle(.plain)
.background(WerkoutTheme.background)
.scrollContentBackground(.hidden)
.sheet(item: $selectedPlannedWorkout) { item in
let viewModel = WorkoutDetailViewModel(workout: item, isPreview: true)
WorkoutDetailView(viewModel: viewModel)