ISFEditorRootView.swift 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  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. Section(header: Text("Schedule")) {
  114. list
  115. }.listRowBackground(Color.chart)
  116. }
  117. .safeAreaInset(edge: .bottom, spacing: 30) { saveButton }
  118. .scrollContentBackground(.hidden).background(appState.trioBackgroundColor(for: colorScheme))
  119. .onAppear(perform: configureView)
  120. .navigationTitle("Insulin Sensitivities")
  121. .navigationBarTitleDisplayMode(.automatic)
  122. .toolbar(content: {
  123. ToolbarItem(placement: .topBarTrailing) {
  124. EditButton()
  125. }
  126. ToolbarItem(placement: .topBarTrailing) {
  127. addButton
  128. }
  129. })
  130. .environment(\.editMode, $editMode)
  131. .onAppear {
  132. state.validate()
  133. }
  134. }
  135. private func pickers(for index: Int) -> some View {
  136. Form {
  137. Section {
  138. Picker(selection: $state.items[index].rateIndex, label: Text("Rate")) {
  139. ForEach(0 ..< state.rateValues.count, id: \.self) { i in
  140. Text(
  141. state.units == .mgdL ? state.rateValues[i].description : state.rateValues[i]
  142. .formattedAsMmolL + " \(state.units.rawValue)/U"
  143. ).tag(i)
  144. }
  145. }
  146. }.listRowBackground(Color.chart)
  147. Section {
  148. Picker(selection: $state.items[index].timeIndex, label: Text("Time")) {
  149. ForEach(0 ..< state.timeValues.count, id: \.self) { i in
  150. Text(
  151. self.dateFormatter
  152. .string(from: Date(
  153. timeIntervalSince1970: state
  154. .timeValues[i]
  155. ))
  156. ).tag(i)
  157. }
  158. }
  159. }.listRowBackground(Color.chart)
  160. }
  161. .padding(.top)
  162. .scrollContentBackground(.hidden).background(appState.trioBackgroundColor(for: colorScheme))
  163. .navigationTitle("Set Rate")
  164. .navigationBarTitleDisplayMode(.automatic)
  165. }
  166. private var list: some View {
  167. List {
  168. chart.padding(.vertical)
  169. ForEach(state.items.indexed(), id: \.1.id) { index, item in
  170. let displayValue = state.units == .mgdL ? state.rateValues[item.rateIndex].description : state
  171. .rateValues[item.rateIndex].formattedAsMmolL
  172. NavigationLink(destination: pickers(for: index)) {
  173. HStack {
  174. Text("Rate").foregroundColor(.secondary)
  175. Text(
  176. displayValue + " \(state.units.rawValue)/U"
  177. )
  178. Spacer()
  179. Text("starts at").foregroundColor(.secondary)
  180. Text(
  181. "\(dateFormatter.string(from: Date(timeIntervalSince1970: state.timeValues[item.timeIndex])))"
  182. )
  183. }
  184. }
  185. .moveDisabled(true)
  186. }
  187. .onDelete(perform: onDelete)
  188. }
  189. }
  190. let chartScale = Calendar.current
  191. .date(from: DateComponents(year: 2001, month: 01, day: 01, hour: 0, minute: 0, second: 0))
  192. var chart: some View {
  193. Chart {
  194. ForEach(state.items.indexed(), id: \.1.id) { index, item in
  195. let displayValue = state.units == .mgdL ? state.rateValues[item.rateIndex].description : state
  196. .rateValues[item.rateIndex].formattedAsMmolL
  197. // Convert from string so we know we use the same math as the rest of Trio.
  198. // However, swift doesn't understand languages that use comma as decimal delminator
  199. let displayValueFloat = Double(displayValue.replacingOccurrences(of: ",", with: "."))
  200. let tzOffset = TimeZone.current.secondsFromGMT() * -1
  201. let startDate = Date(timeIntervalSinceReferenceDate: state.timeValues[item.timeIndex])
  202. .addingTimeInterval(TimeInterval(tzOffset))
  203. let endDate = state.items
  204. .count > index + 1 ?
  205. Date(timeIntervalSinceReferenceDate: state.timeValues[state.items[index + 1].timeIndex])
  206. .addingTimeInterval(TimeInterval(tzOffset)) :
  207. Date(timeIntervalSinceReferenceDate: state.timeValues.last!).addingTimeInterval(30 * 60)
  208. .addingTimeInterval(TimeInterval(tzOffset))
  209. RectangleMark(
  210. xStart: .value("start", startDate),
  211. xEnd: .value("end", endDate),
  212. yStart: .value("rate-start", displayValueFloat ?? 0),
  213. yEnd: .value("rate-end", 0)
  214. ).foregroundStyle(
  215. .linearGradient(
  216. colors: [
  217. Color.insulin.opacity(0.6),
  218. Color.insulin.opacity(0.1)
  219. ],
  220. startPoint: .bottom,
  221. endPoint: .top
  222. )
  223. ).alignsMarkStylesWithPlotArea()
  224. LineMark(x: .value("End Date", startDate), y: .value("ISF", displayValueFloat ?? 0))
  225. .lineStyle(.init(lineWidth: 1)).foregroundStyle(Color.insulin)
  226. LineMark(x: .value("Start Date", endDate), y: .value("ISF", displayValueFloat ?? 0))
  227. .lineStyle(.init(lineWidth: 1)).foregroundStyle(Color.insulin)
  228. }
  229. }
  230. .chartXAxis {
  231. AxisMarks(values: .automatic(desiredCount: 6)) { _ in
  232. AxisValueLabel(format: .dateTime.hour())
  233. AxisGridLine(centered: true, stroke: StrokeStyle(lineWidth: 1, dash: [2, 4]))
  234. }
  235. }
  236. .chartXScale(
  237. domain: Calendar.current.startOfDay(for: chartScale!) ... Calendar.current.startOfDay(for: chartScale!)
  238. .addingTimeInterval(60 * 60 * 24)
  239. )
  240. .chartYAxis {
  241. AxisMarks(values: .automatic(desiredCount: 4)) { _ in
  242. AxisValueLabel()
  243. AxisGridLine(centered: true, stroke: StrokeStyle(lineWidth: 1, dash: [2, 4]))
  244. }
  245. }
  246. }
  247. private var addButton: some View {
  248. guard state.canAdd else {
  249. return AnyView(EmptyView())
  250. }
  251. switch editMode {
  252. case .inactive:
  253. return AnyView(Button(action: onAdd) { Image(systemName: "plus") })
  254. default:
  255. return AnyView(EmptyView())
  256. }
  257. }
  258. func onAdd() {
  259. state.add()
  260. }
  261. private func onDelete(offsets: IndexSet) {
  262. state.items.remove(atOffsets: offsets)
  263. state.validate()
  264. }
  265. }
  266. }