TargetsEditorRootView.swift 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  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. if state.items.isNotEmpty {
  81. ToolbarItem(placement: .topBarTrailing) {
  82. EditButton()
  83. }
  84. }
  85. ToolbarItem(placement: .topBarTrailing) {
  86. Button(action: { state.add() }) {
  87. HStack {
  88. Text("Add Target")
  89. Image(systemName: "plus")
  90. }
  91. }.disabled(!state.canAdd)
  92. }
  93. })
  94. .environment(\.editMode, $editMode)
  95. .onAppear {
  96. state.validate()
  97. }
  98. }
  99. private func pickers(for index: Int) -> some View {
  100. Form {
  101. if !state.canAdd {
  102. Section {
  103. VStack(alignment: .leading) {
  104. Text(
  105. "Target Glucose covered for 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 {
  111. Picker(
  112. selection: $state.items[index].lowIndex,
  113. label: Text("Target ")
  114. ) {
  115. ForEach(0 ..< state.rateValues.count, id: \.self) { i in
  116. Text(state.units == .mgdL ? state.rateValues[i].description : state.rateValues[i].formattedAsMmolL)
  117. .tag(i)
  118. }
  119. }
  120. }.listRowBackground(Color.chart)
  121. Section {
  122. Picker(selection: $state.items[index].timeIndex, label: Text("Time")) {
  123. ForEach(0 ..< state.timeValues.count, id: \.self) { i in
  124. Text(
  125. self.dateFormatter
  126. .string(from: Date(
  127. timeIntervalSince1970: state
  128. .timeValues[i]
  129. ))
  130. ).tag(i)
  131. }
  132. }
  133. }.listRowBackground(Color.chart)
  134. }
  135. .padding(.top)
  136. .scrollContentBackground(.hidden).background(appState.trioBackgroundColor(for: colorScheme))
  137. .navigationTitle("Set Target")
  138. .navigationBarTitleDisplayMode(.automatic)
  139. }
  140. private var list: some View {
  141. List {
  142. chart.padding(.vertical)
  143. ForEach(state.items.indexed(), id: \.1.id) { index, item in
  144. NavigationLink(destination: pickers(for: index)) {
  145. HStack {
  146. Text(
  147. state.units == .mgdL ? state.rateValues[item.lowIndex].description : state
  148. .rateValues[item.lowIndex].formattedAsMmolL
  149. )
  150. Text("\(state.units.rawValue)").foregroundColor(.secondary)
  151. Spacer()
  152. Text("starts at").foregroundColor(.secondary)
  153. Text(
  154. "\(dateFormatter.string(from: Date(timeIntervalSince1970: state.timeValues[item.timeIndex])))"
  155. )
  156. }
  157. }
  158. .moveDisabled(true)
  159. }
  160. .onDelete(perform: onDelete)
  161. }
  162. }
  163. let chartScale = Calendar.current
  164. .date(from: DateComponents(year: 2001, month: 01, day: 01, hour: 0, minute: 0, second: 0))
  165. var chart: some View {
  166. Chart {
  167. ForEach(state.items.indexed(), id: \.1.id) { index, item in
  168. let displayValue = state.units == .mgdL ? state.rateValues[item.lowIndex].description : state
  169. .rateValues[item.lowIndex].formattedAsMmolL
  170. // Convert from string so we know we use the same math as the rest of Trio.
  171. // However, swift doesn't understand languages that use comma as decimal delminator
  172. let displayValueFloat = Double(displayValue.replacingOccurrences(of: ",", with: "."))
  173. let tzOffset = TimeZone.current.secondsFromGMT() * -1
  174. let startDate = Date(timeIntervalSinceReferenceDate: state.timeValues[item.timeIndex])
  175. .addingTimeInterval(TimeInterval(tzOffset))
  176. let endDate = state.items
  177. .count > index + 1 ?
  178. Date(timeIntervalSinceReferenceDate: state.timeValues[state.items[index + 1].timeIndex])
  179. .addingTimeInterval(TimeInterval(tzOffset)) :
  180. Date(timeIntervalSinceReferenceDate: state.timeValues.last!).addingTimeInterval(30 * 60)
  181. .addingTimeInterval(TimeInterval(tzOffset))
  182. LineMark(x: .value("End Date", startDate), y: .value("Target", displayValueFloat ?? 0.0))
  183. .lineStyle(.init(lineWidth: 1)).foregroundStyle(Color.green.gradient)
  184. LineMark(x: .value("Start Date", endDate), y: .value("Target", displayValueFloat ?? 0.0))
  185. .lineStyle(.init(lineWidth: 1)).foregroundStyle(Color.green.gradient)
  186. }
  187. }
  188. .chartXAxis {
  189. AxisMarks(values: .automatic(desiredCount: 6)) { _ in
  190. AxisValueLabel(format: .dateTime.hour())
  191. AxisGridLine(centered: true, stroke: StrokeStyle(lineWidth: 1, dash: [2, 4]))
  192. }
  193. }
  194. .chartXScale(
  195. domain: Calendar.current.startOfDay(for: chartScale!) ... Calendar.current.startOfDay(for: chartScale!)
  196. .addingTimeInterval(60 * 60 * 24)
  197. )
  198. .chartYAxis {
  199. AxisMarks(values: .automatic(desiredCount: 4)) { _ in
  200. AxisValueLabel()
  201. AxisGridLine(centered: true, stroke: StrokeStyle(lineWidth: 1, dash: [2, 4]))
  202. }
  203. }.chartYScale(domain: (state.units == .mgdL ? 72 : 4.0) ... (state.units == .mgdL ? 180 : 10))
  204. }
  205. private func onDelete(offsets: IndexSet) {
  206. state.items.remove(atOffsets: offsets)
  207. state.validate()
  208. }
  209. }
  210. }