BasalProfileEditorRootView.swift 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  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(action: {
  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. }
  87. .frame(width: UIScreen.main.bounds.width * 0.9, alignment: .center)
  88. .padding(10)
  89. })
  90. .frame(width: UIScreen.main.bounds.width * 0.9, height: 40, alignment: .center)
  91. .disabled(shouldDisableButton)
  92. .background(shouldDisableButton ? Color(.systemGray4) : Color(.systemBlue))
  93. .tint(.white)
  94. .clipShape(RoundedRectangle(cornerRadius: 8))
  95. }
  96. }.padding(5)
  97. }
  98. }
  99. var body: some View {
  100. Form {
  101. if !state.canAdd {
  102. Section {
  103. VStack(alignment: .leading) {
  104. Text(
  105. "Basal profile covers 24 hours. You cannot add more rates. Please remove or adjust existing rates to make space."
  106. ).bold()
  107. }
  108. }.listRowBackground(Color.tabBar)
  109. }
  110. Section(header: Text("Schedule")) {
  111. if !state.items.isEmpty {
  112. basalScheduleChart.padding(.vertical)
  113. }
  114. list
  115. }.listRowBackground(Color.chart)
  116. Section {
  117. HStack {
  118. Text("Total")
  119. .bold()
  120. .foregroundColor(.primary)
  121. Spacer()
  122. Text(rateFormatter.string(from: state.total as NSNumber) ?? "0")
  123. .foregroundColor(.primary) +
  124. Text(" U/day")
  125. .foregroundColor(.secondary)
  126. }
  127. }.listRowBackground(Color.chart)
  128. Section {} header: {
  129. VStack(alignment: .leading, spacing: 10) {
  130. HStack {
  131. Image(systemName: "note.text.badge.plus").foregroundStyle(.primary)
  132. Text("Add an entry by tapping 'Add Rate +' in the top right-hand corner of the screen.")
  133. }
  134. HStack {
  135. Image(systemName: "hand.draw.fill").foregroundStyle(.primary)
  136. Text("Swipe to delete a single entry. Tap on it, to edit its time or rate.")
  137. }
  138. }
  139. .textCase(nil)
  140. }
  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.calculateChartData()
  153. }
  154. .scrollContentBackground(.hidden).background(appState.trioBackgroundColor(for: colorScheme))
  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() }) {
  165. HStack {
  166. Text("Add Rate")
  167. Image(systemName: "plus")
  168. }
  169. }.disabled(!state.canAdd)
  170. }
  171. })
  172. .environment(\.editMode, $editMode)
  173. .onAppear {
  174. configureView()
  175. state.validate()
  176. state.calculateChartData()
  177. }
  178. }
  179. private func pickers(for index: Int) -> some View {
  180. Form {
  181. Section {
  182. Picker(selection: $state.items[index].rateIndex, label: Text("Rate")) {
  183. ForEach(0 ..< state.rateValues.count, id: \.self) { i in
  184. Text(
  185. (
  186. self.rateFormatter
  187. .string(from: state.rateValues[i] as NSNumber) ?? ""
  188. ) + " U/hr"
  189. ).tag(i)
  190. }
  191. }
  192. .onChange(of: state.items[index].rateIndex, { state.calcTotal() })
  193. }.listRowBackground(Color.chart)
  194. Section {
  195. Picker(selection: $state.items[index].timeIndex, label: Text("Time")) {
  196. ForEach(state.availableTimeIndices(index), id: \.self) { i in
  197. Text(
  198. self.dateFormatter
  199. .string(from: Date(
  200. timeIntervalSince1970: state
  201. .timeValues[i]
  202. ))
  203. ).tag(i)
  204. }
  205. }
  206. .onChange(of: state.items[index].timeIndex, { state.calcTotal() })
  207. }.listRowBackground(Color.chart)
  208. }
  209. .padding(.top)
  210. .scrollContentBackground(.hidden).background(appState.trioBackgroundColor(for: colorScheme))
  211. .navigationTitle("Set Rate")
  212. .navigationBarTitleDisplayMode(.automatic)
  213. }
  214. private var list: some View {
  215. List {
  216. ForEach(state.items.indexed(), id: \.1.id) { index, item in
  217. NavigationLink(destination: pickers(for: index)) {
  218. HStack {
  219. Text("Rate").foregroundColor(.secondary)
  220. Text(
  221. "\(rateFormatter.string(from: state.rateValues[item.rateIndex] as NSNumber) ?? "0") U/hr"
  222. )
  223. Spacer()
  224. Text("starts at").foregroundColor(.secondary)
  225. Text(
  226. "\(dateFormatter.string(from: Date(timeIntervalSince1970: state.timeValues[item.timeIndex])))"
  227. )
  228. }
  229. }
  230. .moveDisabled(true)
  231. }
  232. .onDelete(perform: onDelete)
  233. }
  234. }
  235. private func onDelete(offsets: IndexSet) {
  236. state.items.remove(atOffsets: offsets)
  237. state.validate()
  238. state.calculateChartData()
  239. }
  240. }
  241. }