TDDChart.swift 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. import Charts
  2. import SwiftUI
  3. struct TDDChartView: View {
  4. @Binding var selectedDuration: Stat.StateModel.StatsTimeInterval
  5. let tddStats: [TDDStats]
  6. let state: Stat.StateModel
  7. @State private var scrollPosition = Date()
  8. @State private var selectedDate: Date?
  9. @State private var currentAverage: Double = 0
  10. @State private var updateTimer = Stat.UpdateTimer()
  11. private var visibleDomainLength: TimeInterval {
  12. switch selectedDuration {
  13. case .Day: return 24 * 3600
  14. case .Week: return 7 * 24 * 3600
  15. case .Month: return 30 * 24 * 3600
  16. case .Total: return 90 * 24 * 3600
  17. }
  18. }
  19. private var visibleDateRange: (start: Date, end: Date) {
  20. let start = scrollPosition
  21. let end = start.addingTimeInterval(visibleDomainLength)
  22. return (start, end)
  23. }
  24. private var dateFormat: Date.FormatStyle {
  25. switch selectedDuration {
  26. case .Day:
  27. return .dateTime.hour()
  28. case .Week:
  29. return .dateTime.weekday(.abbreviated)
  30. case .Month:
  31. return .dateTime.day()
  32. case .Total:
  33. return .dateTime.month(.abbreviated)
  34. }
  35. }
  36. private var alignmentComponents: DateComponents {
  37. switch selectedDuration {
  38. case .Day:
  39. return DateComponents(hour: 0)
  40. case .Week:
  41. return DateComponents(weekday: 2)
  42. case .Month,
  43. .Total:
  44. return DateComponents(day: 1)
  45. }
  46. }
  47. private func getTDDForDate(_ date: Date) -> TDDStats? {
  48. let calendar = Calendar.current
  49. return tddStats.first { stat in
  50. switch selectedDuration {
  51. case .Day:
  52. return calendar.isDate(stat.date, equalTo: date, toGranularity: .hour)
  53. default:
  54. return calendar.isDate(stat.date, inSameDayAs: date)
  55. }
  56. }
  57. }
  58. private func updateAverages() {
  59. currentAverage = state.getCachedTDDAverages(for: visibleDateRange)
  60. }
  61. /// Formats the visible date range into a human-readable string
  62. private func formatVisibleDateRange() -> String {
  63. let start = visibleDateRange.start
  64. let end = visibleDateRange.end
  65. let calendar = Calendar.current
  66. let today = Date()
  67. let timeFormat = start.formatted(.dateTime.hour().minute())
  68. // Special handling for Day view with relative dates
  69. if selectedDuration == .Day {
  70. let startDateText: String
  71. let endDateText: String
  72. // Format start date
  73. if calendar.isDate(start, inSameDayAs: today) {
  74. startDateText = "Today"
  75. } else if calendar.isDate(start, inSameDayAs: calendar.date(byAdding: .day, value: -1, to: today)!) {
  76. startDateText = "Yesterday"
  77. } else if calendar.isDate(start, inSameDayAs: calendar.date(byAdding: .day, value: 1, to: today)!) {
  78. startDateText = "Tomorrow"
  79. } else {
  80. startDateText = start.formatted(.dateTime.day().month())
  81. }
  82. // Format end date
  83. if calendar.isDate(end, inSameDayAs: today) {
  84. endDateText = "Today"
  85. } else if calendar.isDate(end, inSameDayAs: calendar.date(byAdding: .day, value: -1, to: today)!) {
  86. endDateText = "Yesterday"
  87. } else if calendar.isDate(end, inSameDayAs: calendar.date(byAdding: .day, value: 1, to: today)!) {
  88. endDateText = "Tomorrow"
  89. } else {
  90. endDateText = end.formatted(.dateTime.day().month())
  91. }
  92. // If start and end are on the same day, show date only once
  93. if calendar.isDate(start, inSameDayAs: end) {
  94. return "\(startDateText), \(timeFormat) - \(end.formatted(.dateTime.hour().minute()))"
  95. }
  96. return "\(startDateText), \(timeFormat) - \(endDateText), \(end.formatted(.dateTime.hour().minute()))"
  97. }
  98. // Standard format for other views
  99. return "\(start.formatted()) - \(end.formatted())"
  100. }
  101. private func getInitialScrollPosition() -> Date {
  102. let calendar = Calendar.current
  103. let now = Date()
  104. switch selectedDuration {
  105. case .Day:
  106. return calendar.date(byAdding: .day, value: -1, to: now)!
  107. case .Week:
  108. return calendar.date(byAdding: .day, value: -7, to: now)!
  109. case .Month:
  110. return calendar.date(byAdding: .month, value: -1, to: now)!
  111. case .Total:
  112. return calendar.date(byAdding: .month, value: -3, to: now)!
  113. }
  114. }
  115. private func isSameTimeUnit(_ date1: Date, _ date2: Date) -> Bool {
  116. switch selectedDuration {
  117. case .Day:
  118. return Calendar.current.isDate(date1, equalTo: date2, toGranularity: .hour)
  119. default:
  120. return Calendar.current.isDate(date1, inSameDayAs: date2)
  121. }
  122. }
  123. var body: some View {
  124. VStack(alignment: .leading, spacing: 8) {
  125. statsView
  126. chartsView
  127. }
  128. .onAppear {
  129. scrollPosition = getInitialScrollPosition()
  130. updateAverages()
  131. }
  132. .onChange(of: scrollPosition) {
  133. updateTimer.scheduleUpdate {
  134. updateAverages()
  135. }
  136. }
  137. .onChange(of: selectedDuration) {
  138. Task {
  139. scrollPosition = getInitialScrollPosition()
  140. updateAverages()
  141. }
  142. }
  143. }
  144. private var statsView: some View {
  145. HStack {
  146. Text("Average:")
  147. .font(.headline)
  148. .foregroundStyle(.secondary)
  149. Text(currentAverage.formatted(.number.precision(.fractionLength(1))))
  150. .font(.headline)
  151. .foregroundStyle(.secondary)
  152. Text("U")
  153. .font(.headline)
  154. .foregroundStyle(.secondary)
  155. Spacer()
  156. Text(formatVisibleDateRange())
  157. .font(.subheadline)
  158. .foregroundStyle(.secondary)
  159. }
  160. }
  161. private var chartsView: some View {
  162. Chart {
  163. ForEach(tddStats) { stat in
  164. BarMark(
  165. x: .value("Date", stat.date, unit: selectedDuration == .Day ? .hour : .day),
  166. y: .value("Amount", stat.amount)
  167. )
  168. .foregroundStyle(Color.insulin)
  169. .opacity(
  170. selectedDate.map { date in
  171. isSameTimeUnit(stat.date, date) ? 1 : 0.3
  172. } ?? 1
  173. )
  174. }
  175. // Selection popover outside of the ForEach loop!
  176. if let selectedDate,
  177. let selectedTDD = getTDDForDate(selectedDate)
  178. {
  179. RuleMark(
  180. x: .value("Selected Date", selectedDate)
  181. )
  182. .foregroundStyle(.secondary.opacity(0.5))
  183. .annotation(
  184. position: .top,
  185. spacing: 0,
  186. overflowResolution: .init(x: .fit(to: .chart), y: .fit(to: .chart))
  187. ) {
  188. TDDSelectionPopover(date: selectedDate, tdd: selectedTDD, selectedDuration: selectedDuration)
  189. }
  190. }
  191. }
  192. .chartYAxis {
  193. AxisMarks(position: .trailing) { value in
  194. if let amount = value.as(Double.self) {
  195. AxisValueLabel {
  196. Text(amount.formatted(.number.precision(.fractionLength(0))) + " U")
  197. }
  198. AxisGridLine()
  199. }
  200. }
  201. }
  202. .chartXAxis {
  203. AxisMarks(preset: .aligned, values: .stride(by: selectedDuration == .Day ? .hour : .day)) { value in
  204. if let date = value.as(Date.self) {
  205. let day = Calendar.current.component(.day, from: date)
  206. let hour = Calendar.current.component(.hour, from: date)
  207. switch selectedDuration {
  208. case .Day:
  209. if hour % 6 == 0 {
  210. AxisValueLabel(format: dateFormat, centered: true)
  211. AxisGridLine()
  212. }
  213. case .Month:
  214. if day % 5 == 0 {
  215. AxisValueLabel(format: dateFormat, centered: true)
  216. AxisGridLine()
  217. }
  218. case .Total:
  219. if day == 1 && Calendar.current.component(.month, from: date) % 3 == 1 {
  220. AxisValueLabel(format: dateFormat, centered: true)
  221. AxisGridLine()
  222. }
  223. default:
  224. AxisValueLabel(format: dateFormat, centered: true)
  225. AxisGridLine()
  226. }
  227. }
  228. }
  229. }
  230. .chartScrollableAxes(.horizontal)
  231. .chartXSelection(value: $selectedDate.animation(.easeInOut))
  232. .chartScrollPosition(x: $scrollPosition)
  233. .chartScrollTargetBehavior(
  234. .valueAligned(
  235. matching: selectedDuration == .Day ?
  236. DateComponents(minute: 0) :
  237. DateComponents(hour: 0),
  238. majorAlignment: .matching(alignmentComponents)
  239. )
  240. )
  241. .chartXVisibleDomain(length: visibleDomainLength)
  242. .frame(height: 250)
  243. }
  244. }
  245. private struct TDDSelectionPopover: View {
  246. let date: Date
  247. let tdd: TDDStats
  248. let selectedDuration: Stat.StateModel.StatsTimeInterval
  249. var body: some View {
  250. VStack(alignment: .leading, spacing: 4) {
  251. Text(selectedDuration == .Day ? date.formatted(.dateTime.hour().minute()) : date.formatted(.dateTime.month().day()))
  252. .font(.subheadline)
  253. .fontWeight(.bold)
  254. Text(tdd.amount.formatted(.number.precision(.fractionLength(1))) + " U")
  255. .font(.title3.bold())
  256. }
  257. .foregroundStyle(.white)
  258. .padding(20)
  259. .background {
  260. RoundedRectangle(cornerRadius: 10)
  261. .fill(Color.insulin.gradient)
  262. }
  263. }
  264. }