diff --git a/PulseLoop/App/AppTheme.swift b/PulseLoop/App/AppTheme.swift index 8ffa0682..9ffa27f7 100644 --- a/PulseLoop/App/AppTheme.swift +++ b/PulseLoop/App/AppTheme.swift @@ -27,6 +27,7 @@ enum AppRoute: Hashable { case settingsPrivacyData case settingsAbout case settingsNutrition + case settingsCircadian case nutrition case mealDetail(UUID) case pairing @@ -78,6 +79,8 @@ enum PulseColors { static let calories = Color(hex: "#FF8A4C") static let distance = Color(hex: "#4DA3FF") static let readiness = Color(hex: "#D6FF65") + /// Circadian drift (today vs. usual) — gold, distinct from the violet sleep hue it sits beside. + static let rhythm = Color(hex: "#FFD166") static let battery = Color(hex: "#A7F3D0") // Colmi R02 metrics static let stress = Color(hex: "#FF8A4C") diff --git a/PulseLoop/Coach/Notifications/CoachNotificationDelegate.swift b/PulseLoop/Coach/Notifications/CoachNotificationDelegate.swift index e55bf35b..c0f758ac 100644 --- a/PulseLoop/Coach/Notifications/CoachNotificationDelegate.swift +++ b/PulseLoop/Coach/Notifications/CoachNotificationDelegate.swift @@ -12,17 +12,38 @@ final class CoachNavigation { /// Drives the Coach sheet. Coach is no longer a tab, so all entry points /// (summary-card tap, notification deep-link, header button) set this true. var showCoach = false + /// A question to ask in a fresh chat as soon as the coach opens (e.g. a prompt chip on the + /// circadian sheet). `CoachView` sends it and clears it. + var pendingPrompt: String? + /// Facts sent to the model alongside `pendingPrompt` but not shown in the chat bubble. + var pendingPromptContext: String? /// Open the coach on a specific conversation (deep link). func open(_ conversationId: UUID) { requestedConversationId = conversationId + clearPendingPrompt() showCoach = true } + /// Open the coach on a new chat and ask `prompt` straight away. `context` gives the model + /// the on-screen facts the question is about without cluttering the visible message. + func ask(_ prompt: String, context: String? = nil) { + requestedConversationId = nil + pendingPrompt = prompt + pendingPromptContext = context + showCoach = true + } + + func clearPendingPrompt() { + pendingPrompt = nil + pendingPromptContext = nil + } + /// Open the coach with no specific conversation (e.g. the floating bubble). /// Clears any prior deep-link id so it doesn't reopen a stale thread. func openRoot() { requestedConversationId = nil + clearPendingPrompt() showCoach = true } } diff --git a/PulseLoop/Coach/ViewModels/CoachViewModel.swift b/PulseLoop/Coach/ViewModels/CoachViewModel.swift index d722a03c..a07ecd7c 100644 --- a/PulseLoop/Coach/ViewModels/CoachViewModel.swift +++ b/PulseLoop/Coach/ViewModels/CoachViewModel.swift @@ -42,7 +42,8 @@ final class CoachViewModel { conversationId: UUID, context: ModelContext, attachments: [CoachAttachmentRef] = [], - coordinator: RingSyncCoordinator? = nil + coordinator: RingSyncCoordinator? = nil, + hiddenContext: String? = nil ) async { let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines) // Allow image-only sends: require either text or an attachment. @@ -79,8 +80,10 @@ final class CoachViewModel { foodClient: flags.nutritionContextEnabled ? OpenFoodFactsClient() : nil) ) + // `hiddenContext` rides along to the model only: the stored bubble stays the user's own words. + let modelText = hiddenContext.map { "\(trimmed)\n\n[Context from the app: \($0)]" } ?? trimmed let result = await orchestrator.runTurn( - userText: trimmed, + userText: modelText, packet: packet, recentMessages: recent, userImages: userImages diff --git a/PulseLoop/DesignSystem/CircadianDial.swift b/PulseLoop/DesignSystem/CircadianDial.swift new file mode 100644 index 00000000..217ee0cb --- /dev/null +++ b/PulseLoop/DesignSystem/CircadianDial.swift @@ -0,0 +1,294 @@ +import SwiftUI + +/// The circadian dial: a thick track for the day, a node at each event's usual time, and a gold +/// bar from each node showing how far the selected period drifted (outward = later, inward = +/// earlier, length = minutes). Workouts are a green band at the time they happened. +/// +/// One view draws both shapes — the Sleep-page tile's semicircle and the detail sheet's full +/// 24-hour circle — from the same layout. Everything scales with the width it is given, so it +/// holds its proportions from the narrowest to the widest iPhone. +struct CircadianDial: View { + let snapshot: CircadianSnapshot + var shape: CircadianDialGeometry.Shape = .semicircle + + @Environment(\.accessibilityReduceMotion) private var reduceMotion + /// 0 → 1 as the drift bars and their labels draw in. + @State private var reveal: CGFloat = 0 + + private var aspectRatio: CGFloat { + shape == .semicircle + ? CircadianDialLayout.semicircleSize.width / CircadianDialLayout.semicircleSize.height + : CircadianDialLayout.fullSize.width / CircadianDialLayout.fullSize.height + } + + var body: some View { + GeometryReader { proxy in + let layout = CircadianDialLayout(width: proxy.size.width, shape: shape, snapshot: snapshot) + ZStack { + track(layout) + ForEach(Array(layout.night.enumerated()), id: \.offset) { _, piece in + arc(layout, piece) + .stroke(PulseColors.accent.opacity(0.65), style: StrokeStyle(lineWidth: layout.trackWidth, lineCap: .round)) + } + ForEach(layout.spans) { span in + ForEach(Array(span.arcs.enumerated()), id: \.offset) { _, piece in + arc(layout, piece) + .stroke(PulseColors.success, style: StrokeStyle(lineWidth: layout.trackWidth, lineCap: .butt)) + } + } + ForEach(layout.hourLabels, id: \.text) { label in + Text(label.text) + .font(PulseFont.micro) + .foregroundStyle(PulseColors.textMuted) + .position(label.position) + } + ForEach(layout.markers) { marker in + if let start = marker.barStart, let end = marker.barEnd { + Path { path in + path.move(to: start) + path.addLine(to: end) + } + .trim(from: 0, to: reveal) + .stroke(PulseColors.rhythm, style: StrokeStyle(lineWidth: layout.barWidth, lineCap: .round)) + .shadow(color: PulseColors.rhythm.opacity(0.5), radius: 4 * layout.scale) + } + } + ForEach(layout.markers) { marker in + node(marker, layout) + } + ForEach(layout.spans) { span in + Image(systemName: span.workout.category.symbol) + .font(.system(size: 11 * layout.scale, weight: .semibold)) + .foregroundStyle(PulseColors.success) + .position(span.iconPosition) + } + ForEach(layout.markers) { marker in + if let label = marker.label { + Text(label) + .font(.system(size: layout.labelFontSize, weight: .semibold)) + .monospacedDigit() + .foregroundStyle(PulseColors.rhythm) + .fixedSize() + .position(marker.labelPosition) + .opacity(reveal) + } + } + summary(layout) + } + } + .aspectRatio(aspectRatio, contentMode: .fit) + .onAppear { + if reduceMotion { + reveal = 1 + } else { + withAnimation(.snappy(duration: 0.55).delay(0.15)) { reveal = 1 } + } + } + // The card or sheet that hosts the dial describes it in words. + .accessibilityHidden(true) + } + + @ViewBuilder + private func track(_ layout: CircadianDialLayout) -> some View { + let style = StrokeStyle(lineWidth: layout.trackWidth, lineCap: .round) + if shape == .semicircle { + arc(layout, (startAngle: .pi, sweep: .pi)).stroke(PulseColors.elevated, style: style) + } else { + arc(layout, (startAngle: 0, sweep: 2 * .pi)).stroke(PulseColors.elevated, style: style) + } + } + + /// An arc going forward in time. SwiftUI's y-down space makes `clockwise: false` the + /// direction of increasing angle, which is clockwise on screen. + private func arc(_ layout: CircadianDialLayout, _ piece: (startAngle: Double, sweep: Double)) -> Path { + Path { path in + path.addArc( + center: layout.center, radius: layout.radius, + startAngle: .radians(piece.startAngle), endAngle: .radians(piece.startAngle + piece.sweep), + clockwise: false) + } + } + + private func node(_ marker: CircadianDialLayout.Marker, _ layout: CircadianDialLayout) -> some View { + Circle() + .fill(PulseColors.cardSoft) + .overlay(Circle().stroke(Color.white.opacity(0.3), lineWidth: 1)) + .overlay( + Image(systemName: marker.anchor.kind.symbol) + .font(.system(size: layout.nodeRadius * 1.02, weight: .semibold)) + .foregroundStyle(marker.anchor.kind.isMeal ? PulseColors.textPrimary.opacity(0.85) : PulseColors.sleep) + ) + .frame(width: layout.nodeRadius * 2, height: layout.nodeRadius * 2) + .position(marker.position) + } + + private func summary(_ layout: CircadianDialLayout) -> some View { + VStack(spacing: 2) { + Text(snapshot.headline) + .font(PulseFont.number(20 * min(layout.scale, 1.1))) + .foregroundStyle(PulseColors.textPrimary) + .lineLimit(1) + .minimumScaleFactor(0.7) + if !snapshot.subline.isEmpty { + Text(snapshot.subline) + .font(PulseFont.caption) + .foregroundStyle(PulseColors.textSecondary) + .lineLimit(2) + .minimumScaleFactor(0.8) + .multilineTextAlignment(.center) + } + } + .frame(width: layout.summaryWidth) + .position(layout.summaryCenter) + } +} + +/// Everything the dial draws, resolved to points for a given width. Pure layout — no drawing — +/// so the placement rules (spreading close nodes, dropping overlapping labels, keeping a +/// workout icon clear of a drift bar) live in one place. +struct CircadianDialLayout { + /// The proportions the dial was designed at; every measure scales from these. + static let semicircleSize = CGSize(width: 326, height: 168) + static let fullSize = CGSize(width: 358, height: 340) + + /// Points of drift bar per minute off usual, and the longest a bar grows (about an hour). + static let barPointsPerMinute: CGFloat = 0.36 + static let maxBarLength: CGFloat = 22 + /// Below this the event was on time: no bar at all. + static let minBarMinutes: Double = 5 + + struct Marker: Identifiable { + let anchor: CircadianAnchor + let position: CGPoint + let barStart: CGPoint? + let barEnd: CGPoint? + var label: String? + let labelPosition: CGPoint + var id: String { anchor.id } + } + + struct Span: Identifiable { + let workout: CircadianWorkout + let arcs: [(startAngle: Double, sweep: Double)] + let iconPosition: CGPoint + var id: Int { workout.id } + } + + let scale: CGFloat + let center: CGPoint + let radius: CGFloat + let trackWidth: CGFloat + let nodeRadius: CGFloat + let barWidth: CGFloat + let labelFontSize: CGFloat + let summaryCenter: CGPoint + let summaryWidth: CGFloat + private(set) var markers: [Marker] = [] + private(set) var spans: [Span] = [] + private(set) var night: [(startAngle: Double, sweep: Double)] = [] + private(set) var hourLabels: [(text: String, position: CGPoint)] = [] + + init(width: CGFloat, shape: CircadianDialGeometry.Shape, snapshot: CircadianSnapshot) { + let geometry = CircadianDialGeometry(shape: shape) + let semicircle = shape == .semicircle + let s = width / (semicircle ? Self.semicircleSize.width : Self.fullSize.width) + scale = s + center = CGPoint(x: width / 2, y: (semicircle ? 160 : 170) * s) + radius = (semicircle ? 110 : 112) * s + trackWidth = (semicircle ? 12 : 14) * s + nodeRadius = (semicircle ? 9 : 10) * s + barWidth = 4.5 * s + labelFontSize = 11 * min(max(s, 1), 1.15) + summaryCenter = semicircle ? CGPoint(x: width / 2, y: center.y - 24 * s) : center + summaryWidth = (semicircle ? 148 : 136) * s + + let pointsPerMinute = radius * CGFloat(geometry.sweepPerMinute) + let c = center, r = radius + func point(_ minutes: Double, _ distance: CGFloat) -> CGPoint { + geometry.point(minutes, radius: distance, center: c) + } + + if let window = snapshot.sleepWindow { + night = geometry.arcs(from: window.bed, to: window.wake) + } + + // Nodes, nudged apart where two events sit too close to read. + let minGap = Double((nodeRadius * 2 + 3 * s) / pointsPerMinute) + let placed = CircadianDialGeometry.spread(snapshot.anchors.map(\.displayMinutes), minGap: minGap) + let barGap = nodeRadius + 3 * s + var built: [Marker] = [] + for (anchor, minutes) in zip(snapshot.anchors, placed) { + var barStart: CGPoint?, barEnd: CGPoint?, label: String? + var outward: CGFloat = 0 + if let delta = anchor.deltaMinutes, abs(delta) >= Self.minBarMinutes { + let length = min(max(CGFloat(abs(delta)) * Self.barPointsPerMinute, 3), Self.maxBarLength) * s + let sign: CGFloat = delta > 0 ? 1 : -1 + barStart = point(minutes, r + sign * barGap) + barEnd = point(minutes, r + sign * (barGap + length)) + if delta > 0 { outward = length } + // The tile keeps labels to what matters; the full dial has room for all of them. + let threshold: Double = (semicircle && anchor.kind.isMeal) ? CircadianEngine.driftThreshold : 10 + if abs(delta) >= threshold { label = CircadianFormat.signed(delta) } + } + // Labels always sit outside the track, so the middle stays clear for the headline. + // Text is wider than it is tall, so it needs more room where the bar runs sideways. + let angle = geometry.screenAngle(minutes) + let clearance = (5 + 17 * CGFloat(abs(cos(angle))) + 8 * CGFloat(abs(sin(angle)))) * s + var labelPoint = point(minutes, r + barGap + outward + clearance) + labelPoint.x = min(max(labelPoint.x, 18 * s), width - 18 * s) + labelPoint.y = max(labelPoint.y, 8 * s) + built.append(Marker(anchor: anchor, position: point(minutes, r), barStart: barStart, barEnd: barEnd, + label: label, labelPosition: labelPoint)) + } + // Drop labels that would collide: wake and bed win, then the biggest drift. + let priority = built.indices + .filter { built[$0].label != nil } + .sorted { a, b in + let (x, y) = (built[a].anchor, built[b].anchor) + if x.kind.isMeal != y.kind.isMeal { return !x.kind.isMeal } + return abs(x.deltaMinutes ?? 0) > abs(y.deltaMinutes ?? 0) + } + let labelSize = CGSize(width: 38 * s, height: 16 * s) + let rects = priority.map { index in + let p = built[index].labelPosition + return CGRect(x: p.x - labelSize.width / 2, y: p.y - labelSize.height / 2, width: labelSize.width, height: labelSize.height) + } + for (index, keep) in zip(priority, CircadianDialGeometry.keepLabels(rects)) where !keep { + built[index].label = nil + } + markers = built + + // Workout bands, each wide enough to see, with the icon on whichever side is clear. + let minSpanMinutes = Double(6 * s / pointsPerMinute) + let outerOffset = trackWidth / 2 + 11 * s + spans = snapshot.workouts.map { workout in + let duration = max(workout.durationMinutes, minSpanMinutes) + let middle = workout.startMinutes + duration / 2 + let outside = point(middle, r + outerOffset) + let inside = point(middle, r - outerOffset) + func crowded(_ candidate: CGPoint, outwardSide: Bool) -> Bool { + zip(snapshot.anchors, built).contains { anchor, marker in + guard let delta = anchor.deltaMinutes, let end = marker.barEnd, (delta > 0) == outwardSide else { return false } + return hypot(end.x - candidate.x, end.y - candidate.y) < 20 * s + || hypot(marker.labelPosition.x - candidate.x, marker.labelPosition.y - candidate.y) < 20 * s && marker.label != nil + } + } + let useInside = crowded(outside, outwardSide: true) && !crowded(inside, outwardSide: false) + return Span( + workout: workout, + arcs: geometry.arcs(from: workout.startMinutes, to: workout.startMinutes + duration), + iconPosition: useInside ? inside : outside) + } + + if !semicircle { + let labelRadius = r - trackWidth / 2 - 21 * s + hourLabels = [("12 PM", 720.0), ("6 PM", 1080.0), ("12 AM", 0.0), ("6 AM", 360.0)] + .map { text, minutes in (text: text, position: point(minutes, labelRadius)) } + // An inward drift bar or a workout icon can land on an hour label; they win. + .filter { label in + let taken = built.compactMap(\.barEnd) + spans.map(\.iconPosition) + return !taken.contains { hypot($0.x - label.position.x, $0.y - label.position.y) < 24 * s } + } + } + } +} diff --git a/PulseLoop/Persistence/SeedData.swift b/PulseLoop/Persistence/SeedData.swift index 7de63570..9e5415e5 100644 --- a/PulseLoop/Persistence/SeedData.swift +++ b/PulseLoop/Persistence/SeedData.swift @@ -128,7 +128,9 @@ enum SeedData { let workouts: [SeedWorkout] = [ SeedWorkout(offset: 0, type: "run", minutes: 38, distance: 6100, calories: 330, origin: (40.4443, -79.9436)), // CMU / Pittsburgh SeedWorkout(offset: -1, type: "walk", minutes: 52, distance: 4200, calories: 210, origin: (40.4406, -79.9959)), + SeedWorkout(offset: -2, type: "gym", minutes: 50, distance: 0, calories: 300, origin: nil), SeedWorkout(offset: -3, type: "cycle", minutes: 64, distance: 18400, calories: 460, origin: (40.4612, -79.9249)), + SeedWorkout(offset: -4, type: "run", minutes: 35, distance: 5200, calories: 296, origin: nil), // treadmill SeedWorkout(offset: -6, type: "gym", minutes: 45, distance: 0, calories: 280, origin: nil), SeedWorkout(offset: -10, type: "run", minutes: 41, distance: 7300, calories: 372, origin: (40.4280, -79.9420)) ] @@ -184,6 +186,18 @@ enum SeedData { } /// One demo meal to insert. + /// One recurring meal for the demo's month of history: a base time, how far it wanders, + /// and how often a day skips it. + private struct MealHabit { + let type: MealType + let hour: Int + let minute: Int + let spread: Int + let skipEvery: Int + let names: [String] + let kcal: Double + } + private struct MealSeed { let dayOffset: Int let hour: Int @@ -196,7 +210,8 @@ enum SeedData { let source: MealEntrySource } - /// Demo meals for today + yesterday. Dormant until the nutrition feature is enabled in Settings. + /// Demo meals: named entries for today + yesterday plus a month of history. Dormant until the + /// nutrition feature is enabled in Settings. @MainActor private static func seedDemoMeals(_ context: ModelContext, calendar: Calendar, now: Date) { let seeds: [MealSeed] = [ @@ -223,6 +238,32 @@ enum SeedData { source: seed.source )) } + + // A month of earlier meals so the demo has eating habits, not just two days of entries: + // the circadian tile only shows a meal that is logged regularly, and needs its usual time. + // Deterministic (no RNG): times wander within ~25 minutes and a few days skip a meal, the + // way real logging does. + let history: [MealHabit] = [ + MealHabit(type: .breakfast, hour: 7, minute: 50, spread: 25, skipEvery: 6, + names: ["Greek yogurt bowl", "Overnight oats", "Eggs on toast"], kcal: 350), + MealHabit(type: .lunch, hour: 12, minute: 30, spread: 25, skipEvery: 5, + names: ["Chicken salad", "Turkey sandwich", "Grain bowl"], kcal: 530), + MealHabit(type: .dinner, hour: 18, minute: 50, spread: 30, skipEvery: 7, + names: ["Salmon & rice", "Pasta primavera", "Stir-fry"], kcal: 660), + ] + for offset in 2..<30 { + guard let day = calendar.date(byAdding: .day, value: -offset, to: now) else { continue } + for (index, meal) in history.enumerated() where offset % meal.skipEvery != 0 { + let minute = meal.minute + (offset * (7 + index * 4)) % meal.spread + guard let timestamp = calendar.date(bySettingHour: meal.hour + minute / 60, minute: minute % 60, second: 0, of: day) + else { continue } + context.insert(MealEntry( + timestamp: timestamp, name: meal.names[offset % meal.names.count], mealType: meal.type, + calories: meal.kcal, proteinG: meal.kcal * 0.07, carbsG: meal.kcal * 0.1, fatG: meal.kcal * 0.035, + source: .manual + )) + } + } } /// Seeds every vital's measurement history for the demo. Each series is deterministic (no RNG) and diff --git a/PulseLoop/Services/CircadianRhythm.swift b/PulseLoop/Services/CircadianRhythm.swift new file mode 100644 index 00000000..e5a00f94 --- /dev/null +++ b/PulseLoop/Services/CircadianRhythm.swift @@ -0,0 +1,673 @@ +import CoreGraphics +import Foundation +import SwiftData + +// Circadian rhythm: where the anchors of a person's day (wake, meals, workouts, bedtime) usually +// fall, and how far the selected period drifted from that. Everything in `CircadianEngine` is a +// pure function over plain value inputs so each rule is unit-testable without SwiftData; +// `CircadianService` is the thin layer that gathers those inputs from the store. + +// MARK: - Clock math + +/// Time-of-day arithmetic on a 24-hour circle (minutes since local midnight, `0..<1440`). +enum CircadianMath { + static let minutesPerDay: Double = 1440 + + /// Wrap any minute value onto `0..<1440`. + static func normalize(_ minutes: Double) -> Double { + let r = minutes.truncatingRemainder(dividingBy: minutesPerDay) + return r < 0 ? r + minutesPerDay : r + } + + /// Mean time of day on the circle, so 11:30 PM and 12:30 AM average to midnight rather than + /// noon. Nil when there are no samples or they cancel out (no meaningful centre). + static func circularMean(_ minutes: [Double]) -> Double? { + guard !minutes.isEmpty else { return nil } + var x = 0.0, y = 0.0 + for m in minutes { + let angle = m / minutesPerDay * 2 * .pi + x += cos(angle) + y += sin(angle) + } + guard hypot(x, y) / Double(minutes.count) > 1e-6 else { return nil } + return normalize(atan2(y, x) / (2 * .pi) * minutesPerDay) + } + + /// Shortest signed distance from `reference` to `value`, in `(-720, 720]`. + /// Positive = later than the reference. + static func signedDelta(_ value: Double, from reference: Double) -> Double { + var d = normalize(value - reference) + if d > minutesPerDay / 2 { d -= minutesPerDay } + return d + } + + static func minuteOfDay(_ date: Date, calendar: Calendar) -> Double { + let c = calendar.dateComponents([.hour, .minute, .second], from: date) + return Double(c.hour ?? 0) * 60 + Double(c.minute ?? 0) + Double(c.second ?? 0) / 60 + } +} + +// MARK: - Vocabulary + +/// A recurring point in the day that can have a "usual" time. Declared in day order. +enum CircadianAnchorKind: String, CaseIterable, Codable, Hashable, Identifiable { + case wake, breakfast, lunch, dinner, bed + + var id: String { rawValue } + + var label: String { + switch self { + case .wake: return "Wake" + case .breakfast: return "Breakfast" + case .lunch: return "Lunch" + case .dinner: return "Dinner" + case .bed: return "Bed" + } + } + + var symbol: String { + switch self { + case .wake: return "sun.max.fill" + case .bed: return "moon.fill" + case .breakfast, .lunch, .dinner: return "fork.knife" + } + } + + var isMeal: Bool { self == .breakfast || self == .lunch || self == .dinner } + + static let meals: [CircadianAnchorKind] = [.breakfast, .lunch, .dinner] + + /// Snacks have no rhythm worth tracking, so they map to nil. + init?(mealType: MealType) { + switch mealType { + case .breakfast: self = .breakfast + case .lunch: self = .lunch + case .dinner: self = .dinner + case .snack: return nil + } + } +} + +/// Workouts get one of two icons: weights for strength, a runner for everything else. +enum CircadianWorkoutCategory: String, Codable, Equatable { + case cardio, strength + + var symbol: String { self == .strength ? "dumbbell.fill" : "figure.run" } + var label: String { self == .strength ? "Strength" : "Cardio" } + + static func from(type: String) -> CircadianWorkoutCategory { + ActivityMeta.meta(type).type == "gym" ? .strength : .cardio + } +} + +enum CircadianScope: String, Equatable { + case day, week, month, year + + init(_ range: SleepRangeKey) { + switch range { + case .day: self = .day + case .week: self = .week + case .month: self = .month + case .year: self = .year + } + } +} + +/// The days being looked at, as inclusive start-of-day bounds. +struct CircadianPeriod: Equatable { + let scope: CircadianScope + let start: Date + let end: Date +} + +// MARK: - Engine inputs + +struct CircadianSleepSample: Equatable { + /// Waking day the session belongs to. + let day: Date + let start: Date + let end: Date + let minutes: Int +} + +struct CircadianMealSample: Equatable { + let day: Date + let time: Date + let kind: CircadianAnchorKind +} + +struct CircadianWorkoutSample: Equatable { + let start: Date + let durationMinutes: Double + let category: CircadianWorkoutCategory + let label: String +} + +// MARK: - Engine output + +struct CircadianAnchor: Identifiable, Equatable { + let kind: CircadianAnchorKind + /// Average time over the baseline; nil until there is enough history. + let usualMinutes: Double? + /// The selected day's time, or the selected period's average. + let periodMinutes: Double? + + var id: String { kind.rawValue } + + /// Positive = later than usual. Nil unless both sides are known. + var deltaMinutes: Double? { + guard let usualMinutes, let periodMinutes else { return nil } + return CircadianMath.signedDelta(periodMinutes, from: usualMinutes) + } + + /// Where the anchor sits on the dial: its usual time, falling back to the period's own time. + var displayMinutes: Double { usualMinutes ?? periodMinutes ?? 0 } +} + +struct CircadianWorkout: Identifiable, Equatable { + let id: Int + let startMinutes: Double + let durationMinutes: Double + let category: CircadianWorkoutCategory + let label: String + /// True for an aggregate range, where the span is the period's typical workout time. + let isTypical: Bool +} + +struct CircadianSnapshot: Equatable { + let scope: CircadianScope + let anchors: [CircadianAnchor] + let workouts: [CircadianWorkout] + let headline: String + let subline: String + /// Not enough nights yet to know the person's usual wake and bedtime. + let isLearning: Bool + + /// Nothing worth drawing — the tile hides. + var isEmpty: Bool { anchors.isEmpty && workouts.isEmpty } + + func anchor(_ kind: CircadianAnchorKind) -> CircadianAnchor? { anchors.first { $0.kind == kind } } + + /// The sleep window to shade: usual bed → usual wake, or the period's own when no usual exists. + var sleepWindow: (bed: Double, wake: Double)? { + guard let bed = anchor(.bed), let wake = anchor(.wake) else { return nil } + if let b = bed.usualMinutes, let w = wake.usualMinutes { return (b, w) } + if let b = bed.periodMinutes, let w = wake.periodMinutes { return (b, w) } + return nil + } + + var hasDrift: Bool { anchors.contains { $0.deltaMinutes != nil } } +} + +// MARK: - Engine + +enum CircadianEngine { + /// "Usual" is the average over this many days before the period being viewed. + static let baselineDays = 30 + /// Fewer samples than this is not a habit yet — one or two nights must not define "usual". + static let minBaselineSamples = 5 + /// A day's longest session only counts as the night if it is at least this long, so a lone + /// nap on a night the ring missed never becomes that day's wake and bedtime. + static let minNightMinutes = 180 + /// Drift smaller than this reads as "on rhythm". + static let driftThreshold: Double = 30 + /// Smart mode: an event is a habit when it happened on 4 of the last 7 days (new habits show + /// up within a week) or 10 of the last 28 (a missed week does not drop an established one). + static let recentWindow = (days: 7, hits: 4) + static let longWindow = (days: 28, hits: 10) + static let minWorkoutMinutes: Double = 5 + + static func snapshot( + period: CircadianPeriod, + sleep: [CircadianSleepSample], + meals: [CircadianMealSample], + workouts: [CircadianWorkoutSample], + prefs: CircadianPrefs, + nutritionEnabled: Bool, + calendar: Calendar = .current + ) -> CircadianSnapshot { + let periodStart = calendar.startOfDay(for: period.start) + let periodEnd = calendar.startOfDay(for: period.end) + let baselineStart = calendar.date(byAdding: .day, value: -baselineDays, to: periodStart) ?? periodStart + let inBaseline: (Date) -> Bool = { $0 >= baselineStart && $0 < periodStart } + let inPeriod: (Date) -> Bool = { $0 >= periodStart && $0 <= periodEnd } + // An average over a range needs at least two days; a single day is its own value. + let minPeriodSamples = period.scope == .day ? 1 : 2 + + func anchor(_ kind: CircadianAnchorKind, _ byDay: [Date: Double]) -> CircadianAnchor? { + let baseline = byDay.filter { inBaseline($0.key) }.map(\.value) + let current = byDay.filter { inPeriod($0.key) }.map(\.value) + let usual = baseline.count >= minBaselineSamples ? CircadianMath.circularMean(baseline) : nil + let now = current.count >= minPeriodSamples ? CircadianMath.circularMean(current) : nil + guard usual != nil || now != nil else { return nil } + return CircadianAnchor(kind: kind, usualMinutes: usual, periodMinutes: now) + } + + // Sleep: one night per waking day, taken from that day's longest session so naps never + // move the anchors. + var nights: [Date: CircadianSleepSample] = [:] + for sample in sleep where sample.minutes >= minNightMinutes { + let day = calendar.startOfDay(for: sample.day) + if let existing = nights[day], existing.minutes >= sample.minutes { continue } + nights[day] = sample + } + let wakeByDay = nights.mapValues { CircadianMath.minuteOfDay($0.end, calendar: calendar) } + let bedByDay = nights.mapValues { CircadianMath.minuteOfDay($0.start, calendar: calendar) } + let baselineNights = nights.keys.filter(inBaseline).count + + var anchors: [CircadianAnchor] = [] + if let wake = anchor(.wake, wakeByDay) { anchors.append(wake) } + if let bed = anchor(.bed, bedByDay) { anchors.append(bed) } + + // Meals: the first entry of each type per day. + if nutritionEnabled && prefs.showMeals { + for kind in CircadianAnchorKind.meals { + var byDay: [Date: Double] = [:] + var firstTime: [Date: Date] = [:] + for meal in meals where meal.kind == kind { + let day = calendar.startOfDay(for: meal.day) + if let existing = firstTime[day], existing <= meal.time { continue } + firstTime[day] = meal.time + byDay[day] = CircadianMath.minuteOfDay(meal.time, calendar: calendar) + } + let included = prefs.mealSelection == .manual + ? prefs.includesMeal(kind) + : isRegular(days: Set(byDay.keys), endingOn: periodEnd, calendar: calendar) + if included, let meal = anchor(kind, byDay) { anchors.append(meal) } + } + } + anchors.sort { order($0.kind) < order($1.kind) } + + // Workouts: shown at the time they happened, never scored against a usual time. + var spans: [CircadianWorkout] = [] + if prefs.showWorkouts { + let usable = workouts.filter { $0.durationMinutes >= minWorkoutMinutes } + let workoutDays = Set(usable.map { calendar.startOfDay(for: $0.start) }) + let included = prefs.workoutSelection == .manual + || isRegular(days: workoutDays, endingOn: periodEnd, calendar: calendar) + let current = usable + .filter { inPeriod(calendar.startOfDay(for: $0.start)) } + .sorted { $0.start < $1.start } + if included { + if period.scope == .day { + spans = current.enumerated().map { index, w in + CircadianWorkout( + id: index, + startMinutes: CircadianMath.minuteOfDay(w.start, calendar: calendar), + durationMinutes: w.durationMinutes, category: w.category, label: w.label, isTypical: false) + } + } else if current.count >= 2, + let start = CircadianMath.circularMean(current.map { CircadianMath.minuteOfDay($0.start, calendar: calendar) }) { + let strength = current.filter { $0.category == .strength }.count + let category: CircadianWorkoutCategory = strength * 2 > current.count ? .strength : .cardio + let duration = current.map(\.durationMinutes).reduce(0, +) / Double(current.count) + spans = [CircadianWorkout( + id: 0, startMinutes: start, durationMinutes: duration, + category: category, label: "Workout", isTypical: true)] + } + } + } + + // Learning = too few nights to say what "usual" is. A single day needs them before it; a + // range that itself holds enough nights is past learning even with nothing earlier to + // compare against (it shows its own typical times instead). + let hasSleepUsual = anchors.contains { !$0.kind.isMeal && $0.usualMinutes != nil } + let periodNights = nights.keys.filter(inPeriod).count + let knownNights = period.scope == .day ? baselineNights : max(baselineNights, periodNights) + let isLearning = !hasSleepUsual && knownNights < minBaselineSamples + let copy = summary( + scope: period.scope, anchors: anchors, isLearning: isLearning, + nightsNeeded: max(1, minBaselineSamples - knownNights)) + return CircadianSnapshot( + scope: period.scope, anchors: anchors, workouts: spans, + headline: copy.headline, subline: copy.subline, isLearning: isLearning) + } + + /// Whether an event is a habit as of `end`, tolerant of gaps (see `recentWindow`/`longWindow`). + static func isRegular(days: Set, endingOn end: Date, calendar: Calendar = .current) -> Bool { + let endDay = calendar.startOfDay(for: end) + func hits(_ window: Int) -> Int { + guard let from = calendar.date(byAdding: .day, value: -(window - 1), to: endDay) else { return 0 } + return days.filter { $0 >= from && $0 <= endDay }.count + } + return hits(recentWindow.days) >= recentWindow.hits || hits(longWindow.days) >= longWindow.hits + } + + private static func order(_ kind: CircadianAnchorKind) -> Int { + CircadianAnchorKind.allCases.firstIndex(of: kind) ?? 0 + } + + /// The one-line read of the dial plus its supporting line. Both are drawn inside the dial, so + /// each stays short enough for one line there. + static func summary( + scope: CircadianScope, anchors: [CircadianAnchor], isLearning: Bool, nightsNeeded: Int + ) -> (headline: String, subline: String) { + let deltas: [(kind: CircadianAnchorKind, delta: Double)] = anchors.compactMap { a in + a.deltaMinutes.map { (a.kind, $0) } + } + guard !deltas.isEmpty else { + if isLearning { + return ("Learning your rhythm", "Needs \(nightsNeeded) more night\(nightsNeeded == 1 ? "" : "s")") + } + if scope != .day, anchors.contains(where: { $0.periodMinutes != nil }) { + return ("Your typical day", scope == .year ? "Past year's average" : "No earlier baseline yet") + } + if anchors.contains(where: { $0.usualMinutes != nil }) { + return ("Your usual day", "Nothing recorded yet") + } + return ("Your day", "") + } + + let off = deltas.filter { abs($0.delta) >= driftThreshold } + let within = deltas.count - off.count + let threshold = Int(driftThreshold) + let tally = "\(within) of \(deltas.count) within \(threshold) min" + if off.isEmpty { + return ("On rhythm", deltas.count == 1 ? "Within \(threshold) min of usual" : "All \(deltas.count) within \(threshold) min") + } + + // Everything moved the same way: the whole day (or period) shifted. + let mean = deltas.map(\.delta).reduce(0, +) / Double(deltas.count) + let allLater = deltas.allSatisfy { $0.delta > -10 } + let allEarlier = deltas.allSatisfy { $0.delta < 10 } + if deltas.count >= 2, abs(mean) >= driftThreshold, allLater || allEarlier { + let later = mean > 0 + let head = scope == .day ? (later ? "Running late" : "Running early") : (later ? "Shifted later" : "Shifted earlier") + return (head, "About \(CircadianFormat.duration(abs(mean))) \(later ? "later" : "earlier")") + } + + let sleepOff = off.filter { !$0.kind.isMeal } + let mealsOff = off.filter { $0.kind.isMeal } + let hasMeals = deltas.contains { $0.kind.isMeal } + let hasSleep = deltas.contains { !$0.kind.isMeal } + + if sleepOff.isEmpty { + let head: String + switch direction(mealsOff.map(\.delta)) { + case .later: head = "Meals ran late" + case .earlier: head = "Meals ran early" + case .mixed: head = "Meals off schedule" + } + return (head, hasSleep ? "Sleep held steady" : tally) + } + if mealsOff.isEmpty { + let head: String + if sleepOff.count == 1, let only = sleepOff.first { + let late = only.delta > 0 + head = only.kind == .bed + ? (late ? "Bedtime ran late" : "Bedtime ran early") + : (late ? "Wake-up ran late" : "Wake-up ran early") + } else { + switch direction(sleepOff.map(\.delta)) { + case .later: head = "Sleep shifted later" + case .earlier: head = "Sleep shifted earlier" + case .mixed: head = "Sleep off schedule" + } + } + return (head, hasMeals ? "Meals held steady" : tally) + } + return ("Off rhythm", tally) + } + + private enum Direction { case later, earlier, mixed } + + private static func direction(_ deltas: [Double]) -> Direction { + if deltas.allSatisfy({ $0 > 0 }) { return .later } + if deltas.allSatisfy({ $0 < 0 }) { return .earlier } + return .mixed + } +} + +// MARK: - Formatting + +enum CircadianFormat { + /// "22m", "1h", "1h 5m". + static func duration(_ minutes: Double) -> String { + let total = Int(abs(minutes).rounded()) + let h = total / 60, m = total % 60 + if h == 0 { return "\(m)m" } + return m == 0 ? "\(h)h" : "\(h)h \(m)m" + } + + /// "+50m" / "−22m" — the compact label drawn next to a drift bar. + static func signed(_ delta: Double) -> String { + let rounded = delta.rounded() + if rounded == 0 { return "0m" } + return (rounded > 0 ? "+" : "\u{2212}") + duration(rounded) + } + + /// "50m later" / "22m earlier" / "On time". + static func words(_ delta: Double) -> String { + let rounded = delta.rounded() + if rounded == 0 { return "On time" } + return "\(duration(rounded)) \(rounded > 0 ? "later" : "earlier")" + } + + /// Spoken form for VoiceOver: "50 minutes later than usual". + static func spoken(_ delta: Double) -> String { + let total = Int(abs(delta).rounded()) + if total == 0 { return "on time" } + let h = total / 60, m = total % 60 + var parts: [String] = [] + if h > 0 { parts.append("\(h) hour\(h == 1 ? "" : "s")") } + if m > 0 { parts.append("\(m) minute\(m == 1 ? "" : "s")") } + return "\(parts.joined(separator: " ")) \(delta > 0 ? "later" : "earlier") than usual" + } + + /// Minute-of-day → "7:03 AM", matching `SleepFormat.clockTime`. + static func clock(_ minutes: Double) -> String { + let total = Int(CircadianMath.normalize(minutes).rounded()) % 1440 + let h24 = total / 60, m = total % 60 + let h12 = h24 % 12 == 0 ? 12 : h24 % 12 + return "\(h12):\(String(format: "%02d", m)) \(h24 < 12 ? "AM" : "PM")" + } +} + +// MARK: - Coach hand-off + +extension CircadianSnapshot { + /// Up to three questions to open a coach chat with, led by whatever stands out in the dial. + var coachPrompts: [String] { + if isLearning || !hasDrift { + return [ + "What is a circadian rhythm and why does it matter?", + "How do I build a steady sleep schedule?", + "How does meal timing affect my sleep?" + ] + } + var prompts: [String] = [] + let off = anchors.filter { abs($0.deltaMinutes ?? 0) >= CircadianEngine.driftThreshold } + if let bed = off.first(where: { $0.kind == .bed }), let delta = bed.deltaMinutes { + prompts.append(delta > 0 ? "How can I get to bed earlier?" : "Is going to bed earlier than usual a problem?") + } + if let wake = off.first(where: { $0.kind == .wake }), let delta = wake.deltaMinutes { + prompts.append(delta > 0 ? "How do I get back to my usual wake time?" : "Why am I waking earlier than usual?") + } + if let meal = off.first(where: { $0.kind.isMeal }), let delta = meal.deltaMinutes { + prompts.append(delta > 0 + ? "How does eating later than usual affect my sleep?" + : "Does eating earlier than usual change my sleep?") + } + if off.isEmpty { prompts.append("What helps me stay on rhythm?") } + prompts.append("How consistent has my daily rhythm been lately?") + prompts.append("What should I adjust tomorrow to stay on rhythm?") + return Array(prompts.prefix(3)) + } + + /// The dial's facts as one line for the coach. Sent with the question but not shown in the + /// chat bubble — the coach's own tools do not expose bedtimes or wake times. + var coachContext: String { + let scopeText: String + switch scope { + case .day: scopeText = "the selected day" + case .week: scopeText = "the past week's average" + case .month: scopeText = "the past month's average" + case .year: scopeText = "the past year's average" + } + var facts: [String] = anchors.map { a in + var text = a.kind.label.lowercased() + if let now = a.periodMinutes { text += " \(CircadianFormat.clock(now))" } else { text += " not recorded" } + if let usual = a.usualMinutes { text += " (usual \(CircadianFormat.clock(usual))" } else { text += " (no usual yet" } + if let delta = a.deltaMinutes { text += ", \(CircadianFormat.words(delta).lowercased())" } + return text + ")" + } + facts += workouts.map { w in + let name = w.isTypical ? "typical workout" : w.label.lowercased() + return "\(name) at \(CircadianFormat.clock(w.startMinutes)) for \(CircadianFormat.duration(w.durationMinutes))" + } + return "Circadian rhythm from the Sleep tab, for \(scopeText): \(facts.joined(separator: "; ")). " + + "\"Usual\" is the average over the \(CircadianEngine.baselineDays) days before." + } +} + +// MARK: - Dial geometry + +/// Maps time of day onto the dial. Kept free of SwiftUI so the mapping can be unit-tested. +struct CircadianDialGeometry: Equatable { + enum Shape: Equatable { + /// 24 hours across the top half-circle, starting at the app's 4 AM day boundary. + case semicircle + /// 24 hours around the whole circle: noon at the top, midnight at the bottom. + case full + } + + let shape: Shape + + /// Where the semicircle's day begins — the same 4 AM flip `SleepService.dayReferenceNight` uses. + static let dayStartMinutes: Double = 240 + + /// Radians of arc per minute of time. + var sweepPerMinute: Double { + (shape == .semicircle ? Double.pi : 2 * Double.pi) / CircadianMath.minutesPerDay + } + + /// Angle in screen space (0 = right, growing clockwise because y points down). + func screenAngle(_ minutes: Double) -> Double { + switch shape { + case .semicircle: + return Double.pi + CircadianMath.normalize(minutes - Self.dayStartMinutes) * sweepPerMinute + case .full: + return -Double.pi / 2 + (minutes - 720) * sweepPerMinute + } + } + + func point(_ minutes: Double, radius: CGFloat, center: CGPoint) -> CGPoint { + let angle = screenAngle(minutes) + return CGPoint(x: center.x + radius * CGFloat(cos(angle)), y: center.y + radius * CGFloat(sin(angle))) + } + + /// Arc pieces covering `start` → `end` going forward in time. The semicircle splits a span + /// that crosses its 4 AM seam (overnight sleep) into a right-hand and a left-hand piece. + func arcs(from start: Double, to end: Double) -> [(startAngle: Double, sweep: Double)] { + let length = CircadianMath.normalize(end - start) + guard length > 0 else { return [] } + switch shape { + case .full: + return [(screenAngle(start), length * sweepPerMinute)] + case .semicircle: + let offset = CircadianMath.normalize(start - Self.dayStartMinutes) + let toSeam = CircadianMath.minutesPerDay - offset + if length <= toSeam { return [(screenAngle(start), length * sweepPerMinute)] } + return [ + (screenAngle(start), toSeam * sweepPerMinute), + (Double.pi, (length - toSeam) * sweepPerMinute) + ] + } + } + + /// Nudge markers that would overlap apart, each by half the shortfall, so two events close in + /// time (wake and breakfast) stay individually readable. Order is preserved. + static func spread(_ minutes: [Double], minGap: Double) -> [Double] { + guard minutes.count > 1, minGap > 0 else { return minutes } + var linear = minutes.map { CircadianMath.normalize($0 - dayStartMinutes) } + let order = linear.indices.sorted { linear[$0] < linear[$1] } + for _ in 0..<12 { + var moved = false + for i in 1.. CircadianMath.minutesPerDay - 1 { + linear[last] = CircadianMath.minutesPerDay - 1 + } + if !moved { break } + } + return linear.map { CircadianMath.normalize($0 + dayStartMinutes) } + } + + /// Greedy label de-collision: keep each rect, in priority order, unless it hits one already kept. + static func keepLabels(_ rects: [CGRect]) -> [Bool] { + var kept: [CGRect] = [] + return rects.map { rect in + if kept.contains(where: { $0.intersects(rect) }) { return false } + kept.append(rect) + return true + } + } +} + +// MARK: - Store access + +@MainActor +enum CircadianService { + /// The period the Sleep page is showing: the selected day, or the range the page's summary covers. + static func period(range: SleepRangeKey, day: Date, summary: SleepRangeSummary, calendar: Calendar = .current) -> CircadianPeriod { + if range == .day { + let start = calendar.startOfDay(for: day) + return CircadianPeriod(scope: .day, start: start, end: start) + } + return CircadianPeriod( + scope: CircadianScope(range), + start: calendar.startOfDay(for: summary.start), end: calendar.startOfDay(for: summary.end)) + } + + static func snapshot( + period: CircadianPeriod, + context: ModelContext, + prefs: CircadianPrefs? = nil, + nutritionEnabled: Bool? = nil, + calendar: Calendar = .current + ) -> CircadianSnapshot { + // Nil means "the user's current settings" (resolved here, on the main actor). + let prefs = prefs ?? CircadianPrefsStore.shared.prefs + let nutritionEnabled = nutritionEnabled ?? NutritionPrefsStore.shared.prefs.masterEnabled + // Everything the engine can use: the baseline before the period through the period's last day. + let from = calendar.date(byAdding: .day, value: -(CircadianEngine.baselineDays + 1), to: period.start) ?? period.start + let until = calendar.date(byAdding: .day, value: 1, to: period.end) ?? period.end + + let sleep = SleepRepository.sessions(context: context) + .filter { $0.totalMinutes > 0 && $0.date >= from && $0.date < until } + .map { CircadianSleepSample(day: $0.date, start: $0.startAt, end: $0.endAt, minutes: $0.totalMinutes) } + + let meals: [CircadianMealSample] = nutritionEnabled && prefs.showMeals + ? NutritionRepository.entries(from: from, to: until, context: context).compactMap { entry in + CircadianAnchorKind(mealType: entry.mealType).map { + CircadianMealSample(day: entry.date, time: entry.timestamp, kind: $0) + } + } + : [] + + let workouts: [CircadianWorkoutSample] = prefs.showWorkouts + ? ActivityRepository.sessions(context: context).compactMap { session in + guard session.status == .finished, let ended = session.endedAt, + session.startedAt >= from, session.startedAt < until else { return nil } + let seconds = ended.timeIntervalSince(session.startedAt) - session.totalPauseSeconds + return CircadianWorkoutSample( + start: session.startedAt, durationMinutes: max(0, seconds / 60), + category: .from(type: session.type), label: ActivityMeta.label(session.type)) + } + : [] + + return CircadianEngine.snapshot( + period: period, sleep: sleep, meals: meals, workouts: workouts, + prefs: prefs, nutritionEnabled: nutritionEnabled, calendar: calendar) + } +} diff --git a/PulseLoop/Settings/CircadianPrefsStore.swift b/PulseLoop/Settings/CircadianPrefsStore.swift new file mode 100644 index 00000000..21a886e5 --- /dev/null +++ b/PulseLoop/Settings/CircadianPrefsStore.swift @@ -0,0 +1,89 @@ +import Foundation + +/// How the circadian tile decides which optional events to show. +enum CircadianSelectionMode: String, Codable, CaseIterable { + /// The app includes an event only when it is logged often enough to be a habit. + case smart + /// The user's own choices, regardless of how often the event is logged. + case manual +} + +/// User-tunable circadian-tile preferences, persisted as JSON in `UserDefaults`. +/// +/// Unlike nutrition, the tile is **on by default**: it only reads data the app already has. +/// Mirrors the `NutritionPrefsStore` pattern — no SwiftData, no migration — with tolerant decode +/// so adding a future key never wipes an existing user's blob. +struct CircadianPrefs: Codable, Equatable { + /// Show the circadian tile on the Sleep page. + var enabled = true + /// Put meals on the dial (still requires nutrition tracking to be on). + var showMeals = true + var mealSelection: CircadianSelectionMode = .smart + // Which meals to show when `mealSelection` is `.manual`. + var showBreakfast = true + var showLunch = true + var showDinner = true + /// Put workouts on the dial. + var showWorkouts = true + /// `.smart` shows workouts only when they are a regular habit; `.manual` always shows them. + var workoutSelection: CircadianSelectionMode = .smart + + static let `default` = CircadianPrefs() + + init() {} + + init(from decoder: Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + let d = CircadianPrefs.default + enabled = try c.decodeIfPresent(Bool.self, forKey: .enabled) ?? d.enabled + showMeals = try c.decodeIfPresent(Bool.self, forKey: .showMeals) ?? d.showMeals + mealSelection = try c.decodeIfPresent(CircadianSelectionMode.self, forKey: .mealSelection) ?? d.mealSelection + showBreakfast = try c.decodeIfPresent(Bool.self, forKey: .showBreakfast) ?? d.showBreakfast + showLunch = try c.decodeIfPresent(Bool.self, forKey: .showLunch) ?? d.showLunch + showDinner = try c.decodeIfPresent(Bool.self, forKey: .showDinner) ?? d.showDinner + showWorkouts = try c.decodeIfPresent(Bool.self, forKey: .showWorkouts) ?? d.showWorkouts + workoutSelection = try c.decodeIfPresent(CircadianSelectionMode.self, forKey: .workoutSelection) ?? d.workoutSelection + } + + /// The manual per-meal choice for a meal anchor. + func includesMeal(_ kind: CircadianAnchorKind) -> Bool { + switch kind { + case .breakfast: return showBreakfast + case .lunch: return showLunch + case .dinner: return showDinner + case .wake, .bed: return false + } + } +} + +/// Observable, `UserDefaults`-backed store for circadian preferences. +/// Follows the `NutritionPrefsStore` pattern; persists on `didSet`, reads at use-time. +@MainActor +@Observable +final class CircadianPrefsStore { + nonisolated deinit {} // skip the main-actor isolated-deinit hop (crashes on older sim runtimes) + + static let shared = CircadianPrefsStore() + + private static let prefsKey = "pulseloop.circadian.prefs.v1" + private let defaults: UserDefaults + + var prefs: CircadianPrefs { + didSet { persist(prefs) } + } + + init(defaults: UserDefaults = .standard) { + self.defaults = defaults + if let data = defaults.data(forKey: Self.prefsKey), + let stored = try? JSONDecoder().decode(CircadianPrefs.self, from: data) { + self.prefs = stored + } else { + self.prefs = .default + } + } + + private func persist(_ value: CircadianPrefs) { + guard let data = try? JSONEncoder().encode(value) else { return } + defaults.set(data, forKey: Self.prefsKey) + } +} diff --git a/PulseLoop/Views/CircadianRhythmViews.swift b/PulseLoop/Views/CircadianRhythmViews.swift new file mode 100644 index 00000000..89c2ce18 --- /dev/null +++ b/PulseLoop/Views/CircadianRhythmViews.swift @@ -0,0 +1,327 @@ +import SwiftUI + +/// The Sleep page's circadian tile: the semicircular dial with its one-line read. Tapping it +/// opens `CircadianDetailSheet`. +struct CircadianRhythmCard: View { + let snapshot: CircadianSnapshot + let onTap: () -> Void + + var body: some View { + Button(action: onTap) { + ZStack(alignment: .top) { + CircadianDial(snapshot: snapshot, shape: .semicircle) + // Cap the dial so it stays a compact tile on the widest phones. + .frame(maxWidth: 380) + .frame(maxWidth: .infinity) + HStack { + Text("CIRCADIAN") + .font(PulseFont.caption2) + .tracking(1.8) + .foregroundStyle(PulseColors.textMuted) + Spacer() + Image(systemName: "chevron.right") + .font(.system(size: 11, weight: .semibold)) + .foregroundStyle(PulseColors.textMuted) + } + } + .frame(maxWidth: .infinity) + .padding(16) + .contentShape(RoundedRectangle(cornerRadius: 22, style: .continuous)) + .pulseGlass(RoundedRectangle(cornerRadius: 22, style: .continuous)) + } + .buttonStyle(.plain) + .accessibilityElement(children: .ignore) + .accessibilityLabel(snapshot.accessibilitySummary) + .accessibilityHint("Opens circadian rhythm details") + .accessibilityAddTraits(.isButton) + } +} + +extension CircadianSnapshot { + /// The dial in words, for VoiceOver. + var accessibilitySummary: String { + var parts = ["Circadian rhythm", headline] + if !subline.isEmpty { parts.append(subline) } + for anchor in anchors { + if let delta = anchor.deltaMinutes { + parts.append("\(anchor.kind.label) \(CircadianFormat.spoken(delta))") + } + } + for workout in workouts { + parts.append("\(workout.isTypical ? "Typical workout" : workout.label) at \(CircadianFormat.clock(workout.startMinutes))") + } + return parts.joined(separator: ". ") + } +} + +/// The expanded view: the full 24-hour dial, how to read it, each event's time against its +/// usual, and prompts that carry the picture into a coach chat. +struct CircadianDetailSheet: View { + let snapshot: CircadianSnapshot + /// "Today · Fri, Nov 13" or "Past 7 days". + let periodTitle: String + let coachEnabled: Bool + /// Called with the chosen question; the presenter closes this sheet and opens the coach. + let onAskCoach: (String) -> Void + + @Environment(\.dismiss) private var dismiss + + var body: some View { + NavigationStack { + ScrollView { + VStack(alignment: .leading, spacing: 16) { + Text(periodTitle) + .font(PulseFont.caption) + .foregroundStyle(PulseColors.textSecondary) + .textCase(.uppercase) + .kerning(0.5) + .frame(maxWidth: .infinity, alignment: .center) + + CircadianDial(snapshot: snapshot, shape: .full) + .frame(maxWidth: 400) + .frame(maxWidth: .infinity) + .pulseGlass(RoundedRectangle(cornerRadius: 22, style: .continuous)) + .accessibilityElement(children: .ignore) + .accessibilityLabel(snapshot.accessibilitySummary) + + CircadianLegend() + + if !rows.isEmpty { eventList } + + Text(footnote) + .font(PulseFont.caption.weight(.regular)) + .foregroundStyle(PulseColors.textMuted) + .padding(.horizontal, 4) + + if coachEnabled { coachPrompts } + } + .padding(16) + } + .background(PulseColors.background) + .navigationTitle("Circadian rhythm") + .navigationBarTitleDisplayMode(.inline) + .toolbar { + ToolbarItem(placement: .confirmationAction) { + Button("Done") { dismiss() } + } + } + } + .presentationDetents([.large]) + .presentationDragIndicator(.visible) + } + + // MARK: Event list + + private enum Row: Identifiable { + case anchor(CircadianAnchor) + case workout(CircadianWorkout) + + var id: String { + switch self { + case .anchor(let a): return "anchor-\(a.id)" + case .workout(let w): return "workout-\(w.id)" + } + } + + /// Minutes since the 4 AM day boundary, so the list reads in the order the day happens. + var sortKey: Double { + let minutes: Double + switch self { + case .anchor(let a): minutes = a.periodMinutes ?? a.displayMinutes + case .workout(let w): minutes = w.startMinutes + } + return CircadianMath.normalize(minutes - CircadianDialGeometry.dayStartMinutes) + } + } + + private var rows: [Row] { + (snapshot.anchors.map(Row.anchor) + snapshot.workouts.map(Row.workout)).sorted { $0.sortKey < $1.sortKey } + } + + private var eventList: some View { + VStack(spacing: 0) { + ForEach(Array(rows.enumerated()), id: \.element.id) { index, row in + switch row { + case .anchor(let anchor): anchorRow(anchor) + case .workout(let workout): workoutRow(workout) + } + if index < rows.count - 1 { + Divider().overlay(PulseColors.borderSubtle) + } + } + } + .padding(.horizontal, 16) + .padding(.vertical, 4) + .pulseGlass(RoundedRectangle(cornerRadius: 22, style: .continuous)) + } + + private func anchorRow(_ anchor: CircadianAnchor) -> some View { + let delta = anchor.deltaMinutes + let offRhythm = abs(delta ?? 0) >= CircadianEngine.driftThreshold + let detail: String + if let delta { + detail = CircadianFormat.words(delta) + } else if anchor.periodMinutes == nil { + detail = snapshot.scope == .day ? "Not recorded" : "No data" + } else { + detail = "" + } + return eventRow( + symbol: anchor.kind.symbol, + tint: anchor.kind.isMeal ? PulseColors.textPrimary.opacity(0.85) : PulseColors.sleep, + title: anchor.kind.label, + subtitle: anchor.usualMinutes.map { "Usually \(CircadianFormat.clock($0))" } ?? "No usual yet", + value: anchor.periodMinutes.map { CircadianFormat.clock($0) } ?? "—", + detail: detail, + detailColor: offRhythm ? PulseColors.rhythm : PulseColors.textSecondary, + spoken: delta.map { CircadianFormat.spoken($0) } + ) + } + + private func workoutRow(_ workout: CircadianWorkout) -> some View { + eventRow( + symbol: workout.category.symbol, + tint: PulseColors.success, + title: workout.isTypical ? "Workout" : workout.label, + subtitle: workout.isTypical ? "Typical time" : workout.category.label, + value: CircadianFormat.clock(workout.startMinutes), + detail: CircadianFormat.duration(workout.durationMinutes), + detailColor: PulseColors.textSecondary, + spoken: nil + ) + } + + private func eventRow( + symbol: String, tint: Color, title: String, subtitle: String, + value: String, detail: String, detailColor: Color, spoken: String? + ) -> some View { + HStack(spacing: 12) { + Image(systemName: symbol) + .font(.system(size: 13, weight: .semibold)) + .foregroundStyle(tint) + .frame(width: 30, height: 30) + .background(PulseColors.cardSoft, in: Circle()) + VStack(alignment: .leading, spacing: 2) { + Text(title).font(PulseFont.callout.weight(.semibold)).foregroundStyle(PulseColors.textPrimary) + Text(subtitle).font(PulseFont.caption.weight(.regular)).foregroundStyle(PulseColors.textSecondary) + } + Spacer(minLength: 8) + VStack(alignment: .trailing, spacing: 2) { + Text(value).font(PulseFont.callout.weight(.semibold)).monospacedDigit().foregroundStyle(PulseColors.textPrimary) + // Always a line (a space when empty) so every row is the same height. + Text(detail.isEmpty ? " " : detail).font(PulseFont.caption).monospacedDigit().foregroundStyle(detailColor) + } + } + .padding(.vertical, 10) + .accessibilityElement(children: .ignore) + .accessibilityLabel([title, value, spoken ?? detail, subtitle].filter { !$0.isEmpty && $0 != "—" }.joined(separator: ", ")) + } + + private var footnote: String { + let window = snapshot.scope == .day ? "the 30 days before this day" : "the 30 days before this period" + return "Usual is your average over \(window), or as many of them as you've tracked. " + + "It needs at least 5 nights, and a missed night doesn't reset it. " + + "Choose what appears here in Settings, under Circadian rhythm." + } + + // MARK: Coach + + private var coachPrompts: some View { + VStack(alignment: .leading, spacing: 8) { + Text("ASK YOUR COACH") + .font(PulseFont.caption2) + .tracking(1.8) + .foregroundStyle(PulseColors.textMuted) + .padding(.leading, 4) + .accessibilityAddTraits(.isHeader) + ForEach(snapshot.coachPrompts, id: \.self) { prompt in + Button { onAskCoach(prompt) } label: { + CoachFollowUpChipLabel(text: prompt) + } + .buttonStyle(.plain) + .accessibilityHint("Opens the coach with this question") + } + } + .padding(.top, 4) + } +} + +/// How to read the dial: which way a bar points, and what the two colored bands are. +private struct CircadianLegend: View { + private enum Glyph { case later, earlier, sleep, workout } + + var body: some View { + VStack(alignment: .leading, spacing: 12) { + Text("READING THE DIAL") + .font(PulseFont.caption2) + .tracking(1.8) + .foregroundStyle(PulseColors.textMuted) + .accessibilityAddTraits(.isHeader) + Text("Each icon sits at your usual time. A gold bar shows how far you were from it: the longer the bar, the bigger the gap.") + .font(PulseFont.caption.weight(.regular)) + .foregroundStyle(PulseColors.textSecondary) + .fixedSize(horizontal: false, vertical: true) + Grid(alignment: .leading, horizontalSpacing: 12, verticalSpacing: 10) { + GridRow { + item(.later, "Bar pointing out", "Later than usual") + item(.earlier, "Bar pointing in", "Earlier than usual") + } + GridRow { + item(.sleep, "Violet band", "Your usual sleep") + item(.workout, "Green band", "A workout") + } + } + } + .frame(maxWidth: .infinity, alignment: .leading) + .padding(16) + .pulseGlass(RoundedRectangle(cornerRadius: 22, style: .continuous)) + } + + private func item(_ glyph: Glyph, _ title: String, _ meaning: String) -> some View { + HStack(spacing: 8) { + Canvas { context, size in + draw(glyph, in: &context, size: size) + } + .frame(width: 30, height: 26) + .accessibilityHidden(true) + VStack(alignment: .leading, spacing: 1) { + Text(title).font(PulseFont.caption).foregroundStyle(PulseColors.textPrimary) + Text(meaning).font(PulseFont.caption2.weight(.regular)).foregroundStyle(PulseColors.textSecondary) + } + } + .frame(maxWidth: .infinity, alignment: .leading) + .accessibilityElement(children: .combine) + } + + /// A small slice of the dial: a piece of track, and either a node with its bar or a colored band. + private func draw(_ glyph: Glyph, in context: inout GraphicsContext, size: CGSize) { + let midY = size.height / 2 + var track = Path() + track.move(to: CGPoint(x: 2, y: midY + 3)) + track.addQuadCurve(to: CGPoint(x: size.width - 2, y: midY + 3), control: CGPoint(x: size.width / 2, y: midY - 4)) + let trackStyle = StrokeStyle(lineWidth: 5, lineCap: .round) + switch glyph { + case .sleep: + context.stroke(track, with: .color(PulseColors.accent.opacity(0.65)), style: trackStyle) + case .workout: + context.stroke(track, with: .color(PulseColors.elevated), style: trackStyle) + context.stroke(track.trimmedPath(from: 0.3, to: 0.7), with: .color(PulseColors.success), + style: StrokeStyle(lineWidth: 5, lineCap: .butt)) + case .later, .earlier: + context.stroke(track, with: .color(PulseColors.elevated), style: trackStyle) + let node = CGPoint(x: size.width / 2, y: midY - 0.5) + var bar = Path() + if glyph == .later { + bar.move(to: CGPoint(x: node.x, y: node.y - 6)) + bar.addLine(to: CGPoint(x: node.x, y: node.y - 11)) + } else { + bar.move(to: CGPoint(x: node.x, y: node.y + 6)) + bar.addLine(to: CGPoint(x: node.x, y: node.y + 11)) + } + context.stroke(bar, with: .color(PulseColors.rhythm), style: StrokeStyle(lineWidth: 3, lineCap: .round)) + let disc = Path(ellipseIn: CGRect(x: node.x - 4, y: node.y - 4, width: 8, height: 8)) + context.fill(disc, with: .color(PulseColors.cardSoft)) + context.stroke(disc, with: .color(.white.opacity(0.4)), lineWidth: 1) + } + } +} diff --git a/PulseLoop/Views/CoachView.swift b/PulseLoop/Views/CoachView.swift index 704bf2a8..34b128ee 100644 --- a/PulseLoop/Views/CoachView.swift +++ b/PulseLoop/Views/CoachView.swift @@ -155,10 +155,14 @@ struct CoachView: View { activeConversationId = allMessages.last?.conversationId ?? conversations.first?.id } if nav.requestedConversationId != nil { openRequestedConversation() } + askPendingPrompt() } .onChange(of: nav.requestedConversationId) { _, id in if id != nil { openRequestedConversation() } } + .onChange(of: nav.pendingPrompt) { _, prompt in + if prompt != nil { askPendingPrompt() } + } .sheet(isPresented: $showHistory) { CoachHistorySheet(conversations: conversations, activeId: activeConversationId) { id in activeConversationId = id @@ -322,7 +326,20 @@ struct CoachView: View { stagedAttachment = nil } - private func send(_ text: String) { + /// Ask a question handed over from another screen (see `CoachNavigation.ask`) in a chat of + /// its own, titled from the question. + private func askPendingPrompt() { + guard let prompt = nav.pendingPrompt else { return } + let hiddenContext = nav.pendingPromptContext + nav.clearPendingPrompt() + let conversation = CoachConversation(title: String(prompt.prefix(40))) + modelContext.insert(conversation) + try? modelContext.save() + activeConversationId = conversation.id + send(prompt, hiddenContext: hiddenContext) + } + + private func send(_ text: String, hiddenContext: String? = nil) { let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines) let attachment = stagedAttachment // Allow image-only sends: require either text or a staged image. @@ -341,7 +358,11 @@ struct CoachView: View { stagedAttachment = nil composerFocused = false let attachments = attachment.map { [$0] } ?? [] - Task { await viewModel.send(trimmed, conversationId: conversationId, context: modelContext, attachments: attachments, coordinator: coordinator) } + Task { + await viewModel.send( + trimmed, conversationId: conversationId, context: modelContext, + attachments: attachments, coordinator: coordinator, hiddenContext: hiddenContext) + } } /// The active conversation, creating one on first use. diff --git a/PulseLoop/Views/RootViews.swift b/PulseLoop/Views/RootViews.swift index 6001e353..ae3eb788 100644 --- a/PulseLoop/Views/RootViews.swift +++ b/PulseLoop/Views/RootViews.swift @@ -103,6 +103,11 @@ struct RootAppView: View { if UserDefaults.standard.bool(forKey: "openNutritionSettings") { path.append(AppRoute.settingsNutrition) } + // Test tooling: open Settings → Circadian rhythm. (`-openCircadian YES` opens the + // tile's detail sheet instead; SleepView reads that one itself.) + if UserDefaults.standard.bool(forKey: "openCircadianSettings") { + path.append(AppRoute.settingsCircadian) + } // Test tooling: deep-link straight to a seeded workout's detail (route map). if UserDefaults.standard.bool(forKey: "openWorkout"), let session = ActivityRepository.sessions(context: modelContext).first(where: { $0.status == .finished && $0.useGps }) { @@ -182,6 +187,8 @@ struct RootAppView: View { AboutSettingsView(path: $path) case .settingsNutrition: NutritionSettingsView() + case .settingsCircadian: + CircadianSettingsView() case .nutrition: NutritionView(path: $path) case let .mealDetail(id): @@ -345,7 +352,7 @@ struct MainTabView: View { .onChange(of: selected) { _, _ in reorder.end() } .onChange(of: coachEnabled) { _, enabled in // Coach turned off — dismiss the sheet and clear any pending deep link. - if !enabled { nav.requestedConversationId = nil; nav.showCoach = false } + if !enabled { nav.requestedConversationId = nil; nav.clearPendingPrompt(); nav.showCoach = false } } // Coach opens as a sheet (swipe-to-dismiss) instead of a tab, so it never // crowds the tab bar. All entry points set `nav.showCoach`. diff --git a/PulseLoop/Views/Settings/CircadianSettingsView.swift b/PulseLoop/Views/Settings/CircadianSettingsView.swift new file mode 100644 index 00000000..367c6aea --- /dev/null +++ b/PulseLoop/Views/Settings/CircadianSettingsView.swift @@ -0,0 +1,114 @@ +import SwiftUI + +/// Settings → Circadian rhythm: the on/off switch for the Sleep-page tile, plus what goes on it. +/// +/// Follows `NutritionSettingsView`'s rule: every group is ALWAYS rendered and gated with +/// `.disabled/.opacity`; nothing is conditionally inserted, because glass surfaces that +/// appear/disappear morph through capsule shapes on device. +struct CircadianSettingsView: View { + @State private var store = CircadianPrefsStore.shared + @State private var nutritionStore = NutritionPrefsStore.shared + + private var prefs: Binding { + Binding(get: { store.prefs }, set: { store.prefs = $0 }) + } + + private var tileOn: Bool { store.prefs.enabled } + private var nutritionOn: Bool { nutritionStore.prefs.masterEnabled } + private var mealsOn: Bool { tileOn && nutritionOn && store.prefs.showMeals } + private var customMeals: Bool { mealsOn && store.prefs.mealSelection == .manual } + private var workoutsOn: Bool { tileOn && store.prefs.showWorkouts } + + private static let habitRule = "on 4 of the last 7 days, or 10 of the last 28" + + var body: some View { + ScrollView { + VStack(alignment: .leading, spacing: 22) { + SettingsGroup( + footer: "A dial on the Sleep page showing when you usually wake, eat, train and go to bed, " + + "and how far the day or period you're viewing drifted from that. " + + "Wake and bedtime are always on it." + ) { + FormToggleRow(title: "Show circadian rhythm", isOn: prefs.enabled) + } + + mealsGroup + workoutsGroup + + SettingsGroup( + header: "Your usual", + footer: "Each event's usual time is its average over the 30 days before the day or period " + + "you're viewing, or as many of those days as you've tracked. It needs at least 5 nights " + + "before it shows a comparison, and a missed night here and there doesn't reset it." + ) { + FormValueRow(title: "Based on") { + Text("Previous 30 days") + .font(PulseFont.body) + .foregroundStyle(PulseColors.textSecondary) + } + } + .disabled(!tileOn) + .opacity(tileOn ? 1 : 0.5) + } + .padding() + } + .background(PulseColors.background) + .pageChrome("Circadian rhythm") + .onChange(of: store.prefs) { _, _ in + // The Sleep page gates and builds the tile from these — refresh it immediately. + PulseDataChange.shared.notify() + } + } + + private var mealsGroup: some View { + SettingsGroup(header: "Meals", footer: mealsFooter) { + FormToggleRow(title: "Show meals", isOn: prefs.showMeals) + FormMenuRow(title: "Which meals", value: store.prefs.mealSelection == .smart ? "Smart" : "Custom") { + Picker("Which meals", selection: prefs.mealSelection) { + Text("Smart").tag(CircadianSelectionMode.smart) + Text("Custom").tag(CircadianSelectionMode.manual) + } + } + .disabled(!mealsOn) + .opacity(mealsOn ? 1 : 0.5) + Group { + FormToggleRow(title: "Breakfast", isOn: prefs.showBreakfast) + FormToggleRow(title: "Lunch", isOn: prefs.showLunch) + FormToggleRow(title: "Dinner", isOn: prefs.showDinner) + } + .disabled(!customMeals) + .opacity(customMeals ? 1 : 0.5) + } + .disabled(!tileOn || !nutritionOn) + .opacity(tileOn && nutritionOn ? 1 : 0.5) + } + + private var mealsFooter: String { + guard nutritionOn else { + return "Meals come from nutrition tracking, which is off. Turn it on in Settings, under Nutrition." + } + return "Smart shows a meal only when you log it regularly: \(Self.habitRule). " + + "Custom shows the meals you pick below. Snacks are never shown." + } + + private var workoutsGroup: some View { + SettingsGroup( + header: "Workouts", + footer: "A workout appears as a green band at the time you trained, with a runner for cardio or " + + "weights for strength. Smart shows workouts only when you train regularly: \(Self.habitRule). " + + "Always shows every workout." + ) { + FormToggleRow(title: "Show workouts", isOn: prefs.showWorkouts) + FormMenuRow(title: "When", value: store.prefs.workoutSelection == .smart ? "Smart" : "Always") { + Picker("When", selection: prefs.workoutSelection) { + Text("Smart").tag(CircadianSelectionMode.smart) + Text("Always").tag(CircadianSelectionMode.manual) + } + } + .disabled(!workoutsOn) + .opacity(workoutsOn ? 1 : 0.5) + } + .disabled(!tileOn) + .opacity(tileOn ? 1 : 0.5) + } +} diff --git a/PulseLoop/Views/SettingsView.swift b/PulseLoop/Views/SettingsView.swift index fca2041f..9af28f52 100644 --- a/PulseLoop/Views/SettingsView.swift +++ b/PulseLoop/Views/SettingsView.swift @@ -128,6 +128,12 @@ struct SettingsView: View { trailingValue: NutritionPrefsStore.shared.prefs.masterEnabled ? "On" : "Off" ) { path.append(AppRoute.settingsNutrition) + }, + SettingsRowItem( + icon: "sun.and.horizon", tint: PulseColors.rhythm, title: "Circadian Rhythm", + trailingValue: CircadianPrefsStore.shared.prefs.enabled ? "On" : "Off" + ) { + path.append(AppRoute.settingsCircadian) } ] } diff --git a/PulseLoop/Views/SleepView.swift b/PulseLoop/Views/SleepView.swift index d92ddcb5..85832bda 100644 --- a/PulseLoop/Views/SleepView.swift +++ b/PulseLoop/Views/SleepView.swift @@ -21,10 +21,18 @@ struct SleepView: View { /// True while a press-and-hold scrub is active on a hypnogram. Pauses this screen's scroll /// views (outer vertical + session carousel) so the scrub drag doesn't pan them. @State private var hypnogramScrubbing = false + /// Observed so the circadian tile appears, disappears and re-filters as its settings change. + @State private var circadianStore = CircadianPrefsStore.shared + @State private var showCircadian: Bool + /// A coach question picked on the circadian sheet, asked once that sheet has closed (the + /// coach is a sheet on the tab view, and two sheets can't be up at once). + @State private var pendingCoachAsk: (prompt: String, context: String)? init() { let raw = UserDefaults.standard.string(forKey: "startSleepRange") _range = State(initialValue: SleepRangeKey.allCases.first { $0.rawValue == raw } ?? .day) + // Optional `-openCircadian YES` launch arg (screenshot tooling): start on the detail sheet. + _showCircadian = State(initialValue: UserDefaults.standard.bool(forKey: "openCircadian")) } private var summaryService: CoachSummaryService { CoachSummaryService(modelContext: modelContext) } @@ -46,18 +54,21 @@ struct SleepView: View { let summary = SleepService.sleepRange(range, context: modelContext, now: range == .day ? effectiveNow : Date()) let goalMin = MetricsRepository.goals(context: modelContext)?.sleepMinutes let activitySteps = MetricsRepository.latestActivity(context: modelContext)?.steps + let shownDay = SleepService.dayReferenceNight(now: effectiveNow) + // The circadian tile covers whatever the page is showing: the selected day, or the range. + let circadian = circadianSnapshot(shownDay: shownDay, summary: summary) ScrollView { VStack(spacing: 16) { SleepRangeSelectorView(selection: $range) if range == .day { - dayNavHeader(shownDay: SleepService.dayReferenceNight(now: effectiveNow)) - dayView(summary: summary, activitySteps: activitySteps, isToday: dayOffset == 0) + dayNavHeader(shownDay: shownDay) + dayView(summary: summary, activitySteps: activitySteps, isToday: dayOffset == 0, circadian: circadian) .id(dayOffset) .transition(reduceMotion ? .opacity : .push(from: dayNavEdge)) } else { - aggregateView(summary: summary, goalMin: goalMin) + aggregateView(summary: summary, goalMin: goalMin, circadian: circadian) } } .padding(.horizontal, 16) @@ -75,6 +86,23 @@ struct SleepView: View { .sensoryFeedback(.selection, trigger: dayOffset) .onChange(of: dayOffset) { _, newOffset in announceDay(newOffset) } .sheet(isPresented: $showDayPicker) { dayPickerSheet } + .sensoryFeedback(.selection, trigger: showCircadian) + .sheet(isPresented: $showCircadian, onDismiss: askPendingCoachPrompt) { + if let circadian { + CircadianDetailSheet( + snapshot: circadian, + periodTitle: circadianPeriodTitle(shownDay: shownDay), + coachEnabled: coachEnabled, + onAskCoach: { prompt in + pendingCoachAsk = (prompt, circadian.coachContext) + showCircadian = false + } + ) + } else { + // The tile went away underneath the sheet (turned off, or its data was cleared). + Color.clear.onAppear { showCircadian = false } + } + } .task(id: "\(range.rawValue)-\(dayOffset)") { guard coachEnabled else { return } if range == .day { @@ -104,11 +132,48 @@ struct SleepView: View { } } + // MARK: Circadian + + /// Nil when the tile is switched off in Settings or there is nothing to draw. + private func circadianSnapshot(shownDay: Date, summary: SleepRangeSummary) -> CircadianSnapshot? { + guard circadianStore.prefs.enabled else { return nil } + let period = CircadianService.period(range: range, day: shownDay, summary: summary) + let snapshot = CircadianService.snapshot(period: period, context: modelContext, prefs: circadianStore.prefs) + return snapshot.isEmpty ? nil : snapshot + } + + /// The tile that opens every range's page, above the Last Sleep hero. + @ViewBuilder + private func circadianCard(_ snapshot: CircadianSnapshot?) -> some View { + if let snapshot { + CircadianRhythmCard(snapshot: snapshot) { showCircadian = true } + } + } + + private func circadianPeriodTitle(shownDay: Date) -> String { + switch range { + case .day: + let labels = dayLabels(shownDay) + return labels.secondary.isEmpty ? labels.primary : "\(labels.primary) · \(labels.secondary)" + case .week: return "Past 7 days" + case .month: return "Past 30 days" + case .year: return "Past year" + } + } + + /// Runs when the circadian sheet has finished closing: hand its question to the coach. + private func askPendingCoachPrompt() { + guard let ask = pendingCoachAsk else { return } + pendingCoachAsk = nil + CoachNavigation.shared.ask(ask.prompt, context: ask.context) + } + // MARK: Day @ViewBuilder - private func dayView(summary: SleepRangeSummary, activitySteps: Int?, isToday: Bool) -> some View { + private func dayView(summary: SleepRangeSummary, activitySteps: Int?, isToday: Bool, circadian: CircadianSnapshot?) -> some View { let sessions = SleepInsights.validSessions(summary.sessions).sorted { $0.session.startAt < $1.session.startAt } + circadianCard(circadian) if sessions.isEmpty { // The "wear your ring" explainer lives in the architecture card ONLY — the hero and // stage cards just dash out, so the message isn't repeated all over one page. @@ -410,7 +475,7 @@ struct SleepView: View { // MARK: Aggregate @ViewBuilder - private func aggregateView(summary: SleepRangeSummary, goalMin: Int?) -> some View { + private func aggregateView(summary: SleepRangeSummary, goalMin: Int?, circadian: CircadianSnapshot?) -> some View { // Collapse naps into their day so the hero's "N of M nights tracked" counts distinct nights, // consistent with the (already-collapsing) averages and coach copy. let valid = SleepInsights.collapseByDay(SleepInsights.validSessions(summary.sessions)) @@ -428,7 +493,8 @@ struct SleepView: View { : SleepInsights.buildNightAxis(start: summary.start, end: summary.end, sessions: summary.sessions, range: range) let vizTitle = range == .year ? "Monthly average" : "Nightly sleep" - // Hero card opens the page; coach card closes it. + // The circadian tile, then the hero card, open the page; the coach card closes it. + circadianCard(circadian) SleepHeroCardView( label: SleepInsights.rangeHeroLabel[range] ?? "Sleep", value: enough ? SleepFormat.duration(avgMin) : noData.value, diff --git a/PulseLoopTests/CircadianRhythmTests.swift b/PulseLoopTests/CircadianRhythmTests.swift new file mode 100644 index 00000000..dca672dc --- /dev/null +++ b/PulseLoopTests/CircadianRhythmTests.swift @@ -0,0 +1,503 @@ +import SwiftData +import XCTest +@testable import PulseLoop + +/// Pure-logic coverage for the circadian tile: clock math, the usual-vs-period engine, Smart +/// inclusion, the headline copy, formatting, prefs, and the dial's time → angle mapping. +@MainActor +final class CircadianRhythmTests: XCTestCase { + // A fixed calendar and reference day keep every case independent of the machine's clock/zone. + private let cal: Calendar = { + var c = Calendar(identifier: .gregorian) + c.timeZone = TimeZone(identifier: "America/New_York")! + return c + }() + + /// Day 0 — the day (or the last day of the range) being viewed. + private var today: Date { cal.date(from: DateComponents(year: 2026, month: 6, day: 20))! } + + private func day(_ offset: Int) -> Date { cal.date(byAdding: .day, value: offset, to: today)! } + + private func at(_ dayOffset: Int, _ hour: Int, _ minute: Int) -> Date { + cal.date(bySettingHour: hour, minute: minute, second: 0, of: day(dayOffset))! + } + + /// A night keyed on waking day `offset`. An evening bedtime (hour >= 12) falls on the day before. + private func night(_ offset: Int, bed: (Int, Int) = (23, 0), wake: (Int, Int) = (7, 0)) -> CircadianSleepSample { + let start = at(bed.0 >= 12 ? offset - 1 : offset, bed.0, bed.1) + let end = at(offset, wake.0, wake.1) + return CircadianSleepSample(day: day(offset), start: start, end: end, minutes: Int(end.timeIntervalSince(start) / 60)) + } + + private func meal(_ offset: Int, _ kind: CircadianAnchorKind, _ hour: Int, _ minute: Int) -> CircadianMealSample { + CircadianMealSample(day: day(offset), time: at(offset, hour, minute), kind: kind) + } + + private func workout(_ offset: Int, _ hour: Int = 18, minutes: Double = 45, + _ category: CircadianWorkoutCategory = .cardio) -> CircadianWorkoutSample { + CircadianWorkoutSample(start: at(offset, hour, 0), durationMinutes: minutes, category: category, label: "Run") + } + + private var dayPeriod: CircadianPeriod { CircadianPeriod(scope: .day, start: today, end: today) } + + private func snapshot( + period: CircadianPeriod? = nil, + sleep: [CircadianSleepSample] = [], + meals: [CircadianMealSample] = [], + workouts: [CircadianWorkoutSample] = [], + prefs: CircadianPrefs? = nil, + nutritionEnabled: Bool = true + ) -> CircadianSnapshot { + CircadianEngine.snapshot( + period: period ?? dayPeriod, sleep: sleep, meals: meals, workouts: workouts, + prefs: prefs ?? .default, nutritionEnabled: nutritionEnabled, calendar: cal) + } + + /// `count` consecutive baseline nights ending yesterday, all at the same times. + private func baseline(_ count: Int = 10, bed: (Int, Int) = (23, 0), wake: (Int, Int) = (7, 0)) -> [CircadianSleepSample] { + (1...count).map { night(-$0, bed: bed, wake: wake) } + } + + // MARK: Clock math + + func testCircularMeanAveragesAcrossMidnight() throws { + let mean = try XCTUnwrap(CircadianMath.circularMean([1410.0, 30.0])) + XCTAssertEqual(CircadianMath.signedDelta(mean, from: 0), 0, accuracy: 0.01) + } + + func testCircularMeanIsNilWithoutACentre() { + XCTAssertNil(CircadianMath.circularMean([])) + XCTAssertNil(CircadianMath.circularMean([0, 720])) + } + + func testSignedDeltaTakesTheShortWayRound() { + XCTAssertEqual(CircadianMath.signedDelta(10, from: 1430), 20, accuracy: 0.001) + XCTAssertEqual(CircadianMath.signedDelta(1430, from: 10), -20, accuracy: 0.001) + XCTAssertEqual(CircadianMath.signedDelta(450, from: 420), 30, accuracy: 0.001) + } + + // MARK: Sleep anchors + + func testDayDriftIsMeasuredAgainstThePreviousThirtyDays() throws { + let snap = snapshot(sleep: baseline() + [night(0, bed: (23, 30), wake: (6, 30))]) + let wake = try XCTUnwrap(snap.anchor(.wake)) + let bed = try XCTUnwrap(snap.anchor(.bed)) + XCTAssertEqual(try XCTUnwrap(wake.usualMinutes), 420, accuracy: 0.01) + XCTAssertEqual(try XCTUnwrap(wake.deltaMinutes), -30, accuracy: 0.01) + XCTAssertEqual(try XCTUnwrap(bed.usualMinutes), 1380, accuracy: 0.01) + XCTAssertEqual(try XCTUnwrap(bed.deltaMinutes), 30, accuracy: 0.01) + XCTAssertFalse(snap.isLearning) + } + + func testTheSelectedDayIsNotPartOfItsOwnBaseline() throws { + // If today counted toward "usual", a late night would pull the average toward itself. + let snap = snapshot(sleep: baseline(5) + [night(0, bed: (1, 0), wake: (9, 0))]) + XCTAssertEqual(try XCTUnwrap(snap.anchor(.wake)?.usualMinutes), 420, accuracy: 0.01) + } + + func testNapsNeverMoveTheAnchors() throws { + let nap = CircadianSleepSample(day: today, start: at(0, 14, 0), end: at(0, 14, 45), minutes: 45) + let snap = snapshot(sleep: baseline() + [night(0), nap]) + XCTAssertEqual(try XCTUnwrap(snap.anchor(.wake)?.periodMinutes), 420, accuracy: 0.01) + XCTAssertEqual(try XCTUnwrap(snap.anchor(.bed)?.periodMinutes), 1380, accuracy: 0.01) + } + + func testALoneNapIsNotTreatedAsTheNight() throws { + let nap = CircadianSleepSample(day: today, start: at(0, 14, 0), end: at(0, 14, 45), minutes: 45) + let snap = snapshot(sleep: baseline() + [nap]) + let wake = try XCTUnwrap(snap.anchor(.wake)) + XCTAssertNil(wake.periodMinutes) + XCTAssertNotNil(wake.usualMinutes) + } + + func testAMissedNightStillShowsTheUsualDay() throws { + let snap = snapshot(sleep: baseline()) + XCTAssertFalse(snap.isEmpty) + XCTAssertNotNil(snap.anchor(.wake)?.usualMinutes) + XCTAssertNil(snap.anchor(.wake)?.deltaMinutes) + XCTAssertEqual(snap.headline, "Your usual day") + } + + func testGapsInTheBaselineAreTolerated() throws { + // Every other night missing: 15 of 30 nights is still a usual. + let sparse = stride(from: -1, through: -29, by: -2).map { night($0) } + let snap = snapshot(sleep: sparse + [night(0, wake: (7, 40))]) + XCTAssertEqual(try XCTUnwrap(snap.anchor(.wake)?.deltaMinutes), 40, accuracy: 0.01) + } + + func testBaselineUsesWhateverHistoryExistsDownToFiveNights() throws { + XCTAssertNotNil(snapshot(sleep: baseline(5) + [night(0)]).anchor(.wake)?.usualMinutes) + let four = snapshot(sleep: baseline(4) + [night(0)]) + XCTAssertNil(four.anchor(.wake)?.usualMinutes) + XCTAssertTrue(four.isLearning) + XCTAssertEqual(four.headline, "Learning your rhythm") + XCTAssertEqual(four.subline, "Needs 1 more night") + } + + func testNightsOlderThanThirtyDaysDoNotCount() throws { + let old = (35...44).map { night(-$0, bed: (2, 0), wake: (10, 0)) } + let snap = snapshot(sleep: old + baseline(6) + [night(0)]) + XCTAssertEqual(try XCTUnwrap(snap.anchor(.wake)?.usualMinutes), 420, accuracy: 0.01) + } + + func testNothingAtAllIsEmpty() { + XCTAssertTrue(snapshot().isEmpty) + } + + // MARK: Meals + + func testSmartMealsNeedTenOfTwentyEightDays() { + // Spread so no 7-day window holds four of them: only the 28-day rule can apply. + let nine = stride(from: -3, through: -27, by: -3).map { meal($0, .breakfast, 8, 0) } + XCTAssertEqual(nine.count, 9) + XCTAssertNil(snapshot(sleep: baseline(), meals: nine).anchor(.breakfast)) + let ten = nine + [meal(-1, .breakfast, 8, 0)] + XCTAssertNotNil(snapshot(sleep: baseline(), meals: ten).anchor(.breakfast)) + } + + func testSmartMealsPickUpANewHabitWithinAWeek() { + let four = [0, -1, -2, -3].map { meal($0, .lunch, 12, 30) } + XCTAssertNotNil(snapshot(sleep: baseline(), meals: four).anchor(.lunch)) + XCTAssertNil(snapshot(sleep: baseline(), meals: Array(four.prefix(3))).anchor(.lunch)) + } + + func testAnEstablishedMealSurvivesAMissedWeek() throws { + // Logged daily until a week ago, nothing since: still a habit, and still has a usual. + let lapsed = (8...27).map { meal(-$0, .dinner, 19, 0) } + let snap = snapshot(sleep: baseline(), meals: lapsed) + let dinner = try XCTUnwrap(snap.anchor(.dinner)) + XCTAssertEqual(try XCTUnwrap(dinner.usualMinutes), 1140.0, accuracy: 0.01) + XCTAssertNil(dinner.periodMinutes) + } + + func testManualMealChoiceOverridesHowOftenTheyAreLogged() throws { + var prefs = CircadianPrefs.default + prefs.mealSelection = .manual + prefs.showLunch = false + let daily = (0...20).flatMap { [meal(-$0, .lunch, 12, 30)] } + let fewBreakfasts = [meal(0, .breakfast, 8, 30)] + let snap = snapshot(sleep: baseline(), meals: daily + fewBreakfasts, prefs: prefs) + XCTAssertNil(snap.anchor(.lunch)) + // Chosen by hand but with no usual yet: it sits at today's time with no drift. + let breakfast = try XCTUnwrap(snap.anchor(.breakfast)) + XCTAssertNil(breakfast.usualMinutes) + XCTAssertNil(breakfast.deltaMinutes) + XCTAssertEqual(breakfast.displayMinutes, 510.0, accuracy: 0.01) + } + + func testMealsHideWhenNutritionOrTheMealSwitchIsOff() { + let daily = (0...20).map { meal(-$0, .dinner, 19, 0) } + XCTAssertNil(snapshot(sleep: baseline(), meals: daily, nutritionEnabled: false).anchor(.dinner)) + var prefs = CircadianPrefs.default + prefs.showMeals = false + XCTAssertNil(snapshot(sleep: baseline(), meals: daily, prefs: prefs).anchor(.dinner)) + } + + func testAMealUsesTheFirstEntryOfItsTypeThatDay() throws { + let history = (1...12).map { meal(-$0, .dinner, 19, 0) } + let today = [meal(0, .dinner, 21, 0), meal(0, .dinner, 19, 45)] + let snap = snapshot(sleep: baseline(), meals: history + today) + XCTAssertEqual(try XCTUnwrap(snap.anchor(.dinner)?.deltaMinutes), 45, accuracy: 0.01) + } + + func testSnacksHaveNoAnchor() { + XCTAssertNil(CircadianAnchorKind(mealType: .snack)) + XCTAssertEqual(CircadianAnchorKind(mealType: .dinner), .dinner) + } + + func testAnchorsComeBackInDayOrder() { + let meals = (0...12).flatMap { [meal(-$0, .dinner, 19, 0), meal(-$0, .breakfast, 8, 0), meal(-$0, .lunch, 13, 0)] } + let kinds = snapshot(sleep: baseline() + [night(0)], meals: meals).anchors.map(\.kind) + XCTAssertEqual(kinds, [.wake, .breakfast, .lunch, .dinner, .bed]) + } + + // MARK: Workouts + + func testSmartWorkoutsOnlyShowWhenRegular() { + let rare = [workout(0), workout(-9), workout(-20)] + XCTAssertTrue(snapshot(sleep: baseline(), workouts: rare).workouts.isEmpty) + let regular = [workout(0), workout(-1), workout(-3), workout(-5)] + XCTAssertEqual(snapshot(sleep: baseline(), workouts: regular).workouts.count, 1) + } + + func testManualWorkoutsAlwaysShowAndTheSwitchHidesThem() throws { + var prefs = CircadianPrefs.default + prefs.workoutSelection = .manual + let snap = snapshot(sleep: baseline(), workouts: [workout(0, 18, minutes: 45, .strength)], prefs: prefs) + let span = try XCTUnwrap(snap.workouts.first) + XCTAssertEqual(span.startMinutes, 1080.0, accuracy: 0.01) + XCTAssertEqual(span.durationMinutes, 45, accuracy: 0.01) + XCTAssertEqual(span.category, .strength) + XCTAssertFalse(span.isTypical) + + prefs.showWorkouts = false + XCTAssertTrue(snapshot(sleep: baseline(), workouts: [workout(0)], prefs: prefs).workouts.isEmpty) + } + + func testOnlyTheSelectedDaysWorkoutsAreDrawnAndBlipsAreDropped() { + var prefs = CircadianPrefs.default + prefs.workoutSelection = .manual + let all = [workout(0, 7), workout(0, 18), workout(-1, 18), workout(0, 12, minutes: 2)] + let spans = snapshot(sleep: baseline(), workouts: all, prefs: prefs).workouts + XCTAssertEqual(spans.map(\.startMinutes), [420.0, 1080.0]) + } + + func testARangeShowsOneTypicalWorkout() throws { + let week = CircadianPeriod(scope: .week, start: day(-6), end: today) + let sessions = [ + workout(0, 18, minutes: 40, .strength), workout(-2, 18, minutes: 50, .strength), + workout(-4, 18, minutes: 60), workout(-5, 18) + ] + let span = try XCTUnwrap(snapshot(period: week, sleep: baseline(20), workouts: sessions).workouts.first) + XCTAssertTrue(span.isTypical) + XCTAssertEqual(span.startMinutes, 1080.0, accuracy: 0.01) + XCTAssertEqual(span.durationMinutes, 48.75, accuracy: 0.01) // mean of 40, 50, 60, 45 + } + + func testWorkoutTypesMapToTwoIcons() { + XCTAssertEqual(CircadianWorkoutCategory.from(type: "gym"), .strength) + XCTAssertEqual(CircadianWorkoutCategory.from(type: "strength"), .strength) + XCTAssertEqual(CircadianWorkoutCategory.from(type: "run"), .cardio) + XCTAssertEqual(CircadianWorkoutCategory.from(type: "yoga"), .cardio) + XCTAssertEqual(CircadianWorkoutCategory.from(type: "something_new"), .cardio) + XCTAssertEqual(CircadianWorkoutCategory.strength.symbol, "dumbbell.fill") + XCTAssertEqual(CircadianWorkoutCategory.cardio.symbol, "figure.run") + } + + // MARK: Ranges + + func testAWeekIsComparedToTheThirtyDaysBeforeIt() throws { + let week = CircadianPeriod(scope: .week, start: day(-6), end: today) + let before = (7...30).map { night(-$0) } + let during = (0...6).map { night(-$0, bed: (23, 40)) } + let snap = snapshot(period: week, sleep: before + during) + XCTAssertEqual(try XCTUnwrap(snap.anchor(.bed)?.deltaMinutes), 40, accuracy: 0.01) + XCTAssertEqual(try XCTUnwrap(snap.anchor(.wake)?.deltaMinutes), 0, accuracy: 0.01) + XCTAssertEqual(snap.headline, "Bedtime ran late") + } + + func testAWeekWithMissedNightsStillAverages() throws { + let week = CircadianPeriod(scope: .week, start: day(-6), end: today) + let before = (7...30).map { night(-$0) } + let snap = snapshot(period: week, sleep: before + [night(-1, wake: (7, 20)), night(-4, wake: (7, 40))]) + XCTAssertEqual(try XCTUnwrap(snap.anchor(.wake)?.deltaMinutes), 30, accuracy: 0.01) + } + + func testARangeWithNoEarlierHistoryShowsItsTypicalDay() throws { + let month = CircadianPeriod(scope: .month, start: day(-29), end: today) + let snap = snapshot(period: month, sleep: (0...29).map { night(-$0) }) + XCTAssertFalse(snap.isLearning) + XCTAssertFalse(snap.hasDrift) + XCTAssertEqual(try XCTUnwrap(snap.anchor(.wake)?.displayMinutes), 420, accuracy: 0.01) + XCTAssertEqual(snap.headline, "Your typical day") + XCTAssertEqual(snap.subline, "No earlier baseline yet") + + let year = CircadianPeriod(scope: .year, start: day(-364), end: today) + XCTAssertEqual(snapshot(period: year, sleep: (0...40).map { night(-$0) }).subline, "Past year's average") + } + + func testAThinRangeIsStillLearning() { + let week = CircadianPeriod(scope: .week, start: day(-6), end: today) + let snap = snapshot(period: week, sleep: [night(0), night(-1), night(-2)]) + XCTAssertTrue(snap.isLearning) + XCTAssertEqual(snap.subline, "Needs 2 more nights") + } + + // MARK: Headlines + + private func headline(_ deltas: [(CircadianAnchorKind, Double)], scope: CircadianScope = .day) -> (String, String) { + let anchors = deltas.map { CircadianAnchor(kind: $0.0, usualMinutes: 600, periodMinutes: 600 + $0.1) } + let copy = CircadianEngine.summary(scope: scope, anchors: anchors, isLearning: false, nightsNeeded: 1) + return (copy.headline, copy.subline) + } + + func testHeadlines() { + XCTAssertEqual(headline([(.wake, -22), (.bed, 14)]).0, "On rhythm") + XCTAssertEqual(headline([(.wake, -22), (.bed, 14)]).1, "All 2 within 30 min") + + let mealsLate = headline([(.wake, -22), (.breakfast, -15), (.lunch, 50), (.dinner, 60), (.bed, 14)]) + XCTAssertEqual(mealsLate.0, "Meals ran late") + XCTAssertEqual(mealsLate.1, "Sleep held steady") + + XCTAssertEqual(headline([(.breakfast, -45), (.dinner, 50), (.wake, 5)]).0, "Meals off schedule") + XCTAssertEqual(headline([(.wake, 40), (.bed, 5), (.lunch, -5)]).0, "Wake-up ran late") + XCTAssertEqual(headline([(.wake, 40), (.bed, 5), (.lunch, -5)]).1, "Meals held steady") + XCTAssertEqual(headline([(.wake, 45), (.bed, -50)]).0, "Sleep off schedule") + XCTAssertEqual(headline([(.wake, 45), (.lunch, -40)]).0, "Off rhythm") + XCTAssertEqual(headline([(.wake, 45), (.lunch, -40), (.bed, 3)]).1, "1 of 3 within 30 min") + + let late = headline([(.wake, 35), (.lunch, 40), (.bed, 45)]) + XCTAssertEqual(late.0, "Running late") + XCTAssertEqual(late.1, "About 40m later") + XCTAssertEqual(headline([(.wake, 18), (.lunch, 10), (.bed, 62)], scope: .week).0, "Shifted later") + XCTAssertEqual(headline([(.wake, -35), (.bed, -45)]).0, "Running early") + + // Every line has to fit inside the dial. + for copy in [mealsLate, late, headline([(.wake, 45), (.lunch, -40)]), headline([(.wake, -22), (.bed, 14)])] { + XCTAssertLessThanOrEqual(copy.1.count, 24, copy.1) + } + } + + // MARK: Formatting + + func testFormatting() { + XCTAssertEqual(CircadianFormat.duration(22), "22m") + XCTAssertEqual(CircadianFormat.duration(60), "1h") + XCTAssertEqual(CircadianFormat.duration(65), "1h 5m") + XCTAssertEqual(CircadianFormat.signed(50), "+50m") + XCTAssertEqual(CircadianFormat.signed(-22), "\u{2212}22m") + XCTAssertEqual(CircadianFormat.words(-22), "22m earlier") + XCTAssertEqual(CircadianFormat.words(60), "1h later") + XCTAssertEqual(CircadianFormat.words(0.2), "On time") + XCTAssertEqual(CircadianFormat.spoken(-82), "1 hour 22 minutes earlier than usual") + XCTAssertEqual(CircadianFormat.clock(423), "7:03 AM") + XCTAssertEqual(CircadianFormat.clock(0), "12:00 AM") + XCTAssertEqual(CircadianFormat.clock(765.0), "12:45 PM") + XCTAssertEqual(CircadianFormat.clock(1439.7), "12:00 AM") + } + + // MARK: Prefs + + func testPrefsDefaultToOnAndSmart() { + let prefs = CircadianPrefs.default + XCTAssertTrue(prefs.enabled) + XCTAssertTrue(prefs.showMeals) + XCTAssertTrue(prefs.showWorkouts) + XCTAssertEqual(prefs.mealSelection, .smart) + XCTAssertEqual(prefs.workoutSelection, .smart) + } + + func testPrefsDecodeTolerantlyAndPersist() throws { + let partial = try JSONDecoder().decode(CircadianPrefs.self, from: Data(#"{"enabled":false}"#.utf8)) + XCTAssertFalse(partial.enabled) + XCTAssertTrue(partial.showMeals) + XCTAssertEqual(try JSONDecoder().decode(CircadianPrefs.self, from: Data("{}".utf8)), .default) + + let suite = "circadian-prefs-tests-\(UUID().uuidString)" + let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) + defer { defaults.removePersistentDomain(forName: suite) } + let store = CircadianPrefsStore(defaults: defaults) + XCTAssertTrue(store.prefs.enabled) + store.prefs.enabled = false + store.prefs.mealSelection = .manual + store.prefs.showDinner = false + let reloaded = CircadianPrefsStore(defaults: defaults).prefs + XCTAssertFalse(reloaded.enabled) + XCTAssertEqual(reloaded.mealSelection, .manual) + XCTAssertFalse(reloaded.showDinner) + XCTAssertFalse(reloaded.includesMeal(.dinner)) + XCTAssertTrue(reloaded.includesMeal(.lunch)) + } + + // MARK: Dial geometry + + func testSemicircleRunsFourAMToFourAMLeftToRight() { + let dial = CircadianDialGeometry(shape: .semicircle) + let center = CGPoint(x: 100, y: 100) + let start = dial.point(240.0, radius: 50, center: center) + XCTAssertEqual(start.x, 50, accuracy: 0.01) + XCTAssertEqual(start.y, 100, accuracy: 0.01) + let apex = dial.point(960.0, radius: 50, center: center) // 4 PM, halfway through the day + XCTAssertEqual(apex.x, 100, accuracy: 0.01) + XCTAssertEqual(apex.y, 50, accuracy: 0.01) + let late = dial.point(239.0, radius: 50, center: center) + XCTAssertGreaterThan(late.x, 149.9) + // Nothing ever lands below the baseline. + for minute in stride(from: 0.0, to: 1440, by: 30) { + XCTAssertLessThanOrEqual(dial.point(minute, radius: 50, center: center).y, 100.01) + } + } + + func testFullDialPutsNoonOnTopAndMidnightAtTheBottom() { + let dial = CircadianDialGeometry(shape: .full) + let center = CGPoint(x: 100, y: 100) + XCTAssertEqual(dial.point(720.0, radius: 50, center: center).y, 50, accuracy: 0.01) + XCTAssertEqual(dial.point(0, radius: 50, center: center).y, 150, accuracy: 0.01) + XCTAssertEqual(dial.point(1080.0, radius: 50, center: center).x, 150, accuracy: 0.01) + XCTAssertEqual(dial.point(360.0, radius: 50, center: center).x, 50, accuracy: 0.01) + } + + func testOvernightSleepSplitsAtTheSemicircleSeam() { + let bed = 22.0 * 60 + 48, wake = 7.0 * 60 + 3 + let semi = CircadianDialGeometry(shape: .semicircle) + let pieces = semi.arcs(from: bed, to: wake) + XCTAssertEqual(pieces.count, 2) + XCTAssertEqual(pieces.map(\.sweep).reduce(0, +), 495 * semi.sweepPerMinute, accuracy: 1e-9) + XCTAssertEqual(pieces[1].startAngle, .pi, accuracy: 1e-9) // resumes at the left foot + + let full = CircadianDialGeometry(shape: .full) + XCTAssertEqual(full.arcs(from: bed, to: wake).count, 1) + XCTAssertEqual(full.arcs(from: bed, to: wake)[0].sweep, 495 * full.sweepPerMinute, accuracy: 1e-9) + XCTAssertEqual(semi.arcs(from: 1080.0, to: 1125.0).count, 1) + XCTAssertTrue(semi.arcs(from: 600, to: 600).isEmpty) + } + + func testSpreadSeparatesCloseMarkersWithoutReordering() { + let input = [7.0 * 60, 7.0 * 60 + 30, 13.0 * 60, 23.0 * 60] + let out = CircadianDialGeometry.spread(input, minGap: 80) + XCTAssertEqual(out[1] - out[0], 80, accuracy: 0.1) + XCTAssertEqual((out[0] + out[1]) / 2, (input[0] + input[1]) / 2, accuracy: 0.1) // pushed symmetrically + XCTAssertEqual(out[2], input[2], accuracy: 0.01) + XCTAssertEqual(out[3], input[3], accuracy: 0.01) + XCTAssertEqual(CircadianDialGeometry.spread([600], minGap: 80), [600]) + } + + func testOverlappingLabelsAreDroppedInPriorityOrder() { + let a = CGRect(x: 0, y: 0, width: 30, height: 14) + let b = CGRect(x: 20, y: 5, width: 30, height: 14) + let c = CGRect(x: 100, y: 0, width: 30, height: 14) + XCTAssertEqual(CircadianDialGeometry.keepLabels([a, b, c]), [true, false, true]) + } + + // MARK: Coach hand-off + + func testCoachPromptsAndContext() { + let meals = (0...12).map { meal(-$0, .dinner, $0 == 0 ? 20 : 19, 0) } + let snap = snapshot(sleep: baseline() + [night(0)], meals: meals) + XCTAssertEqual(snap.coachPrompts.count, 3) + XCTAssertEqual(snap.coachPrompts.first, "How does eating later than usual affect my sleep?") + XCTAssertTrue(snap.coachContext.contains("dinner 8:00 PM (usual 7:00 PM, 1h later)")) + XCTAssertTrue(snap.coachContext.contains("wake 7:00 AM")) + XCTAssertEqual(snapshot(sleep: [night(0)]).coachPrompts.count, 3) + } + + // MARK: Store integration + + func testServiceReadsSleepMealsAndWorkoutsFromTheStore() throws { + let context = try TestSupport.makeContext() + let calendar = Calendar.current + let today = calendar.startOfDay(for: Date()) + func moment(_ dayOffset: Int, _ hour: Int, _ minute: Int = 0) -> Date { + let base = calendar.date(byAdding: .day, value: dayOffset, to: today)! + return calendar.date(bySettingHour: hour, minute: minute, second: 0, of: base)! + } + for offset in 0...12 { + let wakeDay = calendar.date(byAdding: .day, value: -offset, to: today)! + let late = offset == 0 + context.insert(SleepSession( + date: wakeDay, startAt: moment(-offset - 1, 23), endAt: moment(-offset, late ? 8 : 7), totalMinutes: late ? 540 : 480)) + context.insert(MealEntry(timestamp: moment(-offset, 19), name: "Dinner", mealType: .dinner, calories: 600)) + context.insert(MealEntry(timestamp: moment(-offset, 16), name: "Snack", mealType: .snack, calories: 100)) + } + for offset in [0, 1, 2, 4] { + context.insert(ActivitySession( + type: "gym", status: .finished, startedAt: moment(-offset, 18), endedAt: moment(-offset, 18, 45))) + } + // Still recording: must not appear. + context.insert(ActivitySession(type: "run", status: .recording, startedAt: moment(0, 6))) + try context.save() + + let period = CircadianPeriod(scope: .day, start: today, end: today) + let snap = CircadianService.snapshot(period: period, context: context, prefs: .default, nutritionEnabled: true) + XCTAssertEqual(snap.anchors.map(\.kind), [.wake, .dinner, .bed]) + XCTAssertEqual(try XCTUnwrap(snap.anchor(.wake)?.deltaMinutes), 60, accuracy: 0.5) + XCTAssertEqual(try XCTUnwrap(snap.anchor(.dinner)?.deltaMinutes), 0, accuracy: 0.5) + XCTAssertEqual(snap.workouts.count, 1) + XCTAssertEqual(snap.workouts.first?.category, .strength) + XCTAssertEqual(try XCTUnwrap(snap.workouts.first?.durationMinutes), 45, accuracy: 0.5) + XCTAssertEqual(snap.headline, "Wake-up ran late") + + let withoutNutrition = CircadianService.snapshot(period: period, context: context, prefs: .default, nutritionEnabled: false) + XCTAssertEqual(withoutNutrition.anchors.map(\.kind), [.wake, .bed]) + } +}