ChartsView.swift 12 KB

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