Open-source gym & body-weight tracker, now in the App Store (iPhone + Apple Watch) and as an Android APK. Plan routines, log workouts, see which muscles are trained, import from Strong/Hevy/FitNotes. Self-host it or use it on the phone alone.
JavaScript apple-watchbodyweightdockerfitnessfitness-trackergymhealthiosmcpnodejspasskeysprogressive-web-applicationspwareactself-hostedself-hostingvitewebauthnweightliftingworkout-tracker
feat(ios): Live Activity Next exercise and Skip rest buttons, Log set, no false "All sets done"
Duarte Santos4bc4e7a2f5cc
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 47a86fbe5..f7042bbee 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -29,6 +29,11 @@ per muscle. Settings → Workout → Fine-tuning turns it off.now lists each one in its ⋯ menu during a workout. Tap it and the backup takes over with theslot's own sets, reps, rest and warm-ups, and the exercise it replaced becomes its backup, sogoing back when the bench frees up is one tap too. Your routine stays exactly as it was.+- **Lock Screen: Next exercise and Skip rest** (iPhone, Discord). The workout's Live Activity+ and the Dynamic Island get a small button next to the big one: Skip rest while you rest, Next+ exercise the rest of the time, so a machine somebody grabbed no longer means unlocking the+ phone. Nothing gets ticked, and it works with openGym asleep. The big button now says Log set,+ because "Done" sounded a lot like "I'm going home".- **Machines with odd weight steps** (#688). A machine or cable exercise now has a Weight stackunder Plate loading: type in the weights its pin really picks (5, 11.3, 18.1, the LifeFitnessspecial) or fill an even stack and fix the odd ones. Progression, deloads, warm-ups, drops and@@ -278,6 +283,8 @@ you leave it alone. Handy for deciding whether those legs are really ready (than- Exercise names on the Lock Screen, in the Dynamic Island, on the Apple Watch and in the widgetsare title-cased like in the app (Focus mode's exercise menu too), instead of whispering"barbell bench press".+- After a long run of Lock Screen taps with the app asleep, the Live Activity said "All sets done"+ with sets still to go. It now says "Open openGym for the next set".- Focus mode: the exercise's ⋯ menu has Add set and Add warm-up set, so one more set no longermeans a trip to the Cards layout.- A weight change too small to show (say 0.03 kg) reads 0 instead of a lonely "-0".diff --git a/frontend/ios/App/App/LiveActivityPlugin.swift b/frontend/ios/App/App/LiveActivityPlugin.swiftindex 2a2bef559..2bdfee8a1 100644--- a/frontend/ios/App/App/LiveActivityPlugin.swift+++ b/frontend/ios/App/App/LiveActivityPlugin.swift@@ -5,8 +5,8 @@ import Foundation/*** The running workout's Live Activity, for the page (lib/live-activity.js). The page sends the* whole activity whenever it changes; this starts it for a new workout, updates it for the same- * one, and ends it with the workout. The Done button's taps (WorkoutActivity.swift DoneSetIntent)- * wait in LiveActivityQueue until the page drains and acknowledges them; a "liveActivityEvent"+ * one, and ends it with the workout. Its buttons' taps (WorkoutActivity.swift: Log set, Next+ * exercise, Skip rest) wait in LiveActivityQueue until the page drains and acknowledges them; a "liveActivityEvent"* tells a page that is awake that one came in.** iOS 17 and later (the interactive Done button); earlier, status says unsupported and the pagediff --git a/frontend/ios/App/App/RestAlertPlugin.swift b/frontend/ios/App/App/RestAlertPlugin.swiftindex ea3776a22..34400c278 100644--- a/frontend/ios/App/App/RestAlertPlugin.swift+++ b/frontend/ios/App/App/RestAlertPlugin.swift@@ -48,6 +48,8 @@ public class RestAlertPlugin: CAPPlugin, CAPBridgedPlugin {let nc = NotificationCenter.defaultnc.addObserver(self, selector: #selector(cameToFront), name: UIApplication.didBecomeActiveNotification, object: nil)nc.addObserver(self, selector: #selector(leftFront), name: UIApplication.didEnterBackgroundNotification, object: nil)+ // The Live Activity's Skip rest (WorkoutActivity.swift): this rest's alert is not posted later.+ nc.addObserver(self, selector: #selector(restSkipped), name: LiveActivityQueue.restSkipped, object: nil)// Written ahead, off the main thread: the first rest then finds its sound file there.DispatchQueue.global(qos: .utility).async { RestTone.kinds.forEach { _ = RestTone.soundFile($0) } }}@@ -157,6 +159,10 @@ public class RestAlertPlugin: CAPPlugin, CAPBridgedPlugin {post()}+ @objc private func restSkipped() {+ DispatchQueue.main.async { self.pending = nil }+ }+private func post() {guard let p = pending, p.at > Date() else { return }let content = UNMutableNotificationContent()diff --git a/frontend/ios/App/App/WidgetPreview.swift b/frontend/ios/App/App/WidgetPreview.swiftindex 9c54879d8..ab9620c80 100644--- a/frontend/ios/App/App/WidgetPreview.swift+++ b/frontend/ios/App/App/WidgetPreview.swift@@ -46,13 +46,28 @@ enum WidgetPreview {@available(iOS 17.0, *)private static func live(rest: Bool) -> (WorkoutActivityAttributes, WorkoutActivityAttributes.ContentState)? {let end = (Date().timeIntervalSince1970 + 75) * 1000+ guard let a = decode(WorkoutActivityAttributes.self, """+ {"v":2,"wid":"preview","start":null,"accent":"#30d158","ink":"#000000",+ "labels":{"done":"Log set","rest":"Rest","next":"Up next","allDone":"All sets done","restOver":"Rest’s over. Next set!",+ "nextExercise":"Next exercise","skipRest":"Skip rest","openApp":"Open openGym for the next set"}}+ """), let s = decode(WorkoutActivityAttributes.ContentState.self, """+ {"name":"Push Day","cur":{"exId":"0025","entryIdx":0,"setIdx":2,"exName":"Barbell Bench Press","setLine":"Set 3 of 4",+ "target":"80 kg × 6","restAfter":120,"unit":0},"ahead":[],"restEndsAt":\(rest ? String(end) : "null"),"restLeft":null,+ "restTotal":\(rest ? "120" : "null"),"done":6,"total":17,+ "unitStarts":[{"exId":"0043","entryIdx":1,"setIdx":0,"exName":"Overhead Press","setLine":"Set 1 of 3","target":"40 kg × 8","restAfter":90,"unit":1}]}+ """) else { return nil }+ return (a, s)+ }++ /// An activity a build before LIVE_VERSION 2 started (no unit, unitStarts or new labels) must+ /// still decode, and shows Log set's old label with no second button.+ @available(iOS 17.0, *)+ private static func liveV1() -> (WorkoutActivityAttributes, WorkoutActivityAttributes.ContentState)? {guard let a = decode(WorkoutActivityAttributes.self, """{"v":1,"wid":"preview","start":null,"accent":"#30d158","ink":"#000000","labels":{"done":"Done","rest":"Rest","next":"Up next","allDone":"All sets done","restOver":"Rest’s over. Next set!"}}"""), let s = decode(WorkoutActivityAttributes.ContentState.self, """- {"name":"Push Day","cur":{"exId":"0025","entryIdx":0,"setIdx":2,"exName":"Barbell Bench Press","setLine":"Set 3 of 4",- "target":"80 kg × 6","restAfter":120},"ahead":[],"restEndsAt":\(rest ? String(end) : "null"),"restLeft":null,- "restTotal":\(rest ? "120" : "null"),"done":6,"total":17}+ {"name":"Push Day","cur":null,"ahead":[],"restEndsAt":null,"restLeft":null,"restTotal":null,"done":8,"total":17}""") else { return nil }return (a, s)}@@ -97,6 +112,9 @@ enum WidgetPreview {if case let (a, s)? = live(rest: true) {save("live-lock-resting", CGSize(width: 370, height: 150), dark: dark, radius: 24, padding: 0) { LiveLockView(attributes: a, state: s) }}+ if case let (a, s)? = liveV1() {+ save("live-lock-v1-open-app", CGSize(width: 370, height: 150), dark: dark, radius: 24, padding: 0) { LiveLockView(attributes: a, state: s) }+ }}// The Lock Screen's accessories and the Dynamic Island are drawn light on dark.save("lock-rect", CGSize(width: 172, height: 76), dark: true, radius: 12, padding: 6) { NextRectView(model: plan) }diff --git a/frontend/ios/App/App/WidgetViews.swift b/frontend/ios/App/App/WidgetViews.swiftindex 5399a8b92..fd3f1c9dc 100644--- a/frontend/ios/App/App/WidgetViews.swift+++ b/frontend/ios/App/App/WidgetViews.swift@@ -397,6 +397,16 @@ struct LiveRest: View {}}+@available(iOS 16.1, *)+extension WorkoutActivityAttributes {+ /// The line with no set to show: all done, or sets left that the activity does not carry+ /// (many taps with the page asleep), where "All sets done" was simply wrong (Discord).+ func noSetText(_ state: ContentState) -> String {+ state.done < state.total ? (labels.openApp ?? "Open openGym for the next set") : labels.allDone+ }+}++/// Log set: ticks the set shown (the label from LIVE_VERSION 2 says so; "Done" read like "finish").@available(iOS 17.0, *)struct LiveDoneButton: View {let attributes: WorkoutActivityAttributes@@ -407,9 +417,38 @@ struct LiveDoneButton: View {Label(attributes.labels.done, systemImage: "checkmark").font(.subheadline.weight(.semibold)).foregroundStyle(Color(hex: attributes.ink) ?? .black)+ .lineLimit(1)}.buttonStyle(.borderedProminent).tint(Color(hex: attributes.accent) ?? .green)+ .accessibilityHint(Text([cur.exName, cur.setLine].filter { !$0.isEmpty }.joined(separator: ", ")))+ }+}++/// The smaller button beside Log set: Skip rest while resting, else Next exercise, and nothing+/// when no other exercise has sets open.+@available(iOS 17.0, *)+struct LiveSecondaryButton: View {+ let attributes: WorkoutActivityAttributes+ let state: WorkoutActivityAttributes.ContentState++ var body: some View {+ let accent = Color(hex: attributes.accent) ?? .green+ if state.resting {+ Button(intent: SkipRestIntent(wid: attributes.wid)) {+ Image(systemName: "forward.fill").font(.subheadline.weight(.semibold))+ }+ .buttonStyle(.bordered)+ .tint(accent)+ .accessibilityLabel(Text(attributes.labels.skipRest ?? "Skip rest"))+ } else if let c = state.cur, state.nextUnitStart != nil {+ Button(intent: NextExerciseIntent(wid: attributes.wid, entryIdx: c.entryIdx)) {+ Image(systemName: "forward.end.fill").font(.subheadline.weight(.semibold))+ }+ .buttonStyle(.bordered)+ .tint(accent)+ .accessibilityLabel(Text(attributes.labels.nextExercise ?? "Next exercise"))+ }}}@@ -424,7 +463,7 @@ struct LiveLockView: View {VStack(alignment: .leading, spacing: 10) {HStack(alignment: .top, spacing: 10) {VStack(alignment: .leading, spacing: 2) {- Text(state.cur?.exName ?? attributes.labels.allDone).font(.headline).lineLimit(1)+ Text(state.cur?.exName ?? attributes.noSetText(state)).font(.headline).lineLimit(1)if let c = state.cur {Text([c.setLine, c.target].filter { !$0.isEmpty }.joined(separator: " · ")).font(.subheadline).foregroundStyle(.secondary).lineLimit(1)@@ -443,6 +482,7 @@ struct LiveLockView: View {HStack(spacing: 10) {ProgressBar(value: Double(state.done) / Double(max(1, state.total)), accent: accent)Text("\(state.done)/\(state.total)").font(.caption.weight(.semibold)).monospacedDigit().foregroundStyle(.secondary)+ LiveSecondaryButton(attributes: attributes, state: state)if let c = state.cur { LiveDoneButton(attributes: attributes, cur: c) }}}diff --git a/frontend/ios/App/App/WorkoutActivity.swift b/frontend/ios/App/App/WorkoutActivity.swiftindex af60c3fcc..d8a6a75ee 100644--- a/frontend/ios/App/App/WorkoutActivity.swift+++ b/frontend/ios/App/App/WorkoutActivity.swift@@ -4,10 +4,11 @@ import Foundationimport UserNotifications/*- * The running workout's Live Activity: what it carries, and its Done button. Compiled into both+ * The running workout's Live Activity: what it carries, and its buttons (Log set, and Next exercise+ * or Skip rest beside it). Compiled into both* the app and the widget extension (ios/ci/add-widgets.rb): the extension draws it* (OpenGymWidgets/LiveActivityWidget.swift), the app starts and updates it for the page- * (LiveActivityPlugin.swift, lib/live-activity.js) and runs the Done button's intent.+ * (LiveActivityPlugin.swift, lib/live-activity.js) and runs the buttons' intents.** The page sends both halves as JSON; the field names are lib/live-activity.js buildLiveActivity's.* Text only: no exercise animations or pictures (Gym visual licence).@@ -28,6 +29,11 @@ struct WorkoutActivityAttributes: ActivityAttributes {var next: Stringvar allDone: Stringvar restOver: String+ // From LIVE_VERSION 2. Optional: an activity a build before that started keeps its old+ // labels (they are fixed for the activity's life) and still has to decode.+ var nextExercise: String?+ var skipRest: String?+ var openApp: String?}/// One set as the activity shows it, with the rest that follows it.@@ -39,6 +45,10 @@ struct WorkoutActivityAttributes: ActivityAttributes {var setLine: Stringvar target: Stringvar restAfter: Int+ /// The first entry of its superset unit (LIVE_VERSION 2): Next exercise leaves this unit.+ var unit: Int?++ var unitKey: Int { unit ?? entryIdx }}struct ContentState: Codable, Hashable {@@ -54,6 +64,27 @@ struct WorkoutActivityAttributes: ActivityAttributes {var restTotal: Double?var done: Intvar total: Int+ /// The first open set of the next few exercises, in order (LIVE_VERSION 2), so Next exercise+ /// works while the page sleeps. Always the units after `cur`'s: moving on trims it.+ var unitStarts: [SetInfo]?++ /// A rest is counting down or held.+ var resting: Bool { restEndsAt != nil || restLeft != nil }++ /// Where Next exercise goes: the first open set of the next exercise, or nil when no other+ /// exercise the activity knows of has sets open.+ var nextUnitStart: SetInfo? {+ guard let cur = cur else { return nil }+ return (unitStarts ?? []).first { $0.unitKey != cur.unitKey }+ }++ /// The starts after the unit `set` is in, once the activity moved into it.+ func startsAfter(_ set: SetInfo?) -> [SetInfo]? {+ guard let starts = unitStarts else { return nil }+ guard let set = set else { return [] }+ guard let i = starts.firstIndex(where: { $0.unitKey == set.unitKey }) else { return starts }+ return Array(starts[(i + 1)...])+ }/// The running rest as a range Text(timerInterval:) can count down, or nil.var restRange: ClosedRange<Date>? {@@ -73,12 +104,15 @@ struct WorkoutActivityAttributes: ActivityAttributes {}/**- * The Done taps the page has not applied yet, oldest first, in the App Group. The intent adds to- * it, LiveActivityPlugin hands it to the page and takes out what the page acknowledged.+ * The taps (Log set, Next exercise, Skip rest) the page has not applied yet, oldest first, in the+ * App Group. The intents add to it, LiveActivityPlugin hands it to the page and takes out what the+ * page acknowledged.*/enum LiveActivityQueue {static let key = "liveActivityEvents"static let didChange = Notification.Name("OpenGymLiveActivityEvent")+ /// Skip rest was tapped: RestAlertPlugin forgets the alert it would post on leaving the front.+ static let restSkipped = Notification.Name("OpenGymLiveActivityRestSkipped")private static let lock = NSLock()static func all() -> [[String: Any]] {@@ -144,6 +178,48 @@ struct DoneSetIntent: LiveActivityIntent {}}+/// The Live Activity's Next exercise: on to the next exercise without logging anything (Discord).+@available(iOS 17.0, *)+struct NextExerciseIntent: LiveActivityIntent {+ static let title: LocalizedStringResource = "Next exercise"+ static let isDiscoverable = false++ @Parameter(title: "Workout") var wid: String+ @Parameter(title: "Entry") var entryIdx: Int++ init() {}++ init(wid: String, entryIdx: Int) {+ self.wid = wid+ self.entryIdx = entryIdx+ }++ func perform() async throws -> some IntentResult {+ await LiveActivityTick.nextExercise(wid: wid, entryIdx: entryIdx)+ return .result()+ }+}++/// The Live Activity's Skip rest, the rest bar's Skip.+@available(iOS 17.0, *)+struct SkipRestIntent: LiveActivityIntent {+ static let title: LocalizedStringResource = "Skip rest"+ static let isDiscoverable = false++ @Parameter(title: "Workout") var wid: String++ init() {}++ init(wid: String) {+ self.wid = wid+ }++ func perform() async throws -> some IntentResult {+ await LiveActivityTick.skipRest(wid: wid)+ return .result()+ }+}+@available(iOS 17.0, *)enum LiveActivityTick {static let restRequestId = "opengym.rest" // RestAlertPlugin.requestId: the page's own replaces it@@ -161,6 +237,7 @@ enum LiveActivityTick {next.cur = state.ahead.firstnext.ahead = Array(state.ahead.dropFirst())next.done = min(state.total, state.done + 1)+ next.unitStarts = state.startsAfter(next.cur)next.restLeft = nilif cur.restAfter > 0, next.cur != nil {let end = now.addingTimeInterval(TimeInterval(cur.restAfter))@@ -175,6 +252,51 @@ enum LiveActivityTick {NotificationCenter.default.post(name: LiveActivityQueue.didChange, object: nil)}+ /// Next exercise: the activity moves to the next exercise's first open set, nothing is ticked.+ static func nextExercise(wid: String, entryIdx: Int, now: Date = Date()) async {+ guard let activity = Activity<WorkoutActivityAttributes>.activities.first(where: { $0.attributes.wid == wid }) else { return }+ let state = activity.content.state+ // A button from a state already moved on (two quick taps): the first one went.+ guard let cur = state.cur, cur.entryIdx == entryIdx, let target = state.nextUnitStart else { return }+ LiveActivityQueue.append([+ "id": UUID().uuidString, "type": "next", "wid": wid, "fromEntryIdx": entryIdx,+ "at": (now.timeIntervalSince1970 * 1000).rounded(),+ ])+ var next = state+ // The sets carried for the left exercise are dropped; the ones from the target on stay.+ if let i = state.ahead.firstIndex(where: { $0.unitKey == target.unitKey }) {+ next.cur = state.ahead[i]+ next.ahead = Array(state.ahead[(i + 1)...])+ } else {+ next.cur = target+ next.ahead = []+ }+ next.unitStarts = state.startsAfter(next.cur)+ await activity.update(ActivityContent(state: next, staleDate: nil))+ NotificationCenter.default.post(name: LiveActivityQueue.didChange, object: nil)+ }++ /// Skip rest: the rest ends now, and so does its rest-over notification.+ static func skipRest(wid: String, now: Date = Date()) async {+ guard let activity = Activity<WorkoutActivityAttributes>.activities.first(where: { $0.attributes.wid == wid }) else { return }+ let state = activity.content.state+ guard state.resting else { return }+ LiveActivityQueue.append([+ "id": UUID().uuidString, "type": "restSkip", "wid": wid, "at": (now.timeIntervalSince1970 * 1000).rounded(),+ ])+ var next = state+ next.restEndsAt = nil+ next.restLeft = nil+ next.restTotal = nil+ // The page's own (RestAlertPlugin) uses the same id, so this takes that one down too.+ let center = UNUserNotificationCenter.current()+ center.removePendingNotificationRequests(withIdentifiers: [restRequestId])+ center.removeDeliveredNotifications(withIdentifiers: [restRequestId])+ NotificationCenter.default.post(name: LiveActivityQueue.restSkipped, object: nil)+ await activity.update(ActivityContent(state: next, staleDate: nil))+ NotificationCenter.default.post(name: LiveActivityQueue.didChange, object: nil)+ }+private static func bookRestOver(at: Date, title: String) {let content = UNMutableNotificationContent()content.title = titlediff --git a/frontend/ios/App/OpenGymWidgets/LiveActivityWidget.swift b/frontend/ios/App/OpenGymWidgets/LiveActivityWidget.swiftindex ccc55c3bd..e06eb4b32 100644--- a/frontend/ios/App/OpenGymWidgets/LiveActivityWidget.swift+++ b/frontend/ios/App/OpenGymWidgets/LiveActivityWidget.swift@@ -5,7 +5,8 @@ import WidgetKit/** The running workout on the Lock Screen and in the Dynamic Island (and, through the compact* views, in an Apple Watch's Smart Stack). The app starts and updates it (LiveActivityPlugin.swift);- * its Done button is WorkoutActivity.swift's DoneSetIntent. The views are App/WidgetViews.swift's.+ * its buttons are WorkoutActivity.swift's DoneSetIntent, NextExerciseIntent and SkipRestIntent.+ * The views are App/WidgetViews.swift's.*/struct WorkoutLiveActivity: Widget {var body: some WidgetConfiguration {@@ -17,8 +18,8 @@ struct WorkoutLiveActivity: Widget {return DynamicIsland {DynamicIslandExpandedRegion(.leading) {VStack(alignment: .leading, spacing: 2) {- Text(context.state.cur?.exName ?? context.attributes.labels.allDone)- .font(.headline).lineLimit(1)+ Text(context.state.cur?.exName ?? context.attributes.noSetText(context.state))+ .font(.headline).lineLimit(1).minimumScaleFactor(0.75)if let c = context.state.cur {Text(c.setLine).font(.caption).foregroundStyle(.secondary).lineLimit(1)}@@ -38,6 +39,7 @@ struct WorkoutLiveActivity: Widget {HStack(spacing: 10) {ProgressBar(value: Double(context.state.done) / Double(max(1, context.state.total)), accent: accent)Text("\(context.state.done)/\(context.state.total)").font(.caption.weight(.semibold)).monospacedDigit()+ LiveSecondaryButton(attributes: context.attributes, state: context.state)if let c = context.state.cur { LiveDoneButton(attributes: context.attributes, cur: c) }}}