CarbView.swift 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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 = (MainChartHelper.Config.carbsSize + CGFloat(carbAmount) * MainChartHelper.Config.carbsScale)
  25. let limitedSize = size > 30 ? 30 : size
  26. PointMark(
  27. x: .value("Time", carbDate, unit: .second),
  28. y: .value("Value", yPosition)
  29. )
  30. .symbol {
  31. Image(systemName: "arrowtriangle.down.fill").font(.system(size: limitedSize)).foregroundStyle(Color.orange)
  32. .rotationEffect(.degrees(180))
  33. }
  34. .annotation(position: .bottom) {
  35. Text(MainChartHelper.carbsFormatter.string(from: carbAmount as NSNumber)!).font(.caption2)
  36. .foregroundStyle(Color.primary)
  37. }
  38. }
  39. }
  40. }
  41. private func drawFpus() -> some ChartContent {
  42. ForEach(fpuData, id: \.id) { fpu in
  43. let fpuAmount = fpu.carbs
  44. let size = (MainChartHelper.Config.fpuSize + CGFloat(fpuAmount) * MainChartHelper.Config.carbsScale) * 1.8
  45. let yPosition = minValue
  46. PointMark(
  47. x: .value("Time", fpu.date ?? Date(), unit: .second),
  48. y: .value("Value", yPosition)
  49. )
  50. .symbolSize(size)
  51. .foregroundStyle(Color.brown)
  52. }
  53. }
  54. }