TargetsEditorRootView.swift 9.6 KB

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