DataTableRootView.swift 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562
  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 showFutureEntries: Bool = false // default to hide future entries
  14. @State private var showManualGlucose: Bool = false
  15. @State private var isAmountUnconfirmed: Bool = true
  16. @Environment(\.colorScheme) var colorScheme
  17. private var insulinFormatter: NumberFormatter {
  18. let formatter = NumberFormatter()
  19. formatter.numberStyle = .decimal
  20. formatter.maximumFractionDigits = 2
  21. return formatter
  22. }
  23. private var glucoseFormatter: NumberFormatter {
  24. let formatter = NumberFormatter()
  25. formatter.numberStyle = .decimal
  26. if state.units == .mmolL {
  27. formatter.maximumFractionDigits = 1
  28. formatter.roundingMode = .halfUp
  29. } else {
  30. formatter.maximumFractionDigits = 0
  31. }
  32. return formatter
  33. }
  34. private var manualGlucoseFormatter: NumberFormatter {
  35. let formatter = NumberFormatter()
  36. formatter.numberStyle = .decimal
  37. if state.units == .mmolL {
  38. formatter.maximumFractionDigits = 1
  39. formatter.roundingMode = .ceiling
  40. } else {
  41. formatter.maximumFractionDigits = 0
  42. }
  43. return formatter
  44. }
  45. private var dateFormatter: DateFormatter {
  46. let formatter = DateFormatter()
  47. formatter.timeStyle = .short
  48. return formatter
  49. }
  50. private var color: LinearGradient {
  51. colorScheme == .dark ? LinearGradient(
  52. gradient: Gradient(colors: [
  53. Color.bgDarkBlue,
  54. Color.bgDarkerDarkBlue
  55. ]),
  56. startPoint: .top,
  57. endPoint: .bottom
  58. )
  59. :
  60. LinearGradient(
  61. gradient: Gradient(colors: [Color.gray.opacity(0.1)]),
  62. startPoint: .top,
  63. endPoint: .bottom
  64. )
  65. }
  66. var body: some View {
  67. ZStack(alignment: .center) {
  68. VStack {
  69. Picker("Mode", selection: $state.mode) {
  70. ForEach(
  71. Mode.allCases.filter({ state.historyLayout == .twoTabs ? $0 != .meals : true }).indexed(),
  72. id: \.1
  73. ) { index, item in
  74. if state.historyLayout == .threeTabs && item == .treatments {
  75. Text("Insulin")
  76. .tag(index)
  77. } else {
  78. Text(item.name)
  79. .tag(index)
  80. }
  81. }
  82. }
  83. .pickerStyle(SegmentedPickerStyle())
  84. .padding(.horizontal)
  85. Form {
  86. switch state.mode {
  87. case .treatments: treatmentsList
  88. case .glucose: glucoseList
  89. case .meals: state.historyLayout == .threeTabs ? AnyView(mealsList) : AnyView(EmptyView())
  90. }
  91. }.scrollContentBackground(.hidden)
  92. .background(color)
  93. }.blur(radius: state.waitForSuggestion ? 8 : 0)
  94. if state.waitForSuggestion {
  95. CustomProgressView(text: "Updating History...")
  96. }
  97. }
  98. .background(color)
  99. .onAppear(perform: configureView)
  100. .navigationTitle("History")
  101. .navigationBarTitleDisplayMode(.large)
  102. .toolbar {
  103. ToolbarItem(placement: .topBarTrailing) {
  104. switch state.mode {
  105. case .treatments: addButton({
  106. state.showExternalInsulin = true
  107. state.externalInsulinDate = Date()
  108. })
  109. case .meals: EmptyView()
  110. case .glucose: addButton({
  111. showManualGlucose = true
  112. state.manualGlucose = 0
  113. })
  114. }
  115. }
  116. }
  117. .sheet(isPresented: $showManualGlucose) {
  118. addGlucoseView()
  119. }
  120. .sheet(
  121. isPresented: $state.showExternalInsulin,
  122. onDismiss: { if isAmountUnconfirmed { state.externalInsulinAmount = 0
  123. state.externalInsulinDate = Date() } }
  124. ) {
  125. addExternalInsulinView()
  126. }
  127. }
  128. @ViewBuilder func addButton(_ action: @escaping () -> Void) -> some View {
  129. Button(
  130. action: action,
  131. label: {
  132. Image(systemName: "plus")
  133. .font(.system(size: 20))
  134. }
  135. )
  136. }
  137. private var treatmentsList: some View {
  138. List {
  139. HStack {
  140. if state.historyLayout == .twoTabs {
  141. Text("Insulin").foregroundStyle(.secondary)
  142. Spacer()
  143. filterEntriesButton
  144. } else {
  145. Text("Insulin").foregroundStyle(.secondary)
  146. Spacer()
  147. Text("Time").foregroundStyle(.secondary)
  148. }
  149. }
  150. if !state.treatments.isEmpty {
  151. ForEach(state.treatments.filter({ !showFutureEntries ? $0.date <= Date() : true })) { item in
  152. treatmentView(item)
  153. }
  154. } else {
  155. HStack {
  156. Text("No data.")
  157. }
  158. }
  159. }.listRowBackground(Color.chart)
  160. }
  161. private var mealsList: some View {
  162. List {
  163. HStack {
  164. Text("Type").foregroundStyle(.secondary)
  165. Spacer()
  166. filterEntriesButton
  167. }
  168. if !state.meals.isEmpty {
  169. ForEach(state.meals.filter({ !showFutureEntries ? $0.date <= Date() : true })) { item in
  170. mealView(item)
  171. }
  172. } else {
  173. HStack {
  174. Text("No data.")
  175. }
  176. }
  177. }.listRowBackground(Color.chart)
  178. }
  179. private var glucoseList: some View {
  180. List {
  181. HStack {
  182. Text("Values").foregroundStyle(.secondary)
  183. Spacer()
  184. Text("Time").foregroundStyle(.secondary)
  185. }
  186. if !state.glucose.isEmpty {
  187. ForEach(state.glucose) { item in
  188. glucoseView(item, isManual: item.glucose)
  189. }
  190. } else {
  191. HStack {
  192. Text("No data.")
  193. }
  194. }
  195. }.listRowBackground(Color.chart)
  196. }
  197. @ViewBuilder private func addGlucoseView() -> some View {
  198. let limitLow: Decimal = state.units == .mmolL ? 0.8 : 14
  199. let limitHigh: Decimal = state.units == .mmolL ? 40 : 720
  200. NavigationView {
  201. VStack {
  202. Form {
  203. Section {
  204. HStack {
  205. Text("New Glucose")
  206. DecimalTextField(
  207. " ... ",
  208. value: $state.manualGlucose,
  209. formatter: manualGlucoseFormatter,
  210. autofocus: true,
  211. cleanInput: true
  212. )
  213. Text(state.units.rawValue).foregroundStyle(.secondary)
  214. }
  215. }.listRowBackground(Color.chart)
  216. Section {
  217. HStack {
  218. Button {
  219. state.addManualGlucose()
  220. isAmountUnconfirmed = false
  221. showManualGlucose = false
  222. }
  223. label: { Text("Save") }
  224. .frame(maxWidth: .infinity, alignment: .center)
  225. .disabled(state.manualGlucose < limitLow || state.manualGlucose > limitHigh)
  226. }
  227. }
  228. .listRowBackground(
  229. state.manualGlucose < limitLow || state
  230. .manualGlucose > limitHigh ? Color(.systemGray4) : Color(.systemBlue)
  231. )
  232. .tint(.white)
  233. }.scrollContentBackground(.hidden).background(color)
  234. }
  235. .onAppear(perform: configureView)
  236. .navigationTitle("Add Glucose")
  237. .navigationBarTitleDisplayMode(.inline)
  238. .toolbar {
  239. ToolbarItem(placement: .topBarLeading) {
  240. Button("Close") {
  241. showManualGlucose = false
  242. }
  243. }
  244. }
  245. }
  246. }
  247. private var filterEntriesButton: some View {
  248. Button(action: { showFutureEntries.toggle() }, label: {
  249. HStack {
  250. Text(showFutureEntries ? "Hide Future" : "Show Future")
  251. .foregroundColor(Color.secondary)
  252. Image(systemName: showFutureEntries ? "calendar.badge.minus" : "calendar.badge.plus")
  253. }.frame(maxWidth: .infinity, alignment: .trailing)
  254. }).buttonStyle(.borderless)
  255. }
  256. @ViewBuilder private func treatmentView(_ item: Treatment) -> some View {
  257. HStack {
  258. Image(systemName: "circle.fill").foregroundColor(item.color)
  259. Text((item.isSMB ?? false) ? "SMB" : item.type.name)
  260. Text(item.amountText).foregroundColor(.secondary)
  261. if let duration = item.durationText {
  262. Text(duration).foregroundColor(.secondary)
  263. }
  264. Spacer()
  265. Text(dateFormatter.string(from: item.date))
  266. .moveDisabled(true)
  267. }
  268. .swipeActions {
  269. Button(
  270. "Delete",
  271. systemImage: "trash.fill",
  272. role: .none,
  273. action: {
  274. alertTreatmentToDelete = item
  275. if item.type == .carbs {
  276. alertTitle = "Delete Carbs?"
  277. alertMessage = dateFormatter.string(from: item.date) + ", " + item.amountText
  278. } else if item.type == .fpus {
  279. alertTitle = "Delete Carb Equivalents?"
  280. alertMessage = "All FPUs of the meal will be deleted."
  281. } else {
  282. // item is insulin treatment; item.type == .bolus
  283. alertTitle = "Delete Insulin?"
  284. alertMessage = dateFormatter.string(from: item.date) + ", " + item.amountText
  285. if item.isSMB ?? false {
  286. // Add text snippet, so that alert message is more descriptive for SMBs
  287. alertMessage += "SMB"
  288. }
  289. }
  290. isRemoveHistoryItemAlertPresented = true
  291. }
  292. ).tint(.red)
  293. }
  294. .disabled(item.type == .tempBasal || item.type == .tempTarget || item.type == .resume || item.type == .suspend)
  295. .alert(
  296. Text(NSLocalizedString(alertTitle, comment: "")),
  297. isPresented: $isRemoveHistoryItemAlertPresented
  298. ) {
  299. Button("Cancel", role: .cancel) {}
  300. Button("Delete", role: .destructive) {
  301. guard let treatmentToDelete = alertTreatmentToDelete else {
  302. debug(.default, "Cannot gracefully unwrap alertTreatmentToDelete!")
  303. return
  304. }
  305. if state.historyLayout == .twoTabs, treatmentToDelete.type == .carbs || treatmentToDelete.type == .fpus {
  306. state.deleteCarbs(treatmentToDelete)
  307. state.waitForSuggestion = true
  308. } else {
  309. Task {
  310. do {
  311. await state.deleteInsulin(treatmentToDelete)
  312. state.waitForSuggestion = true
  313. }
  314. }
  315. }
  316. }
  317. } message: {
  318. Text("\n" + NSLocalizedString(alertMessage, comment: ""))
  319. }
  320. }
  321. @ViewBuilder private func mealView(_ meal: Treatment) -> some View {
  322. HStack {
  323. Image(systemName: "circle.fill").foregroundColor(meal.color)
  324. Text(meal.type.name)
  325. Text(meal.amountText).foregroundColor(.secondary)
  326. if let duration = meal.durationText {
  327. Text(duration).foregroundColor(.secondary)
  328. }
  329. Spacer()
  330. Text(dateFormatter.string(from: meal.date))
  331. .moveDisabled(true)
  332. }.swipeActions {
  333. Button(
  334. "Delete",
  335. systemImage: "trash.fill",
  336. role: .none,
  337. action: {
  338. alertTreatmentToDelete = meal
  339. if meal.type == .carbs {
  340. alertTitle = "Delete Carbs?"
  341. alertMessage = dateFormatter.string(from: meal.date) + ", " + meal.amountText
  342. } else if meal.type == .fpus {
  343. alertTitle = "Delete Carb Equivalents?"
  344. alertMessage = "All FPUs of the meal will be deleted."
  345. } else {
  346. // item is insulin treatment; item.type == .bolus
  347. alertTitle = "Delete Insulin?"
  348. alertMessage = dateFormatter.string(from: meal.date) + ", " + meal.amountText
  349. }
  350. isRemoveHistoryItemAlertPresented = true
  351. }
  352. ).tint(.red)
  353. }
  354. .alert(
  355. Text(NSLocalizedString(alertTitle, comment: "")),
  356. isPresented: $isRemoveHistoryItemAlertPresented
  357. ) {
  358. Button("Cancel", role: .cancel) {}
  359. Button("Delete", role: .destructive) {
  360. guard let treatmentToDelete = alertTreatmentToDelete else {
  361. debug(.default, "Cannot gracefully unwrap alertTreatmentToDelete!")
  362. return
  363. }
  364. state.deleteCarbs(treatmentToDelete)
  365. state.waitForSuggestion = true
  366. }
  367. } message: {
  368. Text("\n" + NSLocalizedString(alertMessage, comment: ""))
  369. }
  370. }
  371. @ViewBuilder func addExternalInsulinView() -> some View {
  372. NavigationView {
  373. ZStack(alignment: .center) {
  374. VStack {
  375. Form {
  376. Section {
  377. HStack {
  378. Text("Amount")
  379. Spacer()
  380. DecimalTextField(
  381. "0",
  382. value: $state.externalInsulinAmount,
  383. formatter: insulinFormatter,
  384. autofocus: true,
  385. cleanInput: true
  386. )
  387. Text("U").foregroundColor(.secondary)
  388. }
  389. }.listRowBackground(Color.chart)
  390. Section {
  391. DatePicker("Date", selection: $state.externalInsulinDate, in: ...Date())
  392. }.listRowBackground(Color.chart)
  393. let amountWarningCondition = (state.externalInsulinAmount > state.maxBolus)
  394. var listBackgroundColor: Color {
  395. if amountWarningCondition {
  396. return Color.red
  397. } else if state.externalInsulinAmount <= 0 || state.externalInsulinAmount > state.maxBolus * 3 {
  398. return Color(.systemGray4)
  399. } else {
  400. return Color(.systemBlue)
  401. }
  402. }
  403. var foregroundColor: Color {
  404. if amountWarningCondition {
  405. return Color.white
  406. } else if state.externalInsulinAmount <= 0 || state.externalInsulinAmount > state.maxBolus * 3 {
  407. return Color.secondary
  408. } else {
  409. return Color.white
  410. }
  411. }
  412. Section {
  413. HStack {
  414. Button {
  415. Task {
  416. do {
  417. await state.addExternalInsulin()
  418. state.waitForSuggestion = true
  419. state.addButtonPressed = true
  420. isAmountUnconfirmed = false
  421. }
  422. }
  423. } label: {
  424. Text("Log external insulin")
  425. }
  426. .foregroundStyle(foregroundColor)
  427. .frame(maxWidth: .infinity, alignment: .center)
  428. .disabled(
  429. state.externalInsulinAmount <= 0 || state.externalInsulinAmount > state.maxBolus * 3
  430. )
  431. }
  432. }
  433. header: {
  434. if amountWarningCondition
  435. {
  436. Text("⚠️ Warning! The entered insulin amount is greater than your Max Bolus setting!")
  437. }
  438. }
  439. .listRowBackground(listBackgroundColor).tint(.white)
  440. }.scrollContentBackground(.hidden).background(color)
  441. }.blur(radius: state.waitForSuggestion ? 5 : 0)
  442. if state.waitForSuggestion {
  443. CustomProgressView(text: "Updating IOB")
  444. }
  445. }
  446. .onAppear(perform: configureView)
  447. .onDisappear {
  448. state.addButtonPressed = false
  449. }
  450. .navigationTitle("External Insulin")
  451. .navigationBarTitleDisplayMode(.inline)
  452. .toolbar {
  453. ToolbarItem(placement: .topBarLeading) {
  454. Button("Close") {
  455. state.showExternalInsulin = false
  456. state.externalInsulinAmount = 0
  457. }
  458. }
  459. }
  460. }
  461. }
  462. @ViewBuilder private func glucoseView(_ item: Glucose, isManual: BloodGlucose) -> some View {
  463. HStack {
  464. Text(item.glucose.glucose.map {
  465. (
  466. isManual.type == GlucoseType.manual.rawValue ?
  467. manualGlucoseFormatter :
  468. glucoseFormatter
  469. )
  470. .string(from: Double(
  471. state.units == .mmolL ? $0.asMmolL : Decimal($0)
  472. ) as NSNumber)!
  473. } ?? "--")
  474. if isManual.type == GlucoseType.manual.rawValue {
  475. Image(systemName: "drop.fill").symbolRenderingMode(.monochrome).foregroundStyle(.red)
  476. } else {
  477. Text(item.glucose.direction?.symbol ?? "--")
  478. }
  479. Spacer()
  480. Text(dateFormatter.string(from: item.glucose.dateString))
  481. }
  482. .swipeActions {
  483. Button(
  484. "Delete",
  485. systemImage: "trash.fill",
  486. role: .none,
  487. action: {
  488. alertGlucoseToDelete = item
  489. let valueText = (
  490. isManual.type == GlucoseType.manual.rawValue ?
  491. manualGlucoseFormatter :
  492. glucoseFormatter
  493. ).string(from: Double(
  494. state.units == .mmolL ? Double(item.glucose.value.asMmolL) : item.glucose.value
  495. ) as NSNumber)! + " " + state.units.rawValue
  496. alertTitle = "Delete Glucose?"
  497. alertMessage = dateFormatter.string(from: item.glucose.dateString) + ", " + valueText
  498. isRemoveHistoryItemAlertPresented = true
  499. }
  500. ).tint(.red)
  501. }
  502. .alert(
  503. Text(NSLocalizedString(alertTitle, comment: "")),
  504. isPresented: $isRemoveHistoryItemAlertPresented
  505. ) {
  506. Button("Cancel", role: .cancel) {}
  507. Button("Delete", role: .destructive) {
  508. guard let glucoseToDelete = alertGlucoseToDelete else {
  509. print("Cannot unwrap alertTreatmentToDelete!")
  510. return
  511. }
  512. state.deleteGlucose(glucoseToDelete)
  513. }
  514. } message: {
  515. Text("\n" + NSLocalizedString(alertMessage, comment: ""))
  516. }
  517. }
  518. }
  519. }