ISFEditorRootView.swift 12 KB

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