BolusRootView.swift 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615
  1. import Charts
  2. import CoreData
  3. import LoopKitUI
  4. import SwiftUI
  5. import Swinject
  6. extension Bolus {
  7. struct RootView: BaseView {
  8. let resolver: Resolver
  9. @StateObject var state = StateModel()
  10. @State private var showAlert = false
  11. @State private var autofocus: Bool = true
  12. @State private var calculatorDetent = PresentationDetent.medium
  13. @State private var pushed: Bool = false
  14. @State private var isPromptPresented: Bool = false
  15. @State private var dish: String = ""
  16. @State private var saved: Bool = false
  17. @State private var debounce: DispatchWorkItem?
  18. @Environment(\.managedObjectContext) var moc
  19. private enum Config {
  20. static let dividerHeight: CGFloat = 2
  21. static let spacing: CGFloat = 3
  22. }
  23. @Environment(\.colorScheme) var colorScheme
  24. @FetchRequest(
  25. entity: Presets.entity(),
  26. sortDescriptors: [NSSortDescriptor(key: "dish", ascending: true)]
  27. ) var carbPresets: FetchedResults<Presets>
  28. private var formatter: NumberFormatter {
  29. let formatter = NumberFormatter()
  30. formatter.numberStyle = .decimal
  31. formatter.maximumFractionDigits = 2
  32. return formatter
  33. }
  34. private var mealFormatter: NumberFormatter {
  35. let formatter = NumberFormatter()
  36. formatter.numberStyle = .decimal
  37. formatter.maximumFractionDigits = 1
  38. return formatter
  39. }
  40. private var gluoseFormatter: NumberFormatter {
  41. let formatter = NumberFormatter()
  42. formatter.numberStyle = .decimal
  43. if state.units == .mmolL {
  44. formatter.maximumFractionDigits = 1
  45. } else { formatter.maximumFractionDigits = 0 }
  46. return formatter
  47. }
  48. private var fractionDigits: Int {
  49. if state.units == .mmolL {
  50. return 1
  51. } else { return 0 }
  52. }
  53. private var color: LinearGradient {
  54. colorScheme == .dark ? LinearGradient(
  55. gradient: Gradient(colors: [
  56. Color.bgDarkBlue,
  57. Color.bgDarkerDarkBlue
  58. ]),
  59. startPoint: .top,
  60. endPoint: .bottom
  61. )
  62. :
  63. LinearGradient(
  64. gradient: Gradient(colors: [Color.gray.opacity(0.1)]),
  65. startPoint: .top,
  66. endPoint: .bottom
  67. )
  68. }
  69. private var empty: Bool {
  70. state.useFPUconversion ? (state.carbs <= 0 && state.fat <= 0 && state.protein <= 0) : (state.carbs <= 0)
  71. }
  72. /// Handles macro input (carb, fat, protein) in a debounced fashion.
  73. func handleDebouncedInput() {
  74. debounce?.cancel()
  75. debounce = DispatchWorkItem { [self] in
  76. state.insulinCalculated = state.calculateInsulin()
  77. }
  78. if let debounce = debounce {
  79. DispatchQueue.main.asyncAfter(deadline: .now() + 0.35, execute: debounce)
  80. }
  81. }
  82. private var presetPopover: some View {
  83. Form {
  84. Section {
  85. TextField("Name Of Dish", text: $dish)
  86. Button {
  87. saved = true
  88. if dish != "", saved {
  89. let preset = Presets(context: moc)
  90. preset.dish = dish
  91. preset.fat = state.fat as NSDecimalNumber
  92. preset.protein = state.protein as NSDecimalNumber
  93. preset.carbs = state.carbs as NSDecimalNumber
  94. if self.moc.hasChanges {
  95. try? moc.save()
  96. }
  97. state.addNewPresetToWaitersNotepad(dish)
  98. saved = false
  99. isPromptPresented = false
  100. }
  101. }
  102. label: { Text("Save") }
  103. Button {
  104. dish = ""
  105. saved = false
  106. isPromptPresented = false }
  107. label: { Text("Cancel") }
  108. } header: { Text("Enter Meal Preset Name") }
  109. }
  110. }
  111. private var minusButton: some View {
  112. Button {
  113. if state.carbs != 0,
  114. (state.carbs - (((state.selection?.carbs ?? 0) as NSDecimalNumber) as Decimal) as Decimal) >= 0
  115. {
  116. state.carbs -= (((state.selection?.carbs ?? 0) as NSDecimalNumber) as Decimal)
  117. } else { state.carbs = 0 }
  118. if state.fat != 0,
  119. (state.fat - (((state.selection?.fat ?? 0) as NSDecimalNumber) as Decimal) as Decimal) >= 0
  120. {
  121. state.fat -= (((state.selection?.fat ?? 0) as NSDecimalNumber) as Decimal)
  122. } else { state.fat = 0 }
  123. if state.protein != 0,
  124. (state.protein - (((state.selection?.protein ?? 0) as NSDecimalNumber) as Decimal) as Decimal) >= 0
  125. {
  126. state.protein -= (((state.selection?.protein ?? 0) as NSDecimalNumber) as Decimal)
  127. } else { state.protein = 0 }
  128. state.removePresetFromNewMeal()
  129. if state.carbs == 0, state.fat == 0, state.protein == 0 { state.summation = [] }
  130. }
  131. label: { Image(systemName: "minus.circle.fill")
  132. .font(.system(size: 20))
  133. }
  134. .disabled(
  135. state
  136. .selection == nil ||
  137. (
  138. !state.summation
  139. .contains(state.selection?.dish ?? "") && (state.selection?.dish ?? "") != ""
  140. )
  141. )
  142. .buttonStyle(.borderless)
  143. .tint(.blue)
  144. }
  145. private var plusButton: some View {
  146. Button {
  147. state.carbs += ((state.selection?.carbs ?? 0) as NSDecimalNumber) as Decimal
  148. state.fat += ((state.selection?.fat ?? 0) as NSDecimalNumber) as Decimal
  149. state.protein += ((state.selection?.protein ?? 0) as NSDecimalNumber) as Decimal
  150. state.addPresetToNewMeal()
  151. }
  152. label: { Image(systemName: "plus.circle.fill")
  153. .font(.system(size: 20))
  154. }
  155. .disabled(state.selection == nil)
  156. .buttonStyle(.borderless)
  157. .tint(.blue)
  158. }
  159. private var mealPresets: some View {
  160. Section {
  161. HStack {
  162. if state.selection != nil {
  163. minusButton
  164. }
  165. Picker("Preset", selection: $state.selection) {
  166. Text("Saved Food").tag(nil as Presets?)
  167. ForEach(carbPresets, id: \.self) { (preset: Presets) in
  168. Text(preset.dish ?? "").tag(preset as Presets?)
  169. }
  170. }
  171. .labelsHidden()
  172. .frame(maxWidth: .infinity, alignment: .center)
  173. ._onBindingChange($state.selection) { _ in
  174. state.carbs += ((state.selection?.carbs ?? 0) as NSDecimalNumber) as Decimal
  175. state.fat += ((state.selection?.fat ?? 0) as NSDecimalNumber) as Decimal
  176. state.protein += ((state.selection?.protein ?? 0) as NSDecimalNumber) as Decimal
  177. state.addToSummation()
  178. }
  179. if state.selection != nil {
  180. plusButton
  181. }
  182. }
  183. HStack {
  184. Button("Delete Preset") {
  185. showAlert.toggle()
  186. }
  187. .disabled(state.selection == nil)
  188. .tint(.orange)
  189. .buttonStyle(.borderless)
  190. .alert(
  191. "Delete preset '\(state.selection?.dish ?? "")'?",
  192. isPresented: $showAlert,
  193. actions: {
  194. Button("No", role: .cancel) {}
  195. Button("Yes", role: .destructive) {
  196. state.deletePreset()
  197. state.carbs += ((state.selection?.carbs ?? 0) as NSDecimalNumber) as Decimal
  198. state.fat += ((state.selection?.fat ?? 0) as NSDecimalNumber) as Decimal
  199. state.protein += ((state.selection?.protein ?? 0) as NSDecimalNumber) as Decimal
  200. state.addPresetToNewMeal()
  201. }
  202. }
  203. )
  204. Spacer()
  205. Button {
  206. isPromptPresented = true
  207. }
  208. label: { Text("Save as Preset") }
  209. .buttonStyle(.borderless)
  210. .disabled(
  211. empty ||
  212. (
  213. (((state.selection?.carbs ?? 0) as NSDecimalNumber) as Decimal) == state
  214. .carbs && (((state.selection?.fat ?? 0) as NSDecimalNumber) as Decimal) == state
  215. .fat && (((state.selection?.protein ?? 0) as NSDecimalNumber) as Decimal) == state
  216. .protein
  217. )
  218. )
  219. }
  220. }
  221. }
  222. @ViewBuilder private func proteinAndFat() -> some View {
  223. HStack {
  224. Text("Fat").foregroundColor(.orange)
  225. Spacer()
  226. DecimalTextField(
  227. "0",
  228. value: $state.fat,
  229. formatter: formatter,
  230. autofocus: false,
  231. cleanInput: true
  232. )
  233. Text("g").foregroundColor(.secondary)
  234. }
  235. HStack {
  236. Text("Protein").foregroundColor(.red)
  237. Spacer()
  238. DecimalTextField(
  239. "0",
  240. value: $state.protein,
  241. formatter: formatter,
  242. autofocus: false,
  243. cleanInput: true
  244. ).foregroundColor(.loopRed)
  245. Text("g").foregroundColor(.secondary)
  246. }
  247. }
  248. var body: some View {
  249. ZStack(alignment: .center) {
  250. VStack {
  251. Form {
  252. Section {
  253. HStack {
  254. Text("Carbs").fontWeight(.semibold)
  255. Spacer()
  256. DecimalTextField(
  257. "0",
  258. value: $state.carbs,
  259. formatter: formatter,
  260. autofocus: false,
  261. cleanInput: true
  262. ).onChange(of: state.carbs) { _ in
  263. if state.carbs > 0 {
  264. handleDebouncedInput()
  265. }
  266. }
  267. Text("g").foregroundColor(.secondary)
  268. }
  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. DecimalTextField(
  378. "0",
  379. value: $state.amount,
  380. formatter: formatter,
  381. autofocus: false,
  382. cleanInput: true,
  383. textColor: .systemBlue
  384. )
  385. Text(" U").foregroundColor(.secondary)
  386. }
  387. if state.amount > 0 {
  388. HStack {
  389. Text("External insulin")
  390. Spacer()
  391. Toggle("", isOn: $state.externalInsulin).toggleStyle(Checkbox())
  392. }
  393. }
  394. }.listRowBackground(Color.chart)
  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(
  465. (state.externalInsulin ? externalBolusLimit : pumpBolusLimit) ? Color(.systemRed) :
  466. Color(.systemBlue)
  467. )
  468. .shadow(radius: 3)
  469. .clipShape(RoundedRectangle(cornerRadius: 8))
  470. .padding()
  471. .offset(y: 20)
  472. }
  473. }
  474. private var taskButtonLabel: some View {
  475. let hasInsulin = state.amount > 0
  476. let hasCarbs = state.carbs > 0
  477. let hasFatOrProtein = state.fat > 0 || state.protein > 0
  478. switch (hasInsulin, hasCarbs, hasFatOrProtein) {
  479. case (true, true, true):
  480. return Text(
  481. state
  482. .externalInsulin ? (
  483. externalBolusLimit ? "Manual bolus exceeds max bolus!" : "Log meal and external insulin"
  484. ) :
  485. (pumpBolusLimit ? "Pump bolus exceeds max bolus!" : "Log meal and enact bolus")
  486. )
  487. case (true, true, false):
  488. return Text(
  489. state
  490. .externalInsulin ?
  491. (externalBolusLimit ? "Manual bolus exceeds max bolus!" : "Log carbs and external insulin") :
  492. (pumpBolusLimit ? "Pump bolus exceeds max bolus!" : "Log carbs and enact bolus")
  493. )
  494. case (true, false, true):
  495. return Text(
  496. state
  497. .externalInsulin ?
  498. (externalBolusLimit ? "Manual bolus exceeds max bolus!" : "Log FPUs and external insulin") :
  499. (pumpBolusLimit ? "Pump bolus exceeds max bolus!" : "Log FPUs and enact bolus")
  500. )
  501. case (true, false, false):
  502. return Text(
  503. state
  504. .externalInsulin ? (externalBolusLimit ? "Manual bolus exceeds max bolus!" : "Log external insulin") :
  505. (pumpBolusLimit ? "Pump bolus exceeds max bolus!" : "Enact bolus")
  506. )
  507. case (false, true, true):
  508. return Text("Log meal")
  509. case (false, true, false):
  510. return Text("Log carbs")
  511. case (false, false, true):
  512. return Text("Log FPUs")
  513. default:
  514. return Text("Continue without treatment")
  515. }
  516. }
  517. private var pumpBolusLimit: Bool {
  518. state.amount > state.maxBolus
  519. }
  520. private var externalBolusLimit: Bool {
  521. state.amount > state.maxBolus * 3
  522. }
  523. private var disableTaskButton: Bool {
  524. state.amount > 0 ? (state.externalInsulin ? externalBolusLimit : pumpBolusLimit) : false
  525. }
  526. }
  527. struct DividerDouble: View {
  528. var body: some View {
  529. VStack(spacing: 2) {
  530. Rectangle()
  531. .frame(height: 1)
  532. .foregroundColor(.gray.opacity(0.65))
  533. Rectangle()
  534. .frame(height: 1)
  535. .foregroundColor(.gray.opacity(0.65))
  536. }
  537. .frame(height: 4)
  538. .padding(.vertical)
  539. }
  540. }
  541. struct DividerCustom: View {
  542. var body: some View {
  543. Rectangle()
  544. .frame(height: 1)
  545. .foregroundColor(.gray.opacity(0.65))
  546. .padding(.vertical)
  547. }
  548. }
  549. }
  550. // fix iOS 15 bug
  551. struct ActivityIndicator: UIViewRepresentable {
  552. @Binding var isAnimating: Bool
  553. let style: UIActivityIndicatorView.Style
  554. func makeUIView(context _: UIViewRepresentableContext<ActivityIndicator>) -> UIActivityIndicatorView {
  555. UIActivityIndicatorView(style: style)
  556. }
  557. func updateUIView(_ uiView: UIActivityIndicatorView, context _: UIViewRepresentableContext<ActivityIndicator>) {
  558. isAnimating ? uiView.startAnimating() : uiView.stopAnimating()
  559. }
  560. }