diff --git a/Documentation/Screenshots/Phone Daily Insulin.png b/Documentation/Screenshots/Phone Daily Insulin.png deleted file mode 100644 index c29ab07df2..0000000000 Binary files a/Documentation/Screenshots/Phone Daily Insulin.png and /dev/null differ diff --git a/Documentation/Screenshots/Phone Statistics.png b/Documentation/Screenshots/Phone Statistics.png deleted file mode 100644 index c04d076974..0000000000 Binary files a/Documentation/Screenshots/Phone Statistics.png and /dev/null differ diff --git a/Loop Widget Extension/Bootstrap/Localizable.xcstrings b/Loop Widget Extension/Bootstrap/Localizable.xcstrings index ef9bff8e52..661080c39c 100644 --- a/Loop Widget Extension/Bootstrap/Localizable.xcstrings +++ b/Loop Widget Extension/Bootstrap/Localizable.xcstrings @@ -5,6 +5,18 @@ "comment" : "A space.", "isCommentAutoGenerated" : true }, + "%1$@ g" : { + "comment" : "Amount of carbohydrate in grams. (1: number)" + }, + "%1$@ U" : { + "comment" : "Insulin amount in units. (1: number)" + }, + "%1$@ U/h" : { + "comment" : "Insulin rate in units per hour. (1: number)" + }, + "%1$@ · %2$@ in 5 min" : { + "comment" : "Under the glucose value on the Now screen: the glucose unit and how much glucose changed over 5 minutes. (1: glucose unit, e.g. mmol/L; 2: signed change, e.g. +0.3)" + }, "---" : { "localizations" : { "da" : { @@ -657,6 +669,24 @@ } } }, + "Add carbs" : { + "comment" : "Button on the Now screen that opens carb entry" + }, + "Basal" : { + "comment" : "Label of a tile showing the current basal rate (Now screen) or the day's basal insulin total (Today so far totals)" + }, + "Bolus" : { + "comment" : "Button on the Now screen that opens the bolus screen" + }, + "Closed loop · %1$@" : { + "comment" : "Status pill on the Now screen: closed loop is on. (1: how long ago Loop last ran, e.g. 2m)" + }, + "Closed loop · not run yet" : { + "comment" : "Status pill on the Now screen when closed loop is on but Loop hasn't completed a run yet" + }, + "COB" : { + "comment" : "Abbreviation for carbs on board; label of a tile on the Now screen" + }, "Color" : { "localizations" : { "de" : { @@ -984,6 +1014,12 @@ } } }, + "Eventually" : { + "comment" : "Short label above the glucose Loop predicts at the end of its prediction, in a small tile on the widget and Live Activity. Keep it to one short word, such as 'Forecast'." + }, + "Eventually %1$@ %2$@" : { + "comment" : "Header detail of the Next 3 hours card on the Now screen: the glucose Loop predicts at the end of its prediction. (1: glucose value; 2: glucose unit)" + }, "g" : { "comment" : "The short unit display string for grams", "extractionState" : "stale", @@ -1190,6 +1226,15 @@ } } }, + "High" : { + "comment" : "Pill under the glucose value on the Now screen when glucose is above 250 mg/dL (13.9 mmol/L)" + }, + "Last reading %1$@ ago" : { + "comment" : "Shown on the Now screen under No reading when the latest CGM reading is too old. (1: duration, e.g. 25m)" + }, + "Loop hasn't run for %1$@" : { + "comment" : "Notice title on the Now screen when Loop hasn't completed a run recently. (1: duration, e.g. 25m)" + }, "Loop Status Widget" : { "localizations" : { "da" : { @@ -1266,6 +1311,9 @@ } } }, + "Low" : { + "comment" : "Pill under the glucose value on the Now screen when glucose is below 70 mg/dL (3.9 mmol/L)" + }, "mg/dL" : { "comment" : "The short unit display string for milligrams of glucose per decilter", "extractionState" : "stale", @@ -1518,6 +1566,15 @@ } } }, + "No reading" : { + "comment" : "Shown on the Now screen in place of the glucose value when there is no recent CGM reading" + }, + "Open loop · %1$@" : { + "comment" : "Status pill on the Now screen: closed loop is off. (1: how long ago Loop last ran, e.g. 2m)" + }, + "Open loop · not run yet" : { + "comment" : "Status pill on the Now screen when closed loop is off and Loop hasn't completed a run yet" + }, "Open the app to update the widget" : { "comment" : "No comment", "localizations" : { @@ -1559,6 +1616,12 @@ } } }, + "Pre-meal" : { + "comment" : "Menu item under Presets on the Now screen that turns on the pre-meal target" + }, + "Pre-meal on" : { + "comment" : "Presets button title on the Now screen while the pre-meal target is on" + }, "Preset override" : { "localizations" : { "de" : { @@ -1599,6 +1662,9 @@ } } }, + "Presets" : { + "comment" : "Button on the Now screen that opens override presets (and pre-meal); also its VoiceOver label and menu item" + }, "QUANTITY_VALUE_AND_UNIT" : { "comment" : "Format string for combining localized numeric value and unit. (1: numeric value)(2: unit)", "extractionState" : "extracted_with_value", @@ -1966,6 +2032,9 @@ } } } + }, + "Urgent low" : { + "comment" : "Pill under the glucose value on the Now screen when glucose is below 54 mg/dL (3.0 mmol/L)" } }, "version" : "1.1" diff --git a/Loop Widget Extension/DerivedAssetsBase.xcassets/accent.colorset/Contents.json b/Loop Widget Extension/DerivedAssetsBase.xcassets/accent.colorset/Contents.json new file mode 100644 index 0000000000..9b711cb95b --- /dev/null +++ b/Loop Widget Extension/DerivedAssetsBase.xcassets/accent.colorset/Contents.json @@ -0,0 +1,15 @@ +{ + "colors" : [ + { + "color" : { + "platform" : "ios", + "reference" : "systemBlueColor" + }, + "idiom" : "universal" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/Loop Widget Extension/DerivedAssetsBase.xcassets/carbs.colorset/Contents.json b/Loop Widget Extension/DerivedAssetsBase.xcassets/carbs.colorset/Contents.json new file mode 100644 index 0000000000..5d023a96b0 --- /dev/null +++ b/Loop Widget Extension/DerivedAssetsBase.xcassets/carbs.colorset/Contents.json @@ -0,0 +1,68 @@ +{ + "colors" : [ + { + "color" : { + "color-space" : "srgb", + "components" : { + "alpha" : "1.000", + "blue" : "0.220", + "green" : "0.855", + "red" : "0.388" + } + }, + "idiom" : "universal" + }, + { + "appearances" : [ + { + "appearance" : "luminosity", + "value" : "dark" + } + ], + "color" : { + "color-space" : "srgb", + "components" : { + "alpha" : "1.000", + "blue" : "0.200", + "green" : "0.894", + "red" : "0.349" + } + }, + "idiom" : "universal" + }, + { + "appearances" : [ + { + "appearance" : "contrast", + "value" : "high" + } + ], + "color" : { + "platform" : "ios", + "reference" : "systemGreenColor" + }, + "idiom" : "universal" + }, + { + "appearances" : [ + { + "appearance" : "luminosity", + "value" : "dark" + }, + { + "appearance" : "contrast", + "value" : "high" + } + ], + "color" : { + "platform" : "ios", + "reference" : "systemGreenColor" + }, + "idiom" : "universal" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/Loop Widget Extension/Live Activity/GlucoseLiveActivityConfiguration.swift b/Loop Widget Extension/Live Activity/GlucoseLiveActivityConfiguration.swift index 5358d6e27a..d01d347aab 100644 --- a/Loop Widget Extension/Live Activity/GlucoseLiveActivityConfiguration.swift +++ b/Loop Widget Extension/Live Activity/GlucoseLiveActivityConfiguration.swift @@ -45,6 +45,8 @@ struct GlucoseLiveActivityConfiguration: Widget { // banner on the Home Screen of devices that don't support the Dynamic Island. if #available(iOS 18.0, *) { AdaptiveLockScreenView(context: context) + } else if WidgetDesign.useRedesign { + RedesignLiveActivity.lockScreen(context) } else { fullLockScreenView(context: context) } @@ -56,7 +58,13 @@ struct GlucoseLiveActivityConfiguration: Widget { @Environment(\.activityFamily) private var activityFamily var body: some View { - if activityFamily == .small { + if WidgetDesign.useRedesign { + if activityFamily == .small { + RedesignLiveActivity.smallFamily(context) + } else { + RedesignLiveActivity.lockScreen(context) + } + } else if activityFamily == .small { // WatchOS & CarPlay supplemental view - show only bottom row compactLockScreenView(context: context) } else { @@ -261,6 +269,9 @@ struct GlucoseLiveActivityConfiguration: Widget { private func dynamicIslandView( context: ActivityViewContext ) -> DynamicIsland { + if WidgetDesign.useRedesign { + return RedesignLiveActivity.dynamicIsland(context) + } let glucoseFormatter = NumberFormatter.glucoseFormatter( for: context.state.isMmol ? LoopUnit.millimolesPerLiter : LoopUnit.milligramsPerDeciliter diff --git a/Loop Widget Extension/Redesign/RedesignLiveActivity.swift b/Loop Widget Extension/Redesign/RedesignLiveActivity.swift new file mode 100644 index 0000000000..4f13ec26ce --- /dev/null +++ b/Loop Widget Extension/Redesign/RedesignLiveActivity.swift @@ -0,0 +1,373 @@ +// +// RedesignLiveActivity.swift +// Loop Widget Extension +// +// Copyright © 2026 LoopKit Authors. All rights reserved. +// + +import ActivityKit +import Charts +import HealthKit +import LoopCore +import LoopKit +import LoopAlgorithm +import SwiftUI +import WidgetKit + +/// The Live Activity in the redesign's style. It reads the same `GlucoseActivityAttributes` as the +/// classic one, so the Live Activity settings (chart, bottom row, limits) keep working. +@available(iOS 16.2, *) +enum RedesignLiveActivity { + typealias Context = ActivityViewContext + private typealias P = LoopDesign.Palette + + // MARK: - Shared pieces + + private static func unitName(_ context: Context) -> String { + (context.state.isMmol ? LoopUnit.millimolesPerLiter : LoopUnit.milligramsPerDeciliter).localizedShortUnitString + } + + private static func format(_ value: Double, _ context: Context) -> String { + NumberFormatter.glucoseFormatter(for: context.state.isMmol ? .millimolesPerLiter : .milligramsPerDeciliter).string(from: value) ?? "–" + } + + static func range(_ context: Context) -> WidgetDesign.Range? { + WidgetDesign.Range(context.state.currentGlucose, isMmol: context.state.isMmol) + } + + static func status(_ context: Context) -> WidgetDesign.LoopStatus { + WidgetDesign.LoopStatus(closedLoop: context.state.isCloseLoop, lastCompleted: context.state.isCloseLoop ? context.state.lastCompleted : context.state.date) + } + + /// Low and high in words, otherwise the unit and the change, as under the Now screen's number. + @ViewBuilder + private static func detail(_ context: Context) -> some View { + if let range = range(context) { + HStack(spacing: LoopDesign.Space.s1) { + Circle().fill(range.color).frame(width: 7, height: 7) + Text(range.text) + } + .font(.caption.weight(.semibold)) + .foregroundStyle(P.ink) + } else { + Text(WidgetDesign.readingDetail(unit: unitName(context), delta: context.state.delta)) + .font(.caption) + .foregroundStyle(P.inkMuted) + .lineLimit(1) + .minimumScaleFactor(0.8) + } + } + + private static func eventually(_ context: Context) -> String? { + context.state.eventualGlucose.map { + String(format: NSLocalizedString("Eventually %1$@ %2$@", comment: "Header detail of the Next 3 hours card on the Now screen: the glucose Loop predicts at the end of its prediction. (1: glucose value; 2: glucose unit)"), format($0, context), unitName(context)) + } + } + + private static func hero(_ context: Context, size: CGFloat) -> some View { + VStack(alignment: .leading, spacing: 0) { + WidgetGlucoseValue(value: format(context.state.currentGlucose, context), trend: context.state.trendType, size: size) + detail(context) + } + } + + // MARK: - Lock Screen + + static func lockScreen(_ context: Context) -> some View { + VStack(alignment: .leading, spacing: LoopDesign.Space.s1) { + HStack(alignment: .top) { + hero(context, size: context.attributes.mode == .large ? 30 : 38) + Spacer(minLength: LoopDesign.Space.s2) + VStack(alignment: .trailing, spacing: 4) { + WidgetStatusLine(status: status(context)) + if let eventually = eventually(context) { + Text(eventually) + .font(.caption) + .foregroundStyle(P.inkMuted) + .lineLimit(1) + .minimumScaleFactor(0.8) + } + } + } + if context.attributes.mode == .large { + RedesignActivityChart(context: context) + .frame(height: 54) + } + let tiles = tileItems(context) + if !tiles.isEmpty { + HStack(spacing: 6) { + ForEach(tiles, id: \.self) { item in + tile(item, context, inline: context.attributes.mode == .large) + } + } + .padding(.top, 2) + } + } + .padding(.horizontal, 14) + .padding(.vertical, 10) + .overlay { + if context.state.ended { + Text(NSLocalizedString("Open the app to update the widget", comment: "No comment")) + .font(.subheadline.weight(.semibold)) + .foregroundStyle(P.ink) + .frame(maxWidth: .infinity, maxHeight: .infinity) + .background(.ultraThinMaterial) + } + } + .privacySensitive() + .activityBackgroundTint(P.surfaceRaised.opacity(0.92)) + .activitySystemActionForegroundColor(P.ink) + } + + /// The watch and CarPlay size: the number, the change and the prediction. + static func smallFamily(_ context: Context) -> some View { + HStack(alignment: .center) { + hero(context, size: 26) + Spacer(minLength: LoopDesign.Space.s1) + VStack(alignment: .trailing, spacing: 2) { + Circle().fill(status(context).color).frame(width: 8, height: 8) + if let eventual = context.state.eventualGlucose { + Text(format(eventual, context)) + .font(.system(.headline, design: .rounded).weight(.semibold).monospacedDigit()) + .foregroundStyle(P.ink) + Text(NSLocalizedString("Eventually", comment: "Short label above the glucose Loop predicts at the end of its prediction, in a small tile on the widget and Live Activity. Keep it to one short word, such as 'Forecast'.")) + .font(.caption2) + .foregroundStyle(P.inkMuted) + } + } + } + .padding(LoopDesign.Space.s3) + .privacySensitive() + } + + /// The configured bottom row, less the reading and its change, which the hero already shows. + private static func tileItems(_ context: Context) -> [BottomRowItem] { + context.state.bottomRow.filter { item in + switch item.type { + case .currentBg: return false + case .generic: return item.value != context.state.delta || item.unit != "" + case .basal: return true + } + } + } + + @ViewBuilder + private static func tile(_ item: BottomRowItem, _ context: Context, inline: Bool) -> some View { + switch item.type { + case .basal: + WidgetTile(label: NSLocalizedString("Basal", comment: "Label of a tile showing the current basal rate (Now screen) or the day's basal insulin total (Today so far totals)"), inline: inline) { + Text(String(format: NSLocalizedString("%1$@ U/h", comment: "Insulin rate in units per hour. (1: number)"), WidgetDesign.signed(item.rate, decimals: 2))) + .foregroundStyle(P.insulin) + } + case .generic, .currentBg: + WidgetTile(label: item.label, inline: inline) { + switch item.unit { + case "U": + Text(String(format: NSLocalizedString("%1$@ U", comment: "Insulin amount in units. (1: number)"), item.value)) + .foregroundStyle(P.insulin) + case "g": + Text(String(format: NSLocalizedString("%1$@ g", comment: "Amount of carbohydrate in grams. (1: number)"), item.value)) + .foregroundStyle(P.carbs) + default: + Text(item.value) + .foregroundStyle(P.ink) + } + } + } + } + + // MARK: - Dynamic Island + + static func dynamicIsland(_ context: Context) -> DynamicIsland { + DynamicIsland { + DynamicIslandExpandedRegion(.leading) { + hero(context, size: 34) + .padding(.leading, LoopDesign.Space.s1) + .dynamicIsland(verticalPlacement: .belowIfTooWide) + } + // The trailing region is narrow, so it holds only the prediction, labelled like the widget's tile; + // Loop's status gets the full width above the chart, where long translations still fit. + DynamicIslandExpandedRegion(.trailing) { + if let eventual = context.state.eventualGlucose { + VStack(alignment: .trailing, spacing: 0) { + Text(NSLocalizedString("Eventually", comment: "Short label above the glucose Loop predicts at the end of its prediction, in a small tile on the widget and Live Activity. Keep it to one short word, such as 'Forecast'.")) + .font(.caption2) + .foregroundStyle(P.inkMuted) + .lineLimit(1) + .minimumScaleFactor(0.7) + Text(format(eventual, context)) + .font(.system(.title3, design: .rounded).weight(.semibold).monospacedDigit()) + .foregroundStyle(P.ink) + } + .padding(.trailing, LoopDesign.Space.s1) + .padding(.top, LoopDesign.Space.s1) + } + } + DynamicIslandExpandedRegion(.bottom) { + VStack(alignment: .leading, spacing: LoopDesign.Space.s1) { + WidgetStatusLine(status: status(context), font: .caption.weight(.medium)) + RedesignActivityChart(context: context) + .frame(height: 46) + } + .padding(.horizontal, LoopDesign.Space.s1) + } + } compactLeading: { + HStack(spacing: 3) { + Text(format(context.state.currentGlucose, context)) + .font(.system(.body, design: .rounded).weight(.semibold).monospacedDigit()) + .foregroundStyle(.white) + .minimumScaleFactor(0.6) + if let trend = context.state.trendType { + Image(systemName: WidgetDesign.trendSymbol(trend)) + .font(.system(size: 11, weight: .bold)) + .foregroundStyle(P.glucose) + } + } + } compactTrailing: { + HStack(spacing: 4) { + if let range = range(context) { + Text(range.text) + .font(.caption.weight(.semibold)) + .foregroundStyle(range.color) + } else { + Text(context.state.delta) + .font(.system(.caption, design: .rounded).weight(.medium).monospacedDigit()) + .foregroundStyle(Color(white: 0.75)) + } + Circle().fill(status(context).color).frame(width: 6, height: 6) + } + .minimumScaleFactor(0.6) + } minimal: { + Text(format(context.state.currentGlucose, context)) + .font(.system(.caption, design: .rounded).weight(.semibold).monospacedDigit()) + .foregroundStyle(.white) + .minimumScaleFactor(0.5) + } + // The island's outline says low or high, so the number itself stays white. + .keylineTint(range(context)?.color ?? P.glucose) + } +} + +// MARK: - Chart + +/// The Now screen's prediction chart, sized for the Live Activity: blue readings, Loop's dashed +/// prediction and the target band. +@available(iOS 16.2, *) +struct RedesignActivityChart: View { + let context: ActivityViewContext + private typealias P = LoopDesign.Palette + + private var lowerLimit: Double { + context.state.isMmol ? context.attributes.lowerLimitChartMmol : context.attributes.lowerLimitChartMg + } + + private var upperLimit: Double { + context.state.isMmol ? context.attributes.upperLimitChartMmol : context.attributes.upperLimitChartMg + } + + /// With "use limits" on, readings below them are red and above them yellow, as Loop's warnings are; the rest stay blue. + private func color(_ value: Double) -> Color { + guard context.attributes.useLimits else { return P.glucose } + if value < lowerLimit { return P.statusCritical } + if value > upperLimit { return P.statusWarning } + return P.glucose + } + + private var prediction: [(Date, Double)] { + guard context.attributes.addPredictiveLine, let start = context.state.predicatedStartDate else { return [] } + let interval = context.state.predicatedInterval ?? .minutes(5) + let end = start.addingTimeInterval(.hours(3)) + return context.state.predicatedGlucose.enumerated() + .map { (start.addingTimeInterval(interval * Double($0.offset)), $0.element) } + .filter { $0.0 <= end } + } + + private var domain: ClosedRange { + let marks = context.state.yAxisMarks + return (marks.first ?? 0)...(marks.last ?? 1) + } + + private func clamp(_ value: Double) -> Double { + min(max(value, domain.lowerBound), domain.upperBound) + } + + /// The readings Loop sent and its prediction, at least an hour ahead, as on the Now screen's chart. + private var window: ClosedRange { + let now = context.state.date + let start = min(context.state.glucoseSamples.first?.x ?? now.addingTimeInterval(.hours(-3)), now.addingTimeInterval(.hours(-1))) + let end = max(prediction.last?.0 ?? now, now.addingTimeInterval(.hours(1))) + return start...end + } + + var body: some View { + Chart { + ForEach(context.state.glucoseRanges.filter { $0.endDate > window.lowerBound && $0.startDate < window.upperBound }) { band in + RectangleMark(xStart: .value("Start", max(band.startDate, window.lowerBound)), xEnd: .value("End", min(band.endDate, window.upperBound)), + yStart: .value("Low", clamp(band.minValue)), yEnd: .value("High", clamp(max(band.maxValue, band.minValue + domainPadding)))) + .foregroundStyle(band.isOverride ? P.accent.opacity(0.25) : P.targetBand) + } + ForEach(Array(context.state.glucoseSamples.enumerated()), id: \.offset) { _, sample in + PointMark(x: .value("Time", sample.x), y: .value("Glucose", clamp(sample.y))) + .symbolSize(9) + .foregroundStyle(color(sample.y)) + } + ForEach(Array(prediction.enumerated()), id: \.offset) { _, point in + LineMark(x: .value("Time", point.0), y: .value("Predicted", clamp(point.1)), series: .value("Series", "prediction")) + .foregroundStyle(P.glucose) + .lineStyle(StrokeStyle(lineWidth: 1.5, dash: [4, 3])) + } + RuleMark(x: .value("Now", context.state.date)) + .foregroundStyle(P.inkMuted) + .lineStyle(StrokeStyle(lineWidth: 1, dash: [2, 3])) + } + .chartXScale(domain: window) + .chartYScale(domain: domain) + .chartYAxis { + AxisMarks(position: .leading, values: axisLabels) { _ in + AxisGridLine().foregroundStyle(P.grid) + AxisValueLabel().font(LoopDesign.Typeface.caption).foregroundStyle(P.inkMuted) + } + } + .chartXAxis { + AxisMarks(values: hourMarks) { _ in + AxisGridLine().foregroundStyle(P.grid) + AxisValueLabel(format: .dateTime.hour()).font(LoopDesign.Typeface.caption).foregroundStyle(P.inkMuted) + } + } + .chartLegend(.hidden) + .overlay(alignment: .topTrailing) { + if let preset = context.state.preset, preset.endDate > context.state.date { + Text(preset.title) + .font(.caption2.weight(.semibold)) + .foregroundStyle(P.ink) + .padding(.horizontal, 6) + .padding(.vertical, 2) + .background(P.accent.opacity(0.25), in: Capsule()) + } + } + .accessibilityHidden(true) + } + + /// Whole hours inside the window, kept clear of the edges so their labels aren't clipped. + private var hourMarks: [Date] { + let calendar = Calendar.current + guard var hour = calendar.dateInterval(of: .hour, for: window.lowerBound)?.end else { return [] } + var marks: [Date] = [] + while hour <= window.upperBound.addingTimeInterval(.minutes(-25)) { + if hour >= window.lowerBound.addingTimeInterval(.minutes(12)) { marks.append(hour) } + hour = hour.addingTimeInterval(.hours(1)) + } + return marks + } + + /// Every other value Loop suggests, so labels don't crowd a chart this short. + private var axisLabels: [Double] { + let marks = context.state.yAxisMarks + return marks.count > 3 ? marks.enumerated().filter { $0.offset % 2 == 0 }.map(\.element) : marks + } + + /// A single-value target is drawn as a thin band, so it stays visible. + private var domainPadding: Double { + (domain.upperBound - domain.lowerBound) / 60 + } +} diff --git a/Loop Widget Extension/Redesign/RedesignStatusWidgetView.swift b/Loop Widget Extension/Redesign/RedesignStatusWidgetView.swift new file mode 100644 index 0000000000..5a2c27141f --- /dev/null +++ b/Loop Widget Extension/Redesign/RedesignStatusWidgetView.swift @@ -0,0 +1,173 @@ +// +// RedesignStatusWidgetView.swift +// Loop Widget Extension +// +// Copyright © 2026 LoopKit Authors. All rights reserved. +// + +import HealthKit +import LoopCore +import LoopKit +import LoopAlgorithm +import SwiftUI +import WidgetKit + +/// The home screen widget in the redesign's style: the Now screen's hero on the left, and in the medium +/// size the Now screen's actions on the right. +struct RedesignStatusWidgetView: View { + @Environment(\.widgetFamily) private var family + @Environment(\.widgetRenderingMode) private var renderingMode + + let entry: StatusWidgetTimelimeEntry + + private typealias P = LoopDesign.Palette + + var body: some View { + HStack(spacing: LoopDesign.Space.s3) { + status + if family != .systemSmall { + actions + } + } + .padding(LoopDesign.Space.s3) + .frame(maxWidth: .infinity, maxHeight: .infinity) + .redesignWidgetBackground(renderingMode == .accented ? .clear : P.surfaceRaised) + } + + // MARK: - Status + + private var status: some View { + VStack(alignment: .leading, spacing: 0) { + WidgetStatusLine(status: WidgetDesign.LoopStatus(closedLoop: entry.closeLoop, lastCompleted: entry.closeLoop ? entry.lastLoopCompleted : entry.mostRecentGlucoseDataDate, now: entry.date)) + .opacity(entry.contextIsStale ? 0.6 : 1) + Spacer(minLength: LoopDesign.Space.s1) + reading + Spacer(minLength: LoopDesign.Space.s2) + footer + } + .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .leading) + } + + @ViewBuilder + private var reading: some View { + if let glucose = entry.currentGlucose, let unit = entry.unit, !entry.glucoseIsStale { + let value = glucose.quantity.doubleValue(for: unit) + VStack(alignment: .leading, spacing: 0) { + WidgetGlucoseValue( + value: NumberFormatter.glucoseFormatter(for: unit).string(from: value) ?? "–", + trend: entry.sensor?.trendType, + size: 40 + ) + if let range = WidgetDesign.Range(mgdl: glucose.quantity.doubleValue(for: .milligramsPerDeciliter)) { + HStack(spacing: LoopDesign.Space.s1) { + Circle().fill(range.color).frame(width: 7, height: 7) + Text(range.text) + } + .font(.caption.weight(.semibold)) + .foregroundStyle(P.ink) + } else { + Text(WidgetDesign.readingDetail(unit: unit.localizedShortUnitString, delta: delta(in: unit))) + .font(.caption) + .foregroundStyle(P.inkMuted) + .lineLimit(1) + .minimumScaleFactor(0.8) + } + } + .opacity(entry.glucoseStatusIsStale ? 0.6 : 1) + } else { + VStack(alignment: .leading, spacing: 2) { + Text(NSLocalizedString("No reading", comment: "Shown on the Now screen in place of the glucose value when there is no recent CGM reading")) + .font(.system(size: 22, weight: .bold, design: .rounded)) + .foregroundStyle(P.inkMuted) + .lineLimit(1) + .minimumScaleFactor(0.7) + if let date = entry.currentGlucose?.startDate { + Text(String(format: NSLocalizedString("Last reading %1$@ ago", comment: "Shown on the Now screen under No reading when the latest CGM reading is too old. (1: duration, e.g. 25m)"), WidgetDesign.duration(entry.date.timeIntervalSince(date)))) + .font(.caption) + .foregroundStyle(P.inkMuted) + .lineLimit(1) + .minimumScaleFactor(0.8) + } + } + } + } + + private func delta(in unit: LoopUnit) -> String? { + guard let delta = entry.delta else { return nil } + return WidgetDesign.signed(delta.doubleValue(for: unit), decimals: unit == .millimolesPerLiter ? 1 : 0) + } + + /// A device problem replaces the tiles, as notices lead the Now screen. + @ViewBuilder + private var footer: some View { + if let notice = WidgetNotice.mostSerious([entry.pumpHighlight, entry.cgmHighlight]) { + notice + } else { + HStack(spacing: 6) { + WidgetTile(label: NSLocalizedString("COB", comment: "Abbreviation for carbs on board; label of a tile on the Now screen")) { + Text(entry.carbsOnBoard.map { String(format: NSLocalizedString("%1$@ g", comment: "Amount of carbohydrate in grams. (1: number)"), Self.number($0, decimals: 0)) } ?? "–") + .foregroundStyle(P.carbs) + } + WidgetTile(label: NSLocalizedString("Eventually", comment: "Short label above the glucose Loop predicts at the end of its prediction, in a small tile on the widget and Live Activity. Keep it to one short word, such as 'Forecast'.")) { + Text(eventual ?? "–") + .foregroundStyle(P.ink) + } + } + .opacity(entry.contextIsStale ? 0.6 : 1) + } + } + + private var eventual: String? { + guard let eventual = entry.eventualGlucose else { return nil } + return NumberFormatter.glucoseFormatter(for: eventual.unit).string(from: eventual.quantity.doubleValue(for: eventual.unit)) + } + + static func number(_ value: Double, decimals: Int) -> String { + value.formatted(.number.precision(.fractionLength(decimals))) + } + + // MARK: - Actions + + private var actions: some View { + VStack(spacing: 6) { + HStack(spacing: 6) { + action(.carbEntry(nil), NSLocalizedString("Add carbs", comment: "Button on the Now screen that opens carb entry"), "fork.knife", fill: P.carbs, ink: P.onFill) + action(.bolus, NSLocalizedString("Bolus", comment: "Button on the Now screen that opens the bolus screen"), "syringe.fill", fill: P.insulin, ink: P.onFill) + } + HStack(spacing: 6) { + if entry.preMealPresetAllowed { + action(.preMeal, + entry.preMealPresetActive + ? NSLocalizedString("Pre-meal on", comment: "Presets button title on the Now screen while the pre-meal target is on") + : NSLocalizedString("Pre-meal", comment: "Menu item under Presets on the Now screen that turns on the pre-meal target"), + "fork.knife.circle", + fill: entry.preMealPresetActive ? P.accent.opacity(0.18) : WidgetDesign.sunken, ink: P.ink) + } + action(.customPresets, NSLocalizedString("Presets", comment: "Button on the Now screen that opens override presets (and pre-meal); also its VoiceOver label and menu item"), "slider.horizontal.3", + fill: entry.customPresetActive ? P.accent.opacity(0.18) : WidgetDesign.sunken, ink: P.ink) + } + } + .frame(maxWidth: .infinity, maxHeight: .infinity) + } + + private func action(_ destination: Deeplink, _ title: String, _ symbol: String, fill: Color, ink: Color) -> some View { + Link(destination: URL(string: "loop://\(destination.host.rawValue)")!) { + VStack(alignment: .leading, spacing: 2) { + Image(systemName: symbol) + .font(.system(size: 15, weight: .semibold)) + Spacer(minLength: 0) + Text(title) + .font(.footnote.weight(.semibold)) + .lineLimit(2) + .minimumScaleFactor(0.7) + } + .foregroundStyle(renderingMode == .accented ? P.ink : ink) + .padding(LoopDesign.Space.s2) + .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .leading) + .background( + renderingMode == .accented ? AnyShapeStyle(.white.opacity(0.12)) : AnyShapeStyle(fill), + in: RoundedRectangle(cornerRadius: LoopDesign.Radius.md, style: .continuous) + ) + } + } +} diff --git a/Loop Widget Extension/Redesign/WidgetDesign.swift b/Loop Widget Extension/Redesign/WidgetDesign.swift new file mode 100644 index 0000000000..b19aa2ea84 --- /dev/null +++ b/Loop Widget Extension/Redesign/WidgetDesign.swift @@ -0,0 +1,251 @@ +// +// WidgetDesign.swift +// Loop Widget Extension +// +// Copyright © 2026 LoopKit Authors. All rights reserved. +// + +import HealthKit +import LoopCore +import LoopKit +import SwiftUI + +/// The redesign's rules for the widget and Live Activity, so they read like the Now screen: the glucose +/// number is never tinted, low and high are said in words, and Loop's state is a dot with words. +enum WidgetDesign { + /// The tile fill. The app's sunken grey disappears against a dark home screen widget, so the + /// widget uses a translucent ink that reads on both light and dark. + static let sunken = LoopDesign.Palette.ink.opacity(0.08) + + /// Matches the app's interface setting, which the app mirrors into the app group. + static var useRedesign: Bool { UserDefaults.appGroup?.redesignEnabled ?? true } + + static func trendSymbol(_ trend: GlucoseTrend) -> String { + switch trend { + case .upUpUp: return "arrow.up.to.line" + case .upUp: return "chevron.up.2" + case .up: return "arrow.up" + case .flat: return "arrow.right" + case .down: return "arrow.down" + case .downDown: return "chevron.down.2" + case .downDownDown: return "arrow.down.to.line" + } + } + + enum Range { + case urgentLow, low, high + + /// The Now screen's thresholds: below 54 and 70 mg/dL, above 250 mg/dL. + init?(mgdl: Double) { + switch mgdl { + case ..<54: self = .urgentLow + case ..<70: self = .low + case 250.0.nextUp...: self = .high + default: return nil + } + } + + init?(_ value: Double, isMmol: Bool) { + let unit: HKUnit = isMmol ? .millimolesPerLiter : .milligramsPerDeciliter + self.init(mgdl: HKQuantity(unit: unit, doubleValue: value).doubleValue(for: .milligramsPerDeciliter)) + } + + var text: String { + switch self { + case .urgentLow: return NSLocalizedString("Urgent low", comment: "Pill under the glucose value on the Now screen when glucose is below 54 mg/dL (3.0 mmol/L)") + case .low: return NSLocalizedString("Low", comment: "Pill under the glucose value on the Now screen when glucose is below 70 mg/dL (3.9 mmol/L)") + case .high: return NSLocalizedString("High", comment: "Pill under the glucose value on the Now screen when glucose is above 250 mg/dL (13.9 mmol/L)") + } + } + + var color: Color { + self == .high ? LoopDesign.Palette.statusWarning : LoopDesign.Palette.statusCritical + } + } + + /// Loop's state as on the Now pill. The time of the last run stands in for the Now screen's age, + /// because a widget isn't redrawn every minute and an age would go stale on screen. + /// While the loop is open Loop doesn't complete runs, so callers pass the latest reading's time instead. + struct LoopStatus { + let text: String + let color: Color + + init(closedLoop: Bool, lastCompleted: Date?, now: Date = Date()) { + typealias P = LoopDesign.Palette + guard let lastCompleted else { + text = closedLoop + ? NSLocalizedString("Closed loop · not run yet", comment: "Status pill on the Now screen when closed loop is on but Loop hasn't completed a run yet") + : NSLocalizedString("Open loop · not run yet", comment: "Status pill on the Now screen when closed loop is off and Loop hasn't completed a run yet") + color = P.inkMuted + return + } + let age = max(0, now.timeIntervalSince(lastCompleted)) + if closedLoop, LoopCompletionFreshness(age: age) == .stale { + text = String(format: NSLocalizedString("Loop hasn't run for %1$@", comment: "Notice title on the Now screen when Loop hasn't completed a run recently. (1: duration, e.g. 25m)"), WidgetDesign.duration(age)) + color = P.statusWarning + return + } + let time = lastCompleted.formatted(date: .omitted, time: .shortened) + if closedLoop { + text = String(format: NSLocalizedString("Closed loop · %1$@", comment: "Status pill on the Now screen: closed loop is on. (1: how long ago Loop last ran, e.g. 2m)"), time) + color = LoopCompletionFreshness(age: age) == .fresh ? P.statusAutomated : P.statusWarning + } else { + text = String(format: NSLocalizedString("Open loop · %1$@", comment: "Status pill on the Now screen: closed loop is off. (1: how long ago Loop last ran, e.g. 2m)"), time) + color = LoopCompletionFreshness(age: age) == .fresh ? P.inkMuted : P.statusWarning + } + } + } + + static func duration(_ interval: TimeInterval) -> String { + let formatter = DateComponentsFormatter() + formatter.unitsStyle = .abbreviated + formatter.allowedUnits = interval >= 3600 ? [.hour, .minute] : [.minute] + formatter.maximumUnitCount = 2 + return formatter.string(from: interval) ?? "" + } + + /// "mmol/L · +0.2 in 5 min", as under the number on the Now screen. + static func readingDetail(unit: String, delta: String?) -> String { + guard let delta, !delta.isEmpty else { return unit } + return String(format: NSLocalizedString("%1$@ · %2$@ in 5 min", comment: "Under the glucose value on the Now screen: the glucose unit and how much glucose changed over 5 minutes. (1: glucose unit, e.g. mmol/L; 2: signed change, e.g. +0.3)"), unit, delta) + } + + static func signed(_ value: Double, decimals: Int) -> String { + let formatter = NumberFormatter() + formatter.numberStyle = .decimal + formatter.minimumFractionDigits = decimals + formatter.maximumFractionDigits = decimals + formatter.positivePrefix = formatter.plusSign + return formatter.string(from: NSNumber(value: value)) ?? "" + } +} + +/// The status dot with words, as on the Now screen's first pill. +struct WidgetStatusLine: View { + let status: WidgetDesign.LoopStatus + var font: Font = LoopDesign.Typeface.footnote.weight(.medium) + + var body: some View { + HStack(spacing: LoopDesign.Space.s1) { + Circle().fill(status.color).frame(width: 7, height: 7) + Text(status.text) + .lineLimit(1) + .minimumScaleFactor(0.75) + } + .font(font) + .foregroundStyle(LoopDesign.Palette.ink) + } +} + +/// The glucose number with its trend arrow, in the Now hero's type. +struct WidgetGlucoseValue: View { + let value: String + let trend: GlucoseTrend? + var size: CGFloat + + var body: some View { + HStack(alignment: .center, spacing: size * 0.12) { + Text(value) + .font(.system(size: size, weight: .bold, design: .rounded).monospacedDigit()) + .foregroundStyle(LoopDesign.Palette.ink) + .lineLimit(1) + .minimumScaleFactor(0.6) + .widgetAccentable() + if let trend { + Image(systemName: WidgetDesign.trendSymbol(trend)) + .font(.system(size: size * 0.45, weight: .bold)) + .foregroundStyle(LoopDesign.Palette.glucose) + .accessibilityLabel(trend.localizedDescription) + } + } + } +} + +/// A sunken tile with a label over a value, the widget-sized `ValueTile`. +struct WidgetTile: View { + @Environment(\.widgetRenderingMode) private var renderingMode + let label: String + /// Label and value on one line, where height is short (the Live Activity has 160 points). + var inline = false + @ViewBuilder var value: Value + + var body: some View { + let layout = inline + ? AnyLayout(HStackLayout(alignment: .firstTextBaseline, spacing: LoopDesign.Space.s1)) + : AnyLayout(VStackLayout(alignment: .leading, spacing: 1)) + layout { + Text(label) + .font(.caption2) + .foregroundStyle(LoopDesign.Palette.inkMuted) + .lineLimit(1) + .minimumScaleFactor(0.7) + value + .font(.system(.subheadline, design: .rounded).weight(.semibold).monospacedDigit()) + .lineLimit(1) + .minimumScaleFactor(0.6) + } + .padding(.horizontal, LoopDesign.Space.s2) + .padding(.vertical, inline ? 5 : 6) + .frame(maxWidth: .infinity, alignment: .leading) + .background( + renderingMode == .accented ? AnyShapeStyle(.white.opacity(0.12)) : AnyShapeStyle(WidgetDesign.sunken), + in: RoundedRectangle(cornerRadius: LoopDesign.Radius.md, style: .continuous) + ) + .accessibilityElement(children: .combine) + } +} + +/// A device problem said in words, as in the Now screen's notices. +struct WidgetNotice: View { + let message: String + let symbol: String + let state: DeviceStatusHighlightState + + /// Critical first, then warnings, then information such as a sensor warming up. + static func mostSerious(_ highlights: [DeviceStatusHighlightContext?]) -> WidgetNotice? { + let rank: (DeviceStatusHighlightState) -> Int = { $0 == .critical ? 0 : $0 == .warning ? 1 : 2 } + guard let highlight = highlights.compactMap({ $0 }).min(by: { rank($0.state) < rank($1.state) }) else { return nil } + return WidgetNotice(message: highlight.localizedMessage, symbol: highlight.imageName, state: highlight.state) + } + + private var tint: Color { + switch state { + case .critical: return LoopDesign.Palette.statusCritical + case .warning: return LoopDesign.Palette.statusWarning + default: return LoopDesign.Palette.glucose + } + } + + var body: some View { + HStack(alignment: .top, spacing: 6) { + Image(systemName: symbol) + .font(.caption.weight(.bold)) + .foregroundStyle(tint) + Text(message.replacingOccurrences(of: "\n", with: " ")) + .font(.caption.weight(.semibold)) + .foregroundStyle(LoopDesign.Palette.ink) + .lineLimit(2) + .minimumScaleFactor(0.8) + } + .padding(.horizontal, LoopDesign.Space.s2) + .padding(.vertical, 6) + .frame(maxWidth: .infinity, alignment: .leading) + .background( + tint.opacity(0.18), + in: RoundedRectangle(cornerRadius: LoopDesign.Radius.md, style: .continuous) + ) + .accessibilityElement(children: .combine) + } +} + +extension View { + /// The widget's container background, in the colour of a Now screen card. + @ViewBuilder + func redesignWidgetBackground(_ color: Color) -> some View { + if #available(iOSApplicationExtension 17.0, *) { + containerBackground(for: .widget) { color } + } else { + background { color } + } + } +} diff --git a/Loop Widget Extension/Timeline/StatusWidgetTimelimeEntry.swift b/Loop Widget Extension/Timeline/StatusWidgetTimelimeEntry.swift index 657eecb28d..49c0b19c0f 100644 --- a/Loop Widget Extension/Timeline/StatusWidgetTimelimeEntry.swift +++ b/Loop Widget Extension/Timeline/StatusWidgetTimelimeEntry.swift @@ -28,7 +28,9 @@ struct StatusWidgetTimelimeEntry: TimelineEntry { let sensor: GlucoseDisplayableContext? let pumpHighlight: DeviceStatusHighlightContext? + var cgmHighlight: DeviceStatusHighlightContext? = nil let netBasal: NetBasalContext? + var carbsOnBoard: Double? = nil let eventualGlucose: GlucoseContext? diff --git a/Loop Widget Extension/Timeline/StatusWidgetTimelineProvider.swift b/Loop Widget Extension/Timeline/StatusWidgetTimelineProvider.swift index cb0c7c5ce0..05ea39e916 100644 --- a/Loop Widget Extension/Timeline/StatusWidgetTimelineProvider.swift +++ b/Loop Widget Extension/Timeline/StatusWidgetTimelineProvider.swift @@ -173,7 +173,9 @@ class StatusWidgetTimelineProvider: TimelineProvider { unit: unit, sensor: context.glucoseDisplay, pumpHighlight: context.pumpStatusHighlightContext, + cgmHighlight: context.cgmStatusHighlightContext, netBasal: netBasal, + carbsOnBoard: context.carbsOnBoard, eventualGlucose: eventualGlucose, preMealPresetAllowed: preMealPresetAllowed, preMealPresetActive: preMealPresetActive, diff --git a/Loop Widget Extension/Widgets/SystemStatusWidget.swift b/Loop Widget Extension/Widgets/SystemStatusWidget.swift index fbe95f5384..4d8b6a6959 100644 --- a/Loop Widget Extension/Widgets/SystemStatusWidget.swift +++ b/Loop Widget Extension/Widgets/SystemStatusWidget.swift @@ -93,7 +93,11 @@ struct SystemStatusWidget: Widget { var body: some WidgetConfiguration { StaticConfiguration(kind: kind, provider: StatusWidgetTimelineProvider()) { entry in - SystemStatusWidgetEntryView(entry: entry) + if WidgetDesign.useRedesign { + RedesignStatusWidgetView(entry: entry) + } else { + SystemStatusWidgetEntryView(entry: entry) + } } .configurationDisplayName("Loop Status Widget") .description("See your current blood glucose and insulin delivery.") diff --git a/Loop.xcodeproj/project.pbxproj b/Loop.xcodeproj/project.pbxproj index 9a08a01da2..0f1980c19d 100644 --- a/Loop.xcodeproj/project.pbxproj +++ b/Loop.xcodeproj/project.pbxproj @@ -87,6 +87,10 @@ 82F11F858069EDA2DF65D909 /* Loop/Resources/Sounds/voice_lgs_bryce.caf in Resources */ = {isa = PBXBuildFile; fileRef = FB860882201269230F24C96C /* Loop/Resources/Sounds/voice_lgs_bryce.caf */; }; 0996021E82CDE7DA7A3DD544 /* Loop/Resources/Sounds/voice_ulg_amy.caf in Resources */ = {isa = PBXBuildFile; fileRef = B08A706BF6BC6555453D3E56 /* Loop/Resources/Sounds/voice_ulg_amy.caf */; }; 8BAF071E821EAC3FB1B183B3 /* Loop/Resources/Sounds/voice_ulg_bryce.caf in Resources */ = {isa = PBXBuildFile; fileRef = 1F9BFD4BD97793AAE2407DCB /* Loop/Resources/Sounds/voice_ulg_bryce.caf */; }; + E6E73709263FB037F274B2A0 /* WidgetDesign.swift in Sources */ = {isa = PBXBuildFile; fileRef = FDE6FCD6C3CA3B693C8A349B /* WidgetDesign.swift */; }; + 8602ACA648AEEBBD4793ED49 /* RedesignStatusWidgetView.swift in Sources */ = {isa = PBXBuildFile; fileRef = E169C989E88148A68A4FEFB6 /* RedesignStatusWidgetView.swift */; }; + FE8902221761558AAEDFFE02 /* RedesignLiveActivity.swift in Sources */ = {isa = PBXBuildFile; fileRef = DB9792C496505ED5C2F302AB /* RedesignLiveActivity.swift */; }; + 4CC1A96D0600081991783423 /* LoopDesign.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0BD3DDF41B598A8C4B5CEB92 /* LoopDesign.swift */; }; 1419606928D9554E00BA86E0 /* LoopKitUI.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 437AFEE6203688CF008C4892 /* LoopKitUI.framework */; }; 1419606A28D955BC00BA86E0 /* MockKitUI.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = C101947127DD473C004E7EB8 /* MockKitUI.framework */; }; 142CB7592A60BF2E0075748A /* EditMode.swift in Sources */ = {isa = PBXBuildFile; fileRef = 142CB7582A60BF2E0075748A /* EditMode.swift */; }; @@ -740,11 +744,7 @@ FA37F6EC10FF02D4F985D724 /* Loop/Resources/Sounds/honk.caf in Resources */ = {isa = PBXBuildFile; fileRef = 6D5FCC7207E50ACC682E9E6E /* Loop/Resources/Sounds/honk.caf */; }; FADE0001000000000000DE02 /* DevelopmentBranchAlerter.swift in Sources */ = {isa = PBXBuildFile; fileRef = FADE0001000000000000DE01 /* DevelopmentBranchAlerter.swift */; }; FEEDB0000000000000000000 /* GlucoseStatistics.swift in Sources */ = {isa = PBXBuildFile; fileRef = FEEDF0000000000000000000 /* GlucoseStatistics.swift */; }; - FEEDB0000000000000000001 /* StatisticsViewModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = FEEDF0000000000000000001 /* StatisticsViewModel.swift */; }; - FEEDB0000000000000000002 /* Statistics/StatisticsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = FEEDF0000000000000000002 /* Statistics/StatisticsView.swift */; }; - A3C9F155FD92DC188BD9A21F /* Statistics/DailyInsulinChartView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 747DA22B61531CCAAC79E86D /* Statistics/DailyInsulinChartView.swift */; }; - FEEDB0000000000000000003 /* Statistics/AGPChartView.swift in Sources */ = {isa = PBXBuildFile; fileRef = FEEDF0000000000000000003 /* Statistics/AGPChartView.swift */; }; - FEEDB0000000000000000004 /* Statistics/TimeInRangeBar.swift in Sources */ = {isa = PBXBuildFile; fileRef = FEEDF0000000000000000004 /* Statistics/TimeInRangeBar.swift */; }; + FEEDB0000000000000000004 /* Statistics/GlucoseBand+Display.swift in Sources */ = {isa = PBXBuildFile; fileRef = FEEDF0000000000000000004 /* Statistics/GlucoseBand+Display.swift */; }; 30E4A68B8C914C5E4B245555 /* InsulinDeliveryHistoryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = F69CE2EE3714858772FE7A26 /* InsulinDeliveryHistoryTests.swift */; }; FEEDB0000000000000000005 /* GlucoseStatisticsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = FEEDF0000000000000000005 /* GlucoseStatisticsTests.swift */; }; 17EA66859884C0208DED47CF /* LoopKitTypeAliases.swift in Sources */ = {isa = PBXBuildFile; fileRef = 35FAEFD820F50BFF211AC6D9 /* LoopKitTypeAliases.swift */; }; @@ -755,6 +755,20 @@ 8DC1CE32F39301122B550325 /* LoopKitTypeAliases.swift in Sources */ = {isa = PBXBuildFile; fileRef = 35FAEFD820F50BFF211AC6D9 /* LoopKitTypeAliases.swift */; }; ABD9218EB98C9216FBB04382 /* LoopKitTypeAliases.swift in Sources */ = {isa = PBXBuildFile; fileRef = 35FAEFD820F50BFF211AC6D9 /* LoopKitTypeAliases.swift */; }; AF79DFAB0F55143D66022668 /* LoopKitTypeAliases.swift in Sources */ = {isa = PBXBuildFile; fileRef = 35FAEFD820F50BFF211AC6D9 /* LoopKitTypeAliases.swift */; }; + 89C0C34F420190E8CC7D03B1 /* DayCharts.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6F40DE2F3FC02CBA3BE7AF2F /* DayCharts.swift */; }; + 332CC9FC011E78CE5BEA583C /* LoopDesign.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0BD3DDF41B598A8C4B5CEB92 /* LoopDesign.swift */; }; + 0C70F4D862F6D3FDB3D91D87 /* LoopHistoryMath.swift in Sources */ = {isa = PBXBuildFile; fileRef = 21622B2355AED8F6A12FE17C /* LoopHistoryMath.swift */; }; + 2ADBB92A8ABB74360D18EEFA /* LoopHistoryModels.swift in Sources */ = {isa = PBXBuildFile; fileRef = 471FFD525A4EB897745608BE /* LoopHistoryModels.swift */; }; + A743DC26D066EE5AC88C2F45 /* LoopHistoryProvider.swift in Sources */ = {isa = PBXBuildFile; fileRef = 09448CF97996C40BEDDE6588 /* LoopHistoryProvider.swift */; }; + 591F13AF435B37B4818E2F2B /* TrendsComponents.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4BFDE56977CC73CBDA1170C5 /* TrendsComponents.swift */; }; + 5CD0888FF33D6F844A81E638 /* TrendsScreen.swift in Sources */ = {isa = PBXBuildFile; fileRef = AF0FD64B2B3E9C9AA8764684 /* TrendsScreen.swift */; }; + 6A6C1E1C7A26EC88AFB4FAB1 /* DayDetailView.swift in Sources */ = {isa = PBXBuildFile; fileRef = E3A83D311A9ECAE563F74A51 /* DayDetailView.swift */; }; + A1B2C3D4E5F6A7B8C9D0E1F2 /* AppearanceSettings.swift in Sources */ = {isa = PBXBuildFile; fileRef = F2E1D0C9B8A7F6E5D4C3B2A1 /* AppearanceSettings.swift */; }; + C4B5E0A1D2F3A4B5C6D7E8F9 /* CarbEntryScreen.swift in Sources */ = {isa = PBXBuildFile; fileRef = C4B5E0A1D2F3A4B5C6D7E8FA /* CarbEntryScreen.swift */; }; + 3ED693ACBF8F9E416055BD56 /* MainTabBarController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 844BECBB6357021979B9443F /* MainTabBarController.swift */; }; + 7705483CFFCF0B89F8F1A08E /* NowScreen.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0874B7B679DB9CE661CCE152 /* NowScreen.swift */; }; + 23B98F0A53A093412229364D /* LogbookScreen.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7AEDC42672A7A8C57546EA0C /* LogbookScreen.swift */; }; + 97CF13197936D2794766C84A /* LoopHistoryMathTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 42B08644C3031D9E815F9892 /* LoopHistoryMathTests.swift */; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ @@ -896,6 +910,9 @@ F8760AF31E3C43F6AFBA1BE7 /* G7SensorKit.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; path = G7SensorKit.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 00A28F30399B460CABF4EDD2 /* SettingsProvider.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SettingsProvider.swift; sourceTree = ""; }; 0FC34B523FE5A50C920506D5 /* Loop/Resources/Sounds/alarm.caf */ = {isa = PBXFileReference; lastKnownFileType = file; path = Loop/Resources/Sounds/alarm.caf; sourceTree = SOURCE_ROOT; }; + FDE6FCD6C3CA3B693C8A349B /* WidgetDesign.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WidgetDesign.swift; sourceTree = ""; }; + E169C989E88148A68A4FEFB6 /* RedesignStatusWidgetView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RedesignStatusWidgetView.swift; sourceTree = ""; }; + DB9792C496505ED5C2F302AB /* RedesignLiveActivity.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RedesignLiveActivity.swift; sourceTree = ""; }; 142CB7582A60BF2E0075748A /* EditMode.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = EditMode.swift; sourceTree = ""; }; 142CB75A2A60BFC30075748A /* FavoriteFoodsView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FavoriteFoodsView.swift; sourceTree = ""; }; 1452F4A82A851C9400F8B9E4 /* FavoriteFoodAddEditViewModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FavoriteFoodAddEditViewModel.swift; sourceTree = ""; }; @@ -1623,16 +1640,26 @@ F5E0BDD327E1D71C0033557E /* he */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = he; path = he.lproj/Intents.strings; sourceTree = ""; }; FADE0001000000000000DE01 /* DevelopmentBranchAlerter.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DevelopmentBranchAlerter.swift; sourceTree = ""; }; FEEDF0000000000000000000 /* GlucoseStatistics.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GlucoseStatistics.swift; sourceTree = ""; }; - FEEDF0000000000000000001 /* StatisticsViewModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = StatisticsViewModel.swift; sourceTree = ""; }; - FEEDF0000000000000000002 /* Statistics/StatisticsView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Statistics/StatisticsView.swift; sourceTree = ""; }; - 747DA22B61531CCAAC79E86D /* Statistics/DailyInsulinChartView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Statistics/DailyInsulinChartView.swift; sourceTree = ""; }; - FEEDF0000000000000000003 /* Statistics/AGPChartView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Statistics/AGPChartView.swift; sourceTree = ""; }; - FEEDF0000000000000000004 /* Statistics/TimeInRangeBar.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Statistics/TimeInRangeBar.swift; sourceTree = ""; }; + FEEDF0000000000000000004 /* Statistics/GlucoseBand+Display.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Statistics/GlucoseBand+Display.swift"; sourceTree = ""; }; F69CE2EE3714858772FE7A26 /* InsulinDeliveryHistoryTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = InsulinDeliveryHistoryTests.swift; sourceTree = ""; }; FEEDF0000000000000000005 /* GlucoseStatisticsTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GlucoseStatisticsTests.swift; sourceTree = ""; }; 35FAEFD820F50BFF211AC6D9 /* LoopKitTypeAliases.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = LoopKitTypeAliases.swift; sourceTree = ""; }; 36421A4B9676EF68CDDC4ECD /* AlgorithmBridge.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = AlgorithmBridge.swift; sourceTree = ""; }; 6C372374D3D3D9C5F8E3AD93 /* TemporaryScheduleOverrideAlgorithmTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TemporaryScheduleOverrideAlgorithmTests.swift; sourceTree = ""; }; + 6F40DE2F3FC02CBA3BE7AF2F /* DayCharts.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DayCharts.swift; sourceTree = ""; }; + 0BD3DDF41B598A8C4B5CEB92 /* LoopDesign.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LoopDesign.swift; sourceTree = ""; }; + 21622B2355AED8F6A12FE17C /* LoopHistoryMath.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LoopHistoryMath.swift; sourceTree = ""; }; + 471FFD525A4EB897745608BE /* LoopHistoryModels.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LoopHistoryModels.swift; sourceTree = ""; }; + 09448CF97996C40BEDDE6588 /* LoopHistoryProvider.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LoopHistoryProvider.swift; sourceTree = ""; }; + 4BFDE56977CC73CBDA1170C5 /* TrendsComponents.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TrendsComponents.swift; sourceTree = ""; }; + AF0FD64B2B3E9C9AA8764684 /* TrendsScreen.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TrendsScreen.swift; sourceTree = ""; }; + E3A83D311A9ECAE563F74A51 /* DayDetailView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DayDetailView.swift; sourceTree = ""; }; + F2E1D0C9B8A7F6E5D4C3B2A1 /* AppearanceSettings.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppearanceSettings.swift; sourceTree = ""; }; + C4B5E0A1D2F3A4B5C6D7E8FA /* CarbEntryScreen.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CarbEntryScreen.swift; sourceTree = ""; }; + 844BECBB6357021979B9443F /* MainTabBarController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MainTabBarController.swift; sourceTree = ""; }; + 0874B7B679DB9CE661CCE152 /* NowScreen.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NowScreen.swift; sourceTree = ""; }; + 7AEDC42672A7A8C57546EA0C /* LogbookScreen.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LogbookScreen.swift; sourceTree = ""; }; + 42B08644C3031D9E815F9892 /* LoopHistoryMathTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LoopHistoryMathTests.swift; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -1758,9 +1785,20 @@ path = Managers; sourceTree = ""; }; + 17D23E8E964F381FCC67C938 /* Redesign */ = { + isa = PBXGroup; + children = ( + FDE6FCD6C3CA3B693C8A349B /* WidgetDesign.swift */, + E169C989E88148A68A4FEFB6 /* RedesignStatusWidgetView.swift */, + DB9792C496505ED5C2F302AB /* RedesignLiveActivity.swift */, + ); + path = Redesign; + sourceTree = ""; + }; 14B1736128AED9EC006CCD7C /* Loop Widget Extension */ = { isa = PBXGroup; children = ( + 17D23E8E964F381FCC67C938 /* Redesign */, 147EFE8D2A8BCC5500272438 /* DefaultAssets.xcassets */, 147EFE8F2A8BCD8000272438 /* DerivedAssets.xcassets */, 147EFE912A8BCD8A00272438 /* DerivedAssetsBase.xcassets */, @@ -1978,6 +2016,7 @@ 43776F8E1B8022E90074EA36 /* Loop */ = { isa = PBXGroup; children = ( + 8574687EF267DC59043C0242 /* Redesign */, C16DA84022E8E104008624C2 /* Plugins */, B66D1F322E6A5D6600471149 /* Localizable.xcstrings */, B66D1F382E6A5D6600471149 /* InfoPlist.xcstrings */, @@ -2256,11 +2295,8 @@ 1DE09BA824A3E23F009EE9F9 /* SettingsView.swift */, CFD4A26A23202AF2EA506FCF /* CurrentSetupView.swift */, 0BA918E086710427153DA902 /* ShareOutcomesView.swift */, - FEEDF0000000000000000004 /* Statistics/TimeInRangeBar.swift */, - 747DA22B61531CCAAC79E86D /* Statistics/DailyInsulinChartView.swift */, - FEEDF0000000000000000003 /* Statistics/AGPChartView.swift */, + FEEDF0000000000000000004 /* Statistics/GlucoseBand+Display.swift */, 174DD37A96993576E0E573C6 /* Statistics/SetupComparisonCharts.swift */, - FEEDF0000000000000000002 /* Statistics/StatisticsView.swift */, E4854073AAE5C2CB97167F63 /* HealthAccessView.swift */, DDC389FB2A2BC6670066E2E8 /* SettingsView+algorithmExperimentsSection.swift */, C1DE5D22251BFC4D00439E49 /* SimpleBolusView.swift */, @@ -2771,7 +2807,6 @@ 14D906F32A846510006EB79A /* FavoriteFoodsViewModel.swift */, C11BD0542523CFED00236B08 /* SimpleBolusViewModel.swift */, 1DB1CA4E24A56D7600B3B94C /* SettingsViewModel.swift */, - FEEDF0000000000000000001 /* StatisticsViewModel.swift */, 17C7C2227FAC0A9F7F570A01 /* CurrentSetupViewModel.swift */, 3A13D8D000431C52A5899D1E /* ShareOutcomesViewModel.swift */, 1D49795724E7289700948F05 /* ServicesViewModel.swift */, @@ -2880,6 +2915,7 @@ 6C1F8E3BA2D45079B3E2F512 /* OutcomesPackageTests.swift */, BE36167100E59D7413C50F63 /* SetupComparisonTests.swift */, FEEDF0000000000000000005 /* GlucoseStatisticsTests.swift */, + 42B08644C3031D9E815F9892 /* LoopHistoryMathTests.swift */, A9DFAFB224F0415E00950D1E /* CarbBackfillRequestUserInfoTests.swift */, A963B279252CEBAE0062AA12 /* SetBolusUserInfoTests.swift */, C19008FF252271BB00721625 /* SimpleBolusCalculatorTests.swift */, @@ -3060,6 +3096,26 @@ path = Fixtures; sourceTree = ""; }; + 8574687EF267DC59043C0242 /* Redesign */ = { + isa = PBXGroup; + children = ( + AF0FD64B2B3E9C9AA8764684 /* TrendsScreen.swift */, + E3A83D311A9ECAE563F74A51 /* DayDetailView.swift */, + C4B5E0A1D2F3A4B5C6D7E8FA /* CarbEntryScreen.swift */, + 844BECBB6357021979B9443F /* MainTabBarController.swift */, + 0874B7B679DB9CE661CCE152 /* NowScreen.swift */, + 7AEDC42672A7A8C57546EA0C /* LogbookScreen.swift */, + 4BFDE56977CC73CBDA1170C5 /* TrendsComponents.swift */, + F2E1D0C9B8A7F6E5D4C3B2A1 /* AppearanceSettings.swift */, + 09448CF97996C40BEDDE6588 /* LoopHistoryProvider.swift */, + 471FFD525A4EB897745608BE /* LoopHistoryModels.swift */, + 21622B2355AED8F6A12FE17C /* LoopHistoryMath.swift */, + 0BD3DDF41B598A8C4B5CEB92 /* LoopDesign.swift */, + 6F40DE2F3FC02CBA3BE7AF2F /* DayCharts.swift */, + ); + path = Redesign; + sourceTree = ""; + }; /* End PBXGroup section */ /* Begin PBXHeadersBuildPhase section */ @@ -3681,6 +3737,10 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( + E6E73709263FB037F274B2A0 /* WidgetDesign.swift in Sources */, + 8602ACA648AEEBBD4793ED49 /* RedesignStatusWidgetView.swift in Sources */, + FE8902221761558AAEDFFE02 /* RedesignLiveActivity.swift in Sources */, + 4CC1A96D0600081991783423 /* LoopDesign.swift in Sources */, 14B1738128AEDC70006CCD7C /* StatusExtensionContext.swift in Sources */, 1455ACA92C66665D004F44F2 /* StateColorPalette.swift in Sources */, 14B1737628AEDC6C006CCD7C /* HKUnit.swift in Sources */, @@ -3723,6 +3783,19 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( + 5CD0888FF33D6F844A81E638 /* TrendsScreen.swift in Sources */, + 6A6C1E1C7A26EC88AFB4FAB1 /* DayDetailView.swift in Sources */, + C4B5E0A1D2F3A4B5C6D7E8F9 /* CarbEntryScreen.swift in Sources */, + 3ED693ACBF8F9E416055BD56 /* MainTabBarController.swift in Sources */, + 7705483CFFCF0B89F8F1A08E /* NowScreen.swift in Sources */, + 23B98F0A53A093412229364D /* LogbookScreen.swift in Sources */, + 591F13AF435B37B4818E2F2B /* TrendsComponents.swift in Sources */, + A1B2C3D4E5F6A7B8C9D0E1F2 /* AppearanceSettings.swift in Sources */, + A743DC26D066EE5AC88C2F45 /* LoopHistoryProvider.swift in Sources */, + 2ADBB92A8ABB74360D18EEFA /* LoopHistoryModels.swift in Sources */, + 0C70F4D862F6D3FDB3D91D87 /* LoopHistoryMath.swift in Sources */, + 332CC9FC011E78CE5BEA583C /* LoopDesign.swift in Sources */, + 89C0C34F420190E8CC7D03B1 /* DayCharts.swift in Sources */, C17824A51E1AD4D100D9D25C /* ManualBolusRecommendation.swift in Sources */, 897A5A9624C2175B00C4E71D /* BolusEntryView.swift in Sources */, 4F70C2131DE90339006380B7 /* StatusExtensionContext.swift in Sources */, @@ -3836,7 +3909,6 @@ C1F2CAAC2B7A980600D7F581 /* BasalRelativeDose.swift in Sources */, B4F3D25124AF890C0095CE44 /* BluetoothStateManager.swift in Sources */, 1DDE273D24AEA4B000796622 /* SettingsViewModel.swift in Sources */, - FEEDB0000000000000000001 /* StatisticsViewModel.swift in Sources */, 414E7082E6A6B9DA8CD11EF3 /* CurrentSetupViewModel.swift in Sources */, DD3DBD292A33AFE9000F8B5B /* IntegralRetrospectiveCorrectionSelectionView.swift in Sources */, A1B2C3D42E8F000100000002 /* GuardAndRunwaySelectionView.swift in Sources */, @@ -3912,11 +3984,8 @@ A9DCF32A25B0FABF00C89088 /* LoopUIColorPalette+Default.swift in Sources */, 1DDE273E24AEA4B000796622 /* SettingsView.swift in Sources */, 6D16FF26E7F84F97B5DB6A88 /* CurrentSetupView.swift in Sources */, - FEEDB0000000000000000004 /* Statistics/TimeInRangeBar.swift in Sources */, - A3C9F155FD92DC188BD9A21F /* Statistics/DailyInsulinChartView.swift in Sources */, - FEEDB0000000000000000003 /* Statistics/AGPChartView.swift in Sources */, + FEEDB0000000000000000004 /* Statistics/GlucoseBand+Display.swift in Sources */, 16097A41A1EF24BCF2F670DB /* Statistics/SetupComparisonCharts.swift in Sources */, - FEEDB0000000000000000002 /* Statistics/StatisticsView.swift in Sources */, BAF043BF0BC70EC99AE79F71 /* HealthAccessView.swift in Sources */, A9B607B0247F000F00792BE4 /* UserNotifications+Loop.swift in Sources */, 43F89CA322BDFBBD006BB54E /* UIActivityIndicatorView.swift in Sources */, @@ -4198,6 +4267,7 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( + 97CF13197936D2794766C84A /* LoopHistoryMathTests.swift in Sources */, A9DF02CB24F72B9E00B7C988 /* CriticalEventLogTests.swift in Sources */, 1D80313D24746274002810DF /* AlertStoreTests.swift in Sources */, C1777A6625A125F100595963 /* ManualEntryDoseViewModelTests.swift in Sources */, @@ -4791,6 +4861,7 @@ isa = XCBuildConfiguration; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = "$(APPICON_NAME)"; + ASSETCATALOG_COMPILER_ALTERNATE_APPICON_NAMES = "AppIconDayNight AppIconDay AppIconNight"; CODE_SIGN_ENTITLEMENTS = "$(LOOP_ENTITLEMENTS)"; CODE_SIGN_IDENTITY = "Apple Development"; CODE_SIGN_STYLE = Automatic; @@ -4820,6 +4891,7 @@ isa = XCBuildConfiguration; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = "$(APPICON_NAME)"; + ASSETCATALOG_COMPILER_ALTERNATE_APPICON_NAMES = "AppIconDayNight AppIconDay AppIconNight"; CODE_SIGN_ENTITLEMENTS = "$(LOOP_ENTITLEMENTS)"; CODE_SIGN_IDENTITY = "Apple Development"; CODE_SIGN_STYLE = Automatic; @@ -5210,6 +5282,7 @@ isa = XCBuildConfiguration; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = "$(APPICON_NAME)"; + ASSETCATALOG_COMPILER_ALTERNATE_APPICON_NAMES = "AppIconDayNight AppIconDay AppIconNight"; CODE_SIGN_ENTITLEMENTS = "$(LOOP_ENTITLEMENTS)"; CODE_SIGN_IDENTITY = "Apple Development"; CODE_SIGN_STYLE = Automatic; diff --git a/Loop/DefaultAssets.xcassets/AppIconPreviewDay.imageset/AppIconPreviewDay.png b/Loop/DefaultAssets.xcassets/AppIconPreviewDay.imageset/AppIconPreviewDay.png new file mode 100644 index 0000000000..e47fb9b46f Binary files /dev/null and b/Loop/DefaultAssets.xcassets/AppIconPreviewDay.imageset/AppIconPreviewDay.png differ diff --git a/Loop/DefaultAssets.xcassets/AppIconPreviewDay.imageset/Contents.json b/Loop/DefaultAssets.xcassets/AppIconPreviewDay.imageset/Contents.json new file mode 100644 index 0000000000..689ca3fe4d --- /dev/null +++ b/Loop/DefaultAssets.xcassets/AppIconPreviewDay.imageset/Contents.json @@ -0,0 +1,12 @@ +{ + "images": [ + { + "filename": "AppIconPreviewDay.png", + "idiom": "universal" + } + ], + "info": { + "author": "xcode", + "version": 1 + } +} \ No newline at end of file diff --git a/Loop/DefaultAssets.xcassets/AppIconPreviewDayNight.imageset/AppIconPreviewDayNight.png b/Loop/DefaultAssets.xcassets/AppIconPreviewDayNight.imageset/AppIconPreviewDayNight.png new file mode 100644 index 0000000000..5d9ed19352 Binary files /dev/null and b/Loop/DefaultAssets.xcassets/AppIconPreviewDayNight.imageset/AppIconPreviewDayNight.png differ diff --git a/Loop/DefaultAssets.xcassets/AppIconPreviewDayNight.imageset/Contents.json b/Loop/DefaultAssets.xcassets/AppIconPreviewDayNight.imageset/Contents.json new file mode 100644 index 0000000000..b35f62954c --- /dev/null +++ b/Loop/DefaultAssets.xcassets/AppIconPreviewDayNight.imageset/Contents.json @@ -0,0 +1,12 @@ +{ + "images": [ + { + "filename": "AppIconPreviewDayNight.png", + "idiom": "universal" + } + ], + "info": { + "author": "xcode", + "version": 1 + } +} \ No newline at end of file diff --git a/Loop/DefaultAssets.xcassets/AppIconPreviewNight.imageset/AppIconPreviewNight.png b/Loop/DefaultAssets.xcassets/AppIconPreviewNight.imageset/AppIconPreviewNight.png new file mode 100644 index 0000000000..019c6d968c Binary files /dev/null and b/Loop/DefaultAssets.xcassets/AppIconPreviewNight.imageset/AppIconPreviewNight.png differ diff --git a/Loop/DefaultAssets.xcassets/AppIconPreviewNight.imageset/Contents.json b/Loop/DefaultAssets.xcassets/AppIconPreviewNight.imageset/Contents.json new file mode 100644 index 0000000000..01fec4c507 --- /dev/null +++ b/Loop/DefaultAssets.xcassets/AppIconPreviewNight.imageset/Contents.json @@ -0,0 +1,12 @@ +{ + "images": [ + { + "filename": "AppIconPreviewNight.png", + "idiom": "universal" + } + ], + "info": { + "author": "xcode", + "version": 1 + } +} \ No newline at end of file diff --git a/Loop/DerivedAssetsBase.xcassets/AppIconDay.appiconset/AppIconDay.png b/Loop/DerivedAssetsBase.xcassets/AppIconDay.appiconset/AppIconDay.png new file mode 100644 index 0000000000..767082980e Binary files /dev/null and b/Loop/DerivedAssetsBase.xcassets/AppIconDay.appiconset/AppIconDay.png differ diff --git a/Loop/DerivedAssetsBase.xcassets/AppIconDay.appiconset/Contents.json b/Loop/DerivedAssetsBase.xcassets/AppIconDay.appiconset/Contents.json new file mode 100644 index 0000000000..5e9df36117 --- /dev/null +++ b/Loop/DerivedAssetsBase.xcassets/AppIconDay.appiconset/Contents.json @@ -0,0 +1,14 @@ +{ + "images": [ + { + "filename": "AppIconDay.png", + "idiom": "universal", + "platform": "ios", + "size": "1024x1024" + } + ], + "info": { + "author": "xcode", + "version": 1 + } +} \ No newline at end of file diff --git a/Loop/DerivedAssetsBase.xcassets/AppIconDayNight.appiconset/AppIconDayNight-Dark.png b/Loop/DerivedAssetsBase.xcassets/AppIconDayNight.appiconset/AppIconDayNight-Dark.png new file mode 100644 index 0000000000..47a5dad744 Binary files /dev/null and b/Loop/DerivedAssetsBase.xcassets/AppIconDayNight.appiconset/AppIconDayNight-Dark.png differ diff --git a/Loop/DerivedAssetsBase.xcassets/AppIconDayNight.appiconset/AppIconDayNight.png b/Loop/DerivedAssetsBase.xcassets/AppIconDayNight.appiconset/AppIconDayNight.png new file mode 100644 index 0000000000..767082980e Binary files /dev/null and b/Loop/DerivedAssetsBase.xcassets/AppIconDayNight.appiconset/AppIconDayNight.png differ diff --git a/Loop/DerivedAssetsBase.xcassets/AppIconDayNight.appiconset/Contents.json b/Loop/DerivedAssetsBase.xcassets/AppIconDayNight.appiconset/Contents.json new file mode 100644 index 0000000000..c34d1b8588 --- /dev/null +++ b/Loop/DerivedAssetsBase.xcassets/AppIconDayNight.appiconset/Contents.json @@ -0,0 +1,26 @@ +{ + "images": [ + { + "filename": "AppIconDayNight.png", + "idiom": "universal", + "platform": "ios", + "size": "1024x1024" + }, + { + "appearances": [ + { + "appearance": "luminosity", + "value": "dark" + } + ], + "filename": "AppIconDayNight-Dark.png", + "idiom": "universal", + "platform": "ios", + "size": "1024x1024" + } + ], + "info": { + "author": "xcode", + "version": 1 + } +} \ No newline at end of file diff --git a/Loop/DerivedAssetsBase.xcassets/AppIconNight.appiconset/AppIconNight.png b/Loop/DerivedAssetsBase.xcassets/AppIconNight.appiconset/AppIconNight.png new file mode 100644 index 0000000000..47a5dad744 Binary files /dev/null and b/Loop/DerivedAssetsBase.xcassets/AppIconNight.appiconset/AppIconNight.png differ diff --git a/Loop/DerivedAssetsBase.xcassets/AppIconNight.appiconset/Contents.json b/Loop/DerivedAssetsBase.xcassets/AppIconNight.appiconset/Contents.json new file mode 100644 index 0000000000..a9f66f6697 --- /dev/null +++ b/Loop/DerivedAssetsBase.xcassets/AppIconNight.appiconset/Contents.json @@ -0,0 +1,14 @@ +{ + "images": [ + { + "filename": "AppIconNight.png", + "idiom": "universal", + "platform": "ios", + "size": "1024x1024" + } + ], + "info": { + "author": "xcode", + "version": 1 + } +} \ No newline at end of file diff --git a/Loop/Localizable.xcstrings b/Loop/Localizable.xcstrings index 92601ae0e8..d56c5894ec 100644 --- a/Loop/Localizable.xcstrings +++ b/Loop/Localizable.xcstrings @@ -12,6 +12,762 @@ }, " -" : { + }, + "%1$@ above range" : { + "comment" : "Time in range High row: the consensus target for all time above range, high and very high together. (1: target, e.g. < 25%)" + }, + "%1$@ ago" : { + "comment" : "Carb entry time choice: eaten this long before now. (1: duration, e.g. 15m or 1h)" + }, + "%1$@ below range" : { + "comment" : "Time in range Low row: the consensus target for all time below range, low and very low together. (1: target, e.g. < 4%)" + }, + "%1$@ d" : { + "comment" : "Trends period picker, short label for a period of several days, e.g. 7 d. (1: number of days)" + }, + "%1$@ entries" : { + "comment" : "Trends Carbs per day tile detail: average number of carb entries per day, a fractional value such as 2.5, so not pluralised. (1: number with one decimal)" + }, + "%1$@ for %2$@" : { + "comment" : "A temp basal: its rate and how long it ran. (1: rate, e.g. 0.50 U/h; 2: duration, e.g. 30m)" + }, + "%1$@ for %2$@ (scheduled %3$@)" : { + "comment" : "A temp basal: its rate, how long it ran and the scheduled rate it replaced. (1: rate, e.g. 0.50 U/h; 2: duration, e.g. 30m; 3: scheduled rate number, e.g. 0.80)" + }, + "%1$@ g" : { + "comment" : "Format string for an amount of carbohydrate in grams. (1: grams)" + }, + "%1$@ h" : { + "comment" : "Time in range row: average hours a day spent in the band, abbreviated. (1: hours with one decimal)" + }, + "%1$@ manual, %2$@ automatic" : { + "comment" : "VoiceOver: how the bolus divides. (1: manual units, 2: automatic units)" + }, + "%1$@ mmol/mol" : { + "comment" : "Trends GMI tile detail: the GMI in IFCC units. (1: value)" + }, + "%1$@ of %2$@" : { + "comment" : "Trends Loop active tile detail: time in closed loop out of the time Loop status is known. (1: duration in closed loop, e.g. 6d 4h, 2: duration covered, e.g. 7d) Trends: how many days of the period are averaged. (1: days averaged, a number; 2: days in the period, e.g. 14 days)" + }, + "%1$@ of unknown kind\n+ %2$@ automatic" : { + "comment" : "Trends Boluses per day tile detail when some boluses don't say whether they were manual or automatic, such as some in Apple Health, on two lines: how many of the figure above are of unknown kind, then the automatic boluses on top. (1: boluses of unknown kind per day; 2: automatic boluses per day; both fractional, such as 4.2)" + }, + "%1$@ U/h" : { + "comment" : "Format string for an insulin rate in units per hour. (1: rate)" + }, + "%1$@ unknown" : { + "comment" : "Basal and bolus: bolus whose record doesn't say whether it was manual or automatic, such as some in Apple Health, after the manual and automatic amounts. (1: units, e.g. 3.2 U)" + }, + "%1$@ vs plan" : { + "comment" : "Basal tile on the Now screen: how the current basal rate differs from the scheduled rate. (1: signed difference in U/h, e.g. +0.25)" + }, + "%1$@ · %2$@ in 5 min" : { + "comment" : "Under the glucose value on the Now screen: the glucose unit and how much glucose changed over 5 minutes. (1: glucose unit, e.g. mmol/L; 2: signed change, e.g. +0.3)" + }, + "%1$@ · ending soon" : { + "comment" : "Status pill on the Now screen when a pump pod or CGM sensor is near the end of its life. (1: device name from the pump or CGM plugin, e.g. Omnipod 5)" + }, + "%1$@%%" : { + "comment" : "A percentage. (1: number)" + }, + "%1$@%% CGM active" : { + "comment" : "Trends Time in range card: share of the period with CGM readings. (1: percentage number)" + }, + "%1$@, %2$@ %3$@: %4$@ percent, %5$@ hours a day" : { + "comment" : "VoiceOver label for a Time in range row. (1: band name, e.g. In range, 2: glucose thresholds, e.g. 3.9–10.0, 3: glucose unit, 4: percentage number, 5: average hours a day with one decimal)" + }, + "%1$lld of %2$lld runs completed" : { + "comment" : "Loop status sheet: how many five-minute slots in the last two hours had a completed Loop run. (1: completed; 2: slots, 24)" + }, + "%lld days" : { + "comment" : "A number of days, e.g. a Trends period or how many days are averaged. (1: number of days) Trends period picker, VoiceOver name for a period of several days. (1: number of days)", + "localizations" : { + "en" : { + "variations" : { + "plural" : { + "one" : { + "stringUnit" : { + "state" : "translated", + "value" : "%lld day" + } + }, + "other" : { + "stringUnit" : { + "state" : "translated", + "value" : "%lld days" + } + } + } + } + } + } + }, + "%lld doses" : { + "comment" : "Logbook folded automatic boluses row: how many automatic boluses it holds. (1: number)", + "localizations" : { + "en" : { + "variations" : { + "plural" : { + "one" : { + "stringUnit" : { + "state" : "translated", + "value" : "%lld dose" + } + }, + "other" : { + "stringUnit" : { + "state" : "translated", + "value" : "%lld doses" + } + } + } + } + } + } + }, + "%lld entries" : { + "comment" : "Trends Carbs tile detail for a one-day period: how many carb entries were made that day. (1: number)", + "localizations" : { + "en" : { + "variations" : { + "plural" : { + "one" : { + "stringUnit" : { + "state" : "translated", + "value" : "%lld entry" + } + }, + "other" : { + "stringUnit" : { + "state" : "translated", + "value" : "%lld entries" + } + } + } + } + } + } + }, + "%lld shorter gaps" : { + "comment" : "Chart note: how many other, shorter gaps in glucose readings there were; follows the longest gap. (1: number of gaps)", + "localizations" : { + "en" : { + "variations" : { + "plural" : { + "one" : { + "stringUnit" : { + "state" : "translated", + "value" : "%lld shorter gap" + } + }, + "other" : { + "stringUnit" : { + "state" : "translated", + "value" : "%lld shorter gaps" + } + } + } + } + } + } + }, + "+ %1$@ automatic" : { + "comment" : "Trends Boluses per day tile detail: average number of automatic boluses per day on top of the manual ones, a fractional value such as 4.2. (1: number with one decimal)" + }, + "25–75%" : { + "comment" : "Trends Daily pattern legend: band between the 25th and 75th percentiles of glucose" + }, + "5–95%" : { + "comment" : "Trends Daily pattern legend: band between the 5th and 95th percentiles of glucose" + }, + "Absorbed by %1$@" : { + "comment" : "Under the end of the carb absorption curve: when the carbs will have absorbed (1: time)" + }, + "absorbs over %1$@ h" : { + "comment" : "Logbook carb row detail: carb absorption time in hours. (1: hours, e.g. 3 or 2.5)" + }, + "Add carbs" : { + "comment" : "Button on the Now screen that opens carb entry" + }, + "Add pump" : { + "comment" : "Status pill on the Now screen when no pump is set up; tapping it starts pump setup" + }, + "aim %1$@" : { + "comment" : "Trends: the consensus target under a figure, in lower case. (1: target, e.g. < 7%)" + }, + "aim %1$@, CV %2$@" : { + "comment" : "Trends Average tile: the consensus targets for average glucose and its coefficient of variation, in lower case. (1: glucose target, e.g. < 8.6; 2: CV target, e.g. ≤ 36%)" + }, + "All" : { + "comment" : "Logbook filter chip: show every entry" + }, + "App Icon" : { + "comment" : "Header for the app icon choice" + }, + "Appearance" : { + "comment" : "Title of the light or dark appearance choice" + }, + "Appearance and App Icon" : { + "comment" : "Title of the row that opens the appearance and app icon settings" + }, + "Automatic" : { + "comment" : "Chart legend: hatched bars are automatic boluses given by Loop" + }, + "Automatic %1$@" : { + "comment" : "Basal and bolus: bolus Loop gave automatically. (1: units, e.g. 5.4 U)" + }, + "Automatic bolus" : { + "comment" : "Chart callout label for a bolus Loop delivered automatically near the touched time Logbook row title: a bolus Loop delivered automatically" + }, + "Automatic boluses" : { + "comment" : "Logbook row title: several automatic boluses in a row, folded into one row that lists them" + }, + "average of %1$@" : { + "comment" : "Trends Insulin per day card subtitle when only some days of the period are averaged, such as a day still in progress. (1: days averaged, e.g. 13 of 14 days)" + }, + "average per day" : { + "comment" : "Trends Basal and bolus card subtitle when the figures are averaged per day over the period" + }, + "Basal" : { + "comment" : "Chart callout label for the basal rate at the touched time Label of a tile showing the current basal rate (Now screen) or the day's basal insulin total (Today so far totals) Logbook filter chip: show only basal changes" + }, + "Basal %1$@, %2$@ percent" : { + "comment" : "VoiceOver: basal units and share. (1: units, 2: percentage number)" + }, + "Basal adjustments" : { + "comment" : "Logbook row title summarising the temp basals Loop set in a day" + }, + "Basal and bolus" : { + "comment" : "Trends card title: insulin split into basal and bolus" + }, + "Basal given" : { + "comment" : "Chart legend: filled area is basal insulin actually delivered" + }, + "Basal resumed" : { + "comment" : "Logbook row title: insulin delivery resumed after a suspend" + }, + "Basal suspended" : { + "comment" : "Logbook row title: insulin delivery was suspended" + }, + "Best over 14 days with %1$@ CGM data" : { + "comment" : "Trends GMI tile caption when the period is shorter than 14 days or CGM readings cover less than 70% of it: the consensus for when GMI is representative. (1: share of CGM data, e.g. 70%)" + }, + "Bolus %1$@, %2$@ percent" : { + "comment" : "VoiceOver: bolus units and share. (1: units, 2: percentage number)" + }, + "Boluses" : { + "comment" : "Trends summary tile for a one-day period: how many boluses were given that day, other than Loop's automatic ones" + }, + "Boluses per day" : { + "comment" : "Trends summary tile: average number of boluses per day, other than Loop's automatic ones" + }, + "Boluses, basal changes, carbs and pump events from the last 7 days" : { + "comment" : "Logbook settings descriptive text" + }, + "Carbs" : { + "comment" : "Label of a tile showing the day's total carbohydrate Logbook filter chip: show only carb entries Logbook row title: a carb entry" + }, + "Carbs per day" : { + "comment" : "Trends summary tile: average grams of carbohydrate entered per day" + }, + "CGM data covers %1$@." : { + "comment" : "Trends Summary note when glucose readings start partway through the period. (1: days covered, e.g. 5 of 14 days)" + }, + "Changes with the home screen's light or dark appearance" : { + "comment" : "Description of the app icon that follows the home screen appearance" + }, + "Classic" : { + "comment" : "Name of Loop's original app icon" + }, + "Closed loop" : { + "comment" : "Trends Loop status: time Loop was running in closed loop" + }, + "Closed loop paused · %1$@" : { + "comment" : "Status pill on the Now screen: closed loop is switched on but paused (e.g. no CGM data), and Loop last ran this long ago. (1: duration, e.g. 3m)" + }, + "Closed loop paused · not run yet" : { + "comment" : "Status pill on the Now screen: closed loop is switched on but paused (e.g. no CGM data), and Loop has never completed" + }, + "Closed loop · %1$@" : { + "comment" : "Status pill on the Now screen: closed loop is on and Loop last ran this long ago. (1: duration, e.g. 3m)" + }, + "Closed loop · not run yet" : { + "comment" : "Status pill on the Now screen: closed loop is on but Loop has never completed" + }, + "COB" : { + "comment" : "Abbreviation for carbs on board; label of a tile on the Now screen" + }, + "Couldn't delete" : { + "comment" : "Alert title when deleting a Logbook entry fails" + }, + "Couldn't export" : { + "comment" : "Alert title when exporting the Trends PDF or CSV fails" + }, + "Couldn't load Logbook: %1$@" : { + "comment" : "Logbook error when its history can't be read. (1: system error description)" + }, + "Couldn't load recent CGM readings" : { + "comment" : "Prediction chart on the Now screen when recent glucose couldn't be read" + }, + "Couldn't load this day: %1$@" : { + "comment" : "Day page error when the day's history can't be read. (1: system error description)" + }, + "Couldn't load today's history: %1$@" : { + "comment" : "Shown on the Now screen's Today so far card when history couldn't be read. (1: system error description)" + }, + "Couldn't load Trends: %1$@" : { + "comment" : "Trends error message when the history can't be read. (1: error description)" + }, + "Covers %1$@, from the start of Loop's records, which it keeps for %2$@." : { + "comment" : "Trends Loop status footnote when Loop's records of its runs and settings start partway through the period. (1: date range covered; 2: how long Loop keeps them, e.g. 90 days)" + }, + "CSV, one row per day" : { + "comment" : "Trends export menu item: share a CSV spreadsheet file with one row for each day" + }, + "Custom" : { + "comment" : "Carb entry absorption choice Other, before it is chosen: you set the food and absorption time yourself" + }, + "Daily pattern" : { + "comment" : "Trends card title: the ambulatory glucose profile, glucose by time of day across the period" + }, + "Daily pattern over %1$@. Median highest %2$@ at %3$@, lowest %4$@ at %5$@" : { + "comment" : "VoiceOver label for the Trends Daily pattern chart. (1: days with readings, e.g. 14 days; 2: highest median glucose; 3: time of day; 4: lowest median glucose; 5: time of day)" + }, + "Daily pattern: not enough days" : { + "comment" : "VoiceOver label for the Trends Daily pattern chart when fewer than 5 days have readings" + }, + "Day" : { + "comment" : "Appearance option and app icon name: the light (daytime) version" + }, + "Day (Trends period)" : { + "comment" : "Trends period picker: a period of one calendar day (not daytime)", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Day" + } + } + } + }, + "Day and Night" : { + "comment" : "Name of the app icon that follows the home screen's light or dark appearance" + }, + "Eaten" : { + "comment" : "Carb entry section title: when the food was eaten" + }, + "Eaten at %1$@, absorbed by %2$@" : { + "comment" : "Accessibility summary of the carb entry preview chart (1: time eaten, 2: time absorbed)" + }, + "Edit" : { + "comment" : "Swipe action to edit a Logbook carb entry" + }, + "Edit Carb Entry" : { + "comment" : "Title of the screen for editing a carb entry from the Logbook" + }, + "Enter an amount" : { + "comment" : "Carb entry Continue button while no amount has been typed" + }, + "Export" : { + "comment" : "Trends menu title: export the period as a PDF report or CSV file" + }, + "Fast" : { + "comment" : "Carb entry absorption choice: food that absorbs quickly, such as sweets" + }, + "From Apple Health: Loop keeps 7 days, so this day has no temp basal or schedule detail." : { + "comment" : "Day page note when the day is older than Loop's 7-day history and was read from Apple Health" + }, + "Gaps" : { + "comment" : "Trends Loop status button and screen title: list of times Loop wasn't in closed loop" + }, + "glucose %1$@" : { + "comment" : "Logbook row detail: glucose when the dose was given. (1: glucose value, e.g. 7.5)" + }, + "glucose %1$@ falling" : { + "comment" : "Logbook row detail: glucose when the dose was given, and falling. (1: glucose value, e.g. 11.0)" + }, + "glucose %1$@ rising" : { + "comment" : "Logbook row detail: glucose when the dose was given, and rising. (1: glucose value, e.g. 11.0)" + }, + "Glucose prediction unavailable" : { + "comment" : "VoiceOver label for the prediction chart when Loop has no prediction" + }, + "Health" : { + "comment" : "Logbook carb row detail: the entry came from Apple Health" + }, + "How fast it absorbs" : { + "comment" : "Carb entry section title: choose how quickly the food's carbs absorb" + }, + "In range" : { + "comment" : "Time in range band: glucose 70–180 mg/dL (3.9–10.0 mmol/L) Time-in-range band name: glucose 70–180 mg/dL (3.9–10.0 mmol/L)" + }, + "Infusion set changed" : { + "comment" : "Pump event in the history: the infusion set was replaced" + }, + "Insulin isn't being adjusted. Tap for details." : { + "comment" : "Notice detail on the Now screen when Loop hasn't completed recently" + }, + "Insulin per day" : { + "comment" : "Trends tile and card title: average total insulin per day" + }, + "Insulin per day, average %1$@" : { + "comment" : "VoiceOver label for the Trends Insulin per day chart. (1: average insulin per day, e.g. 32.1 U)" + }, + "Insulin per day, weekly average, average %1$@" : { + "comment" : "VoiceOver label for the Trends Insulin per day chart when bars are weekly averages. (1: average insulin per day, e.g. 32.1 U)" + }, + "Insulin timeline, %1$@, bolus %2$@, basal %3$@, carbs %4$@" : { + "comment" : "VoiceOver summary of the day's insulin timeline chart with no glucose readings. (1: weekday and date; 2: bolus total, e.g. 12.5 U; 3: basal total; 4: carbs total, e.g. 140 g)" + }, + "Insulin timeline, %1$@, bolus %2$@, basal %3$@, carbs %4$@, latest glucose %5$@ %6$@" : { + "comment" : "VoiceOver summary of the day's insulin timeline chart. (1: weekday and date; 2: bolus total, e.g. 12.5 U; 3: basal total; 4: carbs total, e.g. 140 g; 5: latest glucose value; 6: glucose unit, mmol/L or mg/dL)" + }, + "IOB" : { + "comment" : "Abbreviation for insulin on board; label of a tile on the Now screen" + }, + "Last 2 hours" : { + "comment" : "Loop status sheet: title over the strip of Loop's runs in the last two hours" + }, + "Last ran at %1$@" : { + "comment" : "Loop status sheet: when Loop last completed a run, under a minute ago. (1: time of day)" + }, + "Last ran at %1$@, %2$@" : { + "comment" : "Loop status sheet: when Loop last completed a run. (1: time of day; 2: how long ago, e.g. 3 min ago)" + }, + "Last reading %1$@ ago" : { + "comment" : "Shown on the Now screen under No reading when the latest CGM reading is too old. (1: duration, e.g. 25m)" + }, + "Limited" : { + "comment" : "Trends Loop status: time closed loop was on but Loop wasn't completing runs" + }, + "Logbook" : { + "comment" : "Title of the Logbook" + }, + "logged" : { + "comment" : "Logbook bolus row detail: the dose was logged by hand rather than delivered by the pump" + }, + "Loop" : { + "comment" : "Logbook filter chip: show only what Loop did automatically (Loop is the app's name)" + }, + "Loop can't adjust insulin without readings." : { + "comment" : "Notice detail on the Now screen under a CGM problem when there is no recent glucose reading" + }, + "Loop failed · %1$@" : { + "comment" : "Status pill on the Now screen: Loop hasn't completed for over 15 minutes. (1: duration since Loop last ran, e.g. 16m)" + }, + "Loop hasn't run for %1$@" : { + "comment" : "Notice title on the Now screen when Loop hasn't completed recently. (1: duration since Loop last ran, e.g. 16m)" + }, + "Loop keeps the last 7 days on this phone. Older doses and carbs are in Apple Health and on Trends." : { + "comment" : "Logbook footer explaining why only 7 days are listed" + }, + "Loop may not be giving insulin." : { + "comment" : "Notice detail on the Now screen under a critical pump problem reported by the pump" + }, + "Loop predicts %1$@ %2$@ by %3$@" : { + "comment" : "VoiceOver summary of the prediction chart. (1: predicted glucose value; 2: glucose unit, mmol/L or mg/dL; 3: time of the prediction)" + }, + "Loop status" : { + "comment" : "Trends card title: how long Loop spent in closed loop, limited or open loop" + }, + "Loop trends" : { + "comment" : "Title of the exported Trends PDF report" + }, + "Loop trends %1$@" : { + "comment" : "File name of an exported Trends report or CSV, without the extension. (1: date range of the period)" + }, + "Loop · %1$@ · tap to list" : { + "comment" : "Logbook folded automatic boluses row subtitle: Loop gave them, the time span they cover, and tapping lists them. (1: time range, e.g. 15:08 – 16:14)" + }, + "Loop · %lld changes · tap to list" : { + "comment" : "Logbook basal adjustments row subtitle: how many temp basals Loop set in the day; tapping lists them. (1: number of changes)", + "localizations" : { + "en" : { + "variations" : { + "plural" : { + "one" : { + "stringUnit" : { + "state" : "translated", + "value" : "Loop · %lld change · tap to list" + } + }, + "other" : { + "stringUnit" : { + "state" : "translated", + "value" : "Loop · %lld changes · tap to list" + } + } + } + } + } + } + }, + "Manual %1$@" : { + "comment" : "Basal and bolus: bolus the person gave. (1: units, e.g. 16.2 U)" + }, + "Manual · %1$@" : { + "comment" : "Logbook temp basal row subtitle: set by hand, then the rate and how long. (1: description, e.g. 0.50 U/h for 30m (scheduled 0.80))" + }, + "Median" : { + "comment" : "Trends Daily pattern legend: the median glucose line" + }, + "Medium" : { + "comment" : "Carb entry absorption choice: a typical mixed meal" + }, + "New Interface" : { + "comment" : "Title of the toggle for the redesigned interface" + }, + "Next day" : { + "comment" : "Accessibility label for the day page button that steps forward a day" + }, + "Next period" : { + "comment" : "VoiceOver label for the Trends button that moves forward one period" + }, + "Night" : { + "comment" : "Appearance option that always uses dark mode" + }, + "No CGM data" : { + "comment" : "Trends Average tile detail when the period has no glucose readings" + }, + "No CGM data %1$@ – %2$@" : { + "comment" : "Chart note: a gap in glucose readings. (1: start time; 2: end time)" + }, + "No CGM data %1$@ – %2$@ and %3$@" : { + "comment" : "Chart note: the longest gap in glucose readings, plus the shorter ones. (1: start time; 2: end time; 3: number of shorter gaps, e.g. 2 shorter gaps)" + }, + "No CGM data in the last 3 hours" : { + "comment" : "Empty prediction chart on the Now screen" + }, + "No CGM data in this period" : { + "comment" : "Trends chart placeholder when the period has no glucose readings" + }, + "No CGM data on this day" : { + "comment" : "Chart note: there are no glucose readings for the whole day" + }, + "No CGM data yet today" : { + "comment" : "Chart note: there are no glucose readings so far today" + }, + "No gaps: Loop ran closed loop all through this period." : { + "comment" : "Trends Gaps list when Loop was in closed loop for the whole period" + }, + "No insulin recorded in this period" : { + "comment" : "Trends Insulin per day chart placeholder when no insulin was delivered in the period" + }, + "No loop runs recorded in this period" : { + "comment" : "Trends Loop status placeholder when there is no Loop run history for the period" + }, + "No reading" : { + "comment" : "Shown on the Now screen in place of the glucose value when there is no recent CGM reading" + }, + "Not enough days for a pattern: %1$@ of 5" : { + "comment" : "Trends Daily pattern footnote when fewer than 5 days have readings; the chart shows raw readings instead. (1: days with readings)" + }, + "Nothing logged" : { + "comment" : "Logbook day with no entries" + }, + "Nothing logged in the last 7 days." : { + "comment" : "Logbook empty state when there are no entries at all" + }, + "Nothing to show for this filter" : { + "comment" : "Logbook day with no entries matching the selected filter" + }, + "Now" : { + "comment" : "Title at the top of the Now screen, showing current glucose and Loop status Title of the Now tab in the redesigned interface, showing current glucose and Loop status" + }, + "now" : { + "comment" : "Prediction chart x-axis label marking the current time" + }, + "Older days come from Apple Health, which doesn't record the basal schedule, and some boluses there don't say whether they were manual or automatic." : { + "comment" : "Trends Insulin per day footnote when the period reaches back past Loop's own records into Apple Health, so scheduled basal can't be shown, or some boluses there have no record of whether they were manual or automatic" + }, + "Open loop / manual" : { + "comment" : "Trends Loop status: time closed loop was switched off" + }, + "Open loop · %1$@" : { + "comment" : "Status pill on the Now screen: closed loop is off (Loop recommends only) and Loop last ran this long ago. (1: duration, e.g. 3m)" + }, + "Open loop · not run yet" : { + "comment" : "Status pill on the Now screen: closed loop is off and Loop has never completed" + }, + "Open Settings" : { + "comment" : "Loop status sheet button that opens Loop's settings" + }, + "Opens carb absorption" : { + "comment" : "VoiceOver hint for the COB tile on the Now screen" + }, + "Opens CGM settings" : { + "comment" : "VoiceOver hint for the CGM status pill and CGM notice on the Now screen" + }, + "Opens insulin delivery history" : { + "comment" : "VoiceOver hint for the IOB tile on the Now screen" + }, + "Opens Loop's prediction breakdown" : { + "comment" : "VoiceOver hint for the prediction card on the Now screen" + }, + "Opens pump settings" : { + "comment" : "VoiceOver hint for the pump status pill and pump notice on the Now screen" + }, + "Opens the full day" : { + "comment" : "VoiceOver hint for the Today so far card on the Now screen" + }, + "PDF report" : { + "comment" : "Trends export menu item: share a PDF report of the period" + }, + "per day, weekly average" : { + "comment" : "Trends Insulin per day card subtitle when each bar is a week's average daily total" + }, + "per day, weekly average · %1$@" : { + "comment" : "Trends Insulin per day card subtitle when each bar is a week's average daily total and only some days of the period are averaged. (1: days averaged, e.g. 4 of 90 days)" + }, + "Period" : { + "comment" : "Trends: VoiceOver label of the picker that chooses how many days the screen covers" + }, + "Pod changed" : { + "comment" : "Pump event in the history: the pump or pod was replaced" + }, + "Pre-meal on" : { + "comment" : "Presets button title on the Now screen while the pre-meal target is on" + }, + "Predicted" : { + "comment" : "Prediction chart callout label for Loop's predicted glucose at the touched time" + }, + "Previous day" : { + "comment" : "Accessibility label for the day page button that steps back a day" + }, + "Previous period" : { + "comment" : "VoiceOver label for the Trends button that moves back one period" + }, + "Primed" : { + "comment" : "Pump event in the history: the pump primed the tubing or cannula" + }, + "Pump alarm" : { + "comment" : "Pump event in the history: an alarm whose pump gave no title" + }, + "Recent readings unavailable: %1$@" : { + "comment" : "Error under the prediction chart on the Now screen. (1: system error description)" + }, + "Reservoir changed" : { + "comment" : "Pump event in the history: the insulin reservoir was replaced" + }, + "Reservoir rewound" : { + "comment" : "Pump event in the history: the pump rewound its reservoir" + }, + "Scheduled %1$@" : { + "comment" : "Basal and bolus: what the basal schedule delivers over the same time, under the basal row. (1: units, e.g. 18.0 U)" + }, + "Scheduled basal only" : { + "comment" : "Logbook day where only the scheduled basal ran, with nothing else logged" + }, + "SD %1$@ · CV %2$@%%" : { + "comment" : "Trends Average tile detail: standard deviation and coefficient of variation of glucose. (1: standard deviation in the glucose unit, 2: coefficient of variation as a percentage number)" + }, + "Sets up a CGM" : { + "comment" : "VoiceOver hint for the Add CGM status pill on the Now screen" + }, + "Sets up a pump" : { + "comment" : "VoiceOver hint for the Add pump status pill on the Now screen" + }, + "Shows when Loop last ran" : { + "comment" : "VoiceOver hint for the Loop status pill and the Loop notice on the Now screen" + }, + "Slow" : { + "comment" : "Carb entry absorption choice: food that absorbs slowly, such as pizza" + }, + "Summary" : { + "comment" : "Trends card title: the summary statistics tiles" + }, + "Suspended" : { + "comment" : "Chart callout value: insulin delivery was suspended at the touched time Shown in the Basal tile on the Now screen when insulin delivery is suspended" + }, + "System" : { + "comment" : "Appearance option that follows the iPhone's light or dark setting" + }, + "System follows your iPhone's light or dark setting." : { + "comment" : "Footer for the appearance choice" + }, + "Target %1$@" : { + "comment" : "Glucose target on the Now screen hero card when the target range is a single value. (1: glucose value)" + }, + "Target %1$@–%2$@" : { + "comment" : "Glucose target range on the Now screen hero card. (1: lower bound; 2: upper bound)" + }, + "Temp basal" : { + "comment" : "Logbook row title: a temporary basal rate" + }, + "The icon couldn't be changed: %@" : { + "comment" : "Error shown when iOS refuses an app icon change" + }, + "The new interface adds Trends and Logbook tabs. Turn it off to go back to the classic status screen; Settings closes to switch." : { + "comment" : "Footer for the interface choice in settings" + }, + "this day" : { + "comment" : "Trends Basal and bolus card subtitle when the period is one complete day" + }, + "Time" : { + "comment" : "Carb entry row label: the exact time the food was eaten" + }, + "Time in range" : { + "comment" : "Trends card title: share of time in each glucose range" + }, + "Time in range, daily pattern, insulin per day and Loop status" : { + "comment" : "Trends settings descriptive text" + }, + "Today" : { + "comment" : "Day page title when showing today" + }, + "today so far" : { + "comment" : "Trends Basal and bolus card subtitle when the figures are today's total so far" + }, + "Today so far" : { + "comment" : "Title of the card on the Now screen showing today's insulin and carbs" + }, + "Today so far %1$@, usually %2$@ by %3$@." : { + "comment" : "Trends Insulin per day footnote: today's insulin so far against the median by this time of day over the last 14 days. (1: today's units, 2: usual units, 3: time of day)" + }, + "Today · %1$@" : { + "comment" : "Logbook day header for today. (1: weekday and date, e.g. Sun 25 Oct)" + }, + "Total" : { + "comment" : "Basal and bolus total row: basal plus bolus" + }, + "Total %1$@" : { + "comment" : "VoiceOver: total insulin. (1: units)" + }, + "Total so far" : { + "comment" : "Basal and bolus total row for today, which isn't over yet" + }, + "Total so far %1$@" : { + "comment" : "VoiceOver: today's total insulin so far. (1: units)" + }, + "Touch and hold a chart to see exact values." : { + "comment" : "Hint under the day page charts explaining how to scrub them" + }, + "Trends" : { + "comment" : "Title of the Trends tab Title of the Trends tab in the redesigned interface" + }, + "Type an amount to see when it'll be absorbed" : { + "comment" : "Carb entry preview before an amount is typed" + }, + "U/h" : { + "comment" : "Abbreviation for insulin units per hour" + }, + "Urgent low" : { + "comment" : "Pill under the glucose value on the Now screen when glucose is below 54 mg/dL (3.0 mmol/L)" + }, + "Usually %1$@ by %2$@" : { + "comment" : "Trends: the median insulin delivered by this time of day over the last 14 days. (1: units, e.g. 28.4 U, 2: time of day)" + }, + "Very high" : { + "comment" : "Time in range band: glucose above 250 mg/dL (13.9 mmol/L) Time-in-range band name: glucose above 250 mg/dL (13.9 mmol/L)" + }, + "Very low" : { + "comment" : "Time in range band: glucose below 54 mg/dL (3.0 mmol/L) Time-in-range band name: glucose below 54 mg/dL (3.0 mmol/L)" + }, + "vs plan" : { + "comment" : "Logbook basal adjustments row: the insulin amount is the difference from the scheduled basal" + }, + "Yesterday · %1$@" : { + "comment" : "Logbook day header for yesterday. (1: weekday and date, e.g. Sat 24 Oct)" }, " - " : { @@ -11576,9 +12332,6 @@ }, "CAUTION - Investigational device. Limited by Federal (or United States) law to investigational use." : { - }, - "CGM Active" : { - "comment" : "Percent of time CGM data present metric title" }, "Change the pump battery immediately" : { "comment" : "The notification alert describing a low pump battery", @@ -14827,12 +15580,6 @@ } } }, - "Daily glucose pattern" : { - "comment" : "Accessibility label for the daily glucose pattern (AGP) chart" - }, - "Daily Glucose Pattern" : { - "comment" : "Daily glucose pattern (AGP) section header" - }, "Date" : { "comment" : "Date picker label", "localizations" : { @@ -17341,12 +18088,6 @@ }, "During this kind of hard exercise, your body may release hormones that raise glucose. This is more common in the morning before eating." : { - }, - "Each 1% time in range ≈ 15 minutes." : { - "comment" : "TIR helper" - }, - "Each 5% increase in range is clinically beneficial." : { - "comment" : "TIR suggestion" }, "Easy breath. Can carry on a conversation." : { @@ -21049,9 +21790,6 @@ } } }, - "Glucose Metrics" : { - "comment" : "Glucose metrics section header" - }, "Glucose Momentum" : { "comment" : "Title of the prediction input effect for glucose momentum", "localizations" : { @@ -21186,24 +21924,6 @@ "Go to Settings > Focus." : { "comment" : "Focus modes step 1" }, - "Goal: <%@" : { - "comment" : "Average glucose goal" - }, - "Goal: <1%" : { - "comment" : "TIR goal for very low" - }, - "Goal: <5%" : { - "comment" : "TIR goal for very high" - }, - "Goal: <7%" : { - "comment" : "GMI goal" - }, - "Goal: >70%" : { - "comment" : "CGM active goal\nTIR goal for target range" - }, - "Goal: ≤36%" : { - "comment" : "Glucose variability goal" - }, "grams" : { }, @@ -21947,9 +22667,6 @@ } } }, - "In Range" : { - "comment" : "Time-in-range band label (70–180 mg/dL)" - }, "Includes basal and automated boluses" : { }, @@ -26393,9 +27110,6 @@ }, "Meal Timing" : { - }, - "Median (line) with 25–75% and 5–95% bands, by time of day." : { - "comment" : "AGP chart explanation" }, "Medium Intensity (Aerobic)" : { @@ -27807,9 +28521,6 @@ }, "No Delivery" : { - }, - "No glucose data for this period." : { - "comment" : "Statistics empty state" }, "No Maximum Bolus Configured" : { "comment" : "Alert title for a missing maximum bolus setting error", @@ -28506,9 +29217,6 @@ }, "None in last 24 hours" : { - }, - "Not enough data to plot a profile." : { - "comment" : "AGP empty state" }, "Not Set" : { "comment" : "Health sharing status: not determined" @@ -34144,9 +34852,6 @@ }, "She can do this by raising her **Overall Insulin** setting. This tells %@ to deliver more than her usual amount, making her insulin settings stronger." : { - }, - "Showing %1$d days of data — not enough for the full %2$d-day period yet." : { - "comment" : "Notice when the selected statistics range has incomplete data" }, "Shows last loop error" : { "comment" : "Loop Completion HUD accessibility hint", @@ -35195,9 +35900,6 @@ }, "Starting your exercise with high active insulin" : { - }, - "Statistics" : { - "comment" : "Statistics screen title\nStatistics settings button text" }, "Stay hydrated" : { @@ -37409,9 +38111,6 @@ }, "These recommendations should be used as a starting point. Checking your glucose during exercise will help you find the settings that work best for you." : { - }, - "This device keeps %d days of glucose. Increase the cache duration and rebuild to review the full period." : { - "comment" : "Notice when the local cache limits the statistics history" }, "This dose still has active insulin. Deleting it may cause Loop to make up for the reduced active insulin by dosing more." : { "comment" : "Warning when deleting a Loop-recorded dose that still has active insulin" @@ -40058,9 +40757,6 @@ } } }, - "Variability" : { - "comment" : "Coefficient of variation metric title" - }, "Version" : { "comment" : "Label for the app version row in the Support section" }, diff --git a/Loop/Managers/LoopAppManager.swift b/Loop/Managers/LoopAppManager.swift index 8b12cac3ef..46e5a7b1d0 100644 --- a/Loop/Managers/LoopAppManager.swift +++ b/Loop/Managers/LoopAppManager.swift @@ -202,6 +202,7 @@ class LoopAppManager: NSObject { precondition(state == .launchManagers) windowProvider?.window?.tintColor = .loopAccent + windowProvider?.window?.overrideUserInterfaceStyle = LoopAppearancePreference.current.interfaceStyle OrientationLock.deviceOrientationController = self resetLoopManager = ResetLoopManager(delegate: self) @@ -526,6 +527,16 @@ class LoopAppManager: NSObject { analyticsServicesManager.application(didFinishLaunchingWithOptions: launchOptions) + NotificationCenter.default.publisher(for: LoopAppearancePreference.didChange) + .receive(on: RunLoop.main) + .sink { [weak self] _ in self?.windowProvider?.window?.overrideUserInterfaceStyle = LoopAppearancePreference.current.interfaceStyle } + .store(in: &cancellables) + + NotificationCenter.default.publisher(for: LoopInterfacePreference.didChange) + .receive(on: RunLoop.main) + .sink { [weak self] _ in self?.relaunchHomeScreenForInterfaceChange() } + .store(in: &cancellables) + state = state.next await loopDataManager.updateDisplayState() @@ -628,14 +639,14 @@ class LoopAppManager: NSObject { return SetupHistory(settings: settings, experiments: experiments, custom: CustomSetupChangeStore().changes) } viewModel.outcomesPackageBuilder = criticalEventLogExportManager.map { OutcomesPackageBuilder(logs: $0.logs) } + viewModel.historyProvider = LoopHistoryProvider(deviceManager: deviceDataManager, loopDataManager: loopDataManager, + settingsManager: settingsManager, temporaryPresetsManager: temporaryPresetsManager) return viewModel }() - private func launchHomeScreen() async { - dispatchPrecondition(condition: .onQueue(.main)) - precondition(state == .launchHomeScreen) - + /// Builds the status screen and makes it (or the redesign's tabs around it) the window's root. + private func installHomeScreen() { let viewModel = StatusTableViewModel( alertPermissionsChecker: alertPermissionsChecker, alertMuter: alertManager.alertMuter, @@ -661,26 +672,58 @@ class LoopAppManager: NSObject { self.statusTableViewController = statusTableView.viewController - var rootNavigationController = rootViewController as? RootNavigationController - if rootNavigationController == nil { - rootNavigationController = RootNavigationController() - rootViewController = rootNavigationController - } + let showsActionTabs = !LoopInterfacePreference.useRedesign + let statusScreen = UIHostingController( + rootView: statusTableView + .showsActionTabs(showsActionTabs) + .environmentObject(deviceDataManager.displayGlucosePreference) + .environment(\.appName, Bundle.main.bundleDisplayName) + .environment(\.isInvestigationalDevice, FeatureFlags.isInvestigationalDevice) + .environment(\.guidanceColors, .default) + .environment(\.loopStatusColorPalette, .loopStatus) + .environment(\.colorPalette, .default) + .environment(\.settingsManager, settingsManager) + .environment(\.temporaryPresetsManager, temporaryPresetsManager) + .edgesIgnoringSafeArea(.top) + ) - rootNavigationController?.setViewControllers([ - UIHostingController( - rootView: statusTableView - .environmentObject(deviceDataManager.displayGlucosePreference) - .environment(\.appName, Bundle.main.bundleDisplayName) - .environment(\.isInvestigationalDevice, FeatureFlags.isInvestigationalDevice) - .environment(\.guidanceColors, .default) - .environment(\.loopStatusColorPalette, .loopStatus) - .environment(\.colorPalette, .default) - .environment(\.settingsManager, settingsManager) - .environment(\.temporaryPresetsManager, temporaryPresetsManager) - .edgesIgnoringSafeArea(.top) + LoopInterfacePreference.syncToExtensions() + if LoopInterfacePreference.useRedesign { + let rootNavigationController = RootNavigationController() + rootNavigationController.setViewControllers([statusScreen], animated: false) + rootViewController = MainTabBarController( + rootNavigationController: rootNavigationController, + statusTableViewController: statusTableView.viewController, + deviceManager: deviceDataManager, + loopDataManager: loopDataManager, + settingsManager: settingsManager ) - ], animated: true) + } else { + var rootNavigationController = rootViewController as? RootNavigationController + if rootNavigationController == nil { + rootNavigationController = RootNavigationController() + rootViewController = rootNavigationController + } + + rootNavigationController?.setViewControllers([statusScreen], animated: true) + } + } + + /// Swaps between the classic and redesigned interface once Loop is running. + private func relaunchHomeScreenForInterfaceChange() { + guard state == .launchComplete else { return } + if let presented = rootViewController?.presentedViewController { + presented.dismiss(animated: true) { [weak self] in self?.installHomeScreen() } + } else { + installHomeScreen() + } + } + + private func launchHomeScreen() async { + dispatchPrecondition(condition: .onQueue(.main)) + precondition(state == .launchHomeScreen) + + installHomeScreen() await deviceDataManager.refreshDeviceData() @@ -764,6 +807,7 @@ class LoopAppManager: NSObject { } analyticsServicesManager.didOpenFromLink() + (rootViewController as? MainTabBarController)?.showNow() switch deeplink { case let .carbEntry(carbEntryLink): diff --git a/Loop/Models/GlucoseStatistics.swift b/Loop/Models/GlucoseStatistics.swift index c321b6d854..a1d266c240 100644 --- a/Loop/Models/GlucoseStatistics.swift +++ b/Loop/Models/GlucoseStatistics.swift @@ -57,11 +57,15 @@ struct GlucoseStatistics: Equatable { let averageGlucose: Double? /// Glucose Management Indicator (estimated A1C), percent. Nil if no samples. let gmi: Double? + /// Sample standard deviation in mg/dL. Nil if < 2 samples. + let standardDeviation: Double? /// Coefficient of variation (sample SD / mean × 100), percent. Nil if < 2 samples. let coefficientOfVariation: Double? /// Fraction of time (0…1) spent in each band. Time-weighted, gap-capped. let timeInRange: [GlucoseBand: Double] - /// Fraction (0…1) of the window for which CGM data is present. + /// Fraction (0…1) of the window for which CGM data is present: each reading + /// covers the time until the next, up to one `assumedCadence` slot, so a + /// sensor that reports every minute doesn't count its gaps as covered. let percentActive: Double /// Per-time-of-day percentile bands for the AGP chart, ordered by time of day. let agpProfile: [AGPBand] @@ -75,20 +79,33 @@ struct GlucoseStatistics: Equatable { end: Date, bucketDuration: TimeInterval = .minutes(30), calendar: Calendar = .current + ) { + self.init(readings: samples.map { (date: $0.startDate, mgdl: $0.quantity.doubleValue(for: .milligramsPerDeciliter)) }, + start: start, end: end, bucketDuration: bucketDuration, calendar: calendar) + } + + /// Statistics from readings given as a date and a value in mg/dL. + init( + readings: [(date: Date, mgdl: Double)], + start: Date, + end: Date, + bucketDuration: TimeInterval = .minutes(30), + calendar: Calendar = .current ) { self.start = start self.end = end - let sorted = samples - .filter { $0.startDate >= start && $0.startDate < end } - .sorted { $0.startDate < $1.startDate } - let values = sorted.map { $0.quantity.doubleValue(for: .milligramsPerDeciliter) } + let sorted = readings + .filter { $0.date >= start && $0.date < end } + .sorted { $0.date < $1.date } + let values = sorted.map(\.mgdl) self.sampleCount = values.count - // Mean, GMI, CV + // Mean, GMI, SD, CV if values.isEmpty { averageGlucose = nil gmi = nil + standardDeviation = nil coefficientOfVariation = nil } else { let mean = values.reduce(0, +) / Double(values.count) @@ -97,22 +114,26 @@ struct GlucoseStatistics: Equatable { gmi = 3.31 + 0.02392 * mean if values.count >= 2, mean > 0 { let variance = values.reduce(0) { $0 + ($1 - mean) * ($1 - mean) } / Double(values.count - 1) + standardDeviation = variance.squareRoot() coefficientOfVariation = variance.squareRoot() / mean * 100 } else { + standardDeviation = nil coefficientOfVariation = nil } } // Time-in-range: weight each reading by the time until the next reading, // capping each interval so an offline gap can't dominate the breakdown. + // Percent active counts the same intervals, each capped at one reading's slot. let maxInterval = Self.assumedCadence * 2 var durations: [GlucoseBand: TimeInterval] = [:] - for (index, sample) in sorted.enumerated() { - let nextDate = index + 1 < sorted.count ? sorted[index + 1].startDate : end - let duration = min(nextDate.timeIntervalSince(sample.startDate), maxInterval) - guard duration > 0 else { continue } - let band = GlucoseBand.classify(mgdl: values[index]) - durations[band, default: 0] += duration + var covered: TimeInterval = 0 + for (index, reading) in sorted.enumerated() { + let nextDate = index + 1 < sorted.count ? sorted[index + 1].date : end + let interval = nextDate.timeIntervalSince(reading.date) + guard interval > 0 else { continue } + durations[GlucoseBand.classify(mgdl: values[index]), default: 0] += min(interval, maxInterval) + covered += min(interval, Self.assumedCadence) } let totalDuration = durations.values.reduce(0, +) if totalDuration > 0 { @@ -121,21 +142,15 @@ struct GlucoseStatistics: Equatable { timeInRange = [:] } - // Percent active: covered time (gap-capped) over the window length. let windowDuration = end.timeIntervalSince(start) - if windowDuration > 0 { - let covered = Double(values.count) * Self.assumedCadence - percentActive = min(1, covered / windowDuration) - } else { - percentActive = 0 - } + percentActive = windowDuration > 0 ? min(1, covered / windowDuration) : 0 // AGP: pool readings into time-of-day buckets across all days, then take // percentiles per bucket. Skip buckets with too few readings to be useful. let bucketCount = max(1, Int((TimeInterval.hours(24) / bucketDuration).rounded())) var buckets: [[Double]] = Array(repeating: [], count: bucketCount) - for (index, sample) in sorted.enumerated() { - let secondsOfDay = sample.startDate.timeIntervalSince(calendar.startOfDay(for: sample.startDate)) + for (index, reading) in sorted.enumerated() { + let secondsOfDay = reading.date.timeIntervalSince(calendar.startOfDay(for: reading.date)) let bucket = min(bucketCount - 1, max(0, Int(secondsOfDay / bucketDuration))) buckets[bucket].append(values[index]) } diff --git a/Loop/Redesign/AppearanceSettings.swift b/Loop/Redesign/AppearanceSettings.swift new file mode 100644 index 0000000000..259e7b953e --- /dev/null +++ b/Loop/Redesign/AppearanceSettings.swift @@ -0,0 +1,203 @@ +// +// AppearanceSettings.swift +// Loop +// +// Copyright © 2026 LoopKit Authors. All rights reserved. +// + +import SwiftUI +import UIKit + +/// Light, dark or the system's choice, applied to Loop's whole window. +enum LoopAppearancePreference: String, CaseIterable, Identifiable { + case system + case light + case dark + + private static let key = "com.loopkit.Loop.redesign.appearance" + + static let didChange = Notification.Name("LoopAppearancePreferenceDidChange") + + static var current: LoopAppearancePreference { + get { UserDefaults.standard.string(forKey: key).flatMap(LoopAppearancePreference.init(rawValue:)) ?? .system } + set { + guard newValue != current else { return } + UserDefaults.standard.set(newValue.rawValue, forKey: key) + NotificationCenter.default.post(name: didChange, object: nil) + } + } + + var id: String { rawValue } + + var title: String { + switch self { + case .system: return NSLocalizedString("System", comment: "Appearance option that follows the iPhone's light or dark setting") + case .light: return NSLocalizedString("Day", comment: "Appearance option that always uses light mode") + case .dark: return NSLocalizedString("Night", comment: "Appearance option that always uses dark mode") + } + } + + var interfaceStyle: UIUserInterfaceStyle { + switch self { + case .system: return .unspecified + case .light: return .light + case .dark: return .dark + } + } +} + +/// The home screen icons Loop ships. Classic is the primary icon; the others are alternate icon sets in DerivedAssetsBase. +enum LoopAppIcon: String, CaseIterable, Identifiable { + case classic + case dayAndNight + case day + case night + + var id: String { rawValue } + + /// The asset catalog name passed to `setAlternateIconName`; nil is the primary icon. + var alternateIconName: String? { + switch self { + case .classic: return nil + case .dayAndNight: return "AppIconDayNight" + case .day: return "AppIconDay" + case .night: return "AppIconNight" + } + } + + var title: String { + switch self { + case .classic: return NSLocalizedString("Classic", comment: "Name of Loop's original app icon") + case .dayAndNight: return NSLocalizedString("Day and Night", comment: "Name of the app icon that follows the home screen's light or dark appearance") + case .day: return NSLocalizedString("Day", comment: "Name of the light app icon") + case .night: return NSLocalizedString("Night", comment: "Name of the dark app icon") + } + } + + var detail: String? { + switch self { + case .dayAndNight: return NSLocalizedString("Changes with the home screen's light or dark appearance", comment: "Description of the app icon that follows the home screen appearance") + default: return nil + } + } + + static var current: LoopAppIcon { + let name = UIApplication.shared.alternateIconName + return allCases.first { $0.alternateIconName == name } ?? .classic + } + + /// The preview shown in Settings. iOS doesn't expose alternate icons as images, so they have their own + /// preview image sets; Classic is read from the primary icon files, which a workspace may override. + var preview: UIImage? { + switch self { + case .classic: break + case .dayAndNight: return UIImage(named: "AppIconPreviewDayNight") + case .day: return UIImage(named: "AppIconPreviewDay") + case .night: return UIImage(named: "AppIconPreviewNight") + } + let icons = Bundle.main.object(forInfoDictionaryKey: "CFBundleIcons") as? [String: Any] + let entry = icons?["CFBundlePrimaryIcon"] as? [String: Any] + if let files = entry?["CFBundleIconFiles"] as? [String] { + for file in files.reversed() { + if let image = UIImage(named: file) { return image } + } + } + return (entry?["CFBundleIconName"] as? String).flatMap { UIImage(named: $0) } + } +} + +/// Settings → Appearance: day or night for the app, and which icon the home screen shows. +struct AppearanceSettingsView: View { + @State private var appearance = LoopAppearancePreference.current + @State private var icon = LoopAppIcon.current + @State private var iconError: String? + + var body: some View { + List { + Section(footer: Text(NSLocalizedString("System follows your iPhone's light or dark setting.", comment: "Footer for the appearance choice"))) { + Picker(NSLocalizedString("Appearance", comment: "Title of the light or dark appearance choice"), selection: $appearance) { + ForEach(LoopAppearancePreference.allCases) { option in + Text(option.title).tag(option) + } + } + .pickerStyle(.segmented) + .onChange(of: appearance) { LoopAppearancePreference.current = $0 } + } + + Section(header: Text(NSLocalizedString("App Icon", comment: "Header for the app icon choice")), footer: iconFooter) { + ForEach(LoopAppIcon.allCases) { option in + Button { + choose(option) + } label: { + AppIconRow(icon: option, isSelected: option == icon) + } + .buttonStyle(.plain) + } + } + } + .listStyle(.insetGrouped) + .navigationTitle(NSLocalizedString("Appearance", comment: "Title of the appearance settings screen")) + } + + @ViewBuilder + private var iconFooter: some View { + if let iconError { + Text(iconError).foregroundStyle(LoopDesign.Palette.statusCritical) + } + } + + private func choose(_ option: LoopAppIcon) { + guard option != icon, UIApplication.shared.supportsAlternateIcons else { return } + UIApplication.shared.setAlternateIconName(option.alternateIconName) { error in + DispatchQueue.main.async { + // iOS can report an error from the "icon changed" alert even though the icon did change, + // so the icon iOS now reports decides. + if let error, UIApplication.shared.alternateIconName != option.alternateIconName { + iconError = String(format: NSLocalizedString("The icon couldn't be changed: %@", comment: "Error shown when iOS refuses an app icon change"), error.localizedDescription) + } else { + iconError = nil + icon = option + } + } + } + } +} + +private struct AppIconRow: View { + let icon: LoopAppIcon + let isSelected: Bool + + var body: some View { + HStack(spacing: LoopDesign.Space.s3) { + Group { + if let image = icon.preview { + Image(uiImage: image).resizable() + } else { + LoopDesign.Palette.surfaceSunken + } + } + .frame(width: 52, height: 52) + .clipShape(RoundedRectangle(cornerRadius: 12, style: .continuous)) + .overlay(RoundedRectangle(cornerRadius: 12, style: .continuous).strokeBorder(LoopDesign.Palette.separator, lineWidth: 0.5)) + .accessibilityHidden(true) + VStack(alignment: .leading, spacing: 2) { + Text(icon.title) + .foregroundStyle(LoopDesign.Palette.ink) + if let detail = icon.detail { + Text(detail) + .font(LoopDesign.Typeface.footnote) + .foregroundStyle(LoopDesign.Palette.inkMuted) + } + } + Spacer(minLength: 0) + if isSelected { + Image(systemName: "checkmark") + .font(.body.weight(.semibold)) + .foregroundStyle(LoopDesign.Palette.accent) + } + } + .contentShape(Rectangle()) + .accessibilityElement(children: .combine) + .accessibilityAddTraits(isSelected ? [.isButton, .isSelected] : .isButton) + } +} diff --git a/Loop/Redesign/CarbEntryScreen.swift b/Loop/Redesign/CarbEntryScreen.swift new file mode 100644 index 0000000000..aa44c2c169 --- /dev/null +++ b/Loop/Redesign/CarbEntryScreen.swift @@ -0,0 +1,873 @@ +// +// CarbEntryScreen.swift +// Loop +// +// Copyright © 2026 LoopKit Authors. All rights reserved. +// + +import SwiftUI +import LoopKit +import LoopKitUI +import Charts + +private typealias P = LoopDesign.Palette + +/// Adding or editing carbs in the redesign. It drives the same CarbEntryViewModel as CarbEntryView, so validation, +/// favourite foods and the hand-off to the bolus screen are unchanged; only the layout is new. +/// +/// The top of the screen is a preview of the meal as Loop will model it: the amount, over Loop's absorption curve +/// drawn on a real time axis. The amount sets the curve's height, the speed its length, and when it was eaten where +/// it sits against now, so every choice below shows its effect there. +struct CarbEntryScreen: View { + @EnvironmentObject private var displayGlucosePreference: DisplayGlucosePreference + @Environment(\.dismissAction) private var dismiss + @Environment(\.guidanceColors) private var guidanceColors + @Environment(\.dynamicTypeSize) private var typeSize + @Environment(\.accessibilityReduceMotion) private var reduceMotion + + @ObservedObject var viewModel: CarbEntryViewModel + + @State private var amountText: String + @State private var eatenChoice: Int? + @State private var showHowAbsorptionTimeWorks = false + @State private var showAddFavoriteFood = false + @State private var showTimePicker = false + /// Set once the sheet has settled, so the number pad comes up as Loop's carb entry always has. + @State private var focusAmount = false + /// Other was tapped, so it stays chosen even while its food and time still match a preset. + @State private var otherChosen = false + @FocusState private var foodTypeFocused: Bool + @Namespace private var thumbs + + private let isNewEntry: Bool + + /// Minutes before now offered as one-tap times. + private static let eatenChoices = [0, 15, 30, 60] + + init(viewModel: CarbEntryViewModel) { + self.viewModel = viewModel + isNewEntry = viewModel.originalCarbEntry == nil + _amountText = State(initialValue: viewModel.carbsQuantity.flatMap { $0 > 0 ? Self.amountFormatter.string(from: NSNumber(value: $0)) : nil } ?? "") + _eatenChoice = State(initialValue: viewModel.originalCarbEntry == nil && abs(viewModel.time.timeIntervalSinceNow) < 60 ? 0 : nil) + } + + var body: some View { + if isNewEntry { + NavigationStack { + content + .navigationTitle(NSLocalizedString("Add carbs", comment: "Button on the Now screen that opens carb entry")) + .navigationBarTitleDisplayMode(.inline) + .toolbar { + ToolbarItem(placement: .navigationBarLeading) { + Button(NSLocalizedString("Cancel", comment: "Button label for cancel"), action: dismiss) + } + } + } + } else { + content + } + } + + private var content: some View { + ScrollView { + VStack(alignment: .leading, spacing: LoopDesign.Space.s4) { + if let override = viewModel.currentOverride { + ActivePresetBanner(override: override) + } + ForEach(Array(viewModel.warnings).sorted { $0.priority < $1.priority }) { warning in + warningView(warning) + } + mealPreview + if isNewEntry, FeatureFlags.allowExperimentalFeatures { + favourites + } + absorption + eaten + } + .padding(.horizontal, LoopDesign.Space.s4) + .padding(.top, LoopDesign.Space.s2) + .padding(.bottom, LoopDesign.Space.s6) + } + // Any scroll puts the keyboard away: at large text sizes it otherwise covers the rest of the form for good. + .scrollDismissesKeyboard(.immediately) + .toolbar { + if foodTypeFocused { + ToolbarItem(placement: .navigationBarTrailing) { + Button(NSLocalizedString("Done", comment: "Button to put the keyboard away after typing a food type on the carb entry screen")) { + foodTypeFocused = false + } + } + } + } + .background(P.surface) + .safeAreaInset(edge: .bottom) { entryBar } + .onAppear { + // As FoodTypeRow does: a new entry starts as the medium food, so the entry carries its emoji. + if isNewEntry && !viewModel.usesCustomFoodType && viewModel.selectedDefaultAbsorptionTimeEmoji.isEmpty { + viewModel.selectedDefaultAbsorptionTimeEmoji = Speed.medium.emoji + } + } + .task { + // A first responder set while the sheet is still presenting is dropped, so wait for it to settle. + guard viewModel.shouldBeginEditingQuantity else { return } + try? await Task.sleep(for: .milliseconds(450)) + focusAmount = true + } + .onChange(of: viewModel.carbsQuantity) { _, quantity in + // A favourite fills the amount in. What's typed already shows its own amount ("3." is 3), so only a + // change from elsewhere rewrites it. + guard Self.amountFormatter.number(from: amountText)?.doubleValue != quantity else { return } + amountText = quantity.flatMap { $0 > 0 ? Self.amountFormatter.string(from: NSNumber(value: $0)) : nil } ?? "" + } + .navigationDestination(isPresented: Binding(get: { viewModel.bolusViewModel != nil }, set: { if !$0 { viewModel.bolusViewModel = nil } })) { + if let bolusViewModel = viewModel.bolusViewModel { + BolusEntryView(viewModel: bolusViewModel) + .environmentObject(displayGlucosePreference) + .environment(\.dismissAction, dismiss) + .environment(\.guidanceColors, guidanceColors) + } + } + .alert(item: $viewModel.alert, content: alert(for:)) + .sheet(isPresented: $showHowAbsorptionTimeWorks) { + HowAbsorptionTimeWorksView() + } + .sheet(isPresented: $showAddFavoriteFood) { + FavoriteFoodAddEditView(carbsQuantity: viewModel.carbsQuantity, + foodType: viewModel.usesCustomFoodType ? viewModel.foodType : viewModel.selectedDefaultAbsorptionTimeEmoji, + absorptionTime: viewModel.absorptionTime) { food in + showAddFavoriteFood = false + viewModel.onFavoriteFoodSave(food) + } + } + } + + private func animated(_ change: () -> Void) { + if reduceMotion { + change() + } else { + withAnimation(.snappy(duration: 0.3), change) + } + } + + // MARK: Meal preview + + private static let amountFormatter: NumberFormatter = { + let formatter = NumberFormatter() + formatter.numberStyle = .decimal + formatter.maximumFractionDigits = 1 + formatter.usesGroupingSeparator = false + return formatter + }() + + private var mealPreview: some View { + VStack(alignment: .leading, spacing: LoopDesign.Space.s2) { + amountDisplay + + TimelineView(.everyMinute) { context in + MealAbsorptionChart(grams: viewModel.carbsQuantity ?? 0, + absorptionTime: viewModel.absorptionTime, + eaten: viewModel.time, + now: context.date, + axisLength: max(viewModel.defaultAbsorptionTimes.slow, viewModel.absorptionTime)) + } + } + .padding(.horizontal, LoopDesign.Space.s4) + .padding(.top, LoopDesign.Space.s1) + .padding(.bottom, LoopDesign.Space.s4) + .background(P.surfaceRaised, in: RoundedRectangle(cornerRadius: 22, style: .continuous)) + } + + private var hasAmount: Bool { (viewModel.carbsQuantity ?? 0) > 0 } + + private static let amountFont: UIFont = { + let base = UIFont.monospacedDigitSystemFont(ofSize: 56, weight: .bold) + return UIFont(descriptor: base.fontDescriptor.withDesign(.rounded) ?? base.fontDescriptor, size: 56) + }() + + /// The amount, typed on the iPhone's number pad. It reads as the meal's size: carbs green once there is one. + /// A hidden copy of the text sizes the field, so the unit sits right after the number. + private var amountDisplay: some View { + HStack(alignment: .firstTextBaseline, spacing: LoopDesign.Space.s1) { + Text(amountText.isEmpty ? "0" : amountText) + .font(Font(Self.amountFont)) + .padding(.trailing, 4) + .hidden() + .overlay(alignment: .leading) { + DismissibleKeyboardTextField(text: $amountText, placeholder: "0", font: Self.amountFont, + textColor: UIColor(P.carbs), keyboardType: .decimalPad, + shouldBecomeFirstResponder: focusAmount, maxLength: 5, + doneButtonColor: UIColor(P.accent)) + .frame(minWidth: 40) + .accessibilityLabel(NSLocalizedString("Amount Consumed", comment: "Label for carb quantity entry row on carb entry screen")) + .accessibilityIdentifier("textField_CarbsAmount") + } + Text(NSLocalizedString("g", comment: "Abbreviation for grams")) + .font(.system(size: 28, weight: .semibold, design: .rounded)) + .foregroundStyle(P.inkMuted) + .accessibilityHidden(true) + Spacer(minLength: 0) + } + .onChange(of: amountText) { _, text in + // One decimal place at most, as Loop's carb entry allows. + let parts = text.components(separatedBy: Self.decimalSeparator) + if parts.count > 2 || (parts.count == 2 && parts[1].count > 1) { + amountText = parts[0] + Self.decimalSeparator + String((parts.dropFirst().joined()).prefix(1)) + return + } + viewModel.carbsQuantity = Self.amountFormatter.number(from: text)?.doubleValue + } + } + + private static var decimalSeparator: String { amountFormatter.decimalSeparator ?? "." } + + /// Puts the number pad away when another choice is made, so what it covered comes back into view. + private func endEditing() { + UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil) + } + + // MARK: Favourites + + @ViewBuilder + private var favourites: some View { + if !viewModel.favoriteFoods.isEmpty || !viewModel.saveFavoriteFoodButtonDisabled { + VStack(alignment: .leading, spacing: LoopDesign.Space.s2) { + ScrollView(.horizontal, showsIndicators: false) { + HStack(spacing: LoopDesign.Space.s2) { + ForEach(Array(viewModel.favoriteFoods.enumerated()), id: \.element.id) { index, food in + let selected = viewModel.selectedFavoriteFoodIndex == index + Button { + endEditing() + // A favourite brings its own food and time, so the speed shown follows it rather than an earlier Other. + otherChosen = false + animated { + viewModel.selectedFavoriteFoodIndex = selected ? -1 : index + // Letting a new meal's favourite go resets it to medium absorption, so the speed shown and + // the food type saved go back to medium too, rather than a speed chosen before the favourite. + if selected && viewModel.originalCarbEntry == nil { + viewModel.selectedDefaultAbsorptionTimeEmoji = Speed.medium.emoji + } + } + } label: { + HStack(spacing: 6) { + Text(food.foodType) + Text(food.name).foregroundStyle(P.ink) + Text(LoopFormat.grams(food.carbsQuantity.doubleValue(for: .gram))) + .monospacedDigit() + .foregroundStyle(selected ? P.carbs : P.inkMuted) + } + .font(LoopDesign.Typeface.subhead.weight(.medium)) + .padding(.horizontal, 14) + .frame(minHeight: 40) + .background(selected ? P.carbs.opacity(0.18) : P.surfaceRaised, in: Capsule()) + .overlay(Capsule().strokeBorder(selected ? P.carbs : .clear, lineWidth: 1.5)) + } + .buttonStyle(.plain) + .accessibilityAddTraits(selected ? .isSelected : []) + } + if viewModel.selectedFavoriteFood == nil { + Button { + showAddFavoriteFood = true + } label: { + Label(NSLocalizedString("Save as favorite food", comment: "Button on the carb entry screen to save the entry as a favourite food"), systemImage: "star") + .font(LoopDesign.Typeface.subhead.weight(.medium)) + .padding(.horizontal, 14) + .frame(minHeight: 40) + .overlay(Capsule().strokeBorder(P.separator.opacity(0.7), style: StrokeStyle(lineWidth: 1, dash: [3, 3]))) + } + .buttonStyle(.plain) + .foregroundStyle(P.accent) + .disabled(viewModel.saveFavoriteFoodButtonDisabled) + .opacity(viewModel.saveFavoriteFoodButtonDisabled ? 0.4 : 1) + } + } + .padding(.vertical, 1) + } + .scrollClipDisabled() + .accessibilityLabel(NSLocalizedString("Favorite Foods", comment: "The section title for Carb entry screen where Favorite Foods can be selected")) + } + } + } + + // MARK: Eaten + + private func eatenTitle(_ minutes: Int) -> String { + minutes == 0 + ? NSLocalizedString("Now", comment: "Carb entry time choice: eaten now") + : String(format: NSLocalizedString("%1$@ ago", comment: "Carb entry time choice: eaten this long before now. (1: duration, e.g. 15m or 1h)"), LoopFormat.duration(Double(minutes) * 60)) + } + + /// One row: the usual times, then a clock for any other. A time picked there takes the clock's place. + private var eaten: some View { + VStack(alignment: .leading, spacing: LoopDesign.Space.s2) { + sectionTitle(NSLocalizedString("Eaten", comment: "Carb entry section title: when the food was eaten")) + HStack(spacing: LoopDesign.Space.s2) { + ChoiceTrack(choices: Self.eatenChoices, selection: eatenChoice, thumb: "eaten", namespace: thumbs) { minutes in + endEditing() + let date = Date().addingTimeInterval(-Double(minutes) * 60) + animated { + eatenChoice = minutes + viewModel.time = min(max(date, viewModel.minimumDate), viewModel.maximumDate) + } + } label: { minutes, selected in + Text(eatenTitle(minutes)) + .font(LoopDesign.Typeface.subhead.weight(selected ? .semibold : .medium).monospacedDigit()) + .foregroundStyle(selected ? P.carbs : P.ink) + .lineLimit(1) + .minimumScaleFactor(0.7) + .padding(.vertical, LoopDesign.Space.s2) + } + .frame(maxWidth: .infinity) + .layoutPriority(1) + Button { + endEditing() + showTimePicker = true + } label: { + Group { + if eatenChoice == nil { + Text(LoopFormat.time(viewModel.time)) + .font(LoopDesign.Typeface.subhead.weight(.semibold).monospacedDigit()) + .foregroundStyle(P.carbs) + } else { + Image(systemName: "clock") + .font(LoopDesign.Typeface.subhead.weight(.semibold)) + .foregroundStyle(P.ink) + } + } + .padding(.horizontal, LoopDesign.Space.s3) + .frame(minWidth: 52, minHeight: 52) + .background(eatenChoice == nil ? P.carbs.opacity(0.18) : P.surfaceRaised, + in: RoundedRectangle(cornerRadius: 15, style: .continuous)) + .overlay { + if eatenChoice == nil { + RoundedRectangle(cornerRadius: 15, style: .continuous).strokeBorder(P.carbs, lineWidth: 1.5) + } + } + } + .buttonStyle(.plain) + .accessibilityLabel(NSLocalizedString("Time", comment: "Carb entry row label: the exact time the food was eaten")) + .accessibilityValue(LoopFormat.time(viewModel.time)) + } + } + .sheet(isPresented: $showTimePicker) { + NavigationStack { + DatePicker(selection: Binding(get: { viewModel.time }, set: { viewModel.time = $0; eatenChoice = nil }), + in: (viewModel.originalCarbEntry.map { min($0.startDate, viewModel.minimumDate) } ?? viewModel.minimumDate)...viewModel.maximumDate, + displayedComponents: [.date, .hourAndMinute]) { + Text(NSLocalizedString("Time", comment: "Carb entry row label: the exact time the food was eaten")) + } + .datePickerStyle(.wheel) + .labelsHidden() + .padding(.horizontal, LoopDesign.Space.s4) + .navigationTitle(NSLocalizedString("Eaten", comment: "Carb entry section title: when the food was eaten")) + .navigationBarTitleDisplayMode(.inline) + .toolbar { + ToolbarItem(placement: .confirmationAction) { + Button(NSLocalizedString("Done", comment: "Button to close the carb entry time picker")) { showTimePicker = false } + } + } + } + .presentationDetents([.height(320)]) + } + } + + // MARK: Absorption + + enum Speed: CaseIterable { + case fast, medium, slow, other + + /// The emoji FoodTypeRow uses for each default absorption time; the entry stores it as its food type. + var emoji: String { + switch self { + case .fast: return "🍭" + case .medium: return "🌮" + case .slow: return "🍕" + case .other: return "🍽️" + } + } + + var title: String { + switch self { + case .fast: return NSLocalizedString("Fast", comment: "Carb entry absorption choice: food that absorbs quickly, such as sweets") + case .medium: return NSLocalizedString("Medium", comment: "Carb entry absorption choice: a typical mixed meal") + case .slow: return NSLocalizedString("Slow", comment: "Carb entry absorption choice: food that absorbs slowly, such as pizza") + case .other: return NSLocalizedString("Other", comment: "Carb entry absorption choice: set your own food and absorption time") + } + } + } + + private func hours(_ speed: Speed) -> TimeInterval { + switch speed { + case .fast: return viewModel.defaultAbsorptionTimes.fast + case .medium: return viewModel.defaultAbsorptionTimes.medium + case .slow: return viewModel.defaultAbsorptionTimes.slow + case .other: return viewModel.absorptionTime + } + } + + private var selectedSpeed: Speed { + let presets = Speed.allCases.filter { $0 != .other } + if viewModel.usesCustomFoodType { + if otherChosen { return .other } + // A saved entry comes back as a custom food; one that is exactly a preset's emoji and time shows as that preset. + return presets.first { $0.emoji == viewModel.foodType && hours($0) == viewModel.absorptionTime } ?? .other + } + return presets.first { $0.emoji == viewModel.selectedDefaultAbsorptionTimeEmoji } ?? .medium + } + + private var absorption: some View { + VStack(alignment: .leading, spacing: LoopDesign.Space.s2) { + HStack { + sectionTitle(NSLocalizedString("How fast it absorbs", comment: "Carb entry section title: choose how quickly the food's carbs absorb")) + Spacer() + Button { + showHowAbsorptionTimeWorks = true + } label: { + Image(systemName: "info.circle") + .font(LoopDesign.Typeface.subhead.weight(.semibold)) + .frame(minWidth: 44, minHeight: 28, alignment: .trailing) + } + .foregroundStyle(P.accent) + .accessibilityLabel(NSLocalizedString("Absorption Time", comment: "Accessibility label for the button that explains carb absorption time")) + } + ChoiceTrack(choices: Speed.allCases, selection: selectedSpeed, thumb: "speed", namespace: thumbs) { speed in + animated { choose(speed) } + } label: { speed, selected in + VStack(spacing: 2) { + Text(speed.title) + .font(LoopDesign.Typeface.subhead.weight(selected ? .semibold : .medium)) + .foregroundStyle(selected ? P.carbs : P.ink) + HStack(spacing: 3) { + // The food the entry is saved with; Other shows the one typed in. + Text(speed == .other && selected && !viewModel.foodType.isEmpty ? viewModel.foodType : speed.emoji) + .dynamicTypeSize(...DynamicTypeSize.xxxLarge) + Text(durationLabel(speed, selected: selected)) + .foregroundStyle(selected ? P.carbs : P.inkMuted) + } + .font(LoopDesign.Typeface.footnote.monospacedDigit()) + } + .lineLimit(1) + .minimumScaleFactor(0.75) + .padding(.vertical, 10) + .accessibilityElement(children: .ignore) + .accessibilityLabel("\(speed.title), \(durationLabel(speed, selected: selected))") + } + if selectedSpeed == .other { + otherFood + .transition(.opacity.combined(with: .move(edge: .top))) + } + } + } + + private func durationLabel(_ speed: Speed, selected: Bool) -> String { + speed == .other && !selected + ? NSLocalizedString("Custom", comment: "Carb entry absorption choice Other, before it is chosen: you set the food and absorption time yourself") + : LoopFormat.duration(hours(speed)) + } + + private var otherFood: some View { + VStack(spacing: 0) { + HStack { + Text(NSLocalizedString("Food Type", comment: "Label for the food type row on the carb entry screen")) + .font(LoopDesign.Typeface.body) + Spacer() + TextField(Speed.other.emoji, text: $viewModel.foodType) + .multilineTextAlignment(.trailing) + .font(.title3) + .focused($foodTypeFocused) + .frame(maxWidth: 120) + } + .padding(.vertical, 10) + Divider() + Stepper(value: Binding(get: { viewModel.absorptionTime }, set: { newValue in animated { viewModel.absorptionTime = newValue } }), + in: viewModel.absorptionRimesRange, step: 30 * 60) { + HStack { + Text(NSLocalizedString("Absorption Time", comment: "Accessibility label for the button that explains carb absorption time")) + .font(LoopDesign.Typeface.body) + Spacer() + Text(LoopFormat.duration(viewModel.absorptionTime)) + .font(LoopDesign.Typeface.body.monospacedDigit()) + .foregroundStyle(P.carbs) + } + } + .padding(.vertical, 10) + } + .padding(.horizontal, LoopDesign.Space.s4) + .background(P.surfaceRaised, in: RoundedRectangle(cornerRadius: 15, style: .continuous)) + } + + private func choose(_ speed: Speed) { + endEditing() + // Re-choosing the shown speed changes nothing, so an unedited entry stays unedited. + guard speed != selectedSpeed else { return } + // A favourite sets its own food and absorption; choosing a speed instead lets it go but keeps the amount. + if viewModel.selectedFavoriteFood != nil { + let quantity = viewModel.carbsQuantity + viewModel.selectedFavoriteFoodIndex = -1 + viewModel.carbsQuantity = quantity + } + otherChosen = speed == .other + if speed == .other { + viewModel.usesCustomFoodType = true + foodTypeFocused = true + } else { + viewModel.usesCustomFoodType = false + viewModel.foodType = "" + viewModel.selectedDefaultAbsorptionTimeEmoji = speed.emoji + viewModel.absorptionTime = hours(speed) + } + } + + // MARK: Pad and Continue + + /// Continue rides above the number pad while it's up. + private var entryBar: some View { + VStack(spacing: LoopDesign.Space.s3) { + Button(action: viewModel.continueToBolus) { + Text(hasAmount || !viewModel.continueButtonDisabled + ? NSLocalizedString("Continue", comment: "Button label for continue") + : NSLocalizedString("Enter an amount", comment: "Carb entry Continue button while no amount has been typed")) + .font(LoopDesign.Typeface.headline) + .foregroundStyle(viewModel.continueButtonDisabled ? P.inkMuted : P.onFill) + .frame(maxWidth: .infinity, minHeight: 52) + .background(viewModel.continueButtonDisabled ? P.surfaceSunken : P.carbs, + in: RoundedRectangle(cornerRadius: 16, style: .continuous)) + .contentShape(RoundedRectangle(cornerRadius: 16, style: .continuous)) + } + .buttonStyle(.plain) + .disabled(viewModel.continueButtonDisabled) + .accessibilityIdentifier("button_Continue") + } + .padding(.horizontal, LoopDesign.Space.s4) + .padding(.top, LoopDesign.Space.s3) + .padding(.bottom, LoopDesign.Space.s1) + .background { + P.surface + .overlay(alignment: .top) { Rectangle().fill(P.separator.opacity(0.35)).frame(height: 0.5) } + .ignoresSafeArea(edges: .bottom) + } + } + + // MARK: Pieces + + private func sectionTitle(_ title: String) -> some View { + Text(title) + .font(LoopDesign.Typeface.subhead.weight(.semibold)) + .foregroundStyle(P.inkMuted) + .accessibilityAddTraits(.isHeader) + } + + private func warningView(_ warning: CarbEntryViewModel.Warning) -> some View { + HStack(alignment: .top, spacing: LoopDesign.Space.s3) { + Image(systemName: "exclamationmark.triangle.fill") + .foregroundStyle(P.statusCritical) + .accessibilityHidden(true) + Text(warningText(warning)) + .font(LoopDesign.Typeface.subhead) + .foregroundStyle(P.ink) + .fixedSize(horizontal: false, vertical: true) + } + .padding(LoopDesign.Space.s3) + .frame(maxWidth: .infinity, alignment: .leading) + .background(P.statusCritical.opacity(0.16), in: RoundedRectangle(cornerRadius: LoopDesign.Radius.lg, style: .continuous)) + .overlay(RoundedRectangle(cornerRadius: LoopDesign.Radius.lg, style: .continuous).strokeBorder(P.statusCritical.opacity(0.45), lineWidth: 1)) + } + + private func warningText(_ warning: CarbEntryViewModel.Warning) -> String { + switch warning { + case .entryIsMissedMeal: + return NSLocalizedString("Loop has detected an missed meal and estimated its size. Edit the carb amount to match the amount of any carbs you may have eaten.", comment: "Warning displayed when user is adding a meal from an missed meal notification") + case .glucoseRisingRapidly: + return NSLocalizedString("Your glucose is rapidly rising. Check that any carbs you've eaten were logged. If you logged carbs, check that the time you entered lines up with when you started eating.", comment: "Warning to ensure the carb entry is accurate") + } + } + + private func alert(for alert: CarbEntryViewModel.Alert) -> SwiftUI.Alert { + switch alert { + case .maxQuantityExceded: + let message = String( + format: NSLocalizedString("The maximum allowed amount is %@ grams.", comment: "Alert body displayed for quantity greater than max (1: maximum quantity in grams)"), + NumberFormatter.localizedString(from: NSNumber(value: viewModel.maxCarbEntryQuantity.doubleValue(for: viewModel.preferredCarbUnit)), number: .none) + ) + let okMessage = NSLocalizedString("com.loudnate.LoopKit.errorAlertActionTitle", value: "OK", comment: "The title of the action used to dismiss an error alert") + return SwiftUI.Alert( + title: Text("Large Meal Entered", comment: "Title of the warning shown when a large meal was entered"), + message: Text(message), + dismissButton: .cancel(Text(okMessage), action: viewModel.clearAlert) + ) + case .warningQuantityValidation: + let message = String( + format: NSLocalizedString("Did you intend to enter %1$@ grams as the amount of carbohydrates for this meal?", comment: "Alert body when entered carbohydrates is greater than threshold (1: entered quantity in grams)"), + NumberFormatter.localizedString(from: NSNumber(value: viewModel.carbsQuantity ?? 0), number: .none) + ) + return SwiftUI.Alert( + title: Text("Large Meal Entered", comment: "Title of the warning shown when a large meal was entered"), + message: Text(message), + primaryButton: .default(Text("No, edit amount", comment: "The title of the action used when rejecting the the amount of carbohydrates entered."), action: viewModel.clearAlert), + secondaryButton: .cancel(Text("Yes", comment: "The title of the action used when confirming entered amount of carbohydrates."), action: viewModel.clearAlertAndContinueToBolus) + ) + } + } +} + +/// A row of choices sharing one track, with a thumb that slides to the chosen one. Two by two at accessibility text sizes. +private struct ChoiceTrack: View { + let choices: [Choice] + let selection: Choice? + let thumb: String + let namespace: Namespace.ID + let action: (Choice) -> Void + @ViewBuilder let label: (Choice, Bool) -> Label + + @Environment(\.dynamicTypeSize) private var typeSize + + var body: some View { + let columns = Array(repeating: GridItem(.flexible(), spacing: 4), count: typeSize.isAccessibilitySize ? 2 : choices.count) + LazyVGrid(columns: columns, spacing: 4) { + ForEach(choices, id: \.self) { choice in + let selected = choice == selection + Button { + action(choice) + } label: { + label(choice, selected) + .padding(.horizontal, 4) + .frame(maxWidth: .infinity, minHeight: 44) + .background { + if selected { + RoundedRectangle(cornerRadius: 11, style: .continuous) + .fill(P.carbs.opacity(0.18)) + .overlay(RoundedRectangle(cornerRadius: 11, style: .continuous).strokeBorder(P.carbs, lineWidth: 1.5)) + .matchedGeometryEffect(id: thumb, in: namespace) + } + } + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .accessibilityAddTraits(selected ? .isSelected : []) + } + } + .padding(4) + .background(P.surfaceRaised, in: RoundedRectangle(cornerRadius: 15, style: .continuous)) + } +} + +/// The meal's carbs absorbing over time, drawn the way the day page draws carbs on board: a soft fill under a line, +/// solid up to now and dashed after, over hour gridlines. Touch and hold to read how much is left at any time. +private struct MealAbsorptionChart: View { + let grams: Double + let absorptionTime: TimeInterval + let eaten: Date + let now: Date + /// The longest absorption on offer, so a faster food draws a visibly shorter curve. + let axisLength: TimeInterval + + @State private var selection: Date? + @Environment(\.accessibilityReduceMotion) private var reduceMotion + + private static let height: CGFloat = 88 + private static let nowLabelHeight: CGFloat = 20 + + private var absorbed: Date { eaten.addingTimeInterval(absorptionTime) } + + private var window: DateInterval { + let start = min(eaten, now) + return DateInterval(start: start, end: max(eaten.addingTimeInterval(axisLength), now.addingTimeInterval(15 * 60))) + } + + /// Loop's absorption rate as a share of its peak (PiecewiseLinearAbsorption in LoopAlgorithm): rising to the + /// peak at 15% of the absorption time, steady until half way, then falling to nothing. + private static func shape(_ t: Double) -> Double { + switch t { + case ..<0: return 0 + case ..<0.15: return t / 0.15 + case ..<0.5: return 1 + case ..<1: return (1 - t) / 0.5 + default: return 0 + } + } + + /// The share of the carbs absorbed by `t`: the area under `shape` so far, over its whole area of 0.675. + private static func absorbedShare(_ t: Double) -> Double { + let t = min(max(t, 0), 1) + let area: Double + if t < 0.15 { + area = t * t / 0.3 + } else if t < 0.5 { + area = 0.075 + (t - 0.15) + } else { + area = 0.425 + ((t - 0.5) - (t * t - 0.25) / 2) / 0.5 + } + return min(1, area / 0.675) + } + + /// The plotted height of the peak. Its area stands for the grams, so the peak is the rate, grams over + /// 0.675 × the absorption time; a square root keeps a small snack visible beside a large fast one. + private var peak: Double { + guard grams > 0, absorptionTime > 0 else { return 0.42 } + let gramsPerHour = grams / (0.675 * absorptionTime / 3600) + return min(1, max(0.14, (gramsPerHour / 150).squareRoot())) + } + + private struct Sample: Identifiable { + let date: Date + let value: Double + var id: Date { date } + } + + /// The curve's corners, plus the point where it crosses now, so the solid and dashed parts meet exactly. + private var samples: [Sample] { + var shares = [0, 0.15, 0.5, 1.0] + let nowShare = now.timeIntervalSince(eaten) / max(absorptionTime, 1) + if nowShare > 0 && nowShare < 1 { shares.append(nowShare) } + return shares.sorted().map { Sample(date: eaten.addingTimeInterval($0 * absorptionTime), value: Self.shape($0) * peak) } + } + + private var hourMarks: [Date] { + stride(from: 3600.0, to: window.duration, by: 3600).map { eaten.addingTimeInterval($0) }.filter { window.contains($0) } + } + + var body: some View { + let samples = samples + let past = samples.filter { $0.date <= now } + let future = samples.filter { $0.date >= now } + VStack(spacing: 6) { + Chart { + ForEach(samples) { sample in + AreaMark(x: .value("Time", sample.date), yStart: .value("Base", 0), yEnd: .value("Rate", sample.value), series: .value("Series", "fill")) + .foregroundStyle(P.carbs.opacity(grams > 0 ? 0.16 : 0)) + } + // Already absorbed: a firmer fill under the solid part. + ForEach(past) { sample in + AreaMark(x: .value("Time", sample.date), yStart: .value("Base", 0), yEnd: .value("Rate", sample.value), series: .value("Series", "past-fill")) + .foregroundStyle(P.carbs.opacity(grams > 0 ? 0.22 : 0)) + } + ForEach(past) { sample in + LineMark(x: .value("Time", sample.date), y: .value("Rate", sample.value), series: .value("Series", "past")) + .foregroundStyle(grams > 0 ? P.carbs : P.inkMuted.opacity(0.15)) + .lineStyle(StrokeStyle(lineWidth: 2, lineCap: .round, lineJoin: .round)) + } + ForEach(future) { sample in + LineMark(x: .value("Time", sample.date), y: .value("Rate", sample.value), series: .value("Series", "future")) + .foregroundStyle(grams > 0 ? P.carbs : P.inkMuted.opacity(0.15)) + .lineStyle(StrokeStyle(lineWidth: 2, lineCap: .round, lineJoin: .round, dash: [4, 3])) + } + RuleMark(y: .value("Zero", 0)) + .foregroundStyle(P.separator) + .lineStyle(StrokeStyle(lineWidth: 1)) + RuleMark(x: .value("Now", now)) + .foregroundStyle(P.inkMuted) + .lineStyle(StrokeStyle(lineWidth: 1, dash: [1, 3])) + if let selection { + RuleMark(x: .value("Selected", selection)).foregroundStyle(P.ink.opacity(0.6)) + } + } + .chartXScale(domain: window.start...window.end) + .chartYScale(domain: 0...1.0) + .chartXAxis { + AxisMarks(values: hourMarks) { _ in + AxisGridLine().foregroundStyle(P.grid) + } + } + .chartYAxis(.hidden) + .chartOverlay { proxy in + ZStack(alignment: .topLeading) { + ScrubOverlay(proxy: proxy, selection: $selection, clampTo: window) + if selection == nil, let nowX = proxy.position(forX: now) { + GeometryReader { geometry in + // Centred over the line, kept inside the chart. + Text(NSLocalizedString("Now", comment: "Carb entry time choice: eaten now")) + .font(LoopDesign.Typeface.caption) + .foregroundStyle(P.inkMuted) + .dynamicTypeSize(...DynamicTypeSize.xxxLarge) + .fixedSize() + .frame(width: 48) + .position(x: min(max(nowX, 24), geometry.size.width - 24), y: -Self.nowLabelHeight / 2) + .allowsHitTesting(false) + } + } + } + } + .overlay(alignment: .top) { + if let selection { + ScrubCallout(rows: scrubRows(at: selection)) + .offset(y: -Self.nowLabelHeight) + .allowsHitTesting(false) + } + } + .frame(height: Self.height) + .overlay(alignment: .top) { + if grams <= 0 { + Text(NSLocalizedString("Type an amount to see when it'll be absorbed", comment: "Carb entry preview before an amount is typed")) + .font(LoopDesign.Typeface.subhead.weight(.medium)) + .foregroundStyle(P.inkMuted) + .multilineTextAlignment(.center) + .padding(.horizontal, LoopDesign.Space.s6) + .padding(.top, LoopDesign.Space.s1) + .allowsHitTesting(false) + } + } + .padding(.top, Self.nowLabelHeight) + .animation(reduceMotion ? nil : .snappy(duration: 0.35), value: grams) + .animation(reduceMotion ? nil : .snappy(duration: 0.35), value: absorptionTime) + .animation(reduceMotion ? nil : .snappy(duration: 0.35), value: eaten) + + AxisLabels(start: eaten.timeIntervalSince(window.start) / window.duration, end: absorbed.timeIntervalSince(window.start) / window.duration) { + Text(LoopFormat.time(eaten)) + .foregroundStyle(P.ink) + Text(String(format: NSLocalizedString("Absorbed by %1$@", comment: "Under the end of the carb absorption curve: when the carbs will have absorbed (1: time)"), LoopFormat.time(absorbed))) + .foregroundStyle(P.inkMuted) + } + .font(LoopDesign.Typeface.footnote.monospacedDigit()) + } + .accessibilityElement(children: .ignore) + .accessibilityLabel(String(format: NSLocalizedString("Eaten at %1$@, absorbed by %2$@", comment: "Accessibility summary of the carb entry preview chart (1: time eaten, 2: time absorbed)"), LoopFormat.time(eaten), LoopFormat.time(absorbed))) + } + + private func scrubRows(at date: Date) -> [ScrubCallout.Row] { + var rows: [ScrubCallout.Row] = [.init(label: nil, value: LoopFormat.time(date), color: P.ink)] + if grams > 0 { + let left = grams * (1 - Self.absorbedShare(date.timeIntervalSince(eaten) / max(absorptionTime, 1))) + rows.append(.init(label: NSLocalizedString("COB", comment: "Abbreviation for carbs on board (active carbohydrate)"), value: LoopFormat.grams(left), color: P.carbs)) + } + return rows + } +} + +/// Two labels on a time axis: the first starts at `start`, the second ends at `end`, pushed apart when they'd meet. +/// When they can't share a line, as at large text sizes, the second goes under the first. +private struct AxisLabels: Layout { + var start: Double + var end: Double + + private static let gap: CGFloat = 12 + + private func stacked(_ width: CGFloat, _ subviews: Subviews) -> Bool { + subviews.map { $0.sizeThatFits(.unspecified).width }.reduce(Self.gap, +) > width + } + + func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize { + let width = proposal.width ?? 0 + guard stacked(width, subviews) else { + return CGSize(width: width, height: subviews.map { $0.sizeThatFits(.unspecified).height }.max() ?? 0) + } + // Stacked labels wrap to the width rather than run off it. + let height = subviews.map { $0.sizeThatFits(ProposedViewSize(width: width, height: nil)).height }.reduce(0, +) + return CGSize(width: width, height: height) + } + + func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) { + guard subviews.count == 2 else { return } + if stacked(bounds.width, subviews) { + let wrapped = ProposedViewSize(width: bounds.width, height: nil) + let firstHeight = subviews[0].sizeThatFits(wrapped).height + subviews[0].place(at: CGPoint(x: bounds.minX, y: bounds.minY), proposal: wrapped) + subviews[1].place(at: CGPoint(x: bounds.minX, y: bounds.minY + firstHeight), proposal: wrapped) + return + } + let first = subviews[0].sizeThatFits(.unspecified) + let second = subviews[1].sizeThatFits(.unspecified) + let firstX = min(max(bounds.minX, bounds.minX + bounds.width * start), bounds.maxX - first.width) + let secondX = min(max(bounds.minX + bounds.width * end - second.width, firstX + first.width + Self.gap), bounds.maxX - second.width) + subviews[0].place(at: CGPoint(x: firstX, y: bounds.minY), proposal: ProposedViewSize(first)) + subviews[1].place(at: CGPoint(x: secondX, y: bounds.minY), proposal: ProposedViewSize(second)) + } +} diff --git a/Loop/Redesign/DayCharts.swift b/Loop/Redesign/DayCharts.swift new file mode 100644 index 0000000000..bd8a6f3d21 --- /dev/null +++ b/Loop/Redesign/DayCharts.swift @@ -0,0 +1,558 @@ +// +// DayCharts.swift +// Loop +// +// Copyright © 2026 LoopKit Authors. All rights reserved. +// + +import SwiftUI +import Charts +import UIKit + +private typealias P = LoopDesign.Palette + +// MARK: - Shared axis helpers + +enum DayAxis { + /// Midnight, 6 AM, noon and 6 PM inside `window`, by the clock, so a day when the clocks change still marks 6 AM. + static func quarterDayMarks(in window: DateInterval, calendar: Calendar = .current) -> [Date] { + var marks: [Date] = [] + var day = calendar.startOfDay(for: window.start) + while day <= window.end { + for hour in [0, 6, 12, 18] { + if let mark = calendar.date(bySettingHour: hour, minute: 0, second: 0, of: day), window.contains(mark) { + marks.append(mark) + } + } + guard let next = calendar.date(byAdding: .day, value: 1, to: day) else { break } + day = next + } + return marks + } + + static func hourLabel(_ date: Date) -> String { + date.formatted(.dateTime.hour()) + } + + /// Gaps of more than 30 minutes between readings, so a chart can say where data is missing. + static func gaps(in points: [GlucosePoint], window: DateInterval, until end: Date) -> [DateInterval] { + let limit: TimeInterval = 30 * 60 + var gaps: [DateInterval] = [] + var previous = window.start + for point in points.sorted(by: { $0.date < $1.date }) where window.contains(point.date) { + if point.date.timeIntervalSince(previous) > limit { + gaps.append(DateInterval(start: previous, end: point.date)) + } + previous = point.date + } + let last = min(end, window.end) + if last.timeIntervalSince(previous) > limit { + gaps.append(DateInterval(start: previous, end: last)) + } + return gaps + } + + static func gapMessage(_ gaps: [DateInterval], window: DateInterval, until end: Date) -> String? { + guard let longest = gaps.max(by: { $0.duration < $1.duration }) else { return nil } + // A gap over the whole period would read "0:00 – 0:00". + if gaps.count == 1, longest.start == window.start, longest.end == min(end, window.end) { + return window.contains(end) + ? NSLocalizedString("No CGM data yet today", comment: "Chart note: there are no glucose readings so far today") + : NSLocalizedString("No CGM data on this day", comment: "Chart note: there are no glucose readings for the whole day") + } + let start = LoopFormat.time(longest.start) + let end = LoopFormat.time(longest.end) + if gaps.count > 1 { + let others = String.localizedStringWithFormat(NSLocalizedString("%lld shorter gaps", comment: "Chart note: how many other, shorter gaps in glucose readings there were; follows the longest gap. (1: number of gaps)"), gaps.count - 1) + return String(format: NSLocalizedString("No CGM data %1$@ – %2$@ and %3$@", comment: "Chart note: the longest gap in glucose readings, plus the shorter ones. (1: start time; 2: end time; 3: number of shorter gaps, e.g. 2 shorter gaps)"), start, end, others) + } + return String(format: NSLocalizedString("No CGM data %1$@ – %2$@", comment: "Chart note: a gap in glucose readings. (1: start time; 2: end time)"), start, end) + } +} + +// MARK: - DayTimelineCard + +/// A day on one timeline, for a one-day period on Trends. +struct DayTimelineCard: View { + let title: String + let history: DayHistory + let unit: GlucoseUnitStyle + let targetBands: [TargetBand] + var now: Date = Date() + var height: CGFloat = 230 + + static var todayTitle: String { + NSLocalizedString("Today so far", comment: "Title of the card on the Now screen showing today's insulin and carbs") + } + + static let legend: [LegendItem] = [ + LegendItem(swatch: .solid(P.bolus), label: NSLocalizedString("Bolus", comment: "Chart legend: solid bars are manual boluses")), + LegendItem(swatch: .hatch(P.bolus), label: NSLocalizedString("Automatic", comment: "Chart legend: hatched bars are automatic boluses given by Loop")), + LegendItem(swatch: .solid(P.basalArea), label: NSLocalizedString("Basal given", comment: "Chart legend: filled area is basal insulin actually delivered")), + LegendItem(swatch: .dash(P.basalScheduled), label: NSLocalizedString("Scheduled", comment: "Chart legend: dashed line is the scheduled basal rate")), + ] + + var body: some View { + LoopCard { + CardHeader(title: title) { + Text(verbatim: "\(LoopFormat.totalUnits(history.totalUnits)) · \(LoopFormat.grams(history.carbGrams))") + } + InsulinTimelineView(history: history, unit: unit, targetBands: targetBands, now: now, height: height) + ChartLegend(items: Self.legend) + } + } +} + +// MARK: - InsulinTimeline + +/// Carbs, glucose and insulin for one day on one shared time axis. +/// +/// The lanes are drawn in a single chart with stacked y ranges so they can't drift apart: insulin 0–30, +/// glucose 36–92 (the fixed 2–20 mmol/L scale), carb markers at 97. +struct InsulinTimelineView: View { + let history: DayHistory + let unit: GlucoseUnitStyle + let targetBands: [TargetBand] + var now: Date = Date() + var height: CGFloat = 260 + + @State private var selection: Date? + @Environment(\.colorScheme) private var colorScheme + @Environment(\.dynamicTypeSize) private var typeSize + + private static let insulinTop = 30.0 + private static let basalTop = 12.0 + private static let glucoseRange = 36.0...92.0 + private static let carbLane = 97.0 + + private var window: DateInterval { history.window } + + private func y(glucose mgdl: Double) -> Double { + let domain = unit.dayDomain + let value = min(max(unit.value(mgdl), domain.lowerBound), domain.upperBound) + let fraction = (value - domain.lowerBound) / (domain.upperBound - domain.lowerBound) + return Self.glucoseRange.lowerBound + fraction * (Self.glucoseRange.upperBound - Self.glucoseRange.lowerBound) + } + + private var maxBasal: Double { + max(0.5, (history.basal.map(\.rate) + history.scheduledBasal.map(\.rate)).max() ?? 0) + } + + private var maxBolus: Double { + max(1, history.boluses.map(\.units).max() ?? 0) + } + + private func y(basal rate: Double) -> Double { rate / maxBasal * Self.basalTop } + private func y(bolus units: Double) -> Double { max(1.5, units / maxBolus * (Self.insulinTop - 4)) } + + private var gaps: [DateInterval] { DayAxis.gaps(in: history.glucose, window: window, until: now) } + + /// Labels closer than this to the previous label are dropped so they don't overprint; the marks still draw. + private var labelSpacing: TimeInterval { window.duration / 7 } + + private func spacedIDs(_ items: [T], date: (T) -> Date, id: (T) -> String) -> Set { + var kept = Set() + var last: Date? + for item in items.sorted(by: { date($0) < date($1) }) { + if let last, date(item).timeIntervalSince(last) < labelSpacing { continue } + kept.insert(id(item)) + last = date(item) + } + return kept + } + + /// One label per run of carb entries closer together than `labelSpacing`, giving the run's total. + /// It sits after the run's last marker, so no later marker in the run draws over it. + private var carbLabels: [String: Double] { + var labels: [String: Double] = [:] + var runStart: Date? + var runLast: (id: String, total: Double)? + for carb in history.carbs.sorted(by: { $0.date < $1.date }) { + if let start = runStart, let last = runLast, carb.date.timeIntervalSince(start) < labelSpacing { + runLast = (carb.id, last.total + carb.grams) + } else { + if let last = runLast { labels[last.id] = last.total } + runStart = carb.date + runLast = (carb.id, carb.grams) + } + } + if let last = runLast { labels[last.id] = last.total } + return labels + } + private var labelledBoluses: Set { spacedIDs(history.boluses.filter { !$0.automatic }, date: \.date, id: \.id) } + + var body: some View { + VStack(alignment: .leading, spacing: LoopDesign.Space.s2) { + chart + .frame(height: height) + if let message = DayAxis.gapMessage(gaps, window: window, until: now), history.source == .loop || !history.glucose.isEmpty { + Text(message) + .font(LoopDesign.Typeface.footnote) + .foregroundStyle(LoopDesign.Palette.inkMuted) + } + } + } + + private var chart: some View { + Chart { + // Quarter-day rules + ForEach(DayAxis.quarterDayMarks(in: window), id: \.self) { mark in + RuleMark(x: .value("Time", mark)) + .foregroundStyle(P.grid) + .lineStyle(StrokeStyle(lineWidth: 1)) + } + + // Glucose lane + ForEach(Array(targetBands.enumerated()), id: \.offset) { _, band in + RectangleMark(xStart: .value("Start", band.start), xEnd: .value("End", band.end), + yStart: .value("Low", y(glucose: band.range.lowerBound)), yEnd: .value("High", y(glucose: band.range.upperBound))) + .foregroundStyle(P.targetBand) + } + ForEach(Array(history.glucose.enumerated()), id: \.offset) { _, point in + PointMark(x: .value("Time", point.date), y: .value("Glucose", y(glucose: point.mgdl))) + .symbolSize(10) + .foregroundStyle(P.glucose) + } + + // Carb markers + let carbLabels = carbLabels + ForEach(history.carbs) { carb in + PointMark(x: .value("Time", carb.date), y: .value("Carbs", Self.carbLane)) + .symbolSize(60) + .foregroundStyle(P.carbs) + .annotation(position: .trailing, spacing: 2) { + if let grams = carbLabels[carb.id] { + Text(LoopFormat.grams(grams)) + .font(LoopDesign.Typeface.caption) + .foregroundStyle(P.ink) + } + } + } + + // Delivered basal, then the schedule dashed over it + // Draw each recorded segment independently; a gap must not become an interpolated delivery area. + ForEach(Array(history.basal.enumerated()), id: \.offset) { _, segment in + RectangleMark(xStart: .value("Start", segment.start), xEnd: .value("End", segment.end), + yStart: .value("Base", 0), yEnd: .value("Basal", y(basal: segment.rate))) + .foregroundStyle(P.basalArea) + } + ForEach(Array(history.scheduledBasal.enumerated()), id: \.offset) { _, value in + RuleMark(xStart: .value("Start", value.start), xEnd: .value("End", value.end), y: .value("Scheduled", y(basal: value.rate))) + .foregroundStyle(P.basalScheduled) + .lineStyle(StrokeStyle(lineWidth: 1, dash: [3, 3])) + } + + // Boluses over basal: solid for manual with a label, hatched for automatic. + // Each sits in a card-coloured slot a point wider, so it never touches the basal behind it. + ForEach(history.boluses) { bolus in + RectangleMark(x: .value("Time", bolus.date), yStart: .value("Base", 0), yEnd: .value("Bolus", y(bolus: bolus.units)), width: .fixed(7)) + .foregroundStyle(P.surfaceRaised) + } + let bolusLabels = labelledBoluses + ForEach(history.boluses) { bolus in + if bolus.automatic { + RectangleMark(x: .value("Time", bolus.date), yStart: .value("Base", 0), yEnd: .value("Bolus", y(bolus: bolus.units)), width: .fixed(5)) + .foregroundStyle(Hatch.paint(P.bolus, scheme: colorScheme)) + } else { + RectangleMark(x: .value("Time", bolus.date), yStart: .value("Base", 0), yEnd: .value("Bolus", y(bolus: bolus.units)), width: .fixed(5)) + .foregroundStyle(P.bolus) + .annotation(position: .top, spacing: 2) { + if bolusLabels.contains(bolus.id) { + Text(LoopFormat.number(bolus.units, decimals: 1)) + .font(LoopDesign.Typeface.caption) + .foregroundStyle(P.ink) + } + } + } + } + + // Now + if window.contains(now) { + RuleMark(x: .value("Now", now)) + .foregroundStyle(P.inkMuted) + .lineStyle(StrokeStyle(lineWidth: 1, dash: [2, 3])) + } + + if let selection { + RuleMark(x: .value("Selected", selection)) + .foregroundStyle(P.ink.opacity(0.6)) + .lineStyle(StrokeStyle(lineWidth: 1)) + } + } + .chartXScale(domain: window.start...window.end) + .chartYScale(domain: 0...104) + .chartXAxis { + AxisMarks(values: DayAxis.quarterDayMarks(in: window).filter { + !typeSize.isAccessibilitySize || Calendar.current.component(.hour, from: $0).isMultiple(of: 12) + }) { value in + AxisValueLabel { + if let date = value.as(Date.self) { + Text(DayAxis.hourLabel(date)) + } + } + .font(LoopDesign.Typeface.caption) + .foregroundStyle(P.inkMuted) + } + } + .chartYAxis { + AxisMarks(position: .leading, values: unit.dayTicks.map { y(glucose: unit.mgdl($0)) }) { value in + AxisGridLine().foregroundStyle(P.grid) + AxisValueLabel { + if let mapped = value.as(Double.self), let tick = unit.dayTicks.first(where: { abs(y(glucose: unit.mgdl($0)) - mapped) < 0.01 }) { + Text(tick.formatted()) + } + } + .font(LoopDesign.Typeface.caption) + .foregroundStyle(P.inkMuted) + } + } + .chartOverlay { proxy in + ScrubOverlay(proxy: proxy, selection: $selection, clampTo: window) + } + .overlay(alignment: .top) { + if let selection { + ScrubCallout(rows: scrubRows(at: selection)) + .padding(.top, 2) + .allowsHitTesting(false) + } + } + .accessibilityElement(children: .ignore) + .accessibilityLabel(accessibilitySummary) + } + + private func scrubRows(at date: Date) -> [ScrubCallout.Row] { + var rows: [ScrubCallout.Row] = [.init(label: nil, value: LoopFormat.time(date), color: P.ink)] + if let glucose = nearest(history.glucose.map { ($0.date, $0.mgdl) }, to: date, within: 10 * 60) { + rows.append(.init(label: NSLocalizedString("Glucose", comment: "Chart callout label for the glucose reading at the touched time"), value: "\(unit.format(glucose)) \(unit.unitName)", color: P.ink)) + } + if let segment = LoopHistoryMath.basalRate(at: date, in: history.basal) { + let value = segment.kind == .suspended + ? NSLocalizedString("Suspended", comment: "Chart callout value: insulin delivery was suspended at the touched time") + : LoopFormat.rate(segment.rate) + rows.append(.init(label: NSLocalizedString("Basal", comment: "Chart callout label for the basal rate at the touched time"), value: value, color: P.ink)) + } + if let bolus = history.boluses.min(by: { abs($0.date.timeIntervalSince(date)) < abs($1.date.timeIntervalSince(date)) }), + abs(bolus.date.timeIntervalSince(date)) < 5 * 60 { + rows.append(.init(label: bolus.automatic + ? NSLocalizedString("Automatic bolus", comment: "Chart callout label for a bolus Loop delivered automatically near the touched time") + : NSLocalizedString("Bolus", comment: "Chart callout label for a bolus near the touched time"), + value: LoopFormat.doseUnits(bolus.units), color: P.ink)) + } + return rows + } + + private var accessibilitySummary: String { + let day = LoopFormat.weekdayDay(window.start) + let bolus = LoopFormat.totalUnits(history.bolusUnits) + let basal = LoopFormat.totalUnits(history.basalUnits) + let carbs = LoopFormat.grams(history.carbGrams) + if let last = history.glucose.last { + return String(format: NSLocalizedString("Insulin timeline, %1$@, bolus %2$@, basal %3$@, carbs %4$@, latest glucose %5$@ %6$@", comment: "VoiceOver summary of the day's insulin timeline chart. (1: weekday and date; 2: bolus total, e.g. 12.5 U; 3: basal total; 4: carbs total, e.g. 140 g; 5: latest glucose value; 6: glucose unit, mmol/L or mg/dL)"), day, bolus, basal, carbs, unit.format(last.mgdl), unit.unitName) + } + return String(format: NSLocalizedString("Insulin timeline, %1$@, bolus %2$@, basal %3$@, carbs %4$@", comment: "VoiceOver summary of the day's insulin timeline chart with no glucose readings. (1: weekday and date; 2: bolus total, e.g. 12.5 U; 3: basal total; 4: carbs total, e.g. 140 g)"), day, bolus, basal, carbs) + } +} + +func nearest(_ values: [(Date, Double)], to date: Date, within limit: TimeInterval) -> Double? { + guard let best = values.min(by: { abs($0.0.timeIntervalSince(date)) < abs($1.0.timeIntervalSince(date)) }), + abs(best.0.timeIntervalSince(date)) <= limit else { + return nil + } + return best.1 +} + +// MARK: - Scrubbing + +/// The last three hours of readings and Loop's dashed prediction for the next three. +struct PredictionChartView: View { + let readings: [GlucosePoint] + let prediction: [GlucosePoint] + let unit: GlucoseUnitStyle + let targetBands: [TargetBand] + var now: Date = Date() + var height: CGFloat = 150 + + @State private var selection: Date? + + private var window: DateInterval { + DateInterval(start: now.addingTimeInterval(-3 * 3600), end: now.addingTimeInterval(3 * 3600)) + } + + private func clamp(_ mgdl: Double) -> Double { + min(max(unit.value(mgdl), unit.dayDomain.lowerBound), unit.dayDomain.upperBound) + } + + private var futurePrediction: [GlucosePoint] { + prediction.filter { $0.date >= now.addingTimeInterval(-5 * 60) && $0.date <= window.end } + } + + var body: some View { + Chart { + ForEach(Array(targetBands.enumerated()), id: \.offset) { _, band in + RectangleMark(xStart: .value("Start", band.start), xEnd: .value("End", band.end), + yStart: .value("Low", clamp(band.range.lowerBound)), yEnd: .value("High", clamp(band.range.upperBound))) + .foregroundStyle(P.targetBand) + } + ForEach(Array(readings.filter { window.contains($0.date) }.enumerated()), id: \.offset) { _, point in + PointMark(x: .value("Time", point.date), y: .value("Glucose", clamp(point.mgdl))) + .symbolSize(12) + .foregroundStyle(P.glucose) + } + ForEach(Array(futurePrediction.enumerated()), id: \.offset) { index, point in + LineMark(x: .value("Time", point.date), y: .value("Predicted", clamp(point.mgdl)), series: .value("Series", "prediction")) + .foregroundStyle(P.glucose) + .lineStyle(StrokeStyle(lineWidth: 1.5, dash: [4, 3])) + .annotation(position: .topTrailing, spacing: 0) { + if index == futurePrediction.count - 1 { + Text(unit.format(point.mgdl)) + .font(LoopDesign.Typeface.caption.weight(.semibold)) + .foregroundStyle(P.ink) + } + } + } + RuleMark(x: .value("Now", now)) + .foregroundStyle(P.inkMuted) + .lineStyle(StrokeStyle(lineWidth: 1, dash: [2, 3])) + if let selection { + RuleMark(x: .value("Selected", selection)) + .foregroundStyle(P.ink.opacity(0.6)) + } + } + .frame(height: height) + .chartXScale(domain: window.start...window.end) + .chartYScale(domain: unit.dayDomain) + .chartXAxis { + AxisMarks(values: [window.start, now, window.end]) { value in + AxisGridLine().foregroundStyle(P.grid) + AxisValueLabel { + if let date = value.as(Date.self) { + Text(abs(date.timeIntervalSince(now)) < 60 ? NSLocalizedString("now", comment: "Prediction chart x-axis label marking the current time") : LoopFormat.time(date)) + } + } + .font(LoopDesign.Typeface.caption) + .foregroundStyle(P.inkMuted) + } + } + .chartYAxis { + AxisMarks(position: .leading, values: unit.dayTicks) { _ in + AxisGridLine().foregroundStyle(P.grid) + AxisValueLabel().font(LoopDesign.Typeface.caption).foregroundStyle(P.inkMuted) + } + } + .chartOverlay { proxy in + ScrubOverlay(proxy: proxy, selection: $selection, clampTo: window) + } + .overlay(alignment: .top) { + if let selection { + ScrubCallout(rows: scrubRows(at: selection)).allowsHitTesting(false) + } + } + .accessibilityElement(children: .ignore) + .accessibilityLabel(accessibilitySummary) + } + + private func scrubRows(at date: Date) -> [ScrubCallout.Row] { + var rows: [ScrubCallout.Row] = [.init(label: nil, value: LoopFormat.time(date), color: P.ink)] + let source = date <= now ? readings : prediction + if let value = nearest(source.map { ($0.date, $0.mgdl) }, to: date, within: 10 * 60) { + rows.append(.init(label: date <= now + ? NSLocalizedString("Glucose", comment: "Chart callout label for the glucose reading at the touched time") + : NSLocalizedString("Predicted", comment: "Prediction chart callout label for Loop's predicted glucose at the touched time"), + value: "\(unit.format(value)) \(unit.unitName)", color: P.ink)) + } + return rows + } + + private var accessibilitySummary: String { + guard let last = futurePrediction.last else { + return NSLocalizedString("Glucose prediction unavailable", comment: "VoiceOver label for the prediction chart when Loop has no prediction") + } + return String(format: NSLocalizedString("Loop predicts %1$@ %2$@ by %3$@", comment: "VoiceOver summary of the prediction chart. (1: predicted glucose value; 2: glucose unit, mmol/L or mg/dL; 3: time of the prediction)"), unit.format(last.mgdl), unit.unitName, LoopFormat.time(last.date)) + } +} + +/// Touch and hold then drag to scrub; a plain swipe still scrolls the page. +/// +/// A UIKit long-press recogniser is used because a SwiftUI long-press-then-drag gesture inside a table cell +/// takes every drag that starts on the chart, so the page couldn't scroll past it. +struct ScrubOverlay: View { + let proxy: ChartProxy + @Binding var selection: Date? + let clampTo: DateInterval + + var body: some View { + GeometryReader { geometry in + if #available(iOS 18.0, *) { + Color.clear + .contentShape(Rectangle()) + .gesture(ScrubPressRecognizer { location in + update(location, in: geometry) + } onEnd: { + selection = nil + }) + } else { + Color.clear + } + } + } + + private func update(_ location: CGPoint, in geometry: GeometryProxy) { + guard let frame = proxy.plotFrame else { return } + let origin = geometry[frame].origin + if let date: Date = proxy.value(atX: location.x - origin.x) { + selection = min(max(date, clampTo.start), clampTo.end) + } + } +} + +@available(iOS 18.0, *) +private struct ScrubPressRecognizer: UIGestureRecognizerRepresentable { + let onChange: (CGPoint) -> Void + let onEnd: () -> Void + + func makeUIGestureRecognizer(context: Context) -> UILongPressGestureRecognizer { + let recognizer = UILongPressGestureRecognizer() + recognizer.minimumPressDuration = 0.3 + recognizer.allowableMovement = 12 + return recognizer + } + + func handleUIGestureRecognizerAction(_ recognizer: UILongPressGestureRecognizer, context: Context) { + switch recognizer.state { + case .began, .changed: + onChange(context.converter.localLocation) + case .ended, .cancelled, .failed: + onEnd() + default: + break + } + } +} + +struct ScrubCallout: View { + struct Row: Hashable { + let label: String? + let value: String + let color: Color + } + + let rows: [Row] + + var body: some View { + VStack(alignment: .leading, spacing: 2) { + ForEach(rows, id: \.self) { row in + HStack(spacing: LoopDesign.Space.s1) { + if let label = row.label { + Text(label).foregroundStyle(P.inkMuted) + } + Text(row.value).foregroundStyle(row.color).fontWeight(.semibold) + } + } + } + .font(LoopDesign.Typeface.footnote.monospacedDigit()) + .padding(.horizontal, LoopDesign.Space.s2) + .padding(.vertical, LoopDesign.Space.s1) + .background(P.surfaceRaised, in: RoundedRectangle(cornerRadius: LoopDesign.Radius.sm)) + .overlay(RoundedRectangle(cornerRadius: LoopDesign.Radius.sm).strokeBorder(P.separator)) + } +} diff --git a/Loop/Redesign/DayDetailView.swift b/Loop/Redesign/DayDetailView.swift new file mode 100644 index 0000000000..9a4533af52 --- /dev/null +++ b/Loop/Redesign/DayDetailView.swift @@ -0,0 +1,116 @@ +// +// DayDetailView.swift +// Loop +// +// Copyright © 2026 LoopKit Authors. All rights reserved. +// + +import SwiftUI + +private typealias P = LoopDesign.Palette + +/// One full day on the insulin timeline with its basal and bolus split, stepping a day at a time. +struct DayDetailView: View { + let provider: LoopHistoryProvider + + @State private var day: Date + @State private var history: DayHistory? + @State private var targetBands: [TargetBand] = [] + @State private var now = Date() + @State private var loadError: String? + + init(provider: LoopHistoryProvider, day: Date) { + self.provider = provider + _day = State(initialValue: Calendar.current.startOfDay(for: day)) + } + + private var window: DateInterval { + DateInterval(start: day, end: Calendar.current.date(byAdding: .day, value: 1, to: day)!) + } + + private var isToday: Bool { Calendar.current.isDate(day, inSameDayAs: now) } + + var body: some View { + ScrollView { + VStack(alignment: .leading, spacing: LoopDesign.Space.s6) { + dayStepper + if let history { + LoopCard { + CardHeader(title: NSLocalizedString("Insulin", comment: "Title of the day page card showing insulin, carbs and glucose on one timeline")) { + HStack(spacing: 4) { + Text(LoopFormat.totalUnits(history.totalUnits)).foregroundStyle(P.insulin) + Text("·") + Text(LoopFormat.grams(history.carbGrams)).foregroundStyle(P.carbs) + } + } + InsulinTimelineView(history: history, unit: provider.unitStyle, targetBands: targetBands, + now: now, height: 300) + ChartLegend(items: DayTimelineCard.legend) + if history.source == .health { + Text(NSLocalizedString("From Apple Health: Loop keeps 7 days, so this day has no temp basal or schedule detail.", comment: "Day page note when the day is older than Loop's 7-day history and was read from Apple Health")) + .font(LoopDesign.Typeface.footnote) + .foregroundStyle(P.inkMuted) + } + if #available(iOS 18.0, *) { + Text(NSLocalizedString("Touch and hold a chart to see exact values.", comment: "Hint under the day page charts explaining how to scrub them")) + .font(LoopDesign.Typeface.footnote) + .foregroundStyle(P.inkMuted) + } + } + LoopCard { + CardHeader(title: NSLocalizedString("Basal and bolus", comment: "Trends card title: insulin split into basal and bolus")) + InsulinSplitView(split: history.insulinSplit, partial: isToday) + ValueTile(label: NSLocalizedString("Carbs", comment: "Label of a tile showing the day's total carbohydrate")) { + Text(LoopFormat.grams(history.carbGrams)) + .font(LoopDesign.Typeface.statValueSmall) + .foregroundStyle(P.carbs) + } + .fixedSize(horizontal: false, vertical: true) + } + } else if let loadError { + ChartPlaceholder(message: String(format: NSLocalizedString("Couldn't load this day: %1$@", comment: "Day page error when the day's history can't be read. (1: system error description)"), loadError)) + } else { + ProgressView() + .frame(maxWidth: .infinity, minHeight: 300) + } + } + .padding(LoopDesign.Space.s4) + } + .background(P.surface) + .navigationTitle(isToday ? NSLocalizedString("Today", comment: "Day page title when showing today") : LoopFormat.weekdayDay(day)) + .navigationBarTitleDisplayMode(.inline) + .task(id: day) { + now = Date() + let requestedWindow = window + history = nil + loadError = nil + do { + async let historyFetch = provider.dayHistory(requestedWindow) + async let targetsFetch = provider.glucoseTargetBands(in: requestedWindow) + let (result, targets) = try await (historyFetch, targetsFetch) + guard !Task.isCancelled, window == requestedWindow else { return } + history = result + targetBands = targets + } catch { + guard !Task.isCancelled, window == requestedWindow else { return } + loadError = error.localizedDescription + } + } + } + + private var dayStepper: some View { + HStack { + StepButton(systemName: "chevron.left", label: NSLocalizedString("Previous day", comment: "Accessibility label for the day page button that steps back a day")) { + day = Calendar.current.date(byAdding: .day, value: -1, to: day)! + } + Spacer() + Text(LoopFormat.day(day)) + .font(LoopDesign.Typeface.headline) + .foregroundStyle(P.ink) + Spacer() + StepButton(systemName: "chevron.right", label: NSLocalizedString("Next day", comment: "Accessibility label for the day page button that steps forward a day"), enabled: !isToday) { + day = Calendar.current.date(byAdding: .day, value: 1, to: day)! + } + } + } +} diff --git a/Loop/Redesign/LogbookScreen.swift b/Loop/Redesign/LogbookScreen.swift new file mode 100644 index 0000000000..dba132ee12 --- /dev/null +++ b/Loop/Redesign/LogbookScreen.swift @@ -0,0 +1,640 @@ +// +// LogbookScreen.swift +// Loop +// +// Copyright © 2026 LoopKit Authors. All rights reserved. +// + +import SwiftUI +import LoopKit +import LoopKitUI + +private typealias P = LoopDesign.Palette + +/// One row of the logbook. +struct LogEntry: Identifiable { + enum Filter: String, CaseIterable, Identifiable { + case all = "All" + case bolus = "Bolus" + case basal = "Basal" + case carbs = "Carbs" + case loop = "Loop" + var id: String { rawValue } + + var title: String { + switch self { + case .all: return NSLocalizedString("All", comment: "Logbook filter chip: show every entry") + case .bolus: return NSLocalizedString("Bolus", comment: "Logbook filter chip: show only boluses") + case .basal: return NSLocalizedString("Basal", comment: "Logbook filter chip: show only basal changes") + case .carbs: return NSLocalizedString("Carbs", comment: "Logbook filter chip: show only carb entries") + case .loop: return NSLocalizedString("Loop", comment: "Logbook filter chip: show only what Loop did automatically (Loop is the app's name)") + } + } + } + + enum Action { + case deleteCarbs(StoredCarbEntry) + case deleteDose(DoseEntry) + } + + let id: String + let date: Date + let title: String + let subtitle: String + let amount: String + let amountColor: Color + let detail: String + let icon: String + let iconStyle: IconTile.Style + let filters: Set + /// Loop's own small, frequent doses: the amount is set lighter so the person's own entries stand out. + var quiet = false + var basalChanges: [BasalSegment] = [] + var edit: StoredCarbEntry? = nil + var delete: Action? = nil + /// Units of a single automatic bolus, so runs of them can be folded into one row. + var automaticUnits: Double? = nil + /// The automatic boluses a folded row stands for, newest first. + var bolusRun: [LogEntry] = [] + + func matches(_ filter: Filter) -> Bool { + filter == .all || filters.contains(filter) + } +} + +struct LogDay: Identifiable { + let day: Date + let entries: [LogEntry] + let insulin: InsulinSplit + let carbs: Double + var id: Date { day } +} + +@MainActor +final class LogbookModel: ObservableObject { + @Published private(set) var days: [LogDay] = [] + @Published private(set) var loaded = false + @Published var filter: LogEntry.Filter = .all + @Published var error: String? + @Published private(set) var loadError: String? + @Published private(set) var carbEditingAllowed = false + + let provider: LoopHistoryProvider + private var loadTask: Task? + + init(provider: LoopHistoryProvider) { + self.provider = provider + } + + func reload() { + loadTask?.cancel() + carbEditingAllowed = provider.allowsCarbEditing + loadError = nil + loadTask = Task { + do { + let result = try await Self.build(provider: provider) + guard !Task.isCancelled else { return } + self.days = result + } catch { + guard !Task.isCancelled else { return } + self.days = [] + self.loadError = error.localizedDescription + } + self.loaded = true + } + } + + func perform(_ action: LogEntry.Action) { + Task { + do { + switch action { + case .deleteCarbs(let entry): + guard provider.allowsCarbEditing else { return } + try await provider.delete(carb: entry) + case .deleteDose(let dose): try await provider.delete(dose: dose) + } + reload() + } catch { + self.error = error.localizedDescription + } + } + } + + // MARK: Building rows + + private static func build(provider: LoopHistoryProvider, now: Date = Date()) async throws -> [LogDay] { + let calendar = Calendar.current + let start = calendar.startOfDay(for: provider.localHistoryStart.addingTimeInterval(86400)) + let interval = DateInterval(start: start, end: now) + async let historyFetch = provider.dayHistory(interval) + async let pumpFetch = provider.pumpEvents(since: start) + let history = try await historyFetch + let pumpEvents = try await pumpFetch + let unit = provider.unitStyle + let canDelete = FeatureFlags.entryDeletionEnabled + + return LoopHistoryMath.days(in: interval).reversed().map { day in + var entries: [LogEntry] = [] + let inDay: (Date) -> Bool = { $0 >= day.start && $0 < day.end } + let carbsToday = history.carbs.filter { inDay($0.date) } + + for bolus in history.boluses where inDay(bolus.date) { + let glucose = glucoseContext(at: bolus.date, history.glucose, unit: unit, withTrend: bolus.automatic) + var parts = [bolus.automatic ? sourceLoop : sourceManual] + if !bolus.automatic, let meal = carbsToday.first(where: { abs($0.date.timeIntervalSince(bolus.date)) <= 15 * 60 }) { + parts.append(LoopFormat.grams(meal.grams)) + } + if let glucose { parts.append(glucose) } + if bolus.manuallyEntered { parts.append(NSLocalizedString("logged", comment: "Logbook bolus row detail: the dose was logged by hand rather than delivered by the pump")) } + entries.append(LogEntry( + id: "bolus-\(bolus.id)", date: bolus.date, + title: bolus.automatic + ? NSLocalizedString("Automatic bolus", comment: "Logbook row title: a bolus Loop delivered automatically") + : NSLocalizedString("Bolus", comment: "Logbook row title: a bolus"), + subtitle: joined(parts), + amount: LoopFormat.doseUnits(bolus.units), amountColor: P.ink, + detail: LoopFormat.time(bolus.date), + icon: bolus.automatic ? "arrow.triangle.2.circlepath" : "syringe.fill", + iconStyle: bolus.automatic ? .hatch(P.bolus) : .solid(P.bolus), + filters: bolus.automatic ? [.bolus, .loop] : [.bolus], + quiet: bolus.automatic, + delete: canDelete && bolus.manuallyEntered ? bolus.dose.map { .deleteDose($0) } : nil, + automaticUnits: bolus.automatic && !bolus.manuallyEntered ? bolus.units : nil)) + } + + for carb in carbsToday { + var parts = [carb.createdByLoop ? sourceManual : NSLocalizedString("Health", comment: "Logbook carb row detail: the entry came from Apple Health")] + if let food = carb.foodType, !food.isEmpty { parts.append(food) } + if let hours = carb.absorptionHours { parts.append(String(format: NSLocalizedString("absorbs over %1$@ h", comment: "Logbook carb row detail: carb absorption time in hours. (1: hours, e.g. 3 or 2.5)"), hours.formatted(.number.precision(.fractionLength(0...1))))) } + let editable = carb.createdByLoop && provider.allowsCarbEditing ? carb.entry : nil + entries.append(LogEntry( + id: "carbs-\(carb.id)", date: carb.date, + title: NSLocalizedString("Carbs", comment: "Logbook row title: a carb entry"), subtitle: joined(parts), + amount: LoopFormat.grams(carb.grams), amountColor: P.ink, + detail: LoopFormat.time(carb.date), + icon: "fork.knife", iconStyle: .solid(P.carbs), filters: [.carbs], + edit: editable, + delete: canDelete ? editable.map { .deleteCarbs($0) } : nil)) + } + + let segments = history.basal.compactMap { $0.clamped(to: day) } + let automaticTemps = segments.filter { $0.kind == .temp && $0.automatic } + if let latest = automaticTemps.last { + let net = automaticTemps.reduce(0) { $0 + $1.netUnits } + let count = automaticTemps.count + entries.append(LogEntry( + id: "basal-\(day.start.timeIntervalSince1970)", date: latest.start, + title: NSLocalizedString("Basal adjustments", comment: "Logbook row title summarising the temp basals Loop set in a day"), + subtitle: String.localizedStringWithFormat(NSLocalizedString("Loop · %lld changes · tap to list", comment: "Logbook basal adjustments row subtitle: how many temp basals Loop set in the day; tapping lists them. (1: number of changes)"), count), + amount: String(format: NSLocalizedString("%1$@ U", comment: "Format string for an amount of insulin in units. (1: amount)"), LoopFormat.signed(net, decimals: 1)), amountColor: P.ink, + detail: NSLocalizedString("vs plan", comment: "Logbook basal adjustments row: the insulin amount is the difference from the scheduled basal"), + icon: "waveform.path.ecg", iconStyle: .basal, filters: [.basal, .loop], + basalChanges: automaticTemps.reversed())) + } + for temp in segments where temp.kind == .temp && !temp.automatic { + entries.append(LogEntry( + id: "temp-\(temp.start.timeIntervalSince1970)", date: temp.start, + title: NSLocalizedString("Temp basal", comment: "Logbook row title: a temporary basal rate"), + subtitle: String(format: NSLocalizedString("Manual · %1$@", comment: "Logbook temp basal row subtitle: set by hand, then the rate and how long. (1: description, e.g. 0.50 U/h for 30m (scheduled 0.80))"), describe(temp)), + amount: LoopFormat.rate(temp.rate), amountColor: P.ink, + detail: LoopFormat.time(temp.start), + icon: "waveform.path.ecg", iconStyle: .basal, filters: [.basal])) + } + for suspend in segments where suspend.kind == .suspended { + var parts = [suspend.automatic ? sourceLoop : sourceManual, LoopFormat.duration(suspend.end.timeIntervalSince(suspend.start))] + if let glucose = glucoseContext(at: suspend.start, history.glucose, unit: unit, withTrend: false) { parts.append(glucose) } + entries.append(LogEntry( + id: "suspend-\(suspend.start.timeIntervalSince1970)", date: suspend.start, + title: NSLocalizedString("Basal suspended", comment: "Logbook row title: insulin delivery was suspended"), subtitle: joined(parts), + amount: String(format: NSLocalizedString("%1$@ U/h", comment: "Format string for an insulin rate in units per hour. (1: rate)"), LoopFormat.number(0, decimals: 0)), amountColor: P.ink, + detail: LoopFormat.time(suspend.start), + icon: "pause.fill", iconStyle: .solid(P.statusWarning), + filters: suspend.automatic ? [.basal, .loop] : [.basal])) + } + + for event in pumpEvents where inDay(event.date) { + let title: String + switch event.kind { + // Site change and alarm names come from the pump plugin as it reports them. + case .siteChange(let name): title = name + case .alarm(let name): title = name + case .resume: title = NSLocalizedString("Basal resumed", comment: "Logbook row title: insulin delivery resumed after a suspend") + } + entries.append(LogEntry( + id: "pump-\(event.id)", date: event.date, + title: title, subtitle: NSLocalizedString("Pump", comment: "Logbook row subtitle: the event was reported by the insulin pump"), + amount: "", amountColor: P.ink, + detail: LoopFormat.time(event.date), + icon: "circle.dashed", iconStyle: .solid(P.inkMuted.opacity(0.5)), filters: [])) + } + + let insulin = InsulinSplit(basal: segments.reduce(0) { $0 + $1.units }, boluses: history.boluses.filter { inDay($0.date) }) + return LogDay(day: day.start, entries: foldingAutomaticBoluses(entries.sorted { $0.date > $1.date }), insulin: insulin, + carbs: carbsToday.reduce(0) { $0 + $1.grams }) + } + } + + /// Loop gives many small automatic boluses; two or more in a row, with nothing else logged between them, become + /// one row that lists them. The day's Basal adjustments summary row is dated by its latest change, not where it + /// falls, so it doesn't break a run. + static func foldingAutomaticBoluses(_ entries: [LogEntry]) -> [LogEntry] { + var result: [LogEntry] = [] + var run: [LogEntry] = [] + var summaries: [LogEntry] = [] + + func flush() { + if run.count >= 2, let newest = run.first, let oldest = run.last { + let units = run.reduce(0) { $0 + ($1.automaticUnits ?? 0) } + result.append(LogEntry( + id: "autorun-\(newest.id)", date: newest.date, + title: NSLocalizedString("Automatic boluses", comment: "Logbook row title: several automatic boluses in a row, folded into one row that lists them"), + subtitle: String(format: NSLocalizedString("Loop · %1$@ · tap to list", comment: "Logbook folded automatic boluses row subtitle: Loop gave them, the time span they cover, and tapping lists them. (1: time range, e.g. 15:08 – 16:14)"), + "\(LoopFormat.time(oldest.date))–\(LoopFormat.time(newest.date))"), + amount: LoopFormat.doseUnits(units), amountColor: P.ink, + detail: String.localizedStringWithFormat(NSLocalizedString("%lld doses", comment: "Logbook folded automatic boluses row: how many automatic boluses it holds. (1: number)"), run.count), + icon: "arrow.triangle.2.circlepath", iconStyle: .hatch(P.bolus), + filters: [.bolus, .loop], quiet: true, + bolusRun: run)) + } else { + result.append(contentsOf: run) + } + run = [] + } + + for entry in entries { + if entry.automaticUnits != nil { + run.append(entry) + } else if !entry.basalChanges.isEmpty { + summaries.append(entry) + } else { + flush() + result.append(entry) + } + } + flush() + // Put the summary rows back in date order. + return (result + summaries).sorted { $0.date > $1.date } + } + + private static var sourceLoop: String { + NSLocalizedString("Loop", comment: "Logbook row detail: Loop made this change automatically (Loop is the app's name)") + } + + private static var sourceManual: String { + NSLocalizedString("Manual", comment: "Logbook row detail: the user made this entry or change by hand") + } + + /// Row details are a list of independent facts ("Manual", "45 g", "glucose 7.5"), shown with a middle-dot separator. + private static func joined(_ parts: [String]) -> String { + parts.joined(separator: " · ") + } + + static func describe(_ segment: BasalSegment) -> String { + let rate = LoopFormat.rate(segment.rate) + let duration = LoopFormat.duration(segment.end.timeIntervalSince(segment.start)) + if let scheduled = segment.scheduledRate { + return String(format: NSLocalizedString("%1$@ for %2$@ (scheduled %3$@)", comment: "A temp basal: its rate, how long it ran and the scheduled rate it replaced. (1: rate, e.g. 0.50 U/h; 2: duration, e.g. 30m; 3: scheduled rate number, e.g. 0.80)"), rate, duration, LoopFormat.number(scheduled, decimals: 2)) + } + return String(format: NSLocalizedString("%1$@ for %2$@", comment: "A temp basal: its rate and how long it ran. (1: rate, e.g. 0.50 U/h; 2: duration, e.g. 30m)"), rate, duration) + } + + /// "glucose 7.5", or "glucose 11.0 rising" for Loop's own doses. + private static func glucoseContext(at date: Date, _ readings: [GlucosePoint], unit: GlucoseUnitStyle, withTrend: Bool) -> String? { + guard let reading = readings.last(where: { $0.date <= date.addingTimeInterval(60) }), date.timeIntervalSince(reading.date) <= 10 * 60 else { + return nil + } + let value = unit.format(reading.mgdl) + if withTrend, let earlier = readings.last(where: { $0.date <= reading.date.addingTimeInterval(-14 * 60) }), + reading.date.timeIntervalSince(earlier.date) <= 20 * 60 { + let perFifteen = (reading.mgdl - earlier.mgdl) / reading.date.timeIntervalSince(earlier.date) * 900 + if perFifteen > 10 { + return String(format: NSLocalizedString("glucose %1$@ rising", comment: "Logbook row detail: glucose when the dose was given, and rising. (1: glucose value, e.g. 11.0)"), value) + } else if perFifteen < -10 { + return String(format: NSLocalizedString("glucose %1$@ falling", comment: "Logbook row detail: glucose when the dose was given, and falling. (1: glucose value, e.g. 11.0)"), value) + } + } + return String(format: NSLocalizedString("glucose %1$@", comment: "Logbook row detail: glucose when the dose was given. (1: glucose value, e.g. 7.5)"), value) + } +} + +// MARK: - Screen + +struct LogbookView: View { + @StateObject private var model: LogbookModel + @State private var path: [Route] = [] + /// Editing is a sheet, as adding carbs is, with its own navigation for the bolus screen that can follow. + @State private var editingCarbs: CarbEditRoute? + @Environment(\.dynamicTypeSize) private var typeSize + private let deviceManager: DeviceDataManager + private let done: (() -> Void)? + + enum Route: Hashable { + case basal(String) + case boluses(String) + } + + struct CarbEditRoute: Identifiable { + let id = UUID() + let entry: StoredCarbEntry + } + + init(provider: LoopHistoryProvider, deviceManager: DeviceDataManager, done: (() -> Void)? = nil) { + _model = StateObject(wrappedValue: LogbookModel(provider: provider)) + self.deviceManager = deviceManager + self.done = done + } + + private var visibleDays: [LogDay] { + model.days.map { day in + LogDay(day: day.day, entries: day.entries.filter { $0.matches(model.filter) }, insulin: day.insulin, carbs: day.carbs) + } + } + + var body: some View { + NavigationStack(path: $path) { + List { + Section { + chips + .listRowInsets(EdgeInsets()) + .listRowBackground(Color.clear) + } + if let error = model.loadError { + Text(String(format: NSLocalizedString("Couldn't load Logbook: %1$@", comment: "Logbook error when its history can't be read. (1: system error description)"), error)).foregroundStyle(P.statusCritical) + Button(NSLocalizedString("Retry", comment: "Button to try loading the Logbook again")) { model.reload() } + } else if model.loaded && model.days.allSatisfy({ $0.entries.isEmpty }) { + Text(NSLocalizedString("Nothing logged in the last 7 days.", comment: "Logbook empty state when there are no entries at all")) + .foregroundStyle(P.inkMuted) + } + ForEach(visibleDays) { day in + Section { + if day.entries.isEmpty { + Text(model.filter != .all + ? NSLocalizedString("Nothing to show for this filter", comment: "Logbook day with no entries matching the selected filter") + : day.insulin.total > 0 + ? NSLocalizedString("Scheduled basal only", comment: "Logbook day where only the scheduled basal ran, with nothing else logged") + : NSLocalizedString("Nothing logged", comment: "Logbook day with no entries")) + .font(LoopDesign.Typeface.footnote) + .foregroundStyle(P.inkMuted) + } + ForEach(day.entries) { entry in + row(entry) + } + } header: { + dayHeader(day) + } + } + Section { + EmptyView() + } footer: { + Text(NSLocalizedString("Loop keeps the last 7 days on this phone. Older doses and carbs are in Apple Health and on Trends.", comment: "Logbook footer explaining why only 7 days are listed")) + } + } + .listStyle(.insetGrouped) + .scrollContentBackground(.hidden) + .background(P.surface) + .navigationTitle(NSLocalizedString("Logbook", comment: "Title of the Logbook")) + .toolbar { + if let done { + ToolbarItem(placement: .confirmationAction) { + Button(NSLocalizedString("Done", comment: "Button to close the Logbook"), action: done) + } + } + } + .refreshable { model.reload() } + .overlay { + if !model.loaded { ProgressView() } + } + .navigationDestination(for: Route.self) { route in + destination(route) + } + } + .sheet(item: $editingCarbs) { route in + NavigationStack { + LogbookCarbEditor(entry: route.entry, deviceManager: deviceManager, provider: model.provider) { + editingCarbs = nil + model.reload() + } + .toolbar { + ToolbarItem(placement: .navigationBarLeading) { + Button(NSLocalizedString("Cancel", comment: "Button label for cancel")) { editingCarbs = nil } + } + } + } + } + .onAppear { model.reload() } + .onReceive(NotificationCenter.default.publisher(for: .LoopDataUpdated).debounce(for: .seconds(2), scheduler: RunLoop.main)) { _ in + model.reload() + } + .alert(NSLocalizedString("Couldn't delete", comment: "Alert title when deleting a Logbook entry fails"), isPresented: Binding(get: { model.error != nil }, set: { if !$0 { model.error = nil } })) { + Button(NSLocalizedString("OK", comment: "Button to dismiss the Logbook delete error alert"), role: .cancel) {} + } message: { + Text(model.error ?? "") + } + } + + private var chips: some View { + ScrollView(.horizontal, showsIndicators: false) { + HStack(spacing: LoopDesign.Space.s2) { + ForEach(LogEntry.Filter.allCases) { filter in + Button { + model.filter = filter + } label: { + Text(filter.title) + .font(LoopDesign.Typeface.footnote.weight(.semibold)) + .padding(.horizontal, 12) + .padding(.vertical, 6) + .foregroundStyle(model.filter == filter ? Color(uiColor: .systemBackground) : P.ink) + .background(model.filter == filter ? P.ink : P.surfaceSunken, in: Capsule()) + } + .buttonStyle(.plain) + .accessibilityAddTraits(model.filter == filter ? .isSelected : []) + } + } + .padding(.vertical, LoopDesign.Space.s1) + } + } + + private func dayHeader(_ day: LogDay) -> some View { + let calendar = Calendar.current + let date = LoopFormat.weekdayDay(day.day) + let title = calendar.isDateInToday(day.day) + ? String(format: NSLocalizedString("Today · %1$@", comment: "Logbook day header for today. (1: weekday and date, e.g. Sun 25 Oct)"), date) + : calendar.isDateInYesterday(day.day) + ? String(format: NSLocalizedString("Yesterday · %1$@", comment: "Logbook day header for yesterday. (1: weekday and date, e.g. Sat 24 Oct)"), date) + : date + return VStack(alignment: .leading, spacing: LoopDesign.Space.s2) { + let totals = HStack(spacing: LoopDesign.Space.s3) { + if day.insulin.total > 0 { + Text(LoopFormat.totalUnits(day.insulin.total)) + .foregroundStyle(P.ink) + } + Text(LoopFormat.grams(day.carbs)) + .foregroundStyle(P.ink) + } + .font(LoopDesign.Typeface.footnote.monospacedDigit()) + .fixedSize() + // The totals drop under the date when both won't fit on one line, rather than breaking numbers apart. + ViewThatFits(in: .horizontal) { + HStack(alignment: .firstTextBaseline) { + Text(title) + .font(LoopDesign.Typeface.headline) + .foregroundStyle(P.ink) + .fixedSize() + Spacer() + totals + } + VStack(alignment: .leading, spacing: LoopDesign.Space.s1) { + Text(title) + .font(LoopDesign.Typeface.headline) + .foregroundStyle(P.ink) + totals + } + } + if day.insulin.total > 0 { + // The day's total sits on the line above, so the key keeps to one line. + InsulinSplitLine(split: day.insulin, partial: calendar.isDateInToday(day.day)) + } + } + .padding(.bottom, 2) + .textCase(nil) + .accessibilityElement(children: .combine) + } + + @ViewBuilder + private func row(_ entry: LogEntry) -> some View { + // At accessibility sizes the amount moves under the title, so neither column squeezes the other into fragments. + let stacked = typeSize.isAccessibilitySize + let titles = VStack(alignment: .leading, spacing: 2) { + Text(entry.title) + .font(LoopDesign.Typeface.body) + .foregroundStyle(P.ink) + Text(entry.subtitle) + .font(LoopDesign.Typeface.footnote) + .foregroundStyle(P.inkMuted) + } + let amounts = VStack(alignment: stacked ? .leading : .trailing, spacing: 2) { + if !entry.amount.isEmpty { + Text(entry.amount) + .font(LoopDesign.Typeface.body.weight(entry.quiet ? .regular : .semibold).monospacedDigit()) + .foregroundStyle(entry.amountColor) + } + Text(entry.detail) + .font(LoopDesign.Typeface.footnote) + .foregroundStyle(P.inkMuted) + } + let content = HStack(alignment: stacked ? .top : .center, spacing: LoopDesign.Space.s3) { + IconTile(systemName: entry.icon, style: entry.iconStyle) + if stacked { + VStack(alignment: .leading, spacing: LoopDesign.Space.s1) { + titles + amounts + } + Spacer(minLength: 0) + } else { + titles + Spacer(minLength: LoopDesign.Space.s2) + amounts + } + } + .accessibilityElement(children: .combine) + + if !entry.basalChanges.isEmpty { + NavigationLink(value: Route.basal(entry.id)) { content } + } else if !entry.bolusRun.isEmpty { + NavigationLink(value: Route.boluses(entry.id)) { content } + } else { + content + .swipeActions(edge: .trailing, allowsFullSwipe: false) { + if let action = entry.delete, canPerform(action) { + Button(role: .destructive) { model.perform(action) } label: { Label(NSLocalizedString("Delete", comment: "Swipe action to delete a Logbook entry"), systemImage: "trash") } + } + if let carb = entry.edit, model.carbEditingAllowed { + Button { + guard model.provider.allowsCarbEditing else { return } + editingCarbs = CarbEditRoute(entry: carb) + } label: { Label(NSLocalizedString("Edit", comment: "Swipe action to edit a Logbook carb entry"), systemImage: "pencil") } + .tint(P.accent) + } + } + } + } + + private func canPerform(_ action: LogEntry.Action) -> Bool { + switch action { + case .deleteCarbs: return model.carbEditingAllowed + case .deleteDose: return true + } + } + + @ViewBuilder + private func destination(_ route: Route) -> some View { + switch route { + case .basal(let id): + if let entry = model.days.flatMap(\.entries).first(where: { $0.id == id }) { + BasalChangesList(changes: entry.basalChanges) + } + case .boluses(let id): + if let entry = model.days.flatMap(\.entries).first(where: { $0.id == id }) { + List(entry.bolusRun) { bolus in + row(bolus) + } + .navigationTitle(NSLocalizedString("Automatic boluses", comment: "Logbook row title: several automatic boluses in a row, folded into one row that lists them")) + .navigationBarTitleDisplayMode(.inline) + } + } + } +} + +/// Own the draft independently of rows that refresh while the editor or its bolus screen is open. +private struct LogbookCarbEditor: View { + @StateObject private var viewModel: CarbEntryViewModel + let deviceManager: DeviceDataManager + let provider: LoopHistoryProvider + let dismiss: () -> Void + + init(entry: StoredCarbEntry, deviceManager: DeviceDataManager, provider: LoopHistoryProvider, dismiss: @escaping () -> Void) { + _viewModel = StateObject(wrappedValue: provider.carbEntryViewModel(editing: entry)) + self.deviceManager = deviceManager + self.provider = provider + self.dismiss = dismiss + } + + var body: some View { + CarbEntryScreen(viewModel: viewModel) + .environmentObject(deviceManager.displayGlucosePreference) + .environment(\.dismissAction, dismiss) + .navigationTitle(NSLocalizedString("Edit Carb Entry", comment: "Title of the screen for editing a carb entry from the Logbook")) + .navigationBarTitleDisplayMode(.inline) + .onAppear { if !provider.allowsCarbEditing { dismiss() } } + // Loop posts this from its data queue; SwiftUI faults on publishers that emit off the main thread. + .onReceive(NotificationCenter.default.publisher(for: .LoopDataUpdated).receive(on: RunLoop.main)) { _ in + if !provider.allowsCarbEditing { dismiss() } + } + } +} + +/// Every basal change Loop made in a day. +struct BasalChangesList: View { + let changes: [BasalSegment] + + var body: some View { + List(Array(changes.enumerated()), id: \.offset) { _, change in + HStack { + VStack(alignment: .leading, spacing: 2) { + Text(LoopFormat.time(change.start)) + .font(LoopDesign.Typeface.body) + Text(LogbookModel.describe(change)) + .font(LoopDesign.Typeface.footnote) + .foregroundStyle(P.inkMuted) + } + Spacer() + Text(String(format: NSLocalizedString("%1$@ U", comment: "Format string for an amount of insulin in units. (1: amount)"), LoopFormat.signed(change.netUnits))) + .font(LoopDesign.Typeface.body.weight(.semibold).monospacedDigit()) + .foregroundStyle(P.ink) + } + .accessibilityElement(children: .combine) + } + .navigationTitle(NSLocalizedString("Basal adjustments", comment: "Title of the list of every temp basal Loop set in a day")) + .navigationBarTitleDisplayMode(.inline) + } +} diff --git a/Loop/Redesign/LoopDesign.swift b/Loop/Redesign/LoopDesign.swift new file mode 100644 index 0000000000..3cfe37713b --- /dev/null +++ b/Loop/Redesign/LoopDesign.swift @@ -0,0 +1,424 @@ +// +// LoopDesign.swift +// Loop +// +// Copyright © 2026 LoopKit Authors. All rights reserved. +// + +import SwiftUI +import UIKit + +/// Colours, spacing and type for the Trends screen. +/// +/// Every colour is one Loop already has: the `glucose`, `insulin`, `carbs`, `fresh` and `warning` assets, so a +/// DerivedAssetsOverride still recolours them, and the iOS system colours for grounds and text. Bands and fills are +/// those colours at reduced opacity. Text is `label`, or `inkMuted` beside it; colour is for marks, not for numbers. +/// Red is only for something that needs action now. +enum LoopDesign { + + enum Palette { + // Grounds + static let surface = Color(uiColor: .systemGroupedBackground) + static let surfaceRaised = Color(uiColor: .secondarySystemGroupedBackground) + /// A fill rather than a solid grey, so tiles still show on a card in a sheet, where dark mode's raised card is + /// the same grey as `systemGray5`. + static let surfaceSunken = Color(uiColor: .secondarySystemFill) + static let separator = Color(uiColor: .opaqueSeparator) + /// One step lighter than the card in dark mode, for the same reason. + static let grid = Color(uiColor: UIColor { $0.userInterfaceStyle == .dark ? .systemGray4 : .systemGray5 }) + + // Text + static let ink = Color(uiColor: .label) + /// Black or white at reduced opacity, to reach WCAG AAA's 7:1 on every ground. `secondaryLabel` reaches 3.2:1 in + /// light mode and 4.1:1 in dark on a tile. Dark mode needs more opacity because a tile's fill lifts its ground. + static let inkMuted = Color(uiColor: UIColor { + $0.userInterfaceStyle == .dark ? .white.withAlphaComponent(0.85) : .black.withAlphaComponent(0.7) + }) + + // Quantities + static let glucose = Color("glucose") + static let targetBand = glucose.opacity(0.14) + static let agpOuter = glucose.opacity(0.16) + static let agpInner = glucose.opacity(0.34) + static let insulin = Color("insulin") + /// Insulin is one colour, told apart by shape: bolus is solid, automatic bolus is hatched and basal is hollow. + /// No tint of insulin's orange reaches 3:1 against it on a white card, and faded orange turns brown on a dark + /// one. Charts also keep a gap of the card's colour wherever basal and bolus meet. + static let bolus = insulin + static let basal = insulin.opacity(0.1) + static let basalOutline = insulin + /// Basal over a day is a stepped area that an outline would break into pieces, so it's a plain fill. + static let basalArea = insulin.opacity(0.25) + static let basalScheduled = inkMuted + static let carbs = Color("carbs") + + // Loop state + static let statusAutomated = Color("fresh") + static let statusWarning = Color("warning") + static let statusCritical = Color(uiColor: .critical) + static let accent = Color("accent") + /// The glyph on a filled icon tile. + static let onFill = Color.black + } + + enum Space { + static let s1: CGFloat = 4 + static let s2: CGFloat = 8 + static let s3: CGFloat = 12 + static let s4: CGFloat = 16 + static let s6: CGFloat = 24 + static let s8: CGFloat = 32 + } + + enum Radius { + static let sm: CGFloat = 6 + static let md: CGFloat = 10 + static let lg: CGFloat = 14 + } + + /// Text styles follow Dynamic Type; the large numbers are fixed sizes in SF Pro Rounded with tabular figures. + enum Typeface { + static let glucoseHero = Font.system(size: 64, weight: .bold, design: .rounded).monospacedDigit() + static let statValue = Font.system(.title, design: .rounded).weight(.semibold).monospacedDigit() + static let statValueSmall = Font.system(.title3, design: .rounded).weight(.semibold).monospacedDigit() + static let title = Font.title.bold() + static let headline = Font.headline + static let body = Font.body + static let subhead = Font.subheadline + static let footnote = Font.footnote + static let caption = Font.caption2.weight(.medium).monospacedDigit() + } +} + +// MARK: - Card + +struct LoopCard: View { + var padding: CGFloat = LoopDesign.Space.s4 + @ViewBuilder var content: Content + + var body: some View { + VStack(alignment: .leading, spacing: LoopDesign.Space.s3) { + content + } + .padding(padding) + .frame(maxWidth: .infinity, alignment: .leading) + .background(LoopDesign.Palette.surfaceRaised, in: RoundedRectangle(cornerRadius: LoopDesign.Radius.lg, style: .continuous)) + } +} + +/// A card title with an optional trailing detail or action, as on every card in the mock-ups. +struct CardHeader: View { + let title: String + @ViewBuilder var trailing: Trailing + @Environment(\.dynamicTypeSize) private var typeSize + + var body: some View { + AdaptiveRow(spacing: typeSize.isAccessibilitySize ? LoopDesign.Space.s1 : LoopDesign.Space.s2) { + Text(title) + .font(LoopDesign.Typeface.headline) + .foregroundStyle(LoopDesign.Palette.ink) + .accessibilityAddTraits(.isHeader) + if !typeSize.isAccessibilitySize { + Spacer(minLength: LoopDesign.Space.s2) + } + trailing + .font(LoopDesign.Typeface.footnote) + .foregroundStyle(LoopDesign.Palette.inkMuted) + } + } +} + +extension CardHeader where Trailing == EmptyView { + init(title: String) { + self.init(title: title) { EmptyView() } + } +} + +// MARK: - Legend + +struct LegendItem: Identifiable { + enum Swatch { + case solid(Color) + case outline(Color) + case dash(Color) + case dot(Color) + case hatch(Color) + case basal + } + + let id = UUID() + let swatch: Swatch + let label: String +} + +struct ChartLegend: View { + let items: [LegendItem] + + var body: some View { + FlowLayout(spacing: LoopDesign.Space.s3, lineSpacing: LoopDesign.Space.s1) { + ForEach(items) { item in + HStack(spacing: LoopDesign.Space.s1) { + LegendSwatch(swatch: item.swatch) + Text(item.label) + } + .accessibilityElement(children: .combine) + } + } + .font(LoopDesign.Typeface.footnote) + .foregroundStyle(LoopDesign.Palette.inkMuted) + } +} + +/// The 10-point key for one kind of mark, shared by legends and the basal and bolus rows. +struct LegendSwatch: View { + let swatch: LegendItem.Swatch + @Environment(\.colorScheme) private var scheme + + var body: some View { + switch swatch { + case .solid(let color): + RoundedRectangle(cornerRadius: 2).fill(color).frame(width: 10, height: 10) + case .outline(let color): + RoundedRectangle(cornerRadius: 2).strokeBorder(color, lineWidth: 1.5).frame(width: 10, height: 10) + case .dash(let color): + Path { path in + path.move(to: CGPoint(x: 0, y: 1)) + path.addLine(to: CGPoint(x: 14, y: 1)) + } + .stroke(color, style: StrokeStyle(lineWidth: 2, dash: [4, 2])) + .frame(width: 14, height: 2) + case .dot(let color): + Circle().fill(color).frame(width: 8, height: 8) + case .hatch(let color): + RoundedRectangle(cornerRadius: 2).fill(Hatch.paint(color, scheme: scheme)).frame(width: 10, height: 10) + case .basal: + RoundedRectangle(cornerRadius: 2).fill(LoopDesign.Palette.basal) + .overlay(RoundedRectangle(cornerRadius: 2).strokeBorder(LoopDesign.Palette.basalOutline, lineWidth: 1.25)) + .frame(width: 10, height: 10) + } + } +} + +/// A small sunken tile with a label over a value, as used under the hero and the timeline. +struct ValueTile: View { + let label: String + @ViewBuilder var value: Value + + var body: some View { + VStack(alignment: .leading, spacing: 2) { + Text(label) + .font(LoopDesign.Typeface.footnote) + .foregroundStyle(LoopDesign.Palette.inkMuted) + .lineLimit(1) + .minimumScaleFactor(0.7) + .allowsTightening(true) + // A value with a long unit ("0.04 単位") shrinks to fit rather than breaking mid-word. + value + .lineLimit(1) + .minimumScaleFactor(0.6) + } + .padding(LoopDesign.Space.s3) + .frame(maxWidth: .infinity, minHeight: 64, maxHeight: .infinity, alignment: .topLeading) + .background(LoopDesign.Palette.surfaceSunken, in: RoundedRectangle(cornerRadius: LoopDesign.Radius.md, style: .continuous)) + .accessibilityElement(children: .combine) + } +} + +struct StatusPill: View { + let text: String + var dot: Color? = nil + + var body: some View { + HStack(spacing: LoopDesign.Space.s1) { + if let dot { + Circle().fill(dot).frame(width: 8, height: 8) + } + Text(text) + .lineLimit(1) + } + .font(LoopDesign.Typeface.footnote.weight(.medium)) + .foregroundStyle(LoopDesign.Palette.ink) + .padding(.horizontal, 10) + .padding(.vertical, 5) + .background(LoopDesign.Palette.surfaceSunken, in: Capsule()) + } +} + +/// The square icon tile at the start of logbook rows. +/// +/// Insulin tiles are drawn the way the charts draw the same insulin, so a row and its mark read alike: manual bolus +/// solid, automatic bolus hatched, basal pale with its edge. +struct IconTile: View { + enum Style { + case solid(Color) + case hatch(Color) + case basal + } + + let systemName: String + let style: Style + @Environment(\.colorScheme) private var scheme + + init(systemName: String, fill: Color) { + self.systemName = systemName + self.style = .solid(fill) + } + + init(systemName: String, style: Style) { + self.systemName = systemName + self.style = style + } + + private var shape: RoundedRectangle { RoundedRectangle(cornerRadius: LoopDesign.Radius.sm, style: .continuous) } + + var body: some View { + Image(systemName: systemName) + .font(.system(size: isHatched ? 11 : 13, weight: .bold)) + .foregroundStyle(glyph) + // Stripes behind a glyph blur it, so the hatched tile sets its glyph on a plain disc. + .frame(width: isHatched ? 18 : 28, height: isHatched ? 18 : 28) + .background { if isHatched { Circle().fill(LoopDesign.Palette.surfaceRaised) } } + .frame(width: 28, height: 28) + .background { background } + .accessibilityHidden(true) + } + + private var isHatched: Bool { + if case .hatch = style { return true } + return false + } + + private var glyph: Color { + switch style { + case .solid: return LoopDesign.Palette.onFill + case .hatch, .basal: return LoopDesign.Palette.ink + } + } + + @ViewBuilder + private var background: some View { + switch style { + case .solid(let fill): + shape.fill(fill) + case .hatch(let color): + shape.fill(Hatch.paint(color, scheme: scheme)) + .overlay(shape.strokeBorder(color, lineWidth: 1.5)) + case .basal: + shape.fill(LoopDesign.Palette.basal) + .overlay(shape.strokeBorder(LoopDesign.Palette.basalOutline, lineWidth: 1.5)) + } + } +} + +/// Diagonal stripes over a pale tint of a colour: automatic bolus, wherever a mark is wide enough to show it. +enum Hatch { + static func paint(_ color: Color, scheme: ColorScheme) -> ImagePaint { + let resolved = UIColor(color).resolvedColor(with: UITraitCollection(userInterfaceStyle: scheme == .dark ? .dark : .light)) + let size: CGFloat = 5 + let image = UIGraphicsImageRenderer(size: CGSize(width: size, height: size)).image { context in + resolved.withAlphaComponent(scheme == .dark ? 0.3 : 0.22).setFill() + context.fill(CGRect(x: 0, y: 0, width: size, height: size)) + resolved.setStroke() + // One stripe corner to corner, plus the ends of its neighbours, so tiles join into unbroken lines. + let path = UIBezierPath() + path.lineWidth = 1.4 + for offset in [-size, 0, size] { + path.move(to: CGPoint(x: offset, y: size)) + path.addLine(to: CGPoint(x: offset + size, y: 0)) + } + path.stroke() + } + return ImagePaint(image: Image(uiImage: image)) + } +} + +/// Wraps its children onto new lines, for legends and chips. +struct FlowLayout: Layout { + var spacing: CGFloat + var lineSpacing: CGFloat + + func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize { + let width = proposal.width ?? .infinity + var x: CGFloat = 0, y: CGFloat = 0, lineHeight: CGFloat = 0, maxX: CGFloat = 0 + for subview in subviews { + let size = subview.sizeThatFits(.unspecified) + if x > 0 && x + size.width > width { + x = 0 + y += lineHeight + lineSpacing + lineHeight = 0 + } + x += size.width + spacing + maxX = max(maxX, x - spacing) + lineHeight = max(lineHeight, size.height) + } + return CGSize(width: maxX, height: y + lineHeight) + } + + func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) { + var x = bounds.minX, y = bounds.minY, lineHeight: CGFloat = 0 + for subview in subviews { + let size = subview.sizeThatFits(.unspecified) + if x > bounds.minX && x + size.width > bounds.maxX { + x = bounds.minX + y += lineHeight + lineSpacing + lineHeight = 0 + } + subview.place(at: CGPoint(x: x, y: y), proposal: ProposedViewSize(size)) + x += size.width + spacing + lineHeight = max(lineHeight, size.height) + } + } +} + +/// A row that stacks vertically at accessibility text sizes, so tiles and buttons keep their numbers on one line. +struct AdaptiveRow: View { + @Environment(\.dynamicTypeSize) private var typeSize + var spacing: CGFloat = LoopDesign.Space.s2 + @ViewBuilder var content: Content + + var body: some View { + let layout = typeSize.isAccessibilitySize + ? AnyLayout(VStackLayout(alignment: .leading, spacing: spacing)) + : AnyLayout(HStackLayout(spacing: spacing)) + layout { content } + } +} + +/// The round previous and next buttons beside a date or period. +struct StepButton: View { + let systemName: String + let label: String + var enabled = true + let action: () -> Void + + var body: some View { + Button(action: action) { + Image(systemName: systemName) + .font(.footnote.weight(.semibold)) + .frame(width: 30, height: 30) + .background(LoopDesign.Palette.surfaceRaised, in: Circle()) + .overlay(Circle().strokeBorder(LoopDesign.Palette.separator)) + .frame(width: 44, height: 44) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .foregroundStyle(enabled ? LoopDesign.Palette.ink : LoopDesign.Palette.inkMuted.opacity(0.5)) + .disabled(!enabled) + .accessibilityLabel(label) + } +} + +/// A message in place of a chart that has nothing to draw, saying why. +struct ChartPlaceholder: View { + let message: String + var height: CGFloat = 120 + + var body: some View { + Text(message) + .font(LoopDesign.Typeface.footnote) + .foregroundStyle(LoopDesign.Palette.inkMuted) + .multilineTextAlignment(.center) + .frame(maxWidth: .infinity, minHeight: height) + .background(LoopDesign.Palette.surfaceSunken.opacity(0.5), in: RoundedRectangle(cornerRadius: LoopDesign.Radius.md)) + } +} diff --git a/Loop/Redesign/LoopHistoryMath.swift b/Loop/Redesign/LoopHistoryMath.swift new file mode 100644 index 0000000000..f062d28d06 --- /dev/null +++ b/Loop/Redesign/LoopHistoryMath.swift @@ -0,0 +1,354 @@ +// +// LoopHistoryMath.swift +// Loop +// +// Copyright © 2026 LoopKit Authors. All rights reserved. +// + +import Foundation + +/// Pure calculations behind the Trends screen. Nothing here touches a store. +enum LoopHistoryMath { + + // MARK: Glucose + + /// An HbA1c or GMI percentage (NGSP) in mmol/mol (IFCC). + static func mmolPerMol(percent: Double) -> Double { + (percent - 2.152) * 10.929 + } + + /// Whether GMI is as representative as the consensus asks: a period of at least 14 calendar days (today counts, + /// so "14 d" does while it runs), with CGM data for at least 70% of it. + static func gmiIsRepresentative(periodDays: Int, cgmActive: Double) -> Bool { + periodDays >= 14 && cgmActive >= 0.7 + } + + /// Hours a day with CGM readings: what a band's share of time is a share of. One day gives that day's hours + /// with readings, so far when it is today; a longer period gives the average over its days. + static func cgmHoursPerDay(cgmActive: Double, over interval: DateInterval, periodDays: Int) -> Double { + periodDays <= 1 ? cgmActive * interval.duration / 3600 : cgmActive * 24 + } + + /// The number of distinct calendar days with readings. + static func daysWithReadings(_ points: [GlucosePoint], calendar: Calendar = .current) -> Int { + Set(points.map { calendar.startOfDay(for: $0.date) }).count + } + + /// Whole days from the first reading to the end of `interval`, when that falls short of the period by more than a + /// day; nil when the readings span the period, or there are none. + static func cgmCoveredDays(_ points: [GlucosePoint], in interval: DateInterval, periodDays: Int) -> Int? { + guard periodDays > 1, let first = points.map(\.date).min() else { return nil } + let available = interval.end.timeIntervalSince(first) / 86400 + guard available + 1 < Double(periodDays) else { return nil } + return max(1, Int(available.rounded())) + } + + // MARK: Time in range + + /// Whole-number percentages that add up to 100 (largest remainder), so the labels never sum to 99 or 101. + static func roundedPercentages(_ fractions: [GlucoseBand: Double]) -> [GlucoseBand: Int] { + let raw = GlucoseBand.allCases.map { (band: $0, value: (fractions[$0] ?? 0) * 100) } + let total = raw.reduce(0) { $0 + $1.value } + guard total > 0 else { return Dictionary(uniqueKeysWithValues: GlucoseBand.allCases.map { ($0, 0) }) } + var floors = raw.map { (band: $0.band, floor: Int($0.value.rounded(.down)), remainder: $0.value - $0.value.rounded(.down)) } + var missing = Int(total.rounded()) - floors.reduce(0) { $0 + $1.floor } + for index in floors.indices.sorted(by: { floors[$0].remainder > floors[$1].remainder }) where missing > 0 { + floors[index].floor += 1 + missing -= 1 + } + return Dictionary(uniqueKeysWithValues: floors.map { ($0.band, $0.floor) }) + } + + // MARK: Scheduled basal + + /// Units the schedule would deliver over `span`, or nil where the points don't cover all of it. + static func scheduledUnits(_ points: [ScheduledBasalPoint], over span: DateInterval) -> Double? { + var units = 0.0 + var covered: TimeInterval = 0 + for point in points { + let overlap = min(point.end, span.end).timeIntervalSince(max(point.start, span.start)) + guard overlap > 0 else { continue } + units += point.rate * overlap / 3600 + covered += overlap + } + return covered >= span.duration - 60 ? units : nil + } + + // MARK: Loop's stores and Apple Health + + /// Where one kind of data switches from Apple Health to Loop's own records: the later of the start of Loop's + /// local history and its first record of that kind. With no records of that kind, it is `now`, so all of it + /// comes from Health. Loop writes what it records to Health too, so reading Health only before this point and + /// Loop's stores only from it counts nothing twice. + static func healthBoundary(localHistoryStart: Date, firstLocalRecord: Date?, now: Date) -> Date { + max(localHistoryStart, firstLocalRecord ?? now) + } + + /// The earliest record that lies in `chunk`, from records given as start and end. A store can return records + /// outside the range it was asked for, such as a pump's dose still in progress, so only those overlapping the + /// chunk count. A record crossing into the chunk keeps its real start; one with no duration, such as a bolus, + /// counts by its start. + static func firstRecord(in chunk: DateInterval, of records: [(start: Date, end: Date)]) -> Date? { + records + .filter { $0.start < chunk.end && ($0.end > chunk.start || ($0.end <= $0.start && $0.start >= chunk.start)) } + .map(\.start) + .min() + } + + /// Several apps can write the same CGM reading to Health: keeps one CGM reading per 2½ minutes, from readings in + /// date order. Fingersticks are kept apart, so one never takes the place of a CGM reading beside it. + static func thinnedHealthGlucose(_ points: [GlucosePoint]) -> [GlucosePoint] { + var lastCGM: Date? + return points.filter { point in + guard !point.userEntered else { return true } + if let lastCGM, point.date.timeIntervalSince(lastCGM) < 150 { return false } + lastCGM = point.date + return true + } + } + + /// `window` cut at `boundary`: the part before it is read from Apple Health, the part from it on from Loop's + /// stores. Either is nil when the window has none of it; the two never overlap. + static func split(_ window: DateInterval, at boundary: Date) -> (health: DateInterval?, local: DateInterval?) { + let health = window.start < boundary ? DateInterval(start: window.start, end: min(window.end, boundary)) : nil + let local = window.end > boundary ? DateInterval(start: max(window.start, boundary), end: window.end) : nil + return (health, local) + } + + // MARK: Days + + /// Midnight-to-midnight intervals covering `interval`, oldest first, the last one cut off at `interval.end`. + static func days(in interval: DateInterval, calendar: Calendar = .current) -> [DateInterval] { + var result: [DateInterval] = [] + var start = calendar.startOfDay(for: interval.start) + while start < interval.end { + guard let next = calendar.date(byAdding: .day, value: 1, to: start) else { break } + result.append(DateInterval(start: max(start, interval.start), end: min(next, interval.end))) + start = next + } + return result + } + + struct DayTotal: Equatable, Identifiable { + let day: Date + let split: InsulinSplit + /// False for a day still in progress, so its partial total doesn't pull per-day averages down. + var isComplete = true + var id: Date { day } + var basal: Double { split.basal } + var bolus: Double { split.bolus } + var total: Double { split.total } + + init(day: Date, split: InsulinSplit, isComplete: Bool = true) { + self.day = day + self.split = split + self.isComplete = isComplete + } + + /// A total with no manual or automatic detail: all of its bolus counts as manual. + init(day: Date, basal: Double, bolus: Double, isComplete: Bool = true) { + self.init(day: day, split: InsulinSplit(basal: basal, manualBolus: bolus), isComplete: isComplete) + } + } + + /// The days per-day insulin figures average over: days with insulin, leaving out a day still in progress + /// unless no complete day has any. + static func averagingDays(_ totals: [DayTotal]) -> [DayTotal] { + let recorded = totals.filter { $0.total > 0 } + let complete = recorded.filter(\.isComplete) + return complete.isEmpty ? recorded : complete + } + + /// One source for the summary, legend and chart rule, before any weekly aggregation. + static func averageDailyInsulin(_ totals: [DayTotal]) -> Double { + let days = averagingDays(totals) + guard !days.isEmpty else { return 0 } + return days.reduce(0) { $0 + $1.total } / Double(days.count) + } + + /// Averages daily totals by calendar week (Monday start), for periods past 30 days. + static func weekly(_ totals: [DayTotal], calendar: Calendar = .current) -> [DayTotal] { + var cal = calendar + cal.firstWeekday = 2 + let groups = Dictionary(grouping: totals) { cal.dateInterval(of: .weekOfYear, for: $0.day)?.start ?? $0.day } + return groups.keys.sorted().map { week in + DayTotal(day: week, split: InsulinSplit.average(averagingDays(groups[week]!).map(\.split))) + } + } + + // MARK: Basal + + struct ScheduleValue { + let start: Date + let end: Date + let rate: Double + } + + /// A basal record from the pump: scheduled delivery, a temp basal or a suspend. + struct BasalDelivery { + let start: Date + let end: Date + /// U/h; 0 for a suspend. + let rate: Double + let kind: BasalSegment.Kind + let automatic: Bool + } + + /// Delivered basal over `window` from the pump's records (the latest-starting one wins where they overlap). + /// + /// From `recordsStart` on, time without a basal record counts at `programmedRates`, since that is what the pump + /// delivers on its own; this matches Loop's own insulin totals (`InsulinDeliveryHistory`). Before it, or without + /// it, gaps stay unknown. + static func basalSegments(window: DateInterval, schedule: [ScheduleValue], deliveries temps: [BasalDelivery], + programmedRates: [ScheduleValue] = [], recordsStart: Date? = nil) -> [BasalSegment] { + var cuts = Set([window.start, window.end]) + if let recordsStart, window.contains(recordsStart) { cuts.insert(recordsStart) } + for value in schedule + programmedRates { + if window.contains(value.start) { cuts.insert(value.start) } + if window.contains(value.end) { cuts.insert(value.end) } + } + for temp in temps { + if window.contains(temp.start) { cuts.insert(temp.start) } + if window.contains(temp.end) { cuts.insert(temp.end) } + } + let sorted = cuts.sorted() + let sortedTemps = temps.sorted { $0.start < $1.start } + // The furthest end among records up to each index bounds the backward search, so a week of five-minute + // records stays linear rather than scanning every record for every cut. + var furthestEnd: [Date] = [] + furthestEnd.reserveCapacity(sortedTemps.count) + for temp in sortedTemps { furthestEnd.append(max(furthestEnd.last ?? temp.end, temp.end)) } + func latestRecord(covering mid: Date) -> BasalDelivery? { + var low = 0, high = sortedTemps.count + while low < high { + let middle = (low + high) / 2 + if sortedTemps[middle].start <= mid { low = middle + 1 } else { high = middle } + } + var index = low - 1 + while index >= 0, furthestEnd[index] > mid { + if mid < sortedTemps[index].end { return sortedTemps[index] } + index -= 1 + } + return nil + } + var segments: [BasalSegment] = [] + for (a, b) in zip(sorted, sorted.dropFirst()) where b > a { + let mid = a.addingTimeInterval(b.timeIntervalSince(a) / 2) + let scheduled = schedule.first { $0.start <= mid && mid < $0.end }?.rate + let segment: BasalSegment + if let temp = latestRecord(covering: mid) { + segment = BasalSegment(start: a, end: b, rate: temp.kind == .suspended ? 0 : temp.rate, scheduledRate: scheduled, + kind: temp.kind, automatic: temp.automatic) + } else if let recordsStart, a >= recordsStart, + let programmed = programmedRates.first(where: { $0.start <= mid && mid < $0.end })?.rate { + segment = BasalSegment(start: a, end: b, rate: programmed, scheduledRate: scheduled, kind: .scheduled, automatic: false) + } else { + continue + } + if let last = segments.last, last.end == segment.start, last.rate == segment.rate, last.kind == segment.kind, + last.scheduledRate == segment.scheduledRate, last.automatic == segment.automatic { + segments[segments.count - 1] = BasalSegment(start: last.start, end: segment.end, rate: last.rate, + scheduledRate: last.scheduledRate, kind: last.kind, automatic: last.automatic) + } else { + segments.append(segment) + } + } + return segments + } + + /// Basal rate at a moment, from delivered segments. + static func basalRate(at date: Date, in segments: [BasalSegment]) -> BasalSegment? { + segments.last { $0.start <= date && date < $0.end } + } + + // MARK: Loop modes + + struct LoopRun { + let date: Date + let succeeded: Bool + /// The run stopped because a manual temp basal was running, which Loop shows as open loop. + var manualTempBasal = false + } + + /// Closed loop switched on or off, from Loop's stored settings. + struct ModeChange: Equatable { + let date: Date + let closedLoop: Bool + } + + /// Splits `interval` into closed, limited and open stretches. + /// + /// Each 5-minute slot is open when closed loop was switched off (from `modeChanges`), or while a manual temp basal + /// from `manualTempBasals` runs. A run that stopped for a manual temp basal with no dose record of it holds the + /// loop open for 15 minutes; where the record exists, its end or cancellation decides instead. Otherwise a slot is + /// closed when Loop completed a run in the 15 minutes before it ends, and limited when it didn't. Before the first mode change the setting is unknown, so the + /// result starts at the later of `coverageStart` and the first mode change. + static func loopModeSpans(interval: DateInterval, runs: [LoopRun], modeChanges: [ModeChange], coverageStart: Date?, + manualTempBasals: [DateInterval] = [], + recency: TimeInterval = 15 * 60, slot: TimeInterval = 5 * 60) -> [LoopModeSpan] { + guard let coverageStart, let firstChange = modeChanges.map(\.date).min() else { return [] } + let start = max(interval.start, coverageStart, firstChange) + guard interval.end > start else { return [] } + + let sortedRuns = runs.sorted { $0.date < $1.date } + let changes = modeChanges.sorted { $0.date < $1.date } + var spans: [LoopModeSpan] = [] + var runIndex = 0 + var lastRun: LoopRun? = nil + var lastRunHasDoseRecord = false + var lastSuccess: Date? = nil + var changeIndex = 0 + var closedSetting: Bool? = nil + let manualTemps = manualTempBasals.sorted { $0.start < $1.start } + var manualIndex = 0 + let recorded = { (date: Date) in manualTemps.contains { $0.start <= date && date <= $0.end } } + + var t = start + while t < interval.end { + let slotEnd = min(t.addingTimeInterval(slot), interval.end) + while runIndex < sortedRuns.count && sortedRuns[runIndex].date <= slotEnd { + let run = sortedRuns[runIndex] + lastRun = run + lastRunHasDoseRecord = run.manualTempBasal && recorded(run.date) + if run.succeeded { + lastSuccess = run.date + } + runIndex += 1 + } + while changeIndex < changes.count && changes[changeIndex].date <= slotEnd { + closedSetting = changes[changeIndex].closedLoop + changeIndex += 1 + } + + // A manual temp basal holds Loop open for as long as the pump runs it, whatever a later run failed on. + let middle = t.addingTimeInterval(slotEnd.timeIntervalSince(t) / 2) + while manualIndex < manualTemps.count && manualTemps[manualIndex].end <= middle { + manualIndex += 1 + } + let inManualTemp = manualIndex < manualTemps.count && manualTemps[manualIndex].start <= middle + + let mode: LoopModeSpan.Mode + if closedSetting == false || inManualTemp { + mode = .open + } else if let lastRun, lastRun.manualTempBasal, !lastRunHasDoseRecord, slotEnd.timeIntervalSince(lastRun.date) <= recency { + mode = .open + } else if let lastSuccess, slotEnd.timeIntervalSince(lastSuccess) <= recency { + mode = .closed + } else { + mode = .limited + } + + if let last = spans.last, last.mode == mode, last.end == t { + spans[spans.count - 1] = LoopModeSpan(start: last.start, end: slotEnd, mode: mode) + } else { + spans.append(LoopModeSpan(start: t, end: slotEnd, mode: mode)) + } + t = slotEnd + } + return spans + } + + static func duration(of mode: LoopModeSpan.Mode, in spans: [LoopModeSpan]) -> TimeInterval { + spans.filter { $0.mode == mode }.reduce(0) { $0 + $1.duration } + } +} diff --git a/Loop/Redesign/LoopHistoryModels.swift b/Loop/Redesign/LoopHistoryModels.swift new file mode 100644 index 0000000000..a0903ec121 --- /dev/null +++ b/Loop/Redesign/LoopHistoryModels.swift @@ -0,0 +1,370 @@ +// +// LoopHistoryModels.swift +// Loop +// +// Copyright © 2026 LoopKit Authors. All rights reserved. +// + +import Foundation +import HealthKit +import LoopKit +import LoopAlgorithm + +/// Plain value types the redesigned screens draw from. Glucose is kept in mg/dL and converted only for display, +/// so the statistics don't depend on the display unit. + +struct GlucosePoint: Equatable { + let date: Date + let mgdl: Double + /// A fingerstick or other reading typed in: drawn on charts, but left out of CGM statistics. + var userEntered = false +} + +struct BolusEvent: Equatable, Identifiable { + let id: String + let date: Date + let units: Double + /// Issued by Loop (automatic bolus) rather than by the person. + let automatic: Bool + /// Logged by hand, such as an injection, rather than delivered by the pump. Always a manual dose. + let manuallyEntered: Bool + /// Kept so a manually entered dose can be deleted from the dose store. + var dose: DoseEntry? = nil + /// False when the record doesn't say whether it was automatic or given by the person, such as some doses in Apple Health. + var automaticKnown = true + + /// Whether a record says what kind of bolus it is: it carries the automatic flag, or it was logged by hand, which + /// makes it manual. + static func kindKnown(automatic: Bool?, manuallyEntered: Bool) -> Bool { + automatic != nil || manuallyEntered + } + + static func == (lhs: BolusEvent, rhs: BolusEvent) -> Bool { + lhs.id == rhs.id && lhs.date == rhs.date && lhs.units == rhs.units && lhs.automatic == rhs.automatic + } +} + +struct BasalSegment: Equatable { + enum Kind: Equatable { + /// The scheduled rate, with no temp basal running. + case scheduled + /// A temp basal, set by Loop or by hand. + case temp + case suspended + } + + let start: Date + let end: Date + /// The rate actually delivered, in U/h. + let rate: Double + /// The profile rate at the time, in U/h, if known. + let scheduledRate: Double? + let kind: Kind + let automatic: Bool + + var hours: Double { end.timeIntervalSince(start) / 3600 } + var units: Double { rate * hours } + /// Units delivered above (positive) or below (negative) the schedule. + var netUnits: Double { + guard let scheduledRate else { return 0 } + return (rate - scheduledRate) * hours + } + + func clamped(to interval: DateInterval) -> BasalSegment? { + let s = max(start, interval.start), e = min(end, interval.end) + guard e > s else { return nil } + return BasalSegment(start: s, end: e, rate: rate, scheduledRate: scheduledRate, kind: kind, automatic: automatic) + } +} + +struct ScheduledBasalPoint: Equatable { + let start: Date + let end: Date + let rate: Double +} + +/// The correction range over part of a chart, in mg/dL. +struct TargetBand: Equatable { + let start: Date + let end: Date + let range: ClosedRange +} + +struct CarbEvent: Equatable, Identifiable { + let id: String + let date: Date + let grams: Double + let absorptionHours: Double? + let foodType: String? + let createdByLoop: Bool + /// Kept so the entry can be edited or deleted. + var entry: StoredCarbEntry? = nil + + static func == (lhs: CarbEvent, rhs: CarbEvent) -> Bool { + lhs.id == rhs.id && lhs.date == rhs.date && lhs.grams == rhs.grams + } +} + +/// Everything known about one day or reporting period, for InsulinTimeline. +struct PumpLogEvent: Equatable, Identifiable { + enum Kind: Equatable { + case siteChange(String) + case alarm(String) + case resume + } + + let id: String + let date: Date + let kind: Kind +} + +struct DayHistory { + var window: DateInterval + var glucose: [GlucosePoint] = [] + var boluses: [BolusEvent] = [] + var basal: [BasalSegment] = [] + var scheduledBasal: [ScheduledBasalPoint] = [] + var carbs: [CarbEvent] = [] + /// Where the data came from, so older days can say they are missing Loop's own detail. + var source: HistorySource = .loop + /// Where Loop's own dose records take over from Apple Health: before it, insulin has no schedule, and only the + /// boluses Loop wrote say whether they were automatic. + var localInsulinStart = Date.distantPast + + var bolusUnits: Double { boluses.reduce(0) { $0 + $1.units } } + var basalUnits: Double { basal.reduce(0) { $0 + $1.units } } + var carbGrams: Double { carbs.reduce(0) { $0 + $1.grams } } + var totalUnits: Double { bolusUnits + basalUnits } + var insulinSplit: InsulinSplit { InsulinSplit(basal: basalUnits, boluses: boluses) } + + /// Only what falls inside `interval`, with basal cut at its edges. + func clipped(to interval: DateInterval) -> DayHistory { + var history = self + let inside: (Date) -> Bool = { $0 >= interval.start && $0 < interval.end } + history.window = interval + history.glucose = glucose.filter { inside($0.date) } + history.boluses = boluses.filter { inside($0.date) } + history.basal = basal.compactMap { $0.clamped(to: interval) } + history.carbs = carbs.filter { inside($0.date) } + return history + } +} + +/// Basal and bolus for one day, or averaged per day, with bolus split into manual and automatic. +struct InsulinSplit: Equatable { + var basal = 0.0 + var manualBolus = 0.0 + var automaticBolus = 0.0 + /// Bolus that doesn't say whether it was manual or automatic; while there is any, the split isn't shown. + var unclassifiedBolus = 0.0 + + var bolus: Double { manualBolus + automaticBolus + unclassifiedBolus } + var total: Double { basal + bolus } + var isClassified: Bool { unclassifiedBolus < 0.005 } + + /// Shares in whole percent that add up to 100. + var bolusPercent: Int { total > 0 ? Int((bolus / total * 100).rounded()) : 0 } + var basalPercent: Int { total > 0 ? 100 - bolusPercent : 0 } +} + +extension InsulinSplit { + init(basal: Double, boluses: [BolusEvent]) { + self.basal = basal + for bolus in boluses { + if !bolus.automaticKnown { + unclassifiedBolus += bolus.units + } else if bolus.automatic { + automaticBolus += bolus.units + } else { + manualBolus += bolus.units + } + } + } + + /// The per-day average of several days' splits. + static func average(_ splits: [InsulinSplit]) -> InsulinSplit { + guard !splits.isEmpty else { return InsulinSplit() } + let n = Double(splits.count) + return InsulinSplit(basal: splits.reduce(0) { $0 + $1.basal } / n, + manualBolus: splits.reduce(0) { $0 + $1.manualBolus } / n, + automaticBolus: splits.reduce(0) { $0 + $1.automaticBolus } / n, + unclassifiedBolus: splits.reduce(0) { $0 + $1.unclassifiedBolus } / n) + } +} + +enum HistorySource { + /// Loop's own stores: manual versus automatic, temp basals and the schedule are all known. + case loop + /// Apple Health, for days older than Loop keeps. There is no basal schedule, and only the boluses Loop wrote say + /// whether they were automatic. + case health +} + +/// One stretch of the period in a single loop mode. +struct LoopModeSpan: Equatable { + enum Mode: Equatable { + case closed + case limited + case open + } + + let start: Date + let end: Date + let mode: Mode + + var duration: TimeInterval { end.timeIntervalSince(start) } +} + +// MARK: - Glucose unit + +struct GlucoseUnitStyle: Equatable { + let isMmol: Bool + + init(unit: LoopUnit) { + isMmol = unit == .millimolesPerLiter + } + + init(isMmol: Bool) { + self.isMmol = isMmol + } + + /// The factor Loop converts glucose with everywhere else, so a value reads the same here as on Loop's other screens. + static let mgdlPerMmol = 1 / LoopUnit.milligramsPerDeciliter.conversionFactor(toUnit: .millimolesPerLiter)! + + var unitName: String { isMmol ? "mmol/L" : "mg/dL" } + + func value(_ mgdl: Double) -> Double { isMmol ? mgdl / Self.mgdlPerMmol : mgdl } + func mgdl(_ displayValue: Double) -> Double { isMmol ? displayValue * Self.mgdlPerMmol : displayValue } + + func format(_ mgdl: Double) -> String { + isMmol ? LoopFormat.number(mgdl / Self.mgdlPerMmol, decimals: 1) : LoopFormat.number(mgdl, decimals: 0) + } + + /// Fixed chart scales from the design: 2–20 mmol/L on day views, 0–22 on AGP. + var dayDomain: ClosedRange { isMmol ? 2...20 : 36...360 } + var agpDomain: ClosedRange { isMmol ? 0...22 : 0...400 } + var dayTicks: [Double] { isMmol ? [4, 10, 16] : [70, 180, 300] } + var agpTicks: [Double] { isMmol ? [0, 4, 10, 16, 22] : [0, 70, 180, 250, 400] } +} + +// MARK: - Formatting + +enum LoopFormat { + /// A number in the user's locale, e.g. "7.3" or "7,3", with no grouping so values read like Loop's own screens. + static func number(_ value: Double, decimals: Int) -> String { + value.formatted(.number.precision(.fractionLength(decimals)).grouping(.never)) + } + + static func doseUnits(_ units: Double) -> String { + String(format: NSLocalizedString("%1$@ U", comment: "Format string for an amount of insulin in units. (1: amount)"), number(units, decimals: 2)) + } + + static func totalUnits(_ units: Double) -> String { + String(format: NSLocalizedString("%1$@ U", comment: "Format string for an amount of insulin in units. (1: amount)"), number(units, decimals: 1)) + } + + static func rate(_ rate: Double) -> String { + String(format: NSLocalizedString("%1$@ U/h", comment: "Format string for an insulin rate in units per hour. (1: rate)"), number(rate, decimals: 2)) + } + + static func grams(_ grams: Double) -> String { + String(format: NSLocalizedString("%1$@ g", comment: "Format string for an amount of carbohydrate in grams. (1: grams)"), number(grams, decimals: 0)) + } + + static func signed(_ value: Double, decimals: Int = 2) -> String { + let s = number(abs(value), decimals: decimals) + if abs(value) < pow(10, -Double(decimals)) / 2 { return "+" + s } + return (value < 0 ? "−" : "+") + s + } + + static func time(_ date: Date) -> String { + date.formatted(date: .omitted, time: .shortened) + } + + /// "25 Oct 2026" + static func day(_ date: Date) -> String { + date.formatted(.dateTime.day().month(.abbreviated).year()) + } + + /// "Sun 25 Oct" + static func weekdayDay(_ date: Date) -> String { + date.formatted(.dateTime.weekday(.abbreviated).day().month(.abbreviated)) + } + + /// "12 – 25 Oct 2026", "28 Sep – 25 Oct 2026", "20 Dec 2025 – 2 Jan 2026", in the user's locale. + static func range(_ start: Date, _ end: Date, calendar: Calendar = .current) -> String { + if calendar.isDate(start, inSameDayAs: end) { + return day(end) + } + let formatter = DateIntervalFormatter() + formatter.calendar = calendar + formatter.dateTemplate = "dMMMy" + return formatter.string(from: start, to: end) + } + + /// "2m", "1h 5m": how long ago, for the status pill. + static func ago(_ date: Date, now: Date = Date()) -> String { + let minutes = max(0, Int(now.timeIntervalSince(date) / 60)) + let formatter = DateComponentsFormatter() + formatter.unitsStyle = .abbreviated + formatter.allowedUnits = minutes >= 1440 ? [.day, .hour] : minutes >= 60 ? [.hour, .minute] : [.minute] + formatter.zeroFormattingBehavior = minutes == 0 ? .pad : .dropAll + return formatter.string(from: TimeInterval(minutes * 60)) ?? "" + } + + /// "13d 11h", "9h 45m", "40m" in English; abbreviated in the user's language. + static func duration(_ interval: TimeInterval) -> String { + let minutes = Int((interval / 60).rounded()) + let formatter = DateComponentsFormatter() + formatter.unitsStyle = .abbreviated + formatter.allowedUnits = minutes >= 1440 ? [.day, .hour] : minutes >= 60 ? [.hour, .minute] : [.minute] + formatter.zeroFormattingBehavior = .dropAll + return formatter.string(from: TimeInterval(minutes * 60)) ?? "" + } +} + +// MARK: - Store conversion boundaries + +extension BolusEvent { + init?(dose: DoseEntry, in interval: DateInterval) { + guard dose.type == .bolus, dose.startDate >= interval.start, dose.startDate < interval.end else { return nil } + self.init(id: dose.syncIdentifier ?? "\(dose.startDate.timeIntervalSince1970)", date: dose.startDate, + units: dose.unitsInDeliverableIncrements, automatic: !dose.manuallyEntered && (dose.automatic ?? false), + manuallyEntered: dose.manuallyEntered, dose: dose, + // A dose imported without the automatic flag, or not yet reconciled, is of unknown kind; one logged + // by hand is manual. + automaticKnown: BolusEvent.kindKnown(automatic: dose.automatic, manuallyEntered: dose.manuallyEntered)) + } +} + +extension LoopHistoryMath.BasalDelivery { + init?(dose: DoseEntry) { + let kind: BasalSegment.Kind + switch dose.type { + case .basal: kind = .scheduled + case .tempBasal: kind = .temp + case .suspend: kind = .suspended + default: return nil + } + let hours = dose.endDate.timeIntervalSince(dose.startDate) / 3600 + guard hours > 0 else { return nil } + self.init(start: dose.startDate, end: dose.endDate, + rate: kind == .suspended ? 0 : dose.unitsInDeliverableIncrements / hours, + kind: kind, automatic: dose.automatic ?? (kind == .temp)) + } +} + +extension BasalSegment { + init?(healthSample sample: HKQuantitySample, in interval: DateInterval) { + let hours = sample.endDate.timeIntervalSince(sample.startDate) / 3600 + guard hours > 0 else { return nil } + let scheduled = (sample.metadata?["com.loopkit.InsulinKit.MetadataKeyScheduledBasalRate"] as? HKQuantity)? + .doubleValue(for: HKUnit.internationalUnit().unitDivided(by: .hour())) + let segment = BasalSegment(start: sample.startDate, end: sample.endDate, + rate: sample.quantity.doubleValue(for: .internationalUnit()) / hours, + scheduledRate: scheduled, kind: .temp, + automatic: (sample.metadata?["com.loopkit.InsulinKit.MetadataKeyAutomaticallyIssued"] as? NSNumber)?.boolValue ?? false) + guard let clamped = segment.clamped(to: interval) else { return nil } + self = clamped + } +} diff --git a/Loop/Redesign/LoopHistoryProvider.swift b/Loop/Redesign/LoopHistoryProvider.swift new file mode 100644 index 0000000000..df1ba18e6c --- /dev/null +++ b/Loop/Redesign/LoopHistoryProvider.swift @@ -0,0 +1,565 @@ +// +// LoopHistoryProvider.swift +// Loop +// +// Copyright © 2026 LoopKit Authors. All rights reserved. +// + +import Foundation +import HealthKit +import LoopKit +import LoopCore +import LoopAlgorithm +import os + +/// Reads glucose, insulin, carbs and loop runs for the redesigned screens. +/// +/// Loop keeps `LOOP_LOCAL_CACHE_DURATION_DAYS` (90 by default) days in its own stores. From the start of that window, +/// or from Loop's first record of a kind when that is later, everything comes from those stores, so manual and +/// automatic doses, temp basals and the schedule are known. Earlier days come from Apple Health, which has glucose, +/// carbs and insulin split into basal and bolus, and whether Loop gave a bolus automatically only for the doses Loop +/// wrote, but not the basal schedule. +final class LoopHistoryProvider { + + private let deviceManager: DeviceDataManager + private let loopDataManager: LoopDataManager + /// Read once on the main actor, which owns `SettingsManager`; the store itself is safe to use from anywhere. + private let settingsStore: SettingsStore? + private let settingsManager: SettingsManager + private let temporaryPresetsManager: TemporaryPresetsManager + private let dosingDecisionStore: DosingDecisionStoreProtocol + private let doseStore: DoseStore + private let carbStore: CarbStore + private let glucoseStore: GlucoseStore + private let healthStore = HKHealthStore() + private let log = OSLog(category: "LoopHistoryProvider") + private let recordStartsCache = OSAllocatedUnfairLock(initialState: RecordStartsCache()) + private var storeObservers: [NSObjectProtocol] = [] + + @MainActor + init(deviceManager: DeviceDataManager, loopDataManager: LoopDataManager, settingsManager: SettingsManager, temporaryPresetsManager: TemporaryPresetsManager) { + self.deviceManager = deviceManager + self.loopDataManager = loopDataManager + self.settingsStore = settingsManager.settingsStore + self.settingsManager = settingsManager + self.temporaryPresetsManager = temporaryPresetsManager + self.dosingDecisionStore = loopDataManager.dosingDecisionStore + self.doseStore = deviceManager.doseStore + self.carbStore = deviceManager.carbStore + self.glucoseStore = deviceManager.glucoseStore + + // A record added or edited earlier than a cached start would otherwise stay hidden until the cache expires, + // so any change to a store searches for that kind's start again. + let cache = recordStartsCache + func forget(_ name: Notification.Name, of store: AnyObject, _ clear: @escaping @Sendable (inout LocalRecordStarts) -> Void) -> NSObjectProtocol { + NotificationCenter.default.addObserver(forName: name, object: store, queue: nil) { _ in + cache.withLock { cached in + clear(&cached.starts) + cached.generation += 1 + } + } + } + storeObservers = [ + forget(GlucoseStore.glucoseSamplesDidChange, of: glucoseStore) { $0.glucose = nil }, + forget(DoseStore.valuesDidChange, of: doseStore) { $0.insulin = nil }, + forget(CarbStore.carbEntriesDidChange, of: carbStore) { $0.carbs = nil }, + ] + } + + deinit { + storeObservers.forEach(NotificationCenter.default.removeObserver) + } + + @MainActor + var unitStyle: GlucoseUnitStyle { + GlucoseUnitStyle(unit: deviceManager.displayGlucosePreference.unit) + } + + /// Match the classic carb editor's eligibility rule, including mode changes while a screen is open. + @MainActor + var allowsCarbEditing: Bool { + settingsManager.dosingEnabled || !FeatureFlags.simpleBolusCalculatorEnabled + } + + /// The start of what Loop keeps locally. + var localHistoryStart: Date { + Date().addingTimeInterval(-Bundle.main.localCacheDuration) + } + + /// How many days Loop keeps in its own stores (`LOOP_LOCAL_CACHE_DURATION_DAYS`). + var localHistoryDays: Int { + Int((Bundle.main.localCacheDuration / 86400).rounded()) + } + + @MainActor + var glucoseTargetRange: ClosedRange? { + guard let range = temporaryPresetsManager.effectiveCorrectionRange() else { return nil } + return range.lowerBound.doubleValue(for: .milligramsPerDeciliter)...range.upperBound.doubleValue(for: .milligramsPerDeciliter) + } + + /// The median insulin delivered from midnight to this time of day over the last 14 days. + func typicalInsulinByNow() async -> (typical: TypicalInsulinDelivery, at: Date)? { + guard let history = try? await loopDataManager.insulinDeliveryHistory(days: 14), + let typical = history.typicalDelivery(by: history.end) else { return nil } + return (typical, history.end) + } + + /// The targets that actually applied, including dated presets and changes to the stored profile. + func glucoseTargetBands(in interval: DateInterval) async throws -> [TargetBand] { + guard let settingsStore else { return [] } + return try await loopDataManager.glucoseTargetBands(in: interval, settingsStore: settingsStore) + } + + /// SettingsStore's schedule queries extend the first profile backwards to the requested start. Reporting must + /// instead leave time before the first saved profile, and settings records without a profile, unknown. + private static func settingsHistory(in interval: DateInterval, from store: SettingsStore) async throws -> [(settings: StoredSettings, interval: DateInterval)] { + var records = Array(try await store.getStoredSettings(start: interval.start, end: interval.end).reversed()) + if let previous = try await store.getStoredSettings(end: interval.start, limit: 1).first { + records.insert(previous, at: 0) + } + return records.enumerated().compactMap { index, settings in + let start = max(interval.start, settings.date) + let end = min(interval.end, index + 1 < records.count ? records[index + 1].date : interval.end) + guard end > start else { return nil } + return (settings, DateInterval(start: start, end: end)) + } + } + + static func basalHistory(in interval: DateInterval, from store: SettingsStore) async throws -> [AbsoluteScheduleValue] { + let history = try await settingsHistory(in: interval, from: store) + return history.flatMap { record in + record.settings.basalRateSchedule?.truncatingBetween(start: record.interval.start, end: record.interval.end) ?? [] + } + } + + static func targetHistory(in interval: DateInterval, from store: SettingsStore) async throws -> [TargetBand] { + let history = try await settingsHistory(in: interval, from: store) + return history.flatMap { record -> [TargetBand] in + guard let schedule = record.settings.glucoseTargetRangeSchedule else { return [] } + return schedule.truncatingBetween(start: record.interval.start, end: record.interval.end).map { + let range = $0.value.quantityRange(for: schedule.unit) + return TargetBand(start: $0.startDate, end: $0.endDate, + range: range.lowerBound.doubleValue(for: .milligramsPerDeciliter)...range.upperBound.doubleValue(for: .milligramsPerDeciliter)) + } + } + } + + // MARK: - Days + + /// Glucose, insulin and carbs in `window`. Each kind comes from Apple Health before Loop's own records of it + /// begin, and from Loop's stores after, so a Loop younger than its cache still shows what Health has for the + /// days before it. + func dayHistory(_ window: DateInterval) async throws -> DayHistory { + var history = DayHistory(window: window) + let starts = try await localRecordStarts() + let now = Date(), localStart = localHistoryStart + let boundary = { LoopHistoryMath.healthBoundary(localHistoryStart: localStart, firstLocalRecord: $0, now: now) } + let glucoseBoundary = boundary(starts.glucose), insulinBoundary = boundary(starts.insulin), carbBoundary = boundary(starts.carbs) + let glucose = LoopHistoryMath.split(window, at: glucoseBoundary) + let insulin = LoopHistoryMath.split(window, at: insulinBoundary) + let carbs = LoopHistoryMath.split(window, at: carbBoundary) + + async let localGlucose = localGlucose(glucose.local) + async let localInsulin = localInsulin(insulin.local, recordsStart: starts.insulin) + async let localCarbs = localCarbs(carbs.local) + async let healthGlucose = healthGlucose(glucose.health) + async let healthInsulin = healthInsulin(insulin.health) + async let healthCarbs = healthCarbs(carbs.health) + + let (localBoluses, localBasal, scheduled) = try await localInsulin + let (healthBoluses, healthBasal) = try await healthInsulin + history.glucose = try await healthGlucose + localGlucose + history.boluses = healthBoluses + localBoluses + history.basal = healthBasal + localBasal + history.scheduledBasal = scheduled + history.carbs = try await healthCarbs + localCarbs + history.localInsulinStart = insulinBoundary + if window.end <= min(glucoseBoundary, insulinBoundary, carbBoundary) { + history.source = .health + } + try Task.checkCancellation() + return history + } + + /// Where Loop's own records of each kind begin, inside its local history; nil for a kind it has none of. + struct LocalRecordStarts: Equatable { + var glucose: Date? + var insulin: Date? + var carbs: Date? + } + + private struct RecordStartsCache { + var fetched: Date? + var starts = LocalRecordStarts() + /// Counts store changes, so a search that overlapped one doesn't save what it found. + var generation = 0 + } + + /// A found start is kept for a few minutes, so each period doesn't search again, and forgotten as soon as that + /// kind's store changes. A kind with no records yet is searched every time, because its first record can arrive at + /// any moment. + func localRecordStarts() async throws -> LocalRecordStarts { + let now = Date(), start = localHistoryStart + let cached = recordStartsCache.withLock { $0 } + let fresh = cached.fetched.map { now.timeIntervalSince($0) < 300 } ?? false + var starts = fresh ? cached.starts : LocalRecordStarts() + let glucoseStore = self.glucoseStore, doseStore = self.doseStore + if starts.glucose == nil { + starts.glucose = try await Self.firstRecord(from: start, to: now) { chunk in + try await glucoseStore.getGlucoseSamples(start: chunk.start, end: chunk.end).filter { !$0.isDisplayOnly }.map(\.startDate) + } + } + if starts.insulin == nil { + starts.insulin = try await Self.firstRecord(from: start, to: now) { chunk in + let doses = try await doseStore.getNormalizedDoseEntries(start: chunk.start, end: chunk.end) + return LoopHistoryMath.firstRecord(in: chunk, of: doses.map { (start: $0.startDate, end: $0.endDate) }).map { [$0] } ?? [] + } + } + if starts.carbs == nil { + starts.carbs = try await carbStore.getCarbEntries(start: start, end: now, dateAscending: true, fetchLimit: 1).first?.startDate + } + let found = starts + recordStartsCache.withLock { latest in + guard latest.generation == cached.generation else { return } + latest.fetched = fresh ? cached.fetched : now + latest.starts = found + } + return found + } + + /// The earliest date `dates` gives from `start` to `end`, read a week at a time so that finding it doesn't load + /// all of the local history. + private static func firstRecord(from start: Date, to end: Date, _ dates: (DateInterval) async throws -> [Date]) async throws -> Date? { + var chunkStart = start + while chunkStart < end { + let chunk = DateInterval(start: chunkStart, end: min(end, chunkStart.addingTimeInterval(.days(7)))) + if let first = try await dates(chunk).min() { + return first + } + chunkStart = chunk.end + } + return nil + } + + /// CGM readings for any period, local and Health combined. + func glucose(_ interval: DateInterval) async throws -> [GlucosePoint] { + let boundary = localHistoryStart + var points: [GlucosePoint] = [] + if interval.start < boundary { + points += try await healthGlucose(DateInterval(start: interval.start, end: min(interval.end, boundary))) + } + if interval.end > boundary { + points += try await localGlucose(DateInterval(start: max(interval.start, boundary), end: interval.end)) + } + return points + } + + // MARK: - Loop runs + + /// Loop runs in the local window, oldest first, with when the record of them begins. + func loopRuns() async throws -> (runs: [LoopHistoryMath.LoopRun], coverageStart: Date?) { + let start = localHistoryStart + var runs: [LoopHistoryMath.LoopRun] + if let store = dosingDecisionStore as? DosingDecisionStore { + // Decode only the fields a run needs, and only Loop's local window. + runs = try await store.getDosingDecisions(start: start, end: Date(), as: LoopRunRecord.self) + .filter { $0.reason == "loop" } + .map { Self.run(date: $0.date, issues: ($0.errors ?? []).map(\.id)) } + } else { + runs = try await anchoredLoopRuns() + } + try Task.checkCancellation() + runs = runs.filter { $0.date >= start }.sorted { $0.date < $1.date } + return (runs, runs.first?.date) + } + + private static func run(date: Date, issues: [String]) -> LoopHistoryMath.LoopRun { + LoopHistoryMath.LoopRun(date: date, succeeded: issues.isEmpty, manualTempBasal: issues.first == "manualTempBasalRunning") + } + + private struct LoopRunRecord: Decodable { + struct Issue: Decodable { let id: String } + let date: Date + let reason: String + let errors: [Issue]? + } + + /// Fetch each snapshot independently: overlapping reloads must not append the same anchored page twice. + private func anchoredLoopRuns() async throws -> [LoopHistoryMath.LoopRun] { + var anchor: DosingDecisionStore.QueryAnchor? + var runs: [LoopHistoryMath.LoopRun] = [] + while true { + let page: (DosingDecisionStore.QueryAnchor, [StoredDosingDecision]) = try await withCheckedThrowingContinuation { continuation in + dosingDecisionStore.executeDosingDecisionQuery(fromQueryAnchor: anchor, limit: 1000) { result in + switch result { + case .success(let anchor, let decisions): continuation.resume(returning: (anchor, decisions)) + case .failure(let error): continuation.resume(throwing: error) + } + } + } + try Task.checkCancellation() + anchor = page.0 + runs += page.1.filter { $0.reason == "loop" }.map { Self.run(date: $0.date, issues: $0.errors.map(\.id)) } + if page.1.count < 1000 { break } + } + return runs + } + + /// When closed loop was switched on or off, from the settings Loop stores on every change: the setting in force at + /// `interval.start`, then each change after it. Empty when Loop has no settings store. + func loopModeChanges(in interval: DateInterval) async throws -> [LoopHistoryMath.ModeChange] { + guard let store = settingsStore else { return [] } + var changes: [LoopHistoryMath.ModeChange] = [] + if let previous = try await store.getStoredSettings(end: interval.start, limit: 1).first { + changes.append(.init(date: interval.start, closedLoop: previous.dosingEnabled)) + } + // Newest first from the store; every settings save is a record, so keep only the ones that switch the mode. + for settings in try await store.getStoredSettings(start: interval.start, end: interval.end).reversed() + where changes.last?.closedLoop != settings.dosingEnabled { + changes.append(.init(date: settings.date, closedLoop: settings.dosingEnabled)) + } + return changes + } + + /// When manual temp basals ran in `interval`, from Loop's dose records, ended where the pump ended or cancelled + /// them. Loop shows the loop as open while one runs. + func manualTempBasals(in interval: DateInterval) async throws -> [DateInterval] { + // The last run before the period may have stopped for a temp basal that ended before the period too. + // Keep its record so the run-based fallback cannot reopen the loop after that recorded end. + // As on the home screen, only a record that says it isn't automatic counts: one that doesn't say, such as a + // dose worked out from reservoir readings, isn't known to be manual. + try await doseStore.getNormalizedDoseEntries(start: interval.start.addingTimeInterval(-.minutes(15)), end: interval.end) + .filter { $0.type == .tempBasal && $0.automatic == false && $0.endDate > $0.startDate } + .map { DateInterval(start: $0.startDate, end: $0.endDate) } + } + + // MARK: - Pump events + + func pumpEvents(since start: Date) async throws -> [PumpLogEvent] { + let events = try await doseStore.getPumpEventValues(since: start) + let items: [PumpLogEvent] = events.compactMap { event in + let id = event.objectIDURL.absoluteString + switch event.type { + case .replaceComponent(let component)?: + let name: String + switch component { + case .pump: name = NSLocalizedString("Pod changed", comment: "Pump event in the history: the pump or pod was replaced") + case .reservoir: name = NSLocalizedString("Reservoir changed", comment: "Pump event in the history: the insulin reservoir was replaced") + case .infusionSet: name = NSLocalizedString("Infusion set changed", comment: "Pump event in the history: the infusion set was replaced") + } + return PumpLogEvent(id: id, date: event.date, kind: .siteChange(name)) + case .rewind?: + return PumpLogEvent(id: id, date: event.date, kind: .siteChange(NSLocalizedString("Reservoir rewound", comment: "Pump event in the history: the pump rewound its reservoir"))) + case .prime?: + return PumpLogEvent(id: id, date: event.date, kind: .siteChange(NSLocalizedString("Primed", comment: "Pump event in the history: the pump primed the tubing or cannula"))) + case .alarm?: + // `title` is a debug description; only a pump's own alarm text is meant for people. + let pumpText: String? + if case .other(let details)? = event.alarmType, !details.isEmpty { pumpText = details } else { pumpText = nil } + return PumpLogEvent(id: id, date: event.date, kind: .alarm(pumpText ?? NSLocalizedString("Pump alarm", comment: "Pump event in the history: an alarm whose pump gave no title"))) + default: + return nil + } + } + return items + } + + // MARK: - Editing + + /// Edits an entry the way Loop's carb absorption screen does. + @MainActor + func carbEntryViewModel(editing entry: StoredCarbEntry) -> CarbEntryViewModel { + let viewModel = CarbEntryViewModel(delegate: loopDataManager, originalCarbEntry: entry) + viewModel.analyticsServicesManager = loopDataManager.analyticsServicesManager + viewModel.deliveryDelegate = deviceManager + return viewModel + } + + func delete(carb entry: StoredCarbEntry) async throws { + _ = try await loopDataManager.deleteCarbEntry(entry) + } + + func delete(dose: DoseEntry) async throws { + try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in + doseStore.deleteDose(dose) { error in + if let error { + continuation.resume(throwing: error) + } else { + continuation.resume() + } + } + } + } + + // MARK: - Loop's stores + + private func localGlucose(_ interval: DateInterval?) async throws -> [GlucosePoint] { + guard let interval else { return [] } + do { + let samples = try await glucoseStore.getGlucoseSamples(start: interval.start, end: interval.end) + return samples + .filter { !$0.isDisplayOnly } + .map { GlucosePoint(date: $0.startDate, mgdl: $0.quantity.doubleValue(for: .milligramsPerDeciliter), userEntered: $0.wasUserEntered) } + } catch { + os_log("Glucose fetch failed: %{public}@", log: log, type: .error, String(describing: error)) + throw error + } + } + + /// Doses, basal and the schedule for `interval`. `recordsStart` is Loop's earliest local dose: after it, + /// unrecorded time runs at the pump's programmed rate. + private func localInsulin(_ interval: DateInterval?, recordsStart: Date?) async throws -> ([BolusEvent], [BasalSegment], [ScheduledBasalPoint]) { + guard let interval else { return ([], [], []) } + let doses: [DoseEntry] + do { + doses = try await doseStore.getNormalizedDoseEntries(start: interval.start, end: interval.end) + } catch { + os_log("Dose fetch failed: %{public}@", log: log, type: .error, String(describing: error)) + throw error + } + + let boluses = doses.compactMap { BolusEvent(dose: $0, in: interval) } + + let basalHistory: [AbsoluteScheduleValue] + if let store = settingsStore { + basalHistory = try await Self.basalHistory(in: interval, from: store) + } else { + basalHistory = [] + } + let temporaryPresetsManager = self.temporaryPresetsManager + let overrides = await MainActor.run { + temporaryPresetsManager.presetHistory.getOverrideHistory(startDate: interval.start, endDate: interval.end) + } + // A resolved daily schedule repeats recent presets on every day. Use the stored profile and dated overrides. + let scheduleValues = overrides.applyBasal(over: basalHistory) + let schedule = scheduleValues.map { LoopHistoryMath.ScheduleValue(start: $0.startDate, end: $0.endDate, rate: $0.value) } + let deliveries = doses.compactMap { LoopHistoryMath.BasalDelivery(dose: $0) } + let now = Date() + let window = DateInterval(start: interval.start, end: max(interval.start, min(interval.end, now))) + // As in Loop's insulin totals: after the first record, unrecorded time runs at the pump's programmed rate. + let programmed = basalHistory.map { LoopHistoryMath.ScheduleValue(start: $0.startDate, end: $0.endDate, rate: $0.value) } + let basal = window.duration > 0 + ? LoopHistoryMath.basalSegments(window: window, schedule: schedule, deliveries: deliveries, + programmedRates: programmed, recordsStart: recordsStart) + : [] + let scheduled = schedule.map { ScheduledBasalPoint(start: max($0.start, interval.start), end: min($0.end, interval.end), rate: $0.rate) } + return (boluses, basal, scheduled) + } + + private func localCarbs(_ interval: DateInterval?) async throws -> [CarbEvent] { + guard let interval else { return [] } + do { + let entries = try await carbStore.getCarbEntries(start: interval.start, end: interval.end) + return entries.map { entry in + CarbEvent(id: entry.syncIdentifier ?? "\(entry.startDate.timeIntervalSince1970)", + date: entry.startDate, + grams: entry.quantity.doubleValue(for: .gram), + absorptionHours: entry.absorptionTime.map { $0 / 3600 }, + foodType: entry.foodType, + createdByLoop: entry.createdByCurrentApp, + entry: entry) + } + } catch { + os_log("Carb fetch failed: %{public}@", log: log, type: .error, String(describing: error)) + throw error + } + } + + // MARK: - Apple Health + + private func healthSamples(_ type: HKQuantityType, _ interval: DateInterval?, options: HKQueryOptions = .strictStartDate) async throws -> [HKQuantitySample] { + guard let interval, interval.duration > 0 else { return [] } + let log = self.log + return try await withCheckedThrowingContinuation { continuation in + let predicate = HKQuery.predicateForSamples(withStart: interval.start, end: interval.end, options: options) + let sort = NSSortDescriptor(key: HKSampleSortIdentifierStartDate, ascending: true) + let query = HKSampleQuery(sampleType: type, predicate: predicate, limit: HKObjectQueryNoLimit, sortDescriptors: [sort]) { _, samples, error in + if let error { + os_log("Health query for %{public}@ failed: %{public}@", log: log, type: .error, type.identifier, String(describing: error)) + continuation.resume(throwing: error) + } else { + let quantities = (samples as? [HKQuantitySample]) ?? [] + // Match the local stores' half-open ranges, including at the Health/local boundary. Basal + // queries use no strict start so segments crossing into the interval can still be clamped. + continuation.resume(returning: options.contains(.strictStartDate) + ? quantities.filter { $0.startDate >= interval.start && $0.startDate < interval.end } + : quantities) + } + } + healthStore.execute(query) + } + } + + private func healthGlucose(_ interval: DateInterval?) async throws -> [GlucosePoint] { + let samples = try await healthSamples(HKQuantityType(.bloodGlucose), interval) + let own = HKSource.default().bundleIdentifier + return LoopHistoryMath.thinnedHealthGlucose(samples + .filter { !$0.isDisplayOnly + && (FeatureFlags.observeHealthKitGlucoseSamplesFromOtherApps || $0.sourceRevision.source.bundleIdentifier == own) } + .map { GlucosePoint(date: $0.startDate, mgdl: $0.quantity.doubleValue(for: .milligramsPerDeciliter), userEntered: $0.wasUserEntered) }) + } + + private func healthInsulin(_ interval: DateInterval?) async throws -> ([BolusEvent], [BasalSegment]) { + guard let interval else { return ([], []) } + let samples = try await healthSamples(HKQuantityType(.insulinDelivery), interval, options: []) + var boluses: [BolusEvent] = [] + var basal: [BasalSegment] = [] + let own = HKSource.default().bundleIdentifier + for sample in samples where FeatureFlags.observeHealthKitDoseSamplesFromOtherApps || sample.sourceRevision.source.bundleIdentifier == own { + let units = sample.quantity.doubleValue(for: .internationalUnit()) + let reason = (sample.metadata?[HKMetadataKeyInsulinDeliveryReason] as? NSNumber)?.intValue + let automaticFlag = (sample.metadata?["com.loopkit.InsulinKit.MetadataKeyAutomaticallyIssued"] as? NSNumber)?.boolValue + let manuallyEntered = (sample.metadata?["com.loopkit.InsulinKit.MetadataKeyManuallyEntered"] as? NSNumber)?.boolValue ?? false + let automatic = !manuallyEntered && (automaticFlag ?? false) + if reason == HKInsulinDeliveryReason.basal.rawValue { + if let segment = BasalSegment(healthSample: sample, in: interval) { + basal.append(segment) + } + } else if sample.startDate >= interval.start && sample.startDate < interval.end { + boluses.append(BolusEvent(id: sample.uuid.uuidString, date: sample.startDate, units: units, automatic: automatic, + manuallyEntered: manuallyEntered, + automaticKnown: BolusEvent.kindKnown(automatic: automaticFlag, manuallyEntered: manuallyEntered))) + } + } + return (boluses, basal) + } + + private func healthCarbs(_ interval: DateInterval?) async throws -> [CarbEvent] { + let samples = try await healthSamples(HKQuantityType(.dietaryCarbohydrates), interval) + let own = HKSource.default().bundleIdentifier + return samples + .filter { FeatureFlags.observeHealthKitCarbSamplesFromOtherApps || $0.sourceRevision.source.bundleIdentifier == own } + .map { sample in + CarbEvent(id: sample.uuid.uuidString, date: sample.startDate, grams: sample.quantity.doubleValue(for: .gram()), + absorptionHours: nil, foodType: sample.metadata?[HKMetadataKeyFoodType] as? String, + createdByLoop: sample.sourceRevision.source.bundleIdentifier == own) + } + } +} + +// MARK: - Historical targets + +extension LoopDataManager { + /// A historical chart must use the profile and presets from that time, rather than repeat today's targets. + func glucoseTargetBands(in interval: DateInterval, settingsStore: SettingsStore) async throws -> [TargetBand] { + var bands = try await LoopHistoryProvider.targetHistory(in: interval, from: settingsStore) + let overrides = temporaryPresetsManager.presetHistory.getOverrideHistory(startDate: interval.start, endDate: interval.end) + for override in overrides.sorted(by: { $0.startDate < $1.startDate }) { + guard let target = override.settings.targetRange, + let active = override.activeInterval.intersection(with: interval), active.duration > 0 else { continue } + bands = bands.flatMap { band -> [TargetBand] in + var pieces: [TargetBand] = [] + if band.start < active.start { + pieces.append(TargetBand(start: band.start, end: min(band.end, active.start), range: band.range)) + } + if band.end > active.end { + pieces.append(TargetBand(start: max(band.start, active.end), end: band.end, range: band.range)) + } + return pieces + } + [TargetBand(start: active.start, end: active.end, + range: target.lowerBound.doubleValue(for: .milligramsPerDeciliter)...target.upperBound.doubleValue(for: .milligramsPerDeciliter))] + } + return bands.filter { $0.end > $0.start }.sorted { $0.start < $1.start } + } + +} diff --git a/Loop/Redesign/MainTabBarController.swift b/Loop/Redesign/MainTabBarController.swift new file mode 100644 index 0000000000..3765b8d2a7 --- /dev/null +++ b/Loop/Redesign/MainTabBarController.swift @@ -0,0 +1,94 @@ +// +// MainTabBarController.swift +// Loop +// +// Copyright © 2026 LoopKit Authors. All rights reserved. +// + +import UIKit +import SwiftUI +import WidgetKit +import LoopCore + +/// Whether Loop shows the redesigned interface (tabs: Now, Trends, Logbook, Settings) or the classic status screen. +enum LoopInterfacePreference { + private static let key = "com.loopkit.Loop.redesign.enabled" + + static let didChange = Notification.Name("LoopInterfacePreferenceDidChange") + + static var useRedesign: Bool { + get { UserDefaults.standard.object(forKey: key) as? Bool ?? true } + set { + guard newValue != useRedesign else { return } + UserDefaults.standard.set(newValue, forKey: key) + syncToExtensions() + NotificationCenter.default.post(name: didChange, object: nil) + } + } + + /// Copies the setting to the app group, where the widget and Live Activity read it, and redraws both. + static func syncToExtensions() { + guard let shared = UserDefaults.appGroup, shared.redesignEnabled != useRedesign else { return } + shared.redesignEnabled = useRedesign + WidgetCenter.shared.reloadAllTimelines() + // The Live Activity otherwise keeps its old look until Loop next runs. + NotificationCenter.default.post(name: .LiveActivitySettingsChanged, object: nil) + } +} + +/// The redesign's root. The Now tab is Loop's own RootNavigationController, so every existing flow +/// (bolus, carbs, presets, alerts, device settings, deeplinks) keeps working from StatusTableViewController. +final class MainTabBarController: UITabBarController, UITabBarControllerDelegate { + + let rootNavigationController: RootNavigationController + private weak var statusTableViewController: StatusTableViewController? + private let provider: LoopHistoryProvider + private let settingsPlaceholder = UIViewController() + + init(rootNavigationController: RootNavigationController, statusTableViewController: StatusTableViewController, deviceManager: DeviceDataManager, loopDataManager: LoopDataManager, settingsManager: SettingsManager) { + self.rootNavigationController = rootNavigationController + self.statusTableViewController = statusTableViewController + self.provider = LoopHistoryProvider(deviceManager: deviceManager, loopDataManager: loopDataManager, settingsManager: settingsManager, temporaryPresetsManager: statusTableViewController.temporaryPresetsManager) + super.init(nibName: nil, bundle: nil) + + rootNavigationController.tabBarItem = UITabBarItem(title: NSLocalizedString("Now", comment: "Title of the Now tab in the redesigned interface, showing current glucose and Loop status"), image: UIImage(systemName: "drop.fill"), tag: 0) + + let trends = UIHostingController(rootView: TrendsView(provider: provider)) + trends.tabBarItem = UITabBarItem(title: NSLocalizedString("Trends", comment: "Title of the Trends tab in the redesigned interface"), image: UIImage(systemName: "chart.bar.fill"), tag: 1) + + let logbook = UIHostingController(rootView: LogbookView(provider: provider, deviceManager: deviceManager)) + logbook.tabBarItem = UITabBarItem(title: NSLocalizedString("Logbook", comment: "Title of the Logbook tab in the redesigned interface, listing past events"), image: UIImage(systemName: "list.bullet"), tag: 2) + + settingsPlaceholder.tabBarItem = UITabBarItem(title: NSLocalizedString("Settings", comment: "Title of the Settings tab in the redesigned interface"), image: UIImage(systemName: "gearshape.fill"), tag: 3) + + viewControllers = [rootNavigationController, trends, logbook, settingsPlaceholder] + delegate = self + tabBar.tintColor = UIColor(named: "accent") + if #available(iOS 18.0, *) { + mode = .tabBar + } + } + + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + /// Settings stays a sheet, as in classic Loop, so the tab only presents it. It is presented from the Now tab: + /// device and service screens open from Settings through StatusTableViewController, which is only in the window + /// while Now is selected. + func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool { + guard viewController === settingsPlaceholder else { return true } + showNow() + statusTableViewController?.presentSettingsFromTab() + return false + } + + func showNow() { + selectedViewController = rootNavigationController + } + + override func restoreUserActivityState(_ activity: NSUserActivity) { + showNow() + rootNavigationController.restoreUserActivityState(activity) + } +} diff --git a/Loop/Redesign/NowScreen.swift b/Loop/Redesign/NowScreen.swift new file mode 100644 index 0000000000..9ae2d947ac --- /dev/null +++ b/Loop/Redesign/NowScreen.swift @@ -0,0 +1,960 @@ +// +// NowScreen.swift +// Loop +// +// Copyright © 2026 LoopKit Authors. All rights reserved. +// + +import SwiftUI +import HealthKit +import LoopKit +import LoopKitUI +import LoopCore +import LoopAlgorithm + +private typealias P = LoopDesign.Palette + +/// What the Now screen shows. StatusTableViewController owns it and asks it to refresh whenever Loop's data changes. +@MainActor +final class NowModel: ObservableObject { + + struct Reading: Equatable { + let mgdl: Double + let date: Date + let trend: GlucoseTrend? + /// Change since the previous reading, per 5 minutes. + let delta: Double? + } + + struct Device: Equatable { + let name: String + let message: String? + let state: DeviceStatusHighlightState? + /// Set when the message is the device's own status highlight, which the Now screen spells out in a notice. + var symbol: String? = nil + /// The device's lifecycle (pod, sensor) is near its end; the pill says so. + var endingSoon = false + } + + enum LoopState: Equatable { + case fresh + case stale + case failed + case never + } + + @Published private(set) var reading: Reading? + @Published private(set) var lastLoopCompleted: Date? + @Published private(set) var lastLoopFailed = false + @Published private(set) var closedLoop = false + /// Closed loop is switched on but Loop has paused it, for example while the CGM has no session or data. + @Published private(set) var closedLoopPaused = false + @Published private(set) var iob: Double? + @Published private(set) var cob: Double? + @Published private(set) var basalDeliveryState: PumpManagerStatus.BasalDeliveryState? + @Published private(set) var programmedBasalRate: Double? + @Published private(set) var scheduledBasalRate: Double? + @Published private(set) var suspended = false + @Published private(set) var targetRange: ClosedRange? + @Published private(set) var predictionTargets: [TargetBand] = [] + @Published private(set) var todayTargets: [TargetBand] = [] + @Published private(set) var prediction: [GlucosePoint] = [] + @Published private(set) var recentGlucose: [GlucosePoint] = [] + @Published private(set) var historyError: String? + @Published private(set) var glucoseHistoryError: String? + @Published private(set) var today: DayHistory + @Published private(set) var pump: Device? + @Published private(set) var cgm: Device? + @Published private(set) var dosingAvailable = true + @Published private(set) var preMealOn = false + @Published private(set) var overrideName: String? + @Published private(set) var unit: GlucoseUnitStyle + @Published var now = Date() + /// Set by StatusTableViewController, which owns the onboarding state. + var isOnboardingComplete: () -> Bool = { true } + + let provider: LoopHistoryProvider + private let deviceManager: DeviceDataManager + private let loopDataManager: LoopDataManager + private let settingsManager: SettingsManager + private let temporaryPresetsManager: TemporaryPresetsManager + private var refreshTask: Task? + private var pendingRefresh = false + + init(deviceManager: DeviceDataManager, loopDataManager: LoopDataManager, settingsManager: SettingsManager, temporaryPresetsManager: TemporaryPresetsManager) { + self.deviceManager = deviceManager + self.loopDataManager = loopDataManager + self.settingsManager = settingsManager + self.temporaryPresetsManager = temporaryPresetsManager + self.provider = LoopHistoryProvider(deviceManager: deviceManager, loopDataManager: loopDataManager, settingsManager: settingsManager, temporaryPresetsManager: temporaryPresetsManager) + self.unit = provider.unitStyle + let start = Calendar.current.startOfDay(for: Date()) + self.today = DayHistory(window: DateInterval(start: start, duration: 86400)) + } + + var basalRate: Double? { + switch basalDeliveryState { + case .tempBasal(let dose)?: + return dose.startDate <= now && now < dose.endDate ? dose.unitsPerHour : programmedBasalRate + case .active?: return programmedBasalRate + case .suspended?, .suspending?: return 0 + default: return nil + } + } + + /// The time the Loop pill counts from. Loop only completes a run when it can dose automatically, so while + /// closed loop is off or paused (for example by a manual temp basal) the pill follows the latest reading, + /// as Loop's status HUD and Live Activity do. + var loopStatusDate: Date? { + closedLoop ? lastLoopCompleted : reading?.date ?? lastLoopCompleted + } + + var loopState: LoopState { + guard let loopStatusDate else { return .never } + let age = now.timeIntervalSince(loopStatusDate) + if age <= 5 * 60 + 30 { return .fresh } + if age <= 15 * 60 || !closedLoop { return .stale } + return .failed + } + + var readingIsStale: Bool { + guard let reading else { return true } + return now.timeIntervalSince(reading.date) > LoopCoreConstants.inputDataRecencyInterval + } + + /// Refreshes everything; calls made while a refresh runs are coalesced into one more. + func refresh() { + guard refreshTask == nil else { + pendingRefresh = true + return + } + refreshTask = Task { [weak self] in + await self?.load() + guard let self else { return } + self.refreshTask = nil + if self.pendingRefresh { + self.pendingRefresh = false + self.refresh() + } + } + } + + private func load() async { + let now = Date() + self.now = now + unit = provider.unitStyle + + let displayState = await loopDataManager.algorithmDisplayState + let predicted = (displayState.output?.predictedGlucose ?? []).map(\.loopKit).map { + GlucosePoint(date: $0.startDate, mgdl: $0.quantity.doubleValue(for: .milligramsPerDeciliter)) + } + var failed = false + if let output = displayState.output, case .failure = output.recommendationResult { + failed = true + } + + let start = Calendar.current.startOfDay(for: now) + let window = DateInterval(start: start, end: Calendar.current.date(byAdding: .day, value: 1, to: start)!) + async let dayFetch = provider.dayHistory(window) + async let recentFetch = provider.glucose(DateInterval(start: now.addingTimeInterval(-3 * 3600), end: now)) + do { + let targets = try await provider.glucoseTargetBands(in: window) + today = try await dayFetch + todayTargets = targets + historyError = nil + } catch { + historyError = error.localizedDescription + } + do { + let predictionWindow = DateInterval(start: now.addingTimeInterval(-3 * 3600), end: now.addingTimeInterval(3 * 3600)) + predictionTargets = try await provider.glucoseTargetBands(in: predictionWindow) + recentGlucose = try await recentFetch + glucoseHistoryError = nil + } catch { + recentGlucose = [] + glucoseHistoryError = error.localizedDescription + } + + prediction = predicted + iob = loopDataManager.activeInsulin?.value + cob = loopDataManager.activeCarbs?.quantity.doubleValue(for: .gram) + lastLoopFailed = failed + lastLoopCompleted = loopDataManager.lastLoopCompleted + // Closed loop is on but paused while the CGM session or a manual temp basal rules out automation. + closedLoopPaused = settingsManager.dosingEnabled && deviceManager.closedLoopDisallowedLocalizedDescription != nil + closedLoop = settingsManager.dosingEnabled && !closedLoopPaused + targetRange = provider.glucoseTargetRange + + if let latest = loopDataManager.latestGlucose { + let mgdl = latest.quantity.doubleValue(for: .milligramsPerDeciliter) + let previous = recentGlucose.last { $0.date < latest.startDate.addingTimeInterval(-60) } + var delta: Double? = nil + if let previous, latest.startDate.timeIntervalSince(previous.date) <= 15 * 60 { + delta = (mgdl - previous.mgdl) / latest.startDate.timeIntervalSince(previous.date) * 300 + } + // The CGM's own trend, as the classic HUD shows it. + reading = Reading(mgdl: mgdl, date: latest.startDate, trend: deviceManager.glucoseDisplay(for: latest)?.trendType, delta: delta) + } else { + reading = nil + } + + let scheduled = temporaryPresetsManager.basalRateScheduleApplyingOverrideHistory?.value(at: now) + scheduledBasalRate = scheduled + // Presets change Loop's plan; without a temp basal the pump still delivers its programmed profile. + programmedBasalRate = settingsManager.settings.basalRateSchedule?.value(at: now) + basalDeliveryState = deviceManager.pumpManagerStatus?.basalDeliveryState + switch basalDeliveryState { + case .suspended?, .suspending?: suspended = true + default: suspended = false + } + + pump = deviceManager.pumpManager.map { manager in + device(name: manager.localizedTitle, highlight: deviceManager.pumpStatusHighlight, progress: deviceManager.pumpLifecycleProgress) + } + cgm = deviceManager.cgmManager.map { manager in + device(name: manager.localizedTitle, highlight: deviceManager.cgmStatusHighlight, progress: deviceManager.cgmLifecycleProgress) + } + + dosingAvailable = isOnboardingComplete() || deviceManager.pumpManager?.isOnboarded == true + preMealOn = temporaryPresetsManager.isPreMealTargetActive() + overrideName = preMealOn ? nil : temporaryPresetsManager.activePreset?.name + } + + private func device(name: String, highlight: DeviceStatusHighlight?, progress: DeviceLifecycleProgress?) -> Device { + if let highlight { + // Plugins wrap highlights onto two lines for the classic HUD ("Signal\nLoss"). + let message = highlight.localizedMessage.replacingOccurrences(of: "\n", with: " ") + return Device(name: name, message: message, state: highlight.state, symbol: highlight.imageName) + } + if let progress, progress.progressState == .warning || progress.progressState == .critical { + return Device(name: name, message: nil, state: progress.progressState == .critical ? .critical : .warning, endingSoon: true) + } + return Device(name: name, message: nil, state: nil) + } +} + +/// The buttons on the Now screen, wired to StatusTableViewController's existing flows. +struct NowActions { + var addCarbs: () -> Void = {} + var bolus: () -> Void = {} + var presets: () -> Void = {} + var showPrediction: () -> Void = {} + var showToday: () -> Void = {} + var showInsulin: () -> Void = {} + var showCarbs: () -> Void = {} + var pumpTapped: () -> Void = {} + var cgmTapped: () -> Void = {} + var loopStatusTapped: () -> Void = {} +} + +// MARK: - Header: title, status, hero, actions + +struct NowHeaderView: View { + @ObservedObject var model: NowModel + let actions: NowActions + + var body: some View { + VStack(alignment: .leading, spacing: LoopDesign.Space.s3) { + Text(NSLocalizedString("Now", comment: "Title at the top of the Now screen, showing current glucose and Loop status")) + .font(LoopDesign.Typeface.title) + .foregroundStyle(P.ink) + .accessibilityAddTraits(.isHeader) + statusRow + if !noticeItems.isEmpty { + notices + } + hero + actionRow + } + .padding(.horizontal, LoopDesign.Space.s4) + .padding(.top, LoopDesign.Space.s2) + .padding(.bottom, LoopDesign.Space.s2) + .frame(maxWidth: .infinity, alignment: .leading) + .background(P.surface) + .onReceive(Timer.publish(every: 30, on: .main, in: .common).autoconnect()) { model.now = $0 } + } + + // Status pills replace Loop's HUD icons with words. They wrap rather than scroll, so a device is never off-screen. + private var statusRow: some View { + FlowRow(spacing: LoopDesign.Space.s2) { + Button(action: actions.loopStatusTapped) { + StatusPill(text: loopText, dot: loopColor) + } + .accessibilityHint(NSLocalizedString("Shows when Loop last ran", comment: "VoiceOver hint for the Loop status pill and the Loop notice on the Now screen")) + Button(action: actions.pumpTapped) { + if let pump = model.pump { + StatusPill(text: pillText(pump), dot: pillColor(pump)) + } else { + StatusPill(text: NSLocalizedString("Add pump", comment: "Status pill on the Now screen when no pump is set up; tapping it starts pump setup"), dot: P.statusCritical) + } + } + .accessibilityHint(model.pump == nil + ? NSLocalizedString("Sets up a pump", comment: "VoiceOver hint for the Add pump status pill on the Now screen") + : NSLocalizedString("Opens pump settings", comment: "VoiceOver hint for the pump status pill and pump notice on the Now screen")) + Button(action: actions.cgmTapped) { + if let cgm = model.cgm { + StatusPill(text: pillText(cgm), dot: pillColor(cgm)) + } else { + StatusPill(text: NSLocalizedString("Add CGM", comment: "Status pill on the Now screen when no CGM is set up; tapping it starts CGM setup"), dot: P.statusCritical) + } + } + .accessibilityHint(model.cgm == nil + ? NSLocalizedString("Sets up a CGM", comment: "VoiceOver hint for the Add CGM status pill on the Now screen") + : NSLocalizedString("Opens CGM settings", comment: "VoiceOver hint for the CGM status pill and CGM notice on the Now screen")) + } + .buttonStyle(.plain) + } + + // A device problem or a stalled loop gets a notice in words under the pills, most serious first. + private var notices: some View { + let items = noticeItems + return VStack(spacing: LoopDesign.Space.s2) { + ForEach(items) { item in + Button(action: item.action) { + DeviceNotice(item: item) + } + .buttonStyle(.plain) + .accessibilityHint(item.hint) + } + } + } + + private var noticeItems: [DeviceNotice.Item] { + var items: [DeviceNotice.Item] = [] + if model.loopState == .failed, let last = model.lastLoopCompleted { + items.append(DeviceNotice.Item( + id: "loop", + severity: .critical, + symbol: "exclamationmark.arrow.circlepath", + title: String(format: NSLocalizedString("Loop hasn't run for %1$@", comment: "Notice title on the Now screen when Loop hasn't completed recently. (1: duration since Loop last ran, e.g. 16m)"), LoopFormat.ago(last, now: model.now)), + detail: NSLocalizedString("Insulin isn't being adjusted. Tap for details.", comment: "Notice detail on the Now screen when Loop hasn't completed recently"), + hint: NSLocalizedString("Shows when Loop last ran", comment: "VoiceOver hint for the Loop status pill and the Loop notice on the Now screen"), + action: actions.loopStatusTapped)) + } + // While suspended, Loop's own status row says so and offers Resume, so only a critical pump problem adds a notice. + if let pump = model.pump, let symbol = pump.symbol, let message = pump.message, + !model.suspended || pump.state == .critical { + let severity = DeviceNotice.Severity(pump.state) + items.append(DeviceNotice.Item( + id: "pump", + severity: severity, + symbol: symbol, + title: message, + detail: severity == .critical ? NSLocalizedString("Loop may not be giving insulin.", comment: "Notice detail on the Now screen under a critical pump problem reported by the pump") : nil, + hint: NSLocalizedString("Opens pump settings", comment: "VoiceOver hint for the pump status pill and pump notice on the Now screen"), + action: actions.pumpTapped)) + } + if let cgm = model.cgm, let symbol = cgm.symbol, let message = cgm.message { + let severity = DeviceNotice.Severity(cgm.state) + items.append(DeviceNotice.Item( + id: "cgm", + severity: severity, + symbol: symbol, + title: message, + detail: model.readingIsStale ? NSLocalizedString("Loop can't adjust insulin without readings.", comment: "Notice detail on the Now screen under a CGM problem when there is no recent glucose reading") : nil, + hint: NSLocalizedString("Opens CGM settings", comment: "VoiceOver hint for the CGM status pill and CGM notice on the Now screen"), + action: actions.cgmTapped)) + } + return items.sorted { $0.severity > $1.severity } + } + + private var loopText: String { + guard let last = model.loopStatusDate else { + if model.closedLoop { + return NSLocalizedString("Closed loop · not run yet", comment: "Status pill on the Now screen: closed loop is on but Loop has never completed") + } else if model.closedLoopPaused { + return NSLocalizedString("Closed loop paused · not run yet", comment: "Status pill on the Now screen: closed loop is switched on but paused (e.g. no CGM data), and Loop has never completed") + } else { + return NSLocalizedString("Open loop · not run yet", comment: "Status pill on the Now screen: closed loop is off and Loop has never completed") + } + } + let ago = LoopFormat.ago(last, now: model.now) + if model.loopState == .failed { + return String(format: NSLocalizedString("Loop failed · %1$@", comment: "Status pill on the Now screen: Loop hasn't completed for over 15 minutes. (1: duration since Loop last ran, e.g. 16m)"), ago) + } else if model.closedLoop { + return String(format: NSLocalizedString("Closed loop · %1$@", comment: "Status pill on the Now screen: closed loop is on and Loop last ran this long ago. (1: duration, e.g. 3m)"), ago) + } else if model.closedLoopPaused { + return String(format: NSLocalizedString("Closed loop paused · %1$@", comment: "Status pill on the Now screen: closed loop is switched on but paused (e.g. no CGM data), and Loop last ran this long ago. (1: duration, e.g. 3m)"), ago) + } else { + return String(format: NSLocalizedString("Open loop · %1$@", comment: "Status pill on the Now screen: closed loop is off (Loop recommends only) and Loop last ran this long ago. (1: duration, e.g. 3m)"), ago) + } + } + + /// Green only while closed loop is running; open loop that ran on time is neutral. + private var loopColor: Color { + switch model.loopState { + case .fresh: return model.closedLoop ? P.statusAutomated : model.closedLoopPaused ? P.statusWarning : P.inkMuted + case .stale: return P.statusWarning + case .failed, .never: return P.statusCritical + } + } + + /// A highlight (always a plugin message with a symbol) is spelled out in its notice, so its pill keeps to the device name. + private func pillText(_ device: NowModel.Device) -> String { + guard device.symbol == nil else { return device.name } + if device.endingSoon { + return String(format: NSLocalizedString("%1$@ · ending soon", comment: "Status pill on the Now screen when a pump pod or CGM sensor is near the end of its life. (1: device name from the pump or CGM plugin, e.g. Omnipod 5)"), device.name) + } + return device.name + } + + private func pillColor(_ device: NowModel.Device) -> Color? { + switch device.state { + case .critical?: return P.statusCritical + case .warning?: return P.statusWarning + default: return device.symbol == nil ? nil : P.inkMuted + } + } + + /// The reading and where Loop expects it to go are one object: the number, then its last three hours and + /// Loop's next three, then what's on board. + private var hero: some View { + VStack(alignment: .leading, spacing: 0) { + HStack(alignment: .top) { + VStack(alignment: .leading, spacing: 2) { + HStack(alignment: .center, spacing: LoopDesign.Space.s2) { + if let reading = model.reading, !model.readingIsStale { + Text(model.unit.format(reading.mgdl)) + .font(LoopDesign.Typeface.glucoseHero) + .foregroundStyle(P.ink) + .lineLimit(1) + .minimumScaleFactor(0.6) + .contentTransition(.numericText()) + if let trend = reading.trend { + Image(systemName: Self.symbol(for: trend)) + .font(.system(size: 30, weight: .bold)) + .foregroundStyle(P.glucose) + .accessibilityLabel(trend.localizedDescription) + } + } else { + Text(NSLocalizedString("No reading", comment: "Shown on the Now screen in place of the glucose value when there is no recent CGM reading")) + .font(.system(size: 34, weight: .bold, design: .rounded)) + .foregroundStyle(P.inkMuted) + } + } + Text(readingDetail) + .font(LoopDesign.Typeface.subhead) + .foregroundStyle(P.inkMuted) + if let rangePill { + StatusPill(text: rangePill.0, dot: rangePill.1) + .padding(.top, LoopDesign.Space.s1) + } + } + Spacer(minLength: LoopDesign.Space.s2) + eventually + .padding(.top, LoopDesign.Space.s3) + } + .accessibilityElement(children: .combine) + .padding([.horizontal, .top], LoopDesign.Space.s4) + + Button(action: actions.showPrediction) { + Group { + if recentReadings.isEmpty && model.prediction.isEmpty { + ChartPlaceholder(message: model.glucoseHistoryError == nil + ? NSLocalizedString("No CGM data in the last 3 hours", comment: "Empty prediction chart on the Now screen") + : NSLocalizedString("Couldn't load recent CGM readings", comment: "Prediction chart on the Now screen when recent glucose couldn't be read"), + height: 120) + } else { + PredictionChartView(readings: recentReadings, prediction: model.prediction, unit: model.unit, + targetBands: model.predictionTargets, now: model.now, height: 132) + } + } + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .accessibilityHint(NSLocalizedString("Opens Loop's prediction breakdown", comment: "VoiceOver hint for the prediction card on the Now screen")) + .padding(.horizontal, LoopDesign.Space.s4) + .padding(.top, LoopDesign.Space.s3) + if let error = model.glucoseHistoryError { + Text(String(format: NSLocalizedString("Recent readings unavailable: %1$@", comment: "Error under the prediction chart on the Now screen. (1: system error description)"), error)) + .font(LoopDesign.Typeface.footnote) + .foregroundStyle(P.statusCritical) + .padding(.horizontal, LoopDesign.Space.s4) + .padding(.top, LoopDesign.Space.s2) + } + + Rectangle().fill(P.separator.opacity(0.5)).frame(height: 0.5) + .padding(.top, LoopDesign.Space.s3) + onBoard + } + .background(P.surfaceRaised, in: RoundedRectangle(cornerRadius: LoopDesign.Radius.lg, style: .continuous)) + .opacity(model.readingIsStale && model.reading != nil ? 0.7 : 1) + } + + private var recentReadings: [GlucosePoint] { + model.recentGlucose.filter { $0.date >= model.now.addingTimeInterval(-3 * 3600) } + } + + /// Where Loop expects glucose to end up, with the target it's aiming for under it. + private var eventually: some View { + VStack(alignment: .trailing, spacing: 2) { + if let last = model.prediction.last { + Text(NSLocalizedString("Eventually", comment: "Label over Loop's eventual predicted glucose on the Now screen")) + .font(LoopDesign.Typeface.footnote) + .foregroundStyle(P.inkMuted) + Text(model.unit.format(last.mgdl)) + .font(.system(size: 24, weight: .semibold, design: .rounded).monospacedDigit()) + .foregroundStyle(P.ink) + } + if let target = model.targetRange { + Text(targetText(target)) + .font(LoopDesign.Typeface.footnote) + .foregroundStyle(P.inkMuted) + } + } + .multilineTextAlignment(.trailing) + } + + private func targetText(_ target: ClosedRange) -> String { + let low = model.unit.format(target.lowerBound), high = model.unit.format(target.upperBound) + return low == high + ? String(format: NSLocalizedString("Target %1$@", comment: "Glucose target on the Now screen hero card when the target range is a single value. (1: glucose value)"), low) + : String(format: NSLocalizedString("Target %1$@–%2$@", comment: "Glucose target range on the Now screen hero card. (1: lower bound; 2: upper bound)"), low, high) + } + + /// IOB, COB and basal as one strip under the chart. Insulin and carbs open their history, as on the classic charts. + private var onBoard: some View { + AdaptiveRow(spacing: 0) { + Button(action: actions.showInsulin) { + stat(NSLocalizedString("IOB", comment: "Abbreviation for insulin on board; label of a tile on the Now screen"), + value: model.iob.map(LoopFormat.doseUnits) ?? "–", color: P.insulin) + } + .buttonStyle(.plain) + .accessibilityHint(NSLocalizedString("Opens insulin delivery history", comment: "VoiceOver hint for the IOB tile on the Now screen")) + statDivider + Button(action: actions.showCarbs) { + stat(NSLocalizedString("COB", comment: "Abbreviation for carbs on board; label of a tile on the Now screen"), + value: model.cob.map(LoopFormat.grams) ?? "–", color: P.carbs) + } + .buttonStyle(.plain) + .accessibilityHint(NSLocalizedString("Opens carb absorption", comment: "VoiceOver hint for the COB tile on the Now screen")) + statDivider + stat(NSLocalizedString("Basal", comment: "Label of a tile showing the current basal rate (Now screen) or the day's basal insulin total (Today so far totals)"), + value: model.basalRate.map { LoopFormat.number($0, decimals: 2) } ?? "–", unit: NSLocalizedString("U/h", comment: "Abbreviation for insulin units per hour"), + color: P.ink, detail: basalDetail) + } + .fixedSize(horizontal: false, vertical: true) + } + + private var basalDetail: (String, Color)? { + if model.suspended { + return (NSLocalizedString("Suspended", comment: "Shown in the Basal tile on the Now screen when insulin delivery is suspended"), P.statusCritical) + } + if let rate = model.basalRate, let scheduled = model.scheduledBasalRate { + return (String(format: NSLocalizedString("%1$@ vs plan", comment: "Basal tile on the Now screen: how the current basal rate differs from the scheduled rate. (1: signed difference in U/h, e.g. +0.25)"), LoopFormat.signed(rate - scheduled)), P.inkMuted) + } + return nil + } + + private var statDivider: some View { + Rectangle().fill(P.separator.opacity(0.5)).frame(width: 0.5).padding(.vertical, LoopDesign.Space.s3) + } + + private func stat(_ label: String, value: String, unit: String? = nil, color: Color, detail: (String, Color)? = nil) -> some View { + VStack(alignment: .leading, spacing: 2) { + Text(label) + .font(LoopDesign.Typeface.footnote) + .foregroundStyle(P.inkMuted) + HStack(alignment: .firstTextBaseline, spacing: 2) { + Text(value) + .font(LoopDesign.Typeface.statValueSmall) + .foregroundStyle(color) + if let unit { + Text(unit) + .font(LoopDesign.Typeface.footnote) + .foregroundStyle(P.inkMuted) + } + } + .lineLimit(1) + .minimumScaleFactor(0.6) + if let detail { + Text(detail.0) + .font(LoopDesign.Typeface.caption.weight(.medium)) + .foregroundStyle(detail.1) + .lineLimit(1) + .minimumScaleFactor(0.8) + } + } + .padding(.horizontal, LoopDesign.Space.s4) + .padding(.vertical, LoopDesign.Space.s3) + .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading) + .contentShape(Rectangle()) + .accessibilityElement(children: .combine) + } + + private var readingDetail: String { + guard let reading = model.reading else { return model.unit.unitName } + if model.readingIsStale { + return String(format: NSLocalizedString("Last reading %1$@ ago", comment: "Shown on the Now screen under No reading when the latest CGM reading is too old. (1: duration, e.g. 25m)"), LoopFormat.ago(reading.date, now: model.now)) + } + guard let delta = reading.delta else { return model.unit.unitName } + let change = model.unit.isMmol ? LoopFormat.signed(delta / GlucoseUnitStyle.mgdlPerMmol, decimals: 1) : LoopFormat.signed(delta, decimals: 0) + return String(format: NSLocalizedString("%1$@ · %2$@ in 5 min", comment: "Under the glucose value on the Now screen: the glucose unit and how much glucose changed over 5 minutes. (1: glucose unit, e.g. mmol/L; 2: signed change, e.g. +0.3)"), model.unit.unitName, change) + } + + /// Low and high get a pill with words; the number itself is never tinted. + private var rangePill: (String, Color)? { + guard let reading = model.reading, !model.readingIsStale else { return nil } + if reading.mgdl < 54 { return (NSLocalizedString("Urgent low", comment: "Pill under the glucose value on the Now screen when glucose is below 54 mg/dL (3.0 mmol/L)"), P.statusCritical) } + if reading.mgdl < 70 { return (NSLocalizedString("Low", comment: "Pill under the glucose value on the Now screen when glucose is below 70 mg/dL (3.9 mmol/L)"), P.statusCritical) } + if reading.mgdl > 250 { return (NSLocalizedString("High", comment: "Pill under the glucose value on the Now screen when glucose is above 250 mg/dL (13.9 mmol/L)"), P.statusWarning) } + return nil + } + + static func symbol(for trend: GlucoseTrend) -> String { + switch trend { + case .upUpUp: return "arrow.up.to.line" + case .upUp: return "chevron.up.2" + case .up: return "arrow.up" + case .flat: return "arrow.right" + case .down: return "arrow.down" + case .downDown: return "chevron.down.2" + case .downDownDown: return "arrow.down.to.line" + } + } + + /// Tinted rather than solid, so the reading stays the loudest thing on the screen. + private var actionRow: some View { + AdaptiveRow { + Button(action: actions.addCarbs) { + actionLabel(NSLocalizedString("Add carbs", comment: "Button on the Now screen that opens carb entry"), systemImage: "fork.knife", tint: P.carbs, ink: P.ink) + } + .buttonStyle(.plain) + .disabled(!model.dosingAvailable) + .opacity(model.dosingAvailable ? 1 : 0.4) + Button(action: actions.bolus) { + actionLabel(NSLocalizedString("Bolus", comment: "Button on the Now screen that opens the bolus screen"), systemImage: "syringe.fill", tint: P.insulin, ink: P.ink) + } + .buttonStyle(.plain) + .disabled(!model.dosingAvailable) + .opacity(model.dosingAvailable ? 1 : 0.4) + // Pre-meal and the other presets share Loop's Presets screen. + Button(action: actions.presets) { + actionLabel(presetsTitle, systemImage: presetsActive ? "slider.horizontal.below.square.filled.and.square" : "slider.horizontal.3", + tint: presetsActive ? P.accent : P.inkMuted, ink: P.ink) + } + .buttonStyle(.plain) + .accessibilityLabel(NSLocalizedString("Presets", comment: "Button on the Now screen that opens override presets (and pre-meal); also its VoiceOver label and menu item")) + .accessibilityValue(presetsActive ? presetsTitle : "") + } + .fixedSize(horizontal: false, vertical: true) + } + + private var presetsActive: Bool { + model.preMealOn || model.overrideName != nil + } + + private var presetsTitle: String { + if model.preMealOn { return NSLocalizedString("Pre-meal on", comment: "Presets button title on the Now screen while the pre-meal target is on") } + if let name = model.overrideName { return name } + return NSLocalizedString("Presets", comment: "Button on the Now screen that opens override presets (and pre-meal); also its VoiceOver label and menu item") + } + + private func actionLabel(_ title: String, systemImage: String, tint: Color, ink: Color) -> some View { + // Longer languages ("Agregar carbohidratos") wrap onto a second line rather than truncate. + VStack(spacing: 4) { + Image(systemName: systemImage) + .font(.system(size: 18, weight: .semibold)) + .foregroundStyle(tint) + .accessibilityHidden(true) + Text(title) + .font(LoopDesign.Typeface.subhead.weight(.semibold)) + .lineLimit(2) + .multilineTextAlignment(.center) + .minimumScaleFactor(0.8) + .allowsTightening(true) + } + .foregroundStyle(ink) + .padding(.horizontal, LoopDesign.Space.s1) + .padding(.vertical, LoopDesign.Space.s3) + .frame(maxWidth: .infinity, minHeight: 64, maxHeight: .infinity) + .background(tint.opacity(0.16), in: RoundedRectangle(cornerRadius: LoopDesign.Radius.lg, style: .continuous)) + .contentShape(RoundedRectangle(cornerRadius: LoopDesign.Radius.lg, style: .continuous)) + } +} + +// MARK: - Charts: next 3 hours and today so far + +struct NowChartsView: View { + @ObservedObject var model: NowModel + let actions: NowActions + + var body: some View { + VStack(spacing: LoopDesign.Space.s4) { + todayCard + } + .padding(.horizontal, LoopDesign.Space.s4) + .padding(.top, LoopDesign.Space.s2) + .padding(.bottom, LoopDesign.Space.s6) + .frame(maxWidth: .infinity) + .background(P.surface) + } + + private var todayCard: some View { + Button(action: actions.showToday) { + if let error = model.historyError { + LoopCard { + CardHeader(title: DayTimelineCard.todayTitle) + ChartPlaceholder(message: String(format: NSLocalizedString("Couldn't load today's history: %1$@", comment: "Shown on the Now screen's Today so far card when history couldn't be read. (1: system error description)"), error)) + } + } else { + DayTimelineCard(title: DayTimelineCard.todayTitle, history: model.today, unit: model.unit, targetBands: model.todayTargets, + now: model.now, height: 230) + } + } + .buttonStyle(.plain) + .accessibilityHint(NSLocalizedString("Opens the full day", comment: "VoiceOver hint for the Today so far card on the Now screen")) + } +} + +/// One problem in words: what the device or Loop reports, what it means, and where to go. +struct DeviceNotice: View { + enum Severity: Int, Comparable { + case info, warning, critical + + init(_ state: DeviceStatusHighlightState?) { + switch state { + case .critical?: self = .critical + case .warning?: self = .warning + default: self = .info + } + } + + static func < (lhs: Severity, rhs: Severity) -> Bool { lhs.rawValue < rhs.rawValue } + } + + struct Item: Identifiable { + let id: String + let severity: Severity + let symbol: String + let title: String + let detail: String? + let hint: String + let action: () -> Void + } + + let item: Item + + private var tint: Color { + switch item.severity { + case .critical: return P.statusCritical + case .warning: return P.statusWarning + case .info: return P.inkMuted + } + } + + var body: some View { + HStack(alignment: .center, spacing: LoopDesign.Space.s3) { + Image(systemName: item.symbol) + .font(.system(size: 20, weight: .semibold)) + .foregroundStyle(item.severity == .critical ? P.statusCritical : tint) + .frame(width: 24) + .accessibilityHidden(true) + VStack(alignment: .leading, spacing: 2) { + Text(item.title) + .font(LoopDesign.Typeface.headline) + .foregroundStyle(item.severity == .critical ? P.statusCritical : P.ink) + if let detail = item.detail { + Text(detail) + .font(LoopDesign.Typeface.subhead) + .foregroundStyle(P.ink) + .fixedSize(horizontal: false, vertical: true) + } + } + Spacer(minLength: 0) + Image(systemName: "chevron.right") + .font(.footnote.weight(.semibold)) + .foregroundStyle(P.inkMuted) + .accessibilityHidden(true) + } + .padding(LoopDesign.Space.s3) + .frame(maxWidth: .infinity, alignment: .leading) + .background(tint.opacity(item.severity == .info ? 0.12 : 0.16), in: RoundedRectangle(cornerRadius: LoopDesign.Radius.lg, style: .continuous)) + .overlay( + RoundedRectangle(cornerRadius: LoopDesign.Radius.lg, style: .continuous) + .strokeBorder(tint.opacity(item.severity == .info ? 0 : 0.45), lineWidth: 1) + ) + .contentShape(Rectangle()) + .accessibilityElement(children: .combine) + } +} + +/// Lays its children out left to right and starts a new line when the next one won't fit. +struct FlowRow: Layout { + var spacing: CGFloat = 8 + + func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize { + let rows = arrange(width: proposal.width ?? .infinity, subviews: subviews) + let width = rows.map { $0.width }.max() ?? 0 + let height = rows.map { $0.height }.reduce(0, +) + spacing * CGFloat(max(rows.count - 1, 0)) + return CGSize(width: proposal.width ?? width, height: height) + } + + func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) { + var y = bounds.minY + for row in arrange(width: bounds.width, subviews: subviews) { + var x = bounds.minX + for index in row.indices { + let size = subviews[index].sizeThatFits(ProposedViewSize(width: bounds.width, height: nil)) + subviews[index].place(at: CGPoint(x: x, y: y), proposal: ProposedViewSize(width: min(size.width, bounds.width), height: size.height)) + x += min(size.width, bounds.width) + spacing + } + y += row.height + spacing + } + } + + private struct Row { + var indices: [Int] = [] + var width: CGFloat = 0 + var height: CGFloat = 0 + } + + private func arrange(width: CGFloat, subviews: Subviews) -> [Row] { + var rows: [Row] = [] + var row = Row() + for index in subviews.indices { + let size = subviews[index].sizeThatFits(ProposedViewSize(width: width, height: nil)) + let itemWidth = min(size.width, width) + if !row.indices.isEmpty && row.width + spacing + itemWidth > width { + rows.append(row) + row = Row() + } + row.width += (row.indices.isEmpty ? 0 : spacing) + itemWidth + row.height = max(row.height, size.height) + row.indices.append(index) + } + if !row.indices.isEmpty { rows.append(row) } + return rows + } +} + +// MARK: - Loop status sheet + +/// What the Loop pill opens: whether Loop is adjusting insulin, when it last ran, and each of its runs over the last +/// two hours, so a gap or a run of failures shows at a glance. The words are Loop's own status copy. +struct LoopStatusSheet: View { + let viewModel: LoopStatusModalViewModel + let provider: LoopHistoryProvider + let openSettings: () -> Void + let done: () -> Void + + @Environment(\.appName) private var appName + @Environment(\.loopStatusColorPalette) private var loopStatusColors + @State private var runs: [LoopHistoryMath.LoopRun]? + @State private var now = Date() + + private static let slot: TimeInterval = 5 * 60 + private static let slots = 24 + + private var deviceIssue: Bool { + viewModel.isCGMInoperable || viewModel.isPumpInoperable || viewModel.hasBluetoothIssue + } + + var body: some View { + let copy = viewModel.copy(appName: appName) + NavigationStack { + ScrollView { + VStack(alignment: .leading, spacing: LoopDesign.Space.s6) { + HStack(alignment: .center, spacing: LoopDesign.Space.s4) { + LoopCircleView(closedLoop: viewModel.loopIconClosed, freshness: viewModel.freshness, deviceIssue: deviceIssue) + .environment(\.loopStatusColorPalette, loopStatusColors) + .frame(width: 56, height: 56) + .accessibilityHidden(true) + VStack(alignment: .leading, spacing: 2) { + Text(copy.title) + .font(LoopDesign.Typeface.headline) + .foregroundStyle(P.ink) + .accessibilityAddTraits(.isHeader) + if let last = viewModel.lastLoopCompleted { + Text(lastRunText(last)) + .font(LoopDesign.Typeface.subhead) + .foregroundStyle(viewModel.freshness == .fresh ? P.inkMuted : P.statusCritical) + } + } + } + runStrip + Text(copy.message) + .font(LoopDesign.Typeface.body) + .foregroundStyle(P.ink) + .fixedSize(horizontal: false, vertical: true) + if copy.message.contains(viewModel.localizedSettingsWord) { + Button(action: openSettings) { + Text(NSLocalizedString("Open Settings", comment: "Loop status sheet button that opens Loop's settings")) + .font(LoopDesign.Typeface.subhead.weight(.semibold)) + .foregroundStyle(P.accent) + .frame(maxWidth: .infinity, minHeight: 48) + .background(P.accent.opacity(0.14), in: RoundedRectangle(cornerRadius: LoopDesign.Radius.lg, style: .continuous)) + } + .buttonStyle(.plain) + } + } + .padding(LoopDesign.Space.s4) + } + .background(P.surface) + .navigationTitle(NSLocalizedString("Loop", comment: "Title of the Loop status sheet opened from the Loop pill on the Now screen")) + .navigationBarTitleDisplayMode(.inline) + .toolbar { + ToolbarItem(placement: .confirmationAction) { + Button(NSLocalizedString("Done", comment: "Button to close the Loop status sheet"), action: done) + } + } + } + .task { + now = Date() + let start = now.addingTimeInterval(-Double(Self.slots) * Self.slot) + runs = (try? await provider.loopRuns().runs.filter { $0.date >= start }) ?? [] + } + } + + private func lastRunText(_ last: Date) -> String { + guard let ago = viewModel.lastLoopCompletedFormattedTime, (viewModel.ago ?? 0) >= 60 else { + return String(format: NSLocalizedString("Last ran at %1$@", comment: "Loop status sheet: when Loop last completed a run, under a minute ago. (1: time of day)"), LoopFormat.time(last)) + } + return String(format: NSLocalizedString("Last ran at %1$@, %2$@", comment: "Loop status sheet: when Loop last completed a run. (1: time of day; 2: how long ago, e.g. 3 min ago)"), LoopFormat.time(last), ago) + } + + /// One mark per five minutes: green where a run completed, red where one failed, empty where none ran. + private var runStrip: some View { + let start = now.addingTimeInterval(-Double(Self.slots) * Self.slot) + let marks: [Bool?] = (0..= from && $0.date < from.addingTimeInterval(Self.slot) } + if inSlot.isEmpty { return nil } + return inSlot.contains { $0.succeeded } + } + let completed = marks.filter { $0 == true }.count + return VStack(alignment: .leading, spacing: LoopDesign.Space.s2) { + HStack(alignment: .firstTextBaseline) { + Text(NSLocalizedString("Last 2 hours", comment: "Loop status sheet: title over the strip of Loop's runs in the last two hours")) + .font(LoopDesign.Typeface.subhead.weight(.semibold)) + .foregroundStyle(P.ink) + Spacer() + if runs != nil { + Text(String(format: NSLocalizedString("%1$lld of %2$lld runs completed", comment: "Loop status sheet: how many five-minute slots in the last two hours had a completed Loop run. (1: completed; 2: slots, 24)"), completed, Self.slots)) + .font(LoopDesign.Typeface.footnote.monospacedDigit()) + .foregroundStyle(P.inkMuted) + } + } + HStack(spacing: 3) { + ForEach(Array(marks.enumerated()), id: \.offset) { _, mark in + Capsule() + .fill(mark == true ? P.statusAutomated : mark == false ? P.statusCritical : P.inkMuted.opacity(0.3)) + .frame(height: mark == nil ? 6 : 28) + .frame(maxWidth: .infinity, maxHeight: 28, alignment: .bottom) + } + } + .redacted(reason: runs == nil ? .placeholder : []) + HStack { + Text(LoopFormat.time(start)) + Spacer() + Text(NSLocalizedString("now", comment: "Prediction chart x-axis label marking the current time")) + } + .font(LoopDesign.Typeface.caption) + .foregroundStyle(P.inkMuted) + } + .padding(LoopDesign.Space.s4) + .background(P.surfaceRaised, in: RoundedRectangle(cornerRadius: LoopDesign.Radius.lg, style: .continuous)) + .accessibilityElement(children: .ignore) + .accessibilityLabel(String(format: NSLocalizedString("%1$lld of %2$lld runs completed", comment: "Loop status sheet: how many five-minute slots in the last two hours had a completed Loop run. (1: completed; 2: slots, 24)"), completed, Self.slots)) + } +} diff --git a/Loop/Redesign/TrendsComponents.swift b/Loop/Redesign/TrendsComponents.swift new file mode 100644 index 0000000000..250b969151 --- /dev/null +++ b/Loop/Redesign/TrendsComponents.swift @@ -0,0 +1,991 @@ +// +// TrendsComponents.swift +// Loop +// +// Copyright © 2026 LoopKit Authors. All rights reserved. +// + +import SwiftUI +import Charts + +private typealias P = LoopDesign.Palette + +// MARK: - RangeSelector + +enum TrendsPeriod: Int, CaseIterable, Identifiable { + case day = 1 + case week = 7 + case twoWeeks = 14 + case month = 30 + case quarter = 90 + + var id: Int { rawValue } + + var label: String { + self == .day + ? NSLocalizedString("Day (Trends period)", value: "Day", comment: "Trends period picker: a period of one calendar day (not daytime)") + : String(format: NSLocalizedString("%1$@ d", comment: "Trends period picker, short label for a period of several days, e.g. 7 d. (1: number of days)"), + LoopFormat.number(Double(rawValue), decimals: 0)) + } + + var accessibilityName: String { + self == .day + ? NSLocalizedString("Day (Trends period)", value: "Day", comment: "Trends period picker: a period of one calendar day (not daytime)") + : String.localizedStringWithFormat(NSLocalizedString("%lld days", comment: "Trends period picker, VoiceOver name for a period of several days. (1: number of days)"), rawValue) + } + + /// The period ending on `endDay` (inclusive), cut off at `now` when it ends today. + func interval(endingOn endDay: Date, now: Date = Date(), calendar: Calendar = .current) -> DateInterval { + let endOfDay = calendar.date(byAdding: .day, value: 1, to: calendar.startOfDay(for: endDay))! + let start = calendar.date(byAdding: .day, value: -rawValue, to: endOfDay)! + return DateInterval(start: start, end: min(endOfDay, now)) + } +} + +struct RangeSelectorView: View { + @Binding var period: TrendsPeriod + @Binding var endDay: Date + var now: Date = Date() + + private var calendar: Calendar { .current } + + private var canStepForward: Bool { + !calendar.isDate(endDay, inSameDayAs: now) && endDay < now + } + + var body: some View { + VStack(spacing: LoopDesign.Space.s3) { + Picker(NSLocalizedString("Period", comment: "Trends: VoiceOver label of the picker that chooses how many days the screen covers"), + selection: $period.animation(.snappy(duration: 0.2))) { + ForEach(TrendsPeriod.allCases) { option in + Text(option.label) + .accessibilityLabel(option.accessibilityName) + .tag(option) + } + } + .pickerStyle(.segmented) + + HStack { + StepButton(systemName: "chevron.left", label: NSLocalizedString("Previous period", comment: "VoiceOver label for the Trends button that moves back one period")) { step(-1) } + Spacer() + Text(LoopFormat.range(period.interval(endingOn: endDay, now: now).start, endDay)) + .font(LoopDesign.Typeface.headline.monospacedDigit()) + .foregroundStyle(P.ink) + Spacer() + StepButton(systemName: "chevron.right", label: NSLocalizedString("Next period", comment: "VoiceOver label for the Trends button that moves forward one period"), enabled: canStepForward) { step(1) } + } + } + } + + private func step(_ direction: Int) { + guard let next = calendar.date(byAdding: .day, value: direction * period.rawValue, to: endDay) else { return } + endDay = min(next, now) + } +} + +// MARK: - StatGrid + +struct StatTile: Identifiable { + let label: String + let value: String + let unit: String? + let detail: String? + var valueColor: Color = LoopDesign.Palette.ink + /// The consensus target for the figure, e.g. "aim < 7%". + var aim: String? = nil + /// When the figure is less representative than usual, e.g. GMI over a short period. + var caveat: String? = nil + var id: String { label } +} + +struct StatGridView: View { + @Environment(\.dynamicTypeSize) private var typeSize + let tiles: [StatTile] + + /// Pairs of tiles, so both tiles in a row take the taller one's height; one per row at accessibility sizes. + private var rows: [[StatTile]] { + let shown = Array(tiles.prefix(6)) + let perRow = typeSize.isAccessibilitySize ? 1 : 2 + return stride(from: 0, to: shown.count, by: perRow).map { Array(shown[$0.. some View { + VStack(alignment: .leading, spacing: 2) { + Text(tile.label) + .font(LoopDesign.Typeface.footnote) + .foregroundStyle(P.inkMuted) + HStack(alignment: .firstTextBaseline, spacing: 2) { + Text(tile.value) + .font(LoopDesign.Typeface.statValue) + .foregroundStyle(tile.valueColor) + .minimumScaleFactor(0.7) + .lineLimit(1) + if let unit = tile.unit { + Text(unit) + .font(LoopDesign.Typeface.footnote) + .foregroundStyle(P.inkMuted) + } + } + if let detail = tile.detail { + // Not capped: a detail can run to two lines of its own, which wrap again at large sizes. + Text(detail) + .font(LoopDesign.Typeface.footnote) + .foregroundStyle(P.inkMuted) + .fixedSize(horizontal: false, vertical: true) + } + if let aim = tile.aim { + Text(aim) + .font(LoopDesign.Typeface.footnote) + .foregroundStyle(P.inkMuted) + } + if let caveat = tile.caveat { + Text(caveat) + .font(LoopDesign.Typeface.caption) + .foregroundStyle(P.inkMuted) + .fixedSize(horizontal: false, vertical: true) + } + } + .padding(LoopDesign.Space.s3) + .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading) + .background(P.surfaceSunken, in: RoundedRectangle(cornerRadius: LoopDesign.Radius.md, style: .continuous)) + .accessibilityElement(children: .combine) + } +} + +// MARK: - TimeInRange + +extension GlucoseBand { + /// The band's name in the user's language. + var localizedName: String { + switch self { + case .veryHigh: return NSLocalizedString("Very high", comment: "Time in range band: glucose above 250 mg/dL (13.9 mmol/L)") + case .high: return NSLocalizedString("High", comment: "Time in range band: glucose 181–250 mg/dL (10.1–13.9 mmol/L)") + case .target: return NSLocalizedString("In range", comment: "Time in range band: glucose 70–180 mg/dL (3.9–10.0 mmol/L)") + case .low: return NSLocalizedString("Low", comment: "Time in range band: glucose 54–69 mg/dL (3.0–3.8 mmol/L)") + case .veryLow: return NSLocalizedString("Very low", comment: "Time in range band: glucose below 54 mg/dL (3.0 mmol/L)") + } + } + + /// The consensus target for the band. High and low are aims for all time above or below range, + /// so they say so; the others are the band's own. + var localizedTarget: String { + switch self { + case .veryHigh: return ConsensusTarget.under(5) + case .high: return String(format: NSLocalizedString("%1$@ above range", comment: "Time in range High row: the consensus target for all time above range, high and very high together. (1: target, e.g. < 25%)"), ConsensusTarget.under(25)) + case .target: return ConsensusTarget.over(70) + case .low: return String(format: NSLocalizedString("%1$@ below range", comment: "Time in range Low row: the consensus target for all time below range, low and very low together. (1: target, e.g. < 4%)"), ConsensusTarget.under(4)) + case .veryLow: return ConsensusTarget.under(1) + } + } + + /// Consensus thresholds with the user's decimal separator, e.g. "3,9–10,0". + func localizedThresholds(_ unit: GlucoseUnitStyle) -> String { + let decimals = unit.isMmol ? 1 : 0 + let n: (Double) -> String = { LoopFormat.number($0, decimals: decimals) } + switch (self, unit.isMmol) { + case (.veryHigh, true): return "> " + n(13.9) + case (.high, true): return n(10.1) + "–" + n(13.9) + case (.target, true): return n(3.9) + "–" + n(10.0) + case (.low, true): return n(3.0) + "–" + n(3.8) + case (.veryLow, true): return "< " + n(3.0) + case (.veryHigh, false): return "> " + n(250) + case (.high, false): return n(181) + "–" + n(250) + case (.target, false): return n(70) + "–" + n(180) + case (.low, false): return n(54) + "–" + n(69) + case (.veryLow, false): return "< " + n(54) + } + } +} + +/// "12%" in the user's language. +private func percentText(_ value: Double, decimals: Int = 0) -> String { + String(format: NSLocalizedString("%1$@%%", comment: "A percentage. (1: number)"), LoopFormat.number(value, decimals: decimals)) +} + +/// The international consensus targets for CGM metrics, written as "< 4%", "> 70%" or "≤ 36%". +enum ConsensusTarget { + static func under(_ percent: Double) -> String { "< " + percentText(percent) } + static func over(_ percent: Double) -> String { "> " + percentText(percent) } + static func atMost(_ percent: Double) -> String { "≤ " + percentText(percent) } + static func percent(_ percent: Double) -> String { percentText(percent) } + + /// "aim < 7%", under a figure. + static func aim(_ target: String) -> String { + String(format: NSLocalizedString("aim %1$@", comment: "Trends: the consensus target under a figure, in lower case. (1: target, e.g. < 7%)"), target) + } +} + +struct TimeInRangeView: View { + @Environment(\.dynamicTypeSize) private var typeSize + + /// Fractions per band, 0–1, of the time with CGM readings. + let fractions: [GlucoseBand: Double] + /// Hours a day with CGM readings, so a band's hours leave out time without them. + let hoursPerDay: Double + let unit: GlucoseUnitStyle + + private var percentages: [GlucoseBand: Int] { LoopHistoryMath.roundedPercentages(fractions) } + + /// Highest band first, as the bar is drawn. + private static let ladder = Array(GlucoseBand.allCases.reversed()) + + var body: some View { + HStack(alignment: .top, spacing: LoopDesign.Space.s4) { + bar + .frame(width: 14) + VStack(alignment: .leading, spacing: LoopDesign.Space.s2) { + ForEach(Self.ladder, id: \.self) { band in + row(band) + } + } + } + .fixedSize(horizontal: false, vertical: true) + } + + private var bar: some View { + GeometryReader { geometry in + let minimum: CGFloat = 4 + let bands = Self.ladder + let raw = bands.map { CGFloat(fractions[$0] ?? 0) } + let floors = raw.map { $0 > 0 ? max(minimum, $0 * geometry.size.height) : 0 } + let spare = geometry.size.height - floors.reduce(0, +) + // Trim the space the minimums borrowed from the largest band. + let largest = raw.indices.max { raw[$0] < raw[$1] } ?? 2 + VStack(spacing: 1) { + ForEach(Array(bands.enumerated()), id: \.offset) { index, band in + let height = index == largest ? max(0, floors[index] + spare) : floors[index] + if height > 0 { + Rectangle().fill(band.agpColor).frame(height: max(0, height - 1)) + } + } + } + .clipShape(Capsule()) + } + .accessibilityHidden(true) + } + + private func row(_ band: GlucoseBand) -> some View { + let fraction = fractions[band] ?? 0 + let hours = fraction * hoursPerDay + let hoursText = String(format: NSLocalizedString("%1$@ h", comment: "Time in range row: average hours a day spent in the band, abbreviated. (1: hours with one decimal)"), + LoopFormat.number(hours, decimals: 1)) + let percent = Text(percentText(Double(percentages[band] ?? 0))) + .font(LoopDesign.Typeface.statValueSmall) + .foregroundStyle(P.ink) + let name = Text(band.localizedName) + .font(LoopDesign.Typeface.subhead) + .foregroundStyle(P.ink) + return Group { + if typeSize.isAccessibilitySize { + // One figure per line, so nothing is squeezed into a column. + VStack(alignment: .leading, spacing: 0) { + HStack(alignment: .firstTextBaseline, spacing: LoopDesign.Space.s2) { + percent + name + } + Text(verbatim: "\(band.localizedThresholds(unit)) · \(hoursText) · \(band.localizedTarget)") + .font(LoopDesign.Typeface.footnote) + .foregroundStyle(P.inkMuted) + .fixedSize(horizontal: false, vertical: true) + } + .frame(maxWidth: .infinity, alignment: .leading) + } else { + HStack(alignment: .firstTextBaseline, spacing: LoopDesign.Space.s2) { + percent.frame(minWidth: 52, alignment: .trailing) + name + Text(band.localizedThresholds(unit)) + .font(LoopDesign.Typeface.footnote) + .foregroundStyle(P.inkMuted) + Spacer(minLength: LoopDesign.Space.s1) + VStack(alignment: .trailing, spacing: 0) { + Text(hoursText) + .font(LoopDesign.Typeface.footnote.monospacedDigit()) + Text(band.localizedTarget) + .font(LoopDesign.Typeface.caption) + } + .foregroundStyle(P.inkMuted) + } + } + } + .accessibilityElement(children: .ignore) + .accessibilityLabel(String(format: NSLocalizedString("%1$@, %2$@ %3$@: %4$@ percent, %5$@ hours a day", comment: "VoiceOver label for a Time in range row. (1: band name, e.g. In range, 2: glucose thresholds, e.g. 3.9–10.0, 3: glucose unit, 4: percentage number, 5: average hours a day with one decimal)"), + band.localizedName, band.localizedThresholds(unit), unit.unitName, + LoopFormat.number(Double(percentages[band] ?? 0), decimals: 0), LoopFormat.number(hours, decimals: 1)) + + ", " + ConsensusTarget.aim(band.localizedTarget)) + } +} + +// MARK: - AGP + +private extension AGPBand { + /// The middle of the slot, in minutes after midnight. + var minute: Int { Int(timeOfDay / 60) } +} + +struct TrendsAGPChart: View { + let slots: [AGPBand] + let readings: [GlucosePoint] + let days: Int + let unit: GlucoseUnitStyle + let targetRange: ClosedRange? + var height: CGFloat = 180 + @Environment(\.dynamicTypeSize) private var typeSize + + private func v(_ mgdl: Double) -> Double { + min(max(unit.value(mgdl), unit.agpDomain.lowerBound), unit.agpDomain.upperBound) + } + + private static let hourTicks = [0, 360, 720, 1080, 1440] + + private static func label(minute: Int) -> String { + let minute = minute % 1440 + let date = Calendar.current.date(bySettingHour: minute / 60, minute: minute % 60, second: 0, of: Date())! + return DayAxis.hourLabel(date) + } + + var enoughDays: Bool { days >= 5 } + + var body: some View { + VStack(alignment: .leading, spacing: LoopDesign.Space.s2) { + if readings.isEmpty { + ChartPlaceholder(message: NSLocalizedString("No CGM data in this period", comment: "Trends chart placeholder when the period has no glucose readings"), height: height) + } else { + chart.frame(height: height) + if !enoughDays { + Text(String(format: NSLocalizedString("Not enough days for a pattern: %1$@ of 5", comment: "Trends Daily pattern footnote when fewer than 5 days have readings; the chart shows raw readings instead. (1: days with readings)"), + LoopFormat.number(Double(days), decimals: 0))) + .font(LoopDesign.Typeface.footnote) + .foregroundStyle(P.inkMuted) + } + } + } + } + + private func minuteOfDay(_ date: Date) -> Int { + let parts = Calendar.current.dateComponents([.hour, .minute], from: date) + return (parts.hour ?? 0) * 60 + (parts.minute ?? 0) + } + + private var chart: some View { + Chart { + if let targetRange { + RectangleMark(xStart: .value("Start", 0), xEnd: .value("End", 1440), + yStart: .value("Low", v(targetRange.lowerBound)), yEnd: .value("High", v(targetRange.upperBound))) + .foregroundStyle(P.targetBand) + } + if enoughDays { + ForEach(slots, id: \.minute) { slot in + AreaMark(x: .value("Time", slot.minute), yStart: .value("5%", v(slot.p05)), yEnd: .value("95%", v(slot.p95)), series: .value("Band", "outer")) + .foregroundStyle(P.agpOuter) + .interpolationMethod(.monotone) + } + ForEach(slots, id: \.minute) { slot in + AreaMark(x: .value("Time", slot.minute), yStart: .value("25%", v(slot.p25)), yEnd: .value("75%", v(slot.p75)), series: .value("Band", "inner")) + .foregroundStyle(P.agpInner) + .interpolationMethod(.monotone) + } + ForEach(slots, id: \.minute) { slot in + LineMark(x: .value("Time", slot.minute), y: .value("Median", v(slot.p50)), series: .value("Band", "median")) + .foregroundStyle(P.glucose) + .lineStyle(StrokeStyle(lineWidth: 2.5)) + .interpolationMethod(.monotone) + } + } else { + ForEach(Array(readings.enumerated()), id: \.offset) { _, point in + PointMark(x: .value("Time", minuteOfDay(point.date)), y: .value("Glucose", v(point.mgdl))) + .symbolSize(8) + .foregroundStyle(P.glucose) + } + } + } + .chartXScale(domain: 0...1440) + .chartYScale(domain: unit.agpDomain) + .chartXAxis { + AxisMarks(values: typeSize.isAccessibilitySize ? [0, 720, 1440] : Self.hourTicks) { value in + AxisGridLine().foregroundStyle(P.grid) + AxisValueLabel { + if let minute = value.as(Int.self) { Text(Self.label(minute: minute)) } + } + .font(LoopDesign.Typeface.caption) + .foregroundStyle(P.inkMuted) + } + } + .chartYAxis { + AxisMarks(position: .leading, values: typeSize.isAccessibilitySize + ? [unit.agpTicks[0], unit.agpTicks[2], unit.agpTicks[4]] : unit.agpTicks) { _ in + AxisGridLine().foregroundStyle(P.grid) + AxisValueLabel().font(LoopDesign.Typeface.caption).foregroundStyle(P.inkMuted) + } + } + .accessibilityElement(children: .ignore) + .accessibilityLabel(accessibilitySummary) + } + + private var accessibilitySummary: String { + guard enoughDays, let high = slots.max(by: { $0.p50 < $1.p50 }), let low = slots.min(by: { $0.p50 < $1.p50 }) else { + return NSLocalizedString("Daily pattern: not enough days", comment: "VoiceOver label for the Trends Daily pattern chart when fewer than 5 days have readings") + } + let span = String.localizedStringWithFormat(NSLocalizedString("%lld days", comment: "A number of days, e.g. a Trends period or how many days are averaged. (1: number of days)"), days) + return String(format: NSLocalizedString("Daily pattern over %1$@. Median highest %2$@ at %3$@, lowest %4$@ at %5$@", comment: "VoiceOver label for the Trends Daily pattern chart. (1: days with readings, e.g. 14 days; 2: highest median glucose; 3: time of day; 4: lowest median glucose; 5: time of day)"), + span, unit.format(high.p50), Self.label(minute: high.minute), unit.format(low.p50), Self.label(minute: low.minute)) + } +} + +// MARK: - InsulinSplit + +/// Basal against bolus in one capsule: basal, then manual bolus, then automatic bolus. +struct InsulinSplitBar: View { + let split: InsulinSplit + /// A 6-point line for list headers. It is still tall enough to show the automatic bolus stripes. + var hairline = false + @Environment(\.colorScheme) private var scheme + + private enum Part: CaseIterable { case basal, manual, automatic } + + private func units(_ part: Part) -> Double { + switch part { + case .basal: return split.basal + // Unclassified bolus draws as plain bolus. + case .manual: return split.manualBolus + split.unclassifiedBolus + case .automatic: return split.automaticBolus + } + } + + var body: some View { + GeometryReader { geometry in + let parts = Part.allCases.filter { units($0) > 0 } + let gap: CGFloat = hairline ? 1.5 : 2.5 + let width = geometry.size.width - gap * CGFloat(max(0, parts.count - 1)) + let minimum: CGFloat = hairline ? 2 : 4 + let widths = parts.map { max(minimum, width * units($0) / max(split.total, .ulpOfOne)) } + // Take what the minimums add from the widest part, so the bar keeps its length. + let excess = widths.reduce(0, +) - width + let widest = widths.indices.max { widths[$0] < widths[$1] } + HStack(spacing: gap) { + ForEach(Array(parts.enumerated()), id: \.offset) { index, part in + segment(part).frame(width: max(0, widths[index] - (index == widest ? excess : 0))) + } + } + .clipShape(Capsule()) + } + .frame(height: hairline ? 6 : 14) + .accessibilityHidden(true) + } + + @ViewBuilder + private func segment(_ part: Part) -> some View { + switch part { + case .basal: + // Rounded where the capsule is, so the capsule's clip doesn't cut the outline. Basal is always first. + let radius: CGFloat = hairline ? 3 : 7 + let trailing = units(.manual) + units(.automatic) > 0 ? 0 : radius + let shape = UnevenRoundedRectangle(topLeadingRadius: radius, bottomLeadingRadius: radius, bottomTrailingRadius: trailing, topTrailingRadius: trailing) + shape.fill(LoopDesign.Palette.basal) + .overlay(shape.strokeBorder(LoopDesign.Palette.basalOutline, lineWidth: hairline ? 1 : 1.25)) + case .manual: + Rectangle().fill(LoopDesign.Palette.bolus) + case .automatic: + Rectangle().fill(Hatch.paint(LoopDesign.Palette.bolus, scheme: scheme)) + } + } +} + +/// A day's basal and bolus under a list header: the line, then each part keyed the way the charts and rows draw it. +/// The header shows the day's total itself. +struct InsulinSplitLine: View { + let split: InsulinSplit + var partial = false + + var body: some View { + VStack(alignment: .leading, spacing: 6) { + InsulinSplitBar(split: split, hairline: true) + FlowLayout(spacing: LoopDesign.Space.s3, lineSpacing: 2) { + part(.basal, Text(NSLocalizedString("Basal", comment: "Basal and bolus row: insulin delivered as basal")) + Text(verbatim: " ") + Text(LoopFormat.number(split.basal, decimals: 1))) + if split.isClassified { + if split.manualBolus > 0 { + part(.solid(LoopDesign.Palette.bolus), Text(String(format: NSLocalizedString("Manual %1$@", comment: "Basal and bolus: bolus the person gave. (1: units, e.g. 16.2 U)"), LoopFormat.number(split.manualBolus, decimals: 1)))) + } + if split.automaticBolus > 0 { + part(.hatch(LoopDesign.Palette.bolus), Text(String(format: NSLocalizedString("Automatic %1$@", comment: "Basal and bolus: bolus Loop gave automatically. (1: units, e.g. 5.4 U)"), LoopFormat.number(split.automaticBolus, decimals: 1)))) + } + } else { + part(.solid(LoopDesign.Palette.bolus), Text(NSLocalizedString("Bolus", comment: "Basal and bolus row: insulin delivered as bolus, manual and automatic")) + Text(verbatim: " ") + Text(LoopFormat.number(split.bolus, decimals: 1))) + } + } + .font(LoopDesign.Typeface.footnote.monospacedDigit()) + .foregroundStyle(LoopDesign.Palette.inkMuted) + } + .accessibilityElement(children: .ignore) + .accessibilityLabel(InsulinSplitView.accessibilityLabel(split, partial: partial)) + } + + private func part(_ swatch: LegendItem.Swatch, _ text: Text) -> some View { + HStack(spacing: LoopDesign.Space.s1) { + LegendSwatch(swatch: swatch) + text + } + } +} + +/// Basal and bolus in units and shares, how the bolus divides, and the total. +struct InsulinSplitView: View { + let split: InsulinSplit + /// Today so far, rather than a whole day or a per-day average. + var partial = false + /// What the basal schedule delivers over the same time, shown under the basal row. + var scheduledBasal: Double? + /// How many of the days the schedule covers, e.g. "20 of 90 days", when that is fewer than the split's. + var scheduledNote: String? + /// Today against a usual day, e.g. "Usually 28.4 U by 19:46", under the total. + var usual: String? + /// The split as one capsule, where no chart above already draws it. + var showsBar = true + /// The total is the dashed average line of the chart above, so it carries that line's swatch. + var averageLine = false + @Environment(\.dynamicTypeSize) private var typeSize + + var body: some View { + VStack(alignment: .leading, spacing: LoopDesign.Space.s3) { + if showsBar { + InsulinSplitBar(split: split) + } + VStack(alignment: .leading, spacing: LoopDesign.Space.s2) { + row(.basal, NSLocalizedString("Basal", comment: "Basal and bolus row: insulin delivered as basal"), split.basal, split.basalPercent) + // No swatch: nothing on the chart draws the schedule. + if let scheduledBasal { + Text(Self.scheduledText(scheduledBasal, note: scheduledNote)) + .font(LoopDesign.Typeface.footnote.monospacedDigit()) + .foregroundStyle(LoopDesign.Palette.inkMuted) + .padding(.leading, 10 + LoopDesign.Space.s2) + } + row(.solid(LoopDesign.Palette.bolus), NSLocalizedString("Bolus", comment: "Basal and bolus row: insulin delivered as bolus, manual and automatic"), split.bolus, split.bolusPercent) + // Manual, automatic and unknown add up to the bolus row. Unknown has no swatch of its own: it is drawn + // as plain bolus, like manual. + if split.bolus >= 0.005 { + FlowLayout(spacing: LoopDesign.Space.s3, lineSpacing: 2) { + if showsBolusDetail { + part(.solid(LoopDesign.Palette.bolus), String(format: NSLocalizedString("Manual %1$@", comment: "Basal and bolus: bolus the person gave. (1: units, e.g. 16.2 U)"), LoopFormat.totalUnits(split.manualBolus))) + part(.hatch(LoopDesign.Palette.bolus), String(format: NSLocalizedString("Automatic %1$@", comment: "Basal and bolus: bolus Loop gave automatically. (1: units, e.g. 5.4 U)"), LoopFormat.totalUnits(split.automaticBolus))) + } + if !split.isClassified { + Text(Self.unknownText(split.unclassifiedBolus)) + } + } + .font(LoopDesign.Typeface.footnote.monospacedDigit()) + .foregroundStyle(LoopDesign.Palette.inkMuted) + .padding(.leading, 10 + LoopDesign.Space.s2) + } + Divider().padding(.vertical, 2) + HStack(alignment: .firstTextBaseline, spacing: LoopDesign.Space.s2) { + if averageLine { + LegendSwatch(swatch: .dash(LoopDesign.Palette.ink)).alignmentGuide(.firstTextBaseline) { $0[.bottom] + 3 } + } + Text(partial + ? NSLocalizedString("Total so far", comment: "Basal and bolus total row for today, which isn't over yet") + : NSLocalizedString("Total", comment: "Basal and bolus total row: basal plus bolus")) + .font(LoopDesign.Typeface.subhead.weight(.semibold)) + .foregroundStyle(LoopDesign.Palette.ink) + Spacer() + Text(LoopFormat.totalUnits(split.total)) + .font(LoopDesign.Typeface.statValueSmall) + .foregroundStyle(LoopDesign.Palette.ink) + } + if let usual { + Text(usual) + .font(LoopDesign.Typeface.footnote.monospacedDigit()) + .foregroundStyle(LoopDesign.Palette.inkMuted) + .frame(maxWidth: .infinity, alignment: .trailing) + } + } + } + .accessibilityElement(children: .ignore) + .accessibilityLabel(Self.accessibilityLabel(split, partial: partial, scheduledBasal: scheduledBasal.map { Self.scheduledText($0, note: scheduledNote) }, + showsBolusDetail: showsBolusDetail, usual: usual)) + } + + /// Manual and automatic, when any bolus says which it was; a split that is all unknown shows only that. + private var showsBolusDetail: Bool { + split.manualBolus + split.automaticBolus >= 0.005 + } + + /// "3.2 U unknown": bolus whose record doesn't say whether it was manual or automatic. + private static func unknownText(_ units: Double) -> String { + String(format: NSLocalizedString("%1$@ unknown", comment: "Basal and bolus: bolus whose record doesn't say whether it was manual or automatic, such as some in Apple Health, after the manual and automatic amounts. (1: units, e.g. 3.2 U)"), LoopFormat.totalUnits(units)) + } + + /// "Scheduled 18.0 U", or "Scheduled 18.0 U · 20 of 90 days" when the schedule is known for only some days. + private static func scheduledText(_ units: Double, note: String?) -> String { + let text = String(format: NSLocalizedString("Scheduled %1$@", comment: "Basal and bolus: what the basal schedule delivers over the same time, under the basal row. (1: units, e.g. 18.0 U)"), LoopFormat.totalUnits(units)) + return note.map { "\(text) · \($0)" } ?? text + } + + private func row(_ swatch: LegendItem.Swatch, _ label: String, _ units: Double, _ percent: Int) -> some View { + let amount = HStack(alignment: .firstTextBaseline, spacing: LoopDesign.Space.s2) { + Text(LoopFormat.totalUnits(units)) + .font(LoopDesign.Typeface.body.weight(.semibold).monospacedDigit()) + .foregroundStyle(LoopDesign.Palette.ink) + Text(verbatim: "\(percent)%") + .font(LoopDesign.Typeface.footnote.monospacedDigit()) + .foregroundStyle(LoopDesign.Palette.inkMuted) + .frame(minWidth: typeSize.isAccessibilitySize ? nil : 38, alignment: .trailing) + } + return AdaptiveRow(spacing: typeSize.isAccessibilitySize ? 0 : LoopDesign.Space.s2) { + HStack(alignment: .firstTextBaseline, spacing: LoopDesign.Space.s2) { + LegendSwatch(swatch: swatch).alignmentGuide(.firstTextBaseline) { $0[.bottom] - 1 } + Text(label) + .font(LoopDesign.Typeface.subhead) + .foregroundStyle(LoopDesign.Palette.ink) + } + if !typeSize.isAccessibilitySize { + Spacer() + } + amount + } + } + + private func part(_ swatch: LegendItem.Swatch, _ text: String) -> some View { + HStack(spacing: LoopDesign.Space.s1) { + LegendSwatch(swatch: swatch) + Text(text) + } + } + + static func accessibilityLabel(_ split: InsulinSplit, partial: Bool, scheduledBasal: String? = nil, showsBolusDetail: Bool = false, + usual: String? = nil) -> String { + var parts = [ + String(format: NSLocalizedString("Basal %1$@, %2$@ percent", comment: "VoiceOver: basal units and share. (1: units, 2: percentage number)"), LoopFormat.totalUnits(split.basal), "\(split.basalPercent)"), + String(format: NSLocalizedString("Bolus %1$@, %2$@ percent", comment: "VoiceOver: bolus units and share. (1: units, 2: percentage number)"), LoopFormat.totalUnits(split.bolus), "\(split.bolusPercent)"), + ] + if showsBolusDetail { + let text = String(format: NSLocalizedString("%1$@ manual, %2$@ automatic", comment: "VoiceOver: how the bolus divides. (1: manual units, 2: automatic units)"), + LoopFormat.totalUnits(split.manualBolus), LoopFormat.totalUnits(split.automaticBolus)) + parts.append(split.isClassified ? text : "\(text), \(unknownText(split.unclassifiedBolus))") + } else if !split.isClassified { + parts.append(unknownText(split.unclassifiedBolus)) + } + parts.append(String(format: partial + ? NSLocalizedString("Total so far %1$@", comment: "VoiceOver: today's total insulin so far. (1: units)") + : NSLocalizedString("Total %1$@", comment: "VoiceOver: total insulin. (1: units)"), + LoopFormat.totalUnits(split.total))) + if let scheduledBasal { + parts.insert(scheduledBasal, at: 1) + } + if let usual { + parts.append(usual) + } + return parts.joined(separator: ". ") + } +} + +// MARK: - InsulinDailyTotals + +struct InsulinDailyTotalsView: View { + let totals: [LoopHistoryMath.DayTotal] + /// Weekly averages instead of days, for periods past 30 days. + let weekly: Bool + /// Calculated from the original daily totals, even when the bars are weekly averages. + let average: Double + var height: CGFloat = 170 + /// Opens a day when its bar is tapped; weekly bars don't open anything. + var onSelectDay: ((Date) -> Void)? = nil + @Environment(\.colorScheme) private var scheme + @Environment(\.dynamicTypeSize) private var typeSize + + private var yMax: Double { + let top = max(totals.map(\.total).max() ?? 0, average) + return max(10, Self.niceStep(top / 4) * 5) + } + + struct BolusPart: Equatable { + let start: Double + let end: Double + let automatic: Bool + } + + /// Where a day's bolus parts sit above its basal: manual (with bolus of unknown kind), then automatic. Each + /// starts a gap of the card's colour above the part below it, so no two parts touch. A part taller than two gaps + /// gives the gap from its own height; a shorter one moves up by a gap instead, so it stays visible. + static func bolusParts(_ day: LoopHistoryMath.DayTotal, gap: Double) -> [BolusPart] { + var parts: [BolusPart] = [] + var below = day.basal + for (units, automatic) in [(day.split.manualBolus + day.split.unclassifiedBolus, false), (day.split.automaticBolus, true)] where units > 0 { + let start = below + gap + let end = units > gap * 2 ? below + units : start + units + parts.append(BolusPart(start: start, end: end, automatic: automatic)) + below = end + } + return parts + } + + /// 1, 2 or 5 times a power of ten, at or above `raw`. + static func niceStep(_ raw: Double) -> Double { + guard raw > 0 else { return 1 } + let magnitude = pow(10, floor(log10(raw))) + let normalized = raw / magnitude + let nice: Double = normalized <= 1 ? 1 : normalized <= 2 ? 2 : normalized <= 5 ? 5 : 10 + return nice * magnitude + } + + var body: some View { + if totals.allSatisfy({ $0.total == 0 }) { + ChartPlaceholder(message: NSLocalizedString("No insulin recorded in this period", comment: "Trends Insulin per day chart placeholder when no insulin was delivered in the period"), height: height) + } else { + chart.frame(height: height) + } + } + + private var unitWidth: Calendar.Component { weekly ? .weekOfYear : .day } + + /// A bar mark can't have a border, so the outline is four rules along the 0.7-wide bar's edges. + @ChartContentBuilder + private func basalOutline(_ day: LoopHistoryMath.DayTotal) -> some ChartContent { + if day.basal > 0, let unit = Calendar.current.dateInterval(of: unitWidth, for: day.day) { + let left = unit.start.addingTimeInterval(unit.duration * 0.15) + let right = unit.start.addingTimeInterval(unit.duration * 0.85) + let line = StrokeStyle(lineWidth: 1.25) + RuleMark(x: .value("Left", left), yStart: .value("Base", 0), yEnd: .value("Basal", day.basal)) + .foregroundStyle(P.basalOutline).lineStyle(line) + RuleMark(x: .value("Right", right), yStart: .value("Base", 0), yEnd: .value("Basal", day.basal)) + .foregroundStyle(P.basalOutline).lineStyle(line) + RuleMark(xStart: .value("Left", left), xEnd: .value("Right", right), y: .value("Basal", day.basal)) + .foregroundStyle(P.basalOutline).lineStyle(line) + RuleMark(xStart: .value("Left", left), xEnd: .value("Right", right), y: .value("Base", 0)) + .foregroundStyle(P.basalOutline).lineStyle(line) + } + } + + private var chart: some View { + Chart { + ForEach(totals) { day in + BarMark(x: .value("Day", day.day, unit: unitWidth), yStart: .value("Base", 0), yEnd: .value("Basal", day.basal), width: .ratio(0.7)) + .foregroundStyle(P.basal) + basalOutline(day) + ForEach(Self.bolusParts(day, gap: yMax * 0.015), id: \.automatic) { part in + BarMark(x: .value("Day", day.day, unit: unitWidth), yStart: .value("Bolus start", part.start), yEnd: .value("Bolus end", part.end), width: .ratio(0.7)) + .foregroundStyle(part.automatic ? AnyShapeStyle(Hatch.paint(P.bolus, scheme: scheme)) : AnyShapeStyle(P.bolus)) + } + } + // The average's value is the Total row under the chart. + RuleMark(y: .value("Average", average)) + .foregroundStyle(P.ink) + .lineStyle(StrokeStyle(lineWidth: 1, dash: [4, 3])) + } + .chartYScale(domain: 0...yMax) + .chartXAxis { + AxisMarks(values: axisDates) { value in + AxisValueLabel(centered: !typeSize.isAccessibilitySize, + anchor: typeSize.isAccessibilitySize ? (value.index == 0 ? .topLeading : .topTrailing) : nil) { + if let date = value.as(Date.self) { + Text(axisLabel(date)) + .multilineTextAlignment(.center) + } + } + .font(LoopDesign.Typeface.caption) + .foregroundStyle(P.inkMuted) + } + } + .chartYAxis { + if typeSize.isAccessibilitySize { + AxisMarks(position: .leading, values: [0, yMax / 2, yMax]) { _ in + AxisGridLine().foregroundStyle(P.grid) + AxisValueLabel().font(LoopDesign.Typeface.caption).foregroundStyle(P.inkMuted) + } + } else { + AxisMarks(position: .leading) { _ in + AxisGridLine().foregroundStyle(P.grid) + AxisValueLabel().font(LoopDesign.Typeface.caption).foregroundStyle(P.inkMuted) + } + } + } + .chartOverlay { proxy in + GeometryReader { geometry in + Rectangle().fill(.clear).contentShape(Rectangle()) + .onTapGesture { location in + guard let onSelectDay, !weekly, let frame = proxy.plotFrame else { return } + let x = location.x - geometry[frame].origin.x + if let date: Date = proxy.value(atX: x), + let day = totals.min(by: { abs($0.day.addingTimeInterval(43200).timeIntervalSince(date)) < abs($1.day.addingTimeInterval(43200).timeIntervalSince(date)) }) { + onSelectDay(day.day) + } + } + } + } + .accessibilityElement(children: .ignore) + .accessibilityLabel(String(format: weekly + ? NSLocalizedString("Insulin per day, weekly average, average %1$@", comment: "VoiceOver label for the Trends Insulin per day chart when bars are weekly averages. (1: average insulin per day, e.g. 32.1 U)") + : NSLocalizedString("Insulin per day, average %1$@", comment: "VoiceOver label for the Trends Insulin per day chart. (1: average insulin per day, e.g. 32.1 U)"), + LoopFormat.totalUnits(average))) + } + + private var axisDates: [Date] { + // Full dates at the largest text sizes need the width between the two ends of the chart. + if typeSize.isAccessibilitySize, let first = totals.first?.day, let last = totals.last?.day { + return first == last ? [first] : [first, last] + } + if weekly { + let stride = max(1, Int(ceil(Double(totals.count) / 6))) + return totals.enumerated().compactMap { index, total in index % stride == 0 ? total.day : nil } + } + if totals.count > 14 { + return totals.map(\.day).filter { Calendar.current.component(.weekday, from: $0) == 2 } + } + return totals.map(\.day) + } + + private func axisLabel(_ date: Date) -> String { + if weekly { + return date.formatted(.dateTime.day().month(.abbreviated)) + } + let weekday = String(date.formatted(.dateTime.weekday(.narrow))) + if totals.count <= 14 { + let first = totals.first?.day == date, last = totals.last?.day == date + let isMonday = Calendar.current.component(.weekday, from: date) == 2 + return first || last || isMonday ? "\(weekday)\n\(date.formatted(.dateTime.day()))" : weekday + } + // 30 days: label every Monday only. + return Calendar.current.component(.weekday, from: date) == 2 ? date.formatted(.dateTime.day().month(.abbreviated)) : "" + } +} + +// MARK: - LoopModeBar + +struct LoopModeBarView: View { + let spans: [LoopModeSpan] + @Environment(\.dynamicTypeSize) private var typeSize + + private var total: TimeInterval { spans.reduce(0) { $0 + $1.duration } } + + static func color(_ mode: LoopModeSpan.Mode) -> Color { + switch mode { + case .closed: return P.statusAutomated + case .limited: return P.statusWarning + case .open: return P.inkMuted + } + } + + static func name(_ mode: LoopModeSpan.Mode) -> String { + switch mode { + case .closed: return NSLocalizedString("Closed loop", comment: "Trends Loop status: time Loop was running in closed loop") + case .limited: return NSLocalizedString("Limited", comment: "Trends Loop status: time closed loop was on but Loop wasn't completing runs") + case .open: return NSLocalizedString("Open loop / manual", comment: "Trends Loop status: time closed loop was switched off") + } + } + + private let modes: [LoopModeSpan.Mode] = [.closed, .limited, .open] + + var body: some View { + if total <= 0 { + ChartPlaceholder(message: NSLocalizedString("No loop runs recorded in this period", comment: "Trends Loop status placeholder when there is no Loop run history for the period"), height: 60) + } else { + VStack(spacing: LoopDesign.Space.s3) { + bar.frame(height: 10) + ForEach(modes, id: \.self) { mode in + row(mode) + } + } + } + } + + private func fraction(_ mode: LoopModeSpan.Mode) -> Double { + LoopHistoryMath.duration(of: mode, in: spans) / total + } + + private var bar: some View { + GeometryReader { geometry in + let minimum: CGFloat = 4 + let widths = modes.map { fraction($0) > 0 ? max(minimum, fraction($0) * geometry.size.width) : 0 } + let excess = widths.reduce(0, +) - geometry.size.width + HStack(spacing: 1) { + ForEach(Array(modes.enumerated()), id: \.offset) { index, mode in + if widths[index] > 0 { + Rectangle() + .fill(Self.color(mode)) + .frame(width: max(0, index == 0 ? widths[index] - excess - 2 : widths[index])) + } + } + } + .clipShape(Capsule()) + } + .accessibilityHidden(true) + } + + private func row(_ mode: LoopModeSpan.Mode) -> some View { + let duration = LoopHistoryMath.duration(of: mode, in: spans) + let name = HStack(spacing: LoopDesign.Space.s2) { + Circle().fill(Self.color(mode)).frame(width: 8, height: 8) + Text(Self.name(mode)) + .font(LoopDesign.Typeface.subhead) + .foregroundStyle(P.ink) + } + let time = Text(verbatim: "· \(LoopFormat.duration(duration))") + .font(LoopDesign.Typeface.footnote) + .foregroundStyle(P.inkMuted) + let percent = Text(percentText(fraction(mode) * 100, decimals: 1)) + .font(LoopDesign.Typeface.statValueSmall) + .foregroundStyle(P.ink) + return Group { + if typeSize.isAccessibilitySize { + VStack(alignment: .leading, spacing: 0) { + name + HStack(alignment: .firstTextBaseline, spacing: LoopDesign.Space.s2) { + percent + time + } + } + .frame(maxWidth: .infinity, alignment: .leading) + } else { + HStack(spacing: LoopDesign.Space.s2) { + name + time + Spacer() + percent + } + } + } + .accessibilityElement(children: .combine) + } +} + +struct LoopGapsList: View { + let spans: [LoopModeSpan] + + private var gaps: [LoopModeSpan] { + spans.filter { $0.mode != .closed }.sorted { $0.start > $1.start } + } + + var body: some View { + List { + if gaps.isEmpty { + Text(NSLocalizedString("No gaps: Loop ran closed loop all through this period.", comment: "Trends Gaps list when Loop was in closed loop for the whole period")) + .foregroundStyle(P.inkMuted) + } + ForEach(Array(gaps.enumerated()), id: \.offset) { _, gap in + HStack(alignment: .top, spacing: LoopDesign.Space.s3) { + Circle().fill(LoopModeBarView.color(gap.mode)).frame(width: 8, height: 8).padding(.top, 6) + VStack(alignment: .leading, spacing: 2) { + Text(LoopModeBarView.name(gap.mode)) + .font(LoopDesign.Typeface.body) + Text("\(gap.start.formatted(.dateTime.weekday(.abbreviated).day().month(.abbreviated).hour().minute())) · \(LoopFormat.duration(gap.duration))") + .font(LoopDesign.Typeface.footnote) + .foregroundStyle(P.inkMuted) + } + } + .accessibilityElement(children: .combine) + } + } + .navigationTitle(NSLocalizedString("Gaps", comment: "Trends Loop status button and screen title: list of times Loop wasn't in closed loop")) + .navigationBarTitleDisplayMode(.inline) + } +} diff --git a/Loop/Redesign/TrendsScreen.swift b/Loop/Redesign/TrendsScreen.swift new file mode 100644 index 0000000000..e46c0bed52 --- /dev/null +++ b/Loop/Redesign/TrendsScreen.swift @@ -0,0 +1,629 @@ +// +// TrendsScreen.swift +// Loop +// +// Copyright © 2026 LoopKit Authors. All rights reserved. +// + +import SwiftUI +import UIKit + +private typealias P = LoopDesign.Palette + +/// The period review: everything on the screen follows one RangeSelector period. +@MainActor +final class TrendsModel: ObservableObject { + + struct Summary { + var interval: DateInterval + var unit: GlucoseUnitStyle + /// CGM readings only: typed-in fingersticks are left out of every figure. + var glucose: [GlucosePoint] = [] + /// Days from the first reading, when that is short of the period; nil when the readings span it. + var cgmCoveredDays: Int? + var stats: GlucoseStatistics? + var cgmActive: Double { stats?.percentActive ?? 0 } + /// Hours a day with CGM readings, which the time in range shares are of. + var cgmHoursPerDay: Double = 0 + var timeInRange: [GlucoseBand: Double] { stats?.timeInRange ?? [:] } + var agp: [AGPBand] { stats?.agpProfile ?? [] } + var agpDays = 0 + var totals: [LoopHistoryMath.DayTotal] = [] + /// Carbs and bolus counts cover only the days per-day figures divide by (see `dataDays`). + var carbGrams = 0.0 + var carbEntries = 0 + var carbsByDay: [Date: Double] = [:] + var manualBoluses = 0 + var automaticBoluses = 0 + /// Boluses whose record doesn't say whether they were automatic or given by the person, such as some in Apple Health. + var unknownBoluses = 0 + var loopSpans: [LoopModeSpan] = [] + var targetRange: ClosedRange? + /// The whole calendar day, for a one-day period: drawn as the same timeline as Now's Today so far. + var day: DayHistory? + var dayTargets: [TargetBand] = [] + /// What the basal schedule delivers per day, over the averaged days Loop has its schedule for. + var scheduledBasal: Double? + /// The averaged days `scheduledBasal` covers: Apple Health doesn't record the schedule for older days. + var scheduledDays = 0 + /// Some of the insulin comes from Apple Health, before Loop's own dose records begin. + var readsHealthInsulin = false + /// The median insulin by this time of day over the last 14 days, when the period ends now. + var typicalByNow: (typical: TypicalInsulinDelivery, at: Date)? + + /// The days per-day figures divide by: insulin's averaging days, or complete days with CGM data when there is + /// no insulin (today only when no complete day has any), never the period length. + var dataDays = 0 + var days: Double { Double(max(1, dataDays)) } + var insulinPerDay: Double { LoopHistoryMath.averageDailyInsulin(totals) } + /// Per day over the averaged days; a single day in progress when that is all there is. + var split: InsulinSplit { InsulinSplit.average(LoopHistoryMath.averagingDays(totals).map(\.split)) } + /// The split is today's total so far rather than an average of complete days. + var splitIsPartial: Bool { LoopHistoryMath.averagingDays(totals).allSatisfy { !$0.isComplete } } + } + + @Published var period: TrendsPeriod = .twoWeeks + @Published var endDay = Date() + @Published private(set) var summary: Summary? + @Published private(set) var loading = false + @Published private(set) var loadError: String? + + let provider: LoopHistoryProvider + private var loadTask: Task? + + init(provider: LoopHistoryProvider) { + self.provider = provider + } + + var interval: DateInterval { period.interval(endingOn: endDay) } + + func reload() { + loadTask?.cancel() + let interval = self.interval + let oneDay = period == .day + loading = true + summary = nil + loadError = nil + loadTask = Task { + do { + let result = try await Self.load(provider: provider, interval: interval, oneDay: oneDay) + guard !Task.isCancelled else { return } + self.summary = result + } catch { + guard !Task.isCancelled else { return } + self.loadError = error.localizedDescription + } + self.loading = false + } + } + + private static func load(provider: LoopHistoryProvider, interval: DateInterval, oneDay: Bool) async throws -> Summary { + var summary = Summary(interval: interval, unit: provider.unitStyle) + summary.targetRange = provider.glucoseTargetRange + + // A single day is read to midnight, as Today so far is, so the scheduled basal still to come is drawn. + let fetchWindow = oneDay ? DateInterval(start: interval.start, end: Calendar.current.date(byAdding: .day, value: 1, to: interval.start)!) : interval + async let historyFetch = provider.dayHistory(fetchWindow) + async let runsFetch = provider.loopRuns() + async let modeFetch = provider.loopModeChanges(in: interval) + async let manualTempFetch = provider.manualTempBasals(in: interval) + var history = try await historyFetch + let (runs, coverageStart) = try await runsFetch + if oneDay { + summary.day = history + summary.dayTargets = try await provider.glucoseTargetBands(in: fetchWindow) + history = history.clipped(to: interval) + } + + let cgm = history.glucose.filter { !$0.userEntered } + summary.glucose = cgm + summary.stats = GlucoseStatistics(readings: cgm.map { (date: $0.date, mgdl: $0.mgdl) }, start: interval.start, + end: interval.end, bucketDuration: .minutes(15)) + summary.cgmHoursPerDay = LoopHistoryMath.cgmHoursPerDay(cgmActive: summary.cgmActive, over: interval, + periodDays: LoopHistoryMath.days(in: interval).count) + summary.agpDays = LoopHistoryMath.daysWithReadings(cgm) + summary.cgmCoveredDays = LoopHistoryMath.cgmCoveredDays(cgm, in: interval, + periodDays: LoopHistoryMath.days(in: interval).count) + + let calendar = Calendar.current + summary.totals = LoopHistoryMath.days(in: interval).map { day in + let basal = history.basal.compactMap { $0.clamped(to: day) }.reduce(0) { $0 + $1.units } + let boluses = history.boluses.filter { $0.date >= day.start && $0.date < day.end } + return LoopHistoryMath.DayTotal(day: day.start, split: InsulinSplit(basal: basal, boluses: boluses), + isComplete: calendar.date(byAdding: .day, value: 1, to: day.start) == day.end) + } + let glucoseDays = Set(history.glucose.map { calendar.startOfDay(for: $0.date) }) + // Carbs and bolus counts share insulin's days, so a period with years of CGM data but a few days of Loop + // isn't spread thin. Without insulin, fall back to days with CGM data. + let withData = summary.totals.filter { $0.total > 0 || glucoseDays.contains($0.day) } + let insulinDays = LoopHistoryMath.averagingDays(summary.totals) + let averaged = !insulinDays.isEmpty ? insulinDays + : withData.contains(where: \.isComplete) ? withData.filter(\.isComplete) : withData + let averagedDays = Set(averaged.map(\.day)) + let inAveragedDays: (Date) -> Bool = { averagedDays.contains(calendar.startOfDay(for: $0)) } + summary.dataDays = averaged.count + summary.carbsByDay = Dictionary(grouping: history.carbs) { calendar.startOfDay(for: $0.date) } + .mapValues { $0.reduce(0) { $0 + $1.grams } } + let carbs = history.carbs.filter { inAveragedDays($0.date) } + summary.carbGrams = carbs.reduce(0) { $0 + $1.grams } + summary.carbEntries = carbs.count + let boluses = history.boluses.filter { inAveragedDays($0.date) } + summary.manualBoluses = boluses.filter { $0.automaticKnown && !$0.automatic }.count + summary.automaticBoluses = boluses.filter { $0.automaticKnown && $0.automatic }.count + summary.unknownBoluses = boluses.filter { !$0.automaticKnown }.count + + // Only days Loop has its schedule for: older days come from Health, which doesn't record it. + let spans = Dictionary(uniqueKeysWithValues: LoopHistoryMath.days(in: interval).map { ($0.start, $0) }) + let scheduled = insulinDays.compactMap { day in spans[day.day].flatMap { LoopHistoryMath.scheduledUnits(history.scheduledBasal, over: $0) } } + if !scheduled.isEmpty { + summary.scheduledBasal = scheduled.reduce(0, +) / Double(scheduled.count) + summary.scheduledDays = scheduled.count + } + summary.readsHealthInsulin = interval.start < history.localInsulinStart + if interval.end.timeIntervalSinceNow > -300 { + summary.typicalByNow = await provider.typicalInsulinByNow() + } + + summary.loopSpans = LoopHistoryMath.loopModeSpans(interval: interval, runs: runs, modeChanges: try await modeFetch, + coverageStart: coverageStart, manualTempBasals: try await manualTempFetch) + return summary + } + + // MARK: Tiles + + // MARK: Export + + static func exportCSV(_ s: Summary) throws -> URL { + // The CSV header and values are deliberately not localised: fixed English columns and '.' decimals for data interchange. + var lines = ["date,mean_glucose_\(s.unit.isMmol ? "mmol_l" : "mg_dl"),readings,time_in_range_pct,basal_u,bolus_u,total_u,carbs_g,manual_bolus_u,auto_bolus_u"] + let calendar = Calendar.current + let byDay = Dictionary(grouping: s.glucose) { calendar.startOfDay(for: $0.date) } + for total in s.totals { + let readings = byDay[total.day] ?? [] + let mean = readings.isEmpty ? "" : String(format: "%.*f", locale: Locale(identifier: "en_US_POSIX"), + s.unit.isMmol ? 1 : 0, s.unit.value(readings.reduce(0) { $0 + $1.mgdl } / Double(readings.count))) + let dayStats = GlucoseStatistics(readings: readings.map { (date: $0.date, mgdl: $0.mgdl) }, start: total.day, + end: calendar.date(byAdding: .day, value: 1, to: total.day) ?? total.day) + let tir = readings.isEmpty ? "" : String(format: "%.0f", (dayStats.timeInRange[.target] ?? 0) * 100) + let date = Date.ISO8601FormatStyle(timeZone: .current).year().month().day().format(total.day) + let carbs = String(format: "%.0f", s.carbsByDay[total.day] ?? 0) + // Left blank when some of the day's bolus doesn't say whether it was manual or automatic. + let bolusSplit = total.split.isClassified ? String(format: "%.2f,%.2f", total.split.manualBolus, total.split.automaticBolus) : "," + lines.append("\(date),\(mean),\(readings.count),\(tir),\(String(format: "%.2f,%.2f,%.2f", total.basal, total.bolus, total.total)),\(carbs),\(bolusSplit)") + } + let url = FileManager.default.temporaryDirectory.appendingPathComponent(Self.fileName(s.interval) + ".csv") + try lines.joined(separator: "\n").write(to: url, atomically: true, encoding: .utf8) + return url + } + + func exportPDF(_ s: Summary) throws -> URL { + let url = FileManager.default.temporaryDirectory.appendingPathComponent(Self.fileName(s.interval) + ".pdf") + let report = TrendsReport(summary: s, tiles: tiles(s)) + .frame(width: 560) + .environment(\.colorScheme, .light) + let renderer = ImageRenderer(content: report) + renderer.proposedSize = ProposedViewSize(width: 560, height: nil) + var thrown: Error? + renderer.render { size, draw in + var box = CGRect(x: 0, y: 0, width: 612, height: max(792, size.height + 52)) + guard let consumer = CGDataConsumer(url: url as CFURL), let context = CGContext(consumer: consumer, mediaBox: &box, nil) else { + thrown = CocoaError(.fileWriteUnknown) + return + } + context.beginPDFPage(nil) + context.translateBy(x: 26, y: box.height - size.height - 26) + draw(context) + context.endPDFPage() + context.closePDF() + } + if let thrown { throw thrown } + return url + } + + private static func fileName(_ interval: DateInterval) -> String { + String(format: NSLocalizedString("Loop trends %1$@", comment: "File name of an exported Trends report or CSV, without the extension. (1: date range of the period)"), + fileStamp(interval)) + } + + private static func fileStamp(_ interval: DateInterval) -> String { + LoopFormat.range(interval.start, interval.end.addingTimeInterval(-1)).replacingOccurrences(of: " – ", with: " to ") + } + + func tiles(_ s: Summary) -> [StatTile] { + let unit = s.unit + var tiles: [StatTile] = [] + let averageLabel = NSLocalizedString("Average", comment: "Trends summary tile: mean glucose over the period") + let gmiLabel = NSLocalizedString("GMI", comment: "Trends summary tile: abbreviation for Glucose Management Indicator, an estimate of HbA1c from CGM data") + let gmiCaveat = LoopHistoryMath.gmiIsRepresentative(periodDays: s.totals.count, cgmActive: s.cgmActive) ? nil + : String(format: NSLocalizedString("Best over 14 days with %1$@ CGM data", comment: "Trends GMI tile caption when the period is shorter than 14 days or CGM readings cover less than 70% of it: the consensus for when GMI is representative. (1: share of CGM data, e.g. 70%)"), + ConsensusTarget.percent(70)) + // HbA1c in mmol/mol goes with glucose in mmol/L. + func gmiIFCC(_ value: String) -> String? { + unit.isMmol ? String(format: NSLocalizedString("%1$@ mmol/mol", comment: "Trends GMI tile detail: the GMI in IFCC units. (1: value)"), value) : nil + } + if let stats = s.stats, let mean = stats.averageGlucose, let gmi = stats.gmi, + let sd = stats.standardDeviation, let cv = stats.coefficientOfVariation { + tiles.append(StatTile(label: averageLabel, value: unit.format(mean), unit: unit.unitName, + detail: String(format: NSLocalizedString("SD %1$@ · CV %2$@%%", comment: "Trends Average tile detail: standard deviation and coefficient of variation of glucose. (1: standard deviation in the glucose unit, 2: coefficient of variation as a percentage number)"), + unit.format(sd), LoopFormat.number(cv, decimals: 0)), + aim: averageAim(unit))) + // Always shown, as Statistics did. The consensus says how representative it is: 14 days, 70% CGM data. + tiles.append(StatTile(label: gmiLabel, value: LoopFormat.number(gmi, decimals: 1), unit: "%", + detail: gmiIFCC(LoopFormat.number(LoopHistoryMath.mmolPerMol(percent: gmi), decimals: 0)), + aim: ConsensusTarget.aim(ConsensusTarget.under(7)), + caveat: gmiCaveat)) + } else { + tiles.append(StatTile(label: averageLabel, value: "–", unit: unit.unitName, + detail: NSLocalizedString("No CGM data", comment: "Trends Average tile detail when the period has no glucose readings"))) + tiles.append(StatTile(label: gmiLabel, value: "–", unit: "%", + detail: gmiIFCC("–"), + caveat: gmiCaveat)) + } + // One day's figures are that day's own, so its tiles drop "per day" and show whole counts. + let oneDay = s.day != nil + let countDecimals = oneDay ? 0 : 1 + tiles.append(StatTile(label: oneDay + ? NSLocalizedString("Carbs", comment: "Trends summary tile for a one-day period: the day's total carbohydrate") + : NSLocalizedString("Carbs per day", comment: "Trends summary tile: average grams of carbohydrate entered per day"), + value: LoopFormat.number(s.carbGrams / s.days, decimals: 0), + unit: NSLocalizedString("g", comment: "Abbreviation for grams"), + detail: oneDay + ? String(format: NSLocalizedString("%lld entries", comment: "Trends Carbs tile detail for a one-day period: how many carb entries were made that day. (1: number)"), s.carbEntries) + : String(format: NSLocalizedString("%1$@ entries", comment: "Trends Carbs per day tile detail: average number of carb entries per day, a fractional value such as 2.5, so not pluralised. (1: number with one decimal)"), + LoopFormat.number(Double(s.carbEntries) / s.days, decimals: 1)))) + tiles.append(StatTile(label: oneDay + ? NSLocalizedString("Boluses", comment: "Trends summary tile for a one-day period: how many boluses were given that day, other than Loop's automatic ones") + : NSLocalizedString("Boluses per day", comment: "Trends summary tile: average number of boluses per day, other than Loop's automatic ones"), + // Every bolus not known to be automatic, so one of unknown kind still counts. + value: LoopFormat.number(Double(s.manualBoluses + s.unknownBoluses) / s.days, decimals: countDecimals), unit: nil, + detail: s.unknownBoluses > 0 + ? String(format: NSLocalizedString("%1$@ of unknown kind\n+ %2$@ automatic", comment: "Trends Boluses per day tile detail when some boluses don't say whether they were manual or automatic, such as some in Apple Health, on two lines: how many of the figure above are of unknown kind, then the automatic boluses on top. (1: boluses of unknown kind per day; 2: automatic boluses per day; both fractional, such as 4.2)"), + LoopFormat.number(Double(s.unknownBoluses) / s.days, decimals: countDecimals), + LoopFormat.number(Double(s.automaticBoluses) / s.days, decimals: countDecimals)) + : String(format: NSLocalizedString("+ %1$@ automatic", comment: "Trends Boluses per day tile detail: average number of automatic boluses per day on top of the manual ones, a fractional value such as 4.2. (1: number with one decimal)"), + LoopFormat.number(Double(s.automaticBoluses) / s.days, decimals: countDecimals)))) + return tiles + } + + /// "aim < 8.6, CV ≤ 36%": the consensus targets for mean glucose (154 mg/dL) and its variability. + private func averageAim(_ unit: GlucoseUnitStyle) -> String { + String(format: NSLocalizedString("aim %1$@, CV %2$@", comment: "Trends Average tile: the consensus targets for average glucose and its coefficient of variation, in lower case. (1: glucose target, e.g. < 8.6; 2: CV target, e.g. ≤ 36%)"), + "< " + (unit.isMmol ? LoopFormat.number(8.6, decimals: 1) : "154"), ConsensusTarget.atMost(36)) + } + + /// "5 of 14 days" when only part of the period is averaged: days without data, or today while it runs. + func daysNote(_ s: Summary) -> String? { + let insulinDays = LoopHistoryMath.averagingDays(s.totals).count + guard insulinDays < s.totals.count else { return nil } + let total = String.localizedStringWithFormat(NSLocalizedString("%lld days", comment: "A number of days, e.g. a Trends period or how many days are averaged. (1: number of days)"), s.totals.count) + return String(format: NSLocalizedString("%1$@ of %2$@", comment: "Trends: how many days of the period are averaged. (1: days averaged, a number; 2: days in the period, e.g. 14 days)"), LoopFormat.number(Double(insulinDays), decimals: 0), total) + } +} + +// MARK: - Screen + +struct TrendsView: View { + @StateObject private var model: TrendsModel + + /// Closes Trends when it is presented on its own; nil where Trends has nowhere to return to. + private let done: (() -> Void)? + + init(provider: LoopHistoryProvider, done: (() -> Void)? = nil) { + _model = StateObject(wrappedValue: TrendsModel(provider: provider)) + self.done = done + } + + @State private var path: [TrendsRoute] = [] + @State private var exportFile: ExportFile? + @State private var exportError: String? + + enum TrendsRoute: Hashable { + case day(Date) + case gaps + } + + var body: some View { + NavigationStack(path: $path) { + ScrollView { + LazyVStack(alignment: .leading, spacing: LoopDesign.Space.s6, pinnedViews: [.sectionHeaders]) { + Section { + content + } header: { + RangeSelectorView(period: $model.period, endDay: $model.endDay) + .padding(.vertical, LoopDesign.Space.s2) + .background(P.surface) + } + } + .padding(.horizontal, LoopDesign.Space.s4) + .padding(.bottom, LoopDesign.Space.s6) + } + .background(P.surface) + .navigationTitle(NSLocalizedString("Trends", comment: "Title of the Trends tab")) + .refreshable { model.reload() } + .toolbar { + if let done { + ToolbarItem(placement: .confirmationAction) { + Button(NSLocalizedString("Done", comment: "Button to close Trends"), action: done) + } + } + } + .navigationDestination(for: TrendsRoute.self) { route in + switch route { + case .day(let day): + DayDetailView(provider: model.provider, day: day) + case .gaps: + LoopGapsList(spans: model.summary?.loopSpans ?? []) + } + } + } + .onAppear { model.reload() } + .onChange(of: model.period) { _, _ in model.reload() } + .onChange(of: model.endDay) { _, _ in model.reload() } + .sheet(item: $exportFile) { file in + ShareSheet(items: [file.url]) + } + .alert(NSLocalizedString("Couldn't export", comment: "Alert title when exporting the Trends PDF or CSV fails"), + isPresented: Binding(get: { exportError != nil }, set: { if !$0 { exportError = nil } })) { + Button(NSLocalizedString("OK", comment: "Button to dismiss an alert"), role: .cancel) {} + } message: { + Text(exportError ?? "") + } + } + + @ViewBuilder + private var content: some View { + if let s = model.summary { + summaryCard(s) + // A single day leads with its timeline, as Today so far does on Now. + if let day = s.day { + dayCard(day, targets: s.dayTargets, unit: s.unit) + } + LoopCard { + CardHeader(title: NSLocalizedString("Time in range", comment: "Trends card title: share of time in each glucose range")) { + Text(String(format: NSLocalizedString("%1$@%% CGM active", comment: "Trends Time in range card: share of the period with CGM readings. (1: percentage number)"), + LoopFormat.number(s.cgmActive * 100, decimals: 0)) + + " · " + ConsensusTarget.aim(ConsensusTarget.over(70))) + } + if s.glucose.isEmpty { + ChartPlaceholder(message: NSLocalizedString("No CGM data in this period", comment: "Trends chart placeholder when the period has no glucose readings")) + } else { + TimeInRangeView(fractions: s.timeInRange, hoursPerDay: s.cgmHoursPerDay, unit: s.unit) + } + } + if s.day == nil { + patternCard(s) + } + insulinCard(s) + LoopCard { + CardHeader(title: NSLocalizedString("Loop status", comment: "Trends card title: how long Loop spent in closed loop, limited or open loop")) { + Button(NSLocalizedString("Gaps", comment: "Trends Loop status button and screen title: list of times Loop wasn't in closed loop")) { path.append(.gaps) } + .foregroundStyle(P.accent) + .disabled(s.loopSpans.isEmpty) + } + LoopModeBarView(spans: s.loopSpans) + if let note = coverageNote(s) { + Footnote(note) + } + } + } else if let error = model.loadError { + LoopCard { + ChartPlaceholder(message: String(format: NSLocalizedString("Couldn't load Trends: %1$@", comment: "Trends error message when the history can't be read. (1: error description)"), error)) + Button(NSLocalizedString("Retry", comment: "Button to try loading Trends again after an error")) { model.reload() } + } + } else { + ProgressView().frame(maxWidth: .infinity, minHeight: 300) + } + } + + /// Insulin per day with its basal and bolus split, or one day's insulin under its timeline. + private func insulinCard(_ s: TrendsModel.Summary) -> some View { + let weekly = s.totals.count > 30 + return LoopCard { + if s.day != nil { + // One day is one bar, so the timeline above stands in for the chart. + CardHeader(title: NSLocalizedString("Insulin", comment: "Trends card title for a one-day period: the day's insulin, split into basal and bolus")) { + Text(s.splitIsPartial + ? NSLocalizedString("today so far", comment: "Trends Basal and bolus card subtitle when the figures are today's total so far") + : NSLocalizedString("this day", comment: "Trends Basal and bolus card subtitle when the period is one complete day")) + } + } else { + CardHeader(title: NSLocalizedString("Insulin per day", comment: "Trends tile and card title: average total insulin per day")) { + if weekly, let note = model.daysNote(s) { + Text(String(format: NSLocalizedString("per day, weekly average · %1$@", comment: "Trends Insulin per day card subtitle when each bar is a week's average daily total and only some days of the period are averaged. (1: days averaged, e.g. 4 of 90 days)"), note)) + } else if weekly { + Text(NSLocalizedString("per day, weekly average", comment: "Trends Insulin per day card subtitle when each bar is a week's average daily total")) + } else if let note = model.daysNote(s) { + Text(String(format: NSLocalizedString("average of %1$@", comment: "Trends Insulin per day card subtitle when only some days of the period are averaged, such as a day still in progress. (1: days averaged, e.g. 13 of 14 days)"), note)) + } else { + Text(NSLocalizedString("average per day", comment: "Trends Basal and bolus card subtitle when the figures are averaged per day over the period")) + } + } + } + if s.split.total > 0 { + if s.day == nil { + InsulinDailyTotalsView(totals: weekly ? LoopHistoryMath.weekly(s.totals) : s.totals, weekly: weekly, average: s.insulinPerDay) { day in + path.append(.day(day)) + } + } + // Under the chart, the rows name its marks, so there is no separate legend. + let averaged = LoopHistoryMath.averagingDays(s.totals).count + InsulinSplitView(split: s.split, partial: s.splitIsPartial, scheduledBasal: s.scheduledBasal, + scheduledNote: s.scheduledDays < averaged ? daysOf(s.scheduledDays, averaged) : nil, + usual: s.day != nil && s.splitIsPartial ? usualByNow(s) : nil, showsBar: s.day != nil, + averageLine: s.day == nil) + if s.day == nil, let today = todaySoFar(s) { + Footnote(today) + } + // Days read from Apple Health have no schedule, and some boluses there don't say which kind they were. + if s.readsHealthInsulin, s.scheduledBasal == nil || !s.split.isClassified { + Footnote(NSLocalizedString("Older days come from Apple Health, which doesn't record the basal schedule, and some boluses there don't say whether they were manual or automatic.", comment: "Trends Insulin per day footnote when the period reaches back past Loop's own records into Apple Health, so scheduled basal can't be shown, or some boluses there have no record of whether they were manual or automatic")) + } + } else { + ChartPlaceholder(message: NSLocalizedString("No insulin recorded in this period", comment: "Trends Insulin per day chart placeholder when no insulin was delivered in the period"), height: 80) + } + } + } + + /// The same timeline as Today so far: glucose, every bolus and basal change, and carbs, through the day. + private func dayCard(_ day: DayHistory, targets: [TargetBand], unit: GlucoseUnitStyle) -> some View { + let isToday = Calendar.current.isDateInToday(day.window.start) + return Button { + path.append(.day(day.window.start)) + } label: { + DayTimelineCard(title: isToday ? DayTimelineCard.todayTitle : LoopFormat.weekdayDay(day.window.start), + history: day, unit: unit, targetBands: targets, height: 260) + } + .buttonStyle(.plain) + .accessibilityHint(NSLocalizedString("Opens the full day", comment: "VoiceOver hint for the Today so far card on the Now screen")) + } + + private func patternCard(_ s: TrendsModel.Summary) -> some View { + LoopCard { + CardHeader(title: NSLocalizedString("Daily pattern", comment: "Trends card title: the ambulatory glucose profile, glucose by time of day across the period")) { Text(s.unit.unitName) } + TrendsAGPChart(slots: s.agp, readings: s.glucose, days: s.agpDays, unit: s.unit, targetRange: s.targetRange) + ChartLegend(items: [ + LegendItem(swatch: .solid(P.glucose), label: NSLocalizedString("Median", comment: "Trends Daily pattern legend: the median glucose line")), + LegendItem(swatch: .solid(P.agpInner), label: NSLocalizedString("25–75%", comment: "Trends Daily pattern legend: band between the 25th and 75th percentiles of glucose")), + LegendItem(swatch: .solid(P.agpOuter), label: NSLocalizedString("5–95%", comment: "Trends Daily pattern legend: band between the 5th and 95th percentiles of glucose")), + ]) + } + } + + private func summaryCard(_ s: TrendsModel.Summary) -> some View { + LoopCard { + CardHeader(title: NSLocalizedString("Summary", comment: "Trends card title: the summary statistics tiles")) { + Menu(NSLocalizedString("Export", comment: "Trends menu title: export the period as a PDF report or CSV file")) { + Button(NSLocalizedString("PDF report", comment: "Trends export menu item: share a PDF report of the period")) { export { try model.exportPDF(s) } } + Button(NSLocalizedString("CSV, one row per day", comment: "Trends export menu item: share a CSV spreadsheet file with one row for each day")) { export { try TrendsModel.exportCSV(s) } } + } + .foregroundStyle(P.accent) + } + if let covered = s.cgmCoveredDays { + Footnote(String(format: NSLocalizedString("CGM data covers %1$@.", comment: "Trends Summary note when glucose readings start partway through the period. (1: days covered, e.g. 5 of 14 days)"), + daysOf(covered, s.totals.count))) + } + StatGridView(tiles: model.tiles(s)) + .opacity(model.loading ? 0.5 : 1) + } + } + + private func export(_ make: () throws -> URL) { + do { + exportFile = ExportFile(url: try make()) + } catch { + exportError = error.localizedDescription + } + } + + /// "5 of 14 days". + private func daysOf(_ count: Int, _ total: Int) -> String { + let days = String.localizedStringWithFormat(NSLocalizedString("%lld days", comment: "A number of days, e.g. a Trends period or how many days are averaged. (1: number of days)"), total) + return String(format: NSLocalizedString("%1$@ of %2$@", comment: "Trends: how many days of the period are averaged. (1: days averaged, a number; 2: days in the period, e.g. 14 days)"), LoopFormat.number(Double(count), decimals: 0), days) + } + + /// "Usually 28.4 U by 19:46": today's insulin against the last 14 days at the same time. + private func usualByNow(_ s: TrendsModel.Summary) -> String? { + guard let usual = s.typicalByNow else { return nil } + return String(format: NSLocalizedString("Usually %1$@ by %2$@", comment: "Trends: the median insulin delivered by this time of day over the last 14 days. (1: units, e.g. 28.4 U, 2: time of day)"), + LoopFormat.totalUnits(usual.typical.median), LoopFormat.time(usual.at)) + } + + /// Today's bar is still growing, so say where it stands against a usual day. + private func todaySoFar(_ s: TrendsModel.Summary) -> String? { + guard let today = s.totals.last, !today.isComplete, today.total > 0, let usual = s.typicalByNow else { return nil } + return String(format: NSLocalizedString("Today so far %1$@, usually %2$@ by %3$@.", comment: "Trends Insulin per day footnote: today's insulin so far against the median by this time of day over the last 14 days. (1: today's units, 2: usual units, 3: time of day)"), + LoopFormat.totalUnits(today.total), LoopFormat.totalUnits(usual.typical.median), LoopFormat.time(usual.at)) + } + + /// When Loop's records of its runs and settings start inside the period, say so, and how long it keeps them. + private func coverageNote(_ s: TrendsModel.Summary) -> String? { + guard let start = s.loopSpans.first?.start, start > s.interval.start else { return nil } + let kept = String.localizedStringWithFormat(NSLocalizedString("%lld days", comment: "A number of days, e.g. a Trends period or how many days are averaged. (1: number of days)"), + model.provider.localHistoryDays) + return String(format: NSLocalizedString("Covers %1$@, from the start of Loop's records, which it keeps for %2$@.", comment: "Trends Loop status footnote when Loop's records of its runs and settings start partway through the period. (1: date range covered; 2: how long Loop keeps them, e.g. 90 days)"), + LoopFormat.range(start, s.interval.end), kept) + } +} + +/// A card's quiet closing line: a target, a caveat or a comparison. +private struct Footnote: View { + let text: String + + init(_ text: String) { + self.text = text + } + + var body: some View { + Text(text) + .font(LoopDesign.Typeface.footnote) + .foregroundStyle(P.inkMuted) + .fixedSize(horizontal: false, vertical: true) + } +} + +/// A file to share, as the share sheet's item. +struct ExportFile: Identifiable { + let url: URL + var id: URL { url } +} + +struct ShareSheet: UIViewControllerRepresentable { + let items: [Any] + + func makeUIViewController(context: Context) -> UIActivityViewController { + UIActivityViewController(activityItems: items, applicationActivities: nil) + } + + func updateUIViewController(_ controller: UIActivityViewController, context: Context) {} +} + +// MARK: - PDF report + +/// The Trends cards laid out for paper. +private struct TrendsReport: View { + let summary: TrendsModel.Summary + let tiles: [StatTile] + + var body: some View { + VStack(alignment: .leading, spacing: LoopDesign.Space.s4) { + VStack(alignment: .leading, spacing: 2) { + Text(NSLocalizedString("Loop trends", comment: "Title of the exported Trends PDF report")).font(.title2.bold()) + Text(LoopFormat.range(summary.interval.start, summary.interval.end.addingTimeInterval(-1))) + .font(.subheadline) + .foregroundStyle(P.inkMuted) + } + StatGridView(tiles: tiles) + HStack(alignment: .top, spacing: LoopDesign.Space.s4) { + VStack(alignment: .leading, spacing: LoopDesign.Space.s2) { + Text(NSLocalizedString("Time in range", comment: "Trends card title: share of glucose readings in each range")).font(.headline) + TimeInRangeView(fractions: summary.timeInRange, hoursPerDay: summary.cgmHoursPerDay, unit: summary.unit) + } + .frame(maxWidth: .infinity) + } + if let day = summary.day { + VStack(alignment: .leading, spacing: LoopDesign.Space.s2) { + Text(LoopFormat.weekdayDay(day.window.start)).font(.headline) + InsulinTimelineView(history: day, unit: summary.unit, targetBands: summary.dayTargets, height: 220) + ChartLegend(items: DayTimelineCard.legend) + } + } else { + VStack(alignment: .leading, spacing: LoopDesign.Space.s2) { + Text(NSLocalizedString("Daily pattern", comment: "Trends card title: the ambulatory glucose profile, glucose by time of day across the period")).font(.headline) + TrendsAGPChart(slots: summary.agp, readings: summary.glucose, days: summary.agpDays, unit: summary.unit, + targetRange: summary.targetRange, height: 160) + } + VStack(alignment: .leading, spacing: LoopDesign.Space.s2) { + Text(NSLocalizedString("Insulin per day", comment: "Trends tile and card title: average total insulin per day")).font(.headline) + InsulinDailyTotalsView(totals: summary.totals.count > 30 ? LoopHistoryMath.weekly(summary.totals) : summary.totals, + weekly: summary.totals.count > 30, average: summary.insulinPerDay, height: 140) + } + } + VStack(alignment: .leading, spacing: LoopDesign.Space.s2) { + Text(NSLocalizedString("Loop status", comment: "Trends card title: how long Loop spent in closed loop, limited or open loop")).font(.headline) + LoopModeBarView(spans: summary.loopSpans) + } + } + .padding(LoopDesign.Space.s2) + .background(Color.white) + } +} diff --git a/Loop/View Controllers/StatusTableViewController.swift b/Loop/View Controllers/StatusTableViewController.swift index 29dc3d6b58..148112b9e3 100644 --- a/Loop/View Controllers/StatusTableViewController.swift +++ b/Loop/View Controllers/StatusTableViewController.swift @@ -94,6 +94,7 @@ final class StatusTableViewController: LoopChartsTableViewController { tableView.register(BolusProgressTableViewCell.nib(), forCellReuseIdentifier: BolusProgressTableViewCell.className) tableView.register(InsulinSuspendedTableViewCell.nib(), forCellReuseIdentifier: InsulinSuspendedTableViewCell.className) tableView.register(RecentGlucoseTableViewCell.nib(), forCellReuseIdentifier: RecentGlucoseTableViewCell.className) + tableView.register(UITableViewCell.self, forCellReuseIdentifier: Self.nowHostingCellIdentifier) applyDisplayPreferences() @@ -228,6 +229,11 @@ final class StatusTableViewController: LoopChartsTableViewController { addScenarioStepGestureRecognizers() setupPresetsStatusBar() + + if usesRedesign { + tableView.backgroundColor = .systemGroupedBackground + tableView.separatorStyle = .none + } } override func didReceiveMemoryWarning() { @@ -360,6 +366,32 @@ final class StatusTableViewController: LoopChartsTableViewController { private var bolusProgressReporter: DoseProgressReporter? + // MARK: - Redesign + + /// Read once, so a table never mixes the two layouts; LoopAppManager rebuilds the screen when the preference changes. + let usesRedesign = LoopInterfacePreference.useRedesign + + private static let nowHostingCellIdentifier = "NowHostingCell" + + private lazy var nowModel: NowModel = { + let model = NowModel(deviceManager: deviceManager, loopDataManager: loopManager, settingsManager: settingsManager, temporaryPresetsManager: temporaryPresetsManager) + model.isOnboardingComplete = { [weak self] in self?.onboardingManager.isComplete ?? false } + return model + }() + + private lazy var nowActions = NowActions( + addCarbs: { [weak self] in self?.userTappedAddCarbs() }, + bolus: { [weak self] in self?.presentBolusScreen() }, + presets: { [weak self] in self?.presentPresets() }, + showPrediction: { [weak self] in self?.showPredictionFromNow() }, + showToday: { [weak self] in self?.showDay(Date()) }, + showInsulin: { [weak self] in self?.showInsulinDelivery(sender: self) }, + showCarbs: { [weak self] in self?.performSegue(withIdentifier: CarbAbsorptionViewController.className, sender: self) }, + pumpTapped: { [weak self] in self?.executeHUDTapAction(self?.deviceManager.didTapOnPumpStatus(), from: self?.view) }, + cgmTapped: { [weak self] in self?.executeHUDTapAction(self?.deviceManager.didTapOnCGMStatus(), from: self?.view) }, + loopStatusTapped: { [weak self] in self?.showLoopStatusFromNow() } + ) + private func updateBolusProgress() { if let cell = tableView.cellForRow(at: IndexPath(row: StatusRow.status.rawValue, section: Section.status.rawValue)) as? BolusProgressTableViewCell { if case let .bolusing(_, total) = cell.configuration { @@ -403,7 +435,7 @@ final class StatusTableViewController: LoopChartsTableViewController { } private var shouldShowHUD: Bool { - return !landscapeMode + return !landscapeMode && !usesRedesign } // With a vertical status bar there is no top safe area inset, so keep the first row clear of the display corners. @@ -413,7 +445,7 @@ final class StatusTableViewController: LoopChartsTableViewController { } private var shouldShowStatus: Bool { - return !landscapeMode && statusRowMode.hasRow + return (!landscapeMode || usesRedesign) && statusRowMode.hasRow } override func glucoseUnitDidChange() { @@ -700,10 +732,14 @@ final class StatusTableViewController: LoopChartsTableViewController { let statusRowMode = self.determineStatusRowMode() updateBannerAndHUDandStatusRows(statusRowMode: statusRowMode, newSize: currentContext.newSize, animated: animated) - tableView.contentInset = UIEdgeInsets(top: shouldShowBannerWarning ? 0 : cornerClearanceTopInset, left: 0, bottom: ActionTabBarMetrics.tableContentInset, right: 0) + tableView.contentInset = UIEdgeInsets(top: shouldShowBannerWarning ? 0 : cornerClearanceTopInset, left: 0, bottom: usesRedesign ? 0 : ActionTabBarMetrics.tableContentInset, right: 0) redrawCharts() + if usesRedesign { + nowModel.refresh() + } + reloading = false let reloadNow = !self.refreshContext.isEmpty @@ -718,8 +754,10 @@ final class StatusTableViewController: LoopChartsTableViewController { case presets case alertWarning case hud + case nowHeader case status case charts + case nowCharts } // MARK: - Chart Section Data @@ -980,9 +1018,11 @@ final class StatusTableViewController: LoopChartsTableViewController { case .hud: return shouldShowHUD ? 1 : 0 case .charts: - return ChartRow.allCases.count + return usesRedesign ? 0 : ChartRow.allCases.count case .status: return shouldShowStatus ? StatusRow.allCases.count : 0 + case .nowHeader, .nowCharts: + return usesRedesign ? 1 : 0 } } @@ -1068,6 +1108,10 @@ final class StatusTableViewController: LoopChartsTableViewController { cell.hudView.loopCompletionHUD.loopStatusColors = .loopStatus return cell + case .nowHeader: + return nowHostingCell(for: indexPath) { NowHeaderView(model: self.nowModel, actions: self.nowActions) } + case .nowCharts: + return nowHostingCell(for: indexPath) { NowChartsView(model: self.nowModel, actions: self.nowActions) } case .charts: let cell = tableView.dequeueReusableCell(withIdentifier: ChartTableViewCell.className, for: indexPath) as! ChartTableViewCell @@ -1274,7 +1318,7 @@ final class StatusTableViewController: LoopChartsTableViewController { cell.setSubtitleLabel(label: nil) } } - case .presets, .hud, .status, .alertWarning: + case .presets, .hud, .status, .alertWarning, .nowHeader, .nowCharts: break } } @@ -1299,7 +1343,7 @@ final class StatusTableViewController: LoopChartsTableViewController { } case .alertWarning: return UITableView.automaticDimension - case .presets, .hud, .status: + case .presets, .hud, .status, .nowHeader, .nowCharts: return UITableView.automaticDimension } } @@ -1316,7 +1360,7 @@ final class StatusTableViewController: LoopChartsTableViewController { tableView.deselectRow(at: indexPath, animated: true) presentUnmuteAlertConfirmation() } - case .hud: + case .hud, .nowHeader, .nowCharts: break case .status: switch StatusRow(rawValue: indexPath.row)! { @@ -1390,70 +1434,7 @@ final class StatusTableViewController: LoopChartsTableViewController { performSegue(withIdentifier: PredictionTableViewController.className, sender: indexPath) } case .iob: - let showLegacy = false - - if !showLegacy, let pumpManager = deviceManager.pumpManager { - let hostingController = UIHostingController( - rootView: InsulinDeliveryLog( - viewModel: InsulinDeliveryLogViewModel( - loopDataManager: loopManager, - pumpManager: pumpManager - ), - onTapGesture: { [weak navigationController] doseEntry in - Task { - var dosingDecision: StoredDosingDecision? - if let decisionId = doseEntry.decisionId { - do { - dosingDecision = try await self.loopManager.dosingDecisionStore.findDosingDecisionsById(decisionId) - } catch { - self.log.error("Error finding dosing decision: %{public}@", String(describing: error)) - } - } - - let viewController = CommandResponseViewController(command: { (completionHandler) -> String in - var description = [String]() - - let timeFormatter: DateFormatter = { - let formatter = DateFormatter() - - formatter.dateStyle = .none - formatter.timeStyle = .short - - return formatter - }() - - description.append(timeFormatter.string(from: doseEntry.startDate)) - - description.append(String(describing: doseEntry)) - - if let dosingDecision { - description.append(String(describing: dosingDecision)) - } - - return description.joined(separator: "\n\n") - }) - - navigationController?.pushViewController(viewController, animated: true) - } - }, - onEnterManualDose: { [weak self] in - self?.presentManualDoseEntry() - } - ) - .navigationTitle(Text("Insulin")) - .environment(\.colorPalette, .default) - .environment(\.loopStatusColorPalette, .loopStatus) - ) - - hostingController.hidesBottomBarWhenPushed = true - - navigationController?.pushViewController( - hostingController, - animated: true - ) - } else { - performSegue(withIdentifier: InsulinDeliveryTableViewController.className, sender: indexPath) - } + showInsulinDelivery(sender: indexPath) case .cob: performSegue(withIdentifier: CarbAbsorptionViewController.className, sender: indexPath) } @@ -1606,9 +1587,14 @@ final class StatusTableViewController: LoopChartsTableViewController { if let activity { viewModel.restoreUserActivityState(activity) } - let carbEntryView = CarbEntryView(viewModel: viewModel) - .environmentObject(deviceManager.displayGlucosePreference) - let hostingController = DismissibleHostingController(rootView: carbEntryView, isModalInPresentation: false) + let hostingController: UIViewController + if LoopInterfacePreference.useRedesign { + hostingController = DismissibleHostingController(rootView: CarbEntryScreen(viewModel: viewModel) + .environmentObject(deviceManager.displayGlucosePreference), isModalInPresentation: false) + } else { + hostingController = DismissibleHostingController(rootView: CarbEntryView(viewModel: viewModel) + .environmentObject(deviceManager.displayGlucosePreference), isModalInPresentation: false) + } present(hostingController, animated: true) } analyticsServicesManager?.didDisplayCarbEntryScreen() @@ -1812,6 +1798,74 @@ final class StatusTableViewController: LoopChartsTableViewController { } } + /// The insulin screen behind the IOB chart and the Now screen's IOB tile. + private func showInsulinDelivery(sender: Any?) { + let showLegacy = false + + if !showLegacy, let pumpManager = deviceManager.pumpManager { + let hostingController = UIHostingController( + rootView: InsulinDeliveryLog( + viewModel: InsulinDeliveryLogViewModel( + loopDataManager: loopManager, + pumpManager: pumpManager + ), + onTapGesture: { [weak navigationController] doseEntry in + Task { + var dosingDecision: StoredDosingDecision? + if let decisionId = doseEntry.decisionId { + do { + dosingDecision = try await self.loopManager.dosingDecisionStore.findDosingDecisionsById(decisionId) + } catch { + self.log.error("Error finding dosing decision: %{public}@", String(describing: error)) + } + } + + let viewController = CommandResponseViewController(command: { (completionHandler) -> String in + var description = [String]() + + let timeFormatter: DateFormatter = { + let formatter = DateFormatter() + + formatter.dateStyle = .none + formatter.timeStyle = .short + + return formatter + }() + + description.append(timeFormatter.string(from: doseEntry.startDate)) + + description.append(String(describing: doseEntry)) + + if let dosingDecision { + description.append(String(describing: dosingDecision)) + } + + return description.joined(separator: "\n\n") + }) + + navigationController?.pushViewController(viewController, animated: true) + } + }, + onEnterManualDose: { [weak self] in + self?.presentManualDoseEntry() + } + ) + .navigationTitle(Text("Insulin")) + .environment(\.colorPalette, .default) + .environment(\.loopStatusColorPalette, .loopStatus) + ) + + hostingController.hidesBottomBarWhenPushed = true + + navigationController?.pushViewController( + hostingController, + animated: true + ) + } else { + performSegue(withIdentifier: InsulinDeliveryTableViewController.className, sender: sender) + } + } + private func addPumpManagerViewToHUD(_ view: BaseHUDView) { if let hudView = hudView { view.stateColors = .pumpStatus @@ -1848,7 +1902,7 @@ final class StatusTableViewController: LoopChartsTableViewController { let error: Error? // First, check whether we have a device error after the most recent completion date if let deviceError = deviceManager.lastError, - deviceError.date > (hudView?.loopCompletionHUD.lastLoopCompleted ?? .distantPast) + deviceError.date > (loopManager.lastLoopCompleted ?? .distantPast) { error = deviceError.error } else if let lastLoopError = lastLoopError { @@ -2385,3 +2439,59 @@ private struct WarningBannerStyle: ViewModifier { } } } + +// MARK: - Redesigned Now screen + +extension StatusTableViewController { + private func nowHostingCell(for indexPath: IndexPath, @ViewBuilder content: () -> Content) -> UITableViewCell { + let cell = tableView.dequeueReusableCell(withIdentifier: Self.nowHostingCellIdentifier, for: indexPath) + cell.selectionStyle = .none + cell.backgroundColor = .clear + cell.contentConfiguration = UIHostingConfiguration(content: content).margins(.all, 0) + return cell + } + + func presentSettingsFromTab() { + if presentedViewController != nil { + return + } + presentSettings() + } + + private func showPredictionFromNow() { + guard settingsManager.dosingEnabled || !FeatureFlags.simpleBolusCalculatorEnabled else { return } + performSegue(withIdentifier: PredictionTableViewController.className, sender: self) + } + + func showDay(_ day: Date) { + let detail = UIHostingController(rootView: DayDetailView(provider: nowModel.provider, day: day)) + // As for the Insulin, Carbohydrates and Predicted Glucose screens pushed from Now. + detail.hidesBottomBarWhenPushed = true + navigationController?.pushViewController(detail, animated: true) + } + + private func showLoopStatusFromNow() { + let lastCompleted = loopManager.lastLoopCompleted + if let deviceError = deviceManager.lastError, deviceError.date > (lastCompleted ?? .distantPast) { + showLastError(self) + } else if lastLoopError != nil { + showLastError(self) + } else { + // The classic HUD keeps this current; the new interface has no HUD, so set it before presenting. + loopCompletionModalViewModel.ago = lastCompleted.map { Date().timeIntervalSince($0) } + let sheet = UIHostingController(rootView: LoopStatusSheet( + viewModel: loopCompletionModalViewModel, + provider: nowModel.provider, + openSettings: { [weak self] in + self?.dismiss(animated: true) { self?.presentSettings() } + }, + done: { [weak self] in self?.dismiss(animated: true) } + ).environment(\.loopStatusColorPalette, .loopStatus)) + if let presentation = sheet.sheetPresentationController { + presentation.detents = [.medium(), .large()] + presentation.prefersGrabberVisible = true + } + present(sheet, animated: true) + } + } +} diff --git a/Loop/View Models/CarbEntryViewModel.swift b/Loop/View Models/CarbEntryViewModel.swift index 7b84705527..f2d6e34353 100644 --- a/Loop/View Models/CarbEntryViewModel.swift +++ b/Loop/View Models/CarbEntryViewModel.swift @@ -262,8 +262,9 @@ final class CarbEntryViewModel: ObservableObject { } private func observeFavoriteFoodIndexChange() { + // Selection is already on the main actor. Apply it before a caller sets a replacement + // amount or absorption time; a queued reset would otherwise overwrite that choice. $selectedFavoriteFoodIndex - .receive(on: RunLoop.main) .dropFirst() .sink { [weak self] index in self?.favoriteFoodSelected(at: index) diff --git a/Loop/View Models/SettingsViewModel.swift b/Loop/View Models/SettingsViewModel.swift index 3026152f79..857d9d2cd4 100644 --- a/Loop/View Models/SettingsViewModel.swift +++ b/Loop/View Models/SettingsViewModel.swift @@ -120,6 +120,8 @@ class SettingsViewModel { @ObservationIgnored var insulinDeliveryHistory: ((Int) async throws -> InsulinDeliveryHistory)? + @ObservationIgnored var historyProvider: LoopHistoryProvider? + @ObservationIgnored var setupHistory: (() async throws -> SetupHistory)? @ObservationIgnored var outcomesPackageBuilder: OutcomesPackageBuilder? diff --git a/Loop/View Models/ShareOutcomesViewModel.swift b/Loop/View Models/ShareOutcomesViewModel.swift index 96b7367c2c..92c7e2dc68 100644 --- a/Loop/View Models/ShareOutcomesViewModel.swift +++ b/Loop/View Models/ShareOutcomesViewModel.swift @@ -33,6 +33,9 @@ final class ShareOutcomesViewModel: ObservableObject { private let now: () -> Date private var progress: Progress? private var packageURL: URL? + /// The package under a readable name, for saving or sending a copy through the share sheet. + @Published private(set) var copyURL: URL? + private var copyDirectory: URL? private let deleteToken = OutcomesShareClient.makeDeleteToken() init(change: SetupChange, @@ -53,6 +56,9 @@ final class ShareOutcomesViewModel: ObservableObject { if let packageURL { try? FileManager.default.removeItem(at: packageURL) } + if let copyDirectory { + try? FileManager.default.removeItem(at: copyDirectory) + } } var range: DateInterval { @@ -95,6 +101,7 @@ final class ShareOutcomesViewModel: ObservableObject { switch result { case .success(let package): packageURL = package.url + copyURL = makeCopy(of: package, date: now) state = .ready(package) case .failure(let error): if !progress.isCancelled { @@ -103,6 +110,30 @@ final class ShareOutcomesViewModel: ObservableObject { } } + /// Links the package to a file named for the person, such as "Loop Outcomes 2026-11-25.zip". + private func makeCopy(of package: OutcomesPackage, date: Date) -> URL? { + let fileManager = FileManager.default + let directory = fileManager.temporaryDirectory.appendingPathComponent("OutcomesCopy-\(UUID().uuidString)", isDirectory: true) + let formatter = DateFormatter() + formatter.locale = Locale(identifier: "en_US_POSIX") + formatter.dateFormat = "yyyy-MM-dd" + let url = directory.appendingPathComponent("Loop Outcomes \(formatter.string(from: date)).zip") + do { + try fileManager.createDirectory(at: directory, withIntermediateDirectories: true) + copyDirectory = directory + do { + try fileManager.linkItem(at: package.url, to: url) + } catch { + try fileManager.copyItem(at: package.url, to: url) + } + return url + } catch { + try? fileManager.removeItem(at: directory) + copyDirectory = nil + return nil + } + } + func cancel() { progress?.cancel() } diff --git a/Loop/View Models/StatisticsViewModel.swift b/Loop/View Models/StatisticsViewModel.swift deleted file mode 100644 index d2078f2017..0000000000 --- a/Loop/View Models/StatisticsViewModel.swift +++ /dev/null @@ -1,136 +0,0 @@ -// -// StatisticsViewModel.swift -// Loop -// -// Copyright © 2026 LoopKit Authors. All rights reserved. -// - -import Foundation -import LoopKit -import LoopCore -import LoopAlgorithm - -@MainActor -final class StatisticsViewModel: ObservableObject { - - /// Selectable look-back windows. Bounded by the on-device glucose cache. - enum DateRange: Int, CaseIterable, Identifiable { - case week = 7 - case twoWeeks = 14 - case month = 30 - case quarter = 90 - - var id: Int { rawValue } - var days: Int { rawValue } - } - - @Published var selectedRange: DateRange = .twoWeeks { - didSet { - guard selectedRange != oldValue else { return } - recompute() - } - } - - @Published private(set) var statistics: GlucoseStatistics? - @Published private(set) var isLoading = false - /// Days of glucose actually available (bounded by data accumulated and the cache). - @Published private(set) var availableDays: Double = 0 - - /// Complete days of insulin delivery within the selected range, oldest first. - @Published private(set) var insulinDays: [DailyInsulinDelivery] = [] - @Published private(set) var insulinToday: DailyInsulinDelivery? - @Published private(set) var typicalInsulinByNow: TypicalInsulinDelivery? - - private var allSamples: [StoredGlucoseSample] = [] - private var allInsulinDays: [DailyInsulinDelivery] = [] - private let glucoseStore: GlucoseStoreProtocol - private let insulinDeliveryHistory: ((Int) async throws -> InsulinDeliveryHistory)? - private let calendar: Calendar - private let now: () -> Date - - /// Configured local cache duration (how far back glucose is retained on device). - let cacheDuration: TimeInterval - let scheduledBasalTotal: Double? - - init(glucoseStore: GlucoseStoreProtocol, - insulinDeliveryHistory: ((Int) async throws -> InsulinDeliveryHistory)? = nil, - scheduledBasalTotal: Double? = nil, - cacheDuration: TimeInterval = Bundle.main.localCacheDuration, - calendar: Calendar = .current, - now: @escaping () -> Date = { Date() }) { - self.glucoseStore = glucoseStore - self.insulinDeliveryHistory = insulinDeliveryHistory - self.scheduledBasalTotal = scheduledBasalTotal - self.cacheDuration = cacheDuration - self.calendar = calendar - self.now = now - } - - var showsInsulin: Bool { insulinDeliveryHistory != nil } - - /// Mean of the complete days in the selected range. - var averageInsulinDay: InsulinDeliveryTotals? { - guard !insulinDays.isEmpty else { return nil } - let count = Double(insulinDays.count) - let sum = insulinDays.reduce(into: InsulinDeliveryTotals()) { sum, day in - sum.basal += day.totals.basal - sum.automaticBolus += day.totals.automaticBolus - sum.manualBolus += day.totals.manualBolus - } - return InsulinDeliveryTotals(basal: sum.basal / count, automaticBolus: sum.automaticBolus / count, manualBolus: sum.manualBolus / count) - } - - var cacheDurationDays: Int { Int((cacheDuration / 86400).rounded()) } - - /// Info notices for the selected range: shown when the window is incomplete, - /// with an extra line when the local cache is what's limiting the history. - /// Empty when there's enough data to fill the selected window. - var dataNotices: [String] { - guard availableDays + 1 < Double(selectedRange.days) else { return [] } - let have = max(0, Int(availableDays.rounded())) - var notices = [String(format: NSLocalizedString( - "Showing %1$d days of data — not enough for the full %2$d-day period yet.", - comment: "Notice when the selected statistics range has incomplete data"), have, selectedRange.days)] - if cacheDurationDays < selectedRange.days { - notices.append(String(format: NSLocalizedString( - "This device keeps %d days of glucose. Increase the cache duration and rebuild to review the full period.", - comment: "Notice when the local cache limits the statistics history"), cacheDurationDays)) - } - return notices - } - - func load() async { - isLoading = true - defer { isLoading = false } - - let end = now() - let start = end.addingTimeInterval(-cacheDuration) - do { - allSamples = try await glucoseStore.getGlucoseSamples(start: start, end: end) - .filter { !$0.isDisplayOnly && !$0.wasUserEntered } - .sorted { $0.startDate < $1.startDate } - } catch { - allSamples = [] - } - availableDays = allSamples.first.map { end.timeIntervalSince($0.startDate) / 86400 } ?? 0 - - if let insulinDeliveryHistory, let history = try? await insulinDeliveryHistory(cacheDurationDays) { - let days = history.dailyTotals(calendar: calendar) - allInsulinDays = days.filter(\.isComplete) - insulinToday = days.last(where: { !$0.isComplete }) - typicalInsulinByNow = history.typicalDelivery(by: history.end, calendar: calendar) - } - recompute() - } - - /// Recompute statistics for the selected window from the already-loaded samples - /// (no store round-trip), so switching ranges is instant. - private func recompute() { - let end = now() - let start = calendar.date(byAdding: .day, value: -selectedRange.days, to: end) - ?? end.addingTimeInterval(-Double(selectedRange.days) * 24 * 60 * 60) - statistics = GlucoseStatistics(samples: allSamples, start: start, end: end, calendar: calendar) - let firstDay = calendar.date(byAdding: .day, value: -selectedRange.days, to: calendar.startOfDay(for: end)) ?? start - insulinDays = allInsulinDays.filter { $0.start >= firstDay } - } -} diff --git a/Loop/Views/SettingsView.swift b/Loop/Views/SettingsView.swift index 0d0e1ac800..b5b553fe9b 100644 --- a/Loop/Views/SettingsView.swift +++ b/Loop/Views/SettingsView.swift @@ -55,6 +55,8 @@ struct SettingsView: View { case favoriteFoods case presets + case trends + case logbook } } @@ -85,6 +87,7 @@ struct SettingsView: View { } alertManagementSection statisticsSection + interfaceSection if viewModel.pumpManagerSettingsViewModel.isSetUp() { therapySection } @@ -156,6 +159,15 @@ struct SettingsView: View { } case .favoriteFoods: FavoriteFoodsView(insightsDelegate: viewModel.favoriteFoodInsightsDelegate) + case .trends: + if let historyProvider = viewModel.historyProvider { + // Trends brings its own navigation stack, so it is a sheet rather than a push. Done closes only Trends. + TrendsView(provider: historyProvider, done: { self.sheet = nil }) + } + case .logbook: + if let historyProvider = viewModel.historyProvider, let deviceManager = viewModel.deviceManager { + LogbookView(provider: historyProvider, deviceManager: deviceManager, done: { self.sheet = nil }) + } } } .environmentObject(displayGlucosePreference) @@ -341,22 +353,31 @@ extension SettingsView { private var statisticsSection: some View { if let glucoseStore = viewModel.deviceManager?.glucoseStore { Section { - NavigationLink(destination: StatisticsView( - glucoseStore: glucoseStore, - insulinDeliveryHistory: viewModel.insulinDeliveryHistory, - scheduledBasalTotal: viewModel.therapySettings().basalRateSchedule?.total() - )) { + // The new interface's Trends and Logbook tabs cover these. + if viewModel.historyProvider != nil && !LoopInterfacePreference.useRedesign { LargeButton( - action: {}, - includeArrow: false, - imageView: Image(systemName: "chart.xyaxis.line") + action: { sheet = .trends }, + // Opens a sheet, but sits among navigation rows, so it shows their chevron. + arrowLikeNavigationLink: true, + imageView: Image(systemName: "chart.bar.doc.horizontal") .resizable() .aspectRatio(contentMode: .fit) .frame(width: 30), - label: NSLocalizedString("Statistics", comment: "Statistics settings button text"), - descriptiveText: NSLocalizedString("Glucose overview, ambulatory glucose profile and daily insulin", comment: "Statistics settings descriptive text") + label: NSLocalizedString("Trends", comment: "Trends settings button text"), + descriptiveText: NSLocalizedString("Time in range, daily pattern, insulin per day and Loop status", comment: "Trends settings descriptive text") ) - .accessibilityIdentifier("settingsViewStatistics") + .accessibilityIdentifier("settingsViewTrends") + LargeButton( + action: { sheet = .logbook }, + arrowLikeNavigationLink: true, + imageView: Image(systemName: "list.bullet.rectangle") + .resizable() + .aspectRatio(contentMode: .fit) + .frame(width: 30), + label: NSLocalizedString("Logbook", comment: "Logbook settings button text"), + descriptiveText: NSLocalizedString("Boluses, basal changes, carbs and pump events from the last 7 days", comment: "Logbook settings descriptive text") + ) + .accessibilityIdentifier("settingsViewLogbook") } NavigationLink(destination: CurrentSetupView(viewModel: CurrentSetupViewModel( selected: setupChange, @@ -454,6 +475,21 @@ extension SettingsView { .environment(\.insulinTintColor, self.insulinTintColor) } + @ViewBuilder + private var interfaceSection: some View { + Section(footer: Text(NSLocalizedString("The new interface adds Trends and Logbook tabs. Turn it off to go back to the classic status screen; Settings closes to switch.", comment: "Footer for the interface choice in settings"))) { + Toggle(NSLocalizedString("New Interface", comment: "Title of the toggle for the redesigned interface"), isOn: Binding( + get: { LoopInterfacePreference.useRedesign }, + set: { LoopInterfacePreference.useRedesign = $0 } + )) + } + Section { + NavigationLink(destination: AppearanceSettingsView()) { + Text(NSLocalizedString("Appearance and App Icon", comment: "Title of the row that opens the appearance and app icon settings")) + } + } + } + private var therapySection: some View { Section { NavigationLink(destination: therapySettingsView) { @@ -790,6 +826,7 @@ fileprivate struct LargeButton: View { let action: () -> Void var includeArrow: Bool + var arrowLikeNavigationLink: Bool let imageView: Content let secondaryImageView: SecondaryContent let label: String @@ -798,6 +835,7 @@ fileprivate struct LargeButton: View { init( action: @escaping () -> Void, includeArrow: Bool = true, + arrowLikeNavigationLink: Bool = false, imageView: Content, secondaryImageView: SecondaryContent = EmptyView(), label: String, @@ -805,6 +843,7 @@ fileprivate struct LargeButton: View { ) { self.action = action self.includeArrow = includeArrow + self.arrowLikeNavigationLink = arrowLikeNavigationLink self.imageView = imageView self.secondaryImageView = secondaryImageView self.label = label @@ -841,7 +880,14 @@ fileprivate struct LargeButton: View { if includeArrow { // TODO: Ick. I can't use a NavigationLink because we're not Navigating, but this seems worse somehow. - Image(systemName: "chevron.right").foregroundColor(.gray).font(.footnote) + if arrowLikeNavigationLink { + Image(systemName: "chevron.forward") + .font(.subheadline.weight(.medium)) + .foregroundStyle(Color(uiColor: .tertiaryLabel)) + .padding(.trailing, 1) + } else { + Image(systemName: "chevron.right").foregroundColor(.gray).font(.footnote) + } } } .padding(EdgeInsets(top: topBottomPadding, leading: 0, bottom: topBottomPadding, trailing: 0)) diff --git a/Loop/Views/ShareOutcomesView.swift b/Loop/Views/ShareOutcomesView.swift index 3006790e61..44c1fb99c4 100644 --- a/Loop/Views/ShareOutcomesView.swift +++ b/Loop/Views/ShareOutcomesView.swift @@ -92,6 +92,7 @@ struct ShareOutcomesView: View { Button(NSLocalizedString("Send", comment: "Button to send an outcomes share")) { Task { await viewModel.send() } } + copyLink case .sending(let package): summaryRows(package) HStack { @@ -104,6 +105,7 @@ struct ShareOutcomesView: View { .foregroundColor(.accentColor) LabeledContent(NSLocalizedString("Receipt", comment: "Label for an outcomes share's receipt ID"), value: receipt.id) .textSelection(.enabled) + copyLink case .deleted: Text(NSLocalizedString("The share was deleted.", comment: "Shown after the outcomes share just sent is deleted")) case .failed(let message, let package): @@ -113,13 +115,26 @@ struct ShareOutcomesView: View { Button(NSLocalizedString("Try Again", comment: "Button to retry sending an outcomes share")) { Task { await viewModel.send() } } + copyLink } } } } + @ViewBuilder + private var copyLink: some View { + if let url = viewModel.copyURL { + ShareLink(item: url) { + Text(NSLocalizedString("Save or Send a Copy…", comment: "Button that opens the share sheet with a copy of the outcomes share")) + } + } + } + private var sendFooter: some View { var text = NSLocalizedString("Shares are stored on a LoopKit server that only Loop developers can access. You can delete a share from this screen at any time.", comment: "Footer explaining how outcomes shares are stored") + if viewModel.copyURL != nil { + text += " " + NSLocalizedString("A copy you save or send yourself goes only where you choose, and doesn't include your note.", comment: "Footer explaining that a saved copy of an outcomes share isn't sent to the developers") + } if case .ready = viewModel.state, let previous = viewModel.previousShare { text = String(format: NSLocalizedString("You shared this setup on %@.", comment: "Note that the current setup was already shared (1: date)"), previous.sent.formatted(date: .abbreviated, time: .shortened)) + " " + text } diff --git a/Loop/Views/Statistics/AGPChartView.swift b/Loop/Views/Statistics/AGPChartView.swift deleted file mode 100644 index 55bac2b930..0000000000 --- a/Loop/Views/Statistics/AGPChartView.swift +++ /dev/null @@ -1,157 +0,0 @@ -// -// AGPChartView.swift -// Loop -// -// Copyright © 2026 LoopKit Authors. All rights reserved. -// - -import SwiftUI -import LoopKit -import LoopUI - -/// The ambulatory glucose profile, styled after the IDC / captūrAGP report. -/// -/// The percentile bands (5–95% and 25–75%) are each built once as a single -/// continuous shape, then filled with the glucose-zone colors (green target, -/// gold high, orange very-high, red lows) by clipping each color to that zone's -/// horizontal stripe. Because every zone clips the *same* band path, the colored -/// segments always line up at the zone boundaries. Drawn with a `Canvas` for -/// full control over the clipping. Glucose is plotted in the user's display unit. -struct AGPChartView: View { - let profile: [AGPBand] - let unit: LoopUnit - var targetLowMgDL: Double = 70 - var targetHighMgDL: Double = 180 - - private struct Zone { let lo: Double, hi: Double, band: GlucoseBand } - - private var topMgDL: Double { max(350, (profile.map { $0.p95 }.max() ?? 350).rounded(.up)) } - private var zones: [Zone] { - [Zone(lo: 0, hi: 54, band: .veryLow), - Zone(lo: 54, hi: 70, band: .low), - Zone(lo: 70, hi: 180, band: .target), - Zone(lo: 180, hi: 250, band: .high), - Zone(lo: 250, hi: topMgDL, band: .veryHigh)] - } - - private func display(_ mgdl: Double) -> Double { - LoopQuantity(unit: .milligramsPerDeciliter, doubleValue: mgdl).doubleValue(for: unit) - } - private func yLabel(_ mgdl: Double) -> String { - let v = display(mgdl) - return unit == .milligramsPerDeciliter ? "\(Int(v.rounded()))" : String(format: "%.1f", v) - } - - private let leftInset: CGFloat = 34 - private let bottomInset: CGFloat = 18 - private let topInset: CGFloat = 6 - private let rightInset: CGFloat = 6 - private let medianColor = Color(red: 0.16, green: 0.40, blue: 0.20) - - /// Append a smooth (Catmull-Rom) curve through `points` to a path already - /// positioned at `points[0]`. - static func addSmoothCurve(through points: [CGPoint], to path: inout Path) { - guard points.count > 1 else { return } - for i in 0..<(points.count - 1) { - let p0 = points[max(0, i - 1)] - let p1 = points[i] - let p2 = points[i + 1] - let p3 = points[min(points.count - 1, i + 2)] - let c1 = CGPoint(x: p1.x + (p2.x - p0.x) / 6, y: p1.y + (p2.y - p0.y) / 6) - let c2 = CGPoint(x: p2.x - (p3.x - p1.x) / 6, y: p2.y - (p3.y - p1.y) / 6) - path.addCurve(to: p2, control1: c1, control2: c2) - } - } - - var body: some View { - Canvas { ctx, size in - let plot = CGRect(x: leftInset, y: topInset, - width: size.width - leftInset - rightInset, - height: size.height - topInset - bottomInset) - guard plot.width > 0, plot.height > 0 else { return } - let pts = profile.sorted { $0.timeOfDay < $1.timeOfDay } - guard !pts.isEmpty else { return } - let top = topMgDL - - func x(_ hour: Double) -> CGFloat { plot.minX + CGFloat(hour / 24) * plot.width } - func y(_ mgdl: Double) -> CGFloat { plot.minY + CGFloat(1 - mgdl / top) * plot.height } - - func bandPath(_ lo: (AGPBand) -> Double, _ hi: (AGPBand) -> Double) -> Path { - let topPts = pts.map { CGPoint(x: x($0.timeOfDay / 3600), y: y(hi($0))) } - let botPts = pts.reversed().map { CGPoint(x: x($0.timeOfDay / 3600), y: y(lo($0))) } - var p = Path() - p.move(to: topPts[0]) - Self.addSmoothCurve(through: topPts, to: &p) - p.addLine(to: botPts[0]) - Self.addSmoothCurve(through: botPts, to: &p) - p.closeSubpath() - return p - } - let outer = bandPath({ $0.p05 }, { $0.p95 }) - let inner = bandPath({ $0.p25 }, { $0.p75 }) - - // Y gridlines. - for v in [54.0, 70, 180, 250, top] { - var grid = Path() - grid.move(to: CGPoint(x: plot.minX, y: y(v))) - grid.addLine(to: CGPoint(x: plot.maxX, y: y(v))) - ctx.stroke(grid, with: .color(.gray.opacity(0.25)), lineWidth: 0.5) - } - - // Bands: fill each glucose zone's color, clipped to that zone's stripe. - for z in zones { - let stripe = CGRect(x: plot.minX, y: y(z.hi), width: plot.width, height: y(z.lo) - y(z.hi)) - ctx.drawLayer { layer in - layer.clip(to: Path(stripe)) - layer.fill(outer, with: .color(z.band.agpColor.opacity(0.35))) - layer.fill(inner, with: .color(z.band.agpColor.opacity(0.75))) - } - } - - // Target-range boundaries. - for t in [targetLowMgDL, targetHighMgDL] { - var line = Path() - line.move(to: CGPoint(x: plot.minX, y: y(t))) - line.addLine(to: CGPoint(x: plot.maxX, y: y(t))) - ctx.stroke(line, with: .color(GlucoseBand.target.agpColor), lineWidth: 1.5) - } - - // Median. - let medPts = pts.map { CGPoint(x: x($0.timeOfDay / 3600), y: y($0.p50)) } - var med = Path() - med.move(to: medPts[0]) - Self.addSmoothCurve(through: medPts, to: &med) - ctx.stroke(med, with: .color(medianColor), lineWidth: 2.5) - - // Y-axis labels. - for v in [54.0, 70, 180, 250, top] { - ctx.draw(Text(yLabel(v)).font(.caption2).foregroundColor(.secondary), - at: CGPoint(x: plot.minX - 4, y: y(v)), anchor: .trailing) - } - // X-axis labels. - for (hour, label) in [(0, "12a"), (6, "6a"), (12, "12p"), (18, "6p"), (24, "12a")] { - ctx.draw(Text(label).font(.caption2).foregroundColor(.secondary), - at: CGPoint(x: x(Double(hour)), y: plot.maxY + 9), anchor: .center) - } - } - .accessibilityLabel(Text(NSLocalizedString("Daily glucose pattern", comment: "Accessibility label for the daily glucose pattern (AGP) chart"))) - } -} - -#if DEBUG -#Preview { - let bands: [AGPBand] = (0..<48).map { i in - let hour = Double(i) * 0.5 - let base = 150.0 + 55 * sin((hour - 4) / 24 * 2 * .pi) - let spread = 25 + 18 * (1 + sin((hour - 8) / 24 * 2 * .pi)) - return AGPBand( - timeOfDay: (Double(i) + 0.5) * 1800, - p05: max(45, base - spread * 1.8), p25: base - spread * 0.7, - p50: base, p75: base + spread * 0.8, p95: base + spread * 1.9 - ) - } - return AGPChartView(profile: bands, unit: .milligramsPerDeciliter) - .frame(height: 260) - .padding() -} -#endif diff --git a/Loop/Views/Statistics/DailyInsulinChartView.swift b/Loop/Views/Statistics/DailyInsulinChartView.swift deleted file mode 100644 index e372747da3..0000000000 --- a/Loop/Views/Statistics/DailyInsulinChartView.swift +++ /dev/null @@ -1,83 +0,0 @@ -// -// DailyInsulinChartView.swift -// Loop -// -// Copyright © 2026 LoopKit Authors. All rights reserved. -// - -import SwiftUI -import Charts -import LoopKitUI - -/// Insulin delivered per calendar day, stacked by basal, automatic bolus and manual bolus, -/// with the average as a dashed line. -struct DailyInsulinChartView: View { - let days: [DailyInsulinDelivery] - let average: Double? - - @Environment(\.insulinTintColor) private var insulinTintColor - - private enum Part: CaseIterable { - case basal, automaticBolus, manualBolus - - var name: String { - switch self { - case .basal: - return NSLocalizedString("Basal", comment: "Daily insulin chart legend for basal delivery") - case .automaticBolus: - return NSLocalizedString("Automatic Bolus", comment: "Daily insulin chart legend for automatic boluses") - case .manualBolus: - return NSLocalizedString("Manual Bolus", comment: "Daily insulin chart legend for manual boluses") - } - } - - func units(_ totals: InsulinDeliveryTotals) -> Double { - switch self { - case .basal: return totals.basal - case .automaticBolus: return totals.automaticBolus - case .manualBolus: return totals.manualBolus - } - } - } - - private var labelStride: Int { - switch days.count { - case ...8: return 1 - case ...15: return 2 - case ...31: return 7 - default: return 14 - } - } - - var body: some View { - Chart { - ForEach(days) { day in - ForEach(Part.allCases, id: \.self) { part in - BarMark( - x: .value("Day", day.start, unit: .day), - y: .value("Units", part.units(day.totals)) - ) - .foregroundStyle(by: .value("Delivery", part.name)) - } - } - if let average { - RuleMark(y: .value("Average", average)) - .lineStyle(StrokeStyle(lineWidth: 1, dash: [4, 3])) - .foregroundStyle(Color.primary.opacity(0.6)) - } - } - .chartForegroundStyleScale([ - Part.basal.name: insulinTintColor.opacity(0.35), - Part.automaticBolus.name: insulinTintColor.opacity(0.65), - Part.manualBolus.name: insulinTintColor, - ]) - .chartXAxis { - AxisMarks(values: .stride(by: .day, count: labelStride)) { - AxisGridLine() - AxisValueLabel(format: .dateTime.month(.defaultDigits).day(), centered: true) - } - } - .chartLegend(position: .bottom, alignment: .leading) - .accessibilityLabel(Text(NSLocalizedString("Insulin delivered per day", comment: "Accessibility label for the daily insulin chart"))) - } -} diff --git a/Loop/Views/Statistics/GlucoseBand+Display.swift b/Loop/Views/Statistics/GlucoseBand+Display.swift new file mode 100644 index 0000000000..a088563197 --- /dev/null +++ b/Loop/Views/Statistics/GlucoseBand+Display.swift @@ -0,0 +1,61 @@ +// +// GlucoseBand+Display.swift +// Loop +// +// Copyright © 2026 LoopKit Authors. All rights reserved. +// + +import SwiftUI +import LoopKit +import LoopKitUI +import LoopUI + +/// Writes one band edge in the unit the user reads glucose in. +/// +/// The consensus thresholds are defined in mg/dL, but the AGP report publishes +/// its own rounded mmol/L edges rather than conversions of them: converting +/// 181 mg/dL yields 10.046, which prints as "10.0" and collides with the top of +/// the target band. So each edge carries both spellings, and only the number +/// formatting — decimal separator included — is left to the preference. +private func bandEdge(mgdl: Double, mmol: Double, _ preference: DisplayGlucosePreference) -> String { + let quantity = preference.unit == .millimolesPerLiter + ? LoopQuantity(unit: .millimolesPerLiter, doubleValue: mmol) + : LoopQuantity(unit: .milligramsPerDeciliter, doubleValue: mgdl) + return preference.format(quantity, includeUnit: false) +} + +/// captūrAGP / IDC report palette for the glucose bands, matched to the standard +/// Ambulatory Glucose Profile report colors. In dark mode each band is lifted so it +/// stays clear against a dark card, and very low becomes the brighter red. +extension GlucoseBand { + var agpColor: Color { + switch self { + case .veryLow: return Self.color(light: (0.60, 0.13, 0.15), dark: (1.00, 0.27, 0.23)) // dark red + case .low: return Self.color(light: (0.85, 0.26, 0.24), dark: (1.00, 0.62, 0.60)) // red + case .target: return Self.color(light: (0.36, 0.65, 0.37), dark: (0.20, 0.84, 0.29)) // green + case .high: return Self.color(light: (0.91, 0.77, 0.26), dark: (1.00, 0.84, 0.04)) // gold / yellow + case .veryHigh: return Self.color(light: (0.85, 0.55, 0.24), dark: (0.79, 0.54, 0.00)) // orange + } + } + + private static func color(light: (Double, Double, Double), dark: (Double, Double, Double)) -> Color { + Color(uiColor: UIColor { traits in + let (red, green, blue) = traits.userInterfaceStyle == .dark ? dark : light + return UIColor(red: red, green: green, blue: blue, alpha: 1) + }) + } + + /// The band's range, written in the unit the user reads glucose in. + func rangeDescription(_ preference: DisplayGlucosePreference) -> String { + func edge(_ mgdl: Double, _ mmol: Double) -> String { + bandEdge(mgdl: mgdl, mmol: mmol, preference) + } + switch self { + case .veryLow: return "<\(edge(54, 3.0))" + case .low: return "\(edge(54, 3.0))–\(edge(69, 3.8))" + case .target: return "\(edge(70, 3.9))–\(edge(180, 10.0))" + case .high: return "\(edge(181, 10.1))–\(edge(250, 13.9))" + case .veryHigh: return ">\(edge(250, 13.9))" + } + } +} diff --git a/Loop/Views/Statistics/SetupComparisonCharts.swift b/Loop/Views/Statistics/SetupComparisonCharts.swift index d6e104f0f6..0341036f4d 100644 --- a/Loop/Views/Statistics/SetupComparisonCharts.swift +++ b/Loop/Views/Statistics/SetupComparisonCharts.swift @@ -82,7 +82,7 @@ struct MedianComparisonChartView: View { var path = Path() if let first = points.first { path.move(to: first) - AGPChartView.addSmoothCurve(through: points, to: &path) + addSmoothCurve(through: points, to: &path) } return path } @@ -99,7 +99,7 @@ struct MedianComparisonChartView: View { var band = curve(afterSorted, \.p75) let lower = afterSorted.reversed().map { CGPoint(x: x($0), y: y($0.p25)) } band.addLine(to: lower[0]) - AGPChartView.addSmoothCurve(through: lower, to: &band) + addSmoothCurve(through: lower, to: &band) band.closeSubpath() ctx.fill(band, with: .color(Color.accentColor.opacity(0.15))) } @@ -118,3 +118,18 @@ struct MedianComparisonChartView: View { .accessibilityLabel(Text(NSLocalizedString("Median glucose by time of day, before and since the change", comment: "Accessibility label for the setup comparison chart"))) } } + +/// Append a smooth (Catmull-Rom) curve through `points` to a path already +/// positioned at `points[0]`. +private func addSmoothCurve(through points: [CGPoint], to path: inout Path) { + guard points.count > 1 else { return } + for i in 0..<(points.count - 1) { + let p0 = points[max(0, i - 1)] + let p1 = points[i] + let p2 = points[i + 1] + let p3 = points[min(points.count - 1, i + 2)] + let c1 = CGPoint(x: p1.x + (p2.x - p0.x) / 6, y: p1.y + (p2.y - p0.y) / 6) + let c2 = CGPoint(x: p2.x - (p3.x - p1.x) / 6, y: p2.y - (p3.y - p1.y) / 6) + path.addCurve(to: p2, control1: c1, control2: c2) + } +} diff --git a/Loop/Views/Statistics/StatisticsView.swift b/Loop/Views/Statistics/StatisticsView.swift deleted file mode 100644 index 752ba229eb..0000000000 --- a/Loop/Views/Statistics/StatisticsView.swift +++ /dev/null @@ -1,239 +0,0 @@ -// -// StatisticsView.swift -// Loop -// -// Copyright © 2026 LoopKit Authors. All rights reserved. -// - -import SwiftUI -import LoopKit -import LoopCore -import LoopKitUI -import LoopUI - -/// "How am I doing?" overview — an Ambulatory Glucose Profile report: summary -/// metrics, a time-in-range breakdown, and the 24-hour percentile AGP chart, -/// over a selectable look-back window. -struct StatisticsView: View { - @StateObject private var viewModel: StatisticsViewModel - @EnvironmentObject private var displayGlucosePreference: DisplayGlucosePreference - - init(glucoseStore: GlucoseStoreProtocol, insulinDeliveryHistory: ((Int) async throws -> InsulinDeliveryHistory)? = nil, scheduledBasalTotal: Double? = nil) { - _viewModel = StateObject(wrappedValue: StatisticsViewModel(glucoseStore: glucoseStore, insulinDeliveryHistory: insulinDeliveryHistory, scheduledBasalTotal: scheduledBasalTotal)) - } - - var body: some View { - List { - Section { - Picker(NSLocalizedString("Range", comment: "Statistics date-range picker label"), - selection: $viewModel.selectedRange) { - ForEach(StatisticsViewModel.DateRange.allCases) { range in - Text("\(range.days)d").tag(range) - } - } - .pickerStyle(.segmented) - } - - if !viewModel.dataNotices.isEmpty { - Section { - ForEach(viewModel.dataNotices, id: \.self) { line in - Label { - Text(line) - } icon: { - Image(systemName: "info.circle") - } - .font(.footnote) - .foregroundColor(.secondary) - } - } - } - - if let stats = viewModel.statistics, stats.sampleCount > 0 { - metricsSection(stats) - timeInRangeSection(stats) - agpSection(stats) - } else if viewModel.isLoading { - Section { - HStack { Spacer(); ProgressView(); Spacer() } - } - } else { - Section { - Text(NSLocalizedString("No glucose data for this period.", comment: "Statistics empty state")) - .foregroundColor(.secondary) - } - } - - if viewModel.showsInsulin { - insulinSection - } - } - .navigationTitle(Text(NSLocalizedString("Statistics", comment: "Statistics screen title"))) - .navigationBarTitleDisplayMode(.inline) - .task { await viewModel.load() } - } - - // MARK: - Sections - - private func metricsSection(_ stats: GlucoseStatistics) -> some View { - let averageGoal = displayGlucosePreference.format(LoopQuantity(unit: .milligramsPerDeciliter, doubleValue: 154)) - return Section(header: Text(NSLocalizedString("Glucose Metrics", comment: "Glucose metrics section header"))) { - LazyVGrid(columns: [GridItem(.flexible(), spacing: 12), GridItem(.flexible(), spacing: 12)], spacing: 12) { - metric(NSLocalizedString("GMI", comment: "Glucose Management Indicator metric title"), - value: stats.gmi.map { String(format: "%.1f%%", $0) }, - goal: NSLocalizedString("Goal: <7%", comment: "GMI goal")) - metric(NSLocalizedString("Average", comment: "Average glucose metric title"), - value: stats.averageGlucose.map { - displayGlucosePreference.format(LoopQuantity(unit: .milligramsPerDeciliter, doubleValue: $0)) - }, - goal: String(format: NSLocalizedString("Goal: <%@", comment: "Average glucose goal"), averageGoal)) - metric(NSLocalizedString("Variability", comment: "Coefficient of variation metric title"), - value: stats.coefficientOfVariation.map { String(format: "%.0f%%", $0) }, - goal: NSLocalizedString("Goal: ≤36%", comment: "Glucose variability goal")) - metric(NSLocalizedString("CGM Active", comment: "Percent of time CGM data present metric title"), - value: String(format: "%.0f%%", stats.percentActive * 100), - goal: NSLocalizedString("Goal: >70%", comment: "CGM active goal")) - } - .listRowInsets(EdgeInsets(top: 8, leading: 16, bottom: 8, trailing: 16)) - .listRowBackground(Color.clear) - } - } - - private func metric(_ title: String, value: String?, goal: String) -> some View { - VStack(alignment: .leading, spacing: 4) { - Text(title) - .font(.subheadline.weight(.semibold)) - Text(value ?? "–") - .font(.system(.title, design: .rounded).weight(.bold)) - .monospacedDigit() - .minimumScaleFactor(0.6) - .lineLimit(1) - Text(goal) - .font(.caption2) - .foregroundColor(.secondary) - } - .frame(maxWidth: .infinity, alignment: .leading) - .padding(12) - .background( - RoundedRectangle(cornerRadius: 12, style: .continuous) - .fill(Color(.secondarySystemGroupedBackground)) - ) - } - - private func timeInRangeSection(_ stats: GlucoseStatistics) -> some View { - Section(header: Text(NSLocalizedString("Time in Range", comment: "Time-in-range section header"))) { - TimeInRangeBar(timeInRange: stats.timeInRange) - .padding(.vertical, 8) - } - } - - private func units(_ value: Double) -> String { - String(format: NSLocalizedString("%@ U", comment: "Insulin amount in units (1: number)"), value.formatted(.number.precision(.fractionLength(1)))) - } - - private func percent(_ part: Double, of total: Double) -> String { - total > 0 ? (part / total).formatted(.percent.precision(.fractionLength(0))) : "–" - } - - private var todayCaption: String { - guard let typical = viewModel.typicalInsulinByNow, let today = viewModel.insulinToday else { - return NSLocalizedString("Since midnight", comment: "Caption for insulin delivered today when there is no usual amount to compare") - } - return String(format: NSLocalizedString("Usually %1$@ by %2$@", comment: "Caption comparing today's insulin with the usual amount by this time (1: units, 2: time of day)"), - units(typical.median), today.end.formatted(date: .omitted, time: .shortened)) - } - - private var insulinSection: some View { - let average = viewModel.averageInsulinDay - return Section(header: Text(NSLocalizedString("Daily Insulin", comment: "Daily insulin section header")), - footer: Text(NSLocalizedString("Each bar is one calendar day; the dashed line is the average. Today isn't included until the day is over. Usual amounts are the median of the last 14 days at the same time of day.", comment: "Daily insulin section explanation"))) { - LazyVGrid(columns: [GridItem(.flexible(), spacing: 12), GridItem(.flexible(), spacing: 12)], spacing: 12) { - metric(NSLocalizedString("Average", comment: "Average daily insulin metric title"), - value: average.map { units($0.total) }, - goal: String(format: NSLocalizedString("Per day, over %d days", comment: "Caption for average daily insulin (1: number of days)"), viewModel.insulinDays.count)) - metric(NSLocalizedString("Today", comment: "Insulin delivered today metric title"), - value: viewModel.insulinToday.map { units($0.totals.total) }, - goal: todayCaption) - metric(NSLocalizedString("Basal", comment: "Average daily basal metric title"), - value: average.map { units($0.basal) }, - goal: average.map { average in - if let scheduled = viewModel.scheduledBasalTotal { - return String(format: NSLocalizedString("%1$@ · scheduled %2$@", comment: "Caption for average daily basal (1: percent of total, 2: scheduled basal units)"), percent(average.basal, of: average.total), units(scheduled)) - } - return percent(average.basal, of: average.total) - } ?? "–") - metric(NSLocalizedString("Bolus", comment: "Average daily bolus metric title"), - value: average.map { units($0.bolus) }, - goal: average.map { average in - String(format: NSLocalizedString("%1$@ · %2$@ automatic", comment: "Caption for average daily bolus (1: percent of total, 2: automatic bolus units)"), percent(average.bolus, of: average.total), units(average.automaticBolus)) - } ?? "–") - } - .listRowInsets(EdgeInsets(top: 8, leading: 16, bottom: 8, trailing: 16)) - .listRowBackground(Color.clear) - - if !viewModel.insulinDays.isEmpty { - DailyInsulinChartView(days: viewModel.insulinDays, average: average?.total) - .frame(height: 220) - .padding(.vertical, 8) - } - } - } - - @ViewBuilder - private func agpSection(_ stats: GlucoseStatistics) -> some View { - Section(header: Text(NSLocalizedString("Daily Glucose Pattern", comment: "Daily glucose pattern (AGP) section header")), - footer: Text(NSLocalizedString("Median (line) with 25–75% and 5–95% bands, by time of day.", comment: "AGP chart explanation"))) { - if stats.agpProfile.isEmpty { - Text(NSLocalizedString("Not enough data to plot a profile.", comment: "AGP empty state")) - .foregroundColor(.secondary) - } else { - AGPChartView(profile: stats.agpProfile, unit: displayGlucosePreference.unit) - .frame(height: 240) - .padding(.vertical, 8) - } - } - } -} - -#if DEBUG -/// Generates a daily glucose pattern with day-to-day spread so the AGP bands and -/// metrics populate in the canvas. Deterministic (seeded) so previews are stable. -private final class PreviewGlucoseStore: GlucoseStoreProtocol { - private let samples: [StoredGlucoseSample] - - init() { - var seed: UInt64 = 0x9E3779B97F4A7C15 - func unit01() -> Double { - seed = seed &* 6364136223846793005 &+ 1442695040888963407 - return Double(seed >> 11) / Double(UInt64(1) << 53) - } - let cal = Calendar.current - let now = Date() - let cadence: TimeInterval = 15 * 60 - var t = now.addingTimeInterval(-14 * 24 * 60 * 60) - var out: [StoredGlucoseSample] = [] - while t < now { - let hour = t.timeIntervalSince(cal.startOfDay(for: t)) / 3600 - let base = 140.0 + 40 * sin((hour - 4) / 24 * 2 * .pi) - let value = max(45, base + (unit01() - 0.5) * 70) - out.append(StoredGlucoseSample(startDate: t, quantity: LoopQuantity(unit: .milligramsPerDeciliter, doubleValue: value))) - t = t.addingTimeInterval(cadence) - } - samples = out - } - - var latestGlucose: GlucoseSampleValue? { samples.last } - - func getGlucoseSamples(start: Date?, end: Date?) async throws -> [StoredGlucoseSample] { - samples.filter { (start == nil || $0.startDate >= start!) && (end == nil || $0.startDate < end!) } - } - - func addGlucoseSamples(_ samples: [NewGlucoseSample]) async throws -> [StoredGlucoseSample] { [] } -} - -#Preview { - NavigationView { - StatisticsView(glucoseStore: PreviewGlucoseStore()) - .environmentObject(DisplayGlucosePreference(displayGlucoseUnit: .milligramsPerDeciliter)) - } -} -#endif diff --git a/Loop/Views/Statistics/TimeInRangeBar.swift b/Loop/Views/Statistics/TimeInRangeBar.swift deleted file mode 100644 index 171c28b041..0000000000 --- a/Loop/Views/Statistics/TimeInRangeBar.swift +++ /dev/null @@ -1,163 +0,0 @@ -// -// TimeInRangeBar.swift -// Loop -// -// Copyright © 2026 LoopKit Authors. All rights reserved. -// - -import SwiftUI -import LoopKit -import LoopKitUI -import LoopUI - -/// Writes one band edge in the unit the user reads glucose in. -/// -/// The consensus thresholds are defined in mg/dL, but the AGP report publishes -/// its own rounded mmol/L edges rather than conversions of them: converting -/// 181 mg/dL yields 10.046, which prints as "10.0" and collides with the top of -/// the target band. So each edge carries both spellings, and only the number -/// formatting — decimal separator included — is left to the preference. -private func bandEdge(mgdl: Double, mmol: Double, _ preference: DisplayGlucosePreference) -> String { - let quantity = preference.unit == .millimolesPerLiter - ? LoopQuantity(unit: .millimolesPerLiter, doubleValue: mmol) - : LoopQuantity(unit: .milligramsPerDeciliter, doubleValue: mgdl) - return preference.format(quantity, includeUnit: false) -} - -/// captūrAGP / IDC report palette for the glucose bands, matched to the standard -/// Ambulatory Glucose Profile report colors. -extension GlucoseBand { - var agpColor: Color { - switch self { - case .veryLow: return Color(red: 0.60, green: 0.13, blue: 0.15) // dark red - case .low: return Color(red: 0.85, green: 0.26, blue: 0.24) // red - case .target: return Color(red: 0.36, green: 0.65, blue: 0.37) // green - case .high: return Color(red: 0.91, green: 0.77, blue: 0.26) // gold / yellow - case .veryHigh: return Color(red: 0.85, green: 0.55, blue: 0.24) // orange - } - } - - var localizedTitle: String { - switch self { - case .veryLow: return NSLocalizedString("Very Low", comment: "Time-in-range band label (<54 mg/dL)") - case .low: return NSLocalizedString("Low", comment: "Time-in-range band label (54–69 mg/dL)") - case .target: return NSLocalizedString("In Range", comment: "Time-in-range band label (70–180 mg/dL)") - case .high: return NSLocalizedString("High", comment: "Time-in-range band label (181–250 mg/dL)") - case .veryHigh: return NSLocalizedString("Very High", comment: "Time-in-range band label (>250 mg/dL)") - } - } - - /// The band's range, written in the unit the user reads glucose in. - func rangeDescription(_ preference: DisplayGlucosePreference) -> String { - func edge(_ mgdl: Double, _ mmol: Double) -> String { - bandEdge(mgdl: mgdl, mmol: mmol, preference) - } - switch self { - case .veryLow: return "<\(edge(54, 3.0))" - case .low: return "\(edge(54, 3.0))–\(edge(69, 3.8))" - case .target: return "\(edge(70, 3.9))–\(edge(180, 10.0))" - case .high: return "\(edge(181, 10.1))–\(edge(250, 13.9))" - case .veryHigh: return ">\(edge(250, 13.9))" - } - } - - /// The consensus per-band goal, where the standard report lists one. - var goalText: String? { - switch self { - case .veryHigh: return NSLocalizedString("Goal: <5%", comment: "TIR goal for very high") - case .target: return NSLocalizedString("Goal: >70%", comment: "TIR goal for target range") - case .veryLow: return NSLocalizedString("Goal: <1%", comment: "TIR goal for very low") - default: return nil - } - } -} - -/// A vertical stacked time-in-range bar (Very High at top → Very Low at bottom) -/// with per-band percentages, consensus goals, and the standard clinical helper -/// notes, styled after the IDC / captūrAGP report. -struct TimeInRangeBar: View { - let timeInRange: [GlucoseBand: Double] - - @EnvironmentObject private var displayGlucosePreference: DisplayGlucosePreference - - // Top-to-bottom display order. - private static let order: [GlucoseBand] = [.veryHigh, .high, .target, .low, .veryLow] - - private func fraction(_ band: GlucoseBand) -> Double { timeInRange[band] ?? 0 } - private func percent(_ band: GlucoseBand) -> Int { Int(fraction(band) * 100 + 0.5) } - private var aboveRange: Int { Int((fraction(.veryHigh) + fraction(.high)) * 100 + 0.5) } - private var belowRange: Int { Int((fraction(.low) + fraction(.veryLow)) * 100 + 0.5) } - - /// A target-range edge, written in the user's unit. - private func edge(_ mgdl: Double, _ mmol: Double) -> String { - bandEdge(mgdl: mgdl, mmol: mmol, displayGlucosePreference) - } - - var body: some View { - VStack(alignment: .leading, spacing: 16) { - HStack(alignment: .top, spacing: 16) { - // Vertical stacked bar. - GeometryReader { geo in - VStack(spacing: 0) { - ForEach(Self.order, id: \.self) { band in - band.agpColor - .frame(height: max(0, geo.size.height * fraction(band))) - } - Spacer(minLength: 0) - } - .clipShape(RoundedRectangle(cornerRadius: 5)) - } - .frame(width: 26) - - // Per-band rows: name + range on the left, percentage with its - // goal directly beneath it on the right. - VStack(alignment: .leading, spacing: 10) { - ForEach(Self.order, id: \.self) { band in - HStack(alignment: .top, spacing: 8) { - RoundedRectangle(cornerRadius: 2) - .fill(band.agpColor) - .frame(width: 10, height: 10) - .padding(.top, 3) - VStack(alignment: .leading, spacing: 1) { - Text(band.localizedTitle).font(.subheadline.weight(.medium)) - Text(band.rangeDescription(displayGlucosePreference)).font(.caption2).foregroundColor(.secondary) - } - Spacer() - VStack(alignment: .trailing, spacing: 1) { - Text("\(percent(band))%").font(.subheadline.monospacedDigit()) - if let goal = band.goalText { - Text(goal).font(.caption2).foregroundColor(.secondary) - } - } - } - } - } - .frame(maxWidth: .infinity, alignment: .leading) - } - .frame(height: 220) - - // Clinical helper / suggestion text, as on the standard report. - VStack(alignment: .leading, spacing: 4) { - Text(String(format: NSLocalizedString("Above range (>%1$@): %2$d%% · goal <25%%", - comment: "TIR above-range summary (1: upper target edge, 2: percent of time)"), - edge(180, 10.0), aboveRange)) - Text(String(format: NSLocalizedString("Below range (<%1$@): %2$d%% · goal <4%%", - comment: "TIR below-range summary (1: lower target edge, 2: percent of time)"), - edge(70, 3.9), belowRange)) - Text(NSLocalizedString("Each 5% increase in range is clinically beneficial.", comment: "TIR suggestion")) - Text(NSLocalizedString("Each 1% time in range ≈ 15 minutes.", comment: "TIR helper")) - } - .font(.caption) - .foregroundColor(.secondary) - .fixedSize(horizontal: false, vertical: true) - } - } -} - -#if DEBUG -#Preview { - TimeInRangeBar(timeInRange: [.veryLow: 0.04, .low: 0.04, .target: 0.36, .high: 0.25, .veryHigh: 0.31]) - .padding() - .environmentObject(DisplayGlucosePreference(displayGlucoseUnit: .milligramsPerDeciliter)) -} -#endif diff --git a/Loop/Views/StatusTableView.swift b/Loop/Views/StatusTableView.swift index a09e8b9690..f850532f37 100644 --- a/Loop/Views/StatusTableView.swift +++ b/Loop/Views/StatusTableView.swift @@ -97,7 +97,10 @@ struct StatusTableView: View { var wrappedView: some View { wrapped } @Bindable var viewModel: StatusTableViewModel - + + /// The redesign puts these actions on the Now screen and its own tab bar. + private var actionTabsShown = true + init(viewModel: StatusTableViewModel) { self.viewModel = viewModel @@ -123,20 +126,39 @@ struct StatusTableView: View { ) } + func showsActionTabs(_ shown: Bool) -> StatusTableView { + var view = self + view.actionTabsShown = shown + return view + } + + private var statusContent: some View { + wrappedView + .ignoresSafeArea(edges: [.horizontal, .bottom]) + .onChange(of: viewModel.temporaryPresetsManager.activeOverride) { _, _ in + Task { + await viewController.reloadData(animated: true) + } + } + .sheet(item: $viewModel.pendingPreset) { preset in + // This is the active preset; edit disabled + PresetDetentView(preset: preset, roundBasalRate: viewModel.loopDataManager.deliveryDelegate?.roundBasalRate, didTapEdit: { }) + .accessibilityIdentifier("bar_Presets") + } + } + + @ViewBuilder var body: some View { + if actionTabsShown { + actionTabView + } else { + statusContent + } + } + + private var actionTabView: some View { ActionTabView { - wrappedView - .ignoresSafeArea(edges: [.horizontal, .bottom]) - .onChange(of: viewModel.temporaryPresetsManager.activeOverride) { _, _ in - Task { - await viewController.reloadData(animated: true) - } - } - .sheet(item: $viewModel.pendingPreset) { preset in - // This is the active preset; edit disabled - PresetDetentView(preset: preset, roundBasalRate: viewModel.loopDataManager.deliveryDelegate?.roundBasalRate, didTapEdit: { }) - .accessibilityIdentifier("bar_Presets") - } + statusContent } tabs: { ActionTab( title: "Add Carbs", diff --git a/LoopCore/NSUserDefaults.swift b/LoopCore/NSUserDefaults.swift index 0975cefd9a..5a53f896fe 100644 --- a/LoopCore/NSUserDefaults.swift +++ b/LoopCore/NSUserDefaults.swift @@ -23,6 +23,7 @@ extension UserDefaults { case userRequestedLoopReset = "com.loopkit.Loop.userRequestedLoopReset" case liveActivity = "com.loopkit.Loop.liveActivity" case defaultEnvironment = "org.tidepool.TidepoolKit.DefaultEnvironment" + case redesignEnabled = "com.loopkit.Loop.redesign.enabled" } public static let appGroup = UserDefaults(suiteName: Bundle.main.appGroupSuiteName) @@ -154,6 +155,13 @@ extension UserDefaults { } } + /// Whether the redesigned interface is on. The app mirrors its setting into the app group so the + /// widget and Live Activity can match it; they default to the redesign, as the app does. + public var redesignEnabled: Bool { + get { object(forKey: Key.redesignEnabled.rawValue) as? Bool ?? true } + set { set(newValue, forKey: Key.redesignEnabled.rawValue) } + } + public var liveActivity: LiveActivitySettings? { get { let decoder = JSONDecoder() diff --git a/LoopTests/Managers/LoopDataManagerTests.swift b/LoopTests/Managers/LoopDataManagerTests.swift index 075aeca9c1..4b06f9c087 100644 --- a/LoopTests/Managers/LoopDataManagerTests.swift +++ b/LoopTests/Managers/LoopDataManagerTests.swift @@ -695,6 +695,119 @@ class LoopDataManagerTests: XCTestCase { try await assertMissingCarbScheduleThrows(.insulinSensitivitySchedule, preview: true) } + func testFavoriteSelectionCannotOverwriteAReplacementMeal() async throws { + let viewModel = CarbEntryViewModel(delegate: loopDataManager) + let savedFoods = viewModel.favoriteFoods + defer { viewModel.favoriteFoods = savedFoods } + viewModel.favoriteFoods = [StoredFavoriteFood(name: "Meal", carbsQuantity: LoopQuantity(unit: .gram, doubleValue: 35), + foodType: "🌮", absorptionTime: .hours(3))] + viewModel.selectedFavoriteFoodIndex = 0 + let selected = expectation(description: "Favourite selection settled") + RunLoop.main.perform { selected.fulfill() } + await fulfillment(of: [selected], timeout: 2) + XCTAssertEqual(viewModel.carbsQuantity, 35) + + // The person replaces the favourite with a fast meal, retaining its amount. + let quantity = viewModel.carbsQuantity + viewModel.selectedFavoriteFoodIndex = -1 + viewModel.carbsQuantity = quantity + viewModel.usesCustomFoodType = false + viewModel.selectedDefaultAbsorptionTimeEmoji = "🍭" + viewModel.absorptionTime = .minutes(30) + let settled = expectation(description: "Replacement meal settled") + RunLoop.main.perform { settled.fulfill() } + await fulfillment(of: [settled], timeout: 2) + + XCTAssertEqual(viewModel.carbsQuantity, 35) + XCTAssertEqual(viewModel.absorptionTime, .minutes(30)) + XCTAssertFalse(viewModel.continueButtonDisabled) + } + + func testHistoricalTargetsUseStoredProfilesAndEndedPresets() async throws { + func target(_ low: Double, _ high: Double) -> ClosedRange { + LoopQuantity(unit: .milligramsPerDeciliter, doubleValue: low)...LoopQuantity(unit: .milligramsPerDeciliter, doubleValue: high) + } + let window = DateInterval(start: d(-.hours(3)), end: d(-.minutes(30))) + let store = try await reportingSettingsStore([ + StoredSettings(date: window.start, glucoseTargetRangeSchedule: GlucoseRangeSchedule( + unit: .milligramsPerDeciliter, dailyItems: [RepeatingScheduleValue(startTime: 0, value: DoubleRange(minValue: 100, maxValue: 110))], timeZone: .utcTimeZone)), + StoredSettings(date: d(-.hours(2)), glucoseTargetRangeSchedule: GlucoseRangeSchedule( + unit: .milligramsPerDeciliter, dailyItems: [RepeatingScheduleValue(startTime: 0, value: DoubleRange(minValue: 120, maxValue: 130))], timeZone: .utcTimeZone)), + ]) + var preset = TemporaryScheduleOverride(context: .custom, + settings: TemporaryPresetSettings(targetRange: target(150, 160), insulinNeedsScaleFactor: 1), + startDate: d(-.minutes(150)), duration: .finite(.hours(2)), + enactTrigger: .local, syncIdentifier: UUID()) + preset.actualEnd = .early(d(-.minutes(90))) + temporaryPresetsManager.presetHistory.recordOverride(preset, at: d(-.minutes(150))) + + let bands = try await loopDataManager.glucoseTargetBands(in: window, settingsStore: store) + XCTAssertEqual(bands, [ + TargetBand(start: window.start, end: d(-.minutes(150)), range: 100...110), + TargetBand(start: d(-.minutes(150)), end: d(-.minutes(90)), range: 150...160), + TargetBand(start: d(-.minutes(90)), end: window.end, range: 120...130), + ]) + } + + func testTargetBandsAreUnknownBeforeTherapyIsConfigured() async throws { + // Today's profile must not fill in a period whose saved settings had no profile. + let store = try await reportingSettingsStore([StoredSettings(date: d(-.hours(4)))]) + let bands = try await loopDataManager.glucoseTargetBands(in: DateInterval(start: d(-.hours(3)), end: now), settingsStore: store) + XCTAssertTrue(bands.isEmpty) + } + + func testReportingSchedulesLeaveUnrecordedHistoryUnknown() async throws { + let window = DateInterval(start: d(-.hours(4)), end: now) + let first = window.start.addingTimeInterval(.hours(1)) + let missing = first.addingTimeInterval(.hours(1)) + let resumed = missing.addingTimeInterval(.hours(1)) + func profile(at date: Date, rate: Double, target: Double) -> StoredSettings { + StoredSettings(date: date, glucoseTargetRangeSchedule: GlucoseRangeSchedule( + unit: .milligramsPerDeciliter, dailyItems: [RepeatingScheduleValue(startTime: 0, value: DoubleRange(minValue: target, maxValue: target + 10))], timeZone: .utcTimeZone), + basalRateSchedule: BasalRateSchedule(dailyItems: [RepeatingScheduleValue(startTime: 0, value: rate)], timeZone: .utcTimeZone)) + } + let store = try await reportingSettingsStore([ + profile(at: first, rate: 1, target: 100), + StoredSettings(date: missing), + profile(at: resumed, rate: 2, target: 120), + ]) + + let basal = try await LoopHistoryProvider.basalHistory(in: window, from: store) + let schedule = basal.map { LoopHistoryMath.ScheduleValue(start: $0.startDate, end: $0.endDate, rate: $0.value) } + let delivered = LoopHistoryMath.basalSegments(window: window, schedule: schedule, deliveries: [], + programmedRates: schedule, recordsStart: window.start) + XCTAssertEqual(delivered.reduce(0) { $0 + $1.units }, 3, accuracy: 1e-9, + "Only the two recorded hours can supply inferred basal, not the earlier time or missing profile") + XCTAssertNil(LoopHistoryMath.scheduledUnits(basal.map { ScheduledBasalPoint(start: $0.startDate, end: $0.endDate, rate: $0.value) }, over: window)) + let targets = try await loopDataManager.glucoseTargetBands(in: window, settingsStore: store) + XCTAssertEqual(targets, [TargetBand(start: first, end: missing, range: 100...110), + TargetBand(start: resumed, end: window.end, range: 120...130)]) + + // A query starting during a known profile still includes the setting saved before its start. + let inside = DateInterval(start: first.addingTimeInterval(.minutes(30)), end: missing) + let partial = try await LoopHistoryProvider.basalHistory(in: inside, from: store) + XCTAssertEqual(partial.first?.startDate, inside.start) + XCTAssertEqual(partial.reduce(0) { $0 + $1.value * $1.endDate.timeIntervalSince($1.startDate) / 3600 }, 0.5, accuracy: 1e-9) + let before = DateInterval(start: window.start, end: first) + let earlierBasal = try await LoopHistoryProvider.basalHistory(in: before, from: store) + let earlierTargets = try await loopDataManager.glucoseTargetBands(in: before, settingsStore: store) + XCTAssertTrue(earlierBasal.isEmpty) + XCTAssertTrue(earlierTargets.isEmpty) + } + + private func reportingSettingsStore(_ settings: [StoredSettings]) async throws -> SettingsStore { + let store = SettingsStore(store: PersistenceController.mock(), expireAfter: .days(3650)) + for record in settings { + try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in + store.storeSettings(record) { error in + if let error { continuation.resume(throwing: error) } + else { continuation.resume() } + } + } + } + return store + } + func testFetchDataWithHighInsulinNeedsPresetMitigation() async throws { var input = try await loopDataManager.fetchData(for: now) XCTAssertEqual(input.targetMgdl.count, 1) diff --git a/LoopTests/Models/GlucoseStatisticsTests.swift b/LoopTests/Models/GlucoseStatisticsTests.swift index bac7131796..7f5c86893e 100644 --- a/LoopTests/Models/GlucoseStatisticsTests.swift +++ b/LoopTests/Models/GlucoseStatisticsTests.swift @@ -99,6 +99,29 @@ final class GlucoseStatisticsTests: XCTestCase { } } + /// A reading converted from mmol/L sits between whole mg/dL values, so the band edges + /// have to leave no gap: 10.0 mmol/L is in range and 13.9 mmol/L is high, as the + /// consensus defines them in mmol/L. + func testBandEdgesBetweenWholeMilligrams() { + XCTAssertEqual(GlucoseBand.classify(mgdl: 53.9), .veryLow) + XCTAssertEqual(GlucoseBand.classify(mgdl: 54), .low) + XCTAssertEqual(GlucoseBand.classify(mgdl: 69.9), .low) + XCTAssertEqual(GlucoseBand.classify(mgdl: 70), .target) + XCTAssertEqual(GlucoseBand.classify(mgdl: 180.4), .target) + XCTAssertEqual(GlucoseBand.classify(mgdl: 10.0 * 18.0156), .target) + XCTAssertEqual(GlucoseBand.classify(mgdl: 181), .high) + XCTAssertEqual(GlucoseBand.classify(mgdl: 13.9 * 18.0156), .high) + XCTAssertEqual(GlucoseBand.classify(mgdl: 251), .veryHigh) + } + + func testStandardDeviation() { + let start = midnight + let samples = [sample(90, at: start), sample(110, at: start.addingTimeInterval(.minutes(5)))] + let stats = GlucoseStatistics(samples: samples, start: start, end: start.addingTimeInterval(.minutes(10))) + XCTAssertEqual(stats.standardDeviation!, 200.0.squareRoot(), accuracy: 1e-6) + XCTAssertNil(GlucoseStatistics(samples: [samples[0]], start: start, end: start.addingTimeInterval(.hours(1))).standardDeviation) + } + // MARK: - Percent active func testPercentActive() { @@ -109,6 +132,28 @@ final class GlucoseStatisticsTests: XCTestCase { XCTAssertEqual(stats.percentActive, 0.5, accuracy: 1e-6) } + /// A sensor that reports every minute covers only the minutes it reports, not five + /// minutes a reading. + func testPercentActiveWithOneMinuteReadings() { + let start = midnight + let end = start.addingTimeInterval(.hours(1)) + // Readings every minute for the first 20 minutes, then nothing. + let readings = (0..<20).map { (date: start.addingTimeInterval(.minutes(Double($0))), mgdl: 120.0) } + let stats = GlucoseStatistics(readings: readings, start: start, end: end) + XCTAssertEqual(stats.percentActive, 24.0 / 60, accuracy: 1e-6) // 19 one-minute gaps, then one 5-minute slot + XCTAssertEqual(stats.timeInRange[.target]!, 1, accuracy: 1e-6) + } + + /// Readings thinned to one every 2½ minutes and readings every minute give the same coverage. + func testPercentActiveDoesNotDependOnCadence() { + let start = midnight + let end = start.addingTimeInterval(.hours(1)) + let everyMinute = (0..<60).map { (date: start.addingTimeInterval(.minutes(Double($0))), mgdl: 120.0) } + let thinned = stride(from: 0.0, to: 60, by: 2.5).map { (date: start.addingTimeInterval(.minutes($0)), mgdl: 120.0) } + XCTAssertEqual(GlucoseStatistics(readings: everyMinute, start: start, end: end).percentActive, 1, accuracy: 1e-6) + XCTAssertEqual(GlucoseStatistics(readings: thinned, start: start, end: end).percentActive, 1, accuracy: 1e-6) + } + // MARK: - AGP profile func testAGPProfileBucketing() { diff --git a/LoopTests/Models/LoopHistoryMathTests.swift b/LoopTests/Models/LoopHistoryMathTests.swift new file mode 100644 index 0000000000..b29cfb3f43 --- /dev/null +++ b/LoopTests/Models/LoopHistoryMathTests.swift @@ -0,0 +1,468 @@ +// +// LoopHistoryMathTests.swift +// LoopTests +// +// Copyright © 2026 LoopKit Authors. All rights reserved. +// + +import XCTest +import HealthKit +import LoopKit +@testable import Loop + +class LoopHistoryMathTests: XCTestCase { + + private let start = Date(timeIntervalSinceReferenceDate: 800_000_000) + private func at(_ minutes: Double) -> Date { start.addingTimeInterval(minutes * 60) } + + // MARK: Basal + + func testUnrecordedBasalCountsAtTheProgrammedRateOnlyAfterRecordsBegin() { + let window = DateInterval(start: at(0), end: at(240)) + let programmed = [LoopHistoryMath.ScheduleValue(start: at(0), end: at(240), rate: 1.2)] + let temp = LoopHistoryMath.BasalDelivery(start: at(120), end: at(150), rate: 0.4, kind: .temp, automatic: true) + let segments = LoopHistoryMath.basalSegments(window: window, schedule: programmed, deliveries: [temp], + programmedRates: programmed, recordsStart: at(60)) + // Nothing before the first record; 60–120 and 150–240 at 1.2 U/h; 120–150 at the temp rate. + XCTAssertNil(LoopHistoryMath.basalRate(at: at(30), in: segments)) + XCTAssertEqual(LoopHistoryMath.basalRate(at: at(90), in: segments)?.kind, .scheduled) + XCTAssertEqual(LoopHistoryMath.basalRate(at: at(135), in: segments)?.rate, 0.4) + XCTAssertEqual(segments.reduce(0) { $0 + $1.units }, 1.2 * 2.5 + 0.4 * 0.5, accuracy: 1e-9) + } + + func testBasalGapsDoNotInventDelivery() { + let window = DateInterval(start: at(0), end: at(120)) + let schedule = [LoopHistoryMath.ScheduleValue(start: at(-60), end: at(240), rate: 1.0)] + let temp = LoopHistoryMath.BasalDelivery(start: at(60), end: at(90), rate: 2.0, kind: .temp, automatic: true) + let segments = LoopHistoryMath.basalSegments(window: window, schedule: schedule, deliveries: [temp]) + XCTAssertEqual(segments.count, 1) + XCTAssertEqual(segments.reduce(0) { $0 + $1.units }, 1, accuracy: 1e-9) + XCTAssertEqual(segments[0].netUnits, 0.5, accuracy: 1e-9) + } + + func testSuspendDeliversNothingAndLaterRecordWins() { + let window = DateInterval(start: at(0), end: at(60)) + let schedule = [LoopHistoryMath.ScheduleValue(start: at(0), end: at(60), rate: 1.2)] + let deliveries = [ + LoopHistoryMath.BasalDelivery(start: at(0), end: at(60), rate: 3.0, kind: .temp, automatic: true), + LoopHistoryMath.BasalDelivery(start: at(20), end: at(40), rate: 0, kind: .suspended, automatic: false), + ] + let segments = LoopHistoryMath.basalSegments(window: window, schedule: schedule, deliveries: deliveries) + XCTAssertEqual(segments.map(\.kind), [.temp, .suspended, .temp]) + XCTAssertEqual(segments[1].units, 0) + XCTAssertEqual(segments[1].netUnits, -0.4, accuracy: 1e-9) + } + + func testNormalisedBasalPreservesDeliveredQuantityInPartialWindow() throws { + // The pump reports 1.05 U delivered, although the programmed rate implies 1.0625 U. + let dose = DoseEntry(type: .tempBasal, startDate: at(0), endDate: at(30), value: 2.125, + unit: .unitsPerHour, doseId: nil, deliveredUnits: 1.05, automatic: true) + let delivery = try XCTUnwrap(LoopHistoryMath.BasalDelivery(dose: dose)) + for (end, expected) in [(30.0, 1.05), (15.0, 0.525)] { + let segments = LoopHistoryMath.basalSegments(window: DateInterval(start: at(0), end: at(end)), + schedule: [], deliveries: [delivery]) + XCTAssertEqual(segments.reduce(0) { $0 + $1.units }, expected, accuracy: 1e-9) + } + } + + func testHealthAndLocalPartitionsConserveBasalDelivery() throws { + let sample = HKQuantitySample(type: HKQuantityType(.insulinDelivery), + quantity: HKQuantity(unit: .internationalUnit(), doubleValue: 1), + start: at(0), end: at(60), + metadata: [HKMetadataKeyInsulinDeliveryReason: HKInsulinDeliveryReason.basal.rawValue]) + let left = try XCTUnwrap(BasalSegment(healthSample: sample, in: DateInterval(start: at(-30), end: at(30)))) + let right = try XCTUnwrap(BasalSegment(healthSample: sample, in: DateInterval(start: at(30), end: at(90)))) + XCTAssertEqual(left.units, 0.5, accuracy: 1e-9) + XCTAssertEqual(right.units, 0.5, accuracy: 1e-9, "Include basal beginning before the selected interval") + let dose = DoseEntry(type: .basal, startDate: at(0), endDate: at(60), value: 1, unit: .units, doseId: nil, deliveredUnits: 1) + let local = LoopHistoryMath.basalSegments(window: DateInterval(start: at(30), end: at(90)), schedule: [], + deliveries: [try XCTUnwrap(LoopHistoryMath.BasalDelivery(dose: dose))]) + XCTAssertEqual(left.units + local.reduce(0) { $0 + $1.units }, 1, accuracy: 1e-9) + XCTAssertNil(BasalSegment(healthSample: sample, in: DateInterval(start: at(60), end: at(90)))) + + } + + func testBolusWindowIsHalfOpenAndPreservesDeliveredUnits() { + let window = DateInterval(start: at(0), end: at(60)) + for (minute, expected) in [(-1.0, false), (0.0, true), (30.0, true), (60.0, false)] { + let dose = DoseEntry(type: .bolus, startDate: at(minute), value: 1, unit: .units, doseId: nil, deliveredUnits: 0.75) + let event = BolusEvent(dose: dose, in: window) + XCTAssertEqual(event != nil, expected, "Bolus at minute \(minute)") + if expected { XCTAssertEqual(event?.units, 0.75) } + } + } + + // MARK: Glucose + + func testRoundedPercentagesSumTo100() { + let fractions: [GlucoseBand: Double] = [.veryLow: 1 / 7, .low: 1 / 7, .target: 3 / 7, .high: 1 / 7, .veryHigh: 1 / 7] + let percentages = LoopHistoryMath.roundedPercentages(fractions) + XCTAssertEqual(percentages.values.reduce(0, +), 100) + XCTAssertEqual(percentages[.target], 43) + } + + func testGMIInMmolPerMol() { + // An HbA1c of 7% is 53 mmol/mol. + XCTAssertEqual(LoopHistoryMath.mmolPerMol(percent: 7), 52.98, accuracy: 0.01) + } + + func testCGMCoverageNotedOnlyWhenReadingsStartLate() { + let interval = DateInterval(start: at(0), end: at(14 * 1440)) + let late = [GlucosePoint(date: at(9 * 1440), mgdl: 120), GlucosePoint(date: at(10 * 1440), mgdl: 130)] + XCTAssertEqual(LoopHistoryMath.cgmCoveredDays(late, in: interval, periodDays: 14), 5) + // Within a day of the full period, or a one-day period, says nothing. + XCTAssertNil(LoopHistoryMath.cgmCoveredDays([GlucosePoint(date: at(600), mgdl: 120)], in: interval, periodDays: 14)) + XCTAssertNil(LoopHistoryMath.cgmCoveredDays(late, in: DateInterval(start: at(0), end: at(1440)), periodDays: 1)) + XCTAssertNil(LoopHistoryMath.cgmCoveredDays([], in: interval, periodDays: 14)) + } + + func testGMIIsRepresentativeFromFourteenDaysAtSeventyPercent() { + // "14 d" ending today still counts as 14 days, and exactly 70% passes. + XCTAssertTrue(LoopHistoryMath.gmiIsRepresentative(periodDays: 14, cgmActive: 0.73)) + XCTAssertTrue(LoopHistoryMath.gmiIsRepresentative(periodDays: 14, cgmActive: 0.7)) + XCTAssertTrue(LoopHistoryMath.gmiIsRepresentative(periodDays: 90, cgmActive: 0.95)) + // Each condition on its own is enough to add the caption. + XCTAssertFalse(LoopHistoryMath.gmiIsRepresentative(periodDays: 14, cgmActive: 0.69)) + XCTAssertFalse(LoopHistoryMath.gmiIsRepresentative(periodDays: 7, cgmActive: 1)) + XCTAssertFalse(LoopHistoryMath.gmiIsRepresentative(periodDays: 1, cgmActive: 1)) + } + + func testBandHoursCountOnlyTimeWithReadings() { + // Today until 15:00 with readings 15% of the time: 2.25 h with readings, not 24. + let today = DateInterval(start: at(0), end: at(15 * 60)) + XCTAssertEqual(LoopHistoryMath.cgmHoursPerDay(cgmActive: 0.15, over: today, periodDays: 1), 2.25, accuracy: 1e-9) + // A longer period averages over its days. + let fortnight = DateInterval(start: at(0), end: at(14 * 1440)) + XCTAssertEqual(LoopHistoryMath.cgmHoursPerDay(cgmActive: 0.75, over: fortnight, periodDays: 14), 18, accuracy: 1e-9) + } + + func testHealthGlucoseThinningKeepsCGMReadingsBesideFingersticks() { + let points = [ + GlucosePoint(date: at(0), mgdl: 100), + GlucosePoint(date: at(0.5), mgdl: 100), // the same reading from another app + GlucosePoint(date: at(4), mgdl: 140, userEntered: true), // a fingerstick a minute before the next reading + GlucosePoint(date: at(5), mgdl: 110), + GlucosePoint(date: at(10), mgdl: 120), + ] + let thinned = LoopHistoryMath.thinnedHealthGlucose(points) + XCTAssertEqual(thinned.map(\.date), [at(0), at(4), at(5), at(10)]) + XCTAssertEqual(thinned.filter { !$0.userEntered }.count, 3) + } + + func testHealthBoundaryIsTheLaterOfLocalHistoryAndFirstRecord() { + let localStart = at(0), now = at(90 * 1440) + // Loop began recording 20 days into its 90-day history: Health covers the days before. + XCTAssertEqual(LoopHistoryMath.healthBoundary(localHistoryStart: localStart, firstLocalRecord: at(20 * 1440), now: now), at(20 * 1440)) + // A record older than the local history has been purged up to its start. + XCTAssertEqual(LoopHistoryMath.healthBoundary(localHistoryStart: localStart, firstLocalRecord: at(-60), now: now), localStart) + // No records of a kind: all of it comes from Health. + XCTAssertEqual(LoopHistoryMath.healthBoundary(localHistoryStart: localStart, firstLocalRecord: nil, now: now), now) + } + + func testFirstRecordIgnoresRecordsOutsideTheChunk() { + let chunk = DateInterval(start: at(0), end: at(7 * 1440)) + // A dose still in progress today comes back with an older week's query; it isn't that week's first record. + let inProgress = (start: at(30 * 1440), end: at(30 * 1440 + 30)) + XCTAssertNil(LoopHistoryMath.firstRecord(in: chunk, of: [inProgress])) + // A basal crossing into the chunk keeps its real start, and a bolus counts by its start. + let crossing = (start: at(-60), end: at(60)) + let bolus = (start: at(120), end: at(120)) + XCTAssertEqual(LoopHistoryMath.firstRecord(in: chunk, of: [inProgress, bolus, crossing]), at(-60)) + XCTAssertEqual(LoopHistoryMath.firstRecord(in: chunk, of: [inProgress, bolus]), at(120)) + // A bolus before the chunk, or at its end, is outside it. + XCTAssertNil(LoopHistoryMath.firstRecord(in: chunk, of: [(start: at(-5), end: at(-5)), (start: chunk.end, end: chunk.end)])) + } + + func testLoggedInjectionsAreManualAndMissingFlagsUnknown() { + let window = DateInterval(start: at(0), end: at(60)) + for (automatic, entered, manual, auto, unknown) in [ + (nil, true, 1.0, 0.0, 0.0), + (true, true, 1.0, 0.0, 0.0), + (false, false, 1.0, 0.0, 0.0), + (true, false, 0.0, 1.0, 0.0), + (nil, false, 0.0, 0.0, 1.0), + ] as [(Bool?, Bool, Double, Double, Double)] { + let dose = DoseEntry(type: .bolus, startDate: at(5), value: 1, unit: .units, doseId: nil, + automatic: automatic, manuallyEntered: entered) + guard let event = BolusEvent(dose: dose, in: window) else { return XCTFail("Dose must be in the window") } + let split = InsulinSplit(basal: 0, boluses: [event]) + XCTAssertEqual(split.manualBolus, manual) + XCTAssertEqual(split.automaticBolus, auto) + XCTAssertEqual(split.unclassifiedBolus, unknown) + } + } + + func testHealthAndLocalPartsMeetWithoutOverlap() { + let window = DateInterval(start: at(0), end: at(1440)) + let straddling = LoopHistoryMath.split(window, at: at(600)) + XCTAssertEqual(straddling.health, DateInterval(start: at(0), end: at(600))) + XCTAssertEqual(straddling.local, DateInterval(start: at(600), end: at(1440))) + let allLocal = LoopHistoryMath.split(window, at: at(-60)) + XCTAssertNil(allLocal.health) + XCTAssertEqual(allLocal.local, window) + let allHealth = LoopHistoryMath.split(window, at: at(1440)) + XCTAssertEqual(allHealth.health, window) + XCTAssertNil(allHealth.local) + } + + func testBolusPartsNeverTouchAndKeepTheirHeight() { + let day = LoopHistoryMath.DayTotal(day: at(0), split: InsulinSplit(basal: 20, manualBolus: 10, automaticBolus: 0.2, unclassifiedBolus: 2)) + let parts = InsulinDailyTotalsView.bolusParts(day, gap: 0.5) + XCTAssertEqual(parts.map(\.automatic), [false, true]) + // Manual and unknown together, a gap above basal, keeping its top. + XCTAssertEqual(parts[0].start, 20.5, accuracy: 1e-9) + XCTAssertEqual(parts[0].end, 32, accuracy: 1e-9) + // Automatic is shorter than two gaps, so it moves up a gap and keeps its full height. + XCTAssertEqual(parts[1].start, 32.5, accuracy: 1e-9) + XCTAssertEqual(parts[1].end - parts[1].start, 0.2, accuracy: 1e-9) + XCTAssertTrue(InsulinDailyTotalsView.bolusParts(LoopHistoryMath.DayTotal(day: at(0), basal: 20, bolus: 0), gap: 0.5).isEmpty) + } + + func testScheduledUnitsNeedTheWholeSpanCovered() { + let points = [ScheduledBasalPoint(start: at(0), end: at(120), rate: 1.0), ScheduledBasalPoint(start: at(120), end: at(240), rate: 0.5)] + XCTAssertEqual(try XCTUnwrap(LoopHistoryMath.scheduledUnits(points, over: DateInterval(start: at(60), end: at(180)))), 1.5, accuracy: 1e-9) + XCTAssertNil(LoopHistoryMath.scheduledUnits(points, over: DateInterval(start: at(60), end: at(360)))) + } + + // MARK: Loop modes + + func testLoopModesStartAtFirstModeRecord() { + let interval = DateInterval(start: at(0), end: at(60)) + let runs = stride(from: 0.0, through: 60, by: 5).map { LoopHistoryMath.LoopRun(date: at($0), succeeded: true) } + let spans = LoopHistoryMath.loopModeSpans(interval: interval, runs: runs, + modeChanges: [.init(date: at(30), closedLoop: true)], coverageStart: at(0)) + XCTAssertEqual(spans.first?.start, at(30), "Before the first record the mode is unknown and left out") + XCTAssertEqual(LoopHistoryMath.duration(of: .closed, in: spans), 30 * 60, accuracy: 1) + + XCTAssertTrue(LoopHistoryMath.loopModeSpans(interval: interval, runs: runs, modeChanges: [], coverageStart: at(0)).isEmpty) + } + + func testLoopModesClassifyOpenAndLimited() { + let interval = DateInterval(start: at(0), end: at(90)) + // Runs succeed until 20 min, then fail with an error, then stop. + var runs = stride(from: 0.0, through: 20, by: 5).map { LoopHistoryMath.LoopRun(date: at($0), succeeded: true) } + runs.append(.init(date: at(25), succeeded: false)) + let changes: [LoopHistoryMath.ModeChange] = [.init(date: at(0), closedLoop: true), .init(date: at(60), closedLoop: false)] + + let spans = LoopHistoryMath.loopModeSpans(interval: interval, runs: runs, modeChanges: changes, coverageStart: at(0)) + XCTAssertEqual(spans.map(\.mode), [.closed, .limited, .open]) + XCTAssertEqual(spans[1].start, at(35), "Limited starts once the last good run is over 15 minutes old") + XCTAssertEqual(spans[2].start, at(55), "The slot ending at the switch-off counts as open") + } + + func testManualTempBasalCountsAsOpenLoop() { + let interval = DateInterval(start: at(0), end: at(60)) + // Closed loop stays on; from 20 min a manual temp basal holds every run, until it ends at 40 min. + let runs = stride(from: 0.0, through: 60, by: 5).map { minute in + LoopHistoryMath.LoopRun(date: at(minute), succeeded: !(20...40).contains(minute), manualTempBasal: (20...40).contains(minute)) + } + let spans = LoopHistoryMath.loopModeSpans(interval: interval, runs: runs, modeChanges: [.init(date: at(0), closedLoop: true)], + coverageStart: at(0)) + XCTAssertEqual(spans.map(\.mode), [.closed, .open, .closed]) + XCTAssertEqual(spans[1].start, at(15), "The slot holding the first held run is open") + XCTAssertEqual(spans[2].start, at(40), "Closed again with the first good run after it") + } + + func testManualTempBasalStaysOpenWhenALaterRunFailsForAnotherReason() { + let interval = DateInterval(start: at(0), end: at(60)) + // A manual temp basal runs 20–40 min. The run at 25 is held by it; from 30 glucose is stale, so later runs fail + // on that before Loop checks for the manual temp basal. + let runs = stride(from: 0.0, through: 60, by: 5).map { minute in + LoopHistoryMath.LoopRun(date: at(minute), succeeded: minute < 20 || minute > 40, manualTempBasal: minute == 25) + } + let spans = LoopHistoryMath.loopModeSpans(interval: interval, runs: runs, modeChanges: [.init(date: at(0), closedLoop: true)], + coverageStart: at(0), manualTempBasals: [DateInterval(start: at(20), end: at(40))]) + XCTAssertEqual(spans.map(\.mode), [.closed, .open, .closed]) + XCTAssertEqual(spans[1].start, at(20)) + XCTAssertEqual(spans[1].end, at(40), "Open for the whole manual temp basal, not just after the run it held") + } + + func testRecordedCancellationEndsManualTempBasalBeforeTheRunFallback() { + let interval = DateInterval(start: at(0), end: at(30)) + // A good run at 0; a manual temp basal from 3 holds the run at 5; it's cancelled at 12, and no runs follow. + let runs = [LoopHistoryMath.LoopRun(date: at(0), succeeded: true), .init(date: at(5), succeeded: false, manualTempBasal: true)] + let changes: [LoopHistoryMath.ModeChange] = [.init(date: at(0), closedLoop: true)] + let spans = LoopHistoryMath.loopModeSpans(interval: interval, runs: runs, modeChanges: changes, + coverageStart: at(0), manualTempBasals: [DateInterval(start: at(3), end: at(12))]) + XCTAssertEqual(spans.map(\.mode), [.closed, .open, .closed, .limited]) + XCTAssertEqual(spans[1].start, at(5)) + XCTAssertEqual(spans[1].end, at(10), "Open while the recorded temp basal runs, not for 15 minutes after the run it held") + XCTAssertEqual(spans[3].start, at(15), "Limited once the last good run is over 15 minutes old") + + // A period starting after the cancellation still needs the preceding dose record. This can happen at + // midnight, while the last held run is recent enough for the fallback to apply. + let nextPeriod = LoopHistoryMath.loopModeSpans(interval: DateInterval(start: at(15), end: at(30)), runs: runs, + modeChanges: changes, coverageStart: at(0), + manualTempBasals: [DateInterval(start: at(3), end: at(12))]) + XCTAssertEqual(nextPeriod.map(\.mode), [.limited]) + + // With no dose record, the held run alone keeps the loop open for 15 minutes. + let unrecorded = LoopHistoryMath.loopModeSpans(interval: interval, runs: runs, modeChanges: changes, coverageStart: at(0)) + XCTAssertEqual(unrecorded.map(\.mode), [.open, .limited]) + XCTAssertEqual(unrecorded[1].start, at(20)) + } + + // MARK: Calendar + + func testDaysAndQuarterMarksOnClockChangeDay() throws { + var calendar = Calendar(identifier: .gregorian) + calendar.timeZone = try XCTUnwrap(TimeZone(identifier: "Europe/London")) + // 25 Oct 2026: clocks go back an hour, so the day is 25 hours long. + let day = try XCTUnwrap(calendar.date(from: DateComponents(year: 2026, month: 10, day: 25))) + let next = try XCTUnwrap(calendar.date(byAdding: .day, value: 1, to: day)) + XCTAssertEqual(next.timeIntervalSince(day), 25 * 3600) + + let marks = DayAxis.quarterDayMarks(in: DateInterval(start: day, end: next), calendar: calendar) + XCTAssertEqual(marks.map { calendar.component(.hour, from: $0) }, [0, 6, 12, 18, 0]) + + let days = LoopHistoryMath.days(in: DateInterval(start: day, end: next.addingTimeInterval(3600)), calendar: calendar) + XCTAssertEqual(days.count, 2) + XCTAssertEqual(days[0].duration, 25 * 3600) + } + + func testWeeklyAveragesDays() { + let monday = Date(timeIntervalSinceReferenceDate: 815_270_400) // 9436 days after Monday 1 Jan 2001, so a Monday at midnight UTC + var calendar = Calendar(identifier: .gregorian) + calendar.timeZone = TimeZone(identifier: "UTC")! + let totals = (0..<14).map { LoopHistoryMath.DayTotal(day: monday.addingTimeInterval(Double($0) * 86400), basal: 10, bolus: Double($0)) } + let weeks = LoopHistoryMath.weekly(totals, calendar: calendar) + XCTAssertEqual(weeks.count, 2) + XCTAssertEqual(weeks[0].bolus, 3, accuracy: 1e-9) + XCTAssertEqual(weeks[1].bolus, 10, accuracy: 1e-9) + } + + func testDailyInsulinAverageLeavesOutTheDayInProgress() { + let day0 = Date(timeIntervalSinceReferenceDate: 815_270_400) + let complete = (0..<3).map { LoopHistoryMath.DayTotal(day: day0.addingTimeInterval(Double($0) * 86400), basal: 10, bolus: 20) } + let today = LoopHistoryMath.DayTotal(day: day0.addingTimeInterval(3 * 86400), basal: 3, bolus: 2, isComplete: false) + XCTAssertEqual(LoopHistoryMath.averageDailyInsulin(complete + [today]), 30, accuracy: 1e-9) + XCTAssertEqual(LoopHistoryMath.averagingDays(complete + [today]).count, 3) + // With nothing complete, the day in progress is all there is to show. + XCTAssertEqual(LoopHistoryMath.averageDailyInsulin([today]), 5, accuracy: 1e-9) + } + + func testInsulinSplitSeparatesManualAutomaticAndUnclassifiedBolus() { + let boluses = [ + BolusEvent(id: "m", date: at(0), units: 4, automatic: false, manuallyEntered: false), + BolusEvent(id: "a", date: at(5), units: 0.5, automatic: true, manuallyEntered: false), + BolusEvent(id: "u", date: at(10), units: 1, automatic: false, manuallyEntered: false, automaticKnown: false), + ] + let split = InsulinSplit(basal: 14.5, boluses: Array(boluses.prefix(2))) + XCTAssertEqual(split.manualBolus, 4, accuracy: 1e-9) + XCTAssertEqual(split.automaticBolus, 0.5, accuracy: 1e-9) + XCTAssertEqual(split.total, 19, accuracy: 1e-9) + XCTAssertTrue(split.isClassified) + // Shares round independently but always add up to 100. + XCTAssertEqual(split.basalPercent + split.bolusPercent, 100) + XCTAssertEqual(split.bolusPercent, 24) + + // A bolus that doesn't say who gave it still counts, but hides the manual and automatic detail. + let health = InsulinSplit(basal: 14.5, boluses: boluses) + XCTAssertEqual(health.bolus, 5.5, accuracy: 1e-9) + XCTAssertFalse(health.isClassified) + + let average = InsulinSplit.average([split, InsulinSplit(basal: 10.5, manualBolus: 2, automaticBolus: 1.5)]) + XCTAssertEqual(average.basal, 12.5, accuracy: 1e-9) + XCTAssertEqual(average.manualBolus, 3, accuracy: 1e-9) + XCTAssertEqual(average.automaticBolus, 1, accuracy: 1e-9) + } + + func testWeeklyInsulinUsesTheSummaryAveragingDays() { + let monday = Date(timeIntervalSinceReferenceDate: 815_270_400) + var calendar = Calendar(identifier: .gregorian) + calendar.timeZone = TimeZone(identifier: "UTC")! + let totals = [ + LoopHistoryMath.DayTotal(day: monday, basal: 0, bolus: 0), + LoopHistoryMath.DayTotal(day: monday.addingTimeInterval(86400), basal: 10, bolus: 20), + LoopHistoryMath.DayTotal(day: monday.addingTimeInterval(2 * 86400), basal: 10, bolus: 20), + LoopHistoryMath.DayTotal(day: monday.addingTimeInterval(3 * 86400), basal: 1, bolus: 2, isComplete: false), + ] + let weeks = LoopHistoryMath.weekly(totals, calendar: calendar) + XCTAssertEqual(weeks.count, 1) + XCTAssertEqual(weeks[0].basal, 10, accuracy: 1e-9) + XCTAssertEqual(weeks[0].bolus, 20, accuracy: 1e-9) + + // A current week with no complete day must still show the data it has. + let currentWeek = LoopHistoryMath.weekly([totals[3]], calendar: calendar) + XCTAssertEqual(currentWeek.first?.total, 3) + } + + func testGapMessageForADayWithoutReadings() { + let start = Date(timeIntervalSinceReferenceDate: 815_270_400) + let day = DateInterval(start: start, duration: 86400) + let empty = DayAxis.gaps(in: [], window: day, until: day.end.addingTimeInterval(3600)) + XCTAssertEqual(DayAxis.gapMessage(empty, window: day, until: day.end.addingTimeInterval(3600)), "No CGM data on this day") + let morning = start.addingTimeInterval(9 * 3600) + XCTAssertEqual(DayAxis.gapMessage(DayAxis.gaps(in: [], window: day, until: morning), window: day, until: morning), "No CGM data yet today") + let reading = [GlucosePoint(date: start.addingTimeInterval(12 * 3600), mgdl: 120)] + let partial = DayAxis.gaps(in: reading, window: day, until: day.end) + XCTAssertTrue(DayAxis.gapMessage(partial, window: day, until: day.end)?.hasSuffix("and 1 shorter gap") ?? false) + } + + // MARK: Formatting + + func testRangeFormatting() throws { + let calendar = Calendar.current + let a = try XCTUnwrap(calendar.date(from: DateComponents(year: 2026, month: 10, day: 12, hour: 12))) + let b = try XCTUnwrap(calendar.date(from: DateComponents(year: 2026, month: 10, day: 25, hour: 12))) + let c = try XCTUnwrap(calendar.date(from: DateComponents(year: 2026, month: 9, day: 28, hour: 12))) + // Ranges and durations come from the system's formatters, so they follow the user's locale; + // the test host runs in en_US. + XCTAssertEqual(LoopFormat.range(b, b), LoopFormat.day(b)) + let sameMonth = LoopFormat.range(a, b) + XCTAssertTrue(sameMonth.contains("12") && sameMonth.contains("25")) + XCTAssertEqual(sameMonth.components(separatedBy: "2026").count, 2, "the year appears once") + let twoMonths = LoopFormat.range(c, b) + XCTAssertTrue(twoMonths.contains("Sep") && twoMonths.contains("Oct")) + XCTAssertEqual(LoopFormat.duration(13 * 86400 + 11 * 3600), "13d 11h") + XCTAssertEqual(LoopFormat.duration(9 * 3600 + 45 * 60), "9h 45m") + XCTAssertEqual(LoopFormat.number(7.25, decimals: 1), 7.25.formatted(.number.precision(.fractionLength(1)).grouping(.never))) + XCTAssertEqual(LoopFormat.signed(-0.4), "−0.40") + XCTAssertEqual(LoopFormat.signed(0.0001), "+0.00") + } + + // MARK: Day history and Logbook folding + + private func logRow(_ id: String, _ minutes: Double, automaticUnits: Double? = nil, basalSummary: Bool = false) -> LogEntry { + LogEntry(id: id, date: at(minutes), title: id, subtitle: "", amount: "", amountColor: .primary, detail: "", + icon: "plus", iconStyle: .solid(.primary), filters: [], + basalChanges: basalSummary ? [BasalSegment(start: at(0), end: at(30), rate: 0, scheduledRate: 1, kind: .temp, automatic: true)] : [], + automaticUnits: automaticUnits) + } + + @MainActor + func testLogbookFoldsRunsOfAutomaticBolusesBetweenOtherEntries() { + // Newest first, as the Logbook lists them. + let rows = [ + logRow("auto5", 100, automaticUnits: 0.3), + logRow("auto4", 95, automaticUnits: 0.2), + logRow("basal", 90, basalSummary: true), + logRow("auto3", 85, automaticUnits: 0.1), + logRow("carbs", 60), + logRow("auto2", 30, automaticUnits: 0.5), + logRow("manual", 20), + logRow("auto1", 10, automaticUnits: 0.1), + ] + let folded = LogbookModel.foldingAutomaticBoluses(rows) + // auto5, auto4 and auto3 fold together: the basal summary doesn't break a run, the carbs do. + XCTAssertEqual(folded.map(\.id), ["autorun-auto5", "basal", "carbs", "auto2", "manual", "auto1"]) + XCTAssertEqual(folded[0].bolusRun.map(\.id), ["auto5", "auto4", "auto3"]) + XCTAssertEqual(folded[0].date, at(100)) + XCTAssertTrue(folded[0].matches(.loop) && folded[0].matches(.bolus)) + XCTAssertEqual(folded[0].amount, LoopFormat.doseUnits(0.6)) + } + + + func testDayHistoryClippedToNowDropsLaterEventsAndCutsBasal() { + var history = DayHistory(window: DateInterval(start: at(0), end: at(1440))) + history.glucose = [GlucosePoint(date: at(10), mgdl: 100), GlucosePoint(date: at(700), mgdl: 120)] + history.boluses = [BolusEvent(id: "a", date: at(30), units: 1, automatic: false, manuallyEntered: false), + BolusEvent(id: "b", date: at(650), units: 2, automatic: true, manuallyEntered: false)] + history.basal = [BasalSegment(start: at(0), end: at(720), rate: 1, scheduledRate: 1, kind: .scheduled, automatic: false)] + let clipped = history.clipped(to: DateInterval(start: at(0), end: at(600))) + XCTAssertEqual(clipped.window.end, at(600)) + XCTAssertEqual(clipped.glucose.count, 1) + XCTAssertEqual(clipped.boluses.map(\.id), ["a"]) + XCTAssertEqual(clipped.basalUnits, 10, accuracy: 1e-9) + } +} diff --git a/README.md b/README.md index 40506a4c42..099d1d64dc 100644 --- a/README.md +++ b/README.md @@ -17,8 +17,6 @@ Please understand that this project: Presets screen Live Activity on the Lock Screen -Statistics with glucose metrics and time in range -Daily insulin totals on the Statistics screen Choosing a CGM Apple Watch app @@ -34,7 +32,7 @@ Please understand that this project: - **Automated insulin delivery.** Loop forecasts glucose several hours ahead and adjusts delivery with each new glucose reading, using either temporary basal rates or automatic boluses. - **Meal and correction boluses** with a recommended amount and a forecast of where glucose is heading. Carb entries can include food type, absorption time and saved favorite foods. - **Presets** that temporarily adjust insulin needs and correction range: pre-meal, your own custom presets, and built-in activity presets for walking, jogging, biking and strength training (which can be hidden). Presets can be scheduled, and in-app training explains how to use them. -- **Statistics**: GMI, average glucose, variability and time in range, an ambulatory glucose profile, and daily insulin totals split into basal, automatic bolus and manual bolus. +- **Trends**: time in range, GMI, average glucose and variability, a daily glucose pattern, insulin per day split into basal, manual bolus and automatic bolus, and time in closed loop, for one day or for 7 to 90 days. - **Live Activity** on the Lock Screen, in the Dynamic Island and on CarPlay. - **Apple Watch app** with glucose and forecast, carb entry, bolus and presets. - **Alerts** for glucose and device conditions, with urgent alerts that sound even when the phone is silenced or in a Focus.