DataTableRootView.swift 23 KB

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