TreatmentsRootView.swift 20 KB

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