TargetsEditorRootView.swift 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  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. HStack {
  29. Button {
  30. let impactHeavy = UIImpactFeedbackGenerator(style: .heavy)
  31. impactHeavy.impactOccurred()
  32. state.save()
  33. // deactivate saving display after 1.25 seconds
  34. DispatchQueue.main.asyncAfter(deadline: .now() + 1.25) {
  35. state.shouldDisplaySaving = false
  36. }
  37. } label: {
  38. HStack {
  39. if state.shouldDisplaySaving {
  40. ProgressView().padding(.trailing, 10)
  41. }
  42. Text(state.shouldDisplaySaving ? "Saving..." : "Save")
  43. }.padding(10)
  44. }
  45. }
  46. .frame(width: UIScreen.main.bounds.width * 0.9, 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("Target Glucose")
  65. .navigationBarTitleDisplayMode(.automatic)
  66. .toolbar(content: {
  67. ToolbarItem(placement: .topBarTrailing) {
  68. EditButton()
  69. }
  70. ToolbarItem(placement: .topBarTrailing) {
  71. addButton
  72. }
  73. })
  74. .environment(\.editMode, $editMode)
  75. .onAppear {
  76. state.validate()
  77. }
  78. }
  79. private func pickers(for index: Int) -> some View {
  80. Form {
  81. Section {
  82. Picker(
  83. selection: $state.items[index].lowIndex,
  84. label: Text("Target ")
  85. ) {
  86. ForEach(0 ..< state.rateValues.count, id: \.self) { i in
  87. Text(state.units == .mgdL ? state.rateValues[i].description : state.rateValues[i].formattedAsMmolL)
  88. .tag(i)
  89. }
  90. }
  91. }.listRowBackground(Color.chart)
  92. Section {
  93. Picker(selection: $state.items[index].timeIndex, label: Text("Time")) {
  94. ForEach(0 ..< state.timeValues.count, id: \.self) { i in
  95. Text(
  96. self.dateFormatter
  97. .string(from: Date(
  98. timeIntervalSince1970: state
  99. .timeValues[i]
  100. ))
  101. ).tag(i)
  102. }
  103. }
  104. }.listRowBackground(Color.chart)
  105. }
  106. .padding(.top)
  107. .scrollContentBackground(.hidden).background(appState.trioBackgroundColor(for: colorScheme))
  108. .navigationTitle("Set Target")
  109. .navigationBarTitleDisplayMode(.automatic)
  110. }
  111. private var list: some View {
  112. List {
  113. chart.padding(.vertical)
  114. ForEach(state.items.indexed(), id: \.1.id) { index, item in
  115. NavigationLink(destination: pickers(for: index)) {
  116. HStack {
  117. Text(
  118. state.units == .mgdL ? state.rateValues[item.lowIndex].description : state
  119. .rateValues[item.lowIndex].formattedAsMmolL
  120. )
  121. Text("\(state.units.rawValue)").foregroundColor(.secondary)
  122. Spacer()
  123. Text("starts at").foregroundColor(.secondary)
  124. Text(
  125. "\(dateFormatter.string(from: Date(timeIntervalSince1970: state.timeValues[item.timeIndex])))"
  126. )
  127. }
  128. }
  129. .moveDisabled(true)
  130. }
  131. .onDelete(perform: onDelete)
  132. }
  133. }
  134. let chartScale = Calendar.current
  135. .date(from: DateComponents(year: 2001, month: 01, day: 01, hour: 0, minute: 0, second: 0))
  136. var chart: some View {
  137. Chart {
  138. ForEach(state.items.indexed(), id: \.1.id) { index, item in
  139. let displayValue = state.units == .mgdL ? state.rateValues[item.lowIndex].description : state
  140. .rateValues[item.lowIndex].formattedAsMmolL
  141. // Convert from string so we know we use the same math as the rest of Trio.
  142. // However, swift doesn't understand languages that use comma as decimal delminator
  143. let displayValueFloat = Double(displayValue.replacingOccurrences(of: ",", with: "."))
  144. let tzOffset = TimeZone.current.secondsFromGMT() * -1
  145. let startDate = Date(timeIntervalSinceReferenceDate: state.timeValues[item.timeIndex])
  146. .addingTimeInterval(TimeInterval(tzOffset))
  147. let endDate = state.items
  148. .count > index + 1 ?
  149. Date(timeIntervalSinceReferenceDate: state.timeValues[state.items[index + 1].timeIndex])
  150. .addingTimeInterval(TimeInterval(tzOffset)) :
  151. Date(timeIntervalSinceReferenceDate: state.timeValues.last!).addingTimeInterval(30 * 60)
  152. .addingTimeInterval(TimeInterval(tzOffset))
  153. LineMark(x: .value("End Date", startDate), y: .value("Target", displayValueFloat ?? 0.0))
  154. .lineStyle(.init(lineWidth: 1)).foregroundStyle(Color.green.gradient)
  155. LineMark(x: .value("Start Date", endDate), y: .value("Target", displayValueFloat ?? 0.0))
  156. .lineStyle(.init(lineWidth: 1)).foregroundStyle(Color.green.gradient)
  157. }
  158. }
  159. .chartXAxis {
  160. AxisMarks(values: .automatic(desiredCount: 6)) { _ in
  161. AxisValueLabel(format: .dateTime.hour())
  162. AxisGridLine(centered: true, stroke: StrokeStyle(lineWidth: 1, dash: [2, 4]))
  163. }
  164. }
  165. .chartXScale(
  166. domain: Calendar.current.startOfDay(for: chartScale!) ... Calendar.current.startOfDay(for: chartScale!)
  167. .addingTimeInterval(60 * 60 * 24)
  168. )
  169. .chartYAxis {
  170. AxisMarks(values: .automatic(desiredCount: 4)) { _ in
  171. AxisValueLabel()
  172. AxisGridLine(centered: true, stroke: StrokeStyle(lineWidth: 1, dash: [2, 4]))
  173. }
  174. }.chartYScale(domain: (state.units == .mgdL ? 72 : 4.0) ... (state.units == .mgdL ? 180 : 10))
  175. }
  176. private var addButton: some View {
  177. guard state.canAdd else {
  178. return AnyView(EmptyView())
  179. }
  180. switch editMode {
  181. case .inactive:
  182. return AnyView(Button(action: onAdd) { Image(systemName: "plus") })
  183. default:
  184. return AnyView(EmptyView())
  185. }
  186. }
  187. func onAdd() {
  188. state.add()
  189. }
  190. private func onDelete(offsets: IndexSet) {
  191. state.items.remove(atOffsets: offsets)
  192. state.validate()
  193. }
  194. }
  195. }