CarbView.swift 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. import Charts
  2. import Foundation
  3. import SwiftUI
  4. struct CarbView: ChartContent {
  5. let glucoseData: [GlucoseStored]
  6. let units: GlucoseUnits
  7. let carbData: [CarbEntryStored]
  8. let fpuData: [CarbEntryStored]
  9. let minValue: Decimal
  10. var body: some ChartContent {
  11. drawCarbs()
  12. drawFpus()
  13. }
  14. private func drawCarbs() -> some ChartContent {
  15. ForEach(carbData) { carb in
  16. let carbAmount = carb.carbs
  17. let carbDate = carb.date ?? Date()
  18. if let glucose = MainChartHelper.timeToNearestGlucose(
  19. glucoseValues: glucoseData,
  20. time: carbDate.timeIntervalSince1970
  21. )?.glucose {
  22. let yPosition = (units == .mgdL ? Decimal(glucose) : Decimal(glucose).asMmolL) - MainChartHelper
  23. .bolusOffset(units: units)
  24. let size = min(
  25. MainChartHelper.Config.carbsSize + CGFloat(carbAmount) * MainChartHelper.Config.carbsScale,
  26. MainChartHelper.Config.maxCarbSize
  27. )
  28. PointMark(
  29. x: .value("Time", carbDate, unit: .second),
  30. y: .value("Value", yPosition)
  31. )
  32. .symbol {
  33. Image(systemName: "arrowtriangle.down.fill").font(.system(size: size)).foregroundStyle(Color.orange)
  34. .rotationEffect(.degrees(180))
  35. }
  36. .annotation(position: .bottom) {
  37. Text(Formatter.integerFormatter.string(from: carbAmount as NSNumber)!).font(.caption2)
  38. .foregroundStyle(Color.primary)
  39. }
  40. }
  41. }
  42. }
  43. private func drawFpus() -> some ChartContent {
  44. ForEach(fpuData, id: \.id) { fpu in
  45. let fpuAmount = fpu.carbs
  46. let size = (MainChartHelper.Config.fpuSize + CGFloat(fpuAmount) * MainChartHelper.Config.carbsScale) * 1.8
  47. let yPosition = minValue // value is parsed to mmol/L when passed into struct based on user settings
  48. PointMark(
  49. x: .value("Time", fpu.date ?? Date(), unit: .second),
  50. y: .value("Value", yPosition)
  51. )
  52. .symbolSize(size)
  53. .foregroundStyle(Color.brown)
  54. }
  55. }
  56. }