MainChartView2.swift 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  1. import Charts
  2. import SwiftUI
  3. private enum PredictionType: Hashable {
  4. case iob
  5. case cob
  6. case zt
  7. case uam
  8. }
  9. struct DotInfo {
  10. let rect: CGRect
  11. let value: Decimal
  12. }
  13. struct AnnouncementDot {
  14. let rect: CGRect
  15. let value: Decimal
  16. let note: String
  17. }
  18. typealias GlucoseYRange = (minValue: Int, minY: CGFloat, maxValue: Int, maxY: CGFloat)
  19. struct MainChartView2: View {
  20. private enum Config {
  21. static let endID = "End"
  22. static let basalHeight: CGFloat = 80
  23. static let topYPadding: CGFloat = 20
  24. static let bottomYPadding: CGFloat = 80
  25. static let minAdditionalWidth: CGFloat = 150
  26. static let maxGlucose = 270
  27. static let minGlucose = 45
  28. static let yLinesCount = 5
  29. static let glucoseScale: CGFloat = 2 // default 2
  30. static let bolusSize: CGFloat = 8
  31. static let bolusScale: CGFloat = 2.5
  32. static let carbsSize: CGFloat = 10
  33. static let fpuSize: CGFloat = 5
  34. static let carbsScale: CGFloat = 0.3
  35. static let fpuScale: CGFloat = 1
  36. static let announcementSize: CGFloat = 8
  37. static let announcementScale: CGFloat = 2.5
  38. static let owlSeize: CGFloat = 25
  39. static let owlOffset: CGFloat = 80
  40. }
  41. // MARK: BINDINGS
  42. @Binding var glucose: [BloodGlucose]
  43. @Binding var isManual: [BloodGlucose]
  44. @Binding var suggestion: Suggestion?
  45. @Binding var tempBasals: [PumpHistoryEvent]
  46. @Binding var boluses: [PumpHistoryEvent]
  47. @Binding var suspensions: [PumpHistoryEvent]
  48. @Binding var announcement: [Announcement]
  49. @Binding var hours: Int
  50. @Binding var maxBasal: Decimal
  51. @Binding var autotunedBasalProfile: [BasalProfileEntry]
  52. @Binding var basalProfile: [BasalProfileEntry]
  53. @Binding var tempTargets: [TempTarget]
  54. @Binding var carbs: [CarbsEntry]
  55. @Binding var timerDate: Date
  56. @Binding var units: GlucoseUnits
  57. @Binding var smooth: Bool
  58. @Binding var highGlucose: Decimal
  59. @Binding var lowGlucose: Decimal
  60. @Binding var screenHours: Int16
  61. @Binding var displayXgridLines: Bool
  62. @Binding var displayYgridLines: Bool
  63. @Binding var thresholdLines: Bool
  64. // // MARK: STATEs
  65. //
  66. // @State private var glucoseDots: [CGRect] = []
  67. // @State private var glucoseYRange: Range<CGFloat> = 0 ..< 0
  68. @State var didAppearTrigger = false
  69. @State private var glucoseDots: [CGRect] = []
  70. @State private var manualGlucoseDots: [CGRect] = []
  71. @State private var announcementDots: [AnnouncementDot] = []
  72. @State private var announcementPath = Path()
  73. @State private var manualGlucoseDotsCenter: [CGRect] = []
  74. @State private var unSmoothedGlucoseDots: [CGRect] = []
  75. @State private var predictionDots: [PredictionType: [CGRect]] = [:]
  76. @State private var bolusDots: [DotInfo] = []
  77. @State private var bolusPath = Path()
  78. @State private var tempBasalPath = Path()
  79. @State private var regularBasalPath = Path()
  80. @State private var tempTargetsPath = Path()
  81. @State private var suspensionsPath = Path()
  82. @State private var carbsDots: [DotInfo] = []
  83. @State private var carbsPath = Path()
  84. @State private var fpuDots: [DotInfo] = []
  85. @State private var fpuPath = Path()
  86. @State private var glucoseYRange: GlucoseYRange = (0, 0, 0, 0)
  87. @State private var offset: CGFloat = 0
  88. @State private var cachedMaxBasalRate: Decimal?
  89. private var date24Formatter: DateFormatter {
  90. let formatter = DateFormatter()
  91. formatter.locale = Locale(identifier: "en_US_POSIX")
  92. formatter.setLocalizedDateFormatFromTemplate("HH")
  93. return formatter
  94. }
  95. private var dateFormatter: DateFormatter {
  96. let formatter = DateFormatter()
  97. formatter.timeStyle = .short
  98. return formatter
  99. }
  100. var body: some View {
  101. NavigationStack {
  102. ScrollView {
  103. VStack {
  104. let filteredGlucose: [BloodGlucose] = filterGlucoseData(for: 6)
  105. Chart(filteredGlucose) {
  106. PointMark(
  107. x: .value("Time", $0.dateString),
  108. y: .value("Value", $0.value)
  109. )
  110. .foregroundStyle(Color.green.gradient)
  111. .cornerRadius(0)
  112. }
  113. .frame(height: 350)
  114. .chartXAxis {
  115. AxisMarks(values: filteredGlucose.map(\.dateString)) { _ in
  116. AxisValueLabel(format: .dateTime.hour())
  117. }
  118. }
  119. Legend()
  120. }
  121. .padding()
  122. }
  123. }
  124. }
  125. private func filterGlucoseData(for hours: Int) -> [BloodGlucose] {
  126. guard hours > 0 else {
  127. return glucose
  128. }
  129. let currentDate = Date()
  130. let startDate = Calendar.current.date(byAdding: .hour, value: -hours, to: currentDate) ?? currentDate
  131. return glucose.filter { $0.dateString >= startDate }
  132. }
  133. // // MARK: GLUCOSE FOR CHART
  134. //
  135. private func calculateGlucoseDots(fullSize: CGSize) {
  136. let dots = glucose.map { value -> CGRect in
  137. let position = glucoseToCoordinate(value, fullSize: fullSize)
  138. return CGRect(x: position.x - 2, y: position.y - 2, width: 4, height: 4)
  139. }
  140. let range = getGlucoseYRange(fullSize: fullSize)
  141. DispatchQueue.main.async {
  142. glucoseYRange = range
  143. glucoseDots = dots
  144. }
  145. }
  146. private func getGlucoseYRange(fullSize: CGSize) -> GlucoseYRange {
  147. let topYPaddint = Config.topYPadding + Config.basalHeight
  148. let bottomYPadding = Config.bottomYPadding
  149. let (minValue, maxValue) = minMaxYValues()
  150. let stepYFraction = (fullSize.height - topYPaddint - bottomYPadding) / CGFloat(maxValue - minValue)
  151. let yOffset = CGFloat(minValue) * stepYFraction
  152. let maxY = fullSize.height - CGFloat(minValue) * stepYFraction + yOffset - bottomYPadding
  153. let minY = fullSize.height - CGFloat(maxValue) * stepYFraction + yOffset - bottomYPadding
  154. return (minValue: minValue, minY: minY, maxValue: maxValue, maxY: maxY)
  155. }
  156. private func glucoseToCoordinate(_ glucoseEntry: BloodGlucose, fullSize: CGSize) -> CGPoint {
  157. let x = timeToXCoordinate(glucoseEntry.dateString.timeIntervalSince1970, fullSize: fullSize)
  158. let y = glucoseToYCoordinate(glucoseEntry.glucose ?? 0, fullSize: fullSize)
  159. return CGPoint(x: x, y: y)
  160. }
  161. private func glucoseToYCoordinate(_ glucoseValue: Int, fullSize: CGSize) -> CGFloat {
  162. let topYPaddint = Config.topYPadding + Config.basalHeight
  163. let bottomYPadding = Config.bottomYPadding
  164. let (minValue, maxValue) = minMaxYValues()
  165. let stepYFraction = (fullSize.height - topYPaddint - bottomYPadding) / CGFloat(maxValue - minValue)
  166. let yOffset = CGFloat(minValue) * stepYFraction
  167. let y = fullSize.height - CGFloat(glucoseValue) * stepYFraction + yOffset - bottomYPadding
  168. return y
  169. }
  170. private func timeToXCoordinate(_ time: TimeInterval, fullSize: CGSize) -> CGFloat {
  171. let xOffset = -Date().addingTimeInterval(-1.days.timeInterval).timeIntervalSince1970
  172. let stepXFraction = fullGlucoseWidth(viewWidth: fullSize.width) / CGFloat(hours.hours.timeInterval)
  173. let x = CGFloat(time + xOffset) * stepXFraction
  174. return x
  175. }
  176. private func fullGlucoseWidth(viewWidth: CGFloat) -> CGFloat {
  177. viewWidth * CGFloat(hours) / CGFloat(min(max(screenHours, 2), 24))
  178. }
  179. private func minMaxYValues() -> (min: Int, max: Int) {
  180. var maxValue = glucose.compactMap(\.glucose).max() ?? Config.maxGlucose
  181. if let maxPredValue = maxPredValue() {
  182. maxValue = max(maxValue, maxPredValue)
  183. }
  184. if let maxTargetValue = maxTargetValue() {
  185. maxValue = max(maxValue, maxTargetValue)
  186. }
  187. var minValue = glucose.compactMap(\.glucose).min() ?? Config.minGlucose
  188. if let minPredValue = minPredValue() {
  189. minValue = min(minValue, minPredValue)
  190. }
  191. if let minTargetValue = minTargetValue() {
  192. minValue = min(minValue, minTargetValue)
  193. }
  194. if minValue == maxValue {
  195. minValue = Config.minGlucose
  196. maxValue = Config.maxGlucose
  197. }
  198. // fix the grah y-axis as long as the min and max BG values are within set borders
  199. if minValue > Config.minGlucose {
  200. minValue = Config.minGlucose
  201. }
  202. if maxValue < Config.maxGlucose {
  203. maxValue = Config.maxGlucose
  204. }
  205. return (min: minValue, max: maxValue)
  206. }
  207. private func maxTargetValue() -> Int? {
  208. tempTargets.map { $0.targetTop ?? 0 }.filter { $0 > 0 }.max().map(Int.init)
  209. }
  210. private func minPredValue() -> Int? {
  211. [
  212. suggestion?.predictions?.cob ?? [],
  213. suggestion?.predictions?.iob ?? [],
  214. suggestion?.predictions?.zt ?? [],
  215. suggestion?.predictions?.uam ?? []
  216. ]
  217. .flatMap { $0 }
  218. .min()
  219. }
  220. private func minTargetValue() -> Int? {
  221. tempTargets.map { $0.targetBottom ?? 0 }.filter { $0 > 0 }.min().map(Int.init)
  222. }
  223. private func maxPredValue() -> Int? {
  224. [
  225. suggestion?.predictions?.cob ?? [],
  226. suggestion?.predictions?.iob ?? [],
  227. suggestion?.predictions?.zt ?? [],
  228. suggestion?.predictions?.uam ?? []
  229. ]
  230. .flatMap { $0 }
  231. .max()
  232. }
  233. }
  234. // MARK: LEGEND PANEL FOR CHART
  235. struct Legend: View {
  236. var body: some View {
  237. HStack {
  238. Image(systemName: "line.diagonal")
  239. .rotationEffect(Angle(degrees: 45))
  240. .foregroundColor(.green)
  241. Text("BG")
  242. .foregroundColor(.secondary)
  243. Spacer()
  244. Image(systemName: "line.diagonal")
  245. .rotationEffect(Angle(degrees: 45))
  246. .foregroundColor(.insulin)
  247. Text("IOB")
  248. .foregroundColor(.secondary)
  249. Spacer()
  250. Image(systemName: "line.diagonal")
  251. .rotationEffect(Angle(degrees: 45))
  252. .foregroundColor(.purple)
  253. Text("ZT")
  254. .foregroundColor(.secondary)
  255. Spacer()
  256. Image(systemName: "line.diagonal")
  257. .rotationEffect(Angle(degrees: 45))
  258. .foregroundColor(.loopYellow)
  259. Text("COB")
  260. .foregroundColor(.secondary)
  261. Spacer()
  262. Image(systemName: "line.diagonal")
  263. .rotationEffect(Angle(degrees: 45))
  264. .foregroundColor(.orange)
  265. Text("UAM")
  266. .foregroundColor(.secondary)
  267. }
  268. .font(.caption2)
  269. .padding(.horizontal, 4)
  270. .padding(.vertical, 10)
  271. }
  272. }