DataTableRootView.swift 22 KB

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