ChartsView.swift 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. import Charts
  2. import CoreData
  3. import SwiftDate
  4. import SwiftUI
  5. struct ChartsView: View {
  6. @Binding var highLimit: Decimal
  7. @Binding var lowLimit: Decimal
  8. @Binding var units: GlucoseUnits
  9. @Binding var overrideUnit: Bool
  10. @Binding var standing: Bool
  11. var glucose: [GlucoseStored]
  12. @State var headline: Color = .secondary
  13. private let conversionFactor = 0.0555
  14. var body: some View {
  15. glucoseChart
  16. Rectangle().fill(.cyan.opacity(0.2)).frame(maxHeight: 3)
  17. if standing {
  18. VStack {
  19. tirChart
  20. Rectangle().fill(.cyan.opacity(0.2)).frame(maxHeight: 3)
  21. groupedGlucoseStatsLaying
  22. }
  23. } else {
  24. HStack(spacing: 20) {
  25. standingTIRchart
  26. groupedGlucose
  27. }
  28. }
  29. }
  30. init(
  31. _ highLimit: Binding<Decimal>,
  32. _ lowLimit: Binding<Decimal>,
  33. _ units: Binding<GlucoseUnits>,
  34. _ overrideUnit: Binding<Bool>,
  35. _ standing: Binding<Bool>,
  36. glucose: [GlucoseStored]
  37. ) {
  38. _highLimit = highLimit
  39. _lowLimit = lowLimit
  40. _units = units
  41. _overrideUnit = overrideUnit
  42. _standing = standing
  43. self.glucose = glucose
  44. }
  45. var glucoseChart: some View {
  46. // Be aware of the low/lowLimit difference. lowLimit/highLimit is always in mg/dl, whereas low/high is configurable in settings
  47. let low = lowLimit * (units == .mmolL ? Decimal(conversionFactor) : 1)
  48. let high = highLimit * (units == .mmolL ? Decimal(conversionFactor) : 1)
  49. let count = glucose.count
  50. // The symbol size when fewer readings are larger
  51. let sizeOfDataPoints: CGFloat = count < 20 ? 50 : count < 50 ? 35 : count > 2000 ? 5 : 15
  52. return Chart {
  53. ForEach(glucose.filter({ $0.glucose > Int(highLimit) }), id: \.date) { item in
  54. PointMark(
  55. x: .value("Date", item.date ?? Date()),
  56. y: .value("High", Double(item.glucose) * (units == .mmolL ? self.conversionFactor : 1))
  57. )
  58. .foregroundStyle(.orange)
  59. .symbolSize(sizeOfDataPoints)
  60. }
  61. ForEach(
  62. glucose
  63. .filter({
  64. $0.glucose >= Int(lowLimit) && $0
  65. .glucose <= Int(highLimit) }),
  66. id: \.date
  67. ) { item in
  68. PointMark(
  69. x: .value("Date", item.date ?? Date()),
  70. y: .value("In Range", Double(item.glucose) * (units == .mmolL ? conversionFactor : 1))
  71. )
  72. .foregroundStyle(.green)
  73. .symbolSize(sizeOfDataPoints)
  74. }
  75. ForEach(glucose.filter({ $0.glucose < Int(lowLimit) }), id: \.date) { item in
  76. PointMark(
  77. x: .value("Date", item.date ?? Date()),
  78. y: .value("Low", Double(item.glucose) * (units == .mmolL ? conversionFactor : 1))
  79. )
  80. .foregroundStyle(.red)
  81. .symbolSize(sizeOfDataPoints)
  82. }
  83. }
  84. .chartYAxis {
  85. AxisMarks(
  86. values: [
  87. 0,
  88. low,
  89. high,
  90. units == .mmolL ? 15 : 270
  91. ]
  92. )
  93. }
  94. }
  95. var tirChart: some View {
  96. let fetched = tir()
  97. let low = lowLimit * (units == .mmolL ? Decimal(conversionFactor) : 1)
  98. let high = highLimit * (units == .mmolL ? Decimal(conversionFactor) : 1)
  99. let data: [ShapeModel] = [
  100. .init(
  101. type: NSLocalizedString(
  102. "Low",
  103. comment: ""
  104. ) + " (≤\(low.formatted(.number.grouping(.never).rounded().precision(.fractionLength(1)))))",
  105. percent: fetched[0].decimal
  106. ),
  107. .init(type: NSLocalizedString("In Range", comment: ""), percent: fetched[1].decimal),
  108. .init(
  109. type: NSLocalizedString(
  110. "High",
  111. comment: ""
  112. ) + " (≥\(high.formatted(.number.grouping(.never).rounded().precision(.fractionLength(1)))))",
  113. percent: fetched[2].decimal
  114. )
  115. ]
  116. return Chart(data) { shape in
  117. BarMark(
  118. x: .value("TIR", shape.percent)
  119. )
  120. .foregroundStyle(by: .value("Group", shape.type))
  121. .annotation(position: .top, alignment: .center) {
  122. Text(
  123. "\(shape.percent, format: .number.precision(.fractionLength(0))) %"
  124. ).font(.footnote).foregroundColor(.secondary)
  125. }
  126. }
  127. .chartXAxis(.hidden)
  128. .chartForegroundStyleScale([
  129. NSLocalizedString(
  130. "Low",
  131. comment: ""
  132. ) + " (≤\(low.formatted(.number.grouping(.never).rounded().precision(.fractionLength(1)))))": .red,
  133. NSLocalizedString("In Range", comment: ""): .green,
  134. NSLocalizedString(
  135. "High",
  136. comment: ""
  137. ) + " (≥\(high.formatted(.number.grouping(.never).rounded().precision(.fractionLength(1)))))": .orange
  138. ]).frame(maxHeight: 25)
  139. }
  140. var standingTIRchart: some View {
  141. let fetched = tir()
  142. let low = lowLimit * (units == .mmolL ? Decimal(conversionFactor) : 1)
  143. let high = highLimit * (units == .mmolL ? Decimal(conversionFactor) : 1)
  144. let fraction = units == .mmolL ? 1 : 0
  145. let data: [ShapeModel] = [
  146. .init(
  147. type: NSLocalizedString(
  148. "Low",
  149. comment: ""
  150. ) + " (≤ \(low.formatted(.number.grouping(.never).rounded().precision(.fractionLength(1)))))",
  151. percent: fetched[0].decimal
  152. ),
  153. .init(
  154. type: "> \(low.formatted(.number.precision(.fractionLength(fraction)))) - < \(high.formatted(.number.precision(.fractionLength(fraction))))",
  155. percent: fetched[1].decimal
  156. ),
  157. .init(
  158. type: NSLocalizedString(
  159. "High",
  160. comment: ""
  161. ) + " (≥ \(high.formatted(.number.grouping(.never).rounded().precision(.fractionLength(1)))))",
  162. percent: fetched[2].decimal
  163. )
  164. ]
  165. return Chart(data) { shape in
  166. BarMark(
  167. x: .value("Shape", shape.type),
  168. y: .value("Percentage", shape.percent)
  169. )
  170. .foregroundStyle(by: .value("Group", shape.type))
  171. .annotation(position: shape.percent > 19 ? .overlay : .automatic, alignment: .center) {
  172. Text(shape.percent == 0 ? "" : "\(shape.percent, format: .number.precision(.fractionLength(0)))")
  173. }
  174. }
  175. .chartXAxis(.hidden)
  176. .chartYAxis {
  177. AxisMarks(
  178. format: Decimal.FormatStyle.Percent.percent.scale(1)
  179. )
  180. }
  181. .chartForegroundStyleScale([
  182. NSLocalizedString(
  183. "Low",
  184. comment: ""
  185. ) + " (≤ \(low.formatted(.number.grouping(.never).rounded().precision(.fractionLength(1)))))": .red,
  186. "> \(low.formatted(.number.precision(.fractionLength(fraction)))) - < \(high.formatted(.number.precision(.fractionLength(fraction))))": .green,
  187. NSLocalizedString(
  188. "High",
  189. comment: ""
  190. ) + " (≥ \(high.formatted(.number.grouping(.never).rounded().precision(.fractionLength(1)))))": .orange
  191. ])
  192. }
  193. var groupedGlucose: some View {
  194. VStack(alignment: .leading, spacing: 20) {
  195. let mapGlucose = glucose.compactMap({ each in each.glucose })
  196. if !mapGlucose.isEmpty {
  197. let mapGlucoseAcuteLow = mapGlucose.filter({ $0 < Int16(3.3 / 0.0555) })
  198. let mapGlucoseHigh = mapGlucose.filter({ $0 > Int16(11 / 0.0555) })
  199. let mapGlucoseNormal = mapGlucose.filter({ $0 > Int16(3.8 / 0.0555) && $0 < Int16(7.9 / 0.0555) })
  200. HStack {
  201. let value = Double(mapGlucoseHigh.count * 100 / mapGlucose.count)
  202. Text(units == .mmolL ? "> 11 " : "> 198 ").foregroundColor(.secondary)
  203. Text(value.formatted()).foregroundColor(.orange)
  204. Text("%").foregroundColor(.secondary)
  205. }.font(.caption)
  206. HStack {
  207. let value = Double(mapGlucoseNormal.count * 100 / mapGlucose.count)
  208. Text(units == .mmolL ? "3.9-7.8" : "70-140").foregroundColor(.secondary)
  209. Text(value.formatted()).foregroundColor(.green)
  210. Text("%").foregroundColor(.secondary)
  211. }.font(.caption)
  212. HStack {
  213. let value = Double(mapGlucoseAcuteLow.count * 100 / mapGlucose.count)
  214. Text(units == .mmolL ? "< 3.3 " : "< 59 ").foregroundColor(.secondary)
  215. Text(value.formatted()).foregroundColor(.red)
  216. Text("%").foregroundColor(.secondary)
  217. }.font(.caption)
  218. }
  219. }
  220. }
  221. var groupedGlucoseStatsLaying: some View {
  222. HStack {
  223. let mapGlucose = glucose.compactMap({ each in each.glucose })
  224. if !mapGlucose.isEmpty {
  225. let mapGlucoseLow = mapGlucose.filter({ $0 < Int16(3.3 / 0.0555) })
  226. let mapGlucoseNormal = mapGlucose.filter({ $0 > Int16(3.8 / 0.0555) && $0 < Int16(7.9 / 0.0555) })
  227. let mapGlucoseAcuteHigh = mapGlucose.filter({ $0 > Int16(11 / 0.0555) })
  228. HStack {
  229. let value = Double(mapGlucoseLow.count * 100 / mapGlucose.count)
  230. Text(units == .mmolL ? "< 3.3" : "< 59").font(.caption2).foregroundColor(.secondary)
  231. Text(value.formatted()).font(.caption).foregroundColor(value == 0 ? .green : .red)
  232. Text("%").font(.caption)
  233. }
  234. Spacer()
  235. HStack {
  236. let value = Double(mapGlucoseNormal.count * 100 / mapGlucose.count)
  237. Text(units == .mmolL ? "3.9-7.8" : "70-140").foregroundColor(.secondary)
  238. Text(value.formatted()).foregroundColor(.green)
  239. Text("%").foregroundColor(.secondary)
  240. }.font(.caption)
  241. Spacer()
  242. HStack {
  243. let value = Double(mapGlucoseAcuteHigh.count * 100 / mapGlucose.count)
  244. Text(units == .mmolL ? "> 11.0" : "> 198").font(.caption).foregroundColor(.secondary)
  245. Text(value.formatted()).font(.caption).foregroundColor(value == 0 ? .green : .orange)
  246. Text("%").font(.caption)
  247. }
  248. }
  249. }
  250. }
  251. private func tir() -> [(decimal: Decimal, string: String)] {
  252. let hypoLimit = Int(lowLimit)
  253. let hyperLimit = Int(highLimit)
  254. let justGlucoseArray = glucose.compactMap({ each in Int(each.glucose as Int16) })
  255. let totalReadings = justGlucoseArray.count
  256. let hyperArray = glucose.filter({ $0.glucose >= hyperLimit })
  257. let hyperReadings = hyperArray.compactMap({ each in each.glucose as Int16 }).count
  258. let hyperPercentage = Double(hyperReadings) / Double(totalReadings) * 100
  259. let hypoArray = glucose.filter({ $0.glucose <= hypoLimit })
  260. let hypoReadings = hypoArray.compactMap({ each in each.glucose as Int16 }).count
  261. let hypoPercentage = Double(hypoReadings) / Double(totalReadings) * 100
  262. let tir = 100 - (hypoPercentage + hyperPercentage)
  263. var array: [(decimal: Decimal, string: String)] = []
  264. array.append((decimal: Decimal(hypoPercentage), string: "Low"))
  265. array.append((decimal: Decimal(tir), string: "NormaL"))
  266. array.append((decimal: Decimal(hyperPercentage), string: "High"))
  267. return array
  268. }
  269. }