DataTableRootView.swift 20 KB

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