Workouts 2.0: re-base persistence on iCloud Drive documents

Replace Core Data + NSPersistentCloudKitContainer + App-Group store +
WatchConnectivity dictionary sync with the QuickRabbit iCloud-documents
architecture:

- iCloud Drive JSON documents are the sole source of truth (one file per
  aggregate: Splits/<ULID>.json, Workouts/YYYY/MM/<ULID>.json), with a
  rebuildable SwiftData cache populated only by an NSMetadataQuery observer
  and a connect-time reconcile. Soft-delete tombstones; hard iCloud gate.
- Shared model layer (ULID, Codable *Documents + stateless mappers, @Model
  cache entities, SwiftData container) compiled into both targets.
- New iPhone<->Watch bridge over WatchConnectivity keyed by ULIDs; the phone
  is the sole writer of iCloud Drive, the watch round-trips documents.
- AppServices DI + iCloud-required root gate; Swift 6 strict concurrency.
- Starter splits generated on demand from the bundled YAML catalogs.
- Migrate to XcodeGen (project.yml), iOS 26 / watchOS 26; CloudDocuments
  entitlement (drop CloudKit/App Group/aps-environment).
- Duration stored as Int seconds (was a Date epoch hack); fix workout
  end-on-create, undismissable delete dialog, toolbar-hiding nav stacks,
  and the Settings placeholder.
- Add README/CHANGELOG/LICENSE, .gitignore, refreshed REQUIREMENTS, and the
  Scripts/ TestFlight pipeline (release.sh + ASC API scripts).

