ISFEditorRootView.swift 11 KB

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