TargetsEditorRootView.swift 9.8 KB

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