MainChartView.swift 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217
  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. private func timeLabelsView(fullSize: CGSize) -> some View {
  314. let format = screenHours > 6 ? date24Formatter : dateFormatter
  315. return ZStack {
  316. // X time labels
  317. ForEach(0 ..< hours + hours) { hour in
  318. Text(format.string(from: firstHourDate().addingTimeInterval(hour.hours.timeInterval)))
  319. .font(.caption)
  320. .position(
  321. x: firstHourPosition(viewWidth: fullSize.width) +
  322. oneSecondStep(viewWidth: fullSize.width) *
  323. CGFloat(hour) * CGFloat(1.hours.timeInterval),
  324. y: 10.0
  325. )
  326. .foregroundColor(.secondary)
  327. }
  328. }.frame(maxHeight: 20)
  329. }
  330. private func glucoseView(fullSize: CGSize) -> some View {
  331. Path { path in
  332. for rect in glucoseDots {
  333. path.addEllipse(in: rect)
  334. }
  335. }
  336. .fill(Color.loopGreen)
  337. .onChange(of: glucose) { _ in
  338. update(fullSize: fullSize)
  339. }
  340. .onChange(of: didAppearTrigger) { _ in
  341. update(fullSize: fullSize)
  342. }
  343. .onReceive(Foundation.NotificationCenter.default.publisher(for: UIApplication.willEnterForegroundNotification)) { _ in
  344. update(fullSize: fullSize)
  345. }
  346. }
  347. private func manualGlucoseView(fullSize: CGSize) -> some View {
  348. Path { path in
  349. for rect in manualGlucoseDots {
  350. path.addEllipse(in: rect)
  351. }
  352. }
  353. .fill(Color.gray)
  354. .onChange(of: isManual) { _ in
  355. update(fullSize: fullSize)
  356. }
  357. .onChange(of: didAppearTrigger) { _ in
  358. update(fullSize: fullSize)
  359. }
  360. .onReceive(Foundation.NotificationCenter.default.publisher(for: UIApplication.willEnterForegroundNotification)) { _ in
  361. update(fullSize: fullSize)
  362. }
  363. }
  364. private func announcementView(fullSize: CGSize) -> some View {
  365. ZStack {
  366. ForEach(announcementDots, id: \.rect.minX) { info -> AnyView in
  367. let position = CGPoint(x: info.rect.midX + 5, y: info.rect.maxY - Config.owlOffset)
  368. let type: String =
  369. info.note.contains("true") ?
  370. Command.open :
  371. info.note.contains("false") ?
  372. Command.closed :
  373. info.note.contains("suspend") ?
  374. Command.suspend :
  375. info.note.contains("resume") ?
  376. Command.resume :
  377. info.note.contains("tempbasal") ?
  378. Command.tempbasal : Command.bolus
  379. VStack {
  380. Text(type).font(.caption2).foregroundStyle(.orange)
  381. Image("owl").resizable().frame(maxWidth: Config.owlSeize, maxHeight: Config.owlSeize).scaledToFill()
  382. }.position(position).asAny()
  383. }
  384. }
  385. .onChange(of: announcement) { _ in
  386. calculateAnnouncementDots(fullSize: fullSize)
  387. }
  388. .onChange(of: didAppearTrigger) { _ in
  389. calculateAnnouncementDots(fullSize: fullSize)
  390. }
  391. }
  392. private func manualGlucoseCenterView(fullSize: CGSize) -> some View {
  393. Path { path in
  394. for rect in manualGlucoseDotsCenter {
  395. path.addEllipse(in: rect)
  396. }
  397. }
  398. .fill(Color.red)
  399. .onChange(of: isManual) { _ in
  400. update(fullSize: fullSize)
  401. }
  402. .onChange(of: didAppearTrigger) { _ in
  403. update(fullSize: fullSize)
  404. }
  405. .onReceive(
  406. Foundation.NotificationCenter.default
  407. .publisher(for: UIApplication.willEnterForegroundNotification)
  408. ) { _ in
  409. update(fullSize: fullSize)
  410. }
  411. }
  412. private func unSmoothedGlucoseView(fullSize: CGSize) -> some View {
  413. Path { path in
  414. var lines: [CGPoint] = []
  415. for rect in unSmoothedGlucoseDots {
  416. lines.append(CGPoint(x: rect.midX, y: rect.midY))
  417. path.addEllipse(in: rect)
  418. }
  419. path.addLines(lines)
  420. }
  421. .stroke(Color.loopGray, lineWidth: 0.5)
  422. .onChange(of: glucose) { _ in
  423. update(fullSize: fullSize)
  424. }
  425. .onChange(of: didAppearTrigger) { _ in
  426. update(fullSize: fullSize)
  427. }
  428. .onReceive(Foundation.NotificationCenter.default.publisher(for: UIApplication.willEnterForegroundNotification)) { _ in
  429. update(fullSize: fullSize)
  430. }
  431. }
  432. private func bolusView(fullSize: CGSize) -> some View {
  433. ZStack {
  434. bolusPath
  435. .fill(Color.insulin)
  436. bolusPath
  437. .stroke(Color.primary, lineWidth: 0.5)
  438. ForEach(bolusDots, id: \.rect.minX) { info -> AnyView in
  439. let position = CGPoint(x: info.rect.midX, y: info.rect.maxY + 8)
  440. return Text(bolusFormatter.string(from: info.value as NSNumber)!).font(.caption2)
  441. .position(position)
  442. .asAny()
  443. }
  444. }
  445. .onChange(of: boluses) { _ in
  446. calculateBolusDots(fullSize: fullSize)
  447. }
  448. .onChange(of: didAppearTrigger) { _ in
  449. calculateBolusDots(fullSize: fullSize)
  450. }
  451. }
  452. private func carbsView(fullSize: CGSize) -> some View {
  453. ZStack {
  454. carbsPath
  455. .fill(Color.loopYellow)
  456. carbsPath
  457. .stroke(Color.primary, lineWidth: 0.5)
  458. ForEach(carbsDots, id: \.rect.minX) { info -> AnyView in
  459. let position = CGPoint(x: info.rect.midX, y: info.rect.minY - 8)
  460. return Text(carbsFormatter.string(from: info.value as NSNumber)!).font(.caption2)
  461. .position(position)
  462. .asAny()
  463. }
  464. }
  465. .onChange(of: carbs) { _ in
  466. calculateCarbsDots(fullSize: fullSize)
  467. }
  468. .onChange(of: didAppearTrigger) { _ in
  469. calculateCarbsDots(fullSize: fullSize)
  470. }
  471. }
  472. private func fpuView(fullSize: CGSize) -> some View {
  473. ZStack {
  474. fpuPath
  475. .fill(.orange.opacity(0.5))
  476. fpuPath
  477. .stroke(Color.primary, lineWidth: 0.2)
  478. }
  479. .onChange(of: carbs) { _ in
  480. calculateFPUsDots(fullSize: fullSize)
  481. }
  482. .onChange(of: didAppearTrigger) { _ in
  483. calculateFPUsDots(fullSize: fullSize)
  484. }
  485. }
  486. private func tempTargetsView(fullSize: CGSize) -> some View {
  487. ZStack {
  488. tempTargetsPath
  489. .fill(Color.tempBasal.opacity(0.5))
  490. tempTargetsPath
  491. .stroke(Color.basal.opacity(0.5), lineWidth: 1)
  492. }
  493. .onChange(of: glucose) { _ in
  494. calculateTempTargetsRects(fullSize: fullSize)
  495. }
  496. .onChange(of: tempTargets) { _ in
  497. calculateTempTargetsRects(fullSize: fullSize)
  498. }
  499. .onChange(of: didAppearTrigger) { _ in
  500. calculateTempTargetsRects(fullSize: fullSize)
  501. }
  502. }
  503. private func predictionsView(fullSize: CGSize) -> some View {
  504. Group {
  505. Path { path in
  506. for rect in predictionDots[.iob] ?? [] {
  507. path.addEllipse(in: rect)
  508. }
  509. }.fill(Color.insulin)
  510. Path { path in
  511. for rect in predictionDots[.cob] ?? [] {
  512. path.addEllipse(in: rect)
  513. }
  514. }.fill(Color.loopYellow)
  515. Path { path in
  516. for rect in predictionDots[.zt] ?? [] {
  517. path.addEllipse(in: rect)
  518. }
  519. }.fill(Color.zt)
  520. Path { path in
  521. for rect in predictionDots[.uam] ?? [] {
  522. path.addEllipse(in: rect)
  523. }
  524. }.fill(Color.uam)
  525. }
  526. .onChange(of: suggestion) { _ in
  527. update(fullSize: fullSize)
  528. }
  529. }
  530. }
  531. // MARK: - Calculations
  532. extension MainChartView {
  533. private func update(fullSize: CGSize) {
  534. calculatePredictionDots(fullSize: fullSize, type: .iob)
  535. calculatePredictionDots(fullSize: fullSize, type: .cob)
  536. calculatePredictionDots(fullSize: fullSize, type: .zt)
  537. calculatePredictionDots(fullSize: fullSize, type: .uam)
  538. calculateGlucoseDots(fullSize: fullSize)
  539. calculateManualGlucoseDots(fullSize: fullSize)
  540. calculateManualGlucoseDotsCenter(fullSize: fullSize)
  541. calculateAnnouncementDots(fullSize: fullSize)
  542. calculateUnSmoothedGlucoseDots(fullSize: fullSize)
  543. calculateBolusDots(fullSize: fullSize)
  544. calculateCarbsDots(fullSize: fullSize)
  545. calculateFPUsDots(fullSize: fullSize)
  546. calculateTempTargetsRects(fullSize: fullSize)
  547. calculateBasalPoints(fullSize: fullSize)
  548. calculateSuspensions(fullSize: fullSize)
  549. }
  550. private func calculateGlucoseDots(fullSize: CGSize) {
  551. calculationQueue.async {
  552. let dots = glucose.concurrentMap { value -> CGRect in
  553. let position = glucoseToCoordinate(value, fullSize: fullSize)
  554. return CGRect(x: position.x - 2, y: position.y - 2, width: 4, height: 4)
  555. }
  556. let range = self.getGlucoseYRange(fullSize: fullSize)
  557. DispatchQueue.main.async {
  558. glucoseYRange = range
  559. glucoseDots = dots
  560. }
  561. }
  562. }
  563. private func calculateManualGlucoseDots(fullSize: CGSize) {
  564. calculationQueue.async {
  565. let dots = isManual.concurrentMap { value -> CGRect in
  566. let position = glucoseToCoordinate(value, fullSize: fullSize)
  567. return CGRect(x: position.x - 2, y: position.y - 2, width: 14, height: 14)
  568. }
  569. let range = self.getGlucoseYRange(fullSize: fullSize)
  570. DispatchQueue.main.async {
  571. glucoseYRange = range
  572. manualGlucoseDots = dots
  573. }
  574. }
  575. }
  576. private func calculateManualGlucoseDotsCenter(fullSize: CGSize) {
  577. calculationQueue.async {
  578. let dots = isManual.concurrentMap { value -> CGRect in
  579. let position = glucoseToCoordinate(value, fullSize: fullSize)
  580. return CGRect(x: position.x, y: position.y, width: 10, height: 10)
  581. }
  582. let range = self.getGlucoseYRange(fullSize: fullSize)
  583. DispatchQueue.main.async {
  584. glucoseYRange = range
  585. manualGlucoseDotsCenter = dots
  586. }
  587. }
  588. }
  589. private func calculateAnnouncementDots(fullSize: CGSize) {
  590. calculationQueue.async {
  591. let dots = announcement.map { value -> AnnouncementDot in
  592. let center = timeToInterpolatedPoint(value.createdAt.timeIntervalSince1970, fullSize: fullSize)
  593. let size = Config.announcementSize * Config.announcementScale
  594. let rect = CGRect(x: center.x - size / 2, y: center.y - size / 2, width: size, height: size)
  595. let note = value.notes
  596. return AnnouncementDot(rect: rect, value: 10, note: note)
  597. }
  598. let path = Path { path in
  599. for dot in dots {
  600. path.addEllipse(in: dot.rect)
  601. }
  602. }
  603. let range = self.getGlucoseYRange(fullSize: fullSize)
  604. DispatchQueue.main.async {
  605. glucoseYRange = range
  606. announcementDots = dots
  607. announcementPath = path
  608. }
  609. }
  610. }
  611. private func calculateUnSmoothedGlucoseDots(fullSize: CGSize) {
  612. calculationQueue.async {
  613. let dots = glucose.concurrentMap { value -> CGRect in
  614. let position = UnSmoothedGlucoseToCoordinate(value, fullSize: fullSize)
  615. return CGRect(x: position.x - 2, y: position.y - 2, width: 4, height: 4)
  616. }
  617. let range = self.getGlucoseYRange(fullSize: fullSize)
  618. DispatchQueue.main.async {
  619. glucoseYRange = range
  620. unSmoothedGlucoseDots = dots
  621. }
  622. }
  623. }
  624. private func calculateBolusDots(fullSize: CGSize) {
  625. calculationQueue.async {
  626. let dots = boluses.map { value -> DotInfo in
  627. let center = timeToInterpolatedPoint(value.timestamp.timeIntervalSince1970, fullSize: fullSize)
  628. let size = Config.bolusSize + CGFloat(value.amount ?? 0) * Config.bolusScale
  629. let rect = CGRect(x: center.x - size / 2, y: center.y - size / 2, width: size, height: size)
  630. return DotInfo(rect: rect, value: value.amount ?? 0)
  631. }
  632. let path = Path { path in
  633. for dot in dots {
  634. path.addEllipse(in: dot.rect)
  635. }
  636. }
  637. DispatchQueue.main.async {
  638. bolusDots = dots
  639. bolusPath = path
  640. }
  641. }
  642. }
  643. private func calculateCarbsDots(fullSize: CGSize) {
  644. calculationQueue.async {
  645. let realCarbs = carbs.filter { !($0.isFPU ?? false) }
  646. let dots = realCarbs.map { value -> DotInfo in
  647. let center = timeToInterpolatedPoint(value.createdAt.timeIntervalSince1970, fullSize: fullSize)
  648. let size = Config.carbsSize + CGFloat(value.carbs) * Config.carbsScale
  649. let rect = CGRect(x: center.x - size / 2, y: center.y - size / 2, width: size, height: size)
  650. return DotInfo(rect: rect, value: value.carbs)
  651. }
  652. let path = Path { path in
  653. for dot in dots {
  654. path.addEllipse(in: dot.rect)
  655. }
  656. }
  657. DispatchQueue.main.async {
  658. carbsDots = dots
  659. carbsPath = path
  660. }
  661. }
  662. }
  663. private func calculateFPUsDots(fullSize: CGSize) {
  664. calculationQueue.async {
  665. let fpus = carbs.filter { $0.isFPU ?? false }
  666. let dots = fpus.map { value -> DotInfo in
  667. let center = timeToInterpolatedPoint(value.createdAt.timeIntervalSince1970, fullSize: fullSize)
  668. let size = Config.fpuSize + CGFloat(value.carbs) * Config.fpuScale
  669. let rect = CGRect(x: center.x - size / 2, y: center.y - size / 2, width: size, height: size)
  670. return DotInfo(rect: rect, value: value.carbs)
  671. }
  672. let path = Path { path in
  673. for dot in dots {
  674. path.addEllipse(in: dot.rect)
  675. }
  676. }
  677. DispatchQueue.main.async {
  678. fpuDots = dots
  679. fpuPath = path
  680. }
  681. }
  682. }
  683. private func calculatePredictionDots(fullSize: CGSize, type: PredictionType) {
  684. calculationQueue.async {
  685. let values: [Int] = { () -> [Int] in
  686. switch type {
  687. case .iob:
  688. return suggestion?.predictions?.iob ?? []
  689. case .cob:
  690. return suggestion?.predictions?.cob ?? []
  691. case .zt:
  692. return suggestion?.predictions?.zt ?? []
  693. case .uam:
  694. return suggestion?.predictions?.uam ?? []
  695. }
  696. }()
  697. var index = 0
  698. let dots = values.map { value -> CGRect in
  699. let position = predictionToCoordinate(value, fullSize: fullSize, index: index)
  700. index += 1
  701. return CGRect(x: position.x - 2, y: position.y - 2, width: 4, height: 4)
  702. }
  703. DispatchQueue.main.async {
  704. predictionDots[type] = dots
  705. }
  706. }
  707. }
  708. private func calculateBasalPoints(fullSize: CGSize) {
  709. calculationQueue.async {
  710. self.cachedMaxBasalRate = nil
  711. let dayAgoTime = Date().addingTimeInterval(-1.days.timeInterval).timeIntervalSince1970
  712. let firstTempTime = (tempBasals.first?.timestamp ?? Date()).timeIntervalSince1970
  713. var lastTimeEnd = firstTempTime
  714. let firstRegularBasalPoints = findRegularBasalPoints(
  715. timeBegin: dayAgoTime,
  716. timeEnd: firstTempTime,
  717. fullSize: fullSize,
  718. autotuned: false
  719. )
  720. let tempBasalPoints = firstRegularBasalPoints + tempBasals.chunks(ofCount: 2).map { chunk -> [CGPoint] in
  721. let chunk = Array(chunk)
  722. guard chunk.count == 2, chunk[0].type == .tempBasal, chunk[1].type == .tempBasalDuration else { return [] }
  723. let timeBegin = chunk[0].timestamp.timeIntervalSince1970
  724. let timeEnd = timeBegin + (chunk[1].durationMin ?? 0).minutes.timeInterval
  725. let rateCost = Config.basalHeight / CGFloat(maxBasalRate())
  726. let x0 = timeToXCoordinate(timeBegin, fullSize: fullSize)
  727. let y0 = Config.basalHeight - CGFloat(chunk[0].rate ?? 0) * rateCost
  728. let regularPoints = findRegularBasalPoints(
  729. timeBegin: lastTimeEnd,
  730. timeEnd: timeBegin,
  731. fullSize: fullSize,
  732. autotuned: false
  733. )
  734. lastTimeEnd = timeEnd
  735. return regularPoints + [CGPoint(x: x0, y: y0)]
  736. }.flatMap { $0 }
  737. let tempBasalPath = Path { path in
  738. var yPoint: CGFloat = Config.basalHeight
  739. path.move(to: CGPoint(x: 0, y: yPoint))
  740. for point in tempBasalPoints {
  741. path.addLine(to: CGPoint(x: point.x, y: yPoint))
  742. path.addLine(to: point)
  743. yPoint = point.y
  744. }
  745. let lastPoint = lastBasalPoint(fullSize: fullSize)
  746. path.addLine(to: CGPoint(x: lastPoint.x, y: yPoint))
  747. path.addLine(to: CGPoint(x: lastPoint.x, y: Config.basalHeight))
  748. path.addLine(to: CGPoint(x: 0, y: Config.basalHeight))
  749. }
  750. let adjustForOptionalExtraHours = screenHours > 12 ? screenHours - 12 : 0
  751. let endDateTime = dayAgoTime + min(max(screenHours - adjustForOptionalExtraHours, 12), 24).hours
  752. .timeInterval + min(max(screenHours - adjustForOptionalExtraHours, 12), 24).hours
  753. .timeInterval
  754. let autotunedBasalPoints = findRegularBasalPoints(
  755. timeBegin: dayAgoTime,
  756. timeEnd: endDateTime,
  757. fullSize: fullSize,
  758. autotuned: true
  759. )
  760. let autotunedBasalPath = Path { path in
  761. var yPoint: CGFloat = Config.basalHeight
  762. path.move(to: CGPoint(x: -50, y: yPoint))
  763. for point in autotunedBasalPoints {
  764. path.addLine(to: CGPoint(x: point.x, y: yPoint))
  765. path.addLine(to: point)
  766. yPoint = point.y
  767. }
  768. path.addLine(to: CGPoint(x: timeToXCoordinate(endDateTime, fullSize: fullSize), y: yPoint))
  769. }
  770. DispatchQueue.main.async {
  771. self.tempBasalPath = tempBasalPath
  772. self.regularBasalPath = autotunedBasalPath
  773. }
  774. }
  775. }
  776. private func calculateSuspensions(fullSize: CGSize) {
  777. calculationQueue.async {
  778. var rects = suspensions.windows(ofCount: 2).map { window -> CGRect? in
  779. let window = Array(window)
  780. guard window[0].type == .pumpSuspend, window[1].type == .pumpResume else { return nil }
  781. let x0 = self.timeToXCoordinate(window[0].timestamp.timeIntervalSince1970, fullSize: fullSize)
  782. let x1 = self.timeToXCoordinate(window[1].timestamp.timeIntervalSince1970, fullSize: fullSize)
  783. return CGRect(x: x0, y: 0, width: x1 - x0, height: Config.basalHeight * 0.7)
  784. }
  785. let firstRec = self.suspensions.first.flatMap { event -> CGRect? in
  786. guard event.type == .pumpResume else { return nil }
  787. let tbrTime = self.tempBasals.last { $0.timestamp < event.timestamp }
  788. .map { $0.timestamp.timeIntervalSince1970 + TimeInterval($0.durationMin ?? 0) * 60 } ?? Date()
  789. .addingTimeInterval(-1.days.timeInterval).timeIntervalSince1970
  790. let x0 = self.timeToXCoordinate(tbrTime, fullSize: fullSize)
  791. let x1 = self.timeToXCoordinate(event.timestamp.timeIntervalSince1970, fullSize: fullSize)
  792. return CGRect(
  793. x: x0,
  794. y: 0,
  795. width: x1 - x0,
  796. height: Config.basalHeight * 0.7
  797. )
  798. }
  799. let lastRec = self.suspensions.last.flatMap { event -> CGRect? in
  800. guard event.type == .pumpSuspend else { return nil }
  801. let tbrTimeX = self.tempBasals.first { $0.timestamp > event.timestamp }
  802. .map { self.timeToXCoordinate($0.timestamp.timeIntervalSince1970, fullSize: fullSize) }
  803. let x0 = self.timeToXCoordinate(event.timestamp.timeIntervalSince1970, fullSize: fullSize)
  804. let x1 = tbrTimeX ?? self.fullGlucoseWidth(viewWidth: fullSize.width) + self
  805. .additionalWidth(viewWidth: fullSize.width)
  806. return CGRect(x: x0, y: 0, width: x1 - x0, height: Config.basalHeight * 0.7)
  807. }
  808. rects.append(firstRec)
  809. rects.append(lastRec)
  810. let path = Path { path in
  811. path.addRects(rects.compactMap { $0 })
  812. }
  813. DispatchQueue.main.async {
  814. suspensionsPath = path
  815. }
  816. }
  817. }
  818. private func maxBasalRate() -> Decimal {
  819. if let cached = cachedMaxBasalRate {
  820. return cached
  821. }
  822. let maxRegularBasalRate = max(
  823. basalProfile.map(\.rate).max() ?? maxBasal,
  824. autotunedBasalProfile.map(\.rate).max() ?? maxBasal
  825. )
  826. var maxTempBasalRate = tempBasals.compactMap(\.rate).max() ?? maxRegularBasalRate
  827. if maxTempBasalRate == 0 {
  828. maxTempBasalRate = maxRegularBasalRate
  829. }
  830. cachedMaxBasalRate = max(maxTempBasalRate, maxRegularBasalRate)
  831. return cachedMaxBasalRate ?? maxBasal
  832. }
  833. private func calculateTempTargetsRects(fullSize: CGSize) {
  834. calculationQueue.async {
  835. var rects = tempTargets.map { tempTarget -> CGRect in
  836. let x0 = timeToXCoordinate(tempTarget.createdAt.timeIntervalSince1970, fullSize: fullSize)
  837. let y0 = glucoseToYCoordinate(Int(tempTarget.targetTop ?? 0), fullSize: fullSize)
  838. let x1 = timeToXCoordinate(
  839. tempTarget.createdAt.timeIntervalSince1970 + Int(tempTarget.duration).minutes.timeInterval,
  840. fullSize: fullSize
  841. )
  842. let y1 = glucoseToYCoordinate(Int(tempTarget.targetBottom ?? 0), fullSize: fullSize)
  843. return CGRect(
  844. x: x0,
  845. y: y0 - 3,
  846. width: x1 - x0,
  847. height: y1 - y0 + 6
  848. )
  849. }
  850. if rects.count > 1 {
  851. rects = rects.reduce([]) { result, rect -> [CGRect] in
  852. guard var last = result.last else { return [rect] }
  853. if last.origin.x + last.width > rect.origin.x {
  854. last.size.width = rect.origin.x - last.origin.x
  855. }
  856. var res = Array(result.dropLast())
  857. res.append(contentsOf: [last, rect])
  858. return res
  859. }
  860. }
  861. let path = Path { path in
  862. path.addRects(rects)
  863. }
  864. DispatchQueue.main.async {
  865. tempTargetsPath = path
  866. }
  867. }
  868. }
  869. private func findRegularBasalPoints(
  870. timeBegin: TimeInterval,
  871. timeEnd: TimeInterval,
  872. fullSize: CGSize,
  873. autotuned: Bool
  874. ) -> [CGPoint] {
  875. guard timeBegin < timeEnd else {
  876. return []
  877. }
  878. let beginDate = Date(timeIntervalSince1970: timeBegin)
  879. let calendar = Calendar.current
  880. let startOfDay = calendar.startOfDay(for: beginDate)
  881. let profile = autotuned ? autotunedBasalProfile : basalProfile
  882. let basalNormalized = profile.map {
  883. (
  884. time: startOfDay.addingTimeInterval($0.minutes.minutes.timeInterval).timeIntervalSince1970,
  885. rate: $0.rate
  886. )
  887. } + profile.map {
  888. (
  889. time: startOfDay.addingTimeInterval($0.minutes.minutes.timeInterval + 1.days.timeInterval).timeIntervalSince1970,
  890. rate: $0.rate
  891. )
  892. } + profile.map {
  893. (
  894. time: startOfDay.addingTimeInterval($0.minutes.minutes.timeInterval + 2.days.timeInterval).timeIntervalSince1970,
  895. rate: $0.rate
  896. )
  897. }
  898. let basalTruncatedPoints = basalNormalized.windows(ofCount: 2)
  899. .compactMap { window -> CGPoint? in
  900. let window = Array(window)
  901. if window[0].time < timeBegin, window[1].time < timeBegin {
  902. return nil
  903. }
  904. let rateCost = Config.basalHeight / CGFloat(maxBasalRate())
  905. if window[0].time < timeBegin, window[1].time >= timeBegin {
  906. let x = timeToXCoordinate(timeBegin, fullSize: fullSize)
  907. let y = Config.basalHeight - CGFloat(window[0].rate) * rateCost
  908. return CGPoint(x: x, y: y)
  909. }
  910. if window[0].time >= timeBegin, window[0].time < timeEnd {
  911. let x = timeToXCoordinate(window[0].time, fullSize: fullSize)
  912. let y = Config.basalHeight - CGFloat(window[0].rate) * rateCost
  913. return CGPoint(x: x, y: y)
  914. }
  915. return nil
  916. }
  917. return basalTruncatedPoints
  918. }
  919. private func lastBasalPoint(fullSize: CGSize) -> CGPoint {
  920. let lastBasal = Array(tempBasals.suffix(2))
  921. guard lastBasal.count == 2 else {
  922. return CGPoint(x: timeToXCoordinate(Date().timeIntervalSince1970, fullSize: fullSize), y: Config.basalHeight)
  923. }
  924. let endBasalTime = lastBasal[0].timestamp.timeIntervalSince1970 + (lastBasal[1].durationMin?.minutes.timeInterval ?? 0)
  925. let rateCost = Config.basalHeight / CGFloat(maxBasalRate())
  926. let x = timeToXCoordinate(endBasalTime, fullSize: fullSize)
  927. let y = Config.basalHeight - CGFloat(lastBasal[0].rate ?? 0) * rateCost
  928. return CGPoint(x: x, y: y)
  929. }
  930. private func fullGlucoseWidth(viewWidth: CGFloat) -> CGFloat {
  931. viewWidth * CGFloat(hours) / CGFloat(min(max(screenHours, 2), 24))
  932. }
  933. private func additionalWidth(viewWidth: CGFloat) -> CGFloat {
  934. guard let predictions = suggestion?.predictions,
  935. let deliveredAt = suggestion?.deliverAt,
  936. let last = glucose.last
  937. else {
  938. return Config.minAdditionalWidth
  939. }
  940. let iob = predictions.iob?.count ?? 0
  941. let zt = predictions.zt?.count ?? 0
  942. let cob = predictions.cob?.count ?? 0
  943. let uam = predictions.uam?.count ?? 0
  944. let max = [iob, zt, cob, uam].max() ?? 0
  945. let lastDeltaTime = last.dateString.timeIntervalSince(deliveredAt)
  946. let additionalTime = CGFloat(TimeInterval(max) * 5.minutes.timeInterval - lastDeltaTime)
  947. let oneSecondWidth = oneSecondStep(viewWidth: viewWidth)
  948. return Swift.min(Swift.max(additionalTime * oneSecondWidth, Config.minAdditionalWidth), 275)
  949. }
  950. private func oneSecondStep(viewWidth: CGFloat) -> CGFloat {
  951. viewWidth / (CGFloat(min(max(screenHours, 2), 24)) * CGFloat(1.hours.timeInterval))
  952. }
  953. private func maxPredValue() -> Int? {
  954. [
  955. suggestion?.predictions?.cob ?? [],
  956. suggestion?.predictions?.iob ?? [],
  957. suggestion?.predictions?.zt ?? [],
  958. suggestion?.predictions?.uam ?? []
  959. ]
  960. .flatMap { $0 }
  961. .max()
  962. }
  963. private func minPredValue() -> Int? {
  964. [
  965. suggestion?.predictions?.cob ?? [],
  966. suggestion?.predictions?.iob ?? [],
  967. suggestion?.predictions?.zt ?? [],
  968. suggestion?.predictions?.uam ?? []
  969. ]
  970. .flatMap { $0 }
  971. .min()
  972. }
  973. private func maxTargetValue() -> Int? {
  974. tempTargets.map { $0.targetTop ?? 0 }.filter { $0 > 0 }.max().map(Int.init)
  975. }
  976. private func minTargetValue() -> Int? {
  977. tempTargets.map { $0.targetBottom ?? 0 }.filter { $0 > 0 }.min().map(Int.init)
  978. }
  979. private func glucoseToCoordinate(_ glucoseEntry: BloodGlucose, fullSize: CGSize) -> CGPoint {
  980. let x = timeToXCoordinate(glucoseEntry.dateString.timeIntervalSince1970, fullSize: fullSize)
  981. let y = glucoseToYCoordinate(glucoseEntry.glucose ?? 0, fullSize: fullSize)
  982. return CGPoint(x: x, y: y)
  983. }
  984. private func UnSmoothedGlucoseToCoordinate(_ glucoseEntry: BloodGlucose, fullSize: CGSize) -> CGPoint {
  985. let x = timeToXCoordinate(glucoseEntry.dateString.timeIntervalSince1970, fullSize: fullSize)
  986. let glucoseValue: Decimal = glucoseEntry.unfiltered ?? Decimal(glucoseEntry.glucose ?? 0)
  987. let y = glucoseToYCoordinate(Int(glucoseValue), fullSize: fullSize)
  988. return CGPoint(x: x, y: y)
  989. }
  990. private func predictionToCoordinate(_ pred: Int, fullSize: CGSize, index: Int) -> CGPoint {
  991. guard let deliveredAt = suggestion?.deliverAt else {
  992. return .zero
  993. }
  994. let predTime = deliveredAt.timeIntervalSince1970 + TimeInterval(index) * 5.minutes.timeInterval
  995. let x = timeToXCoordinate(predTime, fullSize: fullSize)
  996. let y = glucoseToYCoordinate(pred, fullSize: fullSize)
  997. return CGPoint(x: x, y: y)
  998. }
  999. private func timeToXCoordinate(_ time: TimeInterval, fullSize: CGSize) -> CGFloat {
  1000. let xOffset = -Date().addingTimeInterval(-1.days.timeInterval).timeIntervalSince1970
  1001. let stepXFraction = fullGlucoseWidth(viewWidth: fullSize.width) / CGFloat(hours.hours.timeInterval)
  1002. let x = CGFloat(time + xOffset) * stepXFraction
  1003. return x
  1004. }
  1005. private func glucoseToYCoordinate(_ glucoseValue: Int, fullSize: CGSize) -> CGFloat {
  1006. let topYPaddint = Config.topYPadding + Config.basalHeight
  1007. let bottomYPadding = Config.bottomYPadding
  1008. let (minValue, maxValue) = minMaxYValues()
  1009. let stepYFraction = (fullSize.height - topYPaddint - bottomYPadding) / CGFloat(maxValue - minValue)
  1010. let yOffset = CGFloat(minValue) * stepYFraction
  1011. let y = fullSize.height - CGFloat(glucoseValue) * stepYFraction + yOffset - bottomYPadding
  1012. return y
  1013. }
  1014. private func timeToInterpolatedPoint(_ time: TimeInterval, fullSize: CGSize) -> CGPoint {
  1015. var nextIndex = 0
  1016. for (index, value) in glucose.enumerated() {
  1017. if value.dateString.timeIntervalSince1970 > time {
  1018. nextIndex = index
  1019. break
  1020. }
  1021. }
  1022. let x = timeToXCoordinate(time, fullSize: fullSize)
  1023. guard nextIndex > 0 else {
  1024. let lastY = glucoseToYCoordinate(glucose.last?.glucose ?? 0, fullSize: fullSize)
  1025. return CGPoint(x: x, y: lastY)
  1026. }
  1027. let prevX = timeToXCoordinate(glucose[nextIndex - 1].dateString.timeIntervalSince1970, fullSize: fullSize)
  1028. let prevY = glucoseToYCoordinate(glucose[nextIndex - 1].glucose ?? 0, fullSize: fullSize)
  1029. let nextX = timeToXCoordinate(glucose[nextIndex].dateString.timeIntervalSince1970, fullSize: fullSize)
  1030. let nextY = glucoseToYCoordinate(glucose[nextIndex].glucose ?? 0, fullSize: fullSize)
  1031. let delta = nextX - prevX
  1032. let fraction = (x - prevX) / delta
  1033. return pointInLine(CGPoint(x: prevX, y: prevY), CGPoint(x: nextX, y: nextY), fraction)
  1034. }
  1035. private func minMaxYValues() -> (min: Int, max: Int) {
  1036. var maxValue = glucose.compactMap(\.glucose).max() ?? Config.maxGlucose
  1037. if let maxPredValue = maxPredValue() {
  1038. maxValue = max(maxValue, maxPredValue)
  1039. }
  1040. if let maxTargetValue = maxTargetValue() {
  1041. maxValue = max(maxValue, maxTargetValue)
  1042. }
  1043. var minValue = glucose.compactMap(\.glucose).min() ?? Config.minGlucose
  1044. if let minPredValue = minPredValue() {
  1045. minValue = min(minValue, minPredValue)
  1046. }
  1047. if let minTargetValue = minTargetValue() {
  1048. minValue = min(minValue, minTargetValue)
  1049. }
  1050. if minValue == maxValue {
  1051. minValue = Config.minGlucose
  1052. maxValue = Config.maxGlucose
  1053. }
  1054. // fix the grah y-axis as long as the min and max BG values are within set borders
  1055. if minValue > Config.minGlucose {
  1056. minValue = Config.minGlucose
  1057. }
  1058. if maxValue < Config.maxGlucose {
  1059. maxValue = Config.maxGlucose
  1060. }
  1061. return (min: minValue, max: maxValue)
  1062. }
  1063. private func getGlucoseYRange(fullSize: CGSize) -> GlucoseYRange {
  1064. let topYPaddint = Config.topYPadding + Config.basalHeight
  1065. let bottomYPadding = Config.bottomYPadding
  1066. let (minValue, maxValue) = minMaxYValues()
  1067. let stepYFraction = (fullSize.height - topYPaddint - bottomYPadding) / CGFloat(maxValue - minValue)
  1068. let yOffset = CGFloat(minValue) * stepYFraction
  1069. let maxY = fullSize.height - CGFloat(minValue) * stepYFraction + yOffset - bottomYPadding
  1070. let minY = fullSize.height - CGFloat(maxValue) * stepYFraction + yOffset - bottomYPadding
  1071. return (minValue: minValue, minY: minY, maxValue: maxValue, maxY: maxY)
  1072. }
  1073. private func firstHourDate() -> Date {
  1074. let firstDate = Date().addingTimeInterval(-1.days.timeInterval)
  1075. return firstDate.dateTruncated(from: .minute)!
  1076. }
  1077. private func firstHourPosition(viewWidth: CGFloat) -> CGFloat {
  1078. let firstDate = Date().addingTimeInterval(-1.days.timeInterval)
  1079. let firstHour = firstHourDate()
  1080. let lastDeltaTime = firstHour.timeIntervalSince(firstDate)
  1081. let oneSecondWidth = oneSecondStep(viewWidth: viewWidth)
  1082. return oneSecondWidth * CGFloat(lastDeltaTime)
  1083. }
  1084. }