DataTableRootView.swift 16 KB

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