DataTableRootView.swift 20 KB

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