MainChartView2.swift 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  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. Chart(glucose) {
  105. PointMark(
  106. x: .value("Time", $0.dateString),
  107. y: .value("Value", $0.value)
  108. )
  109. .foregroundStyle(Color.green.gradient)
  110. .cornerRadius(0)
  111. }
  112. .frame(height: 350)
  113. .chartXAxis {
  114. AxisMarks(values: glucose.map(\.dateString)) { _ in
  115. AxisValueLabel(format: .dateTime.hour())
  116. }
  117. }
  118. Legend()
  119. }
  120. .padding()
  121. }
  122. }
  123. }
  124. // // MARK: GLUCOSE FOR CHART
  125. //
  126. private func calculateGlucoseDots(fullSize: CGSize) {
  127. let dots = glucose.map { value -> CGRect in
  128. let position = glucoseToCoordinate(value, fullSize: fullSize)
  129. return CGRect(x: position.x - 2, y: position.y - 2, width: 4, height: 4)
  130. }
  131. let range = getGlucoseYRange(fullSize: fullSize)
  132. DispatchQueue.main.async {
  133. glucoseYRange = range
  134. glucoseDots = dots
  135. }
  136. }
  137. private func getGlucoseYRange(fullSize: CGSize) -> GlucoseYRange {
  138. let topYPaddint = Config.topYPadding + Config.basalHeight
  139. let bottomYPadding = Config.bottomYPadding
  140. let (minValue, maxValue) = minMaxYValues()
  141. let stepYFraction = (fullSize.height - topYPaddint - bottomYPadding) / CGFloat(maxValue - minValue)
  142. let yOffset = CGFloat(minValue) * stepYFraction
  143. let maxY = fullSize.height - CGFloat(minValue) * stepYFraction + yOffset - bottomYPadding
  144. let minY = fullSize.height - CGFloat(maxValue) * stepYFraction + yOffset - bottomYPadding
  145. return (minValue: minValue, minY: minY, maxValue: maxValue, maxY: maxY)
  146. }
  147. private func glucoseToCoordinate(_ glucoseEntry: BloodGlucose, fullSize: CGSize) -> CGPoint {
  148. let x = timeToXCoordinate(glucoseEntry.dateString.timeIntervalSince1970, fullSize: fullSize)
  149. let y = glucoseToYCoordinate(glucoseEntry.glucose ?? 0, fullSize: fullSize)
  150. return CGPoint(x: x, y: y)
  151. }
  152. private func glucoseToYCoordinate(_ glucoseValue: Int, fullSize: CGSize) -> CGFloat {
  153. let topYPaddint = Config.topYPadding + Config.basalHeight
  154. let bottomYPadding = Config.bottomYPadding
  155. let (minValue, maxValue) = minMaxYValues()
  156. let stepYFraction = (fullSize.height - topYPaddint - bottomYPadding) / CGFloat(maxValue - minValue)
  157. let yOffset = CGFloat(minValue) * stepYFraction
  158. let y = fullSize.height - CGFloat(glucoseValue) * stepYFraction + yOffset - bottomYPadding
  159. return y
  160. }
  161. private func timeToXCoordinate(_ time: TimeInterval, fullSize: CGSize) -> CGFloat {
  162. let xOffset = -Date().addingTimeInterval(-1.days.timeInterval).timeIntervalSince1970
  163. let stepXFraction = fullGlucoseWidth(viewWidth: fullSize.width) / CGFloat(hours.hours.timeInterval)
  164. let x = CGFloat(time + xOffset) * stepXFraction
  165. return x
  166. }
  167. private func fullGlucoseWidth(viewWidth: CGFloat) -> CGFloat {
  168. viewWidth * CGFloat(hours) / CGFloat(min(max(screenHours, 2), 24))
  169. }
  170. private func minMaxYValues() -> (min: Int, max: Int) {
  171. var maxValue = glucose.compactMap(\.glucose).max() ?? Config.maxGlucose
  172. if let maxPredValue = maxPredValue() {
  173. maxValue = max(maxValue, maxPredValue)
  174. }
  175. if let maxTargetValue = maxTargetValue() {
  176. maxValue = max(maxValue, maxTargetValue)
  177. }
  178. var minValue = glucose.compactMap(\.glucose).min() ?? Config.minGlucose
  179. if let minPredValue = minPredValue() {
  180. minValue = min(minValue, minPredValue)
  181. }
  182. if let minTargetValue = minTargetValue() {
  183. minValue = min(minValue, minTargetValue)
  184. }
  185. if minValue == maxValue {
  186. minValue = Config.minGlucose
  187. maxValue = Config.maxGlucose
  188. }
  189. // fix the grah y-axis as long as the min and max BG values are within set borders
  190. if minValue > Config.minGlucose {
  191. minValue = Config.minGlucose
  192. }
  193. if maxValue < Config.maxGlucose {
  194. maxValue = Config.maxGlucose
  195. }
  196. return (min: minValue, max: maxValue)
  197. }
  198. private func maxTargetValue() -> Int? {
  199. tempTargets.map { $0.targetTop ?? 0 }.filter { $0 > 0 }.max().map(Int.init)
  200. }
  201. private func minPredValue() -> Int? {
  202. [
  203. suggestion?.predictions?.cob ?? [],
  204. suggestion?.predictions?.iob ?? [],
  205. suggestion?.predictions?.zt ?? [],
  206. suggestion?.predictions?.uam ?? []
  207. ]
  208. .flatMap { $0 }
  209. .min()
  210. }
  211. private func minTargetValue() -> Int? {
  212. tempTargets.map { $0.targetBottom ?? 0 }.filter { $0 > 0 }.min().map(Int.init)
  213. }
  214. private func maxPredValue() -> Int? {
  215. [
  216. suggestion?.predictions?.cob ?? [],
  217. suggestion?.predictions?.iob ?? [],
  218. suggestion?.predictions?.zt ?? [],
  219. suggestion?.predictions?.uam ?? []
  220. ]
  221. .flatMap { $0 }
  222. .max()
  223. }
  224. }
  225. // MARK: LEGEND PANEL FOR CHART
  226. struct Legend: View {
  227. var body: some View {
  228. HStack {
  229. Image(systemName: "line.diagonal")
  230. .rotationEffect(Angle(degrees: 45))
  231. .foregroundColor(.green)
  232. Text("BG")
  233. .foregroundColor(.secondary)
  234. Spacer()
  235. Image(systemName: "line.diagonal")
  236. .rotationEffect(Angle(degrees: 45))
  237. .foregroundColor(.insulin)
  238. Text("IOB")
  239. .foregroundColor(.secondary)
  240. Spacer()
  241. Image(systemName: "line.diagonal")
  242. .rotationEffect(Angle(degrees: 45))
  243. .foregroundColor(.purple)
  244. Text("ZT")
  245. .foregroundColor(.secondary)
  246. Spacer()
  247. Image(systemName: "line.diagonal")
  248. .rotationEffect(Angle(degrees: 45))
  249. .foregroundColor(.loopYellow)
  250. Text("COB")
  251. .foregroundColor(.secondary)
  252. Spacer()
  253. Image(systemName: "line.diagonal")
  254. .rotationEffect(Angle(degrees: 45))
  255. .foregroundColor(.orange)
  256. Text("UAM")
  257. .foregroundColor(.secondary)
  258. }
  259. .font(.caption2)
  260. .padding(.horizontal, 4)
  261. .padding(.vertical, 10)
  262. }
  263. }
  264. // struct BloodGlucose: Identifiable {
  265. // let id = UUID()
  266. // let timestamp: Date
  267. // let value: Int
  268. // }
  269. // struct ViewMonth: Identifiable {
  270. // let id = UUID()
  271. // let date: Date
  272. // let viewCount: Int
  273. // }
  274. // extension Date {
  275. // static func from(year: Int, month: Int, day: Int) -> Date {
  276. // let components = DateComponents(year: year, month: month, day: day)
  277. // return Calendar.current.date(from: components)!
  278. // }
  279. // }