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
Watch: one exercise per page, the rest's end as a notification
Duarte Santos1d5bcd2ac293
diff --git a/.github/workflows/ios.yml b/.github/workflows/ios.ymlindex ef987911d..e363bbbbd 100644--- a/.github/workflows/ios.yml+++ b/.github/workflows/ios.yml@@ -96,9 +96,15 @@ jobs:xcrun simctl boot "$UDID" || truexcrun simctl bootstatus "$UDID" -bxcrun simctl install "$UDID" "$APP"- xcrun simctl launch "$UDID" ch.opengym.app.watchkitapp -OpenGymWatchDemo- sleep 8- xcrun simctl io "$UDID" screenshot build/watch-demo.png+ mkdir -p build/watch+ # One screenshot per screen: the exercise, the crown editor, the rest, no workout.+ for screen in set adjust rest idle; do+ xcrun simctl terminate "$UDID" ch.opengym.app.watchkitapp 2>/dev/null || true+ xcrun simctl launch "$UDID" ch.opengym.app.watchkitapp -OpenGymWatchDemo -OpenGymWatchScreen "$screen"+ sleep 6+ xcrun simctl io "$UDID" screenshot "build/watch/$screen.png"+ done+ ls -la build/watch- uses: actions/upload-artifact@v6if: always()with:@@ -107,7 +113,7 @@ jobs:frontend/ios/App/build/xcodebuild.logfrontend/ios/App/build/console.logfrontend/ios/App/build/first-screen.png- frontend/ios/App/build/watch-demo.png+ frontend/ios/App/build/watchretention-days: 7# A walk through the app in the simulator (ios/App/AppUITests): a rest that ends while the appdiff --git a/frontend/ios/App/Watch/OpenGymWatchApp.swift b/frontend/ios/App/Watch/OpenGymWatchApp.swiftindex 98ed911cf..4fe04c568 100644--- a/frontend/ios/App/Watch/OpenGymWatchApp.swift+++ b/frontend/ios/App/Watch/OpenGymWatchApp.swift@@ -1,9 +1,11 @@import SwiftUI/*- * openGym on the Apple Watch: the workout running on the iPhone, one set at a time. The Digital- * Crown sets the reps (or, after a tap on the weight, the weight) before "Done"; the rest counts- * down here and taps the wrist when it is over. Text and SF Symbols only.+ * openGym on the Apple Watch: the workout running on the iPhone, one exercise per page. The+ * Digital Crown or a vertical swipe pages through the exercises; on a page, one big number (the+ * set's weight × reps) and one main action, Done. A tap on the number opens the crown editor for+ * reps and weight. The rest counts down full screen and taps the wrist when it is over.+ * Text and SF Symbols, in the app's accent colour.*/@mainstruct OpenGymWatchApp: App {@@ -11,110 +13,255 @@ struct OpenGymWatchApp: App {var body: some Scene {WindowGroup {- RootView().environmentObject(store)+ RootView().environmentObject(store).tint(Theme.accent)}}}+enum Theme {+ /// The app's default accent (frontend/src/index.css --green, dark).+ static let accent = Color(red: 0x30 / 255, green: 0xd1 / 255, blue: 0x58 / 255)+}++func formatNumber(_ v: Double) -> String {+ v.rounded() == v ? String(Int(v)) : String(format: "%.1f", v)+}+struct RootView: View {@EnvironmentObject var store: SessionStorevar body: some View {if store.workout == nil {- VStack(spacing: 8) {- Image(systemName: "dumbbell.fill").font(.title2).foregroundStyle(.green)- Text("No workout running").font(.headline)- Text("Start one on your iPhone and it shows up here.")- .font(.footnote).foregroundStyle(.secondary).multilineTextAlignment(.center)- }- .padding()+ IdleView()} else if let end = store.restEndsAt, end > Date() {RestView(end: end)} else {- SetView()+ ExercisePager()}}}-enum CrownTarget { case reps, weight }+/* ---------- no workout ---------- */++struct IdleView: View {+ var body: some View {+ VStack(spacing: 10) {+ Image(systemName: "dumbbell.fill")+ .font(.system(size: 34, weight: .semibold))+ .foregroundStyle(Theme.accent)+ Text("No workout running")+ .font(.headline)+ Text("Start one on your iPhone and it shows up here.")+ .font(.footnote)+ .foregroundStyle(.secondary)+ .multilineTextAlignment(.center)+ }+ .padding(.horizontal, 8)+ }+}-struct SetView: View {+/* ---------- the exercises, one per page ---------- */++struct ExercisePager: View {@EnvironmentObject var store: SessionStore- @State private var crown: CrownTarget = .reps- private func number(_ v: Double) -> String {- v.rounded() == v ? String(Int(v)) : String(format: "%.1f", v)+ var body: some View {+ // Vertical pages: the Digital Crown and a vertical swipe both move between exercises.+ TabView(selection: Binding(get: { store.entryIndex }, set: { store.show(entry: $0) })) {+ ForEach(Array((store.workout?.entries ?? []).enumerated()), id: \.offset) { pair in+ ExercisePage(index: pair.offset).tag(pair.offset)+ }+ }+ .tabViewStyle(.verticalPage)}+}++struct ExercisePage: View {+ @EnvironmentObject var store: SessionStore+ let index: Int+ @State private var editing = falsevar body: some View {- if let entry = store.entry {- VStack(alignment: .leading, spacing: 4) {- Text(entry.name).font(.headline).lineLimit(2).minimumScaleFactor(0.7)- if let si = store.setIndex {- let warm = entry.sets[si].warmup- Text(warm ? "Warm-up \(si + 1) of \(entry.sets.count)" : "Set \(si + 1) of \(entry.sets.count)")- .font(.footnote).foregroundStyle(.secondary)- HStack(spacing: 6) {- Text("\(number(store.weight)) \(store.unit)")- .font(.title3.monospacedDigit())- .foregroundStyle(crown == .weight ? .green : .primary)- .onTapGesture { crown = .weight }- Text("×").foregroundStyle(.secondary)- Text(number(store.reps))- .font(.title3.monospacedDigit())- .foregroundStyle(crown == .reps ? .green : .primary)- .onTapGesture { crown = .reps }- }- .focusable(true)- .digitalCrownRotation(crownBinding, from: 0, through: crown == .weight ? 500 : 100,- by: crown == .weight ? store.weightStep : 1, sensitivity: .low,- isContinuous: false, isHapticFeedbackEnabled: true)- if let last = entry.last {- Text("Last time: \(last)").font(.caption2).foregroundStyle(.secondary).lineLimit(2)+ if let w = store.workout, w.entries.indices.contains(index) {+ let entry = w.entries[index]+ let si = store.setIndex(in: index)+ VStack(spacing: 6) {+ HStack(alignment: .firstTextBaseline) {+ Text(entry.name)+ .font(.system(.headline, design: .rounded))+ .lineLimit(2)+ .minimumScaleFactor(0.75)+ Spacer(minLength: 4)+ Text("\(index + 1)/\(w.entries.count)")+ .font(.caption2.monospacedDigit())+ .foregroundStyle(.secondary)+ }+ SetDots(entry: entry, current: si) { store.pick(set: $0, in: index) }+ if let si = si {+ let target = entry.sets[si]+ Button { editing = true } label: {+ BigNumbers(weight: index == store.entryIndex ? store.weight : (target.w ?? 0),+ reps: index == store.entryIndex ? store.reps : (target.r ?? 0),+ unit: w.unit, warmup: target.warmup)}+ .buttonStyle(.plain)Button { store.completeSet() } label: {Label("Done", systemImage: "checkmark")+ .font(.system(.body, design: .rounded).weight(.semibold))+ .frame(maxWidth: .infinity)}- .tint(.green)+ .buttonStyle(.borderedProminent)+ .tint(Theme.accent)+ .disabled(index != store.entryIndex)} else {- Label("All sets done", systemImage: "checkmark.circle.fill").foregroundStyle(.green)- }- HStack {- Button { store.move(by: -1) } label: { Image(systemName: "chevron.left") }- .disabled(store.entryIndex == 0)Spacer()- Text("\(store.entryIndex + 1)/\(store.workout?.entries.count ?? 0)").font(.caption2).foregroundStyle(.secondary)+ Label("All sets done", systemImage: "checkmark.circle.fill")+ .font(.system(.body, design: .rounded))+ .foregroundStyle(Theme.accent)Spacer()- Button { store.move(by: 1) } label: { Image(systemName: "chevron.right") }- .disabled(store.entryIndex >= (store.workout?.entries.count ?? 1) - 1)}- .buttonStyle(.plain)}- .padding(.horizontal, 4)+ .padding(.horizontal, 6)+ .sheet(isPresented: $editing) { AdjustView() }+ .onAppear { if SessionStore.demoScreen == "adjust" && index == store.entryIndex { editing = true } }+ }+ }+}++/// One dot per set: filled when done, ringed when it is the one up. A tap picks a set.+struct SetDots: View {+ let entry: Entry+ let current: Int?+ let pick: (Int) -> Void++ var body: some View {+ HStack(spacing: 5) {+ ForEach(Array(entry.sets.enumerated()), id: \.offset) { pair in+ let s = pair.element+ Circle()+ .fill(s.done ? Theme.accent : Color.gray.opacity(0.35))+ .overlay(Circle().stroke(Theme.accent, lineWidth: pair.offset == current ? 2 : 0))+ .frame(width: s.warmup ? 7 : 10, height: s.warmup ? 7 : 10)+ .onTapGesture { if !s.done { pick(pair.offset) } }+ }+ Spacer(minLength: 0)+ }+ }+}++struct BigNumbers: View {+ let weight: Double+ let reps: Double+ let unit: String+ let warmup: Bool++ var body: some View {+ VStack(spacing: 0) {+ if warmup {+ Text("Warm-up").font(.caption2).foregroundStyle(.secondary)+ }+ HStack(alignment: .firstTextBaseline, spacing: 3) {+ Text(formatNumber(weight))+ .font(.system(size: 34, weight: .semibold, design: .rounded).monospacedDigit())+ Text(unit).font(.footnote).foregroundStyle(.secondary)+ Text("×").font(.title3).foregroundStyle(.secondary).padding(.horizontal, 2)+ Text(formatNumber(reps))+ .font(.system(size: 34, weight: .semibold, design: .rounded).monospacedDigit())+ }+ .minimumScaleFactor(0.6)+ .lineLimit(1)+ }+ .frame(maxWidth: .infinity)+ }+}++/* ---------- the crown editor ---------- */++enum CrownTarget { case reps, weight }++struct AdjustView: View {+ @EnvironmentObject var store: SessionStore+ @Environment(\.dismiss) private var dismiss+ @State private var target: CrownTarget = .reps++ var body: some View {+ VStack(spacing: 8) {+ Picker("", selection: $target) {+ Text("Reps").tag(CrownTarget.reps)+ Text(store.unit).tag(CrownTarget.weight)+ }+ .pickerStyle(.segmented)+ .labelsHidden()+ Text(formatNumber(target == .weight ? store.weight : store.reps))+ .font(.system(size: 52, weight: .semibold, design: .rounded).monospacedDigit())+ .foregroundStyle(Theme.accent)+ .focusable(true)+ .digitalCrownRotation(crownBinding, from: 0, through: target == .weight ? 500 : 100,+ by: target == .weight ? store.weightStep : 1, sensitivity: .low,+ isContinuous: false, isHapticFeedbackEnabled: true)+ if let last = store.entry?.last {+ Text("Last time: \(last)")+ .font(.caption2)+ .foregroundStyle(.secondary)+ .lineLimit(2)+ .multilineTextAlignment(.center)+ }+ Button {+ store.completeSet()+ dismiss()+ } label: {+ Label("Done", systemImage: "checkmark").frame(maxWidth: .infinity)+ }+ .buttonStyle(.borderedProminent)+ .tint(Theme.accent)}}private var crownBinding: Binding<Double> {Binding(- get: { crown == .weight ? store.weight : store.reps },- set: { v in if crown == .weight { store.weight = max(0, v) } else { store.reps = max(0, v.rounded()) } }+ get: { target == .weight ? store.weight : store.reps },+ set: { v in+ if target == .weight { store.weight = max(0, v) } else { store.reps = max(0, v.rounded()) }+ })}}+/* ---------- the rest ---------- */+struct RestView: View {@EnvironmentObject var store: SessionStorelet end: Datevar body: some View {- VStack(spacing: 8) {- Text("Rest").font(.footnote).foregroundStyle(.secondary)- Text(timerInterval: Date()...end, countsDown: true)- .font(.system(size: 44, weight: .semibold, design: .rounded).monospacedDigit())+ VStack(spacing: 6) {+ ZStack {+ Circle().stroke(Color.gray.opacity(0.25), lineWidth: 6)+ TimelineView(.periodic(from: .now, by: 0.5)) { ctx in+ let total = max(1, end.timeIntervalSince(store.restStartedAt ?? end.addingTimeInterval(-90)))+ let left = max(0, end.timeIntervalSince(ctx.date))+ Circle()+ .trim(from: 0, to: CGFloat(left / total))+ .stroke(Theme.accent, style: StrokeStyle(lineWidth: 6, lineCap: .round))+ .rotationEffect(.degrees(-90))+ }+ Text(timerInterval: Date()...end, countsDown: true)+ .font(.system(size: 34, weight: .semibold, design: .rounded).monospacedDigit())+ .multilineTextAlignment(.center)+ }+ .padding(6)if let e = store.entry, let si = store.setIndex {- Text("Next: \(e.name), set \(si + 1)").font(.caption2).foregroundStyle(.secondary).lineLimit(2)+ Text("Next: \(e.name), set \(si + 1)")+ .font(.caption2)+ .foregroundStyle(.secondary)+ .lineLimit(1)+ }+ HStack {+ Button { store.addRest(15) } label: { Text("+15s") }+ Button { store.skipRest() } label: { Label("Skip", systemImage: "forward.fill") }+ .tint(Theme.accent)}- Button("Skip rest") { store.skipRest() }+ .font(.footnote)}}}diff --git a/frontend/ios/App/Watch/SessionStore.swift b/frontend/ios/App/Watch/SessionStore.swiftindex 0537b1f05..dea2f328e 100644--- a/frontend/ios/App/Watch/SessionStore.swift+++ b/frontend/ios/App/Watch/SessionStore.swift@@ -1,4 +1,5 @@import Foundation+import UserNotificationsimport WatchConnectivityimport WatchKit@@ -48,27 +49,46 @@ struct SetRow: Codable, Equatable {let warmup: Bool}-final class SessionStore: NSObject, ObservableObject, WCSessionDelegate {+final class SessionStore: NSObject, ObservableObject, WCSessionDelegate, UNUserNotificationCenterDelegate {@Published private(set) var workout: ActiveWorkout?@Published var entryIndex = 0@Published var weight: Double = 0@Published var reps: Double = 0@Published private(set) var restEndsAt: Date?+ @Published private(set) var restStartedAt: Date?+ /// A set picked by hand in an exercise (entry index → set index); otherwise the first not done.+ @Published private var picked: [Int: Int] = [:]/// Sets ticked here that the phone has not confirmed yet ("exerciseId#setIndex"): a snapshot/// sent before the phone applied them must not untick them.private var pending = Set<String>()private var restTimer: Timer?private static let savedKey = "snapshot"+ private static let restNotificationId = "opengym.rest"static let demoArgument = "-OpenGymWatchDemo"+ /// CI screenshots: "-OpenGymWatchScreen rest" opens the demo on that screen.+ static var demoScreen: String? {+ let a = ProcessInfo.processInfo.arguments+ guard let i = a.firstIndex(of: "-OpenGymWatchScreen"), i + 1 < a.count else { return nil }+ return a[i + 1]+ }+ var isDemo: Bool { ProcessInfo.processInfo.arguments.contains(SessionStore.demoArgument) }override init() {super.init()- if ProcessInfo.processInfo.arguments.contains(SessionStore.demoArgument) {- apply(json: SessionStore.demoJSON)+ if isDemo {+ if SessionStore.demoScreen != "idle" { apply(json: SessionStore.demoJSON) }+ if SessionStore.demoScreen == "rest" {+ DispatchQueue.main.async { self.startRest(until: Date().addingTimeInterval(83), notify: false) }+ }} else if let saved = UserDefaults.standard.string(forKey: SessionStore.savedKey) {apply(json: saved)}+ // The rest's end as a notification, also when the app is not in front (not in the demo:+ // the permission question would cover the screenshot).+ let center = UNUserNotificationCenter.current()+ center.delegate = self+ if !isDemo { center.requestAuthorization(options: [.alert, .sound]) { _, _ in } }if WCSession.isSupported() {WCSession.default.delegate = selfWCSession.default.activate()@@ -82,9 +102,27 @@ final class SessionStore: NSObject, ObservableObject, WCSessionDelegate {return w.entries[entryIndex]}- /// The set to do next in the current exercise, or nil when they are all done.- var setIndex: Int? {- entry?.sets.firstIndex(where: { !$0.done })+ /// The set to do next in the current exercise (the one picked, or the first not done), or nil+ /// when they are all done.+ var setIndex: Int? { setIndex(in: entryIndex) }++ func setIndex(in ei: Int) -> Int? {+ guard let w = workout, w.entries.indices.contains(ei) else { return nil }+ let sets = w.entries[ei].sets+ if let p = picked[ei], sets.indices.contains(p), !sets[p].done { return p }+ return sets.firstIndex(where: { !$0.done })+ }++ func pick(set si: Int, in ei: Int) {+ picked[ei] = si+ if ei == entryIndex { loadTargets() }+ }++ /// Paging to another exercise (Digital Crown or a vertical swipe).+ func show(entry ei: Int) {+ guard ei != entryIndex else { return }+ entryIndex = ei+ loadTargets()}var unit: String { workout?.unit ?? "kg" }@@ -113,7 +151,7 @@ final class SessionStore: NSObject, ObservableObject, WCSessionDelegate {self.workout = nextif !sameWorkout { self.entryIndex = next.cur }if let rest = next.rest {- self.startRest(until: Date(timeIntervalSince1970: rest.endsAt / 1000))+ self.startRest(until: Date(timeIntervalSince1970: rest.endsAt / 1000), notify: true)}self.entryIndex = min(max(0, self.entryIndex), max(0, next.entries.count - 1))self.loadTargets()@@ -152,7 +190,8 @@ final class SessionStore: NSObject, ObservableObject, WCSessionDelegate {])WKInterfaceDevice.current().play(.success)let rest = e.restSec ?? w.restSec- if rest > 0 { startRest(until: Date().addingTimeInterval(rest)) }+ picked[ei] = nil+ if rest > 0 { startRest(until: Date().addingTimeInterval(rest), notify: true) }// On to the next exercise once this one is done.if setIndex == nil, let next = w.entries.indices.first(where: { $0 > ei && w.entries[$0].sets.contains(where: { !$0.done }) }) {entryIndex = next@@ -169,16 +208,61 @@ final class SessionStore: NSObject, ObservableObject, WCSessionDelegate {func skipRest() {restTimer?.invalidate()restEndsAt = nil+ restStartedAt = nil+ UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: [SessionStore.restNotificationId])}- private func startRest(until end: Date) {+ func addRest(_ seconds: TimeInterval) {+ guard let end = restEndsAt else { return }+ let start = restStartedAt+ startRest(until: end.addingTimeInterval(seconds), notify: true)+ restStartedAt = start+ }++ /// The rest as a timer here (with the app in front: the haptic pattern) and as a notification+ /// for its end (with the app not in front: banner and haptic from the system). A new rest or a+ /// skip takes the old one back.+ private func startRest(until end: Date, notify: Bool) {restTimer?.invalidate()- guard end > Date() else { restEndsAt = nil; return }+ let center = UNUserNotificationCenter.current()+ center.removePendingNotificationRequests(withIdentifiers: [SessionStore.restNotificationId])+ guard end > Date() else { restEndsAt = nil; restStartedAt = nil; return }restEndsAt = end+ restStartedAt = Date()restTimer = Timer.scheduledTimer(withTimeInterval: end.timeIntervalSinceNow, repeats: false) { [weak self] _ in- WKInterfaceDevice.current().play(.notification)- DispatchQueue.main.async { self?.restEndsAt = nil }+ SessionStore.restOverHaptics()+ DispatchQueue.main.async {+ self?.restEndsAt = nil+ self?.restStartedAt = nil+ }}+ guard notify else { return }+ let content = UNMutableNotificationContent()+ content.title = "Rest's over"+ if let e = entry, let si = setIndex {+ content.body = "\(e.name), set \(si + 1)"+ } else {+ content.body = "Next set!"+ }+ content.sound = .default+ content.interruptionLevel = .timeSensitive+ let trigger = UNTimeIntervalNotificationTrigger(timeInterval: max(1, end.timeIntervalSinceNow), repeats: false)+ center.add(UNNotificationRequest(identifier: SessionStore.restNotificationId, content: content, trigger: trigger))+ }++ /// A short, alarm-like pattern on the wrist: three taps.+ static func restOverHaptics() {+ let device = WKInterfaceDevice.current()+ device.play(.notification)+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.6) { device.play(.success) }+ DispatchQueue.main.asyncAfter(deadline: .now() + 1.2) { device.play(.notification) }+ }++ /* ---------- notifications with the app in front ---------- */++ func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification,+ withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {+ completionHandler([.banner, .sound])}private func send(event: [String: Any]) {