CarbRatioEditorRootView.swift 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. import Charts
  2. import SwiftUI
  3. import Swinject
  4. extension CarbRatioEditor {
  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. private var rateFormatter: NumberFormatter {
  33. let formatter = NumberFormatter()
  34. formatter.numberStyle = .decimal
  35. return formatter
  36. }
  37. var saveButton: some View {
  38. ZStack {
  39. let shouldDisableButton = state.shouldDisplaySaving || state.items.isEmpty || !state.hasChanges
  40. Rectangle()
  41. .frame(width: UIScreen.main.bounds.width, height: 65)
  42. .foregroundStyle(colorScheme == .dark ? Color.bgDarkerDarkBlue : Color.white)
  43. .background(.thinMaterial)
  44. .opacity(0.8)
  45. .clipShape(Rectangle())
  46. Group {
  47. HStack {
  48. HStack {
  49. Button {
  50. let impactHeavy = UIImpactFeedbackGenerator(style: .heavy)
  51. impactHeavy.impactOccurred()
  52. state.save()
  53. // deactivate saving display after 1.25 seconds
  54. DispatchQueue.main.asyncAfter(deadline: .now() + 1.25) {
  55. state.shouldDisplaySaving = false
  56. }
  57. } label: {
  58. HStack {
  59. if state.shouldDisplaySaving {
  60. ProgressView().padding(.trailing, 10)
  61. }
  62. Text(state.shouldDisplaySaving ? "Saving..." : "Save")
  63. }.padding(10)
  64. }
  65. }
  66. .frame(width: UIScreen.main.bounds.width * 0.9, alignment: .center)
  67. .disabled(shouldDisableButton)
  68. .background(shouldDisableButton ? Color(.systemGray4) : Color(.systemBlue))
  69. .tint(.white)
  70. .clipShape(RoundedRectangle(cornerRadius: 8))
  71. }
  72. }.padding(5)
  73. }
  74. }
  75. var body: some View {
  76. Form {
  77. if let autotune = state.autotune, !state.settingsManager.settings.onlyAutotuneBasals {
  78. Section(header: Text("Autotune")) {
  79. HStack {
  80. Text("Calculated Ratio")
  81. Spacer()
  82. Text(rateFormatter.string(from: autotune.carbRatio as NSNumber) ?? "0")
  83. Text("g/U").foregroundColor(.secondary)
  84. }
  85. }.listRowBackground(Color.chart)
  86. }
  87. Section(header: Text("Schedule")) {
  88. list
  89. }.listRowBackground(Color.chart)
  90. }
  91. .safeAreaInset(edge: .bottom, spacing: 30) { saveButton }
  92. .scrollContentBackground(.hidden).background(color)
  93. .onAppear(perform: configureView)
  94. .navigationTitle("Carb Ratios")
  95. .navigationBarTitleDisplayMode(.automatic)
  96. .toolbar(content: {
  97. ToolbarItem(placement: .topBarTrailing) {
  98. EditButton()
  99. }
  100. ToolbarItem(placement: .topBarTrailing) {
  101. addButton
  102. }
  103. })
  104. .environment(\.editMode, $editMode)
  105. .onAppear {
  106. state.validate()
  107. }
  108. }
  109. private func pickers(for index: Int) -> some View {
  110. Form {
  111. Section {
  112. Picker(selection: $state.items[index].rateIndex, label: Text("Ratio")) {
  113. ForEach(0 ..< state.rateValues.count, id: \.self) { i in
  114. Text(
  115. (
  116. self.rateFormatter
  117. .string(from: state.rateValues[i] as NSNumber) ?? ""
  118. ) + " g/U"
  119. ).tag(i)
  120. }
  121. }
  122. }.listRowBackground(Color.chart)
  123. Section {
  124. Picker(selection: $state.items[index].timeIndex, label: Text("Time")) {
  125. ForEach(0 ..< state.timeValues.count, id: \.self) { i in
  126. Text(
  127. self.dateFormatter
  128. .string(from: Date(
  129. timeIntervalSince1970: state
  130. .timeValues[i]
  131. ))
  132. ).tag(i)
  133. }
  134. }
  135. }.listRowBackground(Color.chart)
  136. }
  137. .padding(.top)
  138. .scrollContentBackground(.hidden).background(color)
  139. .navigationTitle("Set Ratio")
  140. .navigationBarTitleDisplayMode(.automatic)
  141. }
  142. private var list: some View {
  143. List {
  144. chart.padding(.vertical)
  145. ForEach(state.items.indexed(), id: \.1.id) { index, item in
  146. NavigationLink(destination: pickers(for: index)) {
  147. HStack {
  148. Text("Ratio").foregroundColor(.secondary)
  149. Text(
  150. "\(rateFormatter.string(from: state.rateValues[item.rateIndex] as NSNumber) ?? "0") g/U"
  151. )
  152. Spacer()
  153. Text("starts at").foregroundColor(.secondary)
  154. Text(
  155. "\(dateFormatter.string(from: Date(timeIntervalSince1970: state.timeValues[item.timeIndex])))"
  156. )
  157. }
  158. }
  159. .moveDisabled(true)
  160. }
  161. .onDelete(perform: onDelete)
  162. }
  163. }
  164. let chartScale = Calendar.current
  165. .date(from: DateComponents(year: 2001, month: 01, day: 01, hour: 0, minute: 0, second: 0))
  166. var chart: some View {
  167. Chart {
  168. ForEach(state.items.indexed(), id: \.1.id) { index, item in
  169. let displayValue = state.rateValues[item.rateIndex]
  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. RectangleMark(
  180. xStart: .value("start", startDate),
  181. xEnd: .value("end", endDate),
  182. yStart: .value("rate-start", displayValue),
  183. yEnd: .value("rate-end", 0)
  184. ).foregroundStyle(
  185. .linearGradient(
  186. colors: [
  187. Color.insulin.opacity(0.6),
  188. Color.insulin.opacity(0.1)
  189. ],
  190. startPoint: .bottom,
  191. endPoint: .top
  192. )
  193. ).alignsMarkStylesWithPlotArea()
  194. LineMark(x: .value("End Date", startDate), y: .value("Ratio", displayValue))
  195. .lineStyle(.init(lineWidth: 1)).foregroundStyle(Color.insulin)
  196. LineMark(x: .value("Start Date", endDate), y: .value("Ratio", displayValue))
  197. .lineStyle(.init(lineWidth: 1)).foregroundStyle(Color.insulin)
  198. }
  199. }
  200. .chartXAxis {
  201. AxisMarks(values: .automatic(desiredCount: 6)) { _ in
  202. AxisValueLabel(format: .dateTime.hour())
  203. AxisGridLine(centered: true, stroke: StrokeStyle(lineWidth: 1, dash: [2, 4]))
  204. }
  205. }
  206. .chartXScale(
  207. domain: Calendar.current.startOfDay(for: chartScale!) ... Calendar.current.startOfDay(for: chartScale!)
  208. .addingTimeInterval(60 * 60 * 24)
  209. )
  210. .chartYAxis {
  211. AxisMarks(values: .automatic(desiredCount: 4)) { _ in
  212. AxisValueLabel()
  213. AxisGridLine(centered: true, stroke: StrokeStyle(lineWidth: 1, dash: [2, 4]))
  214. }
  215. }
  216. }
  217. private var addButton: some View {
  218. guard state.canAdd else {
  219. return AnyView(EmptyView())
  220. }
  221. switch editMode {
  222. case .inactive:
  223. return AnyView(Button(action: onAdd) { Image(systemName: "plus") })
  224. default:
  225. return AnyView(EmptyView())
  226. }
  227. }
  228. func onAdd() {
  229. state.add()
  230. }
  231. private func onDelete(offsets: IndexSet) {
  232. state.items.remove(atOffsets: offsets)
  233. state.validate()
  234. }
  235. }
  236. }