BolusRootView.swift 18 KB

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