DataTableRootView.swift 22 KB

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