CarbRatioEditorRootView.swift 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  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. @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. private var rateFormatter: NumberFormatter {
  18. let formatter = NumberFormatter()
  19. formatter.numberStyle = .decimal
  20. return formatter
  21. }
  22. var saveButton: some View {
  23. ZStack {
  24. let shouldDisableButton = state.shouldDisplaySaving || state.items.isEmpty || !state.hasChanges
  25. Rectangle()
  26. .frame(width: UIScreen.main.bounds.width, height: 65)
  27. .foregroundStyle(colorScheme == .dark ? Color.bgDarkerDarkBlue : Color.white)
  28. .background(.thinMaterial)
  29. .opacity(0.8)
  30. .clipShape(Rectangle())
  31. Group {
  32. HStack {
  33. HStack {
  34. Button {
  35. let impactHeavy = UIImpactFeedbackGenerator(style: .heavy)
  36. impactHeavy.impactOccurred()
  37. state.save()
  38. // deactivate saving display after 1.25 seconds
  39. DispatchQueue.main.asyncAfter(deadline: .now() + 1.25) {
  40. state.shouldDisplaySaving = false
  41. }
  42. } label: {
  43. HStack {
  44. if state.shouldDisplaySaving {
  45. ProgressView().padding(.trailing, 10)
  46. }
  47. Text(state.shouldDisplaySaving ? "Saving..." : "Save")
  48. }.padding(10)
  49. }
  50. }
  51. .frame(width: UIScreen.main.bounds.width * 0.9, alignment: .center)
  52. .disabled(shouldDisableButton)
  53. .background(shouldDisableButton ? Color(.systemGray4) : Color(.systemBlue))
  54. .tint(.white)
  55. .clipShape(RoundedRectangle(cornerRadius: 8))
  56. }
  57. }.padding(5)
  58. }
  59. }
  60. var body: some View {
  61. Form {
  62. if let autotune = state.autotune, !state.settingsManager.settings.onlyAutotuneBasals {
  63. Section(header: Text("Autotune")) {
  64. HStack {
  65. Text("Calculated Ratio")
  66. Spacer()
  67. Text(rateFormatter.string(from: autotune.carbRatio as NSNumber) ?? "0")
  68. Text("g/U").foregroundColor(.secondary)
  69. }
  70. }.listRowBackground(Color.chart)
  71. }
  72. Section(header: Text("Schedule")) {
  73. list
  74. }.listRowBackground(Color.chart)
  75. }
  76. .safeAreaInset(edge: .bottom, spacing: 30) { saveButton }
  77. .scrollContentBackground(.hidden).background(appState.trioBackgroundColor(for: colorScheme))
  78. .onAppear(perform: configureView)
  79. .navigationTitle("Carb Ratios")
  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(selection: $state.items[index].rateIndex, label: Text("Ratio")) {
  98. ForEach(0 ..< state.rateValues.count, id: \.self) { i in
  99. Text(
  100. (
  101. self.rateFormatter
  102. .string(from: state.rateValues[i] as NSNumber) ?? ""
  103. ) + " g/U"
  104. ).tag(i)
  105. }
  106. }
  107. }.listRowBackground(Color.chart)
  108. Section {
  109. Picker(selection: $state.items[index].timeIndex, label: Text("Time")) {
  110. ForEach(0 ..< state.timeValues.count, id: \.self) { i in
  111. Text(
  112. self.dateFormatter
  113. .string(from: Date(
  114. timeIntervalSince1970: state
  115. .timeValues[i]
  116. ))
  117. ).tag(i)
  118. }
  119. }
  120. }.listRowBackground(Color.chart)
  121. }
  122. .padding(.top)
  123. .scrollContentBackground(.hidden).background(appState.trioBackgroundColor(for: colorScheme))
  124. .navigationTitle("Set Ratio")
  125. .navigationBarTitleDisplayMode(.automatic)
  126. }
  127. private var list: some View {
  128. List {
  129. chart.padding(.vertical)
  130. ForEach(state.items.indexed(), id: \.1.id) { index, item in
  131. NavigationLink(destination: pickers(for: index)) {
  132. HStack {
  133. Text("Ratio").foregroundColor(.secondary)
  134. Text(
  135. "\(rateFormatter.string(from: state.rateValues[item.rateIndex] as NSNumber) ?? "0") g/U"
  136. )
  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.rateValues[item.rateIndex]
  155. let tzOffset = TimeZone.current.secondsFromGMT() * -1
  156. let startDate = Date(timeIntervalSinceReferenceDate: state.timeValues[item.timeIndex])
  157. .addingTimeInterval(TimeInterval(tzOffset))
  158. let endDate = state.items
  159. .count > index + 1 ?
  160. Date(timeIntervalSinceReferenceDate: state.timeValues[state.items[index + 1].timeIndex])
  161. .addingTimeInterval(TimeInterval(tzOffset)) :
  162. Date(timeIntervalSinceReferenceDate: state.timeValues.last!).addingTimeInterval(30 * 60)
  163. .addingTimeInterval(TimeInterval(tzOffset))
  164. RectangleMark(
  165. xStart: .value("start", startDate),
  166. xEnd: .value("end", endDate),
  167. yStart: .value("rate-start", displayValue),
  168. yEnd: .value("rate-end", 0)
  169. ).foregroundStyle(
  170. .linearGradient(
  171. colors: [
  172. Color.insulin.opacity(0.6),
  173. Color.insulin.opacity(0.1)
  174. ],
  175. startPoint: .bottom,
  176. endPoint: .top
  177. )
  178. ).alignsMarkStylesWithPlotArea()
  179. LineMark(x: .value("End Date", startDate), y: .value("Ratio", displayValue))
  180. .lineStyle(.init(lineWidth: 1)).foregroundStyle(Color.insulin)
  181. LineMark(x: .value("Start Date", endDate), y: .value("Ratio", displayValue))
  182. .lineStyle(.init(lineWidth: 1)).foregroundStyle(Color.insulin)
  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. }
  201. }
  202. private var addButton: some View {
  203. guard state.canAdd else {
  204. return AnyView(EmptyView())
  205. }
  206. switch editMode {
  207. case .inactive:
  208. return AnyView(Button(action: onAdd) { Image(systemName: "plus") })
  209. default:
  210. return AnyView(EmptyView())
  211. }
  212. }
  213. func onAdd() {
  214. state.add()
  215. }
  216. private func onDelete(offsets: IndexSet) {
  217. state.items.remove(atOffsets: offsets)
  218. state.validate()
  219. }
  220. }
  221. }