CurrentGlucoseView.swift 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. import SwiftUI
  2. struct CurrentGlucoseView: View {
  3. @Binding var recentGlucose: BloodGlucose?
  4. @Binding var delta: Int?
  5. @Binding var units: GlucoseUnits
  6. @Binding var alarm: GlucoseAlarm?
  7. private var glucoseFormatter: NumberFormatter {
  8. let formatter = NumberFormatter()
  9. formatter.numberStyle = .decimal
  10. formatter.maximumFractionDigits = 0
  11. if units == .mmolL {
  12. formatter.minimumFractionDigits = 1
  13. formatter.maximumFractionDigits = 1
  14. }
  15. formatter.roundingMode = .halfUp
  16. return formatter
  17. }
  18. private var deltaFormatter: NumberFormatter {
  19. let formatter = NumberFormatter()
  20. formatter.numberStyle = .decimal
  21. formatter.maximumFractionDigits = 2
  22. formatter.positivePrefix = " +"
  23. formatter.negativePrefix = " -"
  24. return formatter
  25. }
  26. private var dateFormatter: DateFormatter {
  27. let formatter = DateFormatter()
  28. formatter.timeStyle = .short
  29. return formatter
  30. }
  31. var body: some View {
  32. VStack(alignment: .center, spacing: 6) {
  33. HStack(spacing: 8) {
  34. Text(
  35. recentGlucose?.glucose
  36. .map {
  37. glucoseFormatter
  38. .string(from: Double(units == .mmolL ? $0.asMmolL : Decimal($0)) as NSNumber)! }
  39. ?? "--"
  40. )
  41. .font(.system(size: 24, weight: .bold))
  42. .fixedSize()
  43. .foregroundColor(alarm == nil ? .primary : .loopRed)
  44. image.padding(.bottom, 2)
  45. }.padding(.leading, 4)
  46. HStack(alignment: .lastTextBaseline, spacing: 2) {
  47. Text(
  48. recentGlucose.map { dateFormatter.string(from: $0.dateString) } ?? "--"
  49. ).font(.caption2).foregroundColor(.secondary)
  50. Text(
  51. delta
  52. .map { deltaFormatter.string(from: Double(units == .mmolL ? $0.asMmolL : Decimal($0)) as NSNumber)!
  53. } ??
  54. "--"
  55. ).font(.system(size: 12, weight: .bold))
  56. }
  57. }
  58. }
  59. var image: Image {
  60. guard let direction = recentGlucose?.direction else {
  61. return Image(systemName: "arrow.left.and.right")
  62. }
  63. switch direction {
  64. case .doubleUp,
  65. .singleUp,
  66. .tripleUp:
  67. return Image(systemName: "arrow.up")
  68. case .fortyFiveUp:
  69. return Image(systemName: "arrow.up.right")
  70. case .flat:
  71. return Image(systemName: "arrow.forward")
  72. case .fortyFiveDown:
  73. return Image(systemName: "arrow.down.forward")
  74. case .doubleDown,
  75. .singleDown,
  76. .tripleDown:
  77. return Image(systemName: "arrow.down")
  78. case .none,
  79. .notComputable,
  80. .rateOutOfRange:
  81. return Image(systemName: "arrow.left.and.right")
  82. }
  83. }
  84. }