CarbRatioEditorRootView.swift 11 KB

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