TDDChart.swift 9.8 KB

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