add minimal workout interface, not linked with exercises yet
This commit is contained in:
@@ -0,0 +1,98 @@
|
||||
//
|
||||
// WorkoutLibraryView.swift
|
||||
// WorkoutsPlus
|
||||
//
|
||||
// Created by Felix Förtsch on 10.08.24.
|
||||
//
|
||||
|
||||
import SwiftUI
|
||||
import SwiftData
|
||||
|
||||
struct WorkoutLibraryView: View {
|
||||
@Environment(\.modelContext) private var modelContext
|
||||
@Query private var workouts: [Workout]
|
||||
|
||||
@State private var isPresentingNewItemSheet = false
|
||||
|
||||
let initialDataSet = [
|
||||
"RR",
|
||||
"Minimalist"
|
||||
]
|
||||
|
||||
var body: some View {
|
||||
NavigationView {
|
||||
List {
|
||||
ForEach(workouts.sorted(by: { $0.name < $1.name })) { workout in
|
||||
NavigationLink(destination: WorkoutDetailsView(workout: workout)) {
|
||||
Text(workout.name)
|
||||
}
|
||||
}
|
||||
.onDelete(perform: deleteWorkout)
|
||||
}
|
||||
.onAppear {
|
||||
if workouts.isEmpty {
|
||||
// TODO: This behaviour puts something into [workouts] whenever(!) it is empty. It's not bound to the first ever start of the app or anything. Check if that's the behaviour we want.
|
||||
loadInitialData(workouts: initialDataSet)
|
||||
}
|
||||
}
|
||||
.toolbar {
|
||||
ToolbarItem(placement: .navigationBarTrailing) {
|
||||
Button {
|
||||
createNewWorkout()
|
||||
} label: {
|
||||
Label("Add Workout", systemImage: "plus")
|
||||
}
|
||||
}
|
||||
}
|
||||
.sheet(isPresented: $isPresentingNewItemSheet) {
|
||||
let newWorkout = Workout(name: "")
|
||||
NavigationView {
|
||||
WorkoutDetailsView(workout: newWorkout, isPresentedAsSheet: true)
|
||||
.onDisappear {
|
||||
if !newWorkout.name.isEmpty {
|
||||
saveWorkout(workout: newWorkout)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func createNewWorkout() {
|
||||
isPresentingNewItemSheet = true
|
||||
}
|
||||
|
||||
private func saveWorkout(workout: Workout) {
|
||||
modelContext.insert(workout)
|
||||
try? modelContext.save()
|
||||
}
|
||||
|
||||
private func deleteWorkout(offsets: IndexSet) {
|
||||
withAnimation {
|
||||
for index in offsets {
|
||||
modelContext.delete(workouts[index])
|
||||
}
|
||||
try? modelContext.save()
|
||||
}
|
||||
}
|
||||
|
||||
private func loadInitialData(workouts: [String]) {
|
||||
var items: [Workout] = []
|
||||
|
||||
for exercise in workouts {
|
||||
let item = Workout(name: exercise)
|
||||
items.append(item)
|
||||
}
|
||||
|
||||
for item in items {
|
||||
modelContext.insert(item)
|
||||
}
|
||||
|
||||
try? modelContext.save()
|
||||
}
|
||||
}
|
||||
|
||||
#Preview {
|
||||
WorkoutLibraryView()
|
||||
.modelContainer(for: Workout.self, inMemory: true)
|
||||
}
|
||||
Reference in New Issue
Block a user