BolusRootView.swift 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. import SwiftUI
  2. import Swinject
  3. extension Bolus {
  4. struct RootView: BaseView {
  5. let resolver: Resolver
  6. let waitForSuggestion: Bool
  7. @StateObject var state = StateModel()
  8. @State private var isAddInsulinAlertPresented = false
  9. @State private var presentInfo = false
  10. @State private var displayError = false
  11. @Environment(\.colorScheme) var colorScheme
  12. private var formatter: NumberFormatter {
  13. let formatter = NumberFormatter()
  14. formatter.numberStyle = .decimal
  15. formatter.maximumFractionDigits = 2
  16. return formatter
  17. }
  18. private var fractionDigits: Int {
  19. if state.units == .mmolL {
  20. return 1
  21. } else { return 0 }
  22. }
  23. var body: some View {
  24. Form {
  25. Section {
  26. if state.waitForSuggestion {
  27. HStack {
  28. Text("Wait please").foregroundColor(.secondary)
  29. Spacer()
  30. ActivityIndicator(isAnimating: .constant(true), style: .medium) // fix iOS 15 bug
  31. }
  32. } else {
  33. HStack {
  34. Text("Insulin recommended")
  35. Spacer()
  36. Text(
  37. formatter
  38. .string(from: state.insulinRecommended as NSNumber)! +
  39. NSLocalizedString(" U", comment: "Insulin unit")
  40. ).foregroundColor((state.error && state.insulinRecommended > 0) ? .red : .secondary)
  41. }.contentShape(Rectangle())
  42. .onTapGesture {
  43. if state.error, state.insulinRecommended > 0 { displayError = true }
  44. else { state.amount = state.insulinRecommended }
  45. }
  46. HStack {
  47. Image(systemName: "info.bubble").symbolRenderingMode(.palette).foregroundStyle(
  48. .primary, .blue
  49. )
  50. }.onTapGesture {
  51. presentInfo.toggle()
  52. }
  53. }
  54. }
  55. header: { Text("Recommendation") }
  56. if !state.waitForSuggestion {
  57. Section {
  58. HStack {
  59. Text("Amount")
  60. Spacer()
  61. DecimalTextField(
  62. "0",
  63. value: $state.amount,
  64. formatter: formatter,
  65. autofocus: true,
  66. cleanInput: true
  67. )
  68. Text("U").foregroundColor(.secondary)
  69. }
  70. }
  71. header: { Text("Bolus") }
  72. Section {
  73. Button { state.add() }
  74. label: { Text(!(state.amount > state.maxBolus) ? "Enact bolus" : "Max Bolus exceeded!") }
  75. .disabled(
  76. state.amount <= 0 || state.amount > state.maxBolus
  77. )
  78. }
  79. Section {
  80. if waitForSuggestion {
  81. Button { state.showModal(for: nil) }
  82. label: { Text("Continue without bolus") }
  83. } else {
  84. Button { isAddInsulinAlertPresented = true }
  85. label: { Text("Add insulin without actually bolusing") }
  86. .disabled(state.amount <= 0 || state.amount > state.maxBolus * 3)
  87. }
  88. }
  89. .alert(isPresented: $isAddInsulinAlertPresented) {
  90. let isOverMax = state.amount > state.maxBolus ? true : false
  91. let addOverMax = NSLocalizedString(
  92. "\nAmount is more than your Max Bolus setting! \nAre you sure you want to add ",
  93. comment: "Alert"
  94. )
  95. let addUnderMax = NSLocalizedString("Add", comment: "Add insulin without bolusing alert")
  96. let insulinUnit = NSLocalizedString(" U", comment: "Insulin unit")
  97. let withoutBolusing = NSLocalizedString(
  98. " without bolusing",
  99. comment: "Add insulin without bolusing alert"
  100. )
  101. let insulinAmount = formatter.string(from: state.amount as NSNumber)!
  102. let overMaxBolusString = addOverMax + insulinAmount + insulinUnit + withoutBolusing + "?"
  103. let underMaxBolusString = addUnderMax + " " + insulinAmount + insulinUnit + withoutBolusing
  104. // Actual alert
  105. return Alert(
  106. title: Text(
  107. isOverMax ? "Warning" : "Are you sure?"
  108. ),
  109. message:
  110. Text(
  111. isOverMax ? overMaxBolusString : underMaxBolusString
  112. ),
  113. primaryButton: .destructive(
  114. Text("Add"),
  115. action: {
  116. state.addWithoutBolus()
  117. isAddInsulinAlertPresented = false
  118. }
  119. ),
  120. secondaryButton: .cancel()
  121. )
  122. }
  123. }
  124. }
  125. .alert(isPresented: $displayError) {
  126. Alert(
  127. title: Text("Warning!"),
  128. message: Text("\n" + alertString() + "\n"),
  129. primaryButton: .destructive(
  130. Text("Add"),
  131. action: {
  132. state.amount = state.insulinRecommended
  133. displayError = false
  134. }
  135. ),
  136. secondaryButton: .cancel()
  137. )
  138. }.onAppear {
  139. configureView {
  140. state.waitForSuggestionInitial = waitForSuggestion
  141. state.waitForSuggestion = waitForSuggestion
  142. }
  143. }
  144. .navigationTitle("Enact Bolus")
  145. .navigationBarTitleDisplayMode(.automatic)
  146. .navigationBarItems(leading: Button("Close", action: state.hideModal))
  147. .popup(isPresented: presentInfo, alignment: .center, direction: .bottom) {
  148. bolusInfo
  149. }
  150. }
  151. var bolusInfo: some View {
  152. VStack {
  153. // Variables
  154. VStack(spacing: 3) {
  155. HStack {
  156. Text("Eventual Glucose").foregroundColor(.secondary)
  157. let evg = state.units == .mmolL ? Decimal(state.evBG).asMmolL : Decimal(state.evBG)
  158. Text(evg.formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits))))
  159. Text(state.units.rawValue).foregroundColor(.secondary)
  160. }
  161. HStack {
  162. Text("Target Glucose").foregroundColor(.secondary)
  163. let target = state.units == .mmolL ? state.target.asMmolL : state.target
  164. Text(target.formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits))))
  165. Text(state.units.rawValue).foregroundColor(.secondary)
  166. }
  167. HStack {
  168. Text("ISF").foregroundColor(.secondary)
  169. let isf = state.isf
  170. Text(isf.formatted())
  171. Text(state.units.rawValue + NSLocalizedString("/U", comment: "/Insulin unit"))
  172. .foregroundColor(.secondary)
  173. }
  174. HStack {
  175. Text("ISF:")
  176. Text("Insulin Sensitivity")
  177. }.foregroundColor(.secondary).italic()
  178. if state.percentage != 100 {
  179. HStack {
  180. Text("Percentage setting").foregroundColor(.secondary)
  181. let percentage = state.percentage
  182. Text(percentage.formatted())
  183. Text("%").foregroundColor(.secondary)
  184. }
  185. }
  186. HStack {
  187. Text("Formula:")
  188. Text("(Eventual Glucose - Target) / ISF")
  189. }.foregroundColor(.secondary).italic().padding(.top, 5)
  190. }
  191. .font(.footnote)
  192. .padding(.top, 10)
  193. Divider()
  194. // Formula
  195. VStack(spacing: 5) {
  196. let unit = NSLocalizedString(
  197. " U",
  198. comment: "Unit in number of units delivered (keep the space character!)"
  199. )
  200. let color: Color = (state.percentage != 100 && state.insulin > 0) ? .secondary : .blue
  201. let fontWeight: Font.Weight = (state.percentage != 100 && state.insulin > 0) ? .regular : .bold
  202. HStack {
  203. Text(NSLocalizedString("Insulin recommended", comment: "") + ":").font(.callout)
  204. Text(state.insulin.formatted() + unit).font(.callout).foregroundColor(color).fontWeight(fontWeight)
  205. }
  206. if state.percentage != 100, state.insulin > 0 {
  207. Divider()
  208. HStack { Text(state.percentage.formatted() + " % ->").font(.callout).foregroundColor(.secondary)
  209. Text(
  210. state.insulinRecommended.formatted() + unit
  211. ).font(.callout).foregroundColor(.blue).bold()
  212. }
  213. }
  214. }
  215. // Warning
  216. if state.error, state.insulinRecommended > 0 {
  217. VStack(spacing: 5) {
  218. Divider()
  219. Text("Warning!").font(.callout).bold().foregroundColor(.orange)
  220. Text(alertString()).font(.footnote)
  221. Divider()
  222. }.padding(.horizontal, 10)
  223. }
  224. // Footer
  225. if !(state.error && state.insulinRecommended > 0) {
  226. VStack {
  227. Text(
  228. "Carbs and previous insulin are included in the glucose prediction, but if the Eventual Glucose is lower than the Target Glucose, a bolus will not be recommended."
  229. ).font(.caption2).foregroundColor(.secondary)
  230. }.padding(20)
  231. }
  232. // Hide button
  233. VStack {
  234. Button { presentInfo = false }
  235. label: { Text("Hide") }.frame(maxWidth: .infinity, alignment: .center).font(.callout)
  236. .foregroundColor(.blue)
  237. }.padding(.bottom, 10)
  238. }
  239. .background(
  240. RoundedRectangle(cornerRadius: 8, style: .continuous)
  241. .fill(Color(colorScheme == .dark ? UIColor.systemGray4 : UIColor.systemGray4))
  242. // .fill(Color(.systemGray).gradient) // A more prominent pop-up, but harder to read
  243. )
  244. }
  245. // Localize the Oref0 error/warning strings. The default should never be returned
  246. private func alertString() -> String {
  247. switch state.errorString {
  248. case 1,
  249. 2:
  250. return NSLocalizedString(
  251. "Eventual Glucose > Target Glucose, but glucose is predicted to first drop down to ",
  252. comment: "Bolus pop-up / Alert string. Make translations concise!"
  253. ) + state.minGuardBG
  254. .formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits))) + " " + state.units
  255. .rawValue + ", " +
  256. NSLocalizedString(
  257. "which is below your Threshold (",
  258. comment: "Bolus pop-up / Alert string. Make translations concise!"
  259. ) + state
  260. .threshold.formatted() + " " + state.units.rawValue + ")"
  261. case 3:
  262. return NSLocalizedString(
  263. "Eventual Glucose > Target Glucose, but glucose is climbing slower than expected. Expected: ",
  264. comment: "Bolus pop-up / Alert string. Make translations concise!"
  265. ) +
  266. state.expectedDelta
  267. .formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits))) +
  268. NSLocalizedString(". Climbing: ", comment: "Bolus pop-up / Alert string. Make translatons concise!") + state
  269. .minDelta.formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits)))
  270. case 4:
  271. return NSLocalizedString(
  272. "Eventual Glucose > Target Glucose, but glucose is falling faster than expected. Expected: ",
  273. comment: "Bolus pop-up / Alert string. Make translations concise!"
  274. ) +
  275. state.expectedDelta
  276. .formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits))) +
  277. NSLocalizedString(". Falling: ", comment: "Bolus pop-up / Alert string. Make translations concise!") + state
  278. .minDelta.formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits)))
  279. case 5:
  280. return NSLocalizedString(
  281. "Eventual Glucose > Target Glucose, but glucose is changing faster than expected. Expected: ",
  282. comment: "Bolus pop-up / Alert string. Make translations concise!"
  283. ) +
  284. state.expectedDelta
  285. .formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits))) +
  286. NSLocalizedString(". Changing: ", comment: "Bolus pop-up / Alert string. Make translations concise!") + state
  287. .minDelta.formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits)))
  288. case 6:
  289. return NSLocalizedString(
  290. "Eventual Glucose > Target Glucose, but glucose is predicted to first drop down to ",
  291. comment: "Bolus pop-up / Alert string. Make translations concise!"
  292. ) + state
  293. .minPredBG
  294. .formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits))) + " " + state
  295. .units
  296. .rawValue
  297. default:
  298. return "Ignore Warning..."
  299. }
  300. }
  301. }
  302. }
  303. struct ActivityIndicator: UIViewRepresentable {
  304. @Binding var isAnimating: Bool
  305. let style: UIActivityIndicatorView.Style
  306. func makeUIView(context _: UIViewRepresentableContext<ActivityIndicator>) -> UIActivityIndicatorView {
  307. UIActivityIndicatorView(style: style)
  308. }
  309. func updateUIView(_ uiView: UIActivityIndicatorView, context _: UIViewRepresentableContext<ActivityIndicator>) {
  310. isAnimating ? uiView.startAnimating() : uiView.stopAnimating()
  311. }
  312. }