MainChartView.swift 50 KB

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