ISFEditorRootView.swift 13 KB

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