ChartsView.swift 12 KB

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