ISFEditorRootView.swift 9.9 KB

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