TreatmentsRootView.swift 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517
  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.large
  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. Task {
  58. state.insulinCalculated = await state.calculateInsulin()
  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. Task {
  195. state.insulinCalculated = await state.calculateInsulin()
  196. if state.useFattyMealCorrectionFactor {
  197. state.useSuperBolus = false
  198. }
  199. }
  200. }
  201. }
  202. if state.sweetMeals {
  203. Toggle(isOn: $state.useSuperBolus) {
  204. Text("Super Bolus")
  205. }
  206. .toggleStyle(CheckboxToggleStyle())
  207. .font(.footnote)
  208. .onChange(of: state.useSuperBolus) {
  209. Task {
  210. state.insulinCalculated = await state.calculateInsulin()
  211. if state.useSuperBolus {
  212. state.useFattyMealCorrectionFactor = false
  213. }
  214. }
  215. }
  216. }
  217. }
  218. }
  219. HStack {
  220. HStack {
  221. Text("Recommendation")
  222. Button(action: {
  223. state.showInfo.toggle()
  224. }, label: {
  225. Image(systemName: "info.circle")
  226. })
  227. .foregroundStyle(.blue)
  228. .buttonStyle(PlainButtonStyle())
  229. }
  230. Spacer()
  231. Button {
  232. state.amount = state.insulinCalculated
  233. } label: {
  234. HStack {
  235. Text(
  236. formatter
  237. .string(from: Double(state.insulinCalculated) as NSNumber) ?? ""
  238. )
  239. Text(
  240. NSLocalizedString(
  241. " U",
  242. comment: "Unit in number of units delivered (keep the space character!)"
  243. )
  244. ).foregroundColor(.secondary)
  245. }
  246. }
  247. .disabled(state.insulinCalculated == 0 || state.amount == state.insulinCalculated)
  248. .buttonStyle(.bordered).padding(.trailing, -10)
  249. }
  250. HStack {
  251. Text("Bolus")
  252. Spacer()
  253. TextFieldWithToolBar(
  254. text: $state.amount,
  255. placeholder: "0",
  256. textColor: colorScheme == .dark ? .white : .blue,
  257. maxLength: 5,
  258. numberFormatter: formatter,
  259. previousTextField: { focusOnPreviousTextField(index: 4) },
  260. nextTextField: { focusOnNextTextField(index: 4) }
  261. ).focused($focusedField, equals: .bolus)
  262. .onChange(of: state.amount) {
  263. Task {
  264. await state.updateForecasts()
  265. }
  266. }
  267. Text(" U").foregroundColor(.secondary)
  268. }
  269. HStack {
  270. Text("External Insulin")
  271. Spacer()
  272. Toggle("", isOn: $state.externalInsulin).toggleStyle(Checkbox())
  273. }
  274. }.listRowBackground(Color.chart)
  275. treatmentButton
  276. }
  277. .listSectionSpacing(sectionSpacing)
  278. }
  279. .blur(radius: state.isAwaitingDeterminationResult ? 5 : 0)
  280. if state.isAwaitingDeterminationResult {
  281. CustomProgressView(text: progressText.rawValue)
  282. }
  283. }
  284. .padding(.top)
  285. .ignoresSafeArea(edges: .top)
  286. .scrollContentBackground(.hidden).background(appState.trioBackgroundColor(for: colorScheme))
  287. .blur(radius: state.showInfo ? 3 : 0)
  288. .navigationTitle("Treatments")
  289. .navigationBarTitleDisplayMode(.inline)
  290. .toolbar(content: {
  291. ToolbarItem(placement: .topBarLeading) {
  292. Button {
  293. state.hideModal()
  294. } label: {
  295. Text("Close")
  296. }
  297. }
  298. if state.displayPresets {
  299. ToolbarItem(placement: .topBarTrailing) {
  300. Button(action: {
  301. showPresetSheet = true
  302. }, label: {
  303. HStack {
  304. Text("Presets")
  305. Image(systemName: "plus")
  306. }
  307. })
  308. }
  309. }
  310. })
  311. .onAppear {
  312. configureView {
  313. state.isActive = true
  314. Task { @MainActor in
  315. state.insulinCalculated = await state.calculateInsulin()
  316. }
  317. }
  318. }
  319. .onDisappear {
  320. state.isActive = false
  321. state.addButtonPressed = false
  322. }
  323. .sheet(isPresented: $state.showInfo) {
  324. PopupView(state: state)
  325. .presentationDetents([.fraction(0.9), .large])
  326. .presentationDragIndicator(.visible)
  327. }
  328. .sheet(isPresented: $showPresetSheet, onDismiss: {
  329. showPresetSheet = false
  330. }) {
  331. MealPresetView(state: state)
  332. }
  333. .alert("Determination Failed", isPresented: $state.showDeterminationFailureAlert) {
  334. Button("OK", role: .cancel) {
  335. state.hideModal()
  336. }
  337. } message: {
  338. Text("Failed to update COB/IOB: \(state.determinationFailureMessage)")
  339. }
  340. }
  341. var progressText: ProgressText {
  342. switch (state.amount > 0, state.carbs > 0) {
  343. case (true, true):
  344. return .updatingIOBandCOB
  345. case (false, true):
  346. return .updatingCOB
  347. case (true, false):
  348. return .updatingIOB
  349. default:
  350. return .updatingTreatments
  351. }
  352. }
  353. var treatmentButton: some View {
  354. var treatmentButtonBackground = Color(.systemBlue)
  355. if limitExceeded {
  356. treatmentButtonBackground = Color(.systemRed)
  357. } else if disableTaskButton {
  358. treatmentButtonBackground = Color(.systemGray)
  359. }
  360. return Button {
  361. state.invokeTreatmentsTask()
  362. } label: {
  363. HStack {
  364. if state.isBolusInProgress && state
  365. .amount > 0 && !state.externalInsulin && (state.carbs == 0 || state.fat == 0 || state.protein == 0)
  366. {
  367. ProgressView()
  368. }
  369. taskButtonLabel
  370. }
  371. .font(.headline)
  372. .foregroundStyle(Color.white)
  373. .frame(maxWidth: .infinity, alignment: .center)
  374. .frame(height: 35)
  375. }
  376. .disabled(disableTaskButton)
  377. .listRowBackground(treatmentButtonBackground)
  378. .shadow(radius: 3)
  379. .clipShape(RoundedRectangle(cornerRadius: 8))
  380. }
  381. private var taskButtonLabel: some View {
  382. if pumpBolusLimitExceeded {
  383. return Text("Max Bolus of \(state.maxBolus.description) U Exceeded")
  384. } else if externalBolusLimitExceeded {
  385. return Text("Max External Bolus of \(state.maxExternal.description) U Exceeded")
  386. } else if carbLimitExceeded {
  387. return Text("Max Carbs of \(state.maxCarbs.description) g Exceeded")
  388. } else if fatLimitExceeded {
  389. return Text("Max Fat of \(state.maxFat.description) g Exceeded")
  390. } else if proteinLimitExceeded {
  391. return Text("Max Protein of \(state.maxProtein.description) g Exceeded")
  392. }
  393. let hasInsulin = state.amount > 0
  394. let hasCarbs = state.carbs > 0
  395. let hasFatOrProtein = state.fat > 0 || state.protein > 0
  396. let bolusString = state.externalInsulin ? "External Insulin" : "Enact Bolus"
  397. if state.isBolusInProgress && hasInsulin && !state.externalInsulin && (!hasCarbs || !hasFatOrProtein) {
  398. return Text("Bolus In Progress...")
  399. }
  400. switch (hasInsulin, hasCarbs, hasFatOrProtein) {
  401. case (true, true, true):
  402. return Text("Log Meal and \(bolusString)")
  403. case (true, true, false):
  404. return Text("Log Carbs and \(bolusString)")
  405. case (true, false, true):
  406. return Text("Log FPU and \(bolusString)")
  407. case (true, false, false):
  408. return Text(state.externalInsulin ? "Log External Insulin" : "Enact Bolus")
  409. case (false, true, true):
  410. return Text("Log Meal")
  411. case (false, true, false):
  412. return Text("Log Carbs")
  413. case (false, false, true):
  414. return Text("Log FPU")
  415. default:
  416. return Text("Continue Without Treatment")
  417. }
  418. }
  419. private var pumpBolusLimitExceeded: Bool {
  420. !state.externalInsulin && state.amount > state.maxBolus
  421. }
  422. private var externalBolusLimitExceeded: Bool {
  423. state.externalInsulin && state.amount > state.maxExternal
  424. }
  425. private var carbLimitExceeded: Bool {
  426. state.carbs > state.maxCarbs
  427. }
  428. private var fatLimitExceeded: Bool {
  429. state.fat > state.maxFat
  430. }
  431. private var proteinLimitExceeded: Bool {
  432. state.protein > state.maxProtein
  433. }
  434. private var limitExceeded: Bool {
  435. pumpBolusLimitExceeded || externalBolusLimitExceeded || carbLimitExceeded || fatLimitExceeded || proteinLimitExceeded
  436. }
  437. private var disableTaskButton: Bool {
  438. (
  439. state.isBolusInProgress && state
  440. .amount > 0 && !state.externalInsulin && (state.carbs == 0 || state.fat == 0 || state.protein == 0)
  441. ) || state
  442. .addButtonPressed || limitExceeded
  443. }
  444. }
  445. struct DividerDouble: View {
  446. var body: some View {
  447. VStack(spacing: 2) {
  448. Rectangle()
  449. .frame(height: 1)
  450. .foregroundColor(.gray.opacity(0.65))
  451. Rectangle()
  452. .frame(height: 1)
  453. .foregroundColor(.gray.opacity(0.65))
  454. }
  455. .frame(height: 4)
  456. .padding(.vertical)
  457. }
  458. }
  459. struct DividerCustom: View {
  460. var body: some View {
  461. Rectangle()
  462. .frame(height: 1)
  463. .foregroundColor(.gray.opacity(0.65))
  464. .padding(.vertical)
  465. }
  466. }
  467. }