DataTableRootView.swift 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546
  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. VStack {
  365. Form {
  366. Section {
  367. HStack {
  368. Text("Amount")
  369. Spacer()
  370. DecimalTextField(
  371. "0",
  372. value: $state.externalInsulinAmount,
  373. formatter: insulinFormatter,
  374. autofocus: true,
  375. cleanInput: true
  376. )
  377. Text("U").foregroundColor(.secondary)
  378. }
  379. }.listRowBackground(Color.chart)
  380. Section {
  381. DatePicker("Date", selection: $state.externalInsulinDate, in: ...Date())
  382. }.listRowBackground(Color.chart)
  383. let amountWarningCondition = (state.externalInsulinAmount > state.maxBolus)
  384. var listBackgroundColor: Color {
  385. if amountWarningCondition {
  386. return Color.red
  387. } else if state.externalInsulinAmount <= 0 || state.externalInsulinAmount > state.maxBolus * 3 {
  388. return Color(.systemGray4)
  389. } else {
  390. return Color(.systemBlue)
  391. }
  392. }
  393. var foregroundColor: Color {
  394. if amountWarningCondition {
  395. return Color.white
  396. } else if state.externalInsulinAmount <= 0 || state.externalInsulinAmount > state.maxBolus * 3 {
  397. return Color.secondary
  398. } else {
  399. return Color.white
  400. }
  401. }
  402. Section {
  403. HStack {
  404. Button {
  405. Task {
  406. do {
  407. await state.addExternalInsulin()
  408. state.waitForSuggestion = true
  409. state.addButtonPressed = true
  410. isAmountUnconfirmed = false
  411. }
  412. }
  413. } label: {
  414. Text("Log external insulin")
  415. }
  416. .foregroundStyle(foregroundColor)
  417. .frame(maxWidth: .infinity, alignment: .center)
  418. .disabled(
  419. state.externalInsulinAmount <= 0 || state.externalInsulinAmount > state.maxBolus * 3
  420. )
  421. }
  422. }
  423. header: {
  424. if amountWarningCondition
  425. {
  426. Text("⚠️ Warning! The entered insulin amount is greater than your Max Bolus setting!")
  427. }
  428. }
  429. .listRowBackground(listBackgroundColor).tint(.white)
  430. }.scrollContentBackground(.hidden).background(color)
  431. }
  432. .onAppear(perform: configureView)
  433. .onDisappear {
  434. state.addButtonPressed = false
  435. }
  436. .navigationTitle("External Insulin")
  437. .navigationBarTitleDisplayMode(.inline)
  438. .toolbar {
  439. ToolbarItem(placement: .topBarLeading) {
  440. Button("Close") {
  441. state.showExternalInsulin = false
  442. state.externalInsulinAmount = 0
  443. }
  444. }
  445. }
  446. }
  447. }
  448. @ViewBuilder private func glucoseView(_ item: Glucose, isManual: BloodGlucose) -> some View {
  449. HStack {
  450. Text(item.glucose.glucose.map {
  451. (
  452. isManual.type == GlucoseType.manual.rawValue ?
  453. manualGlucoseFormatter :
  454. glucoseFormatter
  455. )
  456. .string(from: Double(
  457. state.units == .mmolL ? $0.asMmolL : Decimal($0)
  458. ) as NSNumber)!
  459. } ?? "--")
  460. if isManual.type == GlucoseType.manual.rawValue {
  461. Image(systemName: "drop.fill").symbolRenderingMode(.monochrome).foregroundStyle(.red)
  462. } else {
  463. Text(item.glucose.direction?.symbol ?? "--")
  464. }
  465. Spacer()
  466. Text(dateFormatter.string(from: item.glucose.dateString))
  467. }
  468. .swipeActions {
  469. Button(
  470. "Delete",
  471. systemImage: "trash.fill",
  472. role: .none,
  473. action: {
  474. alertGlucoseToDelete = item
  475. let valueText = (
  476. isManual.type == GlucoseType.manual.rawValue ?
  477. manualGlucoseFormatter :
  478. glucoseFormatter
  479. ).string(from: Double(
  480. state.units == .mmolL ? Double(item.glucose.value.asMmolL) : item.glucose.value
  481. ) as NSNumber)! + " " + state.units.rawValue
  482. alertTitle = "Delete Glucose?"
  483. alertMessage = dateFormatter.string(from: item.glucose.dateString) + ", " + valueText
  484. isRemoveHistoryItemAlertPresented = true
  485. }
  486. ).tint(.red)
  487. }
  488. .alert(
  489. Text(NSLocalizedString(alertTitle, comment: "")),
  490. isPresented: $isRemoveHistoryItemAlertPresented
  491. ) {
  492. Button("Cancel", role: .cancel) {}
  493. Button("Delete", role: .destructive) {
  494. guard let glucoseToDelete = alertGlucoseToDelete else {
  495. print("Cannot unwrap alertTreatmentToDelete!")
  496. return
  497. }
  498. state.deleteGlucose(glucoseToDelete)
  499. }
  500. } message: {
  501. Text("\n" + NSLocalizedString(alertMessage, comment: ""))
  502. }
  503. }
  504. }
  505. }