105 lines
2.3 KiB
Swift
105 lines
2.3 KiB
Swift
//
|
|
// ContentView.swift
|
|
// WorkoutsPlus
|
|
//
|
|
// Created by Felix Förtsch on 10.08.24.
|
|
//
|
|
|
|
import SwiftUI
|
|
import SwiftData
|
|
|
|
struct ContentView: View {
|
|
@Environment(\.modelContext) private var modelContext
|
|
@Query private var exercises: [Exercise]
|
|
|
|
@State private var isAddingNewExercise = false
|
|
@State private var selectedExercise: Exercise?
|
|
|
|
let initialDataSet = [
|
|
"Pull-up",
|
|
"Push-up",
|
|
"Dips",
|
|
"Rows",
|
|
"Split Squat"
|
|
]
|
|
|
|
var body: some View {
|
|
NavigationSplitView {
|
|
List {
|
|
ForEach(exercises) { exercise in
|
|
NavigationLink {
|
|
Text(exercise.name)
|
|
} label: {
|
|
Text(exercise.name)
|
|
}
|
|
}
|
|
.onDelete(perform: deleteExercises)
|
|
}
|
|
.onAppear {
|
|
if exercises.isEmpty {
|
|
loadInitialData(exercises: initialDataSet)
|
|
}
|
|
}
|
|
.toolbar {
|
|
ToolbarItem(placement: .navigationBarTrailing) {
|
|
Button {
|
|
addExercise()
|
|
} label: {
|
|
Label("Add Exercise", systemImage: "plus")
|
|
}
|
|
}
|
|
}
|
|
.sheet(isPresented: $isAddingNewExercise) {
|
|
ExerciseDetailsView(exercise: $selectedExercise, isEditing: false)
|
|
.onDisappear {
|
|
if let selectedExercise = selectedExercise, !selectedExercise.name.isEmpty {
|
|
saveNewExercise()
|
|
}
|
|
}
|
|
}
|
|
} detail: {
|
|
Text("Select an exercise")
|
|
}
|
|
}
|
|
|
|
private func addExercise() {
|
|
selectedExercise = Exercise(name: "")
|
|
isAddingNewExercise = true
|
|
}
|
|
|
|
private func saveNewExercise() {
|
|
guard let newExercise = selectedExercise else { return }
|
|
modelContext.insert(newExercise)
|
|
try? modelContext.save()
|
|
}
|
|
|
|
private func deleteExercises(offsets: IndexSet) {
|
|
withAnimation {
|
|
for index in offsets {
|
|
modelContext.delete(exercises[index])
|
|
}
|
|
try? modelContext.save()
|
|
}
|
|
}
|
|
|
|
private func loadInitialData(exercises: [String]) {
|
|
var items: [Exercise] = []
|
|
|
|
for exercise in exercises {
|
|
let item = Exercise(name: exercise)
|
|
items.append(item)
|
|
}
|
|
|
|
for item in items {
|
|
modelContext.insert(item)
|
|
}
|
|
|
|
try? modelContext.save()
|
|
}
|
|
}
|
|
|
|
#Preview {
|
|
ContentView()
|
|
.modelContainer(for: Exercise.self, inMemory: true)
|
|
}
|