DataTableRootView.swift 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  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: PumpEventStored?
  12. @State private var alertCarbEntryToDelete: CarbEntryStored?
  13. @State private var alertGlucoseToDelete: GlucoseStored?
  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. @State private var showAlert = false
  18. @Environment(\.colorScheme) var colorScheme
  19. @Environment(\.managedObjectContext) var context
  20. @FetchRequest(
  21. entity: GlucoseStored.entity(),
  22. sortDescriptors: [NSSortDescriptor(keyPath: \GlucoseStored.date, ascending: false)],
  23. predicate: NSPredicate.predicateForOneDayAgo,
  24. animation: .bouncy
  25. ) var glucoseStored: FetchedResults<GlucoseStored>
  26. @FetchRequest(
  27. entity: PumpEventStored.entity(),
  28. sortDescriptors: [NSSortDescriptor(keyPath: \PumpEventStored.timestamp, ascending: false)],
  29. predicate: NSPredicate.pumpHistoryLast24h,
  30. animation: .bouncy
  31. ) var pumpEventStored: FetchedResults<PumpEventStored>
  32. @FetchRequest(
  33. entity: CarbEntryStored.entity(),
  34. sortDescriptors: [NSSortDescriptor(keyPath: \CarbEntryStored.date, ascending: false)],
  35. predicate: NSPredicate.predicateForOneDayAgo,
  36. animation: .bouncy
  37. ) var carbEntryStored: FetchedResults<CarbEntryStored>
  38. private var insulinFormatter: NumberFormatter {
  39. let formatter = NumberFormatter()
  40. formatter.numberStyle = .decimal
  41. formatter.maximumFractionDigits = 2
  42. return formatter
  43. }
  44. private var glucoseFormatter: NumberFormatter {
  45. let formatter = NumberFormatter()
  46. formatter.numberStyle = .decimal
  47. if state.units == .mmolL {
  48. formatter.maximumFractionDigits = 1
  49. formatter.roundingMode = .halfUp
  50. } else {
  51. formatter.maximumFractionDigits = 0
  52. }
  53. return formatter
  54. }
  55. private var manualGlucoseFormatter: NumberFormatter {
  56. let formatter = NumberFormatter()
  57. formatter.numberStyle = .decimal
  58. if state.units == .mmolL {
  59. formatter.maximumFractionDigits = 1
  60. formatter.roundingMode = .ceiling
  61. } else {
  62. formatter.maximumFractionDigits = 0
  63. }
  64. return formatter
  65. }
  66. private var dateFormatter: DateFormatter {
  67. let formatter = DateFormatter()
  68. formatter.timeStyle = .short
  69. return formatter
  70. }
  71. private var numberFormatter: NumberFormatter {
  72. let formatter = NumberFormatter()
  73. formatter.numberStyle = .decimal
  74. formatter.maximumFractionDigits = 2
  75. return formatter
  76. }
  77. private var color: LinearGradient {
  78. colorScheme == .dark ? LinearGradient(
  79. gradient: Gradient(colors: [
  80. Color.bgDarkBlue,
  81. Color.bgDarkerDarkBlue
  82. ]),
  83. startPoint: .top,
  84. endPoint: .bottom
  85. )
  86. :
  87. LinearGradient(
  88. gradient: Gradient(colors: [Color.gray.opacity(0.1)]),
  89. startPoint: .top,
  90. endPoint: .bottom
  91. )
  92. }
  93. var body: some View {
  94. ZStack(alignment: .center, content: {
  95. VStack {
  96. Picker("Mode", selection: $state.mode) {
  97. ForEach(
  98. Mode.allCases.indexed(),
  99. id: \.1
  100. ) { index, item in
  101. Text(item.name).tag(index)
  102. }
  103. }
  104. .pickerStyle(SegmentedPickerStyle())
  105. .padding(.horizontal)
  106. Form {
  107. switch state.mode {
  108. case .treatments: treatmentsList
  109. case .glucose: glucoseList
  110. case .meals: mealsList
  111. }
  112. }.scrollContentBackground(.hidden)
  113. .background(color)
  114. }.blur(radius: state.waitForSuggestion ? 8 : 0)
  115. if state.waitForSuggestion {
  116. CustomProgressView(text: progressText.rawValue)
  117. }
  118. })
  119. .background(color)
  120. .onAppear(perform: configureView)
  121. .onDisappear {
  122. state.carbEntryDeleted = false
  123. state.insulinEntryDeleted = false
  124. }
  125. .navigationTitle("History")
  126. .navigationBarTitleDisplayMode(.large)
  127. .toolbar {
  128. ToolbarItem(placement: .topBarTrailing) {
  129. addButton({
  130. showManualGlucose = true
  131. state.manualGlucose = 0
  132. })
  133. }
  134. }
  135. .sheet(isPresented: $showManualGlucose) {
  136. addGlucoseView()
  137. }
  138. }
  139. @ViewBuilder func addButton(_ action: @escaping () -> Void) -> some View {
  140. Button(
  141. action: action,
  142. label: {
  143. HStack {
  144. Text("Add Glucose")
  145. Image(systemName: "plus")
  146. .font(.system(size: 20))
  147. }
  148. }
  149. )
  150. }
  151. private var progressText: ProgressText {
  152. switch (state.carbEntryDeleted, state.insulinEntryDeleted) {
  153. case (true, false):
  154. return .updatingCOB
  155. case(false, true):
  156. return .updatingIOB
  157. default:
  158. return .updatingHistory
  159. }
  160. }
  161. private var treatmentsList: some View {
  162. List {
  163. HStack {
  164. Text("Insulin").foregroundStyle(.secondary)
  165. Spacer()
  166. Text("Time").foregroundStyle(.secondary)
  167. }
  168. if !pumpEventStored.isEmpty {
  169. ForEach(pumpEventStored.filter({ !showFutureEntries ? $0.timestamp ?? Date() <= Date() : true })) { item in
  170. treatmentView(item)
  171. }
  172. } else {
  173. HStack {
  174. Text("No data.")
  175. }
  176. }
  177. }.listRowBackground(Color.chart)
  178. }
  179. private var mealsList: some View {
  180. List {
  181. HStack {
  182. Text("Type").foregroundStyle(.secondary)
  183. Spacer()
  184. filterEntriesButton
  185. }
  186. if !carbEntryStored.isEmpty {
  187. ForEach(carbEntryStored.filter({ !showFutureEntries ? $0.date ?? Date() <= Date() : true })) { item in
  188. mealView(item)
  189. }
  190. } else {
  191. HStack {
  192. Text("No data.")
  193. }
  194. }
  195. }.listRowBackground(Color.chart)
  196. }
  197. private var glucoseList: some View {
  198. List {
  199. HStack {
  200. Text("Values").foregroundStyle(.secondary)
  201. Spacer()
  202. Text("Time").foregroundStyle(.secondary)
  203. }
  204. if !glucoseStored.isEmpty {
  205. ForEach(glucoseStored) { glucose in
  206. HStack {
  207. Text(formatGlucose(glucose.glucose, isManual: glucose.isManual))
  208. /// check for manual glucose
  209. if glucose.isManual {
  210. Image(systemName: "drop.fill").symbolRenderingMode(.monochrome).foregroundStyle(.red)
  211. } else {
  212. Text("\(glucose.direction ?? "--")")
  213. }
  214. Spacer()
  215. Text(dateFormatter.string(from: glucose.date ?? Date()))
  216. }.swipeActions {
  217. Button(
  218. "Delete",
  219. systemImage: "trash.fill",
  220. role: .none,
  221. action: {
  222. alertGlucoseToDelete = glucose
  223. alertTitle = "Delete Glucose?"
  224. alertMessage = dateFormatter
  225. .string(from: glucose.date ?? Date()) + ", " +
  226. (numberFormatter.string(for: glucose.glucose) ?? "0")
  227. isRemoveHistoryItemAlertPresented = true
  228. }
  229. ).tint(.red)
  230. }
  231. .alert(
  232. Text(NSLocalizedString(alertTitle, comment: "")),
  233. isPresented: $isRemoveHistoryItemAlertPresented
  234. ) {
  235. Button("Cancel", role: .cancel) {}
  236. Button("Delete", role: .destructive) {
  237. guard let glucoseToDelete = alertGlucoseToDelete else {
  238. debug(.default, "Cannot gracefully unwrap alertCarbEntryToDelete!")
  239. return
  240. }
  241. let glucoseToDeleteObjectID = glucoseToDelete.objectID
  242. state.invokeGlucoseDeletionTask(glucoseToDeleteObjectID)
  243. }
  244. } message: {
  245. Text("\n" + NSLocalizedString(alertMessage, comment: ""))
  246. }
  247. }
  248. } else {
  249. HStack {
  250. Text("No data.")
  251. }
  252. }
  253. }.listRowBackground(Color.chart)
  254. .alert(isPresented: $showAlert) {
  255. Alert(title: Text("Error"), message: Text(alertMessage), dismissButton: .default(Text("OK")))
  256. }
  257. }
  258. private func deleteGlucose(at offsets: IndexSet) {
  259. for index in offsets {
  260. let glucoseToDelete = glucoseStored[index]
  261. context.delete(glucoseToDelete)
  262. }
  263. do {
  264. try context.save()
  265. debugPrint("Data Table Root View: \(#function) \(DebuggingIdentifiers.succeeded) deleted glucose from core data")
  266. } catch {
  267. debugPrint(
  268. "Data Table Root View: \(#function) \(DebuggingIdentifiers.failed) error while deleting glucose from core data"
  269. )
  270. alertMessage = "Failed to delete glucose data: \(error.localizedDescription)"
  271. showAlert = true
  272. }
  273. }
  274. @ViewBuilder private func addGlucoseView() -> some View {
  275. let limitLow: Decimal = state.units == .mmolL ? 0.8 : 14
  276. let limitHigh: Decimal = state.units == .mmolL ? 40 : 720
  277. NavigationView {
  278. VStack {
  279. Form {
  280. Section {
  281. HStack {
  282. Text("New Glucose")
  283. TextFieldWithToolBar(
  284. text: $state.manualGlucose,
  285. placeholder: " ... ",
  286. numberFormatter: manualGlucoseFormatter
  287. )
  288. Text(state.units.rawValue).foregroundStyle(.secondary)
  289. }
  290. }.listRowBackground(Color.chart)
  291. Section {
  292. HStack {
  293. Button {
  294. state.addManualGlucose()
  295. isAmountUnconfirmed = false
  296. showManualGlucose = false
  297. }
  298. label: { Text("Save") }
  299. .frame(maxWidth: .infinity, alignment: .center)
  300. .disabled(state.manualGlucose < limitLow || state.manualGlucose > limitHigh)
  301. }
  302. }
  303. .listRowBackground(
  304. state.manualGlucose < limitLow || state
  305. .manualGlucose > limitHigh ? Color(.systemGray4) : Color(.systemBlue)
  306. )
  307. .tint(.white)
  308. }.scrollContentBackground(.hidden).background(color)
  309. }
  310. .onAppear(perform: configureView)
  311. .navigationTitle("Add Glucose")
  312. .navigationBarTitleDisplayMode(.inline)
  313. .toolbar {
  314. ToolbarItem(placement: .topBarLeading) {
  315. Button("Close") {
  316. showManualGlucose = false
  317. }
  318. }
  319. }
  320. }
  321. }
  322. private var filterEntriesButton: some View {
  323. Button(action: { showFutureEntries.toggle() }, label: {
  324. HStack {
  325. Text(showFutureEntries ? "Hide Future" : "Show Future")
  326. .foregroundColor(Color.secondary)
  327. Image(systemName: showFutureEntries ? "calendar.badge.minus" : "calendar.badge.plus")
  328. }.frame(maxWidth: .infinity, alignment: .trailing)
  329. }).buttonStyle(.borderless)
  330. }
  331. @ViewBuilder private func treatmentView(_ item: PumpEventStored) -> some View {
  332. HStack {
  333. if let bolus = item.bolus, let amount = bolus.amount {
  334. Image(systemName: "circle.fill").foregroundColor(Color.insulin)
  335. Text(bolus.isSMB ? "SMB" : item.type ?? "Bolus")
  336. Text((insulinFormatter.string(from: amount) ?? "0") + NSLocalizedString(" U", comment: "Insulin unit"))
  337. .foregroundColor(.secondary)
  338. if bolus.isExternal {
  339. Text(NSLocalizedString("External", comment: "External Insulin")).foregroundColor(.secondary)
  340. }
  341. } else if let tempBasal = item.tempBasal, let rate = tempBasal.rate {
  342. Image(systemName: "circle.fill").foregroundColor(Color.insulin.opacity(0.4))
  343. Text("Temp Basal")
  344. Text(
  345. (insulinFormatter.string(from: rate) ?? "0") +
  346. NSLocalizedString(" U/hr", comment: "Unit insulin per hour")
  347. )
  348. .foregroundColor(.secondary)
  349. if tempBasal.duration > 0 {
  350. Text("\(tempBasal.duration.string) min").foregroundColor(.secondary)
  351. }
  352. } else {
  353. Image(systemName: "circle.fill").foregroundColor(Color.loopGray)
  354. Text(item.type ?? "Pump Event")
  355. }
  356. Spacer()
  357. Text(dateFormatter.string(from: item.timestamp ?? Date())).moveDisabled(true)
  358. }
  359. .swipeActions {
  360. if item.bolus != nil {
  361. Button(
  362. "Delete",
  363. systemImage: "trash.fill",
  364. role: .none,
  365. action: {
  366. alertTreatmentToDelete = item
  367. alertTitle = "Delete Insulin?"
  368. alertMessage = dateFormatter
  369. .string(from: item.timestamp ?? Date()) + ", " +
  370. (insulinFormatter.string(from: item.bolus?.amount ?? 0) ?? "0") +
  371. NSLocalizedString(" U", comment: "Insulin unit")
  372. if let bolus = item.bolus {
  373. // Add text snippet, so that alert message is more descriptive for SMBs
  374. alertMessage += bolus.isSMB ? " SMB" : ""
  375. }
  376. isRemoveHistoryItemAlertPresented = true
  377. }
  378. ).tint(.red)
  379. }
  380. }
  381. .alert(
  382. Text(NSLocalizedString(alertTitle, comment: "")),
  383. isPresented: $isRemoveHistoryItemAlertPresented
  384. ) {
  385. Button("Cancel", role: .cancel) {}
  386. Button("Delete", role: .destructive) {
  387. guard let treatmentToDelete = alertTreatmentToDelete else {
  388. debug(.default, "Cannot gracefully unwrap alertTreatmentToDelete!")
  389. return
  390. }
  391. let treatmentObjectID = treatmentToDelete.objectID
  392. state.invokeInsulinDeletionTask(treatmentObjectID)
  393. }
  394. } message: {
  395. Text("\n" + NSLocalizedString(alertMessage, comment: ""))
  396. }
  397. }
  398. @ViewBuilder private func mealView(_ meal: CarbEntryStored) -> some View {
  399. HStack {
  400. if meal.isFPU {
  401. Image(systemName: "circle.fill").foregroundColor(Color.orange.opacity(0.5))
  402. Text("Fat / Protein")
  403. Text((numberFormatter.string(for: meal.carbs) ?? "0") + NSLocalizedString(" g", comment: "gram of carbs"))
  404. } else {
  405. Image(systemName: "circle.fill").foregroundColor(Color.loopYellow)
  406. Text("Carbs")
  407. Text(
  408. (numberFormatter.string(for: meal.carbs) ?? "0") +
  409. NSLocalizedString(" g", comment: "gram of carb equilvalents")
  410. )
  411. }
  412. Spacer()
  413. Text(dateFormatter.string(from: meal.date ?? Date()))
  414. .moveDisabled(true)
  415. }
  416. .swipeActions {
  417. Button(
  418. "Delete",
  419. systemImage: "trash.fill",
  420. role: .none,
  421. action: {
  422. alertCarbEntryToDelete = meal
  423. if !meal.isFPU {
  424. alertTitle = "Delete Carbs?"
  425. alertMessage = dateFormatter
  426. .string(from: meal.date ?? Date()) + ", " + (numberFormatter.string(for: meal.carbs) ?? "0") +
  427. NSLocalizedString(" g", comment: "gram of carbs")
  428. } else {
  429. alertTitle = "Delete Carb Equivalents?"
  430. alertMessage = "All FPUs of the meal will be deleted."
  431. }
  432. isRemoveHistoryItemAlertPresented = true
  433. }
  434. ).tint(.red)
  435. }
  436. .alert(
  437. Text(NSLocalizedString(alertTitle, comment: "")),
  438. isPresented: $isRemoveHistoryItemAlertPresented
  439. ) {
  440. Button("Cancel", role: .cancel) {}
  441. Button("Delete", role: .destructive) {
  442. guard let carbEntryToDelete = alertCarbEntryToDelete else {
  443. debug(.default, "Cannot gracefully unwrap alertCarbEntryToDelete!")
  444. return
  445. }
  446. let treatmentObjectID = carbEntryToDelete.objectID
  447. state.invokeCarbDeletionTask(treatmentObjectID)
  448. }
  449. } message: {
  450. Text("\n" + NSLocalizedString(alertMessage, comment: ""))
  451. }
  452. }
  453. // MARK: - Format glucose
  454. private func formatGlucose(_ value: Int16, isManual: Bool) -> String {
  455. let formatter = isManual ? manualGlucoseFormatter : glucoseFormatter
  456. let formattedValue = formatter.string(from: NSNumber(value: value)) ?? "--"
  457. return state.units == .mmolL ? convertToMMOL(Double(value)) : formattedValue
  458. }
  459. private func convertToMMOL(_ value: Double) -> String {
  460. let mmolValue = value * 0.0555
  461. return "\(mmolValue) mmol/L"
  462. }
  463. }
  464. }