CurrentGlucoseView.swift 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  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. @State private var rotationDegrees: Double = 0.0
  21. @State private var angularGradient = AngularGradient(colors: [
  22. Color(red: 0.7215686275, green: 0.3411764706, blue: 1),
  23. Color(red: 0.6235294118, green: 0.4235294118, blue: 0.9803921569),
  24. Color(red: 0.4862745098, green: 0.5450980392, blue: 0.9529411765),
  25. Color(red: 0.3411764706, green: 0.6666666667, blue: 0.9254901961),
  26. Color(red: 0.262745098, green: 0.7333333333, blue: 0.9137254902),
  27. Color(red: 0.7215686275, green: 0.3411764706, blue: 1)
  28. ], center: .center, startAngle: .degrees(270), endAngle: .degrees(-90))
  29. @Environment(\.colorScheme) var colorScheme
  30. private var deltaFormatter: NumberFormatter {
  31. let formatter = NumberFormatter()
  32. formatter.numberStyle = .decimal
  33. if units == .mmolL {
  34. formatter.maximumFractionDigits = 1
  35. formatter.minimumFractionDigits = 1
  36. formatter.roundingMode = .halfUp
  37. } else {
  38. formatter.maximumFractionDigits = 0
  39. }
  40. formatter.positivePrefix = " +"
  41. formatter.negativePrefix = " -"
  42. return formatter
  43. }
  44. var body: some View {
  45. let triangleColor = Color(red: 0.262745098, green: 0.7333333333, blue: 0.9137254902)
  46. if cgmAvailable {
  47. ZStack {
  48. if let progress = cgmProgress {
  49. SensorLifecycleArcView(
  50. progress: progress.percentComplete,
  51. progressState: progress.progressState
  52. )
  53. }
  54. TrendShape(gradient: angularGradient, color: triangleColor, showArrow: true)
  55. .rotationEffect(.degrees(rotationDegrees))
  56. VStack(alignment: .center) {
  57. bobbleContent()
  58. }
  59. }
  60. .overlay(alignment: .bottom) {
  61. // Tag floats outside the bobble's frame so it doesn't push
  62. // chart / stats / tab bar down. When the trend triangle
  63. // rotates into the lower half (`rotationDegrees >= 45`) it
  64. // ends up around 6 o'clock and collides with the tag —
  65. // hide the SensorStatusTagView to avoid collision
  66. if let tag = tagLabel, !trendIsDownward {
  67. SensorStatusTagView(text: tag.text, theme: tag.theme)
  68. .offset(y: 14)
  69. .zIndex(1)
  70. }
  71. }
  72. .onChange(of: glucose.last?.directionEnum) {
  73. withAnimation {
  74. switch glucose.last?.directionEnum {
  75. case .doubleUp,
  76. .singleUp,
  77. .tripleUp:
  78. rotationDegrees = -90
  79. case .fortyFiveUp:
  80. rotationDegrees = -45
  81. case .flat:
  82. rotationDegrees = 0
  83. case .fortyFiveDown:
  84. rotationDegrees = 45
  85. case .doubleDown,
  86. .singleDown,
  87. .tripleDown:
  88. rotationDegrees = 90
  89. case nil,
  90. .notComputable,
  91. .rateOutOfRange:
  92. rotationDegrees = 0
  93. default:
  94. rotationDegrees = 0
  95. }
  96. }
  97. }
  98. } else {
  99. VStack(alignment: .center, spacing: 12) {
  100. HStack
  101. {
  102. // no cgm defined so display a generic CGM
  103. Image(systemName: "sensor.tag.radiowaves.forward.fill").font(.body).imageScale(.large)
  104. }
  105. HStack {
  106. Text("Add CGM").font(.caption).bold()
  107. }
  108. }.frame(alignment: .top)
  109. }
  110. }
  111. private var delta: String {
  112. guard glucose.count >= 2 else {
  113. return "--"
  114. }
  115. var lastGlucose = Decimal(glucose.last?.glucose ?? 0)
  116. var secondLastGlucose = Decimal(glucose.first?.glucose ?? 0)
  117. if units == .mmolL {
  118. lastGlucose = lastGlucose.asMmolL
  119. secondLastGlucose = secondLastGlucose.asMmolL
  120. }
  121. let delta = lastGlucose - secondLastGlucose
  122. return deltaFormatter.string(from: delta as NSNumber) ?? "--"
  123. }
  124. @ViewBuilder private func bobbleContent() -> some View {
  125. HStack {
  126. if let glucoseValue = glucose.last?.glucose, isReadingFresh {
  127. let displayGlucose = units == .mgdL
  128. ? Decimal(glucoseValue).description
  129. : Decimal(glucoseValue).formattedAsMmolL
  130. Text(glucoseValue == 400 ? "HIGH" : displayGlucose)
  131. .font(.system(size: 40, weight: .bold, design: .rounded))
  132. .foregroundStyle(glucoseColor(for: glucoseValue))
  133. } else {
  134. Text("– –")
  135. .font(.system(size: 40, weight: .bold, design: .rounded))
  136. .foregroundStyle(.secondary)
  137. }
  138. }
  139. if isReadingFresh {
  140. HStack {
  141. let minutesAgoString = TimeAgoFormatter.minutesAgo(from: glucose.last?.date)
  142. Group {
  143. Text(minutesAgoString)
  144. Text(delta)
  145. }
  146. .font(.callout).fontWeight(.bold)
  147. .foregroundStyle(colorScheme == .dark ? Color.white.opacity(0.9) : Color.secondary)
  148. }
  149. .frame(alignment: .top)
  150. }
  151. }
  152. /// Matches `APSManager`'s loop-input freshness gate — readings older than
  153. /// 12 minutes (one missed CGM transmission on a 5-min schedule) get
  154. /// masked to dashes. Handles warmup + sensor failure naturally: no
  155. /// fresh data → no number on the bobble.
  156. private var isReadingFresh: Bool {
  157. guard let date = glucose.last?.date else { return false }
  158. return Date().timeIntervalSince(date) < 12 * 60
  159. }
  160. /// True when the trend arrow is rotated into the lower half of the
  161. /// circle — used to decide whether the bottom tag needs to dodge the
  162. /// triangle by sliding up onto the bobble's rim.
  163. private var trendIsDownward: Bool { rotationDegrees >= 45 }
  164. /// Status highlight wins; otherwise fall back to remaining-time.
  165. private var tagLabel: (text: String, theme: SensorStatusTagTheme)? {
  166. if let status = cgmStatus {
  167. return (status.localizedMessage, theme(for: status.status))
  168. }
  169. if let expiresAt = cgmSensorExpiresAt {
  170. let text = SensorRemainingTimeFormatter.format(until: expiresAt)
  171. let theme: SensorStatusTagTheme
  172. switch cgmProgress?.progressState {
  173. case .critical: theme = .red
  174. case .warning: theme = .orange
  175. default: theme = .green
  176. }
  177. return (text, theme)
  178. }
  179. return nil
  180. }
  181. private func theme(for status: CgmDisplayStatus) -> SensorStatusTagTheme {
  182. switch status {
  183. case .critical: return .red
  184. case .warning: return .orange
  185. case .normal: return .secondary
  186. }
  187. }
  188. private func glucoseColor(for glucoseValue: Int16) -> Color {
  189. // 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
  190. let hardCodedLow = Decimal(55)
  191. let hardCodedHigh = Decimal(220)
  192. let isDynamicColorScheme = glucoseColorScheme == .dynamicColor
  193. guard Decimal(glucoseValue) <= lowGlucose || Decimal(glucoseValue) >= highGlucose else {
  194. return Color.primary
  195. }
  196. return Trio.getDynamicGlucoseColor(
  197. glucoseValue: Decimal(glucoseValue),
  198. highGlucoseColorValue: isDynamicColorScheme ? hardCodedHigh : highGlucose,
  199. lowGlucoseColorValue: isDynamicColorScheme ? hardCodedLow : lowGlucose,
  200. targetGlucose: currentGlucoseTarget,
  201. glucoseColorScheme: glucoseColorScheme
  202. )
  203. }
  204. }
  205. struct Triangle: Shape {
  206. func path(in rect: CGRect) -> Path {
  207. var path = Path()
  208. path.move(to: CGPoint(x: rect.midX, y: rect.minY + 15))
  209. path.addLine(to: CGPoint(x: rect.maxX, y: rect.maxY))
  210. path.addQuadCurve(to: CGPoint(x: rect.minX, y: rect.maxY), control: CGPoint(x: rect.midX, y: rect.midY + 10))
  211. path.closeSubpath()
  212. return path
  213. }
  214. }
  215. struct TrendShape: View {
  216. @Environment(\.colorScheme) var colorScheme
  217. let gradient: AngularGradient
  218. let color: Color
  219. var showArrow: Bool = true
  220. var body: some View {
  221. HStack(alignment: .center) {
  222. ZStack {
  223. Group {
  224. CircleShape(gradient: gradient)
  225. if showArrow {
  226. TriangleShape(color: color)
  227. }
  228. }.shadow(color: Color.black.opacity(colorScheme == .dark ? 0.75 : 0.33), radius: colorScheme == .dark ? 5 : 3)
  229. CircleShape(gradient: gradient)
  230. }
  231. }
  232. }
  233. }
  234. struct CircleShape: View {
  235. @Environment(\.colorScheme) var colorScheme
  236. let gradient: AngularGradient
  237. var body: some View {
  238. Circle()
  239. .stroke(gradient, lineWidth: 6)
  240. .background(Circle().fill(Color.chart))
  241. .frame(width: 130, height: 130)
  242. }
  243. }
  244. struct TriangleShape: View {
  245. let color: Color
  246. var body: some View {
  247. Triangle()
  248. .fill(color)
  249. .frame(width: 35, height: 35)
  250. .rotationEffect(.degrees(90))
  251. .offset(x: 85)
  252. }
  253. }