@capgo/capacitor-widget-kit 8.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/CapgoCapacitorWidgetKit.podspec +17 -0
  2. package/LICENSE +373 -0
  3. package/Package.swift +28 -0
  4. package/README.md +1119 -0
  5. package/android/build.gradle +59 -0
  6. package/android/src/main/AndroidManifest.xml +8 -0
  7. package/android/src/main/java/app/capgo/widgetkit/CapgoNativeWidgetBridge.java +311 -0
  8. package/android/src/main/java/app/capgo/widgetkit/CapgoTemplateActionReceiver.java +36 -0
  9. package/android/src/main/java/app/capgo/widgetkit/CapgoTemplateSvgBitmapRenderer.java +25 -0
  10. package/android/src/main/java/app/capgo/widgetkit/CapgoTemplateWidgetBridge.java +31 -0
  11. package/android/src/main/java/app/capgo/widgetkit/CapgoWidgetKit.java +218 -0
  12. package/android/src/main/java/app/capgo/widgetkit/CapgoWidgetKitConstants.java +18 -0
  13. package/android/src/main/java/app/capgo/widgetkit/CapgoWidgetKitPlugin.java +370 -0
  14. package/android/src/main/java/app/capgo/widgetkit/TemplateActivityStore.java +167 -0
  15. package/android/src/main/java/app/capgo/widgetkit/TemplateJsonUtils.java +369 -0
  16. package/android/src/main/java/app/capgo/widgetkit/TemplateRuntime.java +676 -0
  17. package/android/src/main/res/.gitkeep +0 -0
  18. package/dist/docs.json +2223 -0
  19. package/dist/esm/definitions.d.ts +1117 -0
  20. package/dist/esm/definitions.js +2 -0
  21. package/dist/esm/definitions.js.map +1 -0
  22. package/dist/esm/helpers/workout.d.ts +32 -0
  23. package/dist/esm/helpers/workout.js +129 -0
  24. package/dist/esm/helpers/workout.js.map +1 -0
  25. package/dist/esm/index.d.ts +6 -0
  26. package/dist/esm/index.js +9 -0
  27. package/dist/esm/index.js.map +1 -0
  28. package/dist/esm/runtime.d.ts +25 -0
  29. package/dist/esm/runtime.js +653 -0
  30. package/dist/esm/runtime.js.map +1 -0
  31. package/dist/esm/web.d.ts +23 -0
  32. package/dist/esm/web.js +292 -0
  33. package/dist/esm/web.js.map +1 -0
  34. package/dist/plugin.cjs.js +1096 -0
  35. package/dist/plugin.cjs.js.map +1 -0
  36. package/dist/plugin.js +1099 -0
  37. package/dist/plugin.js.map +1 -0
  38. package/ios/Sources/CapgoWidgetKitPlugin/CapgoNativeWidgetBridge.swift +372 -0
  39. package/ios/Sources/CapgoWidgetKitPlugin/CapgoTemplateWidgetBridge.swift +199 -0
  40. package/ios/Sources/CapgoWidgetKitPlugin/CapgoWidgetKit.swift +218 -0
  41. package/ios/Sources/CapgoWidgetKitPlugin/CapgoWidgetKitPlugin.swift +322 -0
  42. package/ios/Sources/CapgoWidgetKitPlugin/CapgoWidgetKitSharedStore.swift +47 -0
  43. package/ios/Sources/CapgoWidgetKitPlugin/CapgoWorkoutLiveActivityComponents.swift +246 -0
  44. package/ios/Sources/CapgoWidgetKitPlugin/CapgoWorkoutLiveActivityWidget.swift +257 -0
  45. package/ios/Sources/CapgoWidgetKitPlugin/CompleteSetIntent.swift +24 -0
  46. package/ios/Sources/CapgoWidgetKitPlugin/TemplateActionIntent.swift +56 -0
  47. package/ios/Sources/CapgoWidgetKitPlugin/TemplateActivityStore.swift +239 -0
  48. package/ios/Sources/CapgoWidgetKitPlugin/TemplateLiveActivityManager.swift +251 -0
  49. package/ios/Sources/CapgoWidgetKitPlugin/TemplateRuntime.swift +1067 -0
  50. package/ios/Sources/CapgoWidgetKitPlugin/WorkoutActivityStore.swift +111 -0
  51. package/ios/Sources/CapgoWidgetKitPlugin/WorkoutLiveActivityManager.swift +263 -0
  52. package/ios/Sources/CapgoWidgetKitPlugin/WorkoutSession.swift +271 -0
  53. package/ios/Tests/CapgoWidgetKitPluginTests/CapgoWidgetKitPluginTests.swift +130 -0
  54. package/package.json +93 -0
