DataTableRootView.swift 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  1. import CoreData
  2. import SwiftUI
  3. import Swinject
  4. extension DataTable {
  5. struct RootView: BaseView {
  6. let resolver: Resolver
  7. @StateObject var state = StateModel()
  8. @State private var isRemoveHistoryItemAlertPresented: Bool = false
  9. @State private var alertTitle: String = ""
  10. @State private var alertMessage: String = ""
  11. @State private var alertTreatmentToDelete: Treatment?
  12. @State private var alertGlucoseToDelete: Glucose?
  13. @State private var showExternalInsulin: Bool = false
  14. @State private var showFutureEntries: Bool = false // default to hide future entries
  15. @State private var showManualGlucose: Bool = false
  16. @State private var isAmountUnconfirmed: Bool = true
  17. @Environment(\.colorScheme) var colorScheme
  18. private var insulinFormatter: NumberFormatter {
  19. let formatter = NumberFormatter()
  20. formatter.numberStyle = .decimal
  21. formatter.maximumFractionDigits = 2
  22. return formatter
  23. }
  24. private var glucoseFormatter: NumberFormatter {
  25. let formatter = NumberFormatter()
  26. formatter.numberStyle = .decimal
  27. formatter.maximumFractionDigits = 0
  28. if state.units == .mmolL {
  29. formatter.maximumFractionDigits = 1
  30. formatter.roundingMode = .ceiling
  31. }
  32. return formatter
  33. }
  34. private var dateFormatter: DateFormatter {
  35. let formatter = DateFormatter()
  36. formatter.timeStyle = .short
  37. return formatter
  38. }
  39. var body: some View {
  40. VStack {
  41. Picker("Mode", selection: $state.mode) {
  42. ForEach(Mode.allCases.indexed(), id: \.1) { index, item in
  43. Text(item.name).tag(index)
  44. }
  45. }
  46. .pickerStyle(SegmentedPickerStyle())
  47. .padding(.horizontal)
  48. Form {
  49. switch state.mode {
  50. case .treatments: treatmentsList
  51. case .glucose: glucoseList
  52. }
  53. }
  54. }
  55. .onAppear(perform: configureView)
  56. .navigationTitle("History")
  57. .navigationBarTitleDisplayMode(.inline)
  58. .navigationBarItems(trailing: Button("Close", action: state.hideModal))
  59. .sheet(isPresented: $showManualGlucose) {
  60. addGlucoseView
  61. }
  62. .sheet(isPresented: $showExternalInsulin, onDismiss: { if isAmountUnconfirmed { state.externalInsulinAmount = 0
  63. state.externalInsulinDate = Date() } }) {
  64. addExternalInsulinView
  65. }
  66. }
  67. private var treatmentsList: some View {
  68. List {
  69. HStack {
  70. Button(action: { showExternalInsulin = true
  71. state.externalInsulinDate = Date() }, label: {
  72. HStack {
  73. Image(systemName: "syringe")
  74. Text("Add")
  75. .foregroundColor(Color.secondary)
  76. .font(.caption)
  77. }.frame(maxWidth: .infinity, alignment: .leading)
  78. }).buttonStyle(.borderless)
  79. Spacer()
  80. Button(action: { showFutureEntries.toggle() }, label: {
  81. HStack {
  82. Text(showFutureEntries ? "Hide Future" : "Show Future")
  83. .foregroundColor(Color.secondary)
  84. .font(.caption)
  85. Image(systemName: showFutureEntries ? "calendar.badge.minus" : "calendar.badge.plus")
  86. }.frame(maxWidth: .infinity, alignment: .trailing)
  87. }).buttonStyle(.borderless)
  88. }
  89. if !state.treatments.isEmpty {
  90. if !showFutureEntries {
  91. ForEach(state.treatments.filter { item in
  92. item.date <= Date()
  93. }) { item in
  94. treatmentView(item)
  95. }
  96. } else {
  97. ForEach(state.treatments) { item in
  98. treatmentView(item)
  99. }
  100. }
  101. } else {
  102. HStack {
  103. Text("No data.")
  104. }
  105. }
  106. }
  107. }
  108. private var glucoseList: some View {
  109. List {
  110. HStack {
  111. Button(
  112. action: { showManualGlucose = true
  113. state.manualGlucose = 0 },
  114. label: { Image(systemName: "plus.circle.fill").foregroundStyle(.secondary)
  115. }
  116. ).buttonStyle(.borderless)
  117. Text(state.units.rawValue).foregroundStyle(.secondary)
  118. Spacer()
  119. Text("Time").foregroundStyle(.secondary)
  120. }
  121. if !state.glucose.isEmpty {
  122. ForEach(state.glucose) { item in
  123. glucoseView(item, isManual: item.glucose)
  124. }
  125. } else {
  126. HStack {
  127. Text("No data.")
  128. }
  129. }
  130. }
  131. }
  132. var addGlucoseView: some View {
  133. NavigationView {
  134. VStack {
  135. Form {
  136. Section {
  137. HStack {
  138. Text("New Glucose")
  139. DecimalTextField(
  140. " ... ",
  141. value: $state.manualGlucose,
  142. formatter: glucoseFormatter,
  143. autofocus: true,
  144. cleanInput: true
  145. )
  146. Text(state.units.rawValue).foregroundStyle(.secondary)
  147. }
  148. }
  149. Section {
  150. HStack {
  151. let limitLow: Decimal = state.units == .mmolL ? 0.8 : 14
  152. let limitHigh: Decimal = state.units == .mmolL ? 40 : 720
  153. Button {
  154. state.addManualGlucose()
  155. isAmountUnconfirmed = false
  156. showManualGlucose = false
  157. }
  158. label: { Text("Save") }
  159. .frame(maxWidth: .infinity, alignment: .center)
  160. .disabled(state.manualGlucose < limitLow || state.manualGlucose > limitHigh)
  161. }
  162. }
  163. }
  164. }
  165. .onAppear(perform: configureView)
  166. .navigationTitle("Add Glucose")
  167. .navigationBarTitleDisplayMode(.automatic)
  168. .navigationBarItems(trailing: Button("Close", action: { showManualGlucose = false }))
  169. }
  170. }
  171. @ViewBuilder private func treatmentView(_ item: Treatment) -> some View {
  172. HStack {
  173. if item.type == .bolus || item.type == .carbs {
  174. Image(systemName: "circle.fill").foregroundColor(item.color).padding(.vertical)
  175. } else {
  176. Image(systemName: "circle.fill").foregroundColor(item.color)
  177. }
  178. Text((item.isSMB ?? false) ? "SMB" : item.type.name)
  179. Text(item.amountText).foregroundColor(.secondary)
  180. if let duration = item.durationText {
  181. Text(duration).foregroundColor(.secondary)
  182. }
  183. Spacer()
  184. Text(dateFormatter.string(from: item.date))
  185. .moveDisabled(true)
  186. }
  187. .swipeActions {
  188. Button(
  189. "Delete",
  190. systemImage: "trash.fill",
  191. role: .none,
  192. action: {
  193. alertTreatmentToDelete = item
  194. if item.type == .carbs {
  195. alertTitle = "Delete Carbs?"
  196. alertMessage = dateFormatter.string(from: item.date) + ", " + item.amountText
  197. } else if item.type == .fpus {
  198. alertTitle = "Delete Carb Equivalents?"
  199. alertMessage = "All FPUs of the meal will be deleted."
  200. } else {
  201. // item is insulin treatment; item.type == .bolus
  202. alertTitle = "Delete Insulin?"
  203. alertMessage = dateFormatter.string(from: item.date) + ", " + item.amountText
  204. if item.isSMB ?? false {
  205. // Add text snippet, so that alert message is more descriptive for SMBs
  206. alertMessage += "SMB"
  207. }
  208. }
  209. isRemoveHistoryItemAlertPresented = true
  210. }
  211. ).tint(.red)
  212. }
  213. .disabled(item.type == .tempBasal || item.type == .tempTarget || item.type == .resume || item.type == .suspend)
  214. .alert(
  215. Text(NSLocalizedString(alertTitle, comment: "")),
  216. isPresented: $isRemoveHistoryItemAlertPresented
  217. ) {
  218. Button("Cancel", role: .cancel) {}
  219. Button("Delete", role: .destructive) {
  220. guard let treatmentToDelete = alertTreatmentToDelete else {
  221. debug(.default, "Cannot gracefully unwrap alertTreatmentToDelete!")
  222. return
  223. }
  224. if treatmentToDelete.type == .carbs || treatmentToDelete.type == .fpus {
  225. state.deleteCarbs(treatmentToDelete)
  226. } else {
  227. state.deleteInsulin(treatmentToDelete)
  228. }
  229. }
  230. } message: {
  231. Text("\n" + NSLocalizedString(alertMessage, comment: ""))
  232. }
  233. }
  234. var addExternalInsulinView: some View {
  235. NavigationView {
  236. VStack {
  237. Form {
  238. Section {
  239. HStack {
  240. Text("Amount")
  241. Spacer()
  242. DecimalTextField(
  243. "0",
  244. value: $state.externalInsulinAmount,
  245. formatter: insulinFormatter,
  246. autofocus: true,
  247. cleanInput: true
  248. )
  249. Text("U").foregroundColor(.secondary)
  250. }
  251. }
  252. Section {
  253. DatePicker("Date", selection: $state.externalInsulinDate, in: ...Date())
  254. }
  255. let amountWarningCondition = (state.externalInsulinAmount > state.maxBolus)
  256. Section {
  257. HStack {
  258. Button {
  259. state.addExternalInsulin()
  260. isAmountUnconfirmed = false
  261. showExternalInsulin = false
  262. }
  263. label: {
  264. Text("Log external insulin")
  265. }
  266. .foregroundColor(amountWarningCondition ? Color.white : Color.accentColor)
  267. .frame(maxWidth: .infinity, alignment: .center)
  268. .disabled(
  269. state.externalInsulinAmount <= 0 || state.externalInsulinAmount > state.maxBolus * 3
  270. )
  271. }
  272. }
  273. header: {
  274. if amountWarningCondition
  275. {
  276. Text("⚠️ Warning! The entered insulin amount is greater than your Max Bolus setting!")
  277. }
  278. }
  279. .listRowBackground(
  280. amountWarningCondition ? Color
  281. .red : colorScheme == .dark ? Color(UIColor.secondarySystemBackground) : Color.white
  282. )
  283. }
  284. }
  285. .onAppear(perform: configureView)
  286. .navigationTitle("External Insulin")
  287. .navigationBarTitleDisplayMode(.inline)
  288. .navigationBarItems(trailing: Button("Close", action: { showExternalInsulin = false
  289. state.externalInsulinAmount = 0 }))
  290. }
  291. }
  292. @ViewBuilder private func glucoseView(_ item: Glucose, isManual: BloodGlucose) -> some View {
  293. HStack {
  294. Text(item.glucose.glucose.map {
  295. glucoseFormatter.string(from: Double(
  296. state.units == .mmolL ? $0.asMmolL : Decimal($0)
  297. ) as NSNumber)!
  298. } ?? "--")
  299. if isManual.type == GlucoseType.manual.rawValue {
  300. Image(systemName: "drop.fill").symbolRenderingMode(.monochrome).foregroundStyle(.red)
  301. } else {
  302. Text(item.glucose.direction?.symbol ?? "--")
  303. }
  304. Spacer()
  305. Text(dateFormatter.string(from: item.glucose.dateString))
  306. }
  307. .swipeActions {
  308. Button(
  309. "Delete",
  310. systemImage: "trash.fill",
  311. role: .none,
  312. action: {
  313. alertGlucoseToDelete = item
  314. let valueText = glucoseFormatter.string(from: Double(
  315. state.units == .mmolL ? Double(item.glucose.value.asMmolL) : item.glucose.value
  316. ) as NSNumber)! + " " + state.units.rawValue
  317. alertTitle = "Delete Glucose?"
  318. alertMessage = dateFormatter.string(from: item.glucose.dateString) + ", " + valueText
  319. isRemoveHistoryItemAlertPresented = true
  320. }
  321. ).tint(.red)
  322. }
  323. .alert(
  324. Text(NSLocalizedString(alertTitle, comment: "")),
  325. isPresented: $isRemoveHistoryItemAlertPresented
  326. ) {
  327. Button("Cancel", role: .cancel) {}
  328. Button("Delete", role: .destructive) {
  329. // gracefully unwrap value here.
  330. // value cannot ever really be nil because it is an existing(!) table entry
  331. // but just to be sure.
  332. guard let glucoseToDelete = alertGlucoseToDelete else {
  333. print("Cannot gracefully unwrap alertTreatmentToDelete!")
  334. return
  335. }
  336. state.deleteGlucose(glucoseToDelete)
  337. }
  338. } message: {
  339. Text("\n" + NSLocalizedString(alertMessage, comment: ""))
  340. }
  341. }
  342. }
  343. }