TargetsEditorRootView.swift 9.4 KB

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