DeliveryLimitsEditor.swift 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  1. //
  2. // DeliveryLimitsEditor.swift
  3. // LoopKitUI
  4. //
  5. // Created by Michael Pangburn on 6/22/20.
  6. // Copyright © 2020 LoopKit Authors. All rights reserved.
  7. //
  8. import SwiftUI
  9. import HealthKit
  10. import LoopKit
  11. public typealias SyncDeliveryLimits = (_ deliveryLimits: DeliveryLimits, _ completion: @escaping (Swift.Result<DeliveryLimits, Error>) -> Void) -> Void
  12. public struct DeliveryLimitsEditor: View {
  13. fileprivate enum PresentedAlert: Error {
  14. case saveConfirmation(AlertContent)
  15. case saveError(Error)
  16. }
  17. let initialValue: DeliveryLimits
  18. let supportedBasalRates: [Double]
  19. let selectableMaximumBasalRates: [Double]
  20. let scheduledBasalRange: ClosedRange<Double>?
  21. let supportedMaximumBolusVolumes: [Double]
  22. let selectableMaximumBolusVolumes: [Double]
  23. let syncDeliveryLimits: SyncDeliveryLimits?
  24. let save: (_ deliveryLimits: DeliveryLimits) -> Void
  25. let mode: SettingsPresentationMode
  26. @State var value: DeliveryLimits
  27. @State private var userDidTap: Bool = false
  28. @State var settingBeingEdited: DeliveryLimits.Setting?
  29. @State private var isSyncing = false
  30. @State private var presentedAlert: PresentedAlert?
  31. @Environment(\.dismissAction) var dismiss
  32. @Environment(\.authenticate) var authenticate
  33. @Environment(\.appName) var appName
  34. private let lowestCarbRatio: Double?
  35. public init(
  36. value: DeliveryLimits,
  37. supportedBasalRates: [Double],
  38. scheduledBasalRange: ClosedRange<Double>?,
  39. supportedMaximumBolusVolumes: [Double],
  40. lowestCarbRatio: Double?,
  41. syncDeliveryLimits: @escaping SyncDeliveryLimits,
  42. onSave save: @escaping (_ deliveryLimits: DeliveryLimits) -> Void,
  43. mode: SettingsPresentationMode = .settings
  44. ) {
  45. self._value = State(initialValue: value)
  46. self.initialValue = value
  47. self.supportedBasalRates = supportedBasalRates
  48. self.selectableMaximumBasalRates = Guardrail.selectableMaxBasalRates(supportedBasalRates: supportedBasalRates, scheduledBasalRange: scheduledBasalRange, lowestCarbRatio: lowestCarbRatio)
  49. self.scheduledBasalRange = scheduledBasalRange
  50. self.supportedMaximumBolusVolumes = supportedMaximumBolusVolumes
  51. self.selectableMaximumBolusVolumes = Guardrail.selectableBolusVolumes(supportedBolusVolumes: supportedMaximumBolusVolumes)
  52. self.syncDeliveryLimits = syncDeliveryLimits
  53. self.save = save
  54. self.mode = mode
  55. self.lowestCarbRatio = lowestCarbRatio
  56. }
  57. public init(
  58. mode: SettingsPresentationMode,
  59. therapySettingsViewModel: TherapySettingsViewModel,
  60. didSave: (() -> Void)? = nil
  61. ) {
  62. precondition(therapySettingsViewModel.pumpSupportedIncrements() != nil)
  63. let maxBasal = therapySettingsViewModel.therapySettings.maximumBasalRatePerHour.map {
  64. HKQuantity(unit: .internationalUnitsPerHour, doubleValue: $0)
  65. }
  66. let maxBolus = therapySettingsViewModel.therapySettings.maximumBolus.map {
  67. HKQuantity(unit: .internationalUnit(), doubleValue: $0)
  68. }
  69. self.init(
  70. value: DeliveryLimits(maximumBasalRate: maxBasal, maximumBolus: maxBolus),
  71. supportedBasalRates: therapySettingsViewModel.pumpSupportedIncrements()?.basalRates ?? [],
  72. scheduledBasalRange: therapySettingsViewModel.therapySettings.basalRateSchedule?.valueRange(),
  73. supportedMaximumBolusVolumes: therapySettingsViewModel.pumpSupportedIncrements()?.maximumBolusVolumes ?? [],
  74. lowestCarbRatio: therapySettingsViewModel.therapySettings.carbRatioSchedule?.lowestValue(),
  75. syncDeliveryLimits: therapySettingsViewModel.syncDeliveryLimits,
  76. onSave: { [weak therapySettingsViewModel] newLimits in
  77. therapySettingsViewModel?.saveDeliveryLimits(limits: newLimits)
  78. didSave?()
  79. },
  80. mode: mode
  81. )
  82. }
  83. public var body: some View {
  84. switch mode {
  85. case .acceptanceFlow:
  86. content
  87. .disabled(isSyncing)
  88. case .settings:
  89. contentWithCancel
  90. .disabled(isSyncing)
  91. .navigationBarTitle("", displayMode: .inline)
  92. }
  93. }
  94. private var contentWithCancel: some View {
  95. content
  96. .navigationBarBackButtonHidden(value != initialValue)
  97. .toolbar {
  98. ToolbarItem(placement: .navigationBarLeading) {
  99. leadingNavigationBarItem
  100. }
  101. }
  102. }
  103. @ViewBuilder
  104. private var leadingNavigationBarItem: some View {
  105. if value != initialValue {
  106. cancelButton
  107. } else {
  108. EmptyView()
  109. }
  110. }
  111. private var cancelButton: some View {
  112. Button(action: { self.dismiss() } ) { Text(LocalizedString("Cancel", comment: "Cancel editing settings button title")) }
  113. }
  114. private var content: some View {
  115. ConfigurationPage(
  116. title: Text(TherapySetting.deliveryLimits.title),
  117. actionButtonTitle: Text(mode.buttonText(isSaving: isSyncing)),
  118. actionButtonState: saveButtonState,
  119. cards: {
  120. maximumBasalRateCard
  121. maximumBolusCard
  122. },
  123. actionAreaContent: {
  124. instructionalContentIfNecessary
  125. guardrailWarningIfNecessary
  126. },
  127. action: {
  128. if self.crossedThresholds.isEmpty {
  129. self.startSaving()
  130. } else {
  131. self.presentedAlert = .saveConfirmation(confirmationAlertContent)
  132. }
  133. }
  134. )
  135. .alert(item: $presentedAlert, content: alert(for:))
  136. .simultaneousGesture(TapGesture().onEnded {
  137. withAnimation {
  138. self.userDidTap = true
  139. }
  140. })
  141. }
  142. var saveButtonState: ConfigurationPageActionButtonState {
  143. guard value.maximumBasalRate != nil, value.maximumBolus != nil else {
  144. return .disabled
  145. }
  146. if isSyncing {
  147. return .loading
  148. }
  149. if mode == .acceptanceFlow {
  150. return .enabled
  151. }
  152. return value == initialValue && mode != .acceptanceFlow ? .disabled : .enabled
  153. }
  154. var maximumBasalRateGuardrail: Guardrail<HKQuantity> {
  155. return Guardrail.maximumBasalRate(supportedBasalRates: supportedBasalRates, scheduledBasalRange: scheduledBasalRange, lowestCarbRatio: lowestCarbRatio)
  156. }
  157. var maximumBasalRateCard: Card {
  158. Card {
  159. SettingDescription(text: Text(DeliveryLimits.Setting.maximumBasalRate.localizedDescriptiveText(appName: appName)),
  160. informationalContent: { TherapySetting.deliveryLimits.helpScreen() })
  161. ExpandableSetting(
  162. isEditing: Binding(
  163. get: { self.settingBeingEdited == .maximumBasalRate },
  164. set: { isEditing in
  165. withAnimation {
  166. self.settingBeingEdited = isEditing ? .maximumBasalRate : nil
  167. }
  168. }
  169. ),
  170. leadingValueContent: {
  171. Text(DeliveryLimits.Setting.maximumBasalRate.title)
  172. },
  173. trailingValueContent: {
  174. GuardrailConstrainedQuantityView(
  175. value: value.maximumBasalRate,
  176. unit: .internationalUnitsPerHour,
  177. guardrail: maximumBasalRateGuardrail,
  178. isEditing: settingBeingEdited == .maximumBasalRate,
  179. forceDisableAnimations: true
  180. )
  181. },
  182. expandedContent: {
  183. FractionalQuantityPicker(
  184. value: Binding(
  185. get: { self.value.maximumBasalRate ?? self.maximumBasalRateGuardrail.startingSuggestion ?? self.maximumBasalRateGuardrail.recommendedBounds.upperBound },
  186. set: { newValue in
  187. withAnimation {
  188. self.value.maximumBasalRate = newValue
  189. }
  190. }
  191. ),
  192. unit: .internationalUnitsPerHour,
  193. guardrail: self.maximumBasalRateGuardrail,
  194. selectableValues: self.selectableMaximumBasalRates,
  195. usageContext: .independent
  196. )
  197. .accessibility(identifier: "max_basal_picker")
  198. }
  199. )
  200. }
  201. }
  202. var maximumBolusGuardrail: Guardrail<HKQuantity> {
  203. return Guardrail.maximumBolus(supportedBolusVolumes: supportedMaximumBolusVolumes)
  204. }
  205. var maximumBolusCard: Card {
  206. Card {
  207. SettingDescription(text: Text(DeliveryLimits.Setting.maximumBolus.localizedDescriptiveText(appName: appName)),
  208. informationalContent: { TherapySetting.deliveryLimits.helpScreen() })
  209. ExpandableSetting(
  210. isEditing: Binding(
  211. get: { self.settingBeingEdited == .maximumBolus },
  212. set: { isEditing in
  213. withAnimation {
  214. self.settingBeingEdited = isEditing ? .maximumBolus : nil
  215. }
  216. }
  217. ),
  218. leadingValueContent: {
  219. Text(DeliveryLimits.Setting.maximumBolus.title)
  220. },
  221. trailingValueContent: {
  222. GuardrailConstrainedQuantityView(
  223. value: value.maximumBolus,
  224. unit: .internationalUnit(),
  225. guardrail: maximumBolusGuardrail,
  226. isEditing: settingBeingEdited == .maximumBolus,
  227. forceDisableAnimations: true
  228. )
  229. },
  230. expandedContent: {
  231. FractionalQuantityPicker(
  232. value: Binding(
  233. get: { self.value.maximumBolus ?? self.maximumBolusGuardrail.startingSuggestion ?? self.maximumBolusGuardrail.recommendedBounds.upperBound },
  234. set: { newValue in
  235. withAnimation {
  236. self.value.maximumBolus = newValue
  237. }
  238. }
  239. ),
  240. unit: .internationalUnit(),
  241. guardrail: self.maximumBolusGuardrail,
  242. selectableValues: self.selectableMaximumBolusVolumes,
  243. usageContext: .independent
  244. )
  245. .accessibility(identifier: "max_bolus_picker")
  246. }
  247. )
  248. }
  249. }
  250. private var instructionalContentIfNecessary: some View {
  251. return Group {
  252. if mode == .acceptanceFlow && !userDidTap {
  253. instructionalContent
  254. }
  255. }
  256. }
  257. private var instructionalContent: some View {
  258. HStack { // to align with guardrail warning, if present
  259. Text(LocalizedString("You can edit a setting by tapping into any line item.", comment: "Description of how to edit setting"))
  260. .foregroundColor(.secondary)
  261. .font(.subheadline)
  262. Spacer()
  263. }
  264. }
  265. private var guardrailWarningIfNecessary: some View {
  266. let crossedThresholds = self.crossedThresholds
  267. return Group {
  268. if !crossedThresholds.isEmpty && (userDidTap || mode == .settings) {
  269. DeliveryLimitsGuardrailWarning(crossedThresholds: crossedThresholds, value: value)
  270. }
  271. }
  272. }
  273. private var crossedThresholds: [DeliveryLimits.Setting: SafetyClassification.Threshold] {
  274. var crossedThresholds: [DeliveryLimits.Setting: SafetyClassification.Threshold] = [:]
  275. switch value.maximumBasalRate.map(maximumBasalRateGuardrail.classification(for:)) {
  276. case nil, .withinRecommendedRange:
  277. break
  278. case .outsideRecommendedRange(let threshold):
  279. crossedThresholds[.maximumBasalRate] = threshold
  280. }
  281. switch value.maximumBolus.map(maximumBolusGuardrail.classification(for:)) {
  282. case nil, .withinRecommendedRange:
  283. break
  284. case .outsideRecommendedRange(let threshold):
  285. crossedThresholds[.maximumBolus] = threshold
  286. }
  287. return crossedThresholds
  288. }
  289. private func startSaving() {
  290. guard mode == .settings else {
  291. self.monitorSavingMechanism(savingMechanism: .synchronous { deliveryLimits in
  292. save(deliveryLimits)
  293. })
  294. return
  295. }
  296. authenticate(TherapySetting.deliveryLimits.authenticationChallengeDescription) {
  297. switch $0 {
  298. case .success:
  299. self.monitorSavingMechanism(savingMechanism: .asynchronous { deliveryLimits, completion in
  300. synchronizeDeliveryLimits(deliveryLimits, completion)
  301. })
  302. case .failure: break
  303. }
  304. }
  305. }
  306. private func synchronizeDeliveryLimits(_ deliveryLimits: DeliveryLimits, _ completion: @escaping (Error?) -> Void) {
  307. guard let syncDeliveryLimits = self.syncDeliveryLimits else {
  308. actuallySave(deliveryLimits)
  309. return
  310. }
  311. syncDeliveryLimits(deliveryLimits) { result in
  312. switch result {
  313. case .success(let deliveryLimits):
  314. actuallySave(deliveryLimits)
  315. completion(nil)
  316. case .failure(let error):
  317. completion(PresentedAlert.saveError(error))
  318. }
  319. }
  320. }
  321. private func actuallySave(_ deliveryLimits: DeliveryLimits) {
  322. DispatchQueue.main.async {
  323. self.save(deliveryLimits)
  324. }
  325. }
  326. private func monitorSavingMechanism(savingMechanism: SavingMechanism<DeliveryLimits>) {
  327. switch savingMechanism {
  328. case .synchronous(let save):
  329. save(value)
  330. case .asynchronous(let save):
  331. withAnimation {
  332. self.isSyncing = true
  333. }
  334. save(value) { error in
  335. DispatchQueue.main.async {
  336. if let error = error {
  337. withAnimation {
  338. self.isSyncing = false
  339. }
  340. self.presentedAlert = (error as? PresentedAlert) ?? .saveError(error)
  341. }
  342. }
  343. }
  344. }
  345. }
  346. private func alert(for presentedAlert: PresentedAlert) -> SwiftUI.Alert {
  347. switch presentedAlert {
  348. case .saveConfirmation(let content):
  349. return SwiftUI.Alert(
  350. title: content.title,
  351. message: content.message,
  352. primaryButton: .cancel(
  353. content.cancel ??
  354. Text(LocalizedString("Go Back", comment: "Button text to return to editing a schedule after from alert popup when some schedule values are outside the recommended range"))),
  355. secondaryButton: .default(
  356. content.ok ??
  357. Text(LocalizedString("Continue", comment: "Button text to confirm saving from alert popup when some schedule values are outside the recommended range")),
  358. action: startSaving
  359. )
  360. )
  361. case .saveError(let error):
  362. return SwiftUI.Alert(
  363. title: Text(LocalizedString("Unable to Save", comment: "Alert title when error occurs while saving a schedule")),
  364. message: Text(error.localizedDescription)
  365. )
  366. }
  367. }
  368. private var confirmationAlertContent: AlertContent {
  369. AlertContent(
  370. title: Text(LocalizedString("Save Delivery Limits?", comment: "Alert title for confirming delivery limits outside the recommended range")),
  371. message: Text(TherapySetting.deliveryLimits.guardrailSaveWarningCaption),
  372. cancel: Text(LocalizedString("Go Back", comment: "Text for go back action on confirmation alert")),
  373. ok: Text(LocalizedString("Continue", comment: "Text for continue action on confirmation alert")
  374. )
  375. )
  376. }
  377. }
  378. struct DeliveryLimitsGuardrailWarning: View {
  379. let crossedThresholds: [DeliveryLimits.Setting: SafetyClassification.Threshold]
  380. let value: DeliveryLimits
  381. var body: some View {
  382. switch crossedThresholds.count {
  383. case 0:
  384. preconditionFailure("A guardrail warning requires at least one crossed threshold")
  385. case 1:
  386. let (setting, threshold) = crossedThresholds.first!
  387. let title: Text
  388. switch setting {
  389. case .maximumBasalRate:
  390. switch threshold {
  391. case .minimum, .belowRecommended:
  392. title = Text(LocalizedString("Low Maximum Basal Rate", comment: "Title text for low maximum basal rate warning"))
  393. case .aboveRecommended, .maximum:
  394. title = Text(LocalizedString("High Maximum Basal Rate", comment: "Title text for high maximum basal rate warning"))
  395. }
  396. case .maximumBolus:
  397. switch threshold {
  398. case .minimum, .belowRecommended:
  399. title = Text(LocalizedString("Low Maximum Bolus", comment: "Title text for low maximum bolus warning"))
  400. case .aboveRecommended, .maximum:
  401. title = Text(LocalizedString("High Maximum Bolus", comment: "Title text for high maximum bolus warning"))
  402. }
  403. }
  404. return GuardrailWarning(therapySetting: .deliveryLimits, title: title, threshold: threshold)
  405. case 2:
  406. return GuardrailWarning(
  407. therapySetting: .deliveryLimits,
  408. title: Text(LocalizedString("Delivery Limits", comment: "Title text for crossed thresholds guardrail warning")),
  409. thresholds: Array(crossedThresholds.values))
  410. default:
  411. preconditionFailure("Unreachable: only two delivery limit settings exist")
  412. }
  413. }
  414. }
  415. extension DeliveryLimitsEditor.PresentedAlert: Identifiable {
  416. var id: Int {
  417. switch self {
  418. case .saveConfirmation:
  419. return 0
  420. case .saveError:
  421. return 1
  422. }
  423. }
  424. }