BasalProfileEditorRootView.swift 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  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. @Environment(\.colorScheme) var colorScheme
  12. var color: LinearGradient {
  13. colorScheme == .dark ? LinearGradient(
  14. gradient: Gradient(colors: [
  15. Color.bgDarkBlue,
  16. Color.bgDarkerDarkBlue
  17. ]),
  18. startPoint: .top,
  19. endPoint: .bottom
  20. )
  21. :
  22. LinearGradient(
  23. gradient: Gradient(colors: [Color.gray.opacity(0.1)]),
  24. startPoint: .top,
  25. endPoint: .bottom
  26. )
  27. }
  28. private var dateFormatter: DateFormatter {
  29. let formatter = DateFormatter()
  30. formatter.timeZone = TimeZone(secondsFromGMT: 0)
  31. formatter.timeStyle = .short
  32. return formatter
  33. }
  34. private var rateFormatter: NumberFormatter {
  35. let formatter = NumberFormatter()
  36. formatter.numberStyle = .decimal
  37. return formatter
  38. }
  39. var basalScheduleChart: some View {
  40. Chart {
  41. ForEach(state.chartData!, id: \.self) { profile in
  42. RectangleMark(
  43. xStart: .value("start", profile.startDate),
  44. xEnd: .value("end", profile.endDate!),
  45. yStart: .value("rate-start", profile.amount),
  46. yEnd: .value("rate-end", 0)
  47. ).foregroundStyle(
  48. .linearGradient(
  49. colors: [
  50. Color.insulin.opacity(0.6),
  51. Color.insulin.opacity(0.1)
  52. ],
  53. startPoint: .bottom,
  54. endPoint: .top
  55. )
  56. ).alignsMarkStylesWithPlotArea()
  57. LineMark(x: .value("End Date", profile.endDate!), y: .value("Amount", profile.amount))
  58. .lineStyle(.init(lineWidth: 1)).foregroundStyle(Color.insulin)
  59. LineMark(x: .value("Start Date", profile.startDate), y: .value("Amount", profile.amount))
  60. .lineStyle(.init(lineWidth: 1)).foregroundStyle(Color.insulin)
  61. }
  62. }
  63. .chartXAxis {
  64. AxisMarks(values: .automatic(desiredCount: 6)) { _ in
  65. AxisValueLabel(format: .dateTime.hour())
  66. AxisGridLine(centered: true, stroke: StrokeStyle(lineWidth: 1, dash: [2, 4]))
  67. }
  68. }
  69. .chartYAxis {
  70. AxisMarks(values: .automatic(desiredCount: 2)) { _ in
  71. AxisValueLabel()
  72. AxisGridLine(centered: true, stroke: StrokeStyle(lineWidth: 1, dash: [2, 4]))
  73. }
  74. }
  75. .chartXScale(
  76. domain: Calendar.current.startOfDay(for: chartScale!) ... Calendar.current.startOfDay(for: chartScale!)
  77. .addingTimeInterval(60 * 60 * 24)
  78. )
  79. }
  80. var body: some View {
  81. Form {
  82. let shouldDisableButton = state.syncInProgress || state.items.isEmpty || !state.hasChanges
  83. Section(header: Text("Schedule")) {
  84. if !state.items.isEmpty {
  85. basalScheduleChart.padding(.vertical)
  86. }
  87. list
  88. }.listRowBackground(Color.chart)
  89. Section {
  90. HStack {
  91. Text("Total")
  92. .bold()
  93. .foregroundColor(.primary)
  94. Spacer()
  95. Text(rateFormatter.string(from: state.total as NSNumber) ?? "0")
  96. .foregroundColor(.primary) +
  97. Text(" U/day")
  98. .foregroundColor(.secondary)
  99. }
  100. }.listRowBackground(Color.chart)
  101. Section {
  102. HStack {
  103. if state.syncInProgress {
  104. ProgressView().padding(.trailing, 10)
  105. }
  106. Button {
  107. let impactHeavy = UIImpactFeedbackGenerator(style: .heavy)
  108. impactHeavy.impactOccurred()
  109. state.save()
  110. } label: {
  111. Text(state.syncInProgress ? "Saving..." : "Save")
  112. }
  113. .disabled(shouldDisableButton)
  114. .frame(maxWidth: .infinity, alignment: .center)
  115. .tint(.white)
  116. }
  117. }.listRowBackground(shouldDisableButton ? Color(.systemGray4) : Color(.systemBlue))
  118. }
  119. .alert(isPresented: $state.showAlert) {
  120. Alert(
  121. title: Text("Unable to Save"),
  122. message: Text("Trio could not communicate with your pump. Changes to your basal profile were not saved."),
  123. dismissButton: .default(Text("Close"))
  124. )
  125. }
  126. .onChange(of: state.items) {
  127. state.calcTotal()
  128. state.caluclateChartData()
  129. }
  130. .scrollContentBackground(.hidden).background(color)
  131. .navigationTitle("Basal Profile")
  132. .navigationBarTitleDisplayMode(.automatic)
  133. .toolbar(content: {
  134. ToolbarItem(placement: .topBarTrailing) {
  135. EditButton()
  136. }
  137. ToolbarItem(placement: .topBarTrailing) {
  138. addButton
  139. }
  140. })
  141. .environment(\.editMode, $editMode)
  142. .onAppear {
  143. configureView()
  144. state.validate()
  145. state.caluclateChartData()
  146. }
  147. }
  148. private func pickers(for index: Int) -> some View {
  149. Form {
  150. Section {
  151. Picker(selection: $state.items[index].rateIndex, label: Text("Rate")) {
  152. ForEach(0 ..< state.rateValues.count, id: \.self) { i in
  153. Text(
  154. (
  155. self.rateFormatter
  156. .string(from: state.rateValues[i] as NSNumber) ?? ""
  157. ) + " U/hr"
  158. ).tag(i)
  159. }
  160. }
  161. .onChange(of: state.items[index].rateIndex, { state.calcTotal() })
  162. }.listRowBackground(Color.chart)
  163. Section {
  164. Picker(selection: $state.items[index].timeIndex, label: Text("Time")) {
  165. ForEach(state.availableTimeIndices(index), id: \.self) { i in
  166. Text(
  167. self.dateFormatter
  168. .string(from: Date(
  169. timeIntervalSince1970: state
  170. .timeValues[i]
  171. ))
  172. ).tag(i)
  173. }
  174. }
  175. .onChange(of: state.items[index].timeIndex, { state.calcTotal() })
  176. }.listRowBackground(Color.chart)
  177. }
  178. .padding(.top)
  179. .scrollContentBackground(.hidden).background(color)
  180. .navigationTitle("Set Rate")
  181. .navigationBarTitleDisplayMode(.automatic)
  182. }
  183. private var list: some View {
  184. List {
  185. ForEach(state.items.indexed(), id: \.1.id) { index, item in
  186. NavigationLink(destination: pickers(for: index)) {
  187. HStack {
  188. Text("Rate").foregroundColor(.secondary)
  189. Text(
  190. "\(rateFormatter.string(from: state.rateValues[item.rateIndex] as NSNumber) ?? "0") U/hr"
  191. )
  192. Spacer()
  193. Text("starts at").foregroundColor(.secondary)
  194. Text(
  195. "\(dateFormatter.string(from: Date(timeIntervalSince1970: state.timeValues[item.timeIndex])))"
  196. )
  197. }
  198. }
  199. .moveDisabled(true)
  200. }
  201. .onDelete(perform: onDelete)
  202. }
  203. }
  204. private var addButton: some View {
  205. guard state.canAdd else {
  206. return AnyView(EmptyView())
  207. }
  208. switch editMode {
  209. case .inactive:
  210. return AnyView(Button(action: onAdd) { Image(systemName: "plus") })
  211. default:
  212. return AnyView(EmptyView())
  213. }
  214. }
  215. func onAdd() {
  216. state.add()
  217. }
  218. private func onDelete(offsets: IndexSet) {
  219. state.items.remove(atOffsets: offsets)
  220. state.validate()
  221. state.calcTotal()
  222. state.caluclateChartData()
  223. }
  224. }
  225. }