BasalProfileEditorRootView.swift 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  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 saveButton: some View {
  81. ZStack {
  82. let shouldDisableButton = state.syncInProgress || state.items.isEmpty || !state.hasChanges
  83. Rectangle()
  84. .frame(width: UIScreen.main.bounds.width, height: 65)
  85. .foregroundStyle(colorScheme == .dark ? Color.bgDarkerDarkBlue : Color.white)
  86. .background(.thinMaterial)
  87. .opacity(0.8)
  88. .clipShape(Rectangle())
  89. Group {
  90. HStack {
  91. Button {
  92. let impactHeavy = UIImpactFeedbackGenerator(style: .heavy)
  93. impactHeavy.impactOccurred()
  94. state.save()
  95. } label: {
  96. HStack {
  97. if state.syncInProgress {
  98. ProgressView().padding(.trailing, 10)
  99. }
  100. Text(state.syncInProgress ? "Saving..." : "Save")
  101. }.padding(10)
  102. }
  103. .frame(width: UIScreen.main.bounds.width * 0.9, alignment: .center)
  104. .disabled(shouldDisableButton)
  105. .background(shouldDisableButton ? Color(.systemGray4) : Color(.systemBlue))
  106. .tint(.white)
  107. .clipShape(RoundedRectangle(cornerRadius: 8))
  108. }
  109. }.padding(5)
  110. }
  111. }
  112. var body: some View {
  113. Form {
  114. if !state.canAdd {
  115. Section {
  116. VStack(alignment: .leading) {
  117. Text(
  118. "Basal profile covers 24 hours. You cannot add more rates. Please remove or adjust existing rates to make space."
  119. ).bold()
  120. }
  121. }.listRowBackground(Color.tabBar)
  122. }
  123. Section(header: Text("Schedule")) {
  124. if !state.items.isEmpty {
  125. basalScheduleChart.padding(.vertical)
  126. }
  127. list
  128. }.listRowBackground(Color.chart)
  129. Section {
  130. HStack {
  131. Text("Total")
  132. .bold()
  133. .foregroundColor(.primary)
  134. Spacer()
  135. Text(rateFormatter.string(from: state.total as NSNumber) ?? "0")
  136. .foregroundColor(.primary) +
  137. Text(" U/day")
  138. .foregroundColor(.secondary)
  139. }
  140. }.listRowBackground(Color.chart)
  141. }
  142. .safeAreaInset(edge: .bottom, spacing: 30) { saveButton }
  143. .alert(isPresented: $state.showAlert) {
  144. Alert(
  145. title: Text("Unable to Save"),
  146. message: Text("Trio could not communicate with your pump. Changes to your basal profile were not saved."),
  147. dismissButton: .default(Text("Close"))
  148. )
  149. }
  150. .onChange(of: state.items) {
  151. state.calcTotal()
  152. state.caluclateChartData()
  153. }
  154. .scrollContentBackground(.hidden).background(color)
  155. .navigationTitle("Basal Profile")
  156. .navigationBarTitleDisplayMode(.automatic)
  157. .toolbar(content: {
  158. if state.items.isNotEmpty {
  159. ToolbarItem(placement: .topBarTrailing) {
  160. EditButton()
  161. }
  162. }
  163. ToolbarItem(placement: .topBarTrailing) {
  164. Button(action: { state.add() }) { Image(systemName: "plus") }.disabled(!state.canAdd)
  165. }
  166. })
  167. .environment(\.editMode, $editMode)
  168. .onAppear {
  169. configureView()
  170. state.validate()
  171. state.caluclateChartData()
  172. }
  173. }
  174. private func pickers(for index: Int) -> some View {
  175. Form {
  176. Section {
  177. Picker(selection: $state.items[index].rateIndex, label: Text("Rate")) {
  178. ForEach(0 ..< state.rateValues.count, id: \.self) { i in
  179. Text(
  180. (
  181. self.rateFormatter
  182. .string(from: state.rateValues[i] as NSNumber) ?? ""
  183. ) + " U/hr"
  184. ).tag(i)
  185. }
  186. }
  187. .onChange(of: state.items[index].rateIndex, { state.calcTotal() })
  188. }.listRowBackground(Color.chart)
  189. Section {
  190. Picker(selection: $state.items[index].timeIndex, label: Text("Time")) {
  191. ForEach(state.availableTimeIndices(index), id: \.self) { i in
  192. Text(
  193. self.dateFormatter
  194. .string(from: Date(
  195. timeIntervalSince1970: state
  196. .timeValues[i]
  197. ))
  198. ).tag(i)
  199. }
  200. }
  201. .onChange(of: state.items[index].timeIndex, { state.calcTotal() })
  202. }.listRowBackground(Color.chart)
  203. }
  204. .padding(.top)
  205. .scrollContentBackground(.hidden).background(color)
  206. .navigationTitle("Set Rate")
  207. .navigationBarTitleDisplayMode(.automatic)
  208. }
  209. private var list: some View {
  210. List {
  211. ForEach(state.items.indexed(), id: \.1.id) { index, item in
  212. NavigationLink(destination: pickers(for: index)) {
  213. HStack {
  214. Text("Rate").foregroundColor(.secondary)
  215. Text(
  216. "\(rateFormatter.string(from: state.rateValues[item.rateIndex] as NSNumber) ?? "0") U/hr"
  217. )
  218. Spacer()
  219. Text("starts at").foregroundColor(.secondary)
  220. Text(
  221. "\(dateFormatter.string(from: Date(timeIntervalSince1970: state.timeValues[item.timeIndex])))"
  222. )
  223. }
  224. }
  225. .moveDisabled(true)
  226. }
  227. .onDelete(perform: onDelete)
  228. }
  229. }
  230. private func onDelete(offsets: IndexSet) {
  231. state.items.remove(atOffsets: offsets)
  232. state.validate()
  233. state.calcTotal()
  234. state.caluclateChartData()
  235. }
  236. }
  237. }