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: clean layout like the watch's own apps, and a Smart Stack widget
Duarte Santos1ba7c09420cd
diff --git a/.github/workflows/ios.yml b/.github/workflows/ios.ymlindex 6682dc3e6..4d43d6a5e 100644--- a/.github/workflows/ios.yml+++ b/.github/workflows/ios.yml@@ -89,23 +89,28 @@ jobs:APP=build/dd/Build/Products/Debug-watchsimulator/OpenGymWatch.apptest -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"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"+ # Every screen on a small and a large watch: 41 or 42 mm, 45 or 46 mm.+ for size in small large; do+ UDID=$(xcrun simctl list devices available -j | SIZE=$size node -e '+ const d = JSON.parse(require("fs").readFileSync(0)).devices+ const all = Object.entries(d).filter(([k]) => k.includes("watchOS")).flatMap(([, v]) => v).filter(x => /Apple Watch/.test(x.name))+ const re = process.env.SIZE === "small" ? /\((40|41|42)mm\)/ : /\((44|45|46)mm\)/+ const pick = all.filter(x => re.test(x.name) && !/Ultra|SE/.test(x.name)).pop() || all.filter(x => re.test(x.name)).pop()+ process.stdout.write(pick ? pick.udid + " " + pick.name.replace(/[^A-Za-z0-9]+/g, "-") : "")')+ test -n "$UDID" || { echo "::warning::no $size watch simulator"; continue; }+ NAME=${UDID#* }; UDID=${UDID%% *}+ xcrun simctl boot "$UDID" || true+ xcrun simctl bootstatus "$UDID" -b+ xcrun simctl install "$UDID" "$APP"+ for screen in idle empty set weight rest finish; 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/$size-$screen.png"+ done+ echo "$size: $NAME" >> build/watch/devices.txt+ xcrun simctl shutdown "$UDID" || truedonels -la build/watch- uses: actions/upload-artifact@v6diff --git a/frontend/ios/App/Watch/OpenGymWatch.entitlements b/frontend/ios/App/Watch/OpenGymWatch.entitlementsindex 2ab14a262..3e17864bd 100644--- a/frontend/ios/App/Watch/OpenGymWatch.entitlements+++ b/frontend/ios/App/Watch/OpenGymWatch.entitlements@@ -6,5 +6,9 @@<true/><key>com.apple.developer.healthkit.access</key><array/>+ <key>com.apple.security.application-groups</key>+ <array>+ <string>group.ch.opengym.app</string>+ </array></dict></plist>diff --git a/frontend/ios/App/Watch/OpenGymWatchApp.swift b/frontend/ios/App/Watch/OpenGymWatchApp.swiftindex 63ec214b0..0742c7f87 100644--- a/frontend/ios/App/Watch/OpenGymWatchApp.swift+++ b/frontend/ios/App/Watch/OpenGymWatchApp.swift@@ -1,11 +1,17 @@import SwiftUI+import WidgetKit/*- * 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.+ * openGym on the Apple Watch, laid out like the watch's own apps: one primary action per screen+ * as a big round button in the middle, secondary actions small at the edges, the Digital Crown as+ * the obvious value control, black background, the accent colour only on the primary action.+ *+ * start today's workout as one big Start, the other routines in a short list below+ * set weight × reps in big rounded numerals, the round Done, the set dots; the crown turns+ * the reps (or the weight, after a tap on it), marked by the crown symbol under it+ * rest a full-screen ring around a huge countdown, +15 s and Skip as small round buttons+ * finish after the last exercise, one round button+ * Exercises are vertical pages (swipe), with the system's page indicator.*/@mainstruct OpenGymWatchApp: App {@@ -13,7 +19,10 @@ struct OpenGymWatchApp: App {var body: some Scene {WindowGroup {- RootView().environmentObject(store).tint(Theme.accent)+ RootView()+ .environmentObject(store)+ .tint(Theme.accent)+ .background(Color.black)}}}@@ -21,6 +30,9 @@ struct OpenGymWatchApp: App {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)+ static let dim = Color.white.opacity(0.14)+ /// The smallest a thing a finger has to hit may be.+ static let tap: CGFloat = 44}func formatNumber(_ v: Double) -> String {@@ -31,13 +43,60 @@ struct RootView: View {@EnvironmentObject var store: SessionStorevar body: some View {- if store.workout == nil {- IdleView()- } else if let end = store.restEndsAt, end > Date() {- RestView(end: end)- } else {- ExercisePager()+ Group {+ if store.workout == nil {+ IdleView()+ } else if let end = store.restEndsAt, end > Date() {+ RestView(end: end)+ } else {+ ExercisePager()+ }+ }+ .onChange(of: store.widgetState) { state in+ guard !store.isDemo else { return }+ state.write()+ WidgetCenter.shared.reloadAllTimelines()+ }+ }+}++/* ---------- a big round primary button ---------- */++struct RoundButton: View {+ let systemImage: String+ let label: Text+ var size: CGFloat = 76+ let action: () -> Void++ var body: some View {+ Button(action: action) {+ Image(systemName: systemImage)+ .font(.system(size: size * 0.42, weight: .bold))+ .foregroundStyle(Color.black)+ .frame(width: size, height: size)+ .background(Circle().fill(Theme.accent))}+ .buttonStyle(.plain)+ .accessibilityLabel(label)+ }+}++/// A small round secondary button at an edge: an SF Symbol on a dim disc, a 44 pt target.+struct EdgeButton: View {+ let systemImage: String+ let label: Text+ let action: () -> Void++ var body: some View {+ Button(action: action) {+ Image(systemName: systemImage)+ .font(.system(size: 17, weight: .semibold))+ .foregroundStyle(.white)+ .frame(width: Theme.tap, height: Theme.tap)+ .background(Circle().fill(Theme.dim))+ }+ .buttonStyle(.plain)+ .accessibilityLabel(label)}}@@ -49,41 +108,46 @@ struct IdleView: View {var body: some View {if let ready = store.ready, ready.today != nil || !ready.others.isEmpty {ScrollView {- VStack(alignment: .leading, spacing: 8) {+ VStack(spacing: 10) {if let today = ready.today {- Text("Today").font(.caption2).foregroundStyle(.secondary)- Button { store.start(today) } label: {- VStack(alignment: .leading, spacing: 2) {- Text(today.name)- .font(.system(.headline, design: .rounded))- .lineLimit(2)- Label("Start workout", systemImage: "play.fill")- .font(.footnote)- }- .frame(maxWidth: .infinity, alignment: .leading)- }- .buttonStyle(.borderedProminent)- .tint(Theme.accent)+ Text(today.name)+ .font(.system(.headline, design: .rounded))+ .lineLimit(2)+ .minimumScaleFactor(0.7)+ .multilineTextAlignment(.center)+ RoundButton(systemImage: "play.fill", label: Text("Start workout")) { store.start(today) }+ Text("Start workout").font(.footnote).foregroundStyle(.secondary)}- ForEach(Array(ready.others.enumerated()), id: \.offset) { pair in- Button { store.start(pair.element) } label: {- HStack {- Text(pair.element.name).lineLimit(1)- Spacer(minLength: 4)- Image(systemName: "play.fill").font(.caption2).foregroundStyle(Theme.accent)+ if !ready.others.isEmpty {+ VStack(spacing: 4) {+ ForEach(Array(ready.others.enumerated()), id: \.offset) { pair in+ Button { store.start(pair.element) } label: {+ HStack {+ Text(pair.element.name).lineLimit(1).minimumScaleFactor(0.8)+ Spacer(minLength: 4)+ Image(systemName: "play.fill").font(.caption2).foregroundStyle(.secondary)+ }+ .frame(minHeight: Theme.tap)+ .padding(.horizontal, 10)+ .background(RoundedRectangle(cornerRadius: 12).fill(Theme.dim))+ }+ .buttonStyle(.plain)}}+ .padding(.top, 6)}- HealthToggle(health: store.health)+ HealthToggle(health: store.health).padding(.top, 6)}+ .padding(.horizontal, 4)}} else {VStack(spacing: 10) {Image(systemName: "dumbbell.fill").font(.system(size: 34, weight: .semibold))- .foregroundStyle(Theme.accent)+ .foregroundStyle(.secondary)Text("No workout running").font(.headline)+ .multilineTextAlignment(.center)Text("Start one on your iPhone and it shows up here.").font(.footnote).foregroundStyle(.secondary)@@ -100,7 +164,7 @@ struct ExercisePager: View {@EnvironmentObject var store: SessionStorevar body: some View {- // Vertical pages: the Digital Crown and a vertical swipe both move between exercises.+ // Vertical pages, swiped; the crown belongs to the numbers on the page (like a volume).TabView(selection: Binding(get: { store.entryIndex }, set: { store.show(entry: $0) })) {ForEach(Array((store.workout?.entries ?? []).enumerated()), id: \.offset) { pair inExercisePage(index: pair.offset).tag(pair.offset)@@ -111,188 +175,156 @@ struct ExercisePager: View {}}-/// After the last exercise: one action, finish and save (on the phone, as its Finish and save).-struct FinishPage: View {- @EnvironmentObject var store: SessionStore- @State private var confirming = false-- var body: some View {- VStack(spacing: 10) {- Image(systemName: "flag.checkered")- .font(.system(size: 30, weight: .semibold))- .foregroundStyle(Theme.accent)- Text(store.workout?.name ?? "")- .font(.system(.headline, design: .rounded))- .lineLimit(2)- .multilineTextAlignment(.center)- Button { confirming = true } label: {- Label("Finish workout", systemImage: "checkmark")- .frame(maxWidth: .infinity)- }- .buttonStyle(.borderedProminent)- .tint(Theme.accent)- }- .padding(.horizontal, 6)- .confirmationDialog("Finish workout?", isPresented: $confirming) {- Button("Finish and save") { store.finish() }- Button("Cancel", role: .cancel) {}- }- }-}+enum CrownTarget { case reps, weight }struct ExercisePage: View {@EnvironmentObject var store: SessionStorelet index: Int- @State private var editing = false+ @State private var target: CrownTarget = SessionStore.demoScreen == "weight" ? .weight : .reps+ @FocusState private var crownFocus: Boolvar body: some View {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) {+ let current = index == store.entryIndex+ VStack(spacing: 0) {+ HStack(alignment: .top, spacing: 6) {+ if let clip = store.clips[entry.id] {+ ClipView(clip: clip).frame(width: 30, height: 30)+ }Text(entry.name)- .font(.system(.headline, design: .rounded))+ .font(.system(.footnote, design: .rounded).weight(.semibold)).lineLimit(2).minimumScaleFactor(0.75)- Spacer(minLength: 4)- VStack(alignment: .trailing, spacing: 0) {- Text("\(index + 1)/\(w.entries.count)")- .font(.caption2.monospacedDigit())- .foregroundStyle(.secondary)- HeartRateBadge(health: store.health)- }+ .frame(maxWidth: .infinity, alignment: .leading)+ HeartRateBadge(health: store.health)}- if let clip = store.clips[entry.id] {- ClipView(clip: clip).frame(height: 54)- }- SetDots(entry: entry, current: si) { store.pick(set: $0, in: index) }+ Spacer(minLength: 2)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)- }- .buttonStyle(.borderedProminent)- .tint(Theme.accent)- .disabled(index != store.entryIndex)+ let row = entry.sets[si]+ NumbersView(weight: current ? store.weight : (row.w ?? 0),+ reps: current ? store.reps : (row.r ?? 0),+ unit: w.unit, warmup: row.warmup, target: $target)+ .focusable(current)+ .focused($crownFocus)+ .digitalCrownRotation(crownBinding, from: 0, through: target == .weight ? 500 : 100,+ by: target == .weight ? store.weightStep : 1, sensitivity: .low,+ isContinuous: false, isHapticFeedbackEnabled: true)+ Spacer(minLength: 2)+ RoundButton(systemImage: "checkmark", label: Text("Done"), size: 62) { store.completeSet() }+ .disabled(!current)+ Spacer(minLength: 4)+ SetDots(entry: entry, current: si) { store.pick(set: $0, in: index) }} else {- Spacer()- Label("All sets done", systemImage: "checkmark.circle.fill")- .font(.system(.body, design: .rounded))- .foregroundStyle(Theme.accent)- Spacer()+ Image(systemName: "checkmark.circle.fill")+ .font(.system(size: 44))+ .foregroundStyle(.secondary)+ Text("All sets done").font(.footnote).foregroundStyle(.secondary)+ Spacer(minLength: 4)+ SetDots(entry: entry, current: nil) { _ in }}}- .padding(.horizontal, 6)- .sheet(isPresented: $editing) { AdjustView() }- .onAppear { if SessionStore.demoScreen == "adjust" && index == store.entryIndex { editing = true } }+ .padding(.horizontal, 4)+ .onAppear { if current { crownFocus = true } }+ .onChange(of: store.entryIndex) { ei in if ei == index { crownFocus = 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) } }+ private var crownBinding: Binding<Double> {+ Binding(+ get: { target == .weight ? store.weight : store.reps },+ set: { v in+ guard index == store.entryIndex else { return }+ if target == .weight { store.weight = max(0, v) } else { store.reps = max(0, v.rounded()) }}- Spacer(minLength: 0)- }+ )}}-struct BigNumbers: View {+/// Weight × reps in big rounded numerals. The one the crown turns carries the crown symbol under+/// it; a tap on the other hands the crown to that one.+struct NumbersView: View {let weight: Doublelet reps: Doublelet unit: Stringlet warmup: Bool+ @Binding var target: CrownTargetvar body: some View {- VStack(spacing: 0) {- if warmup {- Text("Warm-up").font(.caption2).foregroundStyle(.secondary)+ VStack(spacing: 1) {+ HStack(alignment: .firstTextBaseline, spacing: 4) {+ value(formatNumber(weight), suffix: unit, active: target == .weight) { target = .weight }+ Text(verbatim: "×").font(.system(size: 18, weight: .medium, design: .rounded)).foregroundStyle(.secondary)+ value(formatNumber(reps), suffix: nil, active: target == .reps) { target = .reps }}- 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)+ .minimumScaleFactor(0.55)+ if warmup { Text("Warm-up").font(.caption2).foregroundStyle(.secondary) }}- .frame(maxWidth: .infinity)+ }++ private func value(_ text: String, suffix: String?, active: Bool, tap: @escaping () -> Void) -> some View {+ VStack(spacing: 0) {+ HStack(alignment: .firstTextBaseline, spacing: 2) {+ Text(verbatim: text).font(.system(size: 32, weight: .semibold, design: .rounded).monospacedDigit())+ if let s = suffix { Text(verbatim: s).font(.system(size: 12, weight: .medium, design: .rounded)).foregroundStyle(.secondary) }+ }+ Image(systemName: "digitalcrown.arrow.clockwise.fill")+ .font(.system(size: 9))+ .foregroundStyle(.secondary)+ .opacity(active ? 1 : 0)+ }+ .padding(.horizontal, 4)+ .frame(minHeight: Theme.tap)+ .contentShape(Rectangle())+ .onTapGesture(perform: tap)}}-/* ---------- the crown editor ---------- */+/// 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-enum CrownTarget { case reps, weight }+ var body: some View {+ HStack(spacing: 4) {+ ForEach(Array(entry.sets.enumerated()), id: \.offset) { pair in+ let s = pair.element+ Circle()+ .fill(s.done ? Color.white : Theme.dim)+ .overlay(Circle().stroke(Color.white, lineWidth: pair.offset == current ? 1.5 : 0))+ .frame(width: s.warmup ? 6 : 9, height: s.warmup ? 6 : 9)+ .frame(width: 16, height: 16)+ .contentShape(Rectangle())+ .onTapGesture { if !s.done { pick(pair.offset) } }+ }+ }+ .accessibilityElement(children: .ignore)+ .accessibilityLabel(Text(verbatim: "\(entry.sets.filter { $0.done }.count)/\(entry.sets.count)"))+ }+}-struct AdjustView: View {+/// After the last exercise: one round button, finish and save (on the phone, as its Finish and save).+struct FinishPage: View {@EnvironmentObject var store: SessionStore- @Environment(\.dismiss) private var dismiss- @State private var target: CrownTarget = .reps+ @State private var confirming = falsevar body: some View {VStack(spacing: 8) {- // What the crown turns: reps or the weight (no segmented picker on watchOS).- HStack(spacing: 6) {- CrownChoice(title: Text("Reps"), on: target == .reps) { target = .reps }- CrownChoice(title: Text(store.unit), on: target == .weight) { target = .weight }- }- 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)+ Text(verbatim: store.workout?.name ?? "")+ .font(.system(.footnote, design: .rounded).weight(.semibold))+ .lineLimit(2)+ .multilineTextAlignment(.center)+ RoundButton(systemImage: "flag.checkered", label: Text("Finish workout")) { confirming = true }+ Text("Finish workout").font(.footnote).foregroundStyle(.secondary)+ }+ .padding(.horizontal, 6)+ .confirmationDialog("Finish workout?", isPresented: $confirming) {+ Button("Finish and save") { store.finish() }+ Button("Cancel", role: .cancel) {}}- }-- private var crownBinding: Binding<Double> {- Binding(- 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()) }- }- )}}@@ -303,35 +335,61 @@ struct RestView: View {let end: Datevar body: some View {- 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))+ ZStack {+ TimelineView(.periodic(from: .now, by: 0.25)) { ctx in+ let total = max(1, end.timeIntervalSince(store.restStartedAt ?? end.addingTimeInterval(-90)))+ let left = max(0, end.timeIntervalSince(ctx.date))+ ZStack {+ Circle().stroke(Theme.dim, lineWidth: 7)Circle().trim(from: 0, to: CGFloat(left / total))- .stroke(Theme.accent, style: StrokeStyle(lineWidth: 6, lineCap: .round))+ .stroke(Theme.accent, style: StrokeStyle(lineWidth: 7, 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)+ .padding(4)+ VStack(spacing: 2) {+ Text(timerInterval: Date()...end, countsDown: true)+ .font(.system(size: 46, weight: .semibold, design: .rounded).monospacedDigit())+ .minimumScaleFactor(0.6).lineLimit(1)+ .multilineTextAlignment(.center)+ if let e = store.entry, let si = store.setIndex {+ Text(verbatim: "\(e.name) · \(si + 1)")+ .font(.caption2)+ .foregroundStyle(.secondary)+ .lineLimit(1)+ .padding(.horizontal, 24)+ }}- HStack {- Button { store.addRest(15) } label: { Text("+15s") }- Button { store.skipRest() } label: { Label("Skip", systemImage: "forward.fill") }- .tint(Theme.accent)+ VStack {+ Spacer()+ HStack {+ EdgeButton(systemImage: "goforward.15", label: Text("+15s")) { store.addRest(15) }+ Spacer()+ EdgeButton(systemImage: "forward.end.fill", label: Text("Skip")) { store.skipRest() }+ }}- .font(.footnote)}+ .ignoresSafeArea(edges: .bottom)+ }+}++/* ---------- an exercise's animation, sent by the phone for this workout ---------- */++struct ClipView: View {+ let clip: ClipFrames++ var body: some View {+ TimelineView(.animation(minimumInterval: 1.0 / 12)) { ctx in+ let t = ctx.date.timeIntervalSinceReferenceDate.truncatingRemainder(dividingBy: max(0.1, clip.duration))+ let i = min(clip.images.count - 1, Int(t / max(0.1, clip.duration) * Double(clip.images.count)))+ Image(uiImage: clip.images[i])+ .resizable()+ .scaledToFit()+ .clipShape(RoundedRectangle(cornerRadius: 6))+ }+ .accessibilityHidden(true)}}@@ -343,10 +401,11 @@ struct HeartRateBadge: View {var body: some View {if let hr = health.heartRate {- Label("\(Int(hr.rounded()))", systemImage: "heart.fill")- .font(.caption2.monospacedDigit())- .foregroundStyle(.red)- .labelStyle(.titleAndIcon)+ HStack(spacing: 2) {+ Image(systemName: "heart.fill").font(.system(size: 9))+ Text(verbatim: "\(Int(hr.rounded()))").font(.caption2.monospacedDigit())+ }+ .foregroundStyle(.red)}}}@@ -367,41 +426,6 @@ struct HealthToggle: View {}.tint(Theme.accent).font(.footnote)- }-}--/* ---------- an exercise's animation, sent by the phone for this workout ---------- */--struct ClipView: View {- let clip: ClipFrames-- var body: some View {- TimelineView(.animation(minimumInterval: 1.0 / 12)) { ctx in- let t = ctx.date.timeIntervalSinceReferenceDate.truncatingRemainder(dividingBy: max(0.1, clip.duration))- let i = min(clip.images.count - 1, Int(t / max(0.1, clip.duration) * Double(clip.images.count)))- Image(uiImage: clip.images[i])- .resizable()- .scaledToFit()- .clipShape(RoundedRectangle(cornerRadius: 8))- }- .accessibilityHidden(true)- }-}--struct CrownChoice: View {- let title: Text- let on: Bool- let action: () -> Void-- var body: some View {- Button(action: action) {- title- .font(.footnote.weight(.semibold))- .frame(maxWidth: .infinity)- .padding(.vertical, 4)- .background(Capsule().fill(on ? Theme.accent : Color.gray.opacity(0.25)))- .foregroundStyle(on ? Color.black : Color.primary)- }- .buttonStyle(.plain)+ .frame(minHeight: Theme.tap)}}diff --git a/frontend/ios/App/Watch/SessionStore.swift b/frontend/ios/App/Watch/SessionStore.swiftindex 3aebc8811..5fe5d62b8 100644--- a/frontend/ios/App/Watch/SessionStore.swift+++ b/frontend/ios/App/Watch/SessionStore.swift@@ -129,7 +129,15 @@ final class SessionStore: NSObject, ObservableObject, WCSessionDelegate, UNUserNoverride init() {super.init()if isDemo {- apply(json: SessionStore.demoScreen == "idle" ? SessionStore.demoReadyJSON : SessionStore.demoJSON)+ if SessionStore.demoScreen != "empty" {+ apply(json: SessionStore.demoScreen == "idle" ? SessionStore.demoReadyJSON : SessionStore.demoJSON)+ }+ if SessionStore.demoScreen == "finish" {+ DispatchQueue.main.async { self.entryIndex = self.workout?.entries.count ?? 0 }+ }+ if SessionStore.demoScreen == "weight" {+ DispatchQueue.main.async { self.loadTargets() }+ }if SessionStore.demoScreen == "rest" {DispatchQueue.main.async { self.startRest(until: Date().addingTimeInterval(83), notify: false) }}@@ -184,6 +192,23 @@ final class SessionStore: NSObject, ObservableObject, WCSessionDelegate, UNUserN}var unit: String { workout?.unit ?? "kg" }++ /// What the complications and the Smart Stack widget show (WidgetState).+ var widgetState: WidgetState {+ if let w = workout {+ if let end = restEndsAt, end > Date() {+ return WidgetState(mode: "rest", title: entry?.name ?? w.name, detail: "", restEndsAt: end)+ }+ if let e = entry, let si = setIndex {+ let s = e.sets[si]+ let numbers = "\(formatNumber(s.w ?? 0)) \(w.unit) × \(formatNumber(s.r ?? 0))"+ return WidgetState(mode: "set", title: e.name, detail: numbers, restEndsAt: nil)+ }+ return WidgetState(mode: "set", title: w.name, detail: "", restEndsAt: nil)+ }+ if let today = ready?.today { return WidgetState(mode: "today", title: today.name, detail: "", restEndsAt: nil) }+ return .idle+ }var weightStep: Double { unit == "lb" ? 5 : 2.5 }/* ---------- snapshots from the phone ---------- */diff --git a/frontend/ios/App/Watch/WidgetState.swift b/frontend/ios/App/Watch/WidgetState.swiftnew file mode 100644index 000000000..6d5f0841a--- /dev/null+++ b/frontend/ios/App/Watch/WidgetState.swift@@ -0,0 +1,42 @@+import Foundation++/*+ * What the watch app shows, for its complications and the Smart Stack widget (ios/App/Watch/+ * Widgets): written by the app whenever it changes, read by the widget through the App Group.+ * Compiled into both. Plain text and numbers, no media.+ *+ * rest the rest running, until restEndsAt+ * set the set up next: exercise and weight × reps+ * today no workout running, today's planned one ready to start+ * idle nothing to show but the app+ */+struct WidgetState: Codable, Equatable {+ var mode: String+ var title: String+ var detail: String+ var restEndsAt: Date?+ var updatedAt: Date = .distantPast++ static let idle = WidgetState(mode: "idle", title: "openGym", detail: "", restEndsAt: nil)+ static let groupId = "group.ch.opengym.app"+ private static let key = "widgetState"++ static func == (a: WidgetState, b: WidgetState) -> Bool {+ a.mode == b.mode && a.title == b.title && a.detail == b.detail && a.restEndsAt == b.restEndsAt+ }++ /// The state as written, unless it is about a session long gone (the app stopped without+ /// saying so): then nothing to show, and the iPhone's Live Activity has the Smart Stack.+ static func read() -> WidgetState {+ guard let d = UserDefaults(suiteName: groupId)?.data(forKey: key),+ let s = try? JSONDecoder().decode(WidgetState.self, from: d) else { return .idle }+ if (s.mode == "set" || s.mode == "rest") && Date().timeIntervalSince(s.updatedAt) > 3 * 3600 { return .idle }+ return s+ }++ func write() {+ var s = self+ s.updatedAt = Date()+ if let d = try? JSONEncoder().encode(s) { UserDefaults(suiteName: WidgetState.groupId)?.set(d, forKey: WidgetState.key) }+ }+}diff --git a/frontend/ios/App/WatchWidgets/Info.plist b/frontend/ios/App/WatchWidgets/Info.plistnew file mode 100644index 000000000..28a376966--- /dev/null+++ b/frontend/ios/App/WatchWidgets/Info.plist@@ -0,0 +1,29 @@+<?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>XPC!</string>+ <key>CFBundleShortVersionString</key>+ <string>$(MARKETING_VERSION)</string>+ <key>CFBundleVersion</key>+ <string>$(CURRENT_PROJECT_VERSION)</string>+ <key>NSExtension</key>+ <dict>+ <key>NSExtensionPointIdentifier</key>+ <string>com.apple.widgetkit-extension</string>+ </dict>+</dict>+</plist>diff --git a/frontend/ios/App/WatchWidgets/OpenGymWatchWidgets.entitlements b/frontend/ios/App/WatchWidgets/OpenGymWatchWidgets.entitlementsnew file mode 100644index 000000000..0618d5e4c--- /dev/null+++ b/frontend/ios/App/WatchWidgets/OpenGymWatchWidgets.entitlements@@ -0,0 +1,10 @@+<?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>com.apple.security.application-groups</key>+ <array>+ <string>group.ch.opengym.app</string>+ </array>+</dict>+</plist>diff --git a/frontend/ios/App/WatchWidgets/OpenGymWidgets.swift b/frontend/ios/App/WatchWidgets/OpenGymWidgets.swiftnew file mode 100644index 000000000..10e130fbc--- /dev/null+++ b/frontend/ios/App/WatchWidgets/OpenGymWidgets.swift@@ -0,0 +1,120 @@+import SwiftUI+import WidgetKit++/*+ * openGym's complications and Smart Stack widget on the Apple Watch: the rest counting down while+ * resting, otherwise the set up next, or today's workout to start. Read from what the watch app+ * wrote (WidgetState, App Group). Text and SF Symbols only.+ *+ * The Smart Stack: high relevance only while the watch app runs a session (a rest, a set). Without+ * one this widget is quiet, so the iPhone's Live Activity for a workout running on the phone has+ * the stack instead of two cards saying the same thing.+ */+struct Entry: TimelineEntry {+ let date: Date+ let state: WidgetState++ var relevance: TimelineEntryRelevance? {+ switch state.mode {+ case "rest": return TimelineEntryRelevance(score: 100)+ case "set": return TimelineEntryRelevance(score: 60)+ case "today": return TimelineEntryRelevance(score: 10)+ default: return TimelineEntryRelevance(score: 0)+ }+ }+}++struct Provider: TimelineProvider {+ func placeholder(in context: Context) -> Entry {+ Entry(date: Date(), state: WidgetState(mode: "set", title: "Bench Press", detail: "60 kg × 8", restEndsAt: nil))+ }++ func getSnapshot(in context: Context, completion: @escaping (Entry) -> Void) {+ completion(context.isPreview ? placeholder(in: context) : Entry(date: Date(), state: WidgetState.read()))+ }++ func getTimeline(in context: Context, completion: @escaping (Timeline<Entry>) -> Void) {+ let state = WidgetState.read()+ var entries = [Entry(date: Date(), state: state)]+ // When the rest is over the widget says so by itself; the app writes the next state then.+ if state.mode == "rest", let end = state.restEndsAt, end > Date() {+ entries.append(Entry(date: end, state: WidgetState(mode: "set", title: state.title, detail: "", restEndsAt: nil)))+ }+ completion(Timeline(entries: entries, policy: .never))+ }+}++struct WidgetView: View {+ @Environment(\.widgetFamily) var family+ let entry: Entry++ var body: some View {+ let s = entry.state+ switch family {+ case .accessoryCircular:+ if s.mode == "rest", let end = s.restEndsAt, end > entry.date {+ ProgressView(timerInterval: entry.date...end, countsDown: true) {+ Image(systemName: "timer")+ } currentValueLabel: {+ Text(timerInterval: entry.date...end, countsDown: true).monospacedDigit()+ }+ .progressViewStyle(.circular)+ } else {+ ZStack {+ AccessoryWidgetBackground()+ Image(systemName: s.mode == "today" ? "play.fill" : "dumbbell.fill").font(.title3)+ }+ }+ case .accessoryInline:+ if s.mode == "rest", let end = s.restEndsAt, end > entry.date {+ Text(timerInterval: entry.date...end, countsDown: true)+ } else {+ Text(verbatim: s.detail.isEmpty ? s.title : s.detail)+ }+ case .accessoryCorner:+ Image(systemName: s.mode == "rest" ? "timer" : "dumbbell.fill")+ .font(.title3)+ .widgetLabel {+ if s.mode == "rest", let end = s.restEndsAt, end > entry.date {+ Text(timerInterval: entry.date...end, countsDown: true)+ } else {+ Text(verbatim: s.title)+ }+ }+ default:+ VStack(alignment: .leading, spacing: 2) {+ HStack(spacing: 4) {+ Image(systemName: s.mode == "rest" ? "timer" : s.mode == "today" ? "play.fill" : "dumbbell.fill")+ Text(verbatim: s.mode == "rest" ? s.title : "openGym").lineLimit(1)+ }+ .font(.caption2)+ .foregroundStyle(.secondary)+ if s.mode == "rest", let end = s.restEndsAt, end > entry.date {+ Text(timerInterval: entry.date...end, countsDown: true)+ .font(.system(.title2, design: .rounded).weight(.semibold).monospacedDigit())+ } else {+ Text(verbatim: s.title)+ .font(.system(.headline, design: .rounded))+ .lineLimit(1)+ if !s.detail.isEmpty {+ Text(verbatim: s.detail).font(.system(.body, design: .rounded).monospacedDigit()).lineLimit(1)+ }+ }+ }+ .frame(maxWidth: .infinity, alignment: .leading)+ }+ }+}++@main+struct OpenGymWidget: Widget {+ var body: some WidgetConfiguration {+ StaticConfiguration(kind: "OpenGymWorkout", provider: Provider()) { entry in+ WidgetView(entry: entry)+ .containerBackground(.black, for: .widget)+ }+ .configurationDisplayName("openGym")+ .description("Your rest, your next set, or today's workout.")+ .supportedFamilies([.accessoryRectangular, .accessoryCircular, .accessoryInline, .accessoryCorner])+ }+}diff --git a/frontend/ios/ci/add-watch-app.rb b/frontend/ios/ci/add-watch-app.rbindex 0b3a985d9..ccb4f5f01 100644--- a/frontend/ios/ci/add-watch-app.rb+++ b/frontend/ios/ci/add-watch-app.rb@@ -5,9 +5,11 @@## 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.+# App Store Connect needs, before a signed build: the bundle ids ch.opengym.app.watchkitapp+# (HealthKit, App Group group.ch.opengym.app) and ch.opengym.app.watchkitapp.widgets (App Group+# group.ch.opengym.app), an App Store provisioning profile for each; the release script+# (scripts/ios/finish-ipa.sh) signs the watch app with WATCH_PROFILE and its widget extension with+# WATCH_WIDGET_PROFILE.require 'xcodeproj'NAME = 'OpenGymWatch'@@ -68,6 +70,44 @@ embed.dst_path = '$(CONTENTS_FOLDER_PATH)/Watch'file = embed.add_file_reference(watch.product_reference, true)file.settings = { 'ATTRIBUTES' => ['RemoveHeadersOnCopy'] }+# The complications and the Smart Stack widget (ios/App/WatchWidgets), a WidgetKit extension in the+# watch app (OpenGymWatch.app/PlugIns), reading the state the app writes (Watch/WidgetState.swift,+# compiled into both) through the App Group group.ch.opengym.app.+WIDGET = 'OpenGymWatchWidgets'+WIDGET_DIR = 'WatchWidgets'+widget = proj.new_target(:app_extension, WIDGET, :watchos, '10.0')+wgroup = proj.main_group.new_group(WIDGET_DIR, WIDGET_DIR)+wsources = Dir.children(File.join(dir, WIDGET_DIR)).select { |f| f.end_with?('.swift') }.sort.map { |f| wgroup.new_file(f) }+shared = group.files.find { |f| f.path == 'WidgetState.swift' }+widget.add_file_references(wsources + [shared].compact)+wgroup.new_file('Info.plist')+wgroup.new_file("#{WIDGET}.entitlements")+widget.add_system_framework('WidgetKit')+widget.add_system_framework('SwiftUI')+widget.build_configurations.each do |c|+ s = c.build_settings+ s['PRODUCT_NAME'] = '$(TARGET_NAME)'+ s['PRODUCT_BUNDLE_IDENTIFIER'] = "#{BUNDLE_ID}.widgets"+ s['INFOPLIST_FILE'] = "#{WIDGET_DIR}/Info.plist"+ s['GENERATE_INFOPLIST_FILE'] = 'NO'+ s['CODE_SIGN_ENTITLEMENTS'] = "#{WIDGET_DIR}/#{WIDGET}.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['APPLICATION_EXTENSION_API_ONLY'] = 'YES'+ 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', '@executable_path/../../Frameworks']+end+watch.add_dependency(widget)+wembed = watch.new_copy_files_build_phase('Embed Foundation Extensions')+wembed.symbol_dst_subfolder_spec = :plug_ins+wfile = wembed.add_file_reference(widget.product_reference, true)+wfile.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.newscheme.add_build_target(watch)diff --git a/scripts/ios/finish-ipa.sh b/scripts/ios/finish-ipa.shindex dc483ae43..4a3005045 100755--- a/scripts/ios/finish-ipa.sh+++ b/scripts/ios/finish-ipa.sh@@ -12,6 +12,7 @@# scripts/ios/finish-ipa.sh <App-unsigned.ipa> <dist.p12> <p12-password-file> <profile.mobileprovision> [out.ipa]# EXT_PROFILE=<extension.mobileprovision> ... once the IPA carries the asset pack downloader# WATCH_PROFILE=<watch.mobileprovision> ... once the IPA carries the Apple Watch app+# WATCH_WIDGET_PROFILE=<widget.mobileprovision> once the watch app carries its widget## Before: the phone build with the app's animations, from the same commit as the IPA:# cd frontend && VITE_CLIP_EXT=webp APP_MEDIA_DIR=/mnt/backup-hdd/opengym-media/build-appwebp npm run build:mobile@@ -105,6 +106,24 @@ plistlib.dump(e, open(sys.argv[2], 'wb'))print('watch profile:', p['Name'], '| expires', p['ExpirationDate'])PYWATCH_SIGN=(--entitlements-xml-file "Watch/OpenGymWatch.app/OpenGymWatch:$WORK/watch-entitlements.plist")+ # Its complications / Smart Stack widget (OpenGymWatch.app/PlugIns), with its own profile.+ WIDGET="$WATCH/PlugIns/OpenGymWatchWidgets.appex"+ if [ -d "$WIDGET" ]; then+ [ -n "${WATCH_WIDGET_PROFILE:-}" ] || { echo "the watch app carries its widget: set WATCH_WIDGET_PROFILE to its App Store profile" >&2; exit 1; }+ cp "$WATCH_WIDGET_PROFILE" "$WIDGET/embedded.mobileprovision"+ openssl smime -inform der -verify -noverify -in "$WATCH_WIDGET_PROFILE" -out "$WORK/widget-profile.plist" 2>/dev/null+ python3 - "$WORK/widget-profile.plist" "$WORK/widget-entitlements.plist" <<'PY'+import plistlib, sys+p = plistlib.load(open(sys.argv[1], 'rb'))+e = dict(p['Entitlements'])+e['get-task-allow'] = False+assert e['application-identifier'].endswith('.ch.opengym.app.watchkitapp.widgets'), e['application-identifier']+assert 'group.ch.opengym.app' in e.get('com.apple.security.application-groups', []), 'the widget profile has no App Group'+plistlib.dump(e, open(sys.argv[2], 'wb'))+print('watch widget profile:', p['Name'], '| expires', p['ExpirationDate'])+PY+ WATCH_SIGN+=(--entitlements-xml-file "Watch/OpenGymWatch.app/PlugIns/OpenGymWatchWidgets.appex/OpenGymWatchWidgets:$WORK/widget-entitlements.plist")+ fifi"$RCODESIGN" sign --p12-file "$P12" --p12-password-file "$P12PASS" \