mycode/myApp/Keging/Shared/KegelEngine.swift
songyc macbook 32737d74fd feat(keging): Live Activity 자가 렌더링 재설계 — 앱이 정지해도 움직이는 DI/잠금화면 (실기기 4차 피드백)
- ActivityKit엔 미래 상태 예약 API가 없음을 확인(푸시 서버 없이는 국면 갱신이 앱
  런타임 의존) → 상태에 세트 전체 일정을 실어 시스템 렌더 요소로 심장을 재구성:
  국면 색 타임라인 바(하드 스톱 그라데이션) + 실시간 플레이헤드
  ProgressView(timerInterval:) + 전체 남은 시간. 플레이헤드가 걸친 색 = 지금 국면
- 국면 라벨·횟수는 앱 갱신 유지(syncCurrent 단일 진입점), stale 시 흐림
- 오디오 키퍼: 완전 무음 대신 ±2 LSB 디더 노이즈(무음 감지 정지 회피) +
  백그라운드 전환 ~30초 브리지 태스크
- 통계 타임라인 점별 시각 라벨 제거(겹침 — 시각은 오늘 기록 목록에서)
- 도움말·번역 갱신, CLAUDE.md 현행화. 시뮬: DI 백그라운드 80초+(10/20) 진행 확인

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UPmp29DQHY6Ahfss5SRopT
2026-09-02 16:26:29 +09:00

155 lines
5.6 KiB
Swift

//
// KegelEngine.swift
// Keging
//
// iOS· . onPhaseChange(·Live Activity),
// onSessionEnd( + ). .
//
import Foundation
import Combine
nonisolated enum KegelPhase: String, Codable, Hashable {
case prepare, contract, relax
var label: String {
switch self {
case .prepare: String(localized: "준비")
case .contract: String(localized: "수축")
case .relax: String(localized: "이완")
}
}
var symbolName: String {
switch self {
case .prepare: "timer"
case .contract: "arrow.down.right.and.arrow.up.left"
case .relax: "arrow.up.left.and.arrow.down.right"
}
}
}
@MainActor
final class KegelEngine: ObservableObject {
static let shared = KegelEngine()
enum State: Equatable {
case idle
case running(phase: KegelPhase, rep: Int, phaseStart: Date, phaseEnd: Date)
case finished(reps: Int)
}
@Published private(set) var state: State = .idle
private(set) var config = WorkoutConfig()
/// · ( )
private(set) var startedAt = Date()
///
/// ( , Live Activity )
private(set) var sessionStart = Date()
private var timer: Timer?
/// (phase, rep, phaseStart, phaseEnd)
var onPhaseChange: ((KegelPhase, Int, Date, Date) -> Void)?
/// (completed, )
var onSessionEnd: ((Bool, SessionRecord?) -> Void)?
var isRunning: Bool { if case .running = state { true } else { false } }
private init() {}
func start(config: WorkoutConfig) {
guard !isRunning else { return }
self.config = config
sessionStart = Date()
startedAt = sessionStart.addingTimeInterval(Double(config.prepSeconds))
applyTarget(computeTarget(at: Date()))
}
/// .
/// onPhaseChange(·Live Activity)
func resyncAfterWake() {
guard case .running = state else { return }
applyTarget(computeTarget(at: Date()))
}
/// ( )
func stop() {
guard isRunning else { return }
timer?.invalidate()
timer = nil
state = .idle
onSessionEnd?(false, nil)
}
///
func acknowledgeFinish() {
if case .finished = state { state = .idle }
}
private enum Target {
case finished
case running(KegelPhase, Int, Date, Date)
}
/// sessionStart
private func computeTarget(at now: Date) -> Target {
let prep = Double(config.prepSeconds)
let contract = Double(max(1, config.contractSeconds))
let relax = Double(max(1, config.relaxSeconds))
let cycle = contract + relax
let elapsed = now.timeIntervalSince(sessionStart)
if elapsed < prep {
return .running(.prepare, 1, sessionStart, sessionStart.addingTimeInterval(prep))
}
let exercised = elapsed - prep
let repIndex = Int(exercised / cycle) // 0
guard repIndex < config.reps else { return .finished }
let repStart = sessionStart.addingTimeInterval(prep + Double(repIndex) * cycle)
if exercised - Double(repIndex) * cycle < contract {
return .running(.contract, repIndex + 1, repStart, repStart.addingTimeInterval(contract))
}
return .running(.relax, repIndex + 1, repStart.addingTimeInterval(contract), repStart.addingTimeInterval(cycle))
}
private func applyTarget(_ target: Target) {
switch target {
case .finished:
complete()
case let .running(phase, rep, phaseStart, phaseEnd):
let changed: Bool = {
guard case let .running(currentPhase, currentRep, _, _) = state else { return true }
return currentPhase != phase || currentRep != rep
}()
state = .running(phase: phase, rep: rep, phaseStart: phaseStart, phaseEnd: phaseEnd)
if changed { onPhaseChange?(phase, rep, phaseStart, phaseEnd) }
scheduleTick(at: phaseEnd)
}
}
private func scheduleTick(at date: Date) {
timer?.invalidate()
let interval = max(0.05, date.timeIntervalSinceNow + 0.02)
timer = Timer.scheduledTimer(withTimeInterval: interval, repeats: false) { [weak self] _ in
guard let self else { return }
Task { @MainActor in
guard case .running = self.state else { return }
self.applyTarget(self.computeTarget(at: Date()))
}
}
}
private func complete() {
timer?.invalidate()
timer = nil
state = .finished(reps: config.reps)
let record = SessionRecord(
startedAt: startedAt,
reps: config.reps,
contractSeconds: config.contractSeconds,
relaxSeconds: config.relaxSeconds
)
RecordStore.shared.append(record)
onSessionEnd?(true, record)
}
}