BolusRootView.swift 19 KB

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