TargetsEditorRootView.swift 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. import Charts
  2. import SwiftUI
  3. import Swinject
  4. extension TargetsEditor {
  5. struct RootView: BaseView {
  6. let resolver: Resolver
  7. @StateObject var state = StateModel()
  8. @State private var editMode = EditMode.inactive
  9. @Environment(\.colorScheme) var colorScheme
  10. @Environment(AppState.self) var appState
  11. private var dateFormatter: DateFormatter {
  12. let formatter = DateFormatter()
  13. formatter.timeZone = TimeZone(secondsFromGMT: 0)
  14. formatter.timeStyle = .short
  15. return formatter
  16. }
  17. var saveButton: some View {
  18. ZStack {
  19. let shouldDisableButton = state.shouldDisplaySaving || state.items.isEmpty || !state.hasChanges
  20. Rectangle()
  21. .frame(width: UIScreen.main.bounds.width, height: 65)
  22. .foregroundStyle(colorScheme == .dark ? Color.bgDarkerDarkBlue : Color.white)
  23. .background(.thinMaterial)
  24. .opacity(0.8)
  25. .clipShape(Rectangle())
  26. Group {
  27. HStack {
  28. Button(action: {
  29. let impactHeavy = UIImpactFeedbackGenerator(style: .heavy)
  30. impactHeavy.impactOccurred()
  31. state.save()
  32. // deactivate saving display after 1.25 seconds
  33. DispatchQueue.main.asyncAfter(deadline: .now() + 1.25) {
  34. state.shouldDisplaySaving = false
  35. }
  36. }, label: {
  37. HStack {
  38. if state.shouldDisplaySaving {
  39. ProgressView().padding(.trailing, 10)
  40. }
  41. Text(state.shouldDisplaySaving ? "Saving..." : "Save")
  42. }
  43. .frame(width: UIScreen.main.bounds.width * 0.9, alignment: .center)
  44. .padding(10)
  45. })
  46. .frame(width: UIScreen.main.bounds.width * 0.9, height: 40, alignment: .center)
  47. .disabled(shouldDisableButton)
  48. .background(shouldDisableButton ? Color(.systemGray4) : Color(.systemBlue))
  49. .tint(.white)
  50. .clipShape(RoundedRectangle(cornerRadius: 8))
  51. }
  52. }.padding(5)
  53. }
  54. }
  55. var body: some View {
  56. Form {
  57. Section(header: Text("Schedule")) {
  58. list
  59. }.listRowBackground(Color.chart)
  60. Section {} header: {
  61. VStack(alignment: .leading, spacing: 10) {
  62. HStack {
  63. Image(systemName: "note.text.badge.plus").foregroundStyle(.primary)
  64. Text("Add an entry by tapping 'Add Target +' in the top right-hand corner of the screen.")
  65. }
  66. HStack {
  67. Image(systemName: "hand.draw.fill").foregroundStyle(.primary)
  68. Text("Swipe to delete a single entry. Tap on it, to edit its time or rate.")
  69. }
  70. }
  71. .textCase(nil)
  72. }
  73. }
  74. .safeAreaInset(edge: .bottom, spacing: 30) { saveButton }
  75. .scrollContentBackground(.hidden).background(appState.trioBackgroundColor(for: colorScheme))
  76. .onAppear(perform: configureView)
  77. .navigationTitle("Glucose Targets")
  78. .navigationBarTitleDisplayMode(.automatic)
  79. .toolbar(content: {
  80. ToolbarItem(placement: .topBarTrailing) {
  81. Button(action: { state.add() }) {
  82. HStack {
  83. Text("Add Target")
  84. Image(systemName: "plus")
  85. }
  86. }.disabled(!state.canAdd)
  87. }
  88. })
  89. .environment(\.editMode, $editMode)
  90. .onAppear {
  91. state.validate()
  92. }
  93. }
  94. private func pickers(for index: Int) -> some View {
  95. Form {
  96. if !state.canAdd {
  97. Section {
  98. VStack(alignment: .leading) {
  99. Text(
  100. "Target Glucose covered for 24 hours. You cannot add more rates. Please remove or adjust existing rates to make space."
  101. ).bold()
  102. }
  103. }.listRowBackground(Color.tabBar)
  104. }
  105. Section {
  106. Picker(
  107. selection: $state.items[index].lowIndex,
  108. label: Text("Target ")
  109. ) {
  110. ForEach(0 ..< state.rateValues.count, id: \.self) { i in
  111. Text(state.units == .mgdL ? state.rateValues[i].description : state.rateValues[i].formattedAsMmolL)
  112. .tag(i)
  113. }
  114. }
  115. }.listRowBackground(Color.chart)
  116. Section {
  117. Picker(selection: $state.items[index].timeIndex, label: Text("Time")) {
  118. ForEach(0 ..< state.timeValues.count, id: \.self) { i in
  119. Text(
  120. self.dateFormatter
  121. .string(from: Date(
  122. timeIntervalSince1970: state
  123. .timeValues[i]
  124. ))
  125. ).tag(i)
  126. }
  127. }
  128. }.listRowBackground(Color.chart)
  129. }
  130. .padding(.top)
  131. .scrollContentBackground(.hidden).background(appState.trioBackgroundColor(for: colorScheme))
  132. .navigationTitle("Set Target")
  133. .navigationBarTitleDisplayMode(.automatic)
  134. }
  135. private var list: some View {
  136. List {
  137. chart.padding(.vertical)
  138. ForEach(state.items.indexed(), id: \.1.id) { index, item in
  139. NavigationLink(destination: pickers(for: index)) {
  140. HStack {
  141. Text(
  142. state.units == .mgdL ? state.rateValues[item.lowIndex].description : state
  143. .rateValues[item.lowIndex].formattedAsMmolL
  144. )
  145. Text("\(state.units.rawValue)").foregroundColor(.secondary)
  146. Spacer()
  147. Text("starts at").foregroundColor(.secondary)
  148. Text(
  149. "\(dateFormatter.string(from: Date(timeIntervalSince1970: state.timeValues[item.timeIndex])))"
  150. )
  151. }
  152. }
  153. .moveDisabled(true)
  154. }
  155. .onDelete(perform: onDelete)
  156. }
  157. }
  158. let chartScale = Calendar.current
  159. .date(from: DateComponents(year: 2001, month: 01, day: 01, hour: 0, minute: 0, second: 0))
  160. var chart: some View {
  161. Chart {
  162. ForEach(state.items.indexed(), id: \.1.id) { index, item in
  163. let displayValue = state.units == .mgdL ? state.rateValues[item.lowIndex].description : state
  164. .rateValues[item.lowIndex].formattedAsMmolL
  165. // Convert from string so we know we use the same math as the rest of Trio.
  166. // However, swift doesn't understand languages that use comma as decimal delminator
  167. let displayValueFloat = Double(displayValue.replacingOccurrences(of: ",", with: "."))
  168. let tzOffset = TimeZone.current.secondsFromGMT() * -1
  169. let startDate = Date(timeIntervalSinceReferenceDate: state.timeValues[item.timeIndex])
  170. .addingTimeInterval(TimeInterval(tzOffset))
  171. let endDate = state.items
  172. .count > index + 1 ?
  173. Date(timeIntervalSinceReferenceDate: state.timeValues[state.items[index + 1].timeIndex])
  174. .addingTimeInterval(TimeInterval(tzOffset)) :
  175. Date(timeIntervalSinceReferenceDate: state.timeValues.last!).addingTimeInterval(30 * 60)
  176. .addingTimeInterval(TimeInterval(tzOffset))
  177. LineMark(x: .value("End Date", startDate), y: .value("Target", displayValueFloat ?? 0.0))
  178. .lineStyle(.init(lineWidth: 1)).foregroundStyle(Color.green.gradient)
  179. LineMark(x: .value("Start Date", endDate), y: .value("Target", displayValueFloat ?? 0.0))
  180. .lineStyle(.init(lineWidth: 1)).foregroundStyle(Color.green.gradient)
  181. }
  182. }
  183. .chartXAxis {
  184. AxisMarks(values: .automatic(desiredCount: 6)) { _ in
  185. AxisValueLabel(format: .dateTime.hour())
  186. AxisGridLine(centered: true, stroke: StrokeStyle(lineWidth: 1, dash: [2, 4]))
  187. }
  188. }
  189. .chartXScale(
  190. domain: Calendar.current.startOfDay(for: chartScale!) ... Calendar.current.startOfDay(for: chartScale!)
  191. .addingTimeInterval(60 * 60 * 24)
  192. )
  193. .chartYAxis {
  194. AxisMarks(values: .automatic(desiredCount: 4)) { _ in
  195. AxisValueLabel()
  196. AxisGridLine(centered: true, stroke: StrokeStyle(lineWidth: 1, dash: [2, 4]))
  197. }
  198. }.chartYScale(domain: (state.units == .mgdL ? 72 : 4.0) ... (state.units == .mgdL ? 180 : 10))
  199. }
  200. private func onDelete(offsets: IndexSet) {
  201. state.items.remove(atOffsets: offsets)
  202. state.validate()
  203. }
  204. }
  205. }