BasalProfileEditorRootView.swift 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  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. Section(header: Text("Schedule")) {
  115. if !state.items.isEmpty {
  116. basalScheduleChart.padding(.vertical)
  117. }
  118. list
  119. }.listRowBackground(Color.chart)
  120. Section {
  121. HStack {
  122. Text("Total")
  123. .bold()
  124. .foregroundColor(.primary)
  125. Spacer()
  126. Text(rateFormatter.string(from: state.total as NSNumber) ?? "0")
  127. .foregroundColor(.primary) +
  128. Text(" U/day")
  129. .foregroundColor(.secondary)
  130. }
  131. }.listRowBackground(Color.chart)
  132. }
  133. .safeAreaInset(edge: .bottom, spacing: 30) { saveButton }
  134. .alert(isPresented: $state.showAlert) {
  135. Alert(
  136. title: Text("Unable to Save"),
  137. message: Text("Trio could not communicate with your pump. Changes to your basal profile were not saved."),
  138. dismissButton: .default(Text("Close"))
  139. )
  140. }
  141. .onChange(of: state.items) {
  142. state.calcTotal()
  143. state.calculateChartData()
  144. }
  145. .scrollContentBackground(.hidden).background(color)
  146. .navigationTitle("Basal Profile")
  147. .navigationBarTitleDisplayMode(.automatic)
  148. .toolbar(content: {
  149. ToolbarItem(placement: .topBarTrailing) {
  150. EditButton()
  151. }
  152. ToolbarItem(placement: .topBarTrailing) {
  153. addButton
  154. }
  155. })
  156. .environment(\.editMode, $editMode)
  157. .onAppear {
  158. configureView()
  159. state.validate()
  160. state.calculateChartData()
  161. }
  162. }
  163. private func pickers(for index: Int) -> some View {
  164. Form {
  165. Section {
  166. Picker(selection: $state.items[index].rateIndex, label: Text("Rate")) {
  167. ForEach(0 ..< state.rateValues.count, id: \.self) { i in
  168. Text(
  169. (
  170. self.rateFormatter
  171. .string(from: state.rateValues[i] as NSNumber) ?? ""
  172. ) + " U/hr"
  173. ).tag(i)
  174. }
  175. }
  176. .onChange(of: state.items[index].rateIndex, { state.calcTotal() })
  177. }.listRowBackground(Color.chart)
  178. Section {
  179. Picker(selection: $state.items[index].timeIndex, label: Text("Time")) {
  180. ForEach(state.availableTimeIndices(index), id: \.self) { i in
  181. Text(
  182. self.dateFormatter
  183. .string(from: Date(
  184. timeIntervalSince1970: state
  185. .timeValues[i]
  186. ))
  187. ).tag(i)
  188. }
  189. }
  190. .onChange(of: state.items[index].timeIndex, { state.calcTotal() })
  191. }.listRowBackground(Color.chart)
  192. }
  193. .padding(.top)
  194. .scrollContentBackground(.hidden).background(color)
  195. .navigationTitle("Set Rate")
  196. .navigationBarTitleDisplayMode(.automatic)
  197. }
  198. private var list: some View {
  199. List {
  200. ForEach(state.items.indexed(), id: \.1.id) { index, item in
  201. NavigationLink(destination: pickers(for: index)) {
  202. HStack {
  203. Text("Rate").foregroundColor(.secondary)
  204. Text(
  205. "\(rateFormatter.string(from: state.rateValues[item.rateIndex] as NSNumber) ?? "0") U/hr"
  206. )
  207. Spacer()
  208. Text("starts at").foregroundColor(.secondary)
  209. Text(
  210. "\(dateFormatter.string(from: Date(timeIntervalSince1970: state.timeValues[item.timeIndex])))"
  211. )
  212. }
  213. }
  214. .moveDisabled(true)
  215. }
  216. .onDelete(perform: onDelete)
  217. }
  218. }
  219. private var addButton: some View {
  220. guard state.canAdd else {
  221. return AnyView(EmptyView())
  222. }
  223. switch editMode {
  224. case .inactive:
  225. return AnyView(Button(action: onAdd) { Image(systemName: "plus") })
  226. default:
  227. return AnyView(EmptyView())
  228. }
  229. }
  230. func onAdd() {
  231. state.add()
  232. }
  233. private func onDelete(offsets: IndexSet) {
  234. state.items.remove(atOffsets: offsets)
  235. state.validate()
  236. state.calculateChartData()
  237. }
  238. }
  239. }