add new exercise creation behavior to workouts
This commit is contained in:
@@ -12,52 +12,68 @@ struct WorkoutLibrary: View {
|
||||
@Environment(\.modelContext) private var modelContext
|
||||
@Query(sort: \Workout.name) private var workouts: [Workout]
|
||||
|
||||
@State private var newWorkout: Workout?
|
||||
|
||||
@State private var newWorkout: Workout = Workout(name: "")
|
||||
@State private var newWorkoutName: String = ""
|
||||
@State private var isAddingWorkout: Bool = false
|
||||
@FocusState private var isInputFieldFocused: Bool
|
||||
|
||||
@State private var searchText: String = ""
|
||||
var filteredItems: [Workout] {
|
||||
if searchText.isEmpty {
|
||||
return workouts
|
||||
} else {
|
||||
return workouts.filter { $0.name.localizedCaseInsensitiveContains(searchText) }
|
||||
}
|
||||
}
|
||||
|
||||
var body: some View {
|
||||
NavigationView {
|
||||
Group {
|
||||
if !workouts.isEmpty {
|
||||
List {
|
||||
ForEach(workouts) { workout in
|
||||
NavigationLink {
|
||||
WorkoutDetail(workout: workout)
|
||||
} label: {
|
||||
Text(workout.name)
|
||||
}
|
||||
}
|
||||
.onDelete(perform: deleteWorkout)
|
||||
Button(action: addWorkout) {
|
||||
Label("Add Workout", systemImage: "plus")
|
||||
List {
|
||||
ForEach(filteredItems) { workout in
|
||||
NavigationLink {
|
||||
WorkoutDetail(workout: workout)
|
||||
} label: {
|
||||
Text(workout.name)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
ContentUnavailableView {
|
||||
Label("No Workouts", systemImage: "figure.run.square.stack")
|
||||
.onDelete(perform: deleteWorkout)
|
||||
if isAddingWorkout {
|
||||
TextField("New Workout", text: $newWorkoutName, onCommit: {
|
||||
newWorkout.name = newWorkoutName
|
||||
saveWorkout(workout: newWorkout)
|
||||
isAddingWorkout = false
|
||||
})
|
||||
.textInputAutocapitalization(.words)
|
||||
.focused($isInputFieldFocused)
|
||||
}
|
||||
Button(action: {
|
||||
addWorkout()
|
||||
}) {
|
||||
HStack {
|
||||
Image(systemName: "plus.circle.fill")
|
||||
.foregroundStyle(.green)
|
||||
Text("Add Workout")
|
||||
}
|
||||
}
|
||||
}
|
||||
.searchable(text: $searchText)
|
||||
}
|
||||
.navigationBarTitle("Workouts")
|
||||
.toolbar {
|
||||
ToolbarItem() {
|
||||
EditButton()
|
||||
}
|
||||
}
|
||||
.sheet(item: $newWorkout) { workout in
|
||||
NavigationStack {
|
||||
AddWorkout(workout: workout)
|
||||
}
|
||||
.presentationDetents([.medium])
|
||||
.interactiveDismissDisabled()
|
||||
}
|
||||
.navigationBarTitle("Workouts")
|
||||
.toolbar {
|
||||
ToolbarItem() {
|
||||
EditButton()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func addWorkout() {
|
||||
withAnimation {
|
||||
let item = Workout(name: "")
|
||||
modelContext.insert(item)
|
||||
newWorkout = item
|
||||
newWorkout = Workout(name: "")
|
||||
newWorkoutName = ""
|
||||
isAddingWorkout = true
|
||||
isInputFieldFocused = true
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user