CurrentGlucoseView.swift 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  1. import CoreData
  2. import LoopKit
  3. import SwiftUI
  4. struct CurrentGlucoseView: View {
  5. let timerDate: Date
  6. let units: GlucoseUnits
  7. let alarm: GlucoseAlarm?
  8. let lowGlucose: Decimal
  9. let highGlucose: Decimal
  10. let cgmAvailable: Bool
  11. var currentGlucoseTarget: Decimal
  12. let glucoseColorScheme: GlucoseColorScheme
  13. let glucose: [GlucoseStored] // This contains the last two glucose values, no matter if its manual or a cgm reading
  14. /// Drives the outer ring.
  15. var cgmProgress: DeviceLifecycleProgress?
  16. /// CGM status highlight, rendered verbatim.
  17. var cgmStatus: CgmDisplayState?
  18. /// Sensor expiration — fallback tag when `cgmStatus` is nil.
  19. var cgmSensorExpiresAt: Date?
  20. /// Wall-clock end of the warmup window. Drives the warmup countdown tag.
  21. var cgmWarmupEndsAt: Date?
  22. @State private var rotationDegrees: Double = 0.0
  23. @State private var angularGradient = AngularGradient(colors: [
  24. Color(red: 0.7215686275, green: 0.3411764706, blue: 1),
  25. Color(red: 0.6235294118, green: 0.4235294118, blue: 0.9803921569),
  26. Color(red: 0.4862745098, green: 0.5450980392, blue: 0.9529411765),
  27. Color(red: 0.3411764706, green: 0.6666666667, blue: 0.9254901961),
  28. Color(red: 0.262745098, green: 0.7333333333, blue: 0.9137254902),
  29. Color(red: 0.7215686275, green: 0.3411764706, blue: 1)
  30. ], center: .center, startAngle: .degrees(270), endAngle: .degrees(-90))
  31. @Environment(\.colorScheme) var colorScheme
  32. private var deltaFormatter: NumberFormatter {
  33. let formatter = NumberFormatter()
  34. formatter.numberStyle = .decimal
  35. if units == .mmolL {
  36. formatter.maximumFractionDigits = 1
  37. formatter.minimumFractionDigits = 1
  38. formatter.roundingMode = .halfUp
  39. } else {
  40. formatter.maximumFractionDigits = 0
  41. }
  42. formatter.positivePrefix = " +"
  43. formatter.negativePrefix = " -"
  44. return formatter
  45. }
  46. var body: some View {
  47. let triangleColor = Color(red: 0.262745098, green: 0.7333333333, blue: 0.9137254902)
  48. if cgmAvailable {
  49. if let stale = stalenessState {
  50. // Compact error/transition state — same styles as the
  51. // empty-state "Add CGM" layout below, just colored by tier.
  52. VStack(alignment: .center, spacing: 12) {
  53. HStack {
  54. Image(systemName: stale.imageName)
  55. .font(.body)
  56. .imageScale(.large)
  57. .foregroundStyle(stale.color)
  58. }
  59. HStack {
  60. Text(stale.label)
  61. .font(.caption).bold()
  62. .foregroundStyle(stale.color)
  63. }
  64. }.frame(alignment: .top)
  65. } else {
  66. // Bobble renders at 0.9 to leave breathing room for the right
  67. // panel + pump view siblings; the compact and empty-state
  68. // branches above and below already fit at 1.0.
  69. bobbleAndTag(triangleColor: triangleColor)
  70. .scaleEffect(0.9)
  71. }
  72. } else {
  73. VStack(alignment: .center, spacing: 12) {
  74. HStack
  75. {
  76. // no cgm defined so display a generic CGM
  77. Image(systemName: "sensor.tag.radiowaves.forward.fill").font(.body).imageScale(.large)
  78. }
  79. HStack {
  80. Text("Add CGM").font(.caption).bold()
  81. }
  82. }.frame(alignment: .top)
  83. }
  84. }
  85. @ViewBuilder private func bobbleAndTag(triangleColor: Color) -> some View {
  86. ZStack {
  87. Circle()
  88. .fill(triangleColor)
  89. .frame(width: 124, height: 124)
  90. .blur(radius: 24)
  91. .opacity(colorScheme == .dark ? 0.32 : 0.20)
  92. if let progress = cgmProgress, shouldShowArc {
  93. SensorLifecycleArcView(
  94. progress: progress.percentComplete,
  95. progressState: progress.progressState
  96. )
  97. }
  98. TrendShape(gradient: angularGradient, color: triangleColor, showArrow: true)
  99. .rotationEffect(.degrees(rotationDegrees))
  100. VStack(alignment: .center) {
  101. bobbleContent()
  102. }
  103. }
  104. .overlay(alignment: .bottom) {
  105. // Overlay (not VStack) so the tag doesn't push siblings down;
  106. // hidden when the trend arrow rotates toward 6 o'clock.
  107. if let tag = tagLabel, !trendIsDownward {
  108. SensorStatusTagView(text: tag.text, theme: tag.theme, iconSystemName: tag.icon)
  109. .offset(y: 14)
  110. .zIndex(1)
  111. }
  112. }
  113. .onChange(of: glucose.last?.directionEnum) {
  114. withAnimation {
  115. switch glucose.last?.directionEnum {
  116. case .doubleUp,
  117. .singleUp,
  118. .tripleUp:
  119. rotationDegrees = -90
  120. case .fortyFiveUp:
  121. rotationDegrees = -45
  122. case .flat:
  123. rotationDegrees = 0
  124. case .fortyFiveDown:
  125. rotationDegrees = 45
  126. case .doubleDown,
  127. .singleDown,
  128. .tripleDown:
  129. rotationDegrees = 90
  130. case nil,
  131. .notComputable,
  132. .rateOutOfRange:
  133. rotationDegrees = 0
  134. default:
  135. rotationDegrees = 0
  136. }
  137. }
  138. }
  139. }
  140. private var delta: String {
  141. guard glucose.count >= 2 else {
  142. return "--"
  143. }
  144. var lastGlucose = Decimal(glucose.last?.glucose ?? 0)
  145. var secondLastGlucose = Decimal(glucose.first?.glucose ?? 0)
  146. if units == .mmolL {
  147. lastGlucose = lastGlucose.asMmolL
  148. secondLastGlucose = secondLastGlucose.asMmolL
  149. }
  150. let delta = lastGlucose - secondLastGlucose
  151. return deltaFormatter.string(from: delta as NSNumber) ?? "--"
  152. }
  153. @ViewBuilder private func bobbleContent() -> some View {
  154. HStack {
  155. if let glucoseValue = glucose.last?.glucose, isReadingFresh {
  156. let displayGlucose = units == .mgdL
  157. ? Decimal(glucoseValue).description
  158. : Decimal(glucoseValue).formattedAsMmolL
  159. Text(glucoseValue == 400 ? "HIGH" : displayGlucose)
  160. .font(.system(size: 40, weight: .bold, design: .rounded))
  161. .foregroundStyle(glucoseColor(for: glucoseValue))
  162. } else {
  163. Text("– –")
  164. .font(.system(size: 40, weight: .bold, design: .rounded))
  165. .foregroundStyle(.secondary)
  166. }
  167. }
  168. if isReadingFresh {
  169. HStack {
  170. let minutesAgoString = TimeAgoFormatter.minutesAgo(from: glucose.last?.date)
  171. Group {
  172. Text(minutesAgoString)
  173. Text(delta)
  174. }
  175. .font(.callout).fontWeight(.bold)
  176. .foregroundStyle(colorScheme == .dark ? Color.white.opacity(0.9) : Color.secondary)
  177. }
  178. .frame(alignment: .top)
  179. }
  180. }
  181. /// Matches `APSManager`'s loop-input freshness gate — readings older than
  182. /// 12 minutes (one missed CGM transmission on a 5-min schedule) get
  183. /// masked to dashes. Handles warmup + sensor failure naturally: no
  184. /// fresh data → no number on the bobble.
  185. private var isReadingFresh: Bool {
  186. guard let date = glucose.last?.date else { return false }
  187. return Date().timeIntervalSince(date) < 12 * 60
  188. }
  189. private var trendIsDownward: Bool { rotationDegrees >= 90 }
  190. /// Error/transition states (sensor expired, sensor failure, signal loss,
  191. /// stabilizing, etc.) collapse the bobble to a compact symbol-over-label
  192. /// view — the bobble's purpose is to show glucose, so a fresh-reading-less
  193. /// bobble with arc + dashes obscures rather than informs. Warmup is the
  194. /// exception: it's a short, expected lifecycle phase and the arc + tag
  195. /// countdown carry useful info, so the bobble stays.
  196. private var stalenessState: (imageName: String, label: String, color: Color)? {
  197. guard !isReadingFresh,
  198. !isInWarmup,
  199. let status = cgmStatus,
  200. !status.imageName.isEmpty
  201. else { return nil }
  202. let color: Color
  203. switch status.status {
  204. case .critical: color = .loopRed
  205. case .warning: color = .orange
  206. case .normal: color = .secondary
  207. }
  208. // LibreLoop/G7 split labels with "\n" for their two-line native pills;
  209. // collapse to spaces so the compact label reads cleanly.
  210. let oneLine = status.localizedMessage.replacingOccurrences(of: "\n", with: " ")
  211. return (status.imageName, oneLine, color)
  212. }
  213. /// Arc shown for warmup, the last 48 h of a time-based sensor (incl.
  214. /// grace period), or any non-normal state from a battery-based manager.
  215. private var shouldShowArc: Bool {
  216. if isInWarmup { return true }
  217. if let expiresAt = cgmSensorExpiresAt {
  218. return expiresAt.timeIntervalSinceNow <= 48 * 60 * 60
  219. }
  220. return cgmProgress?.progressState != .normalCGM
  221. }
  222. /// String sniff — loopandlearn LoopKit has no structural warmup flag.
  223. private var isInWarmup: Bool {
  224. guard let message = cgmStatus?.localizedMessage else { return false }
  225. let lowered = message.lowercased()
  226. return lowered.contains("warming up") || lowered.contains("warmup")
  227. }
  228. private var isStabilizing: Bool {
  229. cgmStatus?.localizedMessage.lowercased().contains("stabilizing") ?? false
  230. }
  231. /// Warmup → hourglass + countdown; stabilizing → hourglass + "Stabilizing"
  232. /// (no countdown — duration is sensor-driven); outside warmup/stabilizing
  233. /// the tag is gated to the same 48h window as the arc.
  234. private var tagLabel: (text: String, theme: SensorStatusTagTheme, icon: String?)? {
  235. if isInWarmup {
  236. let text: String
  237. if let endsAt = cgmWarmupEndsAt {
  238. text = SensorRemainingTimeFormatter.format(until: endsAt)
  239. } else {
  240. text = "Warming up"
  241. }
  242. return (text, .orange, "hourglass")
  243. }
  244. if isStabilizing {
  245. return ("Stabilizing", .orange, "hourglass")
  246. }
  247. guard shouldShowArc else { return nil }
  248. if let status = cgmStatus {
  249. // LibreLoop's cgmStatusHighlight uses "\n" to split two-line pill
  250. // labels ("Signal\nLoss", "Sensor\nWarmup"); we render in a
  251. // single-line tag, so collapse newlines to spaces here.
  252. let oneLine = status.localizedMessage.replacingOccurrences(of: "\n", with: " ")
  253. return (oneLine, theme(for: status.status), nil)
  254. }
  255. if let expiresAt = cgmSensorExpiresAt {
  256. let text = SensorRemainingTimeFormatter.format(until: expiresAt)
  257. let theme: SensorStatusTagTheme
  258. switch cgmProgress?.progressState {
  259. case .critical: theme = .red
  260. case .warning: theme = .orange
  261. default: theme = .green
  262. }
  263. return (text, theme, nil)
  264. }
  265. return nil
  266. }
  267. private func theme(for status: CgmDisplayStatus) -> SensorStatusTagTheme {
  268. switch status {
  269. case .critical: return .red
  270. case .warning: return .orange
  271. case .normal: return .secondary
  272. }
  273. }
  274. private func glucoseColor(for glucoseValue: Int16) -> Color {
  275. // TODO: workaround for now: set low value to 55, to have dynamic color shades between 55 and user-set low (approx. 70); same for high glucose
  276. let hardCodedLow = Decimal(55)
  277. let hardCodedHigh = Decimal(220)
  278. let isDynamicColorScheme = glucoseColorScheme == .dynamicColor
  279. guard Decimal(glucoseValue) <= lowGlucose || Decimal(glucoseValue) >= highGlucose else {
  280. return Color.primary
  281. }
  282. return Trio.getDynamicGlucoseColor(
  283. glucoseValue: Decimal(glucoseValue),
  284. highGlucoseColorValue: isDynamicColorScheme ? hardCodedHigh : highGlucose,
  285. lowGlucoseColorValue: isDynamicColorScheme ? hardCodedLow : lowGlucose,
  286. targetGlucose: currentGlucoseTarget,
  287. glucoseColorScheme: glucoseColorScheme
  288. )
  289. }
  290. }
  291. struct Triangle: Shape {
  292. func path(in rect: CGRect) -> Path {
  293. var path = Path()
  294. path.move(to: CGPoint(x: rect.midX, y: rect.minY + 15))
  295. path.addLine(to: CGPoint(x: rect.maxX, y: rect.maxY))
  296. path.addQuadCurve(to: CGPoint(x: rect.minX, y: rect.maxY), control: CGPoint(x: rect.midX, y: rect.midY + 10))
  297. path.closeSubpath()
  298. return path
  299. }
  300. }
  301. struct TrendShape: View {
  302. @Environment(\.colorScheme) var colorScheme
  303. let gradient: AngularGradient
  304. let color: Color
  305. var showArrow: Bool = true
  306. var body: some View {
  307. HStack(alignment: .center) {
  308. ZStack {
  309. Group {
  310. CircleShape(gradient: gradient)
  311. if showArrow {
  312. TriangleShape(color: color)
  313. }
  314. }.shadow(color: Color.black.opacity(colorScheme == .dark ? 0.75 : 0.33), radius: colorScheme == .dark ? 5 : 3)
  315. CircleShape(gradient: gradient)
  316. }
  317. }
  318. }
  319. }
  320. struct CircleShape: View {
  321. @Environment(\.colorScheme) var colorScheme
  322. let gradient: AngularGradient
  323. var body: some View {
  324. Circle()
  325. .stroke(gradient, lineWidth: 6)
  326. .background(Circle().fill(Color.chart))
  327. .frame(width: 130, height: 130)
  328. }
  329. }
  330. struct TriangleShape: View {
  331. let color: Color
  332. var body: some View {
  333. Triangle()
  334. .fill(color)
  335. .frame(width: 35, height: 35)
  336. .rotationEffect(.degrees(90))
  337. .offset(x: 85)
  338. }
  339. }