BasalProfileEditorRootView.swift 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  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. if !state.canAdd {
  100. Section {
  101. VStack(alignment: .leading) {
  102. Text(
  103. "Basal profile covers 24 hours. You cannot add more rates. Please remove or adjust existing rates to make space."
  104. ).bold()
  105. }
  106. }.listRowBackground(Color.tabBar)
  107. }
  108. Section(header: Text("Schedule")) {
  109. if !state.items.isEmpty {
  110. basalScheduleChart.padding(.vertical)
  111. }
  112. list
  113. }.listRowBackground(Color.chart)
  114. Section {
  115. HStack {
  116. Text("Total")
  117. .bold()
  118. .foregroundColor(.primary)
  119. Spacer()
  120. Text(rateFormatter.string(from: state.total as NSNumber) ?? "0")
  121. .foregroundColor(.primary) +
  122. Text(" U/day")
  123. .foregroundColor(.secondary)
  124. }
  125. }.listRowBackground(Color.chart)
  126. }
  127. .safeAreaInset(edge: .bottom, spacing: 30) { saveButton }
  128. .alert(isPresented: $state.showAlert) {
  129. Alert(
  130. title: Text("Unable to Save"),
  131. message: Text("Trio could not communicate with your pump. Changes to your basal profile were not saved."),
  132. dismissButton: .default(Text("Close"))
  133. )
  134. }
  135. .onChange(of: state.items) {
  136. state.calcTotal()
  137. state.calculateChartData()
  138. }
  139. .scrollContentBackground(.hidden).background(appState.trioBackgroundColor(for: colorScheme))
  140. .navigationTitle("Basal Profile")
  141. .navigationBarTitleDisplayMode(.automatic)
  142. .toolbar(content: {
  143. if state.items.isNotEmpty {
  144. ToolbarItem(placement: .topBarTrailing) {
  145. EditButton()
  146. }
  147. }
  148. ToolbarItem(placement: .topBarTrailing) {
  149. Button(action: { state.add() }) { Image(systemName: "plus") }.disabled(!state.canAdd)
  150. }
  151. })
  152. .environment(\.editMode, $editMode)
  153. .onAppear {
  154. configureView()
  155. state.validate()
  156. state.calculateChartData()
  157. }
  158. }
  159. private func pickers(for index: Int) -> some View {
  160. Form {
  161. Section {
  162. Picker(selection: $state.items[index].rateIndex, label: Text("Rate")) {
  163. ForEach(0 ..< state.rateValues.count, id: \.self) { i in
  164. Text(
  165. (
  166. self.rateFormatter
  167. .string(from: state.rateValues[i] as NSNumber) ?? ""
  168. ) + " U/hr"
  169. ).tag(i)
  170. }
  171. }
  172. .onChange(of: state.items[index].rateIndex, { state.calcTotal() })
  173. }.listRowBackground(Color.chart)
  174. Section {
  175. Picker(selection: $state.items[index].timeIndex, label: Text("Time")) {
  176. ForEach(state.availableTimeIndices(index), id: \.self) { i in
  177. Text(
  178. self.dateFormatter
  179. .string(from: Date(
  180. timeIntervalSince1970: state
  181. .timeValues[i]
  182. ))
  183. ).tag(i)
  184. }
  185. }
  186. .onChange(of: state.items[index].timeIndex, { state.calcTotal() })
  187. }.listRowBackground(Color.chart)
  188. }
  189. .padding(.top)
  190. .scrollContentBackground(.hidden).background(appState.trioBackgroundColor(for: colorScheme))
  191. .navigationTitle("Set Rate")
  192. .navigationBarTitleDisplayMode(.automatic)
  193. }
  194. private var list: some View {
  195. List {
  196. ForEach(state.items.indexed(), id: \.1.id) { index, item in
  197. NavigationLink(destination: pickers(for: index)) {
  198. HStack {
  199. Text("Rate").foregroundColor(.secondary)
  200. Text(
  201. "\(rateFormatter.string(from: state.rateValues[item.rateIndex] as NSNumber) ?? "0") U/hr"
  202. )
  203. Spacer()
  204. Text("starts at").foregroundColor(.secondary)
  205. Text(
  206. "\(dateFormatter.string(from: Date(timeIntervalSince1970: state.timeValues[item.timeIndex])))"
  207. )
  208. }
  209. }
  210. .moveDisabled(true)
  211. }
  212. .onDelete(perform: onDelete)
  213. }
  214. }
  215. private func onDelete(offsets: IndexSet) {
  216. state.items.remove(atOffsets: offsets)
  217. state.validate()
  218. state.calculateChartData()
  219. }
  220. }
  221. }