ISFEditorRootView.swift 13 KB

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