ISFEditorRootView.swift 11 KB

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