BasalProfileEditorRootView.swift 9.7 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. @Environment(AppState.self) var appState
  13. private var dateFormatter: DateFormatter {
  14. let formatter = DateFormatter()
  15. formatter.timeZone = TimeZone(secondsFromGMT: 0)
  16. formatter.timeStyle = .short
  17. return formatter
  18. }
  19. private var rateFormatter: NumberFormatter {
  20. let formatter = NumberFormatter()
  21. formatter.numberStyle = .decimal
  22. return formatter
  23. }
  24. var basalScheduleChart: some View {
  25. Chart {
  26. ForEach(state.chartData!, id: \.self) { profile in
  27. RectangleMark(
  28. xStart: .value("start", profile.startDate),
  29. xEnd: .value("end", profile.endDate!),
  30. yStart: .value("rate-start", profile.amount),
  31. yEnd: .value("rate-end", 0)
  32. ).foregroundStyle(
  33. .linearGradient(
  34. colors: [
  35. Color.insulin.opacity(0.6),
  36. Color.insulin.opacity(0.1)
  37. ],
  38. startPoint: .bottom,
  39. endPoint: .top
  40. )
  41. ).alignsMarkStylesWithPlotArea()
  42. LineMark(x: .value("End Date", profile.endDate!), y: .value("Amount", profile.amount))
  43. .lineStyle(.init(lineWidth: 1)).foregroundStyle(Color.insulin)
  44. LineMark(x: .value("Start Date", profile.startDate), y: .value("Amount", profile.amount))
  45. .lineStyle(.init(lineWidth: 1)).foregroundStyle(Color.insulin)
  46. }
  47. }
  48. .chartXAxis {
  49. AxisMarks(values: .automatic(desiredCount: 6)) { _ in
  50. AxisValueLabel(format: .dateTime.hour())
  51. AxisGridLine(centered: true, stroke: StrokeStyle(lineWidth: 1, dash: [2, 4]))
  52. }
  53. }
  54. .chartYAxis {
  55. AxisMarks(values: .automatic(desiredCount: 2)) { _ in
  56. AxisValueLabel()
  57. AxisGridLine(centered: true, stroke: StrokeStyle(lineWidth: 1, dash: [2, 4]))
  58. }
  59. }
  60. .chartXScale(
  61. domain: Calendar.current.startOfDay(for: chartScale!) ... Calendar.current.startOfDay(for: chartScale!)
  62. .addingTimeInterval(60 * 60 * 24)
  63. )
  64. }
  65. var saveButton: some View {
  66. ZStack {
  67. let shouldDisableButton = state.syncInProgress || state.items.isEmpty || !state.hasChanges
  68. Rectangle()
  69. .frame(width: UIScreen.main.bounds.width, height: 65)
  70. .foregroundStyle(colorScheme == .dark ? Color.bgDarkerDarkBlue : Color.white)
  71. .background(.thinMaterial)
  72. .opacity(0.8)
  73. .clipShape(Rectangle())
  74. Group {
  75. HStack {
  76. Button {
  77. let impactHeavy = UIImpactFeedbackGenerator(style: .heavy)
  78. impactHeavy.impactOccurred()
  79. state.save()
  80. } label: {
  81. HStack {
  82. if state.syncInProgress {
  83. ProgressView().padding(.trailing, 10)
  84. }
  85. Text(state.syncInProgress ? "Saving..." : "Save")
  86. }.padding(10)
  87. }
  88. .frame(width: UIScreen.main.bounds.width * 0.9, alignment: .center)
  89. .disabled(shouldDisableButton)
  90. .background(shouldDisableButton ? Color(.systemGray4) : Color(.systemBlue))
  91. .tint(.white)
  92. .clipShape(RoundedRectangle(cornerRadius: 8))
  93. }
  94. }.padding(5)
  95. }
  96. }
  97. var body: some View {
  98. Form {
  99. Section(header: Text("Schedule")) {
  100. if !state.items.isEmpty {
  101. basalScheduleChart.padding(.vertical)
  102. }
  103. list
  104. }.listRowBackground(Color.chart)
  105. Section {
  106. HStack {
  107. Text("Total")
  108. .bold()
  109. .foregroundColor(.primary)
  110. Spacer()
  111. Text(rateFormatter.string(from: state.total as NSNumber) ?? "0")
  112. .foregroundColor(.primary) +
  113. Text(" U/day")
  114. .foregroundColor(.secondary)
  115. }
  116. }.listRowBackground(Color.chart)
  117. }
  118. .safeAreaInset(edge: .bottom, spacing: 30) { saveButton }
  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.calculateChartData()
  129. }
  130. .scrollContentBackground(.hidden).background(appState.trioBackgroundColor(for: colorScheme))
  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.calculateChartData()
  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(appState.trioBackgroundColor(for: colorScheme))
  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.calculateChartData()
  222. }
  223. }
  224. }