ISFEditorRootView.swift 11 KB

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