DataTableRootView.swift 17 KB

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