CarbRatioEditorRootView.swift 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  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. if !state.canAdd {
  88. Section {
  89. VStack(alignment: .leading) {
  90. Text(
  91. "Carb Ratios cover 24 hours. You cannot add more rates. Please remove or adjust existing rates to make space."
  92. ).bold()
  93. }
  94. }.listRowBackground(Color.tabBar)
  95. }
  96. Section(header: Text("Schedule")) {
  97. list
  98. }.listRowBackground(Color.chart)
  99. }
  100. .safeAreaInset(edge: .bottom, spacing: 30) { saveButton }
  101. .scrollContentBackground(.hidden).background(color)
  102. .onAppear(perform: configureView)
  103. .navigationTitle("Carb Ratios")
  104. .navigationBarTitleDisplayMode(.automatic)
  105. .toolbar(content: {
  106. if state.items.isNotEmpty {
  107. ToolbarItem(placement: .topBarTrailing) {
  108. EditButton()
  109. }
  110. }
  111. ToolbarItem(placement: .topBarTrailing) {
  112. Button(action: { state.add() }) { Image(systemName: "plus") }.disabled(!state.canAdd)
  113. }
  114. })
  115. .environment(\.editMode, $editMode)
  116. .onAppear {
  117. state.validate()
  118. }
  119. }
  120. private func pickers(for index: Int) -> some View {
  121. Form {
  122. Section {
  123. Picker(selection: $state.items[index].rateIndex, label: Text("Ratio")) {
  124. ForEach(0 ..< state.rateValues.count, id: \.self) { i in
  125. Text(
  126. (
  127. self.rateFormatter
  128. .string(from: state.rateValues[i] as NSNumber) ?? ""
  129. ) + " g/U"
  130. ).tag(i)
  131. }
  132. }
  133. }.listRowBackground(Color.chart)
  134. Section {
  135. Picker(selection: $state.items[index].timeIndex, label: Text("Time")) {
  136. ForEach(0 ..< state.timeValues.count, id: \.self) { i in
  137. Text(
  138. self.dateFormatter
  139. .string(from: Date(
  140. timeIntervalSince1970: state
  141. .timeValues[i]
  142. ))
  143. ).tag(i)
  144. }
  145. }
  146. }.listRowBackground(Color.chart)
  147. }
  148. .padding(.top)
  149. .scrollContentBackground(.hidden).background(color)
  150. .navigationTitle("Set Ratio")
  151. .navigationBarTitleDisplayMode(.automatic)
  152. }
  153. private var list: some View {
  154. List {
  155. chart.padding(.vertical)
  156. ForEach(state.items.indexed(), id: \.1.id) { index, item in
  157. NavigationLink(destination: pickers(for: index)) {
  158. HStack {
  159. Text("Ratio").foregroundColor(.secondary)
  160. Text(
  161. "\(rateFormatter.string(from: state.rateValues[item.rateIndex] as NSNumber) ?? "0") g/U"
  162. )
  163. Spacer()
  164. Text("starts at").foregroundColor(.secondary)
  165. Text(
  166. "\(dateFormatter.string(from: Date(timeIntervalSince1970: state.timeValues[item.timeIndex])))"
  167. )
  168. }
  169. }
  170. .moveDisabled(true)
  171. }
  172. .onDelete(perform: onDelete)
  173. }
  174. }
  175. let chartScale = Calendar.current
  176. .date(from: DateComponents(year: 2001, month: 01, day: 01, hour: 0, minute: 0, second: 0))
  177. var chart: some View {
  178. Chart {
  179. ForEach(state.items.indexed(), id: \.1.id) { index, item in
  180. let displayValue = state.rateValues[item.rateIndex]
  181. let tzOffset = TimeZone.current.secondsFromGMT() * -1
  182. let startDate = Date(timeIntervalSinceReferenceDate: state.timeValues[item.timeIndex])
  183. .addingTimeInterval(TimeInterval(tzOffset))
  184. let endDate = state.items
  185. .count > index + 1 ?
  186. Date(timeIntervalSinceReferenceDate: state.timeValues[state.items[index + 1].timeIndex])
  187. .addingTimeInterval(TimeInterval(tzOffset)) :
  188. Date(timeIntervalSinceReferenceDate: state.timeValues.last!).addingTimeInterval(30 * 60)
  189. .addingTimeInterval(TimeInterval(tzOffset))
  190. RectangleMark(
  191. xStart: .value("start", startDate),
  192. xEnd: .value("end", endDate),
  193. yStart: .value("rate-start", displayValue),
  194. yEnd: .value("rate-end", 0)
  195. ).foregroundStyle(
  196. .linearGradient(
  197. colors: [
  198. Color.insulin.opacity(0.6),
  199. Color.insulin.opacity(0.1)
  200. ],
  201. startPoint: .bottom,
  202. endPoint: .top
  203. )
  204. ).alignsMarkStylesWithPlotArea()
  205. LineMark(x: .value("End Date", startDate), y: .value("Ratio", displayValue))
  206. .lineStyle(.init(lineWidth: 1)).foregroundStyle(Color.insulin)
  207. LineMark(x: .value("Start Date", endDate), y: .value("Ratio", displayValue))
  208. .lineStyle(.init(lineWidth: 1)).foregroundStyle(Color.insulin)
  209. }
  210. }
  211. .chartXAxis {
  212. AxisMarks(values: .automatic(desiredCount: 6)) { _ in
  213. AxisValueLabel(format: .dateTime.hour())
  214. AxisGridLine(centered: true, stroke: StrokeStyle(lineWidth: 1, dash: [2, 4]))
  215. }
  216. }
  217. .chartXScale(
  218. domain: Calendar.current.startOfDay(for: chartScale!) ... Calendar.current.startOfDay(for: chartScale!)
  219. .addingTimeInterval(60 * 60 * 24)
  220. )
  221. .chartYAxis {
  222. AxisMarks(values: .automatic(desiredCount: 4)) { _ in
  223. AxisValueLabel()
  224. AxisGridLine(centered: true, stroke: StrokeStyle(lineWidth: 1, dash: [2, 4]))
  225. }
  226. }
  227. }
  228. private func onDelete(offsets: IndexSet) {
  229. state.items.remove(atOffsets: offsets)
  230. state.validate()
  231. }
  232. }
  233. }