DataTableRootView.swift 22 KB

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