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
Apple Watch app: the running workout, one set at a time
Duarte Santosa19e36f33ac1
diff --git a/.github/workflows/ios.yml b/.github/workflows/ios.ymlindex 5f2cc8f91..ef987911d 100644--- a/.github/workflows/ios.yml+++ b/.github/workflows/ios.yml@@ -42,12 +42,15 @@ jobs:# The phone build, copied into ios/App/App/public; cap sync runs pod install.- run: npm run build:mobileworking-directory: frontend+ # The Apple Watch app (ios/App/Watch), added to the project for the run and embedded in App.app.+ - run: ruby ios/ci/add-watch-app.rb+ working-directory: frontend- name: Build for the simulatorworking-directory: frontend/ios/Apprun: |set -o pipefailxcodebuild -workspace App.xcworkspace -scheme App -configuration Debug \- -sdk iphonesimulator -derivedDataPath build/dd \+ -destination 'generic/platform=iOS Simulator' -derivedDataPath build/dd \CODE_SIGNING_ALLOWED=NO build | tee build/xcodebuild.log | grep -E "error:|warning: .*(App/|Swift)|BUILD" || truetest -d build/dd/Build/Products/Debug-iphonesimulator/App.app# Starts the app and keeps what it prints: Capacitor logs every bridge call and every@@ -74,6 +77,28 @@ jobs:cat build/console.log | grep -v "^\s*$" | head -200if grep -q "not implemented on ios" build/console.log; then echo "::error::a plugin the page uses is missing on iOS"; exit 1; figrep -q "RestAlert" build/console.log || { echo "::error::the page never reached the RestAlert plugin"; exit 1; }+ # The watch app on its own in a watch simulator, with the demo session it carries+ # (SessionStore.demoJSON: text only, no exercise media), for a look at it.+ - name: Show the watch app+ continue-on-error: true+ working-directory: frontend/ios/App+ run: |+ APP=build/dd/Build/Products/Debug-watchsimulator/OpenGymWatch.app+ test -d "$APP" || { echo "::warning::no watch app was built"; exit 1; }+ if ! xcrun simctl list runtimes | grep -q watchOS; then xcodebuild -downloadPlatform watchOS || true; fi+ UDID=$(xcrun simctl list devices available -j | node -e '+ const d = JSON.parse(require("fs").readFileSync(0)).devices+ const all = Object.entries(d).filter(([k]) => k.includes("watchOS")).flatMap(([, v]) => v)+ const w = all.filter(x => /Apple Watch/.test(x.name))+ const pick = w.find(x => /Series (9|10|11)/.test(x.name)) || w.pop()+ process.stdout.write(pick ? pick.udid : "")')+ test -n "$UDID" || { echo "::warning::no watch simulator available"; exit 1; }+ xcrun simctl boot "$UDID" || true+ xcrun simctl bootstatus "$UDID" -b+ xcrun simctl install "$UDID" "$APP"+ xcrun simctl launch "$UDID" ch.opengym.app.watchkitapp -OpenGymWatchDemo+ sleep 8+ xcrun simctl io "$UDID" screenshot build/watch-demo.png- uses: actions/upload-artifact@v6if: always()with:@@ -82,6 +107,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.pngretention-days: 7# A walk through the app in the simulator (ios/App/AppUITests): a rest that ends while the app@@ -103,6 +129,8 @@ jobs:working-directory: frontend- run: npm run build:mobile && rm -rf ios/App/App/public/exercise-mediaworking-directory: frontend+ - run: ruby ios/ci/add-watch-app.rb+ working-directory: frontend- run: ruby ios/ci/add-ui-tests.rbworking-directory: frontend- name: Run the UI tests@@ -152,6 +180,8 @@ jobs:working-directory: frontend- run: npm run build:mobileworking-directory: frontend+ - run: ruby ios/ci/add-watch-app.rb+ working-directory: frontend- name: Archive, unsignedworking-directory: frontend/ios/Apprun: |diff --git a/frontend/ios/App/Watch/Info.plist b/frontend/ios/App/Watch/Info.plistnew file mode 100644index 000000000..e6bdd6933--- /dev/null+++ b/frontend/ios/App/Watch/Info.plist@@ -0,0 +1,30 @@+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>CFBundleDevelopmentRegion</key>+ <string>en</string>+ <key>CFBundleDisplayName</key>+ <string>openGym</string>+ <key>CFBundleExecutable</key>+ <string>$(EXECUTABLE_NAME)</string>+ <key>CFBundleIdentifier</key>+ <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>+ <key>CFBundleInfoDictionaryVersion</key>+ <string>6.0</string>+ <key>CFBundleName</key>+ <string>$(PRODUCT_NAME)</string>+ <key>CFBundlePackageType</key>+ <string>APPL</string>+ <key>CFBundleShortVersionString</key>+ <string>$(MARKETING_VERSION)</string>+ <key>CFBundleVersion</key>+ <string>$(CURRENT_PROJECT_VERSION)</string>+ <key>WKApplication</key>+ <true/>+ <key>WKCompanionAppBundleIdentifier</key>+ <string>ch.opengym.app</string>+ <key>WKRunsIndependentlyOfCompanionApp</key>+ <false/>+</dict>+</plist>diff --git a/frontend/ios/App/Watch/OpenGymWatchApp.swift b/frontend/ios/App/Watch/OpenGymWatchApp.swiftnew file mode 100644index 000000000..98ed911cf--- /dev/null+++ b/frontend/ios/App/Watch/OpenGymWatchApp.swift@@ -0,0 +1,120 @@+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.+ */+@main+struct OpenGymWatchApp: App {+ @StateObject private var store = SessionStore()++ var body: some Scene {+ WindowGroup {+ RootView().environmentObject(store)+ }+ }+}++struct RootView: View {+ @EnvironmentObject var store: SessionStore++ var 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()+ } else if let end = store.restEndsAt, end > Date() {+ RestView(end: end)+ } else {+ SetView()+ }+ }+}++enum CrownTarget { case reps, weight }++struct SetView: 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 {+ 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)+ }+ Button { store.completeSet() } label: {+ Label("Done", systemImage: "checkmark")+ }+ .tint(.green)+ } 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)+ 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)+ }+ }++ 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()) } }+ )+ }+}++struct RestView: View {+ @EnvironmentObject var store: SessionStore+ let end: Date++ var 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())+ if let e = store.entry, let si = store.setIndex {+ Text("Next: \(e.name), set \(si + 1)").font(.caption2).foregroundStyle(.secondary).lineLimit(2)+ }+ Button("Skip rest") { store.skipRest() }+ }+ }+}diff --git a/frontend/ios/App/Watch/SessionStore.swift b/frontend/ios/App/Watch/SessionStore.swiftnew file mode 100644index 000000000..0537b1f05--- /dev/null+++ b/frontend/ios/App/Watch/SessionStore.swift@@ -0,0 +1,215 @@+import Foundation+import WatchConnectivity+import WatchKit++/*+ * The watch's side of a workout. The phone sends a snapshot of the running session (frontend+ * lib/watch-sync.js through ios/App/App/WatchBridgePlugin.swift); from then on the watch runs it+ * by itself, because the phone's page sleeps once the phone is locked in a pocket. A set ticked+ * here goes back as an event with transferUserInfo, which iOS delivers even when the phone app is+ * not running, and the phone applies it through its own workout screen.+ *+ * Text only: no exercise animations or pictures on the watch.+ */++struct Snapshot: Codable {+ let v: Int+ let active: ActiveWorkout?+}++struct ActiveWorkout: Codable, Equatable {+ let id: String?+ let name: String+ let unit: String+ let cur: Int+ let restSec: Double+ let rest: RestInfo?+ var entries: [Entry]+}++struct RestInfo: Codable, Equatable {+ let endsAt: Double+}++struct Entry: Codable, Equatable {+ let id: String+ let name: String+ let mode: String+ let restSec: Double?+ let last: String?+ var sets: [SetRow]+}++struct SetRow: Codable, Equatable {+ var w: Double?+ var r: Double?+ let sec: Double?+ var done: Bool+ let warmup: Bool+}++final class SessionStore: NSObject, ObservableObject, WCSessionDelegate {+ @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?++ /// 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"+ static let demoArgument = "-OpenGymWatchDemo"++ override init() {+ super.init()+ if ProcessInfo.processInfo.arguments.contains(SessionStore.demoArgument) {+ apply(json: SessionStore.demoJSON)+ } else if let saved = UserDefaults.standard.string(forKey: SessionStore.savedKey) {+ apply(json: saved)+ }+ if WCSession.isSupported() {+ WCSession.default.delegate = self+ WCSession.default.activate()+ }+ }++ /* ---------- what the views read ---------- */++ var entry: Entry? {+ guard let w = workout, w.entries.indices.contains(entryIndex) else { return nil }+ 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 })+ }++ var unit: String { workout?.unit ?? "kg" }+ var weightStep: Double { unit == "lb" ? 5 : 2.5 }++ /* ---------- snapshots from the phone ---------- */++ func apply(json: String) {+ guard let data = json.data(using: .utf8),+ let snap = try? JSONDecoder().decode(Snapshot.self, from: data) else { return }+ DispatchQueue.main.async {+ guard var next = snap.active else {+ self.workout = nil+ self.pending.removeAll()+ self.restEndsAt = nil+ return+ }+ let sameWorkout = next.id != nil && next.id == self.workout?.id+ // Ticks made here and not yet on the phone stay ticked.+ for (ei, e) in next.entries.enumerated() {+ for (si, s) in e.sets.enumerated() {+ let key = "\(e.id)#\(si)"+ if s.done { self.pending.remove(key) } else if self.pending.contains(key) { next.entries[ei].sets[si].done = true }+ }+ }+ self.workout = next+ if !sameWorkout { self.entryIndex = next.cur }+ if let rest = next.rest {+ self.startRest(until: Date(timeIntervalSince1970: rest.endsAt / 1000))+ }+ self.entryIndex = min(max(0, self.entryIndex), max(0, next.entries.count - 1))+ self.loadTargets()+ UserDefaults.standard.set(json, forKey: SessionStore.savedKey)+ }+ }++ /// The weight and reps the crown starts from: the set's own target.+ func loadTargets() {+ guard let e = entry else { return }+ let s = setIndex.map { e.sets[$0] } ?? e.sets.last+ weight = s?.w ?? 0+ reps = s?.r ?? 0+ }++ /* ---------- what the lifter does here ---------- */++ func completeSet() {+ guard var w = workout, let e = entry, let si = setIndex else { return }+ let ei = entryIndex+ w.entries[ei].sets[si].done = true+ w.entries[ei].sets[si].w = weight+ w.entries[ei].sets[si].r = reps+ pending.insert("\(e.id)#\(si)")+ workout = w+ send(event: [+ "id": UUID().uuidString,+ "type": "setDone",+ "wid": w.id ?? "",+ "exId": e.id,+ "entryIdx": ei,+ "setIdx": si,+ "w": weight,+ "r": reps,+ "at": Date().timeIntervalSince1970 * 1000,+ ])+ WKInterfaceDevice.current().play(.success)+ let rest = e.restSec ?? w.restSec+ if rest > 0 { startRest(until: Date().addingTimeInterval(rest)) }+ // 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+ }+ loadTargets()+ }++ func move(by step: Int) {+ guard let w = workout, !w.entries.isEmpty else { return }+ entryIndex = min(max(0, entryIndex + step), w.entries.count - 1)+ loadTargets()+ }++ func skipRest() {+ restTimer?.invalidate()+ restEndsAt = nil+ }++ private func startRest(until end: Date) {+ restTimer?.invalidate()+ guard end > Date() else { restEndsAt = nil; return }+ restEndsAt = end+ restTimer = Timer.scheduledTimer(withTimeInterval: end.timeIntervalSinceNow, repeats: false) { [weak self] _ in+ WKInterfaceDevice.current().play(.notification)+ DispatchQueue.main.async { self?.restEndsAt = nil }+ }+ }++ private func send(event: [String: Any]) {+ guard WCSession.isSupported(),+ let data = try? JSONSerialization.data(withJSONObject: event),+ let json = String(data: data, encoding: .utf8) else { return }+ // Queued by the system and delivered even when the phone app is not running.+ WCSession.default.transferUserInfo(["event": json])+ }++ /* ---------- WCSessionDelegate ---------- */++ func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {+ if let json = session.receivedApplicationContext["snapshot"] as? String { apply(json: json) }+ }++ func session(_ session: WCSession, didReceiveApplicationContext applicationContext: [String: Any]) {+ if let json = applicationContext["snapshot"] as? String { apply(json: json) }+ }++ func session(_ session: WCSession, didReceiveMessage message: [String: Any]) {+ if let json = message["snapshot"] as? String { apply(json: json) }+ }++ /* ---------- the demo the CI screenshot shows ---------- */++ static let demoJSON = """+ {"v":1,"active":{"id":"demo","name":"Push day","unit":"kg","cur":0,"restSec":90,"rest":null,"entries":[+ {"id":"0025","name":"Bench Press","mode":"reps","restSec":120,"last":"60 kg × 8, 60 kg × 8, 60 kg × 7","sets":[+ {"w":60,"r":8,"sec":null,"done":true,"warmup":false},{"w":62.5,"r":8,"sec":null,"done":false,"warmup":false},{"w":62.5,"r":8,"sec":null,"done":false,"warmup":false}]},+ {"id":"0426","name":"Overhead Press","mode":"reps","restSec":null,"last":null,"sets":[+ {"w":40,"r":8,"sec":null,"done":false,"warmup":false},{"w":40,"r":8,"sec":null,"done":false,"warmup":false}]}]}}+ """+}diff --git a/frontend/ios/ci/add-watch-app.rb b/frontend/ios/ci/add-watch-app.rbnew file mode 100644index 000000000..119b3cc5c--- /dev/null+++ b/frontend/ios/ci/add-watch-app.rb@@ -0,0 +1,71 @@+# Adds the Apple Watch app (ios/App/Watch) to App.xcodeproj as its own target and embeds it in the+# iPhone app (App.app/Watch), in the style of add-ui-tests.rb: the project Capacitor generated stays+# as it is in the repository, and CI runs this before every iOS build while the watch app is being+# built up. Running it twice changes nothing. Once it ships, run it once and commit the project.+#+# ruby frontend/ios/ci/add-watch-app.rb+#+# App Store Connect needs, before a signed build: the bundle id ch.opengym.app.watchkitapp (with+# HealthKit once the workout session is in) and an App Store provisioning profile for it; the+# release script then signs App.app/Watch/OpenGymWatch.app with that profile.+require 'xcodeproj'++NAME = 'OpenGymWatch'+BUNDLE_ID = 'ch.opengym.app.watchkitapp'+DIR = 'Watch'++dir = File.expand_path('../App', __dir__)+proj = Xcodeproj::Project.open(File.join(dir, 'App.xcodeproj'))+app = proj.targets.find { |t| t.name == 'App' }+abort 'no App target' unless app+if proj.targets.any? { |t| t.name == NAME }+ puts "#{NAME} is already in the project"+ exit 0+end++# A single-target watchOS app (watchOS 7 and later): a plain application built for watchOS.+watch = proj.new_target(:application, NAME, :watchos, '10.0')+group = proj.main_group.new_group(DIR, DIR)+sources = Dir.children(File.join(dir, DIR)).select { |f| f.end_with?('.swift') }.sort+watch.add_file_references(sources.map { |f| group.new_file(f) })+group.new_file('Info.plist')+entitlements = File.join(dir, DIR, "#{NAME}.entitlements")+group.new_file("#{NAME}.entitlements") if File.exist?(entitlements)++app_settings = app.build_configurations.first.build_settings+watch.build_configurations.each do |c|+ s = c.build_settings+ s['PRODUCT_NAME'] = '$(TARGET_NAME)'+ s['PRODUCT_BUNDLE_IDENTIFIER'] = BUNDLE_ID+ s['INFOPLIST_FILE'] = "#{DIR}/Info.plist"+ s['GENERATE_INFOPLIST_FILE'] = 'NO'+ s['CODE_SIGN_ENTITLEMENTS'] = "#{DIR}/#{NAME}.entitlements" if File.exist?(entitlements)+ s['CODE_SIGN_STYLE'] = 'Automatic'+ s['SWIFT_VERSION'] = '5.0'+ s['SDKROOT'] = 'watchos'+ s['WATCHOS_DEPLOYMENT_TARGET'] = '10.0'+ s['TARGETED_DEVICE_FAMILY'] = '4'+ s['SKIP_INSTALL'] = 'YES'+ s['ASSETCATALOG_COMPILER_APPICON_NAME'] = ''+ s['MARKETING_VERSION'] = app_settings['MARKETING_VERSION']+ s['CURRENT_PROJECT_VERSION'] = app_settings['CURRENT_PROJECT_VERSION']+ s['LD_RUNPATH_SEARCH_PATHS'] = ['$(inherited)', '@executable_path/Frameworks']+ s['ENABLE_PREVIEWS'] = 'NO'+end++# Built before the app, and copied into App.app/Watch, where iOS looks for the companion watch app.+app.add_dependency(watch)+embed = app.new_copy_files_build_phase('Embed Watch Content')+embed.symbol_dst_subfolder_spec = :products_directory+embed.dst_path = '$(CONTENTS_FOLDER_PATH)/Watch'+file = embed.add_file_reference(watch.product_reference, true)+file.settings = { 'ATTRIBUTES' => ['RemoveHeadersOnCopy'] }++# A scheme of its own, so CI can build and run just the watch app in a watch simulator.+scheme = Xcodeproj::XCScheme.new+scheme.add_build_target(watch)+scheme.set_launch_target(watch)+scheme.save_as(File.join(dir, 'App.xcodeproj'), NAME, true)++proj.save+puts "added #{NAME} (#{BUNDLE_ID}), embedded in App"