DataTableRootView.swift 20 KB

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