BolusRootView.swift 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623
  1. import Charts
  2. import CoreData
  3. import LoopKitUI
  4. import SwiftUI
  5. import Swinject
  6. extension Bolus {
  7. struct RootView: BaseView {
  8. enum FocusedField {
  9. case carbs
  10. case fat
  11. case protein
  12. }
  13. @FocusState private var focusedField: FocusedField?
  14. let resolver: Resolver
  15. @StateObject var state = StateModel()
  16. @State private var showAlert = false
  17. @State private var autofocus: Bool = true
  18. @State private var calculatorDetent = PresentationDetent.medium
  19. @State private var pushed: Bool = false
  20. @State private var isPromptPresented: Bool = false
  21. @State private var dish: String = ""
  22. @State private var saved: Bool = false
  23. @State private var debounce: DispatchWorkItem?
  24. @Environment(\.managedObjectContext) var moc
  25. private enum Config {
  26. static let dividerHeight: CGFloat = 2
  27. static let spacing: CGFloat = 3
  28. }
  29. @Environment(\.colorScheme) var colorScheme
  30. @FetchRequest(
  31. entity: MealPresetStored.entity(),
  32. sortDescriptors: [NSSortDescriptor(key: "dish", ascending: true)]
  33. ) var carbPresets: FetchedResults<MealPresetStored>
  34. private var formatter: NumberFormatter {
  35. let formatter = NumberFormatter()
  36. formatter.numberStyle = .decimal
  37. formatter.maximumFractionDigits = 2
  38. return formatter
  39. }
  40. private var mealFormatter: NumberFormatter {
  41. let formatter = NumberFormatter()
  42. formatter.numberStyle = .decimal
  43. formatter.maximumFractionDigits = 1
  44. return formatter
  45. }
  46. private var gluoseFormatter: NumberFormatter {
  47. let formatter = NumberFormatter()
  48. formatter.numberStyle = .decimal
  49. if state.units == .mmolL {
  50. formatter.maximumFractionDigits = 1
  51. } else { formatter.maximumFractionDigits = 0 }
  52. return formatter
  53. }
  54. private var fractionDigits: Int {
  55. if state.units == .mmolL {
  56. return 1
  57. } else { return 0 }
  58. }
  59. private var color: LinearGradient {
  60. colorScheme == .dark ? LinearGradient(
  61. gradient: Gradient(colors: [
  62. Color.bgDarkBlue,
  63. Color.bgDarkerDarkBlue
  64. ]),
  65. startPoint: .top,
  66. endPoint: .bottom
  67. )
  68. :
  69. LinearGradient(
  70. gradient: Gradient(colors: [Color.gray.opacity(0.1)]),
  71. startPoint: .top,
  72. endPoint: .bottom
  73. )
  74. }
  75. private var empty: Bool {
  76. state.useFPUconversion ? (state.carbs <= 0 && state.fat <= 0 && state.protein <= 0) : (state.carbs <= 0)
  77. }
  78. /// Handles macro input (carb, fat, protein) in a debounced fashion.
  79. func handleDebouncedInput() {
  80. debounce?.cancel()
  81. debounce = DispatchWorkItem { [self] in
  82. state.insulinCalculated = state.calculateInsulin()
  83. }
  84. if let debounce = debounce {
  85. DispatchQueue.main.asyncAfter(deadline: .now() + 0.35, execute: debounce)
  86. }
  87. }
  88. private var presetPopover: some View {
  89. Form {
  90. Section {
  91. TextField("Name Of Dish", text: $dish)
  92. Button {
  93. saved = true
  94. if dish != "", saved {
  95. let preset = MealPresetStored(context: moc)
  96. preset.dish = dish
  97. preset.fat = state.fat as NSDecimalNumber
  98. preset.protein = state.protein as NSDecimalNumber
  99. preset.carbs = state.carbs as NSDecimalNumber
  100. if self.moc.hasChanges {
  101. try? moc.save()
  102. }
  103. state.addNewPresetToWaitersNotepad(dish)
  104. saved = false
  105. isPromptPresented = false
  106. }
  107. }
  108. label: { Text("Save") }
  109. Button {
  110. dish = ""
  111. saved = false
  112. isPromptPresented = false }
  113. label: { Text("Cancel") }
  114. } header: { Text("Enter Meal Preset Name") }
  115. }
  116. }
  117. private var minusButton: some View {
  118. Button {
  119. if state.carbs != 0,
  120. (state.carbs - (((state.selection?.carbs ?? 0) as NSDecimalNumber) as Decimal) as Decimal) >= 0
  121. {
  122. state.carbs -= (((state.selection?.carbs ?? 0) as NSDecimalNumber) as Decimal)
  123. } else { state.carbs = 0 }
  124. if state.fat != 0,
  125. (state.fat - (((state.selection?.fat ?? 0) as NSDecimalNumber) as Decimal) as Decimal) >= 0
  126. {
  127. state.fat -= (((state.selection?.fat ?? 0) as NSDecimalNumber) as Decimal)
  128. } else { state.fat = 0 }
  129. if state.protein != 0,
  130. (state.protein - (((state.selection?.protein ?? 0) as NSDecimalNumber) as Decimal) as Decimal) >= 0
  131. {
  132. state.protein -= (((state.selection?.protein ?? 0) as NSDecimalNumber) as Decimal)
  133. } else { state.protein = 0 }
  134. state.removePresetFromNewMeal()
  135. if state.carbs == 0, state.fat == 0, state.protein == 0 { state.summation = [] }
  136. }
  137. label: { Image(systemName: "minus.circle.fill")
  138. .font(.system(size: 20))
  139. }
  140. .disabled(
  141. state
  142. .selection == nil ||
  143. (
  144. !state.summation
  145. .contains(state.selection?.dish ?? "") && (state.selection?.dish ?? "") != ""
  146. )
  147. )
  148. .buttonStyle(.borderless)
  149. .tint(.blue)
  150. }
  151. private var plusButton: some View {
  152. Button {
  153. state.carbs += ((state.selection?.carbs ?? 0) as NSDecimalNumber) as Decimal
  154. state.fat += ((state.selection?.fat ?? 0) as NSDecimalNumber) as Decimal
  155. state.protein += ((state.selection?.protein ?? 0) as NSDecimalNumber) as Decimal
  156. state.addPresetToNewMeal()
  157. }
  158. label: { Image(systemName: "plus.circle.fill")
  159. .font(.system(size: 20))
  160. }
  161. .disabled(state.selection == nil)
  162. .buttonStyle(.borderless)
  163. .tint(.blue)
  164. }
  165. private var mealPresets: some View {
  166. Section {
  167. HStack {
  168. if state.selection != nil {
  169. minusButton
  170. }
  171. Picker("Preset", selection: $state.selection) {
  172. Text("Saved Food").tag(nil as MealPresetStored?)
  173. ForEach(carbPresets, id: \.self) { (preset: MealPresetStored) in
  174. Text(preset.dish ?? "").tag(preset as MealPresetStored?)
  175. }
  176. }
  177. .labelsHidden()
  178. .frame(maxWidth: .infinity, alignment: .center)
  179. ._onBindingChange($state.selection) { _ in
  180. state.carbs += ((state.selection?.carbs ?? 0) as NSDecimalNumber) as Decimal
  181. state.fat += ((state.selection?.fat ?? 0) as NSDecimalNumber) as Decimal
  182. state.protein += ((state.selection?.protein ?? 0) as NSDecimalNumber) as Decimal
  183. state.addToSummation()
  184. }
  185. if state.selection != nil {
  186. plusButton
  187. }
  188. }
  189. HStack {
  190. Button("Delete Preset") {
  191. showAlert.toggle()
  192. }
  193. .disabled(state.selection == nil)
  194. .tint(.orange)
  195. .buttonStyle(.borderless)
  196. .alert(
  197. "Delete preset '\(state.selection?.dish ?? "")'?",
  198. isPresented: $showAlert,
  199. actions: {
  200. Button("No", role: .cancel) {}
  201. Button("Yes", role: .destructive) {
  202. state.deletePreset()
  203. state.carbs += ((state.selection?.carbs ?? 0) as NSDecimalNumber) as Decimal
  204. state.fat += ((state.selection?.fat ?? 0) as NSDecimalNumber) as Decimal
  205. state.protein += ((state.selection?.protein ?? 0) as NSDecimalNumber) as Decimal
  206. state.addPresetToNewMeal()
  207. }
  208. }
  209. )
  210. Spacer()
  211. Button {
  212. isPromptPresented = true
  213. }
  214. label: { Text("Save as Preset") }
  215. .buttonStyle(.borderless)
  216. .disabled(
  217. empty ||
  218. (
  219. (((state.selection?.carbs ?? 0) as NSDecimalNumber) as Decimal) == state
  220. .carbs && (((state.selection?.fat ?? 0) as NSDecimalNumber) as Decimal) == state
  221. .fat && (((state.selection?.protein ?? 0) as NSDecimalNumber) as Decimal) == state
  222. .protein
  223. )
  224. )
  225. }
  226. }
  227. }
  228. @ViewBuilder private func proteinAndFat() -> some View {
  229. HStack {
  230. Text("Fat").foregroundColor(.orange)
  231. Spacer()
  232. TextFieldWithToolBar(text: $state.fat, placeholder: "0", keyboardType: .numberPad, numberFormatter: mealFormatter)
  233. Text("g").foregroundColor(.secondary)
  234. }
  235. HStack {
  236. Text("Protein").foregroundColor(.red)
  237. Spacer()
  238. TextFieldWithToolBar(
  239. text: $state.protein,
  240. placeholder: "0",
  241. keyboardType: .numberPad,
  242. numberFormatter: mealFormatter
  243. )
  244. Text("g").foregroundColor(.secondary)
  245. }
  246. }
  247. @ViewBuilder private func carbsTextField() -> some View {
  248. HStack {
  249. Text("Carbs").fontWeight(.semibold)
  250. Spacer()
  251. TextFieldWithToolBar(
  252. text: $state.carbs,
  253. placeholder: "0",
  254. keyboardType: .numberPad,
  255. numberFormatter: mealFormatter
  256. )
  257. .onChange(of: state.carbs) { _ in
  258. handleDebouncedInput()
  259. }
  260. Text("g").foregroundColor(.secondary)
  261. }
  262. }
  263. var body: some View {
  264. ZStack(alignment: .center) {
  265. VStack {
  266. Form {
  267. Section {
  268. carbsTextField()
  269. if state.useFPUconversion {
  270. proteinAndFat()
  271. }
  272. // Summary when combining presets
  273. if state.waitersNotepad() != "" {
  274. HStack {
  275. Text("Total")
  276. let test = state.waitersNotepad().components(separatedBy: ", ").removeDublicates()
  277. HStack(spacing: 0) {
  278. ForEach(test, id: \.self) {
  279. Text($0).foregroundStyle(Color.blue).font(.footnote)
  280. Text($0 == test[test.count - 1] ? "" : ", ")
  281. }
  282. }.frame(maxWidth: .infinity, alignment: .trailing)
  283. }
  284. }
  285. // Time
  286. HStack {
  287. Text("Time").foregroundStyle(Color.secondary)
  288. Spacer()
  289. if !pushed {
  290. Button {
  291. pushed = true
  292. } label: { Text("Now") }.buttonStyle(.borderless).foregroundColor(.secondary)
  293. .padding(.trailing, 5)
  294. } else {
  295. Button { state.date = state.date.addingTimeInterval(-15.minutes.timeInterval) }
  296. label: { Image(systemName: "minus.circle") }.tint(.blue).buttonStyle(.borderless)
  297. DatePicker(
  298. "Time",
  299. selection: $state.date,
  300. displayedComponents: [.hourAndMinute]
  301. ).controlSize(.mini)
  302. .labelsHidden()
  303. Button {
  304. state.date = state.date.addingTimeInterval(15.minutes.timeInterval)
  305. }
  306. label: { Image(systemName: "plus.circle") }.tint(.blue).buttonStyle(.borderless)
  307. }
  308. }
  309. .popover(isPresented: $isPromptPresented) {
  310. presetPopover
  311. }
  312. }.listRowBackground(Color.chart)
  313. if state.displayPresets {
  314. Section {
  315. mealPresets
  316. }.listRowBackground(Color.chart)
  317. }
  318. Section {
  319. HStack {
  320. Button(action: {
  321. state.showInfo.toggle()
  322. }, label: {
  323. Image(systemName: "info.circle")
  324. Text("Calculations")
  325. })
  326. .foregroundStyle(.blue)
  327. .font(.footnote)
  328. .buttonStyle(PlainButtonStyle())
  329. .frame(maxWidth: .infinity, alignment: .leading)
  330. if state.fattyMeals {
  331. Spacer()
  332. Toggle(isOn: $state.useFattyMealCorrectionFactor) {
  333. Text("Fatty Meal")
  334. }
  335. .toggleStyle(CheckboxToggleStyle())
  336. .font(.footnote)
  337. .onChange(of: state.useFattyMealCorrectionFactor) { _ in
  338. state.insulinCalculated = state.calculateInsulin()
  339. if state.useFattyMealCorrectionFactor {
  340. state.useSuperBolus = false
  341. }
  342. }
  343. }
  344. if state.sweetMeals {
  345. Spacer()
  346. Toggle(isOn: $state.useSuperBolus) {
  347. Text("Super Bolus")
  348. }
  349. .toggleStyle(CheckboxToggleStyle())
  350. .font(.footnote)
  351. .onChange(of: state.useSuperBolus) { _ in
  352. state.insulinCalculated = state.calculateInsulin()
  353. if state.useSuperBolus {
  354. state.useFattyMealCorrectionFactor = false
  355. }
  356. }
  357. }
  358. }
  359. HStack {
  360. Text("Recommended Bolus")
  361. Spacer()
  362. Text(
  363. formatter
  364. .string(from: Double(state.insulinCalculated) as NSNumber) ?? ""
  365. )
  366. Text(
  367. NSLocalizedString(
  368. " U",
  369. comment: "Unit in number of units delivered (keep the space character!)"
  370. )
  371. ).foregroundColor(.secondary)
  372. }.contentShape(Rectangle())
  373. .onTapGesture { state.amount = state.insulinCalculated }
  374. HStack {
  375. Text("Bolus")
  376. Spacer()
  377. TextFieldWithToolBar(
  378. text: $state.amount,
  379. placeholder: "0",
  380. textColor: colorScheme == .dark ? .white : .blue,
  381. maxLength: 5,
  382. numberFormatter: formatter
  383. )
  384. Text(" U").foregroundColor(.secondary)
  385. }
  386. if state.amount > 0 {
  387. HStack {
  388. Text("External insulin")
  389. Spacer()
  390. Toggle("", isOn: $state.externalInsulin).toggleStyle(Checkbox())
  391. }
  392. }
  393. }.listRowBackground(Color.chart)
  394. }
  395. }
  396. .safeAreaInset(edge: .bottom, spacing: 0) {
  397. stickyButton
  398. }.blur(radius: state.waitForSuggestion ? 5 : 0)
  399. if state.waitForSuggestion {
  400. CustomProgressView(text: progressText.rawValue)
  401. }
  402. }
  403. .scrollContentBackground(.hidden).background(color)
  404. .blur(radius: state.showInfo ? 3 : 0)
  405. .navigationTitle("Treatments")
  406. .navigationBarTitleDisplayMode(.inline)
  407. .toolbar(content: {
  408. ToolbarItem(placement: .topBarLeading) {
  409. Button {
  410. state.hideModal()
  411. } label: {
  412. Text("Close")
  413. }
  414. }
  415. })
  416. .onAppear {
  417. configureView {
  418. state.insulinCalculated = state.calculateInsulin()
  419. }
  420. }
  421. .onDisappear {
  422. state.addButtonPressed = false
  423. }
  424. .sheet(isPresented: $state.showInfo) {
  425. PopupView(state: state)
  426. .presentationDetents(
  427. [.fraction(0.9), .large],
  428. selection: $calculatorDetent
  429. )
  430. }
  431. }
  432. var progressText: ProgressText {
  433. switch (state.amount > 0, state.carbs > 0) {
  434. case (true, true):
  435. return .updatingIOBandCOB
  436. case (false, true):
  437. return .updatingCOB
  438. case (true, false):
  439. return .updatingIOB
  440. default:
  441. return .updatingTreatments
  442. }
  443. }
  444. var stickyButton: some View {
  445. ZStack {
  446. Rectangle()
  447. .frame(width: UIScreen.main.bounds.width, height: 120).offset(y: 40)
  448. .shadow(
  449. color: colorScheme == .dark ? Color(red: 0.02745098039, green: 0.1098039216, blue: 0.1411764706) :
  450. Color.black.opacity(0.33),
  451. radius: 3
  452. )
  453. .foregroundStyle(Color.chart)
  454. Button {
  455. state.invokeTreatmentsTask()
  456. } label: {
  457. taskButtonLabel
  458. .font(.headline)
  459. .foregroundStyle(Color.white)
  460. .frame(maxWidth: .infinity, alignment: .center)
  461. .frame(minHeight: 50)
  462. }
  463. .disabled(disableTaskButton)
  464. .background(limitExceeded ? Color(.systemRed) : Color(.systemBlue))
  465. .shadow(radius: 3)
  466. .clipShape(RoundedRectangle(cornerRadius: 8))
  467. .padding()
  468. .offset(y: 20)
  469. }
  470. }
  471. private var taskButtonLabel: some View {
  472. if pumpBolusLimitExceeded {
  473. return Text("Max Bolus of \(state.maxBolus) U Exceeded")
  474. } else if externalBolusLimitExceeded {
  475. return Text("Max External Bolus of \(state.maxExternal) U Exceeded")
  476. } else if carbLimitExceeded {
  477. return Text("Max Carbs of \(state.maxCarbs) g Exceeded")
  478. } else if fatLimitExceeded {
  479. return Text("Max Fat of \(state.maxFat) g Exceeded")
  480. } else if proteinLimitExceeded {
  481. return Text("Max Protein of \(state.maxProtein) g Exceeded")
  482. }
  483. let hasInsulin = state.amount > 0
  484. let hasCarbs = state.carbs > 0
  485. let hasFatOrProtein = state.fat > 0 || state.protein > 0
  486. let bolusString = state.externalInsulin ? "External Insulin" : "Enact Bolus"
  487. switch (hasInsulin, hasCarbs, hasFatOrProtein) {
  488. case (true, true, true):
  489. return Text("Log Meal and \(bolusString)")
  490. case (true, true, false):
  491. return Text("Log Carbs and \(bolusString)")
  492. case (true, false, true):
  493. return Text("Log FPU and \(bolusString)")
  494. case (true, false, false):
  495. return Text(state.externalInsulin ? "Log External Insulin" : "Enact Bolus")
  496. case (false, true, true):
  497. return Text("Log Meal")
  498. case (false, true, false):
  499. return Text("Log Carbs")
  500. case (false, false, true):
  501. return Text("Log FPU")
  502. default:
  503. return Text("Continue Without Treatment")
  504. }
  505. }
  506. private var pumpBolusLimitExceeded: Bool {
  507. !state.externalInsulin && state.amount > state.maxBolus
  508. }
  509. private var externalBolusLimitExceeded: Bool {
  510. state.externalInsulin && state.amount > state.maxExternal
  511. }
  512. private var carbLimitExceeded: Bool {
  513. state.carbs > state.maxCarbs
  514. }
  515. private var fatLimitExceeded: Bool {
  516. state.fat > state.maxFat
  517. }
  518. private var proteinLimitExceeded: Bool {
  519. state.protein > state.maxProtein
  520. }
  521. private var limitExceeded: Bool {
  522. pumpBolusLimitExceeded || externalBolusLimitExceeded || carbLimitExceeded || fatLimitExceeded || proteinLimitExceeded
  523. }
  524. private var disableTaskButton: Bool {
  525. state.addButtonPressed || limitExceeded
  526. }
  527. }
  528. struct DividerDouble: View {
  529. var body: some View {
  530. VStack(spacing: 2) {
  531. Rectangle()
  532. .frame(height: 1)
  533. .foregroundColor(.gray.opacity(0.65))
  534. Rectangle()
  535. .frame(height: 1)
  536. .foregroundColor(.gray.opacity(0.65))
  537. }
  538. .frame(height: 4)
  539. .padding(.vertical)
  540. }
  541. }
  542. struct DividerCustom: View {
  543. var body: some View {
  544. Rectangle()
  545. .frame(height: 1)
  546. .foregroundColor(.gray.opacity(0.65))
  547. .padding(.vertical)
  548. }
  549. }
  550. }
  551. // fix iOS 15 bug
  552. struct ActivityIndicator: UIViewRepresentable {
  553. @Binding var isAnimating: Bool
  554. let style: UIActivityIndicatorView.Style
  555. func makeUIView(context _: UIViewRepresentableContext<ActivityIndicator>) -> UIActivityIndicatorView {
  556. UIActivityIndicatorView(style: style)
  557. }
  558. func updateUIView(_ uiView: UIActivityIndicatorView, context _: UIViewRepresentableContext<ActivityIndicator>) {
  559. isAnimating ? uiView.startAnimating() : uiView.stopAnimating()
  560. }
  561. }