DataTableRootView.swift 21 KB

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