BasalProfileEditorRootView.swift 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. import Charts
  2. import SwiftUI
  3. import Swinject
  4. extension BasalProfileEditor {
  5. struct RootView: BaseView {
  6. let resolver: Resolver
  7. @State var state = StateModel()
  8. @State private var editMode = EditMode.inactive
  9. let chartScale = Calendar.current
  10. .date(from: DateComponents(year: 2001, month: 01, day: 01, hour: 0, minute: 0, second: 0))
  11. let tzOffset = TimeZone.current.secondsFromGMT()
  12. @Environment(\.colorScheme) var colorScheme
  13. @Environment(AppState.self) var appState
  14. private var dateFormatter: DateFormatter {
  15. let formatter = DateFormatter()
  16. formatter.timeZone = TimeZone(secondsFromGMT: 0)
  17. formatter.timeStyle = .short
  18. return formatter
  19. }
  20. private var rateFormatter: NumberFormatter {
  21. let formatter = NumberFormatter()
  22. formatter.numberStyle = .decimal
  23. return formatter
  24. }
  25. var now = Date()
  26. var basalScheduleChart: some View {
  27. Chart {
  28. ForEach(state.chartData!, id: \.self) { profile in
  29. let startDate = Calendar.current.startOfDay(for: now)
  30. .addingTimeInterval(profile.startDate.timeIntervalSinceReferenceDate + Double(tzOffset))
  31. let endDate = Calendar.current.startOfDay(for: now)
  32. .addingTimeInterval(profile.endDate!.timeIntervalSinceReferenceDate + Double(tzOffset))
  33. RectangleMark(
  34. xStart: .value("start", startDate),
  35. xEnd: .value("end", endDate),
  36. yStart: .value("rate-start", profile.amount),
  37. yEnd: .value("rate-end", 0)
  38. ).foregroundStyle(
  39. .linearGradient(
  40. colors: [
  41. Color.insulin.opacity(0.6),
  42. Color.insulin.opacity(0.1)
  43. ],
  44. startPoint: .bottom,
  45. endPoint: .top
  46. )
  47. ).alignsMarkStylesWithPlotArea()
  48. LineMark(x: .value("End Date", endDate), y: .value("Amount", profile.amount))
  49. .lineStyle(.init(lineWidth: 1)).foregroundStyle(Color.insulin)
  50. LineMark(x: .value("Start Date", startDate), y: .value("Amount", profile.amount))
  51. .lineStyle(.init(lineWidth: 1)).foregroundStyle(Color.insulin)
  52. }
  53. }
  54. .chartXAxis {
  55. AxisMarks(values: .automatic(desiredCount: 6)) { _ in
  56. AxisValueLabel(format: .dateTime.hour())
  57. AxisGridLine(centered: true, stroke: StrokeStyle(lineWidth: 1, dash: [2, 4]))
  58. }
  59. }
  60. .chartYAxis {
  61. AxisMarks(values: .automatic(desiredCount: 2)) { _ in
  62. AxisValueLabel()
  63. AxisGridLine(centered: true, stroke: StrokeStyle(lineWidth: 1, dash: [2, 4]))
  64. }
  65. }
  66. .chartXScale(
  67. domain: Calendar.current.startOfDay(for: now) ... Calendar
  68. .current.startOfDay(for: now)
  69. .addingTimeInterval(60 * 60 * 24)
  70. )
  71. }
  72. var saveButton: some View {
  73. ZStack {
  74. let shouldDisableButton = state.syncInProgress || state.items.isEmpty || !state.hasChanges
  75. Rectangle()
  76. .frame(width: UIScreen.main.bounds.width, height: 65)
  77. .foregroundStyle(colorScheme == .dark ? Color.bgDarkerDarkBlue : Color.white)
  78. .background(.thinMaterial)
  79. .opacity(0.8)
  80. .clipShape(Rectangle())
  81. Group {
  82. HStack {
  83. Button(action: {
  84. let impactHeavy = UIImpactFeedbackGenerator(style: .heavy)
  85. impactHeavy.impactOccurred()
  86. state.save()
  87. }, label: {
  88. HStack {
  89. if state.syncInProgress {
  90. ProgressView().padding(.trailing, 10)
  91. }
  92. Text(state.syncInProgress ? "Saving..." : "Save")
  93. }
  94. .frame(width: UIScreen.main.bounds.width * 0.9, alignment: .center)
  95. .padding(10)
  96. })
  97. .frame(width: UIScreen.main.bounds.width * 0.9, height: 40, alignment: .center)
  98. .disabled(shouldDisableButton)
  99. .background(shouldDisableButton ? Color(.systemGray4) : Color(.systemBlue))
  100. .tint(.white)
  101. .clipShape(RoundedRectangle(cornerRadius: 8))
  102. }
  103. }.padding(5)
  104. }
  105. }
  106. var body: some View {
  107. Form {
  108. if !state.canAdd {
  109. Section {
  110. VStack(alignment: .leading) {
  111. Text(
  112. "Basal profile covers 24 hours. You cannot add more rates. Please remove or adjust existing rates to make space."
  113. ).bold()
  114. }
  115. }.listRowBackground(Color.tabBar)
  116. }
  117. Section(header: Text("Schedule")) {
  118. if !state.items.isEmpty {
  119. basalScheduleChart.padding(.vertical)
  120. }
  121. list
  122. }.listRowBackground(Color.chart)
  123. Section {
  124. HStack {
  125. Text("Total")
  126. .bold()
  127. .foregroundColor(.primary)
  128. Spacer()
  129. Text(rateFormatter.string(from: state.total as NSNumber) ?? "0")
  130. .foregroundColor(.primary) +
  131. Text(" U/day")
  132. .foregroundColor(.secondary)
  133. }
  134. }.listRowBackground(Color.chart)
  135. Section {} header: {
  136. VStack(alignment: .leading, spacing: 10) {
  137. HStack {
  138. Image(systemName: "note.text.badge.plus").foregroundStyle(.primary)
  139. Text("Add an entry by tapping 'Add Rate +' in the top right-hand corner of the screen.")
  140. }
  141. HStack {
  142. Image(systemName: "hand.draw.fill").foregroundStyle(.primary)
  143. Text("Swipe to delete a single entry. Tap on it, to edit its time or rate.")
  144. }
  145. }
  146. .textCase(nil)
  147. }
  148. }
  149. .safeAreaInset(edge: .bottom, spacing: 30) { saveButton }
  150. .alert(isPresented: $state.showAlert) {
  151. Alert(
  152. title: Text("Unable to Save"),
  153. message: Text("Trio could not communicate with your pump. Changes to your basal profile were not saved."),
  154. dismissButton: .default(Text("Close"))
  155. )
  156. }
  157. .onChange(of: state.items) {
  158. state.calcTotal()
  159. state.calculateChartData()
  160. }
  161. .scrollContentBackground(.hidden).background(appState.trioBackgroundColor(for: colorScheme))
  162. .navigationTitle("Basal Rates")
  163. .navigationBarTitleDisplayMode(.automatic)
  164. .toolbar(content: {
  165. ToolbarItem(placement: .topBarTrailing) {
  166. Button(action: { state.add() }) {
  167. HStack {
  168. Text("Add Rate")
  169. Image(systemName: "plus")
  170. }
  171. }.disabled(!state.canAdd)
  172. }
  173. })
  174. .environment(\.editMode, $editMode)
  175. .onAppear {
  176. configureView()
  177. state.validate()
  178. state.calculateChartData()
  179. }
  180. }
  181. private func pickers(for index: Int) -> some View {
  182. Form {
  183. Section {
  184. Picker(selection: $state.items[index].rateIndex, label: Text("Rate")) {
  185. ForEach(0 ..< state.rateValues.count, id: \.self) { i in
  186. Text(
  187. (self.rateFormatter.string(from: state.rateValues[i] as NSNumber) ?? "") + " " +
  188. String(localized: "U/hr")
  189. ).tag(i)
  190. }
  191. }
  192. .onChange(of: state.items[index].rateIndex, { state.calcTotal() })
  193. }.listRowBackground(Color.chart)
  194. Section {
  195. Picker(selection: $state.items[index].timeIndex, label: Text("Time")) {
  196. ForEach(state.availableTimeIndices(index), id: \.self) { i in
  197. Text(
  198. self.dateFormatter
  199. .string(from: Date(
  200. timeIntervalSince1970: state
  201. .timeValues[i]
  202. ))
  203. ).tag(i)
  204. }
  205. }
  206. .onChange(of: state.items[index].timeIndex, { state.calcTotal() })
  207. }.listRowBackground(Color.chart)
  208. }
  209. .padding(.top)
  210. .scrollContentBackground(.hidden).background(appState.trioBackgroundColor(for: colorScheme))
  211. .navigationTitle("Set Rate")
  212. .navigationBarTitleDisplayMode(.automatic)
  213. }
  214. private var list: some View {
  215. List {
  216. ForEach(state.items.indexed(), id: \.1.id) { index, item in
  217. NavigationLink(destination: pickers(for: index)) {
  218. HStack {
  219. Text("Rate").foregroundColor(.secondary)
  220. Text(
  221. "\(rateFormatter.string(from: state.rateValues[item.rateIndex] as NSNumber) ?? "0") U/hr"
  222. )
  223. Spacer()
  224. Text("starts at").foregroundColor(.secondary)
  225. Text(
  226. "\(dateFormatter.string(from: Date(timeIntervalSince1970: state.timeValues[item.timeIndex])))"
  227. )
  228. }
  229. }
  230. .moveDisabled(true)
  231. }
  232. .onDelete(perform: onDelete)
  233. }
  234. }
  235. private func onDelete(offsets: IndexSet) {
  236. state.items.remove(atOffsets: offsets)
  237. state.validate()
  238. state.calculateChartData()
  239. }
  240. }
  241. }