@@ -0,0 +1,111 @@
1
+ import Foundation
2
+
3
+ public struct StoredWorkoutEnvelope: Codable, Hashable, Sendable {
4
+ public var session: WorkoutSession
5
+ public var revision: Int
6
+ public var activityId: String?
7
+ public var updatedAtMs: Int64
8
+
9
+ public init(session: WorkoutSession, revision: Int, activityId: String?, updatedAtMs: Int64) {
10
+ self.session = session
11
+ self.revision = revision
12
+ self.activityId = activityId
13
+ self.updatedAtMs = updatedAtMs
14
+ }
15
+ }
16
+
17
+ enum WorkoutActivityStoreError: LocalizedError {
18
+ case missingAppGroup
19
+ case invalidSuite(String)
20
+
21
+ var errorDescription: String? {
22
+ switch self {
23
+ case .missingAppGroup:
24
+ return "Missing App Group configuration. Set CapgoWidgetKitAppGroup in the app and widget extension Info.plist files."
25
+ case .invalidSuite(let suiteName):
26
+ return "Unable to open the shared App Group suite: \(suiteName)"
27
+ }
28
+ }
29
+ }
30
+
31
+ public final class WorkoutActivityStore {
32
+ public static let appGroupInfoKey = "CapgoWidgetKitAppGroup"
33
+
34
+ private static let activityMapKey = "capgo.widgetkit.activity-map"
35
+ private let defaults: UserDefaults
36
+ private let encoder = JSONEncoder()
37
+ private let decoder = JSONDecoder()
38
+
39
+ private init(defaults: UserDefaults) {
40
+ self.defaults = defaults
41
+ }
42
+
43
+ public static func make(bundle: Bundle = .main) throws -> WorkoutActivityStore {
44
+ guard let suiteName = resolveAppGroupId(bundle: bundle) else {
45
+ throw WorkoutActivityStoreError.missingAppGroup
46
+ }
47
+ guard let defaults = UserDefaults(suiteName: suiteName) else {
48
+ throw WorkoutActivityStoreError.invalidSuite(suiteName)
49
+ }
50
+ return WorkoutActivityStore(defaults: defaults)
51
+ }
52
+
53
+ public static func resolveAppGroupId(bundle: Bundle = .main) -> String? {
54
+ if let configured = bundle.object(forInfoDictionaryKey: appGroupInfoKey) as? String, !configured.isEmpty {
55
+ return configured
56
+ }
57
+
58
+ guard let bundleId = bundle.bundleIdentifier, !bundleId.isEmpty else {
59
+ return nil
60
+ }
61
+
62
+ let lowercased = bundleId.lowercased()
63
+ if lowercased.contains("widget") || lowercased.contains("extension"),
64
+ bundleId.split(separator: ".").count > 1 {
65
+ return "group.\(bundleId.split(separator: ".").dropLast().joined(separator: ".")).widgetkit"
66
+ }
67
+
68
+ return "group.\(bundleId).widgetkit"
69
+ }
70
+
71
+ public func loadEnvelope(sessionId: String) -> StoredWorkoutEnvelope? {
72
+ guard let data = defaults.data(forKey: sessionKey(sessionId)) else {
73
+ return nil
74
+ }
75
+ return try? decoder.decode(StoredWorkoutEnvelope.self, from: data)
76
+ }
77
+
78
+ public func saveEnvelope(_ envelope: StoredWorkoutEnvelope) throws {
79
+ let data = try encoder.encode(envelope)
80
+ defaults.set(data, forKey: sessionKey(envelope.session.sessionId))
81
+ defaults.synchronize()
82
+ }
83
+
84
+ public func sessionId(forActivityId activityId: String) -> String? {
85
+ activityMap()[activityId]
86
+ }
87
+
88
+ public func setActivityId(_ activityId: String, forSessionId sessionId: String) {
89
+ var mapping = activityMap()
90
+ mapping[activityId] = sessionId
91
+ defaults.set(mapping, forKey: Self.activityMapKey)
92
+ }
93
+
94
+ public func removeActivityId(_ activityId: String) {
95
+ var mapping = activityMap()
96
+ mapping.removeValue(forKey: activityId)
97
+ defaults.set(mapping, forKey: Self.activityMapKey)
98
+ }
99
+
100
+ public func allActivityMappings() -> [String: String] {
101
+ activityMap()
102
+ }
103
+
104
+ private func activityMap() -> [String: String] {
105
+ defaults.dictionary(forKey: Self.activityMapKey) as? [String: String] ?? [:]
106
+ }
107
+
108
+ private func sessionKey(_ sessionId: String) -> String {
109
+ "capgo.widgetkit.session.\(sessionId)"
110
+ }
111
+ }
@@ -0,0 +1,263 @@
1
+ #if canImport(ActivityKit)
2
+ import ActivityKit
3
+ #endif
4
+ import Foundation
5
+ import UserNotifications
6
+
7
+ public struct WorkoutActivityInfo: Hashable, Sendable {
8
+ public let activityId: String
9
+ public let sessionId: String
10
+ public let state: String
11
+ public let updatedAtMs: Int64
12
+ }
13
+
14
+ #if canImport(ActivityKit)
15
+ @available(iOS 16.2, *)
16
+ public struct WorkoutActivityAttributes: ActivityAttributes, Sendable {
17
+ public struct ContentState: Codable, Hashable {
18
+ public var revision: Int
19
+ public var activeExerciseIndex: Int?
20
+ public var activeSetIndex: Int?
21
+ public var timerStartedAtMs: Int64?
22
+ public var timerDurationMs: Int64?
23
+ public var isComplete: Bool
24
+ }
25
+
26
+ public var sessionId: String
27
+ public var title: String
28
+ public var deepLinkUrl: String?
29
+
30
+ public init(sessionId: String, title: String, deepLinkUrl: String?) {
31
+ self.sessionId = sessionId
32
+ self.title = title
33
+ self.deepLinkUrl = deepLinkUrl
34
+ }
35
+ }
36
+ #endif
37
+
38
+ public final class WorkoutLiveActivityManager {
39
+ public static let shared = WorkoutLiveActivityManager()
40
+
41
+ private init() {}
42
+
43
+ public func areActivitiesSupported() -> (Bool, String?) {
44
+ #if canImport(ActivityKit)
45
+ if #available(iOS 16.2, *) {
46
+ let authorizationInfo = ActivityAuthorizationInfo()
47
+ guard authorizationInfo.areActivitiesEnabled else {
48
+ return (false, "Live Activities are disabled in Settings.")
49
+ }
50
+ return (true, nil)
51
+ }
52
+ return (false, "iOS 16.2 or later is required for the native workout live activity.")
53
+ #else
54
+ return (false, "ActivityKit is unavailable in this build configuration.")
55
+ #endif
56
+ }
57
+
58
+ public func start(session: WorkoutSession) async throws -> (activityId: String, sessionId: String) {
59
+ #if canImport(ActivityKit)
60
+ guard #available(iOS 16.2, *) else {
61
+ throw WorkoutActivityStoreError.missingAppGroup
62
+ }
63
+
64
+ let store = try WorkoutActivityStore.make()
65
+ let updatedAtMs = Int64(Date().timeIntervalSince1970 * 1000)
66
+ var envelope = StoredWorkoutEnvelope(
67
+ session: session,
68
+ revision: (store.loadEnvelope(sessionId: session.sessionId)?.revision ?? 0) + 1,
69
+ activityId: nil,
70
+ updatedAtMs: updatedAtMs
71
+ )
72
+ try store.saveEnvelope(envelope)
73
+
74
+ let attributes = WorkoutActivityAttributes(
75
+ sessionId: session.sessionId,
76
+ title: session.title,
77
+ deepLinkUrl: session.deepLinkUrl
78
+ )
79
+ let content = ActivityContent(state: makeContentState(from: envelope), staleDate: nil)
80
+ let activity = try Activity.request(attributes: attributes, content: content, pushType: nil)
81
+
82
+ envelope.activityId = activity.id
83
+ try store.saveEnvelope(envelope)
84
+ store.setActivityId(activity.id, forSessionId: session.sessionId)
85
+ scheduleTimerNotificationIfNeeded(for: session)
86
+
87
+ return (activity.id, session.sessionId)
88
+ #else
89
+ throw WorkoutActivityStoreError.missingAppGroup
90
+ #endif
91
+ }
92
+
93
+ public func update(activityId: String, session: WorkoutSession) async throws {
94
+ #if canImport(ActivityKit)
95
+ guard #available(iOS 16.2, *) else {
96
+ return
97
+ }
98
+
99
+ let store = try WorkoutActivityStore.make()
100
+ let current = store.loadEnvelope(sessionId: session.sessionId)
101
+ let envelope = StoredWorkoutEnvelope(
102
+ session: session,
103
+ revision: (current?.revision ?? 0) + 1,
104
+ activityId: activityId,
105
+ updatedAtMs: Int64(Date().timeIntervalSince1970 * 1000)
106
+ )
107
+ try store.saveEnvelope(envelope)
108
+ store.setActivityId(activityId, forSessionId: session.sessionId)
109
+
110
+ if let activity = activity(with: activityId) {
111
+ await activity.update(ActivityContent(state: makeContentState(from: envelope), staleDate: nil))
112
+ }
113
+
114
+ scheduleTimerNotificationIfNeeded(for: session)
115
+ #endif
116
+ }
117
+
118
+ public func end(activityId: String, finalSession: WorkoutSession?) async throws {
119
+ #if canImport(ActivityKit)
120
+ guard #available(iOS 16.2, *) else {
121
+ return
122
+ }
123
+
124
+ let store = try WorkoutActivityStore.make()
125
+ if let finalSession {
126
+ let current = store.loadEnvelope(sessionId: finalSession.sessionId)
127
+ let envelope = StoredWorkoutEnvelope(
128
+ session: finalSession,
129
+ revision: (current?.revision ?? 0) + 1,
130
+ activityId: nil,
131
+ updatedAtMs: Int64(Date().timeIntervalSince1970 * 1000)
132
+ )
133
+ try store.saveEnvelope(envelope)
134
+ }
135
+
136
+ if let activity = activity(with: activityId), let sessionId = store.sessionId(forActivityId: activityId) {
137
+ let envelope = store.loadEnvelope(sessionId: sessionId)
138
+ if let envelope {
139
+ await activity.end(ActivityContent(state: makeContentState(from: envelope), staleDate: nil), dismissalPolicy: .immediate)
140
+ } else {
141
+ await activity.end(nil, dismissalPolicy: .immediate)
142
+ }
143
+ }
144
+
145
+ store.removeActivityId(activityId)
146
+ #endif
147
+ }
148
+
149
+ @discardableResult
150
+ public func completeSet(sessionId: String, activityId: String?) async throws -> WorkoutSession {
151
+ let store = try WorkoutActivityStore.make()
152
+ guard var envelope = store.loadEnvelope(sessionId: sessionId) else {
153
+ throw NSError(domain: "CapgoWidgetKit", code: 404, userInfo: [NSLocalizedDescriptionKey: "No stored session found for \(sessionId)."])
154
+ }
155
+
156
+ envelope.session.completeActiveSet(at: Int64(Date().timeIntervalSince1970 * 1000))
157
+ envelope.revision += 1
158
+ envelope.updatedAtMs = Int64(Date().timeIntervalSince1970 * 1000)
159
+ try store.saveEnvelope(envelope)
160
+
161
+ let resolvedActivityId = activityId ?? envelope.activityId
162
+ if let resolvedActivityId {
163
+ store.setActivityId(resolvedActivityId, forSessionId: sessionId)
164
+ try await update(activityId: resolvedActivityId, session: envelope.session)
165
+ } else {
166
+ scheduleTimerNotificationIfNeeded(for: envelope.session)
167
+ }
168
+
169
+ return envelope.session
170
+ }
171
+
172
+ public func storedSession(sessionId: String?, activityId: String?) throws -> WorkoutSession? {
173
+ let store = try WorkoutActivityStore.make()
174
+
175
+ if let sessionId {
176
+ return store.loadEnvelope(sessionId: sessionId)?.session
177
+ }
178
+
179
+ if let activityId, let sessionId = store.sessionId(forActivityId: activityId) {
180
+ return store.loadEnvelope(sessionId: sessionId)?.session
181
+ }
182
+
183
+ return nil
184
+ }
185
+
186
+ public func listActivities() throws -> [WorkoutActivityInfo] {
187
+ let store = try WorkoutActivityStore.make()
188
+ let activeIds: Set<String>
189
+ #if canImport(ActivityKit)
190
+ if #available(iOS 16.2, *) {
191
+ activeIds = Set(Activity<WorkoutActivityAttributes>.activities.map(\.id))
192
+ } else {
193
+ activeIds = []
194
+ }
195
+ #else
196
+ activeIds = []
197
+ #endif
198
+
199
+ return store.allActivityMappings().compactMap { activityId, sessionId in
200
+ guard let envelope = store.loadEnvelope(sessionId: sessionId) else {
201
+ return nil
202
+ }
203
+ return WorkoutActivityInfo(
204
+ activityId: activityId,
205
+ sessionId: sessionId,
206
+ state: activeIds.contains(activityId) ? "active" : "ended",
207
+ updatedAtMs: envelope.updatedAtMs
208
+ )
209
+ }
210
+ .sorted { $0.updatedAtMs > $1.updatedAtMs }
211
+ }
212
+
213
+ #if canImport(ActivityKit)
214
+ @available(iOS 16.2, *)
215
+ private func makeContentState(from envelope: StoredWorkoutEnvelope) -> WorkoutActivityAttributes.ContentState {
216
+ let timer = envelope.session.activeTimer()
217
+ return WorkoutActivityAttributes.ContentState(
218
+ revision: envelope.revision,
219
+ activeExerciseIndex: envelope.session.activeExerciseIndex,
220
+ activeSetIndex: envelope.session.activeSetIndex,
221
+ timerStartedAtMs: timer?.startedAtMs,
222
+ timerDurationMs: timer?.durationMs,
223
+ isComplete: envelope.session.isComplete
224
+ )
225
+ }
226
+
227
+ @available(iOS 16.2, *)
228
+ private func activity(with activityId: String) -> Activity<WorkoutActivityAttributes>? {
229
+ Activity<WorkoutActivityAttributes>.activities.first(where: { $0.id == activityId })
230
+ }
231
+ #endif
232
+
233
+ private func scheduleTimerNotificationIfNeeded(for session: WorkoutSession) {
234
+ let notificationId = "capgo.widgetkit.timer.\(session.sessionId)"
235
+ let center = UNUserNotificationCenter.current()
236
+ center.removePendingNotificationRequests(withIdentifiers: [notificationId])
237
+
238
+ guard let notificationSettings = session.timerNotifications, notificationSettings.enabled else {
239
+ return
240
+ }
241
+
242
+ guard let timer = session.activeTimer(), timer.isActive() else {
243
+ return
244
+ }
245
+
246
+ let content = UNMutableNotificationContent()
247
+ content.title = notificationSettings.title ?? "Rest finished"
248
+ content.body = notificationSettings.body ?? defaultTimerBody(for: session)
249
+ content.sound = .default
250
+
251
+ let seconds = max(1, Int(ceil(Double(timer.remainingMs()) / 1000.0)))
252
+ let trigger = UNTimeIntervalNotificationTrigger(timeInterval: TimeInterval(seconds), repeats: false)
253
+ let request = UNNotificationRequest(identifier: notificationId, content: content, trigger: trigger)
254
+ center.add(request)
255
+ }
256
+
257
+ private func defaultTimerBody(for session: WorkoutSession) -> String {
258
+ if let nextSet = session.currentSet {
259
+ return "Start your next set: \(nextSet.title)"
260
+ }
261
+ return "Continue your session \(session.title)."
262
+ }
263
+ }
@@ -0,0 +1,271 @@
1
+ import Foundation
2
+
3
+ public struct WorkoutNotificationSettings: Codable, Hashable, Sendable {
4
+ public var enabled: Bool
5
+ public var title: String?
6
+ public var body: String?
7
+
8
+ public init(enabled: Bool, title: String? = nil, body: String? = nil) {
9
+ self.enabled = enabled
10
+ self.title = title
11
+ self.body = body
12
+ }
13
+
14
+ private enum CodingKeys: String, CodingKey {
15
+ case enabled
16
+ case title
17
+ case body
18
+ }
19
+
20
+ public init(from decoder: Decoder) throws {
21
+ let singleValueContainer = try decoder.singleValueContainer()
22
+ if let enabled = try? singleValueContainer.decode(Bool.self) {
23
+ self = .init(enabled: enabled)
24
+ return
25
+ }
26
+
27
+ let keyed = try decoder.container(keyedBy: CodingKeys.self)
28
+ enabled = try keyed.decode(Bool.self, forKey: .enabled)
29
+ title = try keyed.decodeIfPresent(String.self, forKey: .title)
30
+ body = try keyed.decodeIfPresent(String.self, forKey: .body)
31
+ }
32
+ }
33
+
34
+ public struct WorkoutSet: Codable, Hashable, Sendable {
35
+ public var id: String?
36
+ public var title: String
37
+ public var recommendation: String?
38
+ public var completedAt: Int64?
39
+ public var timerDurationMs: Int64?
40
+ public var nextExerciseIndex: Int?
41
+ public var nextSetIndex: Int?
42
+
43
+ public init(
44
+ title: String,
45
+ id: String? = nil,
46
+ recommendation: String? = nil,
47
+ completedAt: Int64? = nil,
48
+ timerDurationMs: Int64? = nil,
49
+ nextExerciseIndex: Int? = nil,
50
+ nextSetIndex: Int? = nil
51
+ ) {
52
+ self.id = id
53
+ self.title = title
54
+ self.recommendation = recommendation
55
+ self.completedAt = completedAt
56
+ self.timerDurationMs = timerDurationMs
57
+ self.nextExerciseIndex = nextExerciseIndex
58
+ self.nextSetIndex = nextSetIndex
59
+ }
60
+ }
61
+
62
+ public struct WorkoutExercise: Codable, Hashable, Sendable {
63
+ public var id: String
64
+ public var title: String
65
+ public var subtitle: String?
66
+ public var iconSystemName: String?
67
+ public var imageAssetName: String?
68
+ public var sets: [WorkoutSet]
69
+
70
+ public init(
71
+ id: String,
72
+ title: String,
73
+ sets: [WorkoutSet],
74
+ subtitle: String? = nil,
75
+ iconSystemName: String? = nil,
76
+ imageAssetName: String? = nil
77
+ ) {
78
+ self.id = id
79
+ self.title = title
80
+ self.sets = sets
81
+ self.subtitle = subtitle
82
+ self.iconSystemName = iconSystemName
83
+ self.imageAssetName = imageAssetName
84
+ }
85
+ }
86
+
87
+ public struct WorkoutSetReference: Hashable, Sendable {
88
+ public let exerciseIndex: Int
89
+ public let setIndex: Int
90
+ public let set: WorkoutSet
91
+ public let exercise: WorkoutExercise
92
+ }
93
+
94
+ public struct WorkoutActiveTimer: Hashable, Sendable {
95
+ public let source: WorkoutSetReference
96
+ public let startedAtMs: Int64
97
+ public let durationMs: Int64
98
+
99
+ public var endAtMs: Int64 {
100
+ startedAtMs + durationMs
101
+ }
102
+
103
+ public func remainingMs(now: Date = Date()) -> Int64 {
104
+ max(0, endAtMs - Int64(now.timeIntervalSince1970 * 1000))
105
+ }
106
+
107
+ public func isActive(now: Date = Date()) -> Bool {
108
+ remainingMs(now: now) > 0
109
+ }
110
+
111
+ public func progress(now: Date = Date()) -> Double {
112
+ guard durationMs > 0 else {
113
+ return 0
114
+ }
115
+ let elapsed = Double(Int64(now.timeIntervalSince1970 * 1000) - startedAtMs)
116
+ return min(max(elapsed / Double(durationMs), 0), 1)
117
+ }
118
+
119
+ public func remainingText(now: Date = Date()) -> String {
120
+ let totalSeconds = Int(ceil(Double(remainingMs(now: now)) / 1000.0))
121
+ let minutes = totalSeconds / 60
122
+ let seconds = totalSeconds % 60
123
+ return String(format: "%d:%02d", minutes, seconds)
124
+ }
125
+ }
126
+
127
+ public struct WorkoutSession: Codable, Hashable, Sendable {
128
+ public var sessionId: String
129
+ public var title: String
130
+ public var startedAt: Int64
131
+ public var activeExerciseIndex: Int?
132
+ public var activeSetIndex: Int?
133
+ public var deepLinkUrl: String?
134
+ public var timerNotifications: WorkoutNotificationSettings?
135
+ public var sessionNotifications: WorkoutNotificationSettings?
136
+ public var exercises: [WorkoutExercise]
137
+
138
+ public init(
139
+ sessionId: String,
140
+ title: String,
141
+ startedAt: Int64,
142
+ exercises: [WorkoutExercise],
143
+ activeExerciseIndex: Int? = nil,
144
+ activeSetIndex: Int? = nil,
145
+ deepLinkUrl: String? = nil,
146
+ timerNotifications: WorkoutNotificationSettings? = nil,
147
+ sessionNotifications: WorkoutNotificationSettings? = nil
148
+ ) {
149
+ self.sessionId = sessionId
150
+ self.title = title
151
+ self.startedAt = startedAt
152
+ self.exercises = exercises
153
+ self.activeExerciseIndex = activeExerciseIndex
154
+ self.activeSetIndex = activeSetIndex
155
+ self.deepLinkUrl = deepLinkUrl
156
+ self.timerNotifications = timerNotifications
157
+ self.sessionNotifications = sessionNotifications
158
+ }
159
+
160
+ public var isComplete: Bool {
161
+ activeExerciseIndex == nil || activeSetIndex == nil
162
+ }
163
+
164
+ public var currentExercise: WorkoutExercise? {
165
+ guard let activeExerciseIndex, exercises.indices.contains(activeExerciseIndex) else {
166
+ return nil
167
+ }
168
+ return exercises[activeExerciseIndex]
169
+ }
170
+
171
+ public var currentSet: WorkoutSet? {
172
+ guard let activeSetIndex, let currentExercise, currentExercise.sets.indices.contains(activeSetIndex) else {
173
+ return nil
174
+ }
175
+ return currentExercise.sets[activeSetIndex]
176
+ }
177
+
178
+ public func currentSetReference() -> WorkoutSetReference? {
179
+ guard
180
+ let activeExerciseIndex,
181
+ exercises.indices.contains(activeExerciseIndex),
182
+ let activeSetIndex,
183
+ exercises[activeExerciseIndex].sets.indices.contains(activeSetIndex)
184
+ else {
185
+ return nil
186
+ }
187
+
188
+ let exercise = exercises[activeExerciseIndex]
189
+ return WorkoutSetReference(
190
+ exerciseIndex: activeExerciseIndex,
191
+ setIndex: activeSetIndex,
192
+ set: exercise.sets[activeSetIndex],
193
+ exercise: exercise
194
+ )
195
+ }
196
+
197
+ public func previousSetReference() -> WorkoutSetReference? {
198
+ guard let activeExerciseIndex, let activeSetIndex else {
199
+ return nil
200
+ }
201
+
202
+ for (exerciseIndex, exercise) in exercises.enumerated() {
203
+ for (setIndex, set) in exercise.sets.enumerated() {
204
+ if set.nextExerciseIndex == activeExerciseIndex, set.nextSetIndex == activeSetIndex {
205
+ return WorkoutSetReference(
206
+ exerciseIndex: exerciseIndex,
207
+ setIndex: setIndex,
208
+ set: set,
209
+ exercise: exercise
210
+ )
211
+ }
212
+ }
213
+ }
214
+
215
+ return nil
216
+ }
217
+
218
+ public func activeTimer(now: Date = Date()) -> WorkoutActiveTimer? {
219
+ guard
220
+ let previous = previousSetReference(),
221
+ let completedAt = previous.set.completedAt,
222
+ let duration = previous.set.timerDurationMs,
223
+ duration > 0
224
+ else {
225
+ return nil
226
+ }
227
+
228
+ let timer = WorkoutActiveTimer(
229
+ source: previous,
230
+ startedAtMs: completedAt,
231
+ durationMs: duration
232
+ )
233
+
234
+ return timer.isActive(now: now) ? timer : nil
235
+ }
236
+
237
+ public mutating func completeActiveSet(at timestampMs: Int64) {
238
+ guard
239
+ let currentExerciseIndex = activeExerciseIndex,
240
+ exercises.indices.contains(currentExerciseIndex),
241
+ let currentSetIndex = activeSetIndex,
242
+ exercises[currentExerciseIndex].sets.indices.contains(currentSetIndex)
243
+ else {
244
+ return
245
+ }
246
+
247
+ exercises[currentExerciseIndex].sets[currentSetIndex].completedAt = timestampMs
248
+ let completedSet = exercises[currentExerciseIndex].sets[currentSetIndex]
249
+ activeExerciseIndex = completedSet.nextExerciseIndex
250
+ activeSetIndex = completedSet.nextSetIndex
251
+ }
252
+
253
+ public func exerciseCompleted(at index: Int) -> Bool {
254
+ guard exercises.indices.contains(index) else {
255
+ return false
256
+ }
257
+
258
+ if let activeExerciseIndex {
259
+ if index < activeExerciseIndex {
260
+ return true
261
+ }
262
+ if index > activeExerciseIndex {
263
+ return false
264
+ }
265
+ } else if isComplete {
266
+ return true
267
+ }
268
+
269
+ return exercises[index].sets.allSatisfy { $0.completedAt != nil }
270
+ }
271
+ }