DataTableRootView.swift 21 KB

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