MARKETING_VERSION 2.0.
This commit is contained in:
2026-06-19 14:25:27 -04:00
parent 9a881e841b
commit 85d0eaddbb
86 changed files with 3873 additions and 3755 deletions
+118 -62
View File
@@ -8,15 +8,20 @@
//
import SwiftUI
import CoreData
import SwiftData
import Charts
struct ExerciseView: View {
@Environment(\.managedObjectContext) private var viewContext
@Environment(SyncEngine.self) private var sync
@Environment(\.dismiss) private var dismiss
@ObservedObject var workoutLog: WorkoutLog
let workout: Workout
let logID: String
/// Working copy of the parent workout. Editing a log = editing this doc and
/// re-saving the whole aggregate. Driving the UI from local state (not the
/// cache entity) keeps rapid set taps from racing the filecache update.
@State private var doc: WorkoutDocument
@State private var progress: Int = 0
@State private var showingPlanEdit = false
@State private var showingNotesEdit = false
@@ -24,12 +29,49 @@ struct ExerciseView: View {
let notStartedColor = Color.white
let completedColor = Color.green
/// `seedDoc` lets the caller hand over an in-memory document (e.g. the parent's
/// working copy right after adding an exercise) so the screen doesn't wait on
/// the filecache round-trip to find the just-created log.
init(workout: Workout, logID: String, seedDoc: WorkoutDocument? = nil) {
self.workout = workout
self.logID = logID
_doc = State(initialValue: seedDoc ?? WorkoutDocument(from: workout))
}
/// The log being edited within the working doc.
private var log: WorkoutLogDocument? {
doc.logs.first { $0.id == logID }
}
var body: some View {
Group {
if let log {
content(for: log)
} else {
// The just-added log hasn't reached the cache yet; refresh shortly.
ProgressView()
}
}
.navigationTitle(log?.exerciseName ?? "")
.sheet(isPresented: $showingPlanEdit) {
PlanEditView(workout: workout, logID: logID)
}
.sheet(isPresented: $showingNotesEdit) {
NotesEditView(workout: workout, logID: logID)
}
.onAppear {
refreshDocIfNeeded()
progress = log?.currentStateIndex ?? 0
}
}
@ViewBuilder
private func content(for log: WorkoutLogDocument) -> some View {
Form {
// MARK: - Progress Section
Section(header: Text("Progress")) {
LazyVGrid(columns: Array(repeating: GridItem(.flexible()), count: Int(workoutLog.sets)), spacing: 4) {
ForEach(1...max(1, Int(workoutLog.sets)), id: \.self) { index in
LazyVGrid(columns: Array(repeating: GridItem(.flexible()), count: max(1, log.sets)), spacing: 4) {
ForEach(1...max(1, log.sets), id: \.self) { index in
ZStack {
let completed = index <= progress
let color = completed ? completedColor : notStartedColor
@@ -50,21 +92,17 @@ struct ExerciseView: View {
.colorInvert()
}
.onTapGesture {
let totalSets = Int(workoutLog.sets)
let totalSets = log.sets
let isLastTile = index == totalSets
let wasAlreadyAtThisProgress = progress == index
withAnimation(.easeInOut(duration: 0.2)) {
if wasAlreadyAtThisProgress {
progress = 0
} else {
progress = index
}
progress = wasAlreadyAtThisProgress ? 0 : index
}
updateLogStatus()
// If tapping the last tile to complete, go back to list
// Tapping the final tile to complete returns to the list.
if isLastTile && !wasAlreadyAtThisProgress {
dismiss()
}
@@ -75,7 +113,7 @@ struct ExerciseView: View {
// MARK: - Plan Section (Read-only with Edit button)
Section {
PlanTilesView(workoutLog: workoutLog)
PlanTilesView(log: log)
} header: {
HStack {
Text("Plan")
@@ -90,7 +128,7 @@ struct ExerciseView: View {
// MARK: - Notes Section (Read-only with Edit button)
Section {
if let notes = workoutLog.notes, !notes.isEmpty {
if let notes = log.notes, !notes.isEmpty {
Text(notes)
.foregroundColor(.primary)
} else {
@@ -112,93 +150,111 @@ struct ExerciseView: View {
// MARK: - Progress Tracking Chart
Section(header: Text("Progress Tracking")) {
WeightProgressionChartView(exerciseName: workoutLog.exerciseName)
WeightProgressionChartView(exerciseName: log.exerciseName)
}
}
.navigationTitle(workoutLog.exerciseName)
.sheet(isPresented: $showingPlanEdit) {
PlanEditView(workoutLog: workoutLog)
// Pull plan/notes edits made in the sheets back into the live doc.
.onChange(of: showingPlanEdit) { _, presenting in
if !presenting { refreshDocFromCache() }
}
.sheet(isPresented: $showingNotesEdit) {
NotesEditView(workoutLog: workoutLog)
}
.onAppear {
progress = Int(workoutLog.currentStateIndex)
}
.onChange(of: workoutLog.currentStateIndex) { _, newValue in
// Update local state when CoreData changes (e.g., from Watch sync)
if progress != Int(newValue) {
withAnimation(.easeInOut(duration: 0.2)) {
progress = Int(newValue)
}
}
.onChange(of: showingNotesEdit) { _, presenting in
if !presenting { refreshDocFromCache() }
}
}
// MARK: - Mutations
private func updateLogStatus() {
workoutLog.currentStateIndex = Int32(progress)
if progress >= Int(workoutLog.sets) {
workoutLog.status = .completed
workoutLog.completed = true
guard let i = doc.logs.firstIndex(where: { $0.id == logID }) else { return }
doc.logs[i].currentStateIndex = progress
if progress >= doc.logs[i].sets {
doc.logs[i].status = WorkoutStatus.completed.rawValue
doc.logs[i].completed = true
} else if progress > 0 {
workoutLog.status = .inProgress
workoutLog.completed = false
doc.logs[i].status = WorkoutStatus.inProgress.rawValue
doc.logs[i].completed = false
} else {
workoutLog.status = .notStarted
workoutLog.completed = false
doc.logs[i].status = WorkoutStatus.notStarted.rawValue
doc.logs[i].completed = false
}
updateWorkoutStatus()
saveChanges()
recomputeWorkoutStatus()
doc.updatedAt = Date()
let snapshot = doc
Task { await sync.save(workout: snapshot) }
}
private func updateWorkoutStatus() {
guard let workout = workoutLog.workout else { return }
let logs = workout.logsArray
let allCompleted = logs.allSatisfy { $0.status == .completed }
let anyInProgress = logs.contains { $0.status == .inProgress }
let allNotStarted = logs.allSatisfy { $0.status == .notStarted }
/// Recompute the workout's status/end from its logs.
private func recomputeWorkoutStatus() {
let statuses = doc.logs.map { WorkoutStatus(rawValue: $0.status) ?? .notStarted }
let allCompleted = !statuses.isEmpty && statuses.allSatisfy { $0 == .completed }
let anyInProgress = statuses.contains { $0 == .inProgress }
let allNotStarted = statuses.allSatisfy { $0 == .notStarted }
if allCompleted {
workout.status = .completed
workout.end = Date()
doc.status = WorkoutStatus.completed.rawValue
doc.end = Date()
} else if anyInProgress || !allNotStarted {
workout.status = .inProgress
doc.status = WorkoutStatus.inProgress.rawValue
doc.end = nil
} else {
workout.status = .notStarted
doc.status = WorkoutStatus.notStarted.rawValue
doc.end = nil
}
}
private func saveChanges() {
try? viewContext.save()
WatchConnectivityManager.shared.syncAllData()
/// If the requested log isn't in the working doc yet (just-added race), pull a
/// fresh copy from the cache entity once it catches up.
private func refreshDocIfNeeded() {
guard log == nil else { return }
refreshDocFromCache()
}
/// Re-read the workout from the cache to absorb edits made by child sheets
/// (plan/notes) without clobbering progress edits made here.
private func refreshDocFromCache() {
let fresh = WorkoutDocument(from: workout)
// Preserve the locally edited progress for the open log if the cache lags.
if let i = fresh.logs.firstIndex(where: { $0.id == logID }),
let mine = doc.logs.first(where: { $0.id == logID }),
fresh.logs[i].currentStateIndex != mine.currentStateIndex {
doc = fresh
doc.logs[i].currentStateIndex = mine.currentStateIndex
} else {
doc = fresh
}
if let current = log {
progress = current.currentStateIndex
}
}
}
// MARK: - Plan Tiles View
struct PlanTilesView: View {
@ObservedObject var workoutLog: WorkoutLog
let log: WorkoutLogDocument
var body: some View {
if workoutLog.loadTypeEnum == .duration {
if LoadType(rawValue: log.loadType) == .duration {
// Duration layout: Sets | Duration
HStack(spacing: 0) {
PlanTile(label: "Sets", value: "\(workoutLog.sets)")
PlanTile(label: "Sets", value: "\(log.sets)")
PlanTile(label: "Duration", value: formattedDuration)
}
} else {
// Weight layout: Sets | Reps | Weight
HStack(spacing: 0) {
PlanTile(label: "Sets", value: "\(workoutLog.sets)")
PlanTile(label: "Reps", value: "\(workoutLog.reps)")
PlanTile(label: "Weight", value: "\(workoutLog.weight) lbs")
PlanTile(label: "Sets", value: "\(log.sets)")
PlanTile(label: "Reps", value: "\(log.reps)")
PlanTile(label: "Weight", value: "\(log.weight) lbs")
}
}
}
private var formattedDuration: String {
let mins = workoutLog.durationMinutes
let secs = workoutLog.durationSeconds
let mins = log.durationSeconds / 60
let secs = log.durationSeconds % 60
if mins > 0 && secs > 0 {
return "\(mins)m \(secs)s"
} else if mins > 0 {