ISFEditorRootView.swift 13 KB

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