TreatmentsRootView.swift 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  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("Fat")
  70. TextFieldWithToolBar(
  71. text: $state.fat,
  72. placeholder: "0",
  73. keyboardType: .numberPad,
  74. numberFormatter: mealFormatter,
  75. previousTextField: { focusOnPreviousTextField(index: 2) },
  76. nextTextField: { focusOnNextTextField(index: 2) }
  77. ).focused($focusedField, equals: .fat)
  78. Text("g").foregroundColor(.secondary)
  79. }
  80. Divider().foregroundStyle(.primary).fontWeight(.bold).frame(width: 10)
  81. HStack {
  82. Text("Protein")
  83. TextFieldWithToolBar(
  84. text: $state.protein,
  85. placeholder: "0",
  86. keyboardType: .numberPad,
  87. numberFormatter: mealFormatter,
  88. previousTextField: { focusOnPreviousTextField(index: 3) },
  89. nextTextField: { focusOnNextTextField(index: 3) }
  90. ).focused($focusedField, equals: .protein)
  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. }.listSectionSpacing(20)
  266. }
  267. .blur(radius: state.waitForSuggestion ? 5 : 0)
  268. if state.waitForSuggestion {
  269. CustomProgressView(text: progressText.rawValue)
  270. }
  271. }
  272. .padding(.top)
  273. .ignoresSafeArea(edges: .top)
  274. .scrollContentBackground(.hidden).background(appState.trioBackgroundColor(for: colorScheme))
  275. .blur(radius: state.showInfo ? 3 : 0)
  276. .navigationTitle("Treatments")
  277. .navigationBarTitleDisplayMode(.inline)
  278. .toolbar(content: {
  279. ToolbarItem(placement: .topBarLeading) {
  280. Button {
  281. state.hideModal()
  282. } label: {
  283. Text("Close")
  284. }
  285. }
  286. ToolbarItem(placement: .topBarTrailing) {
  287. Button(action: {
  288. showPresetSheet = true
  289. }, label: {
  290. HStack {
  291. Text("Presets")
  292. Image(systemName: "plus")
  293. }
  294. })
  295. }
  296. })
  297. .onAppear {
  298. configureView {
  299. state.isActive = true
  300. state.insulinCalculated = state.calculateInsulin()
  301. }
  302. }
  303. .onDisappear {
  304. state.isActive = false
  305. state.addButtonPressed = false
  306. }
  307. .sheet(isPresented: $state.showInfo) {
  308. PopupView(state: state)
  309. .presentationDetents(
  310. [.fraction(0.9), .large],
  311. selection: $calculatorDetent
  312. )
  313. }
  314. .sheet(isPresented: $showPresetSheet, onDismiss: {
  315. showPresetSheet = false
  316. }) {
  317. MealPresetView(state: state)
  318. }
  319. }
  320. var progressText: ProgressText {
  321. switch (state.amount > 0, state.carbs > 0) {
  322. case (true, true):
  323. return .updatingIOBandCOB
  324. case (false, true):
  325. return .updatingCOB
  326. case (true, false):
  327. return .updatingIOB
  328. default:
  329. return .updatingTreatments
  330. }
  331. }
  332. var treatmentButton: some View {
  333. Button {
  334. state.invokeTreatmentsTask()
  335. } label: {
  336. taskButtonLabel
  337. .font(.headline)
  338. .foregroundStyle(Color.white)
  339. .frame(maxWidth: .infinity, alignment: .center)
  340. .frame(height: 35)
  341. }
  342. .disabled(disableTaskButton)
  343. .listRowBackground(
  344. limitExceeded ? Color(.systemRed) :
  345. disableTaskButton ? Color(.systemGray) :
  346. Color(.systemBlue)
  347. )
  348. .shadow(radius: 3)
  349. .clipShape(RoundedRectangle(cornerRadius: 8))
  350. }
  351. private var taskButtonLabel: some View {
  352. if pumpBolusLimitExceeded {
  353. return Text("Max Bolus of \(state.maxBolus.description) U Exceeded")
  354. } else if externalBolusLimitExceeded {
  355. return Text("Max External Bolus of \(state.maxExternal.description) U Exceeded")
  356. } else if carbLimitExceeded {
  357. return Text("Max Carbs of \(state.maxCarbs.description) g Exceeded")
  358. } else if fatLimitExceeded {
  359. return Text("Max Fat of \(state.maxFat.description) g Exceeded")
  360. } else if proteinLimitExceeded {
  361. return Text("Max Protein of \(state.maxProtein.description) g Exceeded")
  362. }
  363. let hasInsulin = state.amount > 0
  364. let hasCarbs = state.carbs > 0
  365. let hasFatOrProtein = state.fat > 0 || state.protein > 0
  366. let bolusString = state.externalInsulin ? "External Insulin" : "Enact Bolus"
  367. switch (hasInsulin, hasCarbs, hasFatOrProtein) {
  368. case (true, true, true):
  369. return Text("Log Meal and \(bolusString)")
  370. case (true, true, false):
  371. return Text("Log Carbs and \(bolusString)")
  372. case (true, false, true):
  373. return Text("Log FPU and \(bolusString)")
  374. case (true, false, false):
  375. return Text(state.externalInsulin ? "Log External Insulin" : "Enact Bolus")
  376. case (false, true, true):
  377. return Text("Log Meal")
  378. case (false, true, false):
  379. return Text("Log Carbs")
  380. case (false, false, true):
  381. return Text("Log FPU")
  382. default:
  383. return Text("Continue Without Treatment")
  384. }
  385. }
  386. private var pumpBolusLimitExceeded: Bool {
  387. !state.externalInsulin && state.amount > state.maxBolus
  388. }
  389. private var externalBolusLimitExceeded: Bool {
  390. state.externalInsulin && state.amount > state.maxExternal
  391. }
  392. private var carbLimitExceeded: Bool {
  393. state.carbs > state.maxCarbs
  394. }
  395. private var fatLimitExceeded: Bool {
  396. state.fat > state.maxFat
  397. }
  398. private var proteinLimitExceeded: Bool {
  399. state.protein > state.maxProtein
  400. }
  401. private var limitExceeded: Bool {
  402. pumpBolusLimitExceeded || externalBolusLimitExceeded || carbLimitExceeded || fatLimitExceeded || proteinLimitExceeded
  403. }
  404. private var disableTaskButton: Bool {
  405. state.addButtonPressed || limitExceeded
  406. }
  407. }
  408. struct DividerDouble: View {
  409. var body: some View {
  410. VStack(spacing: 2) {
  411. Rectangle()
  412. .frame(height: 1)
  413. .foregroundColor(.gray.opacity(0.65))
  414. Rectangle()
  415. .frame(height: 1)
  416. .foregroundColor(.gray.opacity(0.65))
  417. }
  418. .frame(height: 4)
  419. .padding(.vertical)
  420. }
  421. }
  422. struct DividerCustom: View {
  423. var body: some View {
  424. Rectangle()
  425. .frame(height: 1)
  426. .foregroundColor(.gray.opacity(0.65))
  427. .padding(.vertical)
  428. }
  429. }
  430. }
  431. // fix iOS 15 bug
  432. struct ActivityIndicator: UIViewRepresentable {
  433. @Binding var isAnimating: Bool
  434. let style: UIActivityIndicatorView.Style
  435. func makeUIView(context _: UIViewRepresentableContext<ActivityIndicator>) -> UIActivityIndicatorView {
  436. UIActivityIndicatorView(style: style)
  437. }
  438. func updateUIView(_ uiView: UIActivityIndicatorView, context _: UIViewRepresentableContext<ActivityIndicator>) {
  439. isAnimating ? uiView.startAnimating() : uiView.stopAnimating()
  440. }
  441. }