MainChartView.swift 48 KB

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