MainChartView2.swift 11 KB

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