BolusRootView.swift 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  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 showPresetSheet = false
  18. @State private var autofocus: Bool = true
  19. @State private var calculatorDetent = PresentationDetent.medium
  20. @State private var pushed: Bool = false
  21. // @State private var isPromptPresented: Bool = false
  22. // @State private var dish: String = ""
  23. // @State private var saved: Bool = false
  24. @State private var debounce: DispatchWorkItem?
  25. // @Environment(\.managedObjectContext) var moc
  26. private enum Config {
  27. static let dividerHeight: CGFloat = 2
  28. static let spacing: CGFloat = 3
  29. }
  30. @Environment(\.colorScheme) var colorScheme
  31. // @FetchRequest(
  32. // entity: MealPresetStored.entity(),
  33. // sortDescriptors: [NSSortDescriptor(key: "dish", ascending: true)]
  34. // ) var carbPresets: FetchedResults<MealPresetStored>
  35. private var formatter: NumberFormatter {
  36. let formatter = NumberFormatter()
  37. formatter.numberStyle = .decimal
  38. formatter.maximumFractionDigits = 2
  39. return formatter
  40. }
  41. private var mealFormatter: NumberFormatter {
  42. let formatter = NumberFormatter()
  43. formatter.numberStyle = .decimal
  44. formatter.maximumFractionDigits = 1
  45. return formatter
  46. }
  47. private var gluoseFormatter: NumberFormatter {
  48. let formatter = NumberFormatter()
  49. formatter.numberStyle = .decimal
  50. if state.units == .mmolL {
  51. formatter.maximumFractionDigits = 1
  52. } else { formatter.maximumFractionDigits = 0 }
  53. return formatter
  54. }
  55. private var fractionDigits: Int {
  56. if state.units == .mmolL {
  57. return 1
  58. } else { return 0 }
  59. }
  60. private var color: LinearGradient {
  61. colorScheme == .dark ? LinearGradient(
  62. gradient: Gradient(colors: [
  63. Color.bgDarkBlue,
  64. Color.bgDarkerDarkBlue
  65. ]),
  66. startPoint: .top,
  67. endPoint: .bottom
  68. )
  69. :
  70. LinearGradient(
  71. gradient: Gradient(colors: [Color.gray.opacity(0.1)]),
  72. startPoint: .top,
  73. endPoint: .bottom
  74. )
  75. }
  76. // private var empty: Bool {
  77. // state.useFPUconversion ? (state.carbs <= 0 && state.fat <= 0 && state.protein <= 0) : (state.carbs <= 0)
  78. // }
  79. /// Handles macro input (carb, fat, protein) in a debounced fashion.
  80. func handleDebouncedInput() {
  81. debounce?.cancel()
  82. debounce = DispatchWorkItem { [self] in
  83. state.insulinCalculated = state.calculateInsulin()
  84. Task {
  85. await state.updateForecasts()
  86. }
  87. }
  88. if let debounce = debounce {
  89. DispatchQueue.main.asyncAfter(deadline: .now() + 0.35, execute: debounce)
  90. }
  91. }
  92. @ViewBuilder private func proteinAndFat() -> some View {
  93. HStack {
  94. Text("Fat").foregroundColor(.orange)
  95. Spacer()
  96. TextFieldWithToolBar(text: $state.fat, placeholder: "0", keyboardType: .numberPad, numberFormatter: mealFormatter)
  97. Text("g").foregroundColor(.secondary)
  98. }
  99. HStack {
  100. Text("Protein").foregroundColor(.red)
  101. Spacer()
  102. TextFieldWithToolBar(
  103. text: $state.protein,
  104. placeholder: "0",
  105. keyboardType: .numberPad,
  106. numberFormatter: mealFormatter
  107. )
  108. Text("g").foregroundColor(.secondary)
  109. }
  110. }
  111. @ViewBuilder private func carbsTextField() -> some View {
  112. HStack {
  113. Text("Carbs").fontWeight(.semibold)
  114. Spacer()
  115. TextFieldWithToolBar(
  116. text: $state.carbs,
  117. placeholder: "0",
  118. keyboardType: .numberPad,
  119. numberFormatter: mealFormatter
  120. )
  121. .onChange(of: state.carbs) { _ in
  122. if state.carbs > 0 {
  123. handleDebouncedInput()
  124. }
  125. }
  126. Text("g").foregroundColor(.secondary)
  127. }
  128. }
  129. var body: some View {
  130. ZStack(alignment: .center) {
  131. VStack {
  132. Form {
  133. Section {
  134. carbsTextField()
  135. if state.useFPUconversion {
  136. proteinAndFat()
  137. }
  138. // Time
  139. HStack {
  140. Text("Time").foregroundStyle(Color.secondary)
  141. Spacer()
  142. if !pushed {
  143. Button {
  144. pushed = true
  145. } label: { Text("Now") }.buttonStyle(.borderless).foregroundColor(.secondary)
  146. .padding(.trailing, 5)
  147. } else {
  148. Button { state.date = state.date.addingTimeInterval(-15.minutes.timeInterval) }
  149. label: { Image(systemName: "minus.circle") }.tint(.blue).buttonStyle(.borderless)
  150. DatePicker(
  151. "Time",
  152. selection: $state.date,
  153. displayedComponents: [.hourAndMinute]
  154. ).controlSize(.mini)
  155. .labelsHidden()
  156. Button {
  157. state.date = state.date.addingTimeInterval(15.minutes.timeInterval)
  158. }
  159. label: { Image(systemName: "plus.circle") }.tint(.blue).buttonStyle(.borderless)
  160. }
  161. }
  162. }.listRowBackground(Color.chart)
  163. // if state.displayPresets {
  164. // Section {
  165. // mealPresets
  166. // }.listRowBackground(Color.chart)
  167. // }
  168. Section {
  169. HStack {
  170. Button(action: {
  171. state.showInfo.toggle()
  172. }, label: {
  173. Image(systemName: "info.circle")
  174. Text("Calculations")
  175. })
  176. .foregroundStyle(.blue)
  177. .font(.footnote)
  178. .buttonStyle(PlainButtonStyle())
  179. .frame(maxWidth: .infinity, alignment: .leading)
  180. if state.fattyMeals {
  181. Spacer()
  182. Toggle(isOn: $state.useFattyMealCorrectionFactor) {
  183. Text("Fatty Meal")
  184. }
  185. .toggleStyle(CheckboxToggleStyle())
  186. .font(.footnote)
  187. .onChange(of: state.useFattyMealCorrectionFactor) { _ in
  188. state.insulinCalculated = state.calculateInsulin()
  189. if state.useFattyMealCorrectionFactor {
  190. state.useSuperBolus = false
  191. }
  192. }
  193. }
  194. if state.sweetMeals {
  195. Spacer()
  196. Toggle(isOn: $state.useSuperBolus) {
  197. Text("Super Bolus")
  198. }
  199. .toggleStyle(CheckboxToggleStyle())
  200. .font(.footnote)
  201. .onChange(of: state.useSuperBolus) { _ in
  202. state.insulinCalculated = state.calculateInsulin()
  203. if state.useSuperBolus {
  204. state.useFattyMealCorrectionFactor = false
  205. }
  206. }
  207. }
  208. }
  209. HStack {
  210. Text("Recommended Bolus")
  211. Spacer()
  212. Text(
  213. formatter
  214. .string(from: Double(state.insulinCalculated) as NSNumber) ?? ""
  215. )
  216. Text(
  217. NSLocalizedString(
  218. " U",
  219. comment: "Unit in number of units delivered (keep the space character!)"
  220. )
  221. ).foregroundColor(.secondary)
  222. }.contentShape(Rectangle())
  223. .onTapGesture { state.amount = state.insulinCalculated }
  224. HStack {
  225. Text("Bolus")
  226. Spacer()
  227. TextFieldWithToolBar(
  228. text: $state.amount,
  229. placeholder: "0",
  230. textColor: colorScheme == .dark ? .white : .blue,
  231. maxLength: 5,
  232. numberFormatter: formatter
  233. ).onChange(of: state.amount) { _ in
  234. Task {
  235. await state.updateForecasts()
  236. }
  237. }
  238. Text(" U").foregroundColor(.secondary)
  239. }
  240. if state.amount > 0 {
  241. HStack {
  242. Text("External insulin")
  243. Spacer()
  244. Toggle("", isOn: $state.externalInsulin).toggleStyle(Checkbox())
  245. }
  246. }
  247. }.listRowBackground(Color.chart)
  248. Section {
  249. ForeCastChart(state: state, units: $state.units)
  250. .padding(.vertical)
  251. }.listRowBackground(Color.chart)
  252. }
  253. }
  254. .safeAreaInset(edge: .bottom, spacing: 0) {
  255. stickyButton
  256. }.blur(radius: state.waitForSuggestion ? 5 : 0)
  257. if state.waitForSuggestion {
  258. CustomProgressView(text: progressText.rawValue)
  259. }
  260. }
  261. .scrollContentBackground(.hidden).background(color)
  262. .blur(radius: state.showInfo ? 3 : 0)
  263. .navigationTitle("Treatments")
  264. .navigationBarTitleDisplayMode(.inline)
  265. .toolbar(content: {
  266. ToolbarItem(placement: .topBarLeading) {
  267. Button {
  268. state.hideModal()
  269. } label: {
  270. Text("Close")
  271. }
  272. }
  273. ToolbarItem(placement: .topBarTrailing) {
  274. Button(action: {
  275. showPresetSheet = true
  276. }, label: {
  277. Image(systemName: "plus")
  278. })
  279. }
  280. })
  281. .onAppear {
  282. configureView {
  283. state.insulinCalculated = state.calculateInsulin()
  284. }
  285. }
  286. .onDisappear {
  287. state.addButtonPressed = false
  288. }
  289. .sheet(isPresented: $state.showInfo) {
  290. PopupView(state: state)
  291. .presentationDetents(
  292. [.fraction(0.9), .large],
  293. selection: $calculatorDetent
  294. )
  295. }
  296. .sheet(isPresented: $showPresetSheet, onDismiss: {
  297. showPresetSheet = false
  298. }) {
  299. MealPresetView(state: state)
  300. }
  301. }
  302. var progressText: ProgressText {
  303. switch (state.amount > 0, state.carbs > 0) {
  304. case (true, true):
  305. return .updatingIOBandCOB
  306. case (false, true):
  307. return .updatingCOB
  308. case (true, false):
  309. return .updatingIOB
  310. default:
  311. return .updatingTreatments
  312. }
  313. }
  314. var stickyButton: some View {
  315. ZStack {
  316. Rectangle()
  317. .frame(width: UIScreen.main.bounds.width, height: 120).offset(y: 40)
  318. .shadow(
  319. color: colorScheme == .dark ? Color(red: 0.02745098039, green: 0.1098039216, blue: 0.1411764706) :
  320. Color.black.opacity(0.33),
  321. radius: 3
  322. )
  323. .foregroundStyle(Color.chart)
  324. Button {
  325. state.invokeTreatmentsTask()
  326. } label: {
  327. taskButtonLabel
  328. .font(.headline)
  329. .foregroundStyle(Color.white)
  330. .frame(maxWidth: .infinity, alignment: .center)
  331. .frame(minHeight: 50)
  332. }
  333. .disabled(disableTaskButton)
  334. .background(
  335. (state.externalInsulin ? externalBolusLimit : pumpBolusLimit) ? Color(.systemRed) :
  336. Color(.systemBlue)
  337. )
  338. .shadow(radius: 3)
  339. .clipShape(RoundedRectangle(cornerRadius: 8))
  340. .padding()
  341. .offset(y: 20)
  342. }
  343. }
  344. private var taskButtonLabel: some View {
  345. let hasInsulin = state.amount > 0
  346. let hasCarbs = state.carbs > 0
  347. let hasFatOrProtein = state.fat > 0 || state.protein > 0
  348. switch (hasInsulin, hasCarbs, hasFatOrProtein) {
  349. case (true, true, true):
  350. return Text(
  351. state
  352. .externalInsulin ? (
  353. externalBolusLimit ? "Manual bolus exceeds max bolus!" : "Log meal and external insulin"
  354. ) :
  355. (pumpBolusLimit ? "Pump bolus exceeds max bolus!" : "Log meal and enact bolus")
  356. )
  357. case (true, true, false):
  358. return Text(
  359. state
  360. .externalInsulin ?
  361. (externalBolusLimit ? "Manual bolus exceeds max bolus!" : "Log carbs and external insulin") :
  362. (pumpBolusLimit ? "Pump bolus exceeds max bolus!" : "Log carbs and enact bolus")
  363. )
  364. case (true, false, true):
  365. return Text(
  366. state
  367. .externalInsulin ?
  368. (externalBolusLimit ? "Manual bolus exceeds max bolus!" : "Log FPUs and external insulin") :
  369. (pumpBolusLimit ? "Pump bolus exceeds max bolus!" : "Log FPUs and enact bolus")
  370. )
  371. case (true, false, false):
  372. return Text(
  373. state
  374. .externalInsulin ? (externalBolusLimit ? "Manual bolus exceeds max bolus!" : "Log external insulin") :
  375. (pumpBolusLimit ? "Pump bolus exceeds max bolus!" : "Enact bolus")
  376. )
  377. case (false, true, true):
  378. return Text("Log meal")
  379. case (false, true, false):
  380. return Text("Log carbs")
  381. case (false, false, true):
  382. return Text("Log FPUs")
  383. default:
  384. return Text("Continue without treatment")
  385. }
  386. }
  387. private var pumpBolusLimit: Bool {
  388. state.amount > state.maxBolus
  389. }
  390. private var externalBolusLimit: Bool {
  391. state.amount > state.maxBolus * 3
  392. }
  393. private var disableTaskButton: Bool {
  394. state.amount > 0 ? (state.externalInsulin ? externalBolusLimit : pumpBolusLimit) : false
  395. }
  396. }
  397. struct DividerDouble: View {
  398. var body: some View {
  399. VStack(spacing: 2) {
  400. Rectangle()
  401. .frame(height: 1)
  402. .foregroundColor(.gray.opacity(0.65))
  403. Rectangle()
  404. .frame(height: 1)
  405. .foregroundColor(.gray.opacity(0.65))
  406. }
  407. .frame(height: 4)
  408. .padding(.vertical)
  409. }
  410. }
  411. struct DividerCustom: View {
  412. var body: some View {
  413. Rectangle()
  414. .frame(height: 1)
  415. .foregroundColor(.gray.opacity(0.65))
  416. .padding(.vertical)
  417. }
  418. }
  419. }
  420. // fix iOS 15 bug
  421. struct ActivityIndicator: UIViewRepresentable {
  422. @Binding var isAnimating: Bool
  423. let style: UIActivityIndicatorView.Style
  424. func makeUIView(context _: UIViewRepresentableContext<ActivityIndicator>) -> UIActivityIndicatorView {
  425. UIActivityIndicatorView(style: style)
  426. }
  427. func updateUIView(_ uiView: UIActivityIndicatorView, context _: UIViewRepresentableContext<ActivityIndicator>) {
  428. isAnimating ? uiView.startAnimating() : uiView.stopAnimating()
  429. }
  430. }