MainChartView.swift 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280
  1. import Algorithms
  2. import SwiftDate
  3. import SwiftUI
  4. private enum PredictionType: Hashable {
  5. case iob
  6. case cob
  7. case zt
  8. case uam
  9. }
  10. struct DotInfo {
  11. let rect: CGRect
  12. let value: Decimal
  13. }
  14. struct AnnouncementDot {
  15. let rect: CGRect
  16. let value: Decimal
  17. let note: String
  18. }
  19. typealias GlucoseYRange = (minValue: Int, minY: CGFloat, maxValue: Int, maxY: CGFloat)
  20. struct MainChartView: View {
  21. private enum Config {
  22. static let endID = "End"
  23. static let basalHeight: CGFloat = 80
  24. static let topYPadding: CGFloat = 20
  25. static let bottomYPadding: CGFloat = 80
  26. static let minAdditionalWidth: CGFloat = 150
  27. static let maxGlucose = 270
  28. static let minGlucose = 45
  29. static let yLinesCount = 5
  30. static let glucoseScale: CGFloat = 2 // default 2
  31. static let bolusSize: CGFloat = 8
  32. static let bolusScale: CGFloat = 2.5
  33. static let carbsSize: CGFloat = 10
  34. static let fpuSize: CGFloat = 5
  35. static let carbsScale: CGFloat = 0.3
  36. static let fpuScale: CGFloat = 1
  37. static let announcementSize: CGFloat = 8
  38. static let announcementScale: CGFloat = 2.5
  39. static let owlSeize: CGFloat = 25
  40. static let owlOffset: CGFloat = 80
  41. }
  42. private enum Command {
  43. static let open = "🔴"
  44. static let closed = "🟢"
  45. static let suspend = "❌"
  46. static let resume = "✅"
  47. static let tempbasal = "basal"
  48. static let bolus = "💧"
  49. }
  50. @Binding var glucose: [BloodGlucose]
  51. @Binding var isManual: [BloodGlucose]
  52. @Binding var suggestion: Suggestion?
  53. @Binding var tempBasals: [PumpHistoryEvent]
  54. @Binding var boluses: [PumpHistoryEvent]
  55. @Binding var suspensions: [PumpHistoryEvent]
  56. @Binding var announcement: [Announcement]
  57. @Binding var hours: Int
  58. @Binding var maxBasal: Decimal
  59. @Binding var autotunedBasalProfile: [BasalProfileEntry]
  60. @Binding var basalProfile: [BasalProfileEntry]
  61. @Binding var tempTargets: [TempTarget]
  62. @Binding var carbs: [CarbsEntry]
  63. @Binding var timerDate: Date
  64. @Binding var units: GlucoseUnits
  65. @Binding var smooth: Bool
  66. @Binding var highGlucose: Decimal
  67. @Binding var lowGlucose: Decimal
  68. @Binding var screenHours: Int16
  69. @Binding var displayXgridLines: Bool
  70. @Binding var displayYgridLines: Bool
  71. @Binding var thresholdLines: Bool
  72. @State var didAppearTrigger = false
  73. @State private var glucoseDots: [CGRect] = []
  74. @State private var manualGlucoseDots: [CGRect] = []
  75. @State private var announcementDots: [AnnouncementDot] = []
  76. @State private var announcementPath = Path()
  77. @State private var manualGlucoseDotsCenter: [CGRect] = []
  78. @State private var unSmoothedGlucoseDots: [CGRect] = []
  79. @State private var predictionDots: [PredictionType: [CGRect]] = [:]
  80. @State private var bolusDots: [DotInfo] = []
  81. @State private var tempBasalPath = Path()
  82. @State private var regularBasalPath = Path()
  83. @State private var tempTargetsPath = Path()
  84. @State private var suspensionsPath = Path()
  85. @State private var carbsDots: [DotInfo] = []
  86. @State private var fpuDots: [DotInfo] = []
  87. @State private var glucoseYRange: GlucoseYRange = (0, 0, 0, 0)
  88. @State private var cachedMaxBasalRate: Decimal?
  89. private var zoomScale: Double {
  90. 1.0 / Double(screenHours)
  91. }
  92. private let calculationQueue = DispatchQueue(
  93. label: "MainChartView.calculationQueue",
  94. qos: .userInteractive,
  95. attributes: .concurrent
  96. )
  97. private var dateFormatter: DateFormatter {
  98. let formatter = DateFormatter()
  99. formatter.timeStyle = .short
  100. return formatter
  101. }
  102. private var date24Formatter: DateFormatter {
  103. let formatter = DateFormatter()
  104. formatter.locale = Locale(identifier: "en_US_POSIX")
  105. formatter.setLocalizedDateFormatFromTemplate("HH")
  106. return formatter
  107. }
  108. private var glucoseFormatter: NumberFormatter {
  109. let formatter = NumberFormatter()
  110. formatter.numberStyle = .decimal
  111. formatter.maximumFractionDigits = 1
  112. return formatter
  113. }
  114. private var bolusFormatter: NumberFormatter {
  115. let formatter = NumberFormatter()
  116. formatter.numberStyle = .decimal
  117. formatter.minimumIntegerDigits = 0
  118. formatter.maximumFractionDigits = 2
  119. formatter.decimalSeparator = "."
  120. return formatter
  121. }
  122. private var carbsFormatter: NumberFormatter {
  123. let formatter = NumberFormatter()
  124. formatter.numberStyle = .decimal
  125. formatter.maximumFractionDigits = 0
  126. return formatter
  127. }
  128. private var fpuFormatter: NumberFormatter {
  129. let formatter = NumberFormatter()
  130. formatter.numberStyle = .decimal
  131. formatter.maximumFractionDigits = 1
  132. formatter.decimalSeparator = "."
  133. formatter.minimumIntegerDigits = 0
  134. return formatter
  135. }
  136. @Environment(\.horizontalSizeClass) var hSizeClass
  137. @Environment(\.verticalSizeClass) var vSizeClass
  138. // MARK: - Views
  139. var body: some View {
  140. GeometryReader { geo in
  141. ZStack(alignment: .leading) {
  142. yGridView(fullSize: geo.size)
  143. mainScrollView(fullSize: geo.size)
  144. glucoseLabelsView(fullSize: geo.size)
  145. }
  146. .onChange(of: hSizeClass) { _ in
  147. update(fullSize: geo.size)
  148. }
  149. .onChange(of: vSizeClass) { _ in
  150. update(fullSize: geo.size)
  151. }
  152. .onReceive(
  153. Foundation.NotificationCenter.default
  154. .publisher(for: UIDevice.orientationDidChangeNotification)
  155. ) { _ in
  156. update(fullSize: geo.size)
  157. }
  158. }
  159. }
  160. private func mainScrollView(fullSize: CGSize) -> some View {
  161. ScrollViewReader { scroll in
  162. ScrollView(.horizontal, showsIndicators: false) {
  163. ZStack(alignment: .top) {
  164. tempTargetsView(fullSize: fullSize).drawingGroup()
  165. basalView(fullSize: fullSize).drawingGroup()
  166. mainView(fullSize: fullSize).id(Config.endID)
  167. .drawingGroup()
  168. }
  169. }
  170. .onChange(of: glucose) { _ in
  171. scroll.scrollTo(Config.endID, anchor: .trailing)
  172. }
  173. .onChange(of: suggestion) { _ in
  174. scroll.scrollTo(Config.endID, anchor: .trailing)
  175. }
  176. .onChange(of: tempBasals) { _ in
  177. scroll.scrollTo(Config.endID, anchor: .trailing)
  178. }
  179. .onChange(of: screenHours) { _ in
  180. scroll.scrollTo(Config.endID, anchor: .trailing)
  181. }
  182. .onAppear {
  183. // add trigger to the end of main queue
  184. DispatchQueue.main.async {
  185. scroll.scrollTo(Config.endID, anchor: .trailing)
  186. didAppearTrigger = true
  187. }
  188. }
  189. }
  190. }
  191. private func yGridView(fullSize: CGSize) -> some View {
  192. let useColour = displayYgridLines ? Color.secondary : Color.clear
  193. return ZStack {
  194. Path { path in
  195. let range = glucoseYRange
  196. let step = (range.maxY - range.minY) / CGFloat(Config.yLinesCount)
  197. for line in 0 ... Config.yLinesCount {
  198. path.move(to: CGPoint(x: 0, y: range.minY + CGFloat(line) * step))
  199. path.addLine(to: CGPoint(x: fullSize.width, y: range.minY + CGFloat(line) * step))
  200. }
  201. }.stroke(useColour, lineWidth: 0.15)
  202. // horizontal limits
  203. if thresholdLines {
  204. let range = glucoseYRange
  205. let topstep = (range.maxY - range.minY) / CGFloat(range.maxValue - range.minValue) *
  206. (CGFloat(range.maxValue) - CGFloat(highGlucose))
  207. if CGFloat(range.maxValue) > CGFloat(highGlucose) {
  208. Path { path in
  209. path.move(to: CGPoint(x: 0, y: range.minY + topstep))
  210. path.addLine(to: CGPoint(x: fullSize.width, y: range.minY + topstep))
  211. }.stroke(Color.loopYellow, lineWidth: 0.5) // .StrokeStyle(lineWidth: 0.5, dash: [5])
  212. }
  213. let yrange = glucoseYRange
  214. let bottomstep = (yrange.maxY - yrange.minY) / CGFloat(yrange.maxValue - yrange.minValue) *
  215. (CGFloat(yrange.maxValue) - CGFloat(lowGlucose))
  216. if CGFloat(yrange.minValue) < CGFloat(lowGlucose) {
  217. Path { path in
  218. path.move(to: CGPoint(x: 0, y: yrange.minY + bottomstep))
  219. path.addLine(to: CGPoint(x: fullSize.width, y: yrange.minY + bottomstep))
  220. }.stroke(Color.loopRed, lineWidth: 0.5)
  221. }
  222. }
  223. }
  224. }
  225. private func glucoseLabelsView(fullSize: CGSize) -> some View {
  226. ForEach(0 ..< Config.yLinesCount + 1, id: \.self) { line -> AnyView in
  227. let range = glucoseYRange
  228. let yStep = (range.maxY - range.minY) / CGFloat(Config.yLinesCount)
  229. let valueStep = Double(range.maxValue - range.minValue) / Double(Config.yLinesCount)
  230. let value = round(Double(range.maxValue) - Double(line) * valueStep) *
  231. (units == .mmolL ? Double(GlucoseUnits.exchangeRate) : 1)
  232. return Text(glucoseFormatter.string(from: value as NSNumber)!)
  233. .position(CGPoint(x: fullSize.width - 12, y: range.minY + CGFloat(line) * yStep))
  234. .font(.caption2)
  235. .asAny()
  236. }
  237. }
  238. private func basalView(fullSize: CGSize) -> some View {
  239. ZStack {
  240. tempBasalPath.scale(x: zoomScale, anchor: .zero).fill(Color.basal.opacity(0.5))
  241. tempBasalPath.scale(x: zoomScale, anchor: .zero).stroke(Color.insulin, lineWidth: 1)
  242. regularBasalPath.scale(x: zoomScale, anchor: .zero)
  243. .stroke(Color.insulin, style: StrokeStyle(lineWidth: 0.7, dash: [4]))
  244. suspensionsPath.scale(x: zoomScale, anchor: .zero)
  245. .stroke(Color.loopGray.opacity(0.7), style: StrokeStyle(lineWidth: 0.7)).scaleEffect(x: 1, y: -1)
  246. suspensionsPath.scale(x: zoomScale, anchor: .zero).fill(Color.loopGray.opacity(0.2)).scaleEffect(x: 1, y: -1)
  247. }
  248. .scaleEffect(x: 1, y: -1)
  249. .frame(width: glucoseAndAdditionalWidth(fullSize: fullSize))
  250. .frame(maxHeight: Config.basalHeight)
  251. .background(Color.clear)
  252. .onChange(of: tempBasals) { _ in
  253. calculateBasalPoints(fullSize: fullSize)
  254. }
  255. .onChange(of: suspensions) { _ in
  256. calculateSuspensions(fullSize: fullSize)
  257. }
  258. .onChange(of: maxBasal) { _ in
  259. calculateBasalPoints(fullSize: fullSize)
  260. }
  261. .onChange(of: autotunedBasalProfile) { _ in
  262. calculateBasalPoints(fullSize: fullSize)
  263. }
  264. .onChange(of: didAppearTrigger) { _ in
  265. calculateBasalPoints(fullSize: fullSize)
  266. }
  267. }
  268. private func mainView(fullSize: CGSize) -> some View {
  269. VStack {
  270. ZStack {
  271. xGridView(fullSize: fullSize)
  272. carbsView(fullSize: fullSize)
  273. fpuView(fullSize: fullSize)
  274. bolusView(fullSize: fullSize)
  275. if smooth { unSmoothedGlucoseView(fullSize: fullSize) }
  276. glucoseView(fullSize: fullSize)
  277. manualGlucoseView(fullSize: fullSize)
  278. manualGlucoseCenterView(fullSize: fullSize)
  279. announcementView(fullSize: fullSize)
  280. predictionsView(fullSize: fullSize)
  281. }
  282. timeLabelsView(fullSize: fullSize)
  283. }
  284. .frame(width: glucoseAndAdditionalWidth(fullSize: fullSize))
  285. }
  286. /// returns the width of the full chart view including predictions for the current `screenHours`
  287. private func glucoseAndAdditionalWidth(fullSize: CGSize) -> CGFloat {
  288. // fullGlucoseWidth returns the width scaled to 1h screen hours. Scale it down to screenHours
  289. fullGlucoseWidth(viewWidth: fullSize.width) / CGFloat(screenHours)
  290. + additionalWidthScaled(viewWidth: fullSize.width)
  291. }
  292. /// returns the additional width for predictions, scaled to `screenHours`
  293. private func additionalWidthScaled(viewWidth: CGFloat) -> CGFloat {
  294. guard let predictions = suggestion?.predictions,
  295. let deliveredAt = suggestion?.deliverAt,
  296. let last = glucose.last
  297. else {
  298. return Config.minAdditionalWidth
  299. }
  300. let iob = predictions.iob?.count ?? 0
  301. let zt = predictions.zt?.count ?? 0
  302. let cob = predictions.cob?.count ?? 0
  303. let uam = predictions.uam?.count ?? 0
  304. let max = [iob, zt, cob, uam].max() ?? 0
  305. let lastDeltaTime = last.dateString.timeIntervalSince(deliveredAt)
  306. let additionalTime = CGFloat(TimeInterval(max) * 5.minutes.timeInterval - lastDeltaTime)
  307. let oneSecondWidth = oneSecondStep(viewWidth: viewWidth) / CGFloat(screenHours)
  308. return Swift.min(Swift.max(additionalTime * oneSecondWidth, Config.minAdditionalWidth), 275)
  309. }
  310. @Environment(\.colorScheme) var colorScheme
  311. private func xGridView(fullSize: CGSize) -> some View {
  312. let useColour = displayXgridLines ? Color.secondary : Color.clear
  313. return ZStack {
  314. Path { path in
  315. for hour in 0 ..< hours + hours {
  316. if screenHours < 12 || hour % 2 == 0 {
  317. // only show every second line if screenHours is too big
  318. let x = firstHourPosition(viewWidth: fullSize.width) +
  319. oneSecondStep(viewWidth: fullSize.width) *
  320. CGFloat(hour) * CGFloat(1.hours.timeInterval)
  321. path.move(to: CGPoint(x: x, y: 0))
  322. path.addLine(to: CGPoint(x: x, y: fullSize.height - 20))
  323. }
  324. }
  325. }
  326. .stroke(useColour, lineWidth: 0.15)
  327. Path { path in // vertical timeline
  328. let x = timeToXCoordinate(timerDate.timeIntervalSince1970, fullSize: fullSize) * zoomScale
  329. path.move(to: CGPoint(x: x, y: 0))
  330. path.addLine(to: CGPoint(x: x, y: fullSize.height - 20))
  331. }
  332. .stroke(
  333. colorScheme == .dark ? Color.white : Color.black,
  334. style: StrokeStyle(lineWidth: 0.5, dash: [5])
  335. )
  336. }
  337. }
  338. // MARK: TO DO: CHANGE TIME LABELS TO ONLY DISPLAY EVERY SECOND LABEL WHEN SCREENHOURS IS TOO BIG
  339. // private func timeLabelsView(fullSize: CGSize) -> some View {
  340. // let format = screenHours > 6 ? date24Formatter : dateFormatter
  341. // return ZStack {
  342. // // X time labels
  343. // ForEach(0 ..< hours + hours) { hour in
  344. // Text(format.string(from: firstHourDate().addingTimeInterval(hour.hours.timeInterval)))
  345. // .font(.caption)
  346. // .position(
  347. // x: firstHourPosition(viewWidth: fullSize.width) +
  348. // oneSecondStep(viewWidth: fullSize.width) *
  349. // CGFloat(hour) * CGFloat(1.hours.timeInterval),
  350. // y: 10.0
  351. // )
  352. // .foregroundColor(.secondary)
  353. // }
  354. // }.frame(maxHeight: 20)
  355. // }
  356. private func timeLabelsView(fullSize: CGSize) -> some View {
  357. let format = screenHours > 6 ? date24Formatter : dateFormatter
  358. return ZStack {
  359. // X time labels
  360. ForEach(0 ..< hours + hours) { hour in
  361. if screenHours >= 12 && hour % 2 == 1 {
  362. // only show every second time label if screenHours is too big
  363. EmptyView()
  364. } else {
  365. Text(format.string(from: firstHourDate().addingTimeInterval(hour.hours.timeInterval)))
  366. .font(.caption)
  367. .position(
  368. x: firstHourPosition(viewWidth: fullSize.width) +
  369. oneSecondStep(viewWidth: fullSize.width) *
  370. CGFloat(hour) * CGFloat(1.hours.timeInterval),
  371. y: 10.0
  372. )
  373. .foregroundColor(.secondary)
  374. }
  375. }
  376. }.frame(maxHeight: 20)
  377. }
  378. private func glucoseView(fullSize: CGSize) -> some View {
  379. Path { path in
  380. for rect in glucoseDots {
  381. path.addEllipse(in: scaleCenter(rect: rect))
  382. }
  383. }
  384. .fill(Color.loopGreen)
  385. .onChange(of: glucose) { _ in
  386. update(fullSize: fullSize)
  387. }
  388. .onChange(of: didAppearTrigger) { _ in
  389. update(fullSize: fullSize)
  390. }
  391. .onReceive(Foundation.NotificationCenter.default.publisher(for: UIApplication.willEnterForegroundNotification)) { _ in
  392. update(fullSize: fullSize)
  393. }
  394. }
  395. private func manualGlucoseView(fullSize: CGSize) -> some View {
  396. Path { path in
  397. for rect in manualGlucoseDots {
  398. path.addEllipse(in: scaleCenter(rect: rect))
  399. }
  400. }
  401. .fill(Color.gray)
  402. .onChange(of: isManual) { _ in
  403. update(fullSize: fullSize)
  404. }
  405. .onChange(of: didAppearTrigger) { _ in
  406. update(fullSize: fullSize)
  407. }
  408. .onReceive(Foundation.NotificationCenter.default.publisher(for: UIApplication.willEnterForegroundNotification)) { _ in
  409. update(fullSize: fullSize)
  410. }
  411. }
  412. private func announcementView(fullSize: CGSize) -> some View {
  413. ZStack {
  414. ForEach(announcementDots, id: \.rect.minX) { info -> AnyView in
  415. let scaledRect = scaleCenter(rect: info.rect)
  416. let position = CGPoint(x: scaledRect.midX + 5, y: scaledRect.maxY - Config.owlOffset)
  417. let type: String =
  418. info.note.contains("true") ?
  419. Command.open :
  420. info.note.contains("false") ?
  421. Command.closed :
  422. info.note.contains("suspend") ?
  423. Command.suspend :
  424. info.note.contains("resume") ?
  425. Command.resume :
  426. info.note.contains("tempbasal") ?
  427. Command.tempbasal : Command.bolus
  428. VStack {
  429. Text(type).font(.caption2).foregroundStyle(.orange)
  430. Image("owl").resizable().frame(maxWidth: Config.owlSeize, maxHeight: Config.owlSeize).scaledToFill()
  431. }.position(position).asAny()
  432. }
  433. }
  434. .onChange(of: announcement) { _ in
  435. calculateAnnouncementDots(fullSize: fullSize)
  436. }
  437. .onChange(of: didAppearTrigger) { _ in
  438. calculateAnnouncementDots(fullSize: fullSize)
  439. }
  440. }
  441. private func manualGlucoseCenterView(fullSize: CGSize) -> some View {
  442. Path { path in
  443. for rect in manualGlucoseDotsCenter {
  444. path.addEllipse(in: scaleCenter(rect: rect))
  445. }
  446. }
  447. .fill(Color.red)
  448. .onChange(of: isManual) { _ in
  449. update(fullSize: fullSize)
  450. }
  451. .onChange(of: didAppearTrigger) { _ in
  452. update(fullSize: fullSize)
  453. }
  454. .onReceive(
  455. Foundation.NotificationCenter.default
  456. .publisher(for: UIApplication.willEnterForegroundNotification)
  457. ) { _ in
  458. update(fullSize: fullSize)
  459. }
  460. }
  461. private func unSmoothedGlucoseView(fullSize: CGSize) -> some View {
  462. Path { path in
  463. var lines: [CGPoint] = []
  464. for rect in unSmoothedGlucoseDots {
  465. let scaled = scaleCenter(rect: rect)
  466. lines.append(CGPoint(x: scaled.midX, y: scaled.midY))
  467. path.addEllipse(in: scaled)
  468. }
  469. path.addLines(lines)
  470. }
  471. .stroke(Color.loopGray, lineWidth: 0.5)
  472. .onChange(of: glucose) { _ in
  473. update(fullSize: fullSize)
  474. }
  475. .onChange(of: didAppearTrigger) { _ in
  476. update(fullSize: fullSize)
  477. }
  478. .onReceive(Foundation.NotificationCenter.default.publisher(for: UIApplication.willEnterForegroundNotification)) { _ in
  479. update(fullSize: fullSize)
  480. }
  481. }
  482. private func bolusView(fullSize: CGSize) -> some View {
  483. ZStack {
  484. let bolusPath = Path { path in
  485. for dot in bolusDots {
  486. path.addEllipse(in: scaleCenter(rect: dot.rect))
  487. }
  488. }
  489. bolusPath
  490. .fill(Color.insulin)
  491. bolusPath
  492. .stroke(Color.primary, lineWidth: 0.5)
  493. ForEach(bolusDots, id: \.rect.minX) { info -> AnyView in
  494. let rect = scaleCenter(rect: info.rect)
  495. let position = CGPoint(x: rect.midX, y: rect.maxY + 8)
  496. return Text(bolusFormatter.string(from: info.value as NSNumber)!).font(.caption2)
  497. .position(position)
  498. .asAny()
  499. }
  500. }
  501. .onChange(of: boluses) { _ in
  502. calculateBolusDots(fullSize: fullSize)
  503. }
  504. .onChange(of: didAppearTrigger) { _ in
  505. calculateBolusDots(fullSize: fullSize)
  506. }
  507. }
  508. private func carbsView(fullSize: CGSize) -> some View {
  509. ZStack {
  510. let carbsPath = Path { path in
  511. for dot in carbsDots {
  512. path.addEllipse(in: scaleCenter(rect: dot.rect))
  513. }
  514. }
  515. carbsPath
  516. .fill(Color.loopYellow)
  517. carbsPath
  518. .stroke(Color.primary, lineWidth: 0.5)
  519. ForEach(carbsDots, id: \.rect.minX) { info -> AnyView in
  520. let rect = scaleCenter(rect: info.rect)
  521. let position = CGPoint(x: rect.midX, y: rect.minY - 8)
  522. return Text(carbsFormatter.string(from: info.value as NSNumber)!).font(.caption2)
  523. .position(position)
  524. .asAny()
  525. }
  526. }
  527. .onChange(of: carbs) { _ in
  528. calculateCarbsDots(fullSize: fullSize)
  529. }
  530. .onChange(of: didAppearTrigger) { _ in
  531. calculateCarbsDots(fullSize: fullSize)
  532. }
  533. }
  534. private func fpuView(fullSize: CGSize) -> some View {
  535. ZStack {
  536. let fpuPath = Path { path in
  537. for dot in fpuDots {
  538. path.addEllipse(in: scaleCenter(rect: dot.rect))
  539. }
  540. }
  541. fpuPath
  542. .fill(.orange.opacity(0.5))
  543. fpuPath
  544. .stroke(Color.primary, lineWidth: 0.2)
  545. }
  546. .onChange(of: carbs) { _ in
  547. calculateFPUsDots(fullSize: fullSize)
  548. }
  549. .onChange(of: didAppearTrigger) { _ in
  550. calculateFPUsDots(fullSize: fullSize)
  551. }
  552. }
  553. private func tempTargetsView(fullSize: CGSize) -> some View {
  554. ZStack {
  555. tempTargetsPath
  556. .scale(x: zoomScale, anchor: .zero)
  557. .fill(Color.tempBasal.opacity(0.5))
  558. tempTargetsPath
  559. .scale(x: zoomScale, anchor: .zero)
  560. .stroke(Color.basal.opacity(0.5), lineWidth: 1)
  561. }
  562. .onChange(of: glucose) { _ in
  563. calculateTempTargetsRects(fullSize: fullSize)
  564. }
  565. .onChange(of: tempTargets) { _ in
  566. calculateTempTargetsRects(fullSize: fullSize)
  567. }
  568. .onChange(of: didAppearTrigger) { _ in
  569. calculateTempTargetsRects(fullSize: fullSize)
  570. }
  571. }
  572. private func scale(rect: CGRect) -> CGRect {
  573. CGRect(origin: CGPoint(x: rect.origin.x * zoomScale, y: rect.origin.y), size: rect.size)
  574. }
  575. private func scaleCenter(rect: CGRect) -> CGRect {
  576. CGRect(origin: CGPoint(x: rect.midX * zoomScale - rect.width / 2, y: rect.origin.y), size: rect.size)
  577. }
  578. private func predictionsView(fullSize: CGSize) -> some View {
  579. Group {
  580. Path { path in
  581. for rect in predictionDots[.iob] ?? [] {
  582. path.addEllipse(in: scaleCenter(rect: rect))
  583. }
  584. }.fill(Color.insulin)
  585. Path { path in
  586. for rect in predictionDots[.cob] ?? [] {
  587. path.addEllipse(in: scaleCenter(rect: rect))
  588. }
  589. }.fill(Color.loopYellow)
  590. Path { path in
  591. for rect in predictionDots[.zt] ?? [] {
  592. path.addEllipse(in: scaleCenter(rect: rect))
  593. }
  594. }.fill(Color.zt)
  595. Path { path in
  596. for rect in predictionDots[.uam] ?? [] {
  597. path.addEllipse(in: scaleCenter(rect: rect))
  598. }
  599. }.fill(Color.uam)
  600. }
  601. .onChange(of: suggestion) { _ in
  602. update(fullSize: fullSize)
  603. }
  604. }
  605. }
  606. // MARK: - Calculations
  607. /// some of the calculations done here can take quite long (100ms+) and are not able to update data at a fast rate
  608. /// therefore we stick to the 1h screen window for these calculations and scale the results as needed to `screenHours` which has little extra overhead and enables changing the screen hours with no lag
  609. extension MainChartView {
  610. private func update(fullSize: CGSize) {
  611. calculatePredictionDots(fullSize: fullSize, type: .iob)
  612. calculatePredictionDots(fullSize: fullSize, type: .cob)
  613. calculatePredictionDots(fullSize: fullSize, type: .zt)
  614. calculatePredictionDots(fullSize: fullSize, type: .uam)
  615. calculateGlucoseDots(fullSize: fullSize)
  616. calculateManualGlucoseDots(fullSize: fullSize)
  617. calculateManualGlucoseDotsCenter(fullSize: fullSize)
  618. calculateAnnouncementDots(fullSize: fullSize)
  619. calculateUnSmoothedGlucoseDots(fullSize: fullSize)
  620. calculateBolusDots(fullSize: fullSize)
  621. calculateCarbsDots(fullSize: fullSize)
  622. calculateFPUsDots(fullSize: fullSize)
  623. calculateTempTargetsRects(fullSize: fullSize)
  624. calculateBasalPoints(fullSize: fullSize)
  625. calculateSuspensions(fullSize: fullSize)
  626. }
  627. private func calculateGlucoseDots(fullSize: CGSize) {
  628. calculationQueue.async {
  629. let dots = glucose.concurrentMap { value -> CGRect in
  630. let position = glucoseToCoordinate(value, fullSize: fullSize)
  631. return CGRect(x: position.x - 2, y: position.y - 2, width: 4, height: 4)
  632. }
  633. let range = self.getGlucoseYRange(fullSize: fullSize)
  634. DispatchQueue.main.async {
  635. glucoseYRange = range
  636. glucoseDots = dots
  637. }
  638. }
  639. }
  640. private func calculateManualGlucoseDots(fullSize: CGSize) {
  641. calculationQueue.async {
  642. let dots = isManual.concurrentMap { value -> CGRect in
  643. let position = glucoseToCoordinate(value, fullSize: fullSize)
  644. return CGRect(x: position.x - 2, y: position.y - 2, width: 14, height: 14)
  645. }
  646. let range = self.getGlucoseYRange(fullSize: fullSize)
  647. DispatchQueue.main.async {
  648. glucoseYRange = range
  649. manualGlucoseDots = dots
  650. }
  651. }
  652. }
  653. private func calculateManualGlucoseDotsCenter(fullSize: CGSize) {
  654. calculationQueue.async {
  655. let dots = isManual.concurrentMap { value -> CGRect in
  656. let position = glucoseToCoordinate(value, fullSize: fullSize)
  657. return CGRect(x: position.x, y: position.y, width: 10, height: 10)
  658. }
  659. let range = self.getGlucoseYRange(fullSize: fullSize)
  660. DispatchQueue.main.async {
  661. glucoseYRange = range
  662. manualGlucoseDotsCenter = dots
  663. }
  664. }
  665. }
  666. private func calculateAnnouncementDots(fullSize: CGSize) {
  667. calculationQueue.async {
  668. let dots = announcement.map { value -> AnnouncementDot in
  669. let center = timeToInterpolatedPoint(value.createdAt.timeIntervalSince1970, fullSize: fullSize)
  670. let size = Config.announcementSize * Config.announcementScale
  671. let rect = CGRect(x: center.x - size / 2, y: center.y - size / 2, width: size, height: size)
  672. let note = value.notes
  673. return AnnouncementDot(rect: rect, value: 10, note: note)
  674. }
  675. let path = Path { path in
  676. for dot in dots {
  677. path.addEllipse(in: dot.rect)
  678. }
  679. }
  680. let range = self.getGlucoseYRange(fullSize: fullSize)
  681. DispatchQueue.main.async {
  682. glucoseYRange = range
  683. announcementDots = dots
  684. announcementPath = path
  685. }
  686. }
  687. }
  688. private func calculateUnSmoothedGlucoseDots(fullSize: CGSize) {
  689. calculationQueue.async {
  690. let dots = glucose.concurrentMap { value -> CGRect in
  691. let position = UnSmoothedGlucoseToCoordinate(value, fullSize: fullSize)
  692. return CGRect(x: position.x - 2, y: position.y - 2, width: 4, height: 4)
  693. }
  694. let range = self.getGlucoseYRange(fullSize: fullSize)
  695. DispatchQueue.main.async {
  696. glucoseYRange = range
  697. unSmoothedGlucoseDots = dots
  698. }
  699. }
  700. }
  701. private func calculateBolusDots(fullSize: CGSize) {
  702. calculationQueue.async {
  703. let dots = boluses.map { value -> DotInfo in
  704. let center = timeToInterpolatedPoint(value.timestamp.timeIntervalSince1970, fullSize: fullSize)
  705. let size = Config.bolusSize + CGFloat(value.amount ?? 0) * Config.bolusScale
  706. let rect = CGRect(x: center.x - size / 2, y: center.y - size / 2, width: size, height: size)
  707. return DotInfo(rect: rect, value: value.amount ?? 0)
  708. }
  709. DispatchQueue.main.async {
  710. bolusDots = dots
  711. }
  712. }
  713. }
  714. private func calculateCarbsDots(fullSize: CGSize) {
  715. calculationQueue.async {
  716. let realCarbs = carbs.filter { !($0.isFPU ?? false) }
  717. let dots = realCarbs.map { value -> DotInfo in
  718. let center = timeToInterpolatedPoint(
  719. value.actualDate != nil ? (value.actualDate ?? Date()).timeIntervalSince1970 : value.createdAt
  720. .timeIntervalSince1970,
  721. fullSize: fullSize
  722. )
  723. let size = Config.carbsSize + CGFloat(value.carbs) * Config.carbsScale
  724. let rect = CGRect(x: center.x - size / 2, y: center.y - size / 2, width: size, height: size)
  725. return DotInfo(rect: rect, value: value.carbs)
  726. }
  727. DispatchQueue.main.async {
  728. carbsDots = dots
  729. }
  730. }
  731. }
  732. private func calculateFPUsDots(fullSize: CGSize) {
  733. calculationQueue.async {
  734. let fpus = carbs.filter { $0.isFPU ?? false }
  735. let dots = fpus.map { value -> DotInfo in
  736. let center = timeToInterpolatedPoint(
  737. value.actualDate != nil ? (value.actualDate ?? Date()).timeIntervalSince1970 : value.createdAt
  738. .timeIntervalSince1970,
  739. fullSize: fullSize
  740. )
  741. let size = Config.fpuSize + CGFloat(value.carbs) * Config.fpuScale
  742. let rect = CGRect(x: center.x - size / 2, y: center.y - size / 2, width: size, height: size)
  743. return DotInfo(rect: rect, value: value.carbs)
  744. }
  745. DispatchQueue.main.async {
  746. fpuDots = dots
  747. }
  748. }
  749. }
  750. private func calculatePredictionDots(fullSize: CGSize, type: PredictionType) {
  751. calculationQueue.async {
  752. let values: [Int] = { () -> [Int] in
  753. switch type {
  754. case .iob:
  755. return suggestion?.predictions?.iob ?? []
  756. case .cob:
  757. return suggestion?.predictions?.cob ?? []
  758. case .zt:
  759. return suggestion?.predictions?.zt ?? []
  760. case .uam:
  761. return suggestion?.predictions?.uam ?? []
  762. }
  763. }()
  764. var index = 0
  765. let dots = values.map { value -> CGRect in
  766. let position = predictionToCoordinate(value, fullSize: fullSize, index: index)
  767. index += 1
  768. return CGRect(x: position.x - 2, y: position.y - 2, width: 4, height: 4)
  769. }
  770. DispatchQueue.main.async {
  771. predictionDots[type] = dots
  772. }
  773. }
  774. }
  775. private func calculateBasalPoints(fullSize: CGSize) {
  776. calculationQueue.async {
  777. self.cachedMaxBasalRate = nil
  778. let dayAgoTime = Date().addingTimeInterval(-1.days.timeInterval).timeIntervalSince1970
  779. let firstTempTime = (tempBasals.first?.timestamp ?? Date()).timeIntervalSince1970
  780. var lastTimeEnd = firstTempTime
  781. let firstRegularBasalPoints = findRegularBasalPoints(
  782. timeBegin: dayAgoTime,
  783. timeEnd: firstTempTime,
  784. fullSize: fullSize,
  785. autotuned: false
  786. )
  787. let tempBasalPoints = firstRegularBasalPoints + tempBasals.chunks(ofCount: 2).map { chunk -> [CGPoint] in
  788. let chunk = Array(chunk)
  789. guard chunk.count == 2, chunk[0].type == .tempBasal, chunk[1].type == .tempBasalDuration else { return [] }
  790. let timeBegin = chunk[0].timestamp.timeIntervalSince1970
  791. let timeEnd = timeBegin + (chunk[1].durationMin ?? 0).minutes.timeInterval
  792. let rateCost = Config.basalHeight / CGFloat(maxBasalRate())
  793. let x0 = timeToXCoordinate(timeBegin, fullSize: fullSize)
  794. let y0 = Config.basalHeight - CGFloat(chunk[0].rate ?? 0) * rateCost
  795. let regularPoints = findRegularBasalPoints(
  796. timeBegin: lastTimeEnd,
  797. timeEnd: timeBegin,
  798. fullSize: fullSize,
  799. autotuned: false
  800. )
  801. lastTimeEnd = timeEnd
  802. return regularPoints + [CGPoint(x: x0, y: y0)]
  803. }.flatMap { $0 }
  804. let tempBasalPath = Path { path in
  805. var yPoint: CGFloat = Config.basalHeight
  806. path.move(to: CGPoint(x: 0, y: yPoint))
  807. for point in tempBasalPoints {
  808. path.addLine(to: CGPoint(x: point.x, y: yPoint))
  809. path.addLine(to: point)
  810. yPoint = point.y
  811. }
  812. let lastPoint = lastBasalPoint(fullSize: fullSize)
  813. path.addLine(to: CGPoint(x: lastPoint.x, y: yPoint))
  814. path.addLine(to: CGPoint(x: lastPoint.x, y: Config.basalHeight))
  815. path.addLine(to: CGPoint(x: 0, y: Config.basalHeight))
  816. }
  817. let endDateTime = dayAgoTime + 12.hours
  818. .timeInterval + 12.hours
  819. .timeInterval
  820. let autotunedBasalPoints = findRegularBasalPoints(
  821. timeBegin: dayAgoTime,
  822. timeEnd: endDateTime,
  823. fullSize: fullSize,
  824. autotuned: true
  825. )
  826. let autotunedBasalPath = Path { path in
  827. var yPoint: CGFloat = Config.basalHeight
  828. path.move(to: CGPoint(x: -50, y: yPoint))
  829. for point in autotunedBasalPoints {
  830. path.addLine(to: CGPoint(x: point.x, y: yPoint))
  831. path.addLine(to: point)
  832. yPoint = point.y
  833. }
  834. path.addLine(to: CGPoint(x: timeToXCoordinate(endDateTime, fullSize: fullSize), y: yPoint))
  835. }
  836. DispatchQueue.main.async {
  837. self.tempBasalPath = tempBasalPath
  838. self.regularBasalPath = autotunedBasalPath
  839. }
  840. }
  841. }
  842. private func calculateSuspensions(fullSize: CGSize) {
  843. calculationQueue.async {
  844. var rects = suspensions.windows(ofCount: 2).map { window -> CGRect? in
  845. let window = Array(window)
  846. guard window[0].type == .pumpSuspend, window[1].type == .pumpResume else { return nil }
  847. let x0 = self.timeToXCoordinate(window[0].timestamp.timeIntervalSince1970, fullSize: fullSize)
  848. let x1 = self.timeToXCoordinate(window[1].timestamp.timeIntervalSince1970, fullSize: fullSize)
  849. return CGRect(x: x0, y: 0, width: x1 - x0, height: Config.basalHeight * 0.7)
  850. }
  851. let firstRec = self.suspensions.first.flatMap { event -> CGRect? in
  852. guard event.type == .pumpResume else { return nil }
  853. let tbrTime = self.tempBasals.last { $0.timestamp < event.timestamp }
  854. .map { $0.timestamp.timeIntervalSince1970 + TimeInterval($0.durationMin ?? 0) * 60 } ?? Date()
  855. .addingTimeInterval(-1.days.timeInterval).timeIntervalSince1970
  856. let x0 = self.timeToXCoordinate(tbrTime, fullSize: fullSize)
  857. let x1 = self.timeToXCoordinate(event.timestamp.timeIntervalSince1970, fullSize: fullSize)
  858. return CGRect(
  859. x: x0,
  860. y: 0,
  861. width: x1 - x0,
  862. height: Config.basalHeight * 0.7
  863. )
  864. }
  865. let lastRec = self.suspensions.last.flatMap { event -> CGRect? in
  866. guard event.type == .pumpSuspend else { return nil }
  867. let tbrTimeX = self.tempBasals.first { $0.timestamp > event.timestamp }
  868. .map { self.timeToXCoordinate($0.timestamp.timeIntervalSince1970, fullSize: fullSize) }
  869. let x0 = self.timeToXCoordinate(event.timestamp.timeIntervalSince1970, fullSize: fullSize)
  870. let x1 = tbrTimeX ?? self.fullGlucoseWidth(viewWidth: fullSize.width) + 275
  871. return CGRect(x: x0, y: 0, width: x1 - x0, height: Config.basalHeight * 0.7)
  872. }
  873. rects.append(firstRec)
  874. rects.append(lastRec)
  875. let path = Path { path in
  876. path.addRects(rects.compactMap { $0 })
  877. }
  878. DispatchQueue.main.async {
  879. suspensionsPath = path
  880. }
  881. }
  882. }
  883. private func maxBasalRate() -> Decimal {
  884. if let cached = cachedMaxBasalRate {
  885. return cached
  886. }
  887. let maxRegularBasalRate = max(
  888. basalProfile.map(\.rate).max() ?? maxBasal,
  889. autotunedBasalProfile.map(\.rate).max() ?? maxBasal
  890. )
  891. var maxTempBasalRate = tempBasals.compactMap(\.rate).max() ?? maxRegularBasalRate
  892. if maxTempBasalRate == 0 {
  893. maxTempBasalRate = maxRegularBasalRate
  894. }
  895. cachedMaxBasalRate = max(maxTempBasalRate, maxRegularBasalRate)
  896. return cachedMaxBasalRate ?? maxBasal
  897. }
  898. private func calculateTempTargetsRects(fullSize: CGSize) {
  899. calculationQueue.async {
  900. var rects = tempTargets.map { tempTarget -> CGRect in
  901. let x0 = timeToXCoordinate(tempTarget.createdAt.timeIntervalSince1970, fullSize: fullSize)
  902. let y0 = glucoseToYCoordinate(Int(tempTarget.targetTop ?? 0), fullSize: fullSize)
  903. let x1 = timeToXCoordinate(
  904. tempTarget.createdAt.timeIntervalSince1970 + Int(tempTarget.duration).minutes.timeInterval,
  905. fullSize: fullSize
  906. )
  907. let y1 = glucoseToYCoordinate(Int(tempTarget.targetBottom ?? 0), fullSize: fullSize)
  908. return CGRect(
  909. x: x0,
  910. y: y0 - 3,
  911. width: x1 - x0,
  912. height: y1 - y0 + 6
  913. )
  914. }
  915. if rects.count > 1 {
  916. rects = rects.reduce([]) { result, rect -> [CGRect] in
  917. guard var last = result.last else { return [rect] }
  918. if last.origin.x + last.width > rect.origin.x {
  919. last.size.width = rect.origin.x - last.origin.x
  920. }
  921. var res = Array(result.dropLast())
  922. res.append(contentsOf: [last, rect])
  923. return res
  924. }
  925. }
  926. let path = Path { path in
  927. path.addRects(rects)
  928. }
  929. DispatchQueue.main.async {
  930. tempTargetsPath = path
  931. }
  932. }
  933. }
  934. private func findRegularBasalPoints(
  935. timeBegin: TimeInterval,
  936. timeEnd: TimeInterval,
  937. fullSize: CGSize,
  938. autotuned: Bool
  939. ) -> [CGPoint] {
  940. guard timeBegin < timeEnd else {
  941. return []
  942. }
  943. let beginDate = Date(timeIntervalSince1970: timeBegin)
  944. let calendar = Calendar.current
  945. let startOfDay = calendar.startOfDay(for: beginDate)
  946. let profile = autotuned ? autotunedBasalProfile : basalProfile
  947. let basalNormalized = profile.map {
  948. (
  949. time: startOfDay.addingTimeInterval($0.minutes.minutes.timeInterval).timeIntervalSince1970,
  950. rate: $0.rate
  951. )
  952. } + profile.map {
  953. (
  954. time: startOfDay.addingTimeInterval($0.minutes.minutes.timeInterval + 1.days.timeInterval).timeIntervalSince1970,
  955. rate: $0.rate
  956. )
  957. } + profile.map {
  958. (
  959. time: startOfDay.addingTimeInterval($0.minutes.minutes.timeInterval + 2.days.timeInterval).timeIntervalSince1970,
  960. rate: $0.rate
  961. )
  962. }
  963. let basalTruncatedPoints = basalNormalized.windows(ofCount: 2)
  964. .compactMap { window -> CGPoint? in
  965. let window = Array(window)
  966. if window[0].time < timeBegin, window[1].time < timeBegin {
  967. return nil
  968. }
  969. let rateCost = Config.basalHeight / CGFloat(maxBasalRate())
  970. if window[0].time < timeBegin, window[1].time >= timeBegin {
  971. let x = timeToXCoordinate(timeBegin, fullSize: fullSize)
  972. let y = Config.basalHeight - CGFloat(window[0].rate) * rateCost
  973. return CGPoint(x: x, y: y)
  974. }
  975. if window[0].time >= timeBegin, window[0].time < timeEnd {
  976. let x = timeToXCoordinate(window[0].time, fullSize: fullSize)
  977. let y = Config.basalHeight - CGFloat(window[0].rate) * rateCost
  978. return CGPoint(x: x, y: y)
  979. }
  980. return nil
  981. }
  982. return basalTruncatedPoints
  983. }
  984. private func lastBasalPoint(fullSize: CGSize) -> CGPoint {
  985. let lastBasal = Array(tempBasals.suffix(2))
  986. guard lastBasal.count == 2 else {
  987. return CGPoint(x: timeToXCoordinate(Date().timeIntervalSince1970, fullSize: fullSize), y: Config.basalHeight)
  988. }
  989. let endBasalTime = lastBasal[0].timestamp.timeIntervalSince1970 + (lastBasal[1].durationMin?.minutes.timeInterval ?? 0)
  990. let rateCost = Config.basalHeight / CGFloat(maxBasalRate())
  991. let x = timeToXCoordinate(endBasalTime, fullSize: fullSize)
  992. let y = Config.basalHeight - CGFloat(lastBasal[0].rate ?? 0) * rateCost
  993. return CGPoint(x: x, y: y)
  994. }
  995. private func fullGlucoseWidth(viewWidth: CGFloat) -> CGFloat {
  996. viewWidth * CGFloat(hours)
  997. }
  998. private func oneSecondStep(viewWidth: CGFloat) -> CGFloat {
  999. viewWidth / CGFloat(1.hours.timeInterval)
  1000. }
  1001. private func maxPredValue() -> Int? {
  1002. [
  1003. suggestion?.predictions?.cob ?? [],
  1004. suggestion?.predictions?.iob ?? [],
  1005. suggestion?.predictions?.zt ?? [],
  1006. suggestion?.predictions?.uam ?? []
  1007. ]
  1008. .flatMap { $0 }
  1009. .max()
  1010. }
  1011. private func minPredValue() -> Int? {
  1012. [
  1013. suggestion?.predictions?.cob ?? [],
  1014. suggestion?.predictions?.iob ?? [],
  1015. suggestion?.predictions?.zt ?? [],
  1016. suggestion?.predictions?.uam ?? []
  1017. ]
  1018. .flatMap { $0 }
  1019. .min()
  1020. }
  1021. private func maxTargetValue() -> Int? {
  1022. tempTargets.map { $0.targetTop ?? 0 }.filter { $0 > 0 }.max().map(Int.init)
  1023. }
  1024. private func minTargetValue() -> Int? {
  1025. tempTargets.map { $0.targetBottom ?? 0 }.filter { $0 > 0 }.min().map(Int.init)
  1026. }
  1027. private func glucoseToCoordinate(_ glucoseEntry: BloodGlucose, fullSize: CGSize) -> CGPoint {
  1028. let x = timeToXCoordinate(glucoseEntry.dateString.timeIntervalSince1970, fullSize: fullSize)
  1029. let y = glucoseToYCoordinate(glucoseEntry.glucose ?? 0, fullSize: fullSize)
  1030. return CGPoint(x: x, y: y)
  1031. }
  1032. private func UnSmoothedGlucoseToCoordinate(_ glucoseEntry: BloodGlucose, fullSize: CGSize) -> CGPoint {
  1033. let x = timeToXCoordinate(glucoseEntry.dateString.timeIntervalSince1970, fullSize: fullSize)
  1034. let glucoseValue: Decimal = glucoseEntry.unfiltered ?? Decimal(glucoseEntry.glucose ?? 0)
  1035. let y = glucoseToYCoordinate(Int(glucoseValue), fullSize: fullSize)
  1036. return CGPoint(x: x, y: y)
  1037. }
  1038. private func predictionToCoordinate(_ pred: Int, fullSize: CGSize, index: Int) -> CGPoint {
  1039. guard let deliveredAt = suggestion?.deliverAt else {
  1040. return .zero
  1041. }
  1042. let predTime = deliveredAt.timeIntervalSince1970 + TimeInterval(index) * 5.minutes.timeInterval
  1043. let x = timeToXCoordinate(predTime, fullSize: fullSize)
  1044. let y = glucoseToYCoordinate(pred, fullSize: fullSize)
  1045. return CGPoint(x: x, y: y)
  1046. }
  1047. private func timeToXCoordinate(_ time: TimeInterval, fullSize: CGSize) -> CGFloat {
  1048. let xOffset = -Date().addingTimeInterval(-1.days.timeInterval).timeIntervalSince1970
  1049. let stepXFraction = fullGlucoseWidth(viewWidth: fullSize.width) / CGFloat(hours.hours.timeInterval)
  1050. let x = CGFloat(time + xOffset) * stepXFraction
  1051. return x
  1052. }
  1053. /// inverse of `timeToXCoordinate`
  1054. private func xCoordinateToTime(x: CGFloat, fullSize: CGSize) -> TimeInterval {
  1055. let stepXFraction = fullGlucoseWidth(viewWidth: fullSize.width) / CGFloat(hours.hours.timeInterval)
  1056. let xx = x / stepXFraction
  1057. let xOffset = -Date().addingTimeInterval(-1.days.timeInterval).timeIntervalSince1970
  1058. let time = xx - xOffset
  1059. return time
  1060. }
  1061. private func glucoseToYCoordinate(_ glucoseValue: Int, fullSize: CGSize) -> CGFloat {
  1062. let topYPaddint = Config.topYPadding + Config.basalHeight
  1063. let bottomYPadding = Config.bottomYPadding
  1064. let (minValue, maxValue) = minMaxYValues()
  1065. let stepYFraction = (fullSize.height - topYPaddint - bottomYPadding) / CGFloat(maxValue - minValue)
  1066. let yOffset = CGFloat(minValue) * stepYFraction
  1067. let y = fullSize.height - CGFloat(glucoseValue) * stepYFraction + yOffset - bottomYPadding
  1068. return y
  1069. }
  1070. private func timeToInterpolatedPoint(_ time: TimeInterval, fullSize: CGSize) -> CGPoint {
  1071. var nextIndex = 0
  1072. for (index, value) in glucose.enumerated() {
  1073. if value.dateString.timeIntervalSince1970 > time {
  1074. nextIndex = index
  1075. break
  1076. }
  1077. }
  1078. let x = timeToXCoordinate(time, fullSize: fullSize)
  1079. guard nextIndex > 0 else {
  1080. let lastY = glucoseToYCoordinate(glucose.last?.glucose ?? 0, fullSize: fullSize)
  1081. return CGPoint(x: x, y: lastY)
  1082. }
  1083. let prevX = timeToXCoordinate(glucose[nextIndex - 1].dateString.timeIntervalSince1970, fullSize: fullSize)
  1084. let prevY = glucoseToYCoordinate(glucose[nextIndex - 1].glucose ?? 0, fullSize: fullSize)
  1085. let nextX = timeToXCoordinate(glucose[nextIndex].dateString.timeIntervalSince1970, fullSize: fullSize)
  1086. let nextY = glucoseToYCoordinate(glucose[nextIndex].glucose ?? 0, fullSize: fullSize)
  1087. let delta = nextX - prevX
  1088. let fraction = (x - prevX) / delta
  1089. return pointInLine(CGPoint(x: prevX, y: prevY), CGPoint(x: nextX, y: nextY), fraction)
  1090. }
  1091. private func minMaxYValues() -> (min: Int, max: Int) {
  1092. var maxValue = glucose.compactMap(\.glucose).max() ?? Config.maxGlucose
  1093. if let maxPredValue = maxPredValue() {
  1094. maxValue = max(maxValue, maxPredValue)
  1095. }
  1096. if let maxTargetValue = maxTargetValue() {
  1097. maxValue = max(maxValue, maxTargetValue)
  1098. }
  1099. var minValue = glucose.compactMap(\.glucose).min() ?? Config.minGlucose
  1100. if let minPredValue = minPredValue() {
  1101. minValue = min(minValue, minPredValue)
  1102. }
  1103. if let minTargetValue = minTargetValue() {
  1104. minValue = min(minValue, minTargetValue)
  1105. }
  1106. if minValue == maxValue {
  1107. minValue = Config.minGlucose
  1108. maxValue = Config.maxGlucose
  1109. }
  1110. // fix the grah y-axis as long as the min and max BG values are within set borders
  1111. if minValue > Config.minGlucose {
  1112. minValue = Config.minGlucose
  1113. }
  1114. if maxValue < Config.maxGlucose {
  1115. maxValue = Config.maxGlucose
  1116. }
  1117. return (min: minValue, max: maxValue)
  1118. }
  1119. private func getGlucoseYRange(fullSize: CGSize) -> GlucoseYRange {
  1120. let topYPaddint = Config.topYPadding + Config.basalHeight
  1121. let bottomYPadding = Config.bottomYPadding
  1122. let (minValue, maxValue) = minMaxYValues()
  1123. let stepYFraction = (fullSize.height - topYPaddint - bottomYPadding) / CGFloat(maxValue - minValue)
  1124. let yOffset = CGFloat(minValue) * stepYFraction
  1125. let maxY = fullSize.height - CGFloat(minValue) * stepYFraction + yOffset - bottomYPadding
  1126. let minY = fullSize.height - CGFloat(maxValue) * stepYFraction + yOffset - bottomYPadding
  1127. return (minValue: minValue, minY: minY, maxValue: maxValue, maxY: maxY)
  1128. }
  1129. private func firstHourDate() -> Date {
  1130. let firstDate = Date().addingTimeInterval(-1.days.timeInterval)
  1131. return firstDate.dateTruncated(from: .minute)!
  1132. }
  1133. private func firstHourPosition(viewWidth: CGFloat) -> CGFloat {
  1134. let firstDate = Date().addingTimeInterval(-1.days.timeInterval)
  1135. let firstHour = firstHourDate()
  1136. let lastDeltaTime = firstHour.timeIntervalSince(firstDate)
  1137. let oneSecondWidth = oneSecondStep(viewWidth: viewWidth)
  1138. return oneSecondWidth * CGFloat(lastDeltaTime)
  1139. }
  1140. }