BasalProfileEditorRootView.swift 10.0 KB

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