DataTableRootView.swift 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  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. state.deleteInsulin(treatmentToDelete)
  301. }
  302. }
  303. } message: {
  304. Text("\n" + NSLocalizedString(alertMessage, comment: ""))
  305. }
  306. }
  307. @ViewBuilder private func mealView(_ meal: Treatment) -> some View {
  308. HStack {
  309. Image(systemName: "circle.fill").foregroundColor(meal.color)
  310. Text(meal.type.name)
  311. Text(meal.amountText).foregroundColor(.secondary)
  312. if let duration = meal.durationText {
  313. Text(duration).foregroundColor(.secondary)
  314. }
  315. Spacer()
  316. Text(dateFormatter.string(from: meal.date))
  317. .moveDisabled(true)
  318. }.swipeActions {
  319. Button(
  320. "Delete",
  321. systemImage: "trash.fill",
  322. role: .none,
  323. action: {
  324. alertTreatmentToDelete = meal
  325. if meal.type == .carbs {
  326. alertTitle = "Delete Carbs?"
  327. alertMessage = dateFormatter.string(from: meal.date) + ", " + meal.amountText
  328. } else if meal.type == .fpus {
  329. alertTitle = "Delete Carb Equivalents?"
  330. alertMessage = "All FPUs of the meal will be deleted."
  331. } else {
  332. // item is insulin treatment; item.type == .bolus
  333. alertTitle = "Delete Insulin?"
  334. alertMessage = dateFormatter.string(from: meal.date) + ", " + meal.amountText
  335. }
  336. isRemoveHistoryItemAlertPresented = true
  337. }
  338. ).tint(.red)
  339. }
  340. .alert(
  341. Text(NSLocalizedString(alertTitle, comment: "")),
  342. isPresented: $isRemoveHistoryItemAlertPresented
  343. ) {
  344. Button("Cancel", role: .cancel) {}
  345. Button("Delete", role: .destructive) {
  346. guard let treatmentToDelete = alertTreatmentToDelete else {
  347. debug(.default, "Cannot gracefully unwrap alertTreatmentToDelete!")
  348. return
  349. }
  350. state.deleteCarbs(treatmentToDelete)
  351. }
  352. } message: {
  353. Text("\n" + NSLocalizedString(alertMessage, comment: ""))
  354. }
  355. }
  356. @ViewBuilder func addExternalInsulinView() -> some View {
  357. NavigationView {
  358. VStack {
  359. Form {
  360. Section {
  361. HStack {
  362. Text("Amount")
  363. Spacer()
  364. DecimalTextField(
  365. "0",
  366. value: $state.externalInsulinAmount,
  367. formatter: insulinFormatter,
  368. autofocus: true,
  369. cleanInput: true
  370. )
  371. Text("U").foregroundColor(.secondary)
  372. }
  373. }.listRowBackground(Color.chart)
  374. Section {
  375. DatePicker("Date", selection: $state.externalInsulinDate, in: ...Date())
  376. }.listRowBackground(Color.chart)
  377. let amountWarningCondition = (state.externalInsulinAmount > state.maxBolus)
  378. var listBackgroundColor: Color {
  379. if amountWarningCondition {
  380. return Color.red
  381. } else if state.externalInsulinAmount <= 0 || state.externalInsulinAmount > state.maxBolus * 3 {
  382. return Color(.systemGray4)
  383. } else {
  384. return Color(.systemBlue)
  385. }
  386. }
  387. var foregroundColor: Color {
  388. if amountWarningCondition {
  389. return Color.white
  390. } else if state.externalInsulinAmount <= 0 || state.externalInsulinAmount > state.maxBolus * 3 {
  391. return Color.secondary
  392. } else {
  393. return Color.white
  394. }
  395. }
  396. Section {
  397. HStack {
  398. Button {
  399. state.addExternalInsulin()
  400. isAmountUnconfirmed = false
  401. showExternalInsulin = false
  402. }
  403. label: {
  404. Text("Log external insulin")
  405. }
  406. .foregroundStyle(foregroundColor)
  407. .frame(maxWidth: .infinity, alignment: .center)
  408. .disabled(
  409. state.externalInsulinAmount <= 0 || state.externalInsulinAmount > state.maxBolus * 3
  410. )
  411. }
  412. }
  413. header: {
  414. if amountWarningCondition
  415. {
  416. Text("⚠️ Warning! The entered insulin amount is greater than your Max Bolus setting!")
  417. }
  418. }
  419. .listRowBackground(listBackgroundColor).tint(.white)
  420. }.scrollContentBackground(.hidden).background(color)
  421. }
  422. .onAppear(perform: configureView)
  423. .navigationTitle("External Insulin")
  424. .navigationBarTitleDisplayMode(.inline)
  425. .toolbar {
  426. ToolbarItem(placement: .topBarLeading) {
  427. Button("Close") {
  428. showExternalInsulin = false
  429. state.externalInsulinAmount = 0
  430. }
  431. }
  432. }
  433. }
  434. }
  435. @ViewBuilder private func glucoseView(_ item: Glucose, isManual: BloodGlucose) -> some View {
  436. HStack {
  437. Text(item.glucose.glucose.map {
  438. (
  439. isManual.type == GlucoseType.manual.rawValue ?
  440. manualGlucoseFormatter :
  441. glucoseFormatter
  442. )
  443. .string(from: Double(
  444. state.units == .mmolL ? $0.asMmolL : Decimal($0)
  445. ) as NSNumber)!
  446. } ?? "--")
  447. if isManual.type == GlucoseType.manual.rawValue {
  448. Image(systemName: "drop.fill").symbolRenderingMode(.monochrome).foregroundStyle(.red)
  449. } else {
  450. Text(item.glucose.direction?.symbol ?? "--")
  451. }
  452. Spacer()
  453. Text(dateFormatter.string(from: item.glucose.dateString))
  454. }
  455. .swipeActions {
  456. Button(
  457. "Delete",
  458. systemImage: "trash.fill",
  459. role: .none,
  460. action: {
  461. alertGlucoseToDelete = item
  462. let valueText = (
  463. isManual.type == GlucoseType.manual.rawValue ?
  464. manualGlucoseFormatter :
  465. glucoseFormatter
  466. ).string(from: Double(
  467. state.units == .mmolL ? Double(item.glucose.value.asMmolL) : item.glucose.value
  468. ) as NSNumber)! + " " + state.units.rawValue
  469. alertTitle = "Delete Glucose?"
  470. alertMessage = dateFormatter.string(from: item.glucose.dateString) + ", " + valueText
  471. isRemoveHistoryItemAlertPresented = true
  472. }
  473. ).tint(.red)
  474. }
  475. .alert(
  476. Text(NSLocalizedString(alertTitle, comment: "")),
  477. isPresented: $isRemoveHistoryItemAlertPresented
  478. ) {
  479. Button("Cancel", role: .cancel) {}
  480. Button("Delete", role: .destructive) {
  481. guard let glucoseToDelete = alertGlucoseToDelete else {
  482. print("Cannot unwrap alertTreatmentToDelete!")
  483. return
  484. }
  485. state.deleteGlucose(glucoseToDelete)
  486. }
  487. } message: {
  488. Text("\n" + NSLocalizedString(alertMessage, comment: ""))
  489. }
  490. }
  491. }
  492. }