MainChartView2.swift 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  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. @State private var glucoseDots: [CGRect] = []
  66. @State private var glucoseYRange: Range<CGFloat> = 0 ..< 0
  67. @State var didAppearTrigger = false
  68. @State private var glucoseDots: [CGRect] = []
  69. @State private var manualGlucoseDots: [CGRect] = []
  70. @State private var announcementDots: [AnnouncementDot] = []
  71. @State private var announcementPath = Path()
  72. @State private var manualGlucoseDotsCenter: [CGRect] = []
  73. @State private var unSmoothedGlucoseDots: [CGRect] = []
  74. @State private var predictionDots: [PredictionType: [CGRect]] = [:]
  75. @State private var bolusDots: [DotInfo] = []
  76. @State private var bolusPath = Path()
  77. @State private var tempBasalPath = Path()
  78. @State private var regularBasalPath = Path()
  79. @State private var tempTargetsPath = Path()
  80. @State private var suspensionsPath = Path()
  81. @State private var carbsDots: [DotInfo] = []
  82. @State private var carbsPath = Path()
  83. @State private var fpuDots: [DotInfo] = []
  84. @State private var fpuPath = Path()
  85. @State private var glucoseYRange: GlucoseYRange = (0, 0, 0, 0)
  86. @State private var offset: CGFloat = 0
  87. @State private var cachedMaxBasalRate: Decimal?
  88. var body: some View {
  89. NavigationStack {
  90. ScrollView {
  91. VStack {
  92. Chart {
  93. ForEach(glucoseDots.indices, id: \.self) { index in
  94. PointMark(position: glucoseDots[index].origin)
  95. .frame(width: glucoseDots[index].width, height: glucoseDots[index].height)
  96. .foregroundStyle(Color.green.gradient)
  97. }
  98. }
  99. .frame(height: 350)
  100. .chartXAxis {
  101. // to do
  102. }
  103. Legend()
  104. }
  105. .padding()
  106. }
  107. }
  108. .onAppear {
  109. calculateGlucoseDots(fullSize: UIScreen.main.bounds.size)
  110. }
  111. }
  112. // MARK: GLUCOSE FOR CHART
  113. private func calculateGlucoseDots(fullSize: CGSize) {
  114. let dots = glucose.map { value -> CGRect in
  115. let position = glucoseToCoordinate(value, fullSize: fullSize)
  116. return CGRect(x: position.x - 2, y: position.y - 2, width: 4, height: 4)
  117. }
  118. let range = getGlucoseYRange(fullSize: fullSize)
  119. DispatchQueue.main.async {
  120. glucoseYRange = range
  121. glucoseDots = dots
  122. }
  123. }
  124. private func getGlucoseYRange(fullSize: CGSize) -> GlucoseYRange {
  125. let topYPaddint = Config.topYPadding + Config.basalHeight
  126. let bottomYPadding = Config.bottomYPadding
  127. let (minValue, maxValue) = minMaxYValues()
  128. let stepYFraction = (fullSize.height - topYPaddint - bottomYPadding) / CGFloat(maxValue - minValue)
  129. let yOffset = CGFloat(minValue) * stepYFraction
  130. let maxY = fullSize.height - CGFloat(minValue) * stepYFraction + yOffset - bottomYPadding
  131. let minY = fullSize.height - CGFloat(maxValue) * stepYFraction + yOffset - bottomYPadding
  132. return (minValue: minValue, minY: minY, maxValue: maxValue, maxY: maxY)
  133. }
  134. private func glucoseToCoordinate(_ glucoseEntry: BloodGlucose, fullSize: CGSize) -> CGPoint {
  135. let x = timeToXCoordinate(glucoseEntry.dateString.timeIntervalSince1970, fullSize: fullSize)
  136. let y = glucoseToYCoordinate(glucoseEntry.glucose ?? 0, fullSize: fullSize)
  137. return CGPoint(x: x, y: y)
  138. }
  139. private func glucoseToYCoordinate(_ glucoseValue: Int, fullSize: CGSize) -> CGFloat {
  140. let topYPaddint = Config.topYPadding + Config.basalHeight
  141. let bottomYPadding = Config.bottomYPadding
  142. let (minValue, maxValue) = minMaxYValues()
  143. let stepYFraction = (fullSize.height - topYPaddint - bottomYPadding) / CGFloat(maxValue - minValue)
  144. let yOffset = CGFloat(minValue) * stepYFraction
  145. let y = fullSize.height - CGFloat(glucoseValue) * stepYFraction + yOffset - bottomYPadding
  146. return y
  147. }
  148. private func timeToXCoordinate(_ time: TimeInterval, fullSize: CGSize) -> CGFloat {
  149. let xOffset = -Date().addingTimeInterval(-1.days.timeInterval).timeIntervalSince1970
  150. let stepXFraction = fullGlucoseWidth(viewWidth: fullSize.width) / CGFloat(hours.hours.timeInterval)
  151. let x = CGFloat(time + xOffset) * stepXFraction
  152. return x
  153. }
  154. private func fullGlucoseWidth(viewWidth: CGFloat) -> CGFloat {
  155. viewWidth * CGFloat(hours) / CGFloat(min(max(screenHours, 2), 24))
  156. }
  157. private func minMaxYValues() -> (min: Int, max: Int) {
  158. var maxValue = glucose.compactMap(\.glucose).max() ?? Config.maxGlucose
  159. if let maxPredValue = maxPredValue() {
  160. maxValue = max(maxValue, maxPredValue)
  161. }
  162. if let maxTargetValue = maxTargetValue() {
  163. maxValue = max(maxValue, maxTargetValue)
  164. }
  165. var minValue = glucose.compactMap(\.glucose).min() ?? Config.minGlucose
  166. if let minPredValue = minPredValue() {
  167. minValue = min(minValue, minPredValue)
  168. }
  169. if let minTargetValue = minTargetValue() {
  170. minValue = min(minValue, minTargetValue)
  171. }
  172. if minValue == maxValue {
  173. minValue = Config.minGlucose
  174. maxValue = Config.maxGlucose
  175. }
  176. // fix the grah y-axis as long as the min and max BG values are within set borders
  177. if minValue > Config.minGlucose {
  178. minValue = Config.minGlucose
  179. }
  180. if maxValue < Config.maxGlucose {
  181. maxValue = Config.maxGlucose
  182. }
  183. return (min: minValue, max: maxValue)
  184. }
  185. private func maxTargetValue() -> Int? {
  186. tempTargets.map { $0.targetTop ?? 0 }.filter { $0 > 0 }.max().map(Int.init)
  187. }
  188. private func minPredValue() -> Int? {
  189. [
  190. suggestion?.predictions?.cob ?? [],
  191. suggestion?.predictions?.iob ?? [],
  192. suggestion?.predictions?.zt ?? [],
  193. suggestion?.predictions?.uam ?? []
  194. ]
  195. .flatMap { $0 }
  196. .min()
  197. }
  198. private func minTargetValue() -> Int? {
  199. tempTargets.map { $0.targetBottom ?? 0 }.filter { $0 > 0 }.min().map(Int.init)
  200. }
  201. private func maxPredValue() -> Int? {
  202. [
  203. suggestion?.predictions?.cob ?? [],
  204. suggestion?.predictions?.iob ?? [],
  205. suggestion?.predictions?.zt ?? [],
  206. suggestion?.predictions?.uam ?? []
  207. ]
  208. .flatMap { $0 }
  209. .max()
  210. }
  211. }
  212. // MARK: LEGEND PANEL FOR CHART
  213. struct Legend: View {
  214. var body: some View {
  215. HStack {
  216. Image(systemName: "line.diagonal")
  217. .rotationEffect(Angle(degrees: 45))
  218. .foregroundColor(.green)
  219. Text("BG")
  220. .foregroundColor(.secondary)
  221. Spacer()
  222. Image(systemName: "line.diagonal")
  223. .rotationEffect(Angle(degrees: 45))
  224. .foregroundColor(.insulin)
  225. Text("IOB")
  226. .foregroundColor(.secondary)
  227. Spacer()
  228. Image(systemName: "line.diagonal")
  229. .rotationEffect(Angle(degrees: 45))
  230. .foregroundColor(.purple)
  231. Text("ZT")
  232. .foregroundColor(.secondary)
  233. Spacer()
  234. Image(systemName: "line.diagonal")
  235. .rotationEffect(Angle(degrees: 45))
  236. .foregroundColor(.loopYellow)
  237. Text("COB")
  238. .foregroundColor(.secondary)
  239. Spacer()
  240. Image(systemName: "line.diagonal")
  241. .rotationEffect(Angle(degrees: 45))
  242. .foregroundColor(.orange)
  243. Text("UAM")
  244. .foregroundColor(.secondary)
  245. }
  246. .font(.caption2)
  247. .padding(.horizontal, 4)
  248. .padding(.vertical, 10)
  249. }
  250. }
  251. // struct BloodGlucose: Identifiable {
  252. // let id = UUID()
  253. // let timestamp: Date
  254. // let value: Int
  255. // }
  256. // struct ViewMonth: Identifiable {
  257. // let id = UUID()
  258. // let date: Date
  259. // let viewCount: Int
  260. // }
  261. // extension Date {
  262. // static func from(year: Int, month: Int, day: Int) -> Date {
  263. // let components = DateComponents(year: year, month: month, day: day)
  264. // return Calendar.current.date(from: components)!
  265. // }
  266. // }