BasalChart.swift 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. import Charts
  2. import Foundation
  3. import SwiftUI
  4. struct BasalProfile: Hashable {
  5. let amount: Double
  6. var isOverwritten: Bool
  7. let startDate: Date
  8. let endDate: Date?
  9. init(amount: Double, isOverwritten: Bool, startDate: Date, endDate: Date? = nil) {
  10. self.amount = amount
  11. self.isOverwritten = isOverwritten
  12. self.startDate = startDate
  13. self.endDate = endDate
  14. }
  15. }
  16. extension MainChartView {
  17. var basalChart: some View {
  18. VStack {
  19. Chart {
  20. drawStartRuleMark()
  21. drawEndRuleMark()
  22. drawCurrentTimeMarker()
  23. drawTempBasals(dummy: false)
  24. drawBasalProfile()
  25. drawSuspensions()
  26. }.onChange(of: state.tempBasals) {
  27. calculateBasals()
  28. calculateTempBasals()
  29. }
  30. .onChange(of: state.maxBasal) {
  31. calculateBasals()
  32. }
  33. .frame(minHeight: geo.size.height * 0.05)
  34. .frame(width: fullWidth(viewWidth: screenSize.width))
  35. .chartXScale(domain: state.startMarker ... state.endMarker)
  36. .chartXAxis { basalChartXAxis }
  37. .chartXAxis(.hidden)
  38. .chartYAxis(.hidden)
  39. .chartPlotStyle { basalChartPlotStyle($0) }
  40. }
  41. }
  42. }
  43. // MARK: - Draw functions
  44. extension MainChartView {
  45. func drawTempBasals(dummy: Bool) -> some ChartContent {
  46. ForEach(preparedTempBasals, id: \.rate) { basal in
  47. if dummy {
  48. RectangleMark(
  49. xStart: .value("start", basal.start),
  50. xEnd: .value("end", basal.end),
  51. yStart: .value("rate-start", 0),
  52. yEnd: .value("rate-end", basal.rate)
  53. ).foregroundStyle(Color.clear)
  54. LineMark(x: .value("Start Date", basal.start), y: .value("Amount", basal.rate))
  55. .lineStyle(.init(lineWidth: 1)).foregroundStyle(Color.clear)
  56. LineMark(x: .value("End Date", basal.end), y: .value("Amount", basal.rate))
  57. .lineStyle(.init(lineWidth: 1)).foregroundStyle(Color.clear)
  58. } else {
  59. RectangleMark(
  60. xStart: .value("start", basal.start),
  61. xEnd: .value("end", basal.end),
  62. yStart: .value("rate-start", 0),
  63. yEnd: .value("rate-end", basal.rate)
  64. ).foregroundStyle(
  65. .linearGradient(
  66. colors: [
  67. Color.insulin.opacity(0.6),
  68. Color.insulin.opacity(0.1)
  69. ],
  70. startPoint: .bottom,
  71. endPoint: .top
  72. )
  73. ).alignsMarkStylesWithPlotArea()
  74. LineMark(x: .value("Start Date", basal.start), y: .value("Amount", basal.rate))
  75. .lineStyle(.init(lineWidth: 1)).foregroundStyle(Color.insulin)
  76. LineMark(x: .value("End Date", basal.end), y: .value("Amount", basal.rate))
  77. .lineStyle(.init(lineWidth: 1)).foregroundStyle(Color.insulin)
  78. }
  79. }
  80. }
  81. func drawBasalProfile() -> some ChartContent {
  82. /// dashed profile line
  83. ForEach(basalProfiles, id: \.self) { profile in
  84. LineMark(
  85. x: .value("Start Date", profile.startDate),
  86. y: .value("Amount", profile.amount),
  87. series: .value("profile", "profile")
  88. ).lineStyle(.init(lineWidth: 2, dash: [2, 4])).foregroundStyle(Color.insulin)
  89. LineMark(
  90. x: .value("End Date", profile.endDate ?? state.endMarker),
  91. y: .value("Amount", profile.amount),
  92. series: .value("profile", "profile")
  93. ).lineStyle(.init(lineWidth: 2.5, dash: [2, 4])).foregroundStyle(Color.insulin)
  94. }
  95. }
  96. func drawSuspensions() -> some ChartContent {
  97. let suspensions = state.suspendAndResumeEvents
  98. return ForEach(suspensions) { suspension in
  99. let now = Date()
  100. if let type = suspension.type, type == EventType.pumpSuspend.rawValue, let suspensionStart = suspension.timestamp {
  101. let suspensionEnd = min(
  102. (
  103. suspensions
  104. .first(where: {
  105. $0.timestamp ?? now > suspensionStart && $0.type == EventType.pumpResume.rawValue })?
  106. .timestamp
  107. ) ?? now,
  108. now
  109. )
  110. let basalProfileDuringSuspension = basalProfiles.first(where: { $0.startDate <= suspensionStart })
  111. let suspensionMarkHeight = basalProfileDuringSuspension?.amount ?? 1
  112. RectangleMark(
  113. xStart: .value("start", suspensionStart),
  114. xEnd: .value("end", suspensionEnd),
  115. yStart: .value("suspend-start", 0),
  116. yEnd: .value("suspend-end", suspensionMarkHeight)
  117. )
  118. .foregroundStyle(Color.loopGray.opacity(colorScheme == .dark ? 0.3 : 0.8))
  119. }
  120. }
  121. }
  122. }
  123. // MARK: - Calculation
  124. extension MainChartView {
  125. @MainActor func calculateTempBasals() {
  126. let now = Date()
  127. let suspensionTimes = state.suspendAndResumeEvents.compactMap(\.timestamp)
  128. // Snapshot the managed-object fields once; plain values from here on.
  129. let events = state.tempBasals.map {
  130. (timestamp: $0.timestamp, duration: $0.tempBasal?.duration ?? 0, rate: $0.tempBasal?.rate)
  131. }
  132. var prepared = [(start: Date, end: Date, rate: Double)]()
  133. prepared.reserveCapacity(events.count)
  134. for (index, event) in events.enumerated() {
  135. let timestamp = event.timestamp ?? now
  136. let end = timestamp + event.duration.minutes
  137. let isInsulinSuspended = suspensionTimes.contains { $0 >= timestamp && $0 <= end }
  138. let rate = Double(truncating: event.rate ?? 0) * (isInsulinSuspended ? 0 : 1)
  139. // A bar ends where the next later-starting temp basal begins,
  140. // else at its own scheduled end.
  141. var next = index + 1
  142. while next < events.count {
  143. if let nextStart = events[next].timestamp, nextStart > timestamp { break }
  144. next += 1
  145. }
  146. if next < events.count, let nextStart = events[next].timestamp {
  147. prepared.append((timestamp, nextStart, rate))
  148. } else {
  149. prepared.append((timestamp, end, rate))
  150. }
  151. }
  152. preparedTempBasals = prepared
  153. }
  154. func findRegularBasalPoints(
  155. timeBegin: TimeInterval,
  156. timeEnd: TimeInterval
  157. ) async -> [BasalProfile] {
  158. guard timeBegin < timeEnd else { return [] }
  159. let beginDate = Date(timeIntervalSince1970: timeBegin)
  160. let startOfDay = Calendar.current.startOfDay(for: beginDate)
  161. let profile = state.basalProfile
  162. var basalPoints: [BasalProfile] = []
  163. var lastEntryBeforeRange: (amount: Double, date: Date)?
  164. // Iterate over the next three days, multiplying the time intervals
  165. for dayOffset in 0 ..< 3 {
  166. let dayTimeOffset = TimeInterval(dayOffset * 24 * 60 * 60) // One Day in seconds
  167. for entry in profile {
  168. let basalTime = startOfDay.addingTimeInterval(entry.minutes.minutes.timeInterval + dayTimeOffset)
  169. let basalTimeInterval = basalTime.timeIntervalSince1970
  170. if basalTimeInterval < timeBegin {
  171. // Track the last profile entry before the visible range
  172. if lastEntryBeforeRange == nil || basalTime > lastEntryBeforeRange!.date {
  173. lastEntryBeforeRange = (amount: Double(entry.rate), date: basalTime)
  174. }
  175. } else if basalTimeInterval < timeEnd {
  176. basalPoints.append(BasalProfile(
  177. amount: Double(entry.rate),
  178. isOverwritten: false,
  179. startDate: basalTime
  180. ))
  181. }
  182. }
  183. }
  184. // Include the active profile entry at timeBegin so the line starts at the chart's left edge
  185. if let lastBefore = lastEntryBeforeRange {
  186. basalPoints.append(BasalProfile(
  187. amount: lastBefore.amount,
  188. isOverwritten: false,
  189. startDate: beginDate
  190. ))
  191. }
  192. return basalPoints
  193. }
  194. func calculateBasals() {
  195. Task {
  196. let dayAgoTime = Date().addingTimeInterval(-1.days.timeInterval).timeIntervalSince1970
  197. async let getRegularBasalPoints = findRegularBasalPoints(
  198. timeBegin: dayAgoTime,
  199. timeEnd: state.endMarker.timeIntervalSince1970
  200. )
  201. var regularPoints = await getRegularBasalPoints
  202. regularPoints.sort { $0.startDate < $1.startDate }
  203. var basals: [BasalProfile] = []
  204. // No basal data? Then there's nothing to draw
  205. if regularPoints.isEmpty {
  206. // basals stays empty; do nothing
  207. }
  208. // Exactly one data point?
  209. else if regularPoints.count == 1 {
  210. let single = regularPoints[0]
  211. // Make one BasalProfile that stretches entire marker area
  212. basals.append(
  213. BasalProfile(
  214. amount: single.amount,
  215. isOverwritten: single.isOverwritten,
  216. startDate: state.startMarker,
  217. endDate: state.endMarker
  218. )
  219. )
  220. }
  221. // Multiple data points: chain them so each point ends where the next begins
  222. else {
  223. for i in 0 ..< (regularPoints.count - 1) {
  224. basals.append(
  225. BasalProfile(
  226. amount: regularPoints[i].amount,
  227. isOverwritten: regularPoints[i].isOverwritten,
  228. startDate: regularPoints[i].startDate,
  229. endDate: regularPoints[i + 1].startDate
  230. )
  231. )
  232. }
  233. // The last item goes from its start to endMarker
  234. if let lastItem = regularPoints.last {
  235. basals.append(
  236. BasalProfile(
  237. amount: lastItem.amount,
  238. isOverwritten: lastItem.isOverwritten,
  239. startDate: lastItem.startDate,
  240. endDate: state.endMarker
  241. )
  242. )
  243. }
  244. }
  245. await MainActor.run {
  246. basalProfiles = basals
  247. }
  248. }
  249. }
  250. }