Add per-routine target heart rate with live in-run indicator
Endurance routines (HIIT, cardio, cycling) can carry an optional target bpm (RoutineDocument.targetHeartRate, not schema-bumped — same preference-field rationale as restSeconds/autoAdvance), snapshotted onto the WorkoutDocument at plan time like the other pacing fields. During a run, the watch streams its live HR sample to the phone over a new best-effort liveHeartRate message — deliberately outside the LiveProgress machinery (no version bump, no staging/retry; a gauge, not a record), throttled to changed-bpm-or-10s in the watch bridge. LiveRunState holds the sample with a 30s staleness auto-clear so a dead stream never shows a frozen number. Both run screens show the reading only when the run carries a target: the phone's ExerciseProgressView as a top pill, the watch's in the top-trailing toolbar slot, each tinted by a shared ±5 bpm HeartRateBand with an arrow cue to push harder (low) or ease off (high) — e.g. dialing in a treadmill incline to hold a steady effort. Claude-Session: https://claude.ai/code/session_01Y7ZhkCYWNiTSAFhFCGnJ8n
This commit is contained in:
@@ -34,6 +34,26 @@ final class LiveRunState {
|
||||
return c
|
||||
}
|
||||
|
||||
/// Latest live heart-rate sample forwarded by the watch (bpm), or `nil` when none is
|
||||
/// fresh. Device-level, not run-scoped — it's the wearer's pulse. Auto-clears after
|
||||
/// `hrStaleAfter` without a new sample, so the UI never shows a frozen number after
|
||||
/// the watch stops sending (session ended, unreachable).
|
||||
private(set) var heartRate: Double?
|
||||
|
||||
private var heartRateExpiry: Task<Void, Never>?
|
||||
private static let hrStaleAfter: Duration = .seconds(30)
|
||||
|
||||
/// Apply an incoming heart-rate sample and (re)arm its staleness expiry.
|
||||
func applyHeartRate(_ bpm: Double) {
|
||||
heartRate = bpm
|
||||
heartRateExpiry?.cancel()
|
||||
heartRateExpiry = Task { [weak self] in
|
||||
try? await Task.sleep(for: Self.hrStaleAfter)
|
||||
guard !Task.isCancelled else { return }
|
||||
self?.heartRate = nil
|
||||
}
|
||||
}
|
||||
|
||||
/// Apply an incoming frame, dropping a stale (or redelivered) one for the same run.
|
||||
func apply(_ frame: LiveProgress) {
|
||||
if let c = current, c.logID == frame.logID, !frame.isNewer(than: c) { return }
|
||||
|
||||
@@ -267,6 +267,10 @@ final class PhoneConnectivityBridge: NSObject {
|
||||
if let logID = dict[WCPayload.lpLogIDKey] as? String {
|
||||
Task { @MainActor in self.liveRunState.end(logID: logID) }
|
||||
}
|
||||
case WCPayload.liveHeartRateType:
|
||||
if let sample = WCPayload.decodeLiveHeartRate(dict) {
|
||||
Task { @MainActor in self.liveRunState.applyHeartRate(sample.bpm) }
|
||||
}
|
||||
default:
|
||||
break
|
||||
}
|
||||
|
||||
@@ -36,7 +36,8 @@ enum WorkoutStarter {
|
||||
createdAt: startDate,
|
||||
updatedAt: startDate,
|
||||
logs: logs,
|
||||
restSeconds: routine.restSeconds, autoAdvance: routine.autoAdvance
|
||||
restSeconds: routine.restSeconds, autoAdvance: routine.autoAdvance,
|
||||
targetHeartRate: routine.targetHeartRate
|
||||
)
|
||||
|
||||
await sync.save(workout: doc)
|
||||
|
||||
@@ -32,6 +32,8 @@ struct RoutineAddEditView: View {
|
||||
@State private var autoAdvance: Bool = false
|
||||
@State private var restOverrideEnabled: Bool = false
|
||||
@State private var restSecondsValue: Int = 45
|
||||
@State private var targetHREnabled: Bool = false
|
||||
@State private var targetHRValue: Int = 135
|
||||
@State private var showingIconPicker: Bool = false
|
||||
@State private var showingDeleteConfirmation: Bool = false
|
||||
|
||||
@@ -48,6 +50,8 @@ struct RoutineAddEditView: View {
|
||||
_autoAdvance = State(initialValue: routine.autoAdvance ?? false)
|
||||
_restOverrideEnabled = State(initialValue: routine.restSeconds != nil)
|
||||
_restSecondsValue = State(initialValue: routine.restSeconds ?? 45)
|
||||
_targetHREnabled = State(initialValue: routine.targetHeartRate != nil)
|
||||
_targetHRValue = State(initialValue: routine.targetHeartRate ?? 135)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -136,6 +140,26 @@ struct RoutineAddEditView: View {
|
||||
Text("Auto-Advance flows from one exercise to the next with a rest between, so you can run the whole routine hands-free. Custom Rest Time sets this routine's rest — used between sets, and between exercises when auto-advancing; otherwise the Settings default applies.")
|
||||
}
|
||||
|
||||
// Only endurance types get a target — a strength set's HR swings by design.
|
||||
if activityType.supportsHeartRateTarget {
|
||||
Section {
|
||||
Toggle("Target Heart Rate", isOn: $targetHREnabled)
|
||||
if targetHREnabled {
|
||||
Stepper(value: $targetHRValue, in: 80...200, step: 5) {
|
||||
HStack {
|
||||
Text("Target")
|
||||
Spacer()
|
||||
Text("\(targetHRValue) bpm").foregroundColor(.secondary)
|
||||
}
|
||||
}
|
||||
}
|
||||
} header: {
|
||||
Text("Heart Rate")
|
||||
} footer: {
|
||||
Text("During a run, the exercise screen shows your live heart rate from the watch with a cue to ease off or push harder — useful for holding a steady effort, like dialing in a treadmill incline.")
|
||||
}
|
||||
}
|
||||
|
||||
if let routine = routine {
|
||||
Section(header: Text("Exercises")) {
|
||||
NavigationLink {
|
||||
@@ -205,6 +229,9 @@ struct RoutineAddEditView: View {
|
||||
doc.activityType = activityType.rawValue
|
||||
doc.restSeconds = restOverrideEnabled ? restSecondsValue : nil
|
||||
doc.autoAdvance = autoAdvance ? true : nil
|
||||
// Cleared when the type no longer supports a target (the section hides).
|
||||
doc.targetHeartRate = activityType.supportsHeartRateTarget && targetHREnabled
|
||||
? targetHRValue : nil
|
||||
doc.updatedAt = Date()
|
||||
Task { await sync.save(routine: doc) }
|
||||
} else {
|
||||
@@ -222,7 +249,9 @@ struct RoutineAddEditView: View {
|
||||
exercises: [],
|
||||
activityType: activityType.rawValue,
|
||||
restSeconds: restOverrideEnabled ? restSecondsValue : nil,
|
||||
autoAdvance: autoAdvance ? true : nil
|
||||
autoAdvance: autoAdvance ? true : nil,
|
||||
targetHeartRate: activityType.supportsHeartRateTarget && targetHREnabled
|
||||
? targetHRValue : nil
|
||||
)
|
||||
Task { await sync.save(routine: doc) }
|
||||
}
|
||||
|
||||
@@ -30,6 +30,10 @@ struct ExerciseProgressView: View {
|
||||
@Environment(\.dismiss) private var dismiss
|
||||
@Environment(\.verticalSizeClass) private var verticalSizeClass
|
||||
|
||||
/// Live watch-forwarded heart rate (see `LiveRunState.heartRate`) — drives the
|
||||
/// target-HR pill when this run carries a `targetHeartRate`.
|
||||
@Environment(LiveRunState.self) private var liveRun
|
||||
|
||||
|
||||
/// The shared working workout document owned by the parent list. We mutate the
|
||||
/// matching log in place and ask the parent to persist each change — driving the UI
|
||||
@@ -391,6 +395,9 @@ struct ExerciseProgressView: View {
|
||||
.padding(.bottom, 8)
|
||||
}
|
||||
}
|
||||
.overlay(alignment: .top) {
|
||||
heartRatePill
|
||||
}
|
||||
|
||||
// Bottom half: the looping form-guide figure. Shows the *next* exercise while
|
||||
// resting between exercises (a live preview of what's coming up), otherwise this
|
||||
@@ -731,6 +738,33 @@ struct ExerciseProgressView: View {
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Live heart rate vs. target
|
||||
|
||||
/// Live heart rate against this run's target (cardio routines only): the bpm the
|
||||
/// watch is streaming, tinted by band, with a cue to ease off (arrow down) or push
|
||||
/// harder (arrow up) — how you dial in a treadmill incline from a propped phone.
|
||||
/// Renders nothing unless the run carries a target *and* a fresh sample exists, so
|
||||
/// it has zero footprint on strength runs or when the watch isn't active.
|
||||
@ViewBuilder
|
||||
private var heartRatePill: some View {
|
||||
if let target = doc.targetHeartRate, let bpm = liveRun.heartRate {
|
||||
let band = HeartRateBand(bpm: bpm, target: target)
|
||||
HStack(spacing: 6) {
|
||||
Image(systemName: "heart.fill")
|
||||
Text("\(Int(bpm.rounded()))")
|
||||
.monospacedDigit()
|
||||
Image(systemName: band.cueSymbol)
|
||||
}
|
||||
.font(.subheadline.weight(.semibold))
|
||||
.foregroundStyle(band.tint)
|
||||
.padding(.horizontal, 14)
|
||||
.padding(.vertical, 7)
|
||||
.background(.quaternary.opacity(0.5), in: Capsule())
|
||||
.padding(.top, 6)
|
||||
.animation(.easeInOut(duration: 0.3), value: band)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Adjust the last set's entry
|
||||
|
||||
/// The just-completed set's recorded entry, shown on the rest and finish pages
|
||||
@@ -1119,6 +1153,27 @@ private enum WorkoutHaptic {
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Heart-rate band presentation
|
||||
|
||||
private extension HeartRateBand {
|
||||
/// The correction cue: below target → push harder (up), above → ease off (down).
|
||||
var cueSymbol: String {
|
||||
switch self {
|
||||
case .low: "arrow.up"
|
||||
case .inRange: "checkmark"
|
||||
case .high: "arrow.down"
|
||||
}
|
||||
}
|
||||
|
||||
var tint: Color {
|
||||
switch self {
|
||||
case .low: .blue
|
||||
case .inRange: .green
|
||||
case .high: .orange
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Phase Colors
|
||||
|
||||
private extension Color {
|
||||
|
||||
Reference in New Issue
Block a user