DataTableRootView.swift 22 KB

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