BolusRootView.swift 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619
  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. }
  397. }
  398. .safeAreaInset(edge: .bottom, spacing: 0) {
  399. stickyButton
  400. }.blur(radius: state.waitForSuggestion ? 5 : 0)
  401. if state.waitForSuggestion {
  402. CustomProgressView(text: progressText.rawValue)
  403. }
  404. }
  405. .scrollContentBackground(.hidden).background(color)
  406. .blur(radius: state.showInfo ? 3 : 0)
  407. .navigationTitle("Treatments")
  408. .navigationBarTitleDisplayMode(.inline)
  409. .toolbar(content: {
  410. ToolbarItem(placement: .topBarLeading) {
  411. Button {
  412. state.hideModal()
  413. } label: {
  414. Text("Close")
  415. }
  416. }
  417. })
  418. .onAppear {
  419. configureView {
  420. state.insulinCalculated = state.calculateInsulin()
  421. }
  422. }
  423. .onDisappear {
  424. state.addButtonPressed = false
  425. }
  426. .sheet(isPresented: $state.showInfo) {
  427. PopupView(state: state)
  428. .presentationDetents(
  429. [.fraction(0.9), .large],
  430. selection: $calculatorDetent
  431. )
  432. }
  433. }
  434. var progressText: ProgressText {
  435. switch (state.amount > 0, state.carbs > 0) {
  436. case (true, true):
  437. return .updatingIOBandCOB
  438. case (false, true):
  439. return .updatingCOB
  440. case (true, false):
  441. return .updatingIOB
  442. default:
  443. return .updatingTreatments
  444. }
  445. }
  446. var stickyButton: some View {
  447. ZStack {
  448. Rectangle()
  449. .frame(width: UIScreen.main.bounds.width, height: 120).offset(y: 40)
  450. .shadow(
  451. color: colorScheme == .dark ? Color(red: 0.02745098039, green: 0.1098039216, blue: 0.1411764706) :
  452. Color.black.opacity(0.33),
  453. radius: 3
  454. )
  455. .foregroundStyle(Color.chart)
  456. Button {
  457. state.invokeTreatmentsTask()
  458. } label: {
  459. taskButtonLabel
  460. .font(.headline)
  461. .foregroundStyle(Color.white)
  462. .frame(maxWidth: .infinity, alignment: .center)
  463. .frame(minHeight: 50)
  464. }
  465. .disabled(disableTaskButton)
  466. .background(
  467. (state.externalInsulin ? externalBolusLimit : pumpBolusLimit) ? Color(.systemRed) :
  468. Color(.systemBlue)
  469. )
  470. .shadow(radius: 3)
  471. .clipShape(RoundedRectangle(cornerRadius: 8))
  472. .padding()
  473. .offset(y: 20)
  474. }
  475. }
  476. private var taskButtonLabel: some View {
  477. let hasInsulin = state.amount > 0
  478. let hasCarbs = state.carbs > 0
  479. let hasFatOrProtein = state.fat > 0 || state.protein > 0
  480. switch (hasInsulin, hasCarbs, hasFatOrProtein) {
  481. case (true, true, true):
  482. return Text(
  483. state
  484. .externalInsulin ? (
  485. externalBolusLimit ? "Manual bolus exceeds max bolus!" : "Log meal and external insulin"
  486. ) :
  487. (pumpBolusLimit ? "Pump bolus exceeds max bolus!" : "Log meal and enact bolus")
  488. )
  489. case (true, true, false):
  490. return Text(
  491. state
  492. .externalInsulin ?
  493. (externalBolusLimit ? "Manual bolus exceeds max bolus!" : "Log carbs and external insulin") :
  494. (pumpBolusLimit ? "Pump bolus exceeds max bolus!" : "Log carbs and enact bolus")
  495. )
  496. case (true, false, true):
  497. return Text(
  498. state
  499. .externalInsulin ?
  500. (externalBolusLimit ? "Manual bolus exceeds max bolus!" : "Log FPUs and external insulin") :
  501. (pumpBolusLimit ? "Pump bolus exceeds max bolus!" : "Log FPUs and enact bolus")
  502. )
  503. case (true, false, false):
  504. return Text(
  505. state
  506. .externalInsulin ? (externalBolusLimit ? "Manual bolus exceeds max bolus!" : "Log external insulin") :
  507. (pumpBolusLimit ? "Pump bolus exceeds max bolus!" : "Enact bolus")
  508. )
  509. case (false, true, true):
  510. return Text("Log meal")
  511. case (false, true, false):
  512. return Text("Log carbs")
  513. case (false, false, true):
  514. return Text("Log FPUs")
  515. default:
  516. return Text("Continue without treatment")
  517. }
  518. }
  519. private var pumpBolusLimit: Bool {
  520. state.amount > state.maxBolus
  521. }
  522. private var externalBolusLimit: Bool {
  523. state.amount > state.maxBolus * 3
  524. }
  525. private var disableTaskButton: Bool {
  526. state.amount > 0 ? (state.externalInsulin ? externalBolusLimit : pumpBolusLimit) : false
  527. }
  528. }
  529. struct DividerDouble: View {
  530. var body: some View {
  531. VStack(spacing: 2) {
  532. Rectangle()
  533. .frame(height: 1)
  534. .foregroundColor(.gray.opacity(0.65))
  535. Rectangle()
  536. .frame(height: 1)
  537. .foregroundColor(.gray.opacity(0.65))
  538. }
  539. .frame(height: 4)
  540. .padding(.vertical)
  541. }
  542. }
  543. struct DividerCustom: View {
  544. var body: some View {
  545. Rectangle()
  546. .frame(height: 1)
  547. .foregroundColor(.gray.opacity(0.65))
  548. .padding(.vertical)
  549. }
  550. }
  551. }
  552. // fix iOS 15 bug
  553. struct ActivityIndicator: UIViewRepresentable {
  554. @Binding var isAnimating: Bool
  555. let style: UIActivityIndicatorView.Style
  556. func makeUIView(context _: UIViewRepresentableContext<ActivityIndicator>) -> UIActivityIndicatorView {
  557. UIActivityIndicatorView(style: style)
  558. }
  559. func updateUIView(_ uiView: UIActivityIndicatorView, context _: UIViewRepresentableContext<ActivityIndicator>) {
  560. isAnimating ? uiView.startAnimating() : uiView.stopAnimating()
  561. }
  562. }