BolusRootView.swift 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624
  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. if state.carbs > 0 {
  259. handleDebouncedInput()
  260. }
  261. }
  262. Text("g").foregroundColor(.secondary)
  263. }
  264. }
  265. var body: some View {
  266. ZStack(alignment: .center) {
  267. VStack {
  268. Form {
  269. Section {
  270. carbsTextField()
  271. if state.useFPUconversion {
  272. proteinAndFat()
  273. }
  274. // Summary when combining presets
  275. if state.waitersNotepad() != "" {
  276. HStack {
  277. Text("Total")
  278. let test = state.waitersNotepad().components(separatedBy: ", ").removeDublicates()
  279. HStack(spacing: 0) {
  280. ForEach(test, id: \.self) {
  281. Text($0).foregroundStyle(Color.blue).font(.footnote)
  282. Text($0 == test[test.count - 1] ? "" : ", ")
  283. }
  284. }.frame(maxWidth: .infinity, alignment: .trailing)
  285. }
  286. }
  287. // Time
  288. HStack {
  289. Text("Time").foregroundStyle(Color.secondary)
  290. Spacer()
  291. if !pushed {
  292. Button {
  293. pushed = true
  294. } label: { Text("Now") }.buttonStyle(.borderless).foregroundColor(.secondary)
  295. .padding(.trailing, 5)
  296. } else {
  297. Button { state.date = state.date.addingTimeInterval(-15.minutes.timeInterval) }
  298. label: { Image(systemName: "minus.circle") }.tint(.blue).buttonStyle(.borderless)
  299. DatePicker(
  300. "Time",
  301. selection: $state.date,
  302. displayedComponents: [.hourAndMinute]
  303. ).controlSize(.mini)
  304. .labelsHidden()
  305. Button {
  306. state.date = state.date.addingTimeInterval(15.minutes.timeInterval)
  307. }
  308. label: { Image(systemName: "plus.circle") }.tint(.blue).buttonStyle(.borderless)
  309. }
  310. }
  311. .popover(isPresented: $isPromptPresented) {
  312. presetPopover
  313. }
  314. }.listRowBackground(Color.chart)
  315. if state.displayPresets {
  316. Section {
  317. mealPresets
  318. }.listRowBackground(Color.chart)
  319. }
  320. Section {
  321. HStack {
  322. Button(action: {
  323. state.showInfo.toggle()
  324. }, label: {
  325. Image(systemName: "info.circle")
  326. Text("Calculations")
  327. })
  328. .foregroundStyle(.blue)
  329. .font(.footnote)
  330. .buttonStyle(PlainButtonStyle())
  331. .frame(maxWidth: .infinity, alignment: .leading)
  332. if state.fattyMeals {
  333. Spacer()
  334. Toggle(isOn: $state.useFattyMealCorrectionFactor) {
  335. Text("Fatty Meal")
  336. }
  337. .toggleStyle(CheckboxToggleStyle())
  338. .font(.footnote)
  339. .onChange(of: state.useFattyMealCorrectionFactor) { _ in
  340. state.insulinCalculated = state.calculateInsulin()
  341. if state.useFattyMealCorrectionFactor {
  342. state.useSuperBolus = false
  343. }
  344. }
  345. }
  346. if state.sweetMeals {
  347. Spacer()
  348. Toggle(isOn: $state.useSuperBolus) {
  349. Text("Super Bolus")
  350. }
  351. .toggleStyle(CheckboxToggleStyle())
  352. .font(.footnote)
  353. .onChange(of: state.useSuperBolus) { _ in
  354. state.insulinCalculated = state.calculateInsulin()
  355. if state.useSuperBolus {
  356. state.useFattyMealCorrectionFactor = false
  357. }
  358. }
  359. }
  360. }
  361. HStack {
  362. Text("Recommended Bolus")
  363. Spacer()
  364. Text(
  365. formatter
  366. .string(from: Double(state.insulinCalculated) as NSNumber) ?? ""
  367. )
  368. Text(
  369. NSLocalizedString(
  370. " U",
  371. comment: "Unit in number of units delivered (keep the space character!)"
  372. )
  373. ).foregroundColor(.secondary)
  374. }.contentShape(Rectangle())
  375. .onTapGesture { state.amount = state.insulinCalculated }
  376. HStack {
  377. Text("Bolus")
  378. Spacer()
  379. TextFieldWithToolBar(
  380. text: $state.amount,
  381. placeholder: "0",
  382. textColor: colorScheme == .dark ? .white : .blue,
  383. maxLength: 5,
  384. numberFormatter: formatter
  385. )
  386. Text(" U").foregroundColor(.secondary)
  387. }
  388. if state.amount > 0 {
  389. HStack {
  390. Text("External insulin")
  391. Spacer()
  392. Toggle("", isOn: $state.externalInsulin).toggleStyle(Checkbox())
  393. }
  394. }
  395. }.listRowBackground(Color.chart)
  396. Section {
  397. ForeCastChart(state: state, units: $state.units)
  398. .padding(.vertical)
  399. }.listRowBackground(Color.chart)
  400. }
  401. }
  402. .safeAreaInset(edge: .bottom, spacing: 0) {
  403. stickyButton
  404. }.blur(radius: state.waitForSuggestion ? 5 : 0)
  405. if state.waitForSuggestion {
  406. CustomProgressView(text: progressText.rawValue)
  407. }
  408. }
  409. .scrollContentBackground(.hidden).background(color)
  410. .blur(radius: state.showInfo ? 3 : 0)
  411. .navigationTitle("Treatments")
  412. .navigationBarTitleDisplayMode(.inline)
  413. .toolbar(content: {
  414. ToolbarItem(placement: .topBarLeading) {
  415. Button {
  416. state.hideModal()
  417. } label: {
  418. Text("Close")
  419. }
  420. }
  421. })
  422. .onAppear {
  423. configureView {
  424. state.insulinCalculated = state.calculateInsulin()
  425. }
  426. }
  427. .onDisappear {
  428. state.addButtonPressed = false
  429. }
  430. .sheet(isPresented: $state.showInfo) {
  431. PopupView(state: state)
  432. .presentationDetents(
  433. [.fraction(0.9), .large],
  434. selection: $calculatorDetent
  435. )
  436. }
  437. }
  438. var progressText: ProgressText {
  439. switch (state.amount > 0, state.carbs > 0) {
  440. case (true, true):
  441. return .updatingIOBandCOB
  442. case (false, true):
  443. return .updatingCOB
  444. case (true, false):
  445. return .updatingIOB
  446. default:
  447. return .updatingTreatments
  448. }
  449. }
  450. var stickyButton: some View {
  451. ZStack {
  452. Rectangle()
  453. .frame(width: UIScreen.main.bounds.width, height: 120).offset(y: 40)
  454. .shadow(
  455. color: colorScheme == .dark ? Color(red: 0.02745098039, green: 0.1098039216, blue: 0.1411764706) :
  456. Color.black.opacity(0.33),
  457. radius: 3
  458. )
  459. .foregroundStyle(Color.chart)
  460. Button {
  461. state.invokeTreatmentsTask()
  462. } label: {
  463. taskButtonLabel
  464. .font(.headline)
  465. .foregroundStyle(Color.white)
  466. .frame(maxWidth: .infinity, alignment: .center)
  467. .frame(minHeight: 50)
  468. }
  469. .disabled(disableTaskButton)
  470. .background(
  471. (state.externalInsulin ? externalBolusLimit : pumpBolusLimit) ? Color(.systemRed) :
  472. Color(.systemBlue)
  473. )
  474. .shadow(radius: 3)
  475. .clipShape(RoundedRectangle(cornerRadius: 8))
  476. .padding()
  477. .offset(y: 20)
  478. }
  479. }
  480. private var taskButtonLabel: some View {
  481. let hasInsulin = state.amount > 0
  482. let hasCarbs = state.carbs > 0
  483. let hasFatOrProtein = state.fat > 0 || state.protein > 0
  484. switch (hasInsulin, hasCarbs, hasFatOrProtein) {
  485. case (true, true, true):
  486. return Text(
  487. state
  488. .externalInsulin ? (
  489. externalBolusLimit ? "Manual bolus exceeds max bolus!" : "Log meal and external insulin"
  490. ) :
  491. (pumpBolusLimit ? "Pump bolus exceeds max bolus!" : "Log meal and enact bolus")
  492. )
  493. case (true, true, false):
  494. return Text(
  495. state
  496. .externalInsulin ?
  497. (externalBolusLimit ? "Manual bolus exceeds max bolus!" : "Log carbs and external insulin") :
  498. (pumpBolusLimit ? "Pump bolus exceeds max bolus!" : "Log carbs and enact bolus")
  499. )
  500. case (true, false, true):
  501. return Text(
  502. state
  503. .externalInsulin ?
  504. (externalBolusLimit ? "Manual bolus exceeds max bolus!" : "Log FPUs and external insulin") :
  505. (pumpBolusLimit ? "Pump bolus exceeds max bolus!" : "Log FPUs and enact bolus")
  506. )
  507. case (true, false, false):
  508. return Text(
  509. state
  510. .externalInsulin ? (externalBolusLimit ? "Manual bolus exceeds max bolus!" : "Log external insulin") :
  511. (pumpBolusLimit ? "Pump bolus exceeds max bolus!" : "Enact bolus")
  512. )
  513. case (false, true, true):
  514. return Text("Log meal")
  515. case (false, true, false):
  516. return Text("Log carbs")
  517. case (false, false, true):
  518. return Text("Log FPUs")
  519. default:
  520. return Text("Continue without treatment")
  521. }
  522. }
  523. private var pumpBolusLimit: Bool {
  524. state.amount > state.maxBolus
  525. }
  526. private var externalBolusLimit: Bool {
  527. state.amount > state.maxBolus * 3
  528. }
  529. private var disableTaskButton: Bool {
  530. state.amount > 0 ? (state.externalInsulin ? externalBolusLimit : pumpBolusLimit) : false
  531. }
  532. }
  533. struct DividerDouble: View {
  534. var body: some View {
  535. VStack(spacing: 2) {
  536. Rectangle()
  537. .frame(height: 1)
  538. .foregroundColor(.gray.opacity(0.65))
  539. Rectangle()
  540. .frame(height: 1)
  541. .foregroundColor(.gray.opacity(0.65))
  542. }
  543. .frame(height: 4)
  544. .padding(.vertical)
  545. }
  546. }
  547. struct DividerCustom: View {
  548. var body: some View {
  549. Rectangle()
  550. .frame(height: 1)
  551. .foregroundColor(.gray.opacity(0.65))
  552. .padding(.vertical)
  553. }
  554. }
  555. }
  556. // fix iOS 15 bug
  557. struct ActivityIndicator: UIViewRepresentable {
  558. @Binding var isAnimating: Bool
  559. let style: UIActivityIndicatorView.Style
  560. func makeUIView(context _: UIViewRepresentableContext<ActivityIndicator>) -> UIActivityIndicatorView {
  561. UIActivityIndicatorView(style: style)
  562. }
  563. func updateUIView(_ uiView: UIActivityIndicatorView, context _: UIViewRepresentableContext<ActivityIndicator>) {
  564. isAnimating ? uiView.startAnimating() : uiView.stopAnimating()
  565. }
  566. }