AddOverrideForm.swift 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  1. import Foundation
  2. import SwiftUI
  3. struct AddOverrideForm: View {
  4. @Environment(\.presentationMode) var presentationMode
  5. @Environment(\.colorScheme) var colorScheme
  6. @Environment(\.dismiss) var dismiss
  7. @Environment(AppState.self) var appState
  8. @Bindable var state: Adjustments.StateModel
  9. @State private var selectedIsfCrOption: IsfAndOrCrOptions = .isfAndCr
  10. @State private var selectedDisableSmbOption: DisableSmbOptions = .dontDisable
  11. @State private var percentageStep: Int = 5
  12. @State private var displayPickerPercentage: Bool = false
  13. @State private var displayPickerDuration: Bool = false
  14. @State private var targetStep: Decimal = 5
  15. @State private var displayPickerTarget: Bool = false
  16. @State private var displayPickerDisableSmbSchedule: Bool = false
  17. @State private var displayPickerSmbMinutes: Bool = false
  18. @State private var durationHours = 0
  19. @State private var durationMinutes = 0
  20. @State private var overrideTarget = false
  21. @State private var didPressSave = false
  22. var body: some View {
  23. NavigationView {
  24. List {
  25. addOverride()
  26. saveButton
  27. }
  28. .listSectionSpacing(10)
  29. .padding(.top, 30)
  30. .ignoresSafeArea(edges: .top)
  31. .scrollContentBackground(.hidden)
  32. .background(appState.trioBackgroundColor(for: colorScheme))
  33. .navigationTitle("Add Override")
  34. .navigationBarTitleDisplayMode(.inline)
  35. .toolbar {
  36. ToolbarItem(placement: .topBarLeading) {
  37. Button(action: {
  38. presentationMode.wrappedValue.dismiss()
  39. }, label: {
  40. Text("Cancel")
  41. })
  42. }
  43. ToolbarItem(placement: .topBarTrailing) {
  44. Button(
  45. action: {
  46. state.isHelpSheetPresented.toggle()
  47. },
  48. label: {
  49. Image(systemName: "questionmark.circle")
  50. }
  51. )
  52. }
  53. }
  54. .onAppear { targetStep = state.units == .mgdL ? 5 : 9 }
  55. .sheet(isPresented: $state.isHelpSheetPresented) {
  56. OverrideHelpView(state: state, helpSheetDetent: $state.helpSheetDetent)
  57. }
  58. }
  59. }
  60. @ViewBuilder private func addOverride() -> some View {
  61. Group {
  62. Section {
  63. HStack {
  64. Text("Name")
  65. Spacer()
  66. TextField("(Optional)", text: $state.overrideName).multilineTextAlignment(.trailing)
  67. }
  68. }
  69. .listRowBackground(Color.chart)
  70. Section(footer: state.percentageDescription(state.overridePercentage)) {
  71. // Percentage Picker
  72. HStack {
  73. Text("Basal Rate Adjustment")
  74. Spacer()
  75. Text("\(state.overridePercentage.formatted(.number)) %")
  76. .foregroundColor(!displayPickerPercentage ? .primary : .accentColor)
  77. .onTapGesture {
  78. displayPickerPercentage = toggleScrollWheel(displayPickerPercentage)
  79. }
  80. }
  81. if displayPickerPercentage {
  82. HStack {
  83. // Radio buttons and text on the left side
  84. VStack(alignment: .leading) {
  85. // Radio buttons for step iteration
  86. ForEach([1, 5], id: \.self) { step in
  87. RadioButton(isSelected: percentageStep == step, label: "\(step) %") {
  88. percentageStep = step
  89. state.overridePercentage = Adjustments.StateModel.roundOverridePercentageToStep(
  90. state.overridePercentage,
  91. step
  92. )
  93. }
  94. .padding(.top, 10)
  95. }
  96. }
  97. .frame(maxWidth: .infinity)
  98. Spacer()
  99. // Picker on the right side
  100. Picker(
  101. selection: Binding(
  102. get: { Int(truncating: state.overridePercentage as NSNumber) },
  103. set: { state.overridePercentage = Double($0) }
  104. ), label: Text("")
  105. ) {
  106. ForEach(Array(stride(from: 40, through: 150, by: percentageStep)), id: \.self) { percent in
  107. Text("\(percent) %").tag(percent)
  108. }
  109. }
  110. .pickerStyle(WheelPickerStyle())
  111. .frame(maxWidth: .infinity)
  112. }
  113. .frame(maxWidth: .infinity)
  114. .listRowSeparator(.hidden, edges: .top)
  115. }
  116. // Picker for ISF/CR settings
  117. Picker("Also Inversely Change", selection: $selectedIsfCrOption) {
  118. ForEach(IsfAndOrCrOptions.allCases, id: \.self) { option in
  119. Text(option.rawValue).tag(option)
  120. }
  121. }
  122. .pickerStyle(MenuPickerStyle())
  123. .onChange(of: selectedIsfCrOption) { _, newValue in
  124. switch newValue {
  125. case .isfAndCr:
  126. state.isfAndCr = true
  127. state.isf = true
  128. state.cr = true
  129. case .isf:
  130. state.isfAndCr = false
  131. state.isf = true
  132. state.cr = false
  133. case .cr:
  134. state.isfAndCr = false
  135. state.isf = false
  136. state.cr = true
  137. case .nothing:
  138. state.isfAndCr = false
  139. state.isf = false
  140. state.cr = false
  141. }
  142. }
  143. }
  144. .listRowBackground(Color.chart)
  145. Section {
  146. Toggle(isOn: $state.shouldOverrideTarget) {
  147. Text("Override Target")
  148. }
  149. if state.shouldOverrideTarget {
  150. let settingsProvider = PickerSettingsProvider.shared
  151. let glucoseSetting = PickerSetting(value: 0, step: targetStep, min: 72, max: 270, type: .glucose)
  152. TargetPicker(
  153. label: "Target Glucose",
  154. selection: Binding(
  155. get: { state.target },
  156. set: { state.target = $0 }
  157. ),
  158. options: settingsProvider.generatePickerValues(
  159. from: glucoseSetting,
  160. units: state.units,
  161. roundMinToStep: true
  162. ),
  163. units: state.units,
  164. targetStep: $targetStep,
  165. displayPickerTarget: $displayPickerTarget,
  166. toggleScrollWheel: toggleScrollWheel
  167. )
  168. .onAppear {
  169. if state.target == 0 {
  170. state.target = 100
  171. }
  172. }
  173. }
  174. }
  175. .listRowBackground(Color.chart)
  176. Section {
  177. // Picker for ISF/CR settings
  178. Picker("Disable SMBs", selection: $selectedDisableSmbOption) {
  179. ForEach(DisableSmbOptions.allCases, id: \.self) { option in
  180. Text(option.rawValue).tag(option)
  181. }
  182. }
  183. .pickerStyle(MenuPickerStyle())
  184. .onChange(of: selectedDisableSmbOption) { _, newValue in
  185. switch newValue {
  186. case .dontDisable:
  187. state.smbIsOff = false
  188. state.smbIsScheduledOff = false
  189. case .disable:
  190. state.smbIsOff = true
  191. state.smbIsScheduledOff = false
  192. case .disableOnSchedule:
  193. state.smbIsOff = false
  194. state.smbIsScheduledOff = true
  195. }
  196. }
  197. if state.smbIsScheduledOff {
  198. // First Hour SMBs Are Disabled
  199. HStack {
  200. Text("From")
  201. Spacer()
  202. Text(
  203. state.is24HourFormat() ? state.format24Hour(Int(truncating: state.start as NSNumber)) + ":00" :
  204. state.convertTo12HourFormat(Int(truncating: state.start as NSNumber))
  205. )
  206. .foregroundColor(!displayPickerDisableSmbSchedule ? .primary : .accentColor)
  207. .onTapGesture {
  208. displayPickerDisableSmbSchedule = toggleScrollWheel(displayPickerDisableSmbSchedule)
  209. }
  210. Spacer()
  211. Divider().frame(width: 1, height: 20)
  212. Spacer()
  213. Text("To")
  214. Spacer()
  215. Text(
  216. state.is24HourFormat() ? state.format24Hour(Int(truncating: state.end as NSNumber)) + ":00" :
  217. state.convertTo12HourFormat(Int(truncating: state.end as NSNumber))
  218. )
  219. .foregroundColor(!displayPickerDisableSmbSchedule ? .primary : .accentColor)
  220. .onTapGesture {
  221. displayPickerDisableSmbSchedule = toggleScrollWheel(displayPickerDisableSmbSchedule)
  222. }
  223. Spacer()
  224. }
  225. if displayPickerDisableSmbSchedule {
  226. HStack {
  227. // From Picker
  228. Picker(selection: Binding(
  229. get: { Int(truncating: state.start as NSNumber) },
  230. set: { state.start = Decimal($0) }
  231. ), label: Text("")) {
  232. ForEach(0 ..< 24, id: \.self) { hour in
  233. Text(
  234. state.is24HourFormat() ? state.format24Hour(hour) + ":00" : state
  235. .convertTo12HourFormat(hour)
  236. )
  237. .tag(hour)
  238. }
  239. }
  240. .pickerStyle(WheelPickerStyle())
  241. .frame(maxWidth: .infinity)
  242. // To Picker
  243. Picker(selection: Binding(
  244. get: { Int(truncating: state.end as NSNumber) },
  245. set: { state.end = Decimal($0) }
  246. ), label: Text("")) {
  247. ForEach(0 ..< 24, id: \.self) { hour in
  248. Text(
  249. state.is24HourFormat() ? state.format24Hour(hour) + ":00" : state
  250. .convertTo12HourFormat(hour)
  251. )
  252. .tag(hour)
  253. }
  254. }
  255. .pickerStyle(WheelPickerStyle())
  256. .frame(maxWidth: .infinity)
  257. }
  258. .listRowSeparator(.hidden, edges: .top)
  259. }
  260. }
  261. }
  262. .listRowBackground(Color.chart)
  263. if !state.smbIsOff {
  264. Section {
  265. Toggle(isOn: $state.advancedSettings) {
  266. Text("Override Max SMB Minutes")
  267. }
  268. if state.advancedSettings {
  269. // SMB Minutes Picker
  270. HStack {
  271. Text("SMB")
  272. Spacer()
  273. Text("\(state.smbMinutes.formatted(.number)) min")
  274. .foregroundColor(!displayPickerSmbMinutes ? .primary : .accentColor)
  275. .onTapGesture {
  276. displayPickerSmbMinutes = toggleScrollWheel(displayPickerSmbMinutes)
  277. }
  278. Spacer()
  279. Divider().frame(width: 1, height: 20)
  280. Spacer()
  281. Text("UAM")
  282. Spacer()
  283. Text("\(state.uamMinutes.formatted(.number)) min")
  284. .foregroundColor(!displayPickerSmbMinutes ? .primary : .accentColor)
  285. .onTapGesture {
  286. displayPickerSmbMinutes = toggleScrollWheel(displayPickerSmbMinutes)
  287. }
  288. }
  289. if displayPickerSmbMinutes {
  290. HStack {
  291. Picker(selection: Binding(
  292. get: { Int(truncating: state.smbMinutes as NSNumber) },
  293. set: { state.smbMinutes = Decimal($0) }
  294. ), label: Text("")) {
  295. ForEach(Array(stride(from: 0, through: 180, by: 5)), id: \.self) { minute in
  296. Text("\(minute) min").tag(minute)
  297. }
  298. }
  299. .pickerStyle(WheelPickerStyle())
  300. .frame(maxWidth: .infinity)
  301. Picker(selection: Binding(
  302. get: { Int(truncating: state.uamMinutes as NSNumber) },
  303. set: { state.uamMinutes = Decimal($0) }
  304. ), label: Text("")) {
  305. ForEach(Array(stride(from: 0, through: 180, by: 5)), id: \.self) { minute in
  306. Text("\(minute) min").tag(minute)
  307. }
  308. }
  309. .pickerStyle(WheelPickerStyle())
  310. .frame(maxWidth: .infinity)
  311. }
  312. .listRowSeparator(.hidden, edges: .top)
  313. }
  314. }
  315. }
  316. .listRowBackground(Color.chart)
  317. }
  318. Section {
  319. Toggle(isOn: $state.indefinite) {
  320. Text("Enable Indefinitely")
  321. }
  322. if !state.indefinite {
  323. HStack {
  324. Text("Duration")
  325. Spacer()
  326. Text(state.formatHrMin(Int(state.overrideDuration)))
  327. .foregroundColor(!displayPickerDuration ? .primary : .accentColor)
  328. .onTapGesture {
  329. displayPickerDuration = toggleScrollWheel(displayPickerDuration)
  330. }
  331. }
  332. if displayPickerDuration {
  333. HStack {
  334. Picker("Hours", selection: $durationHours) {
  335. ForEach(0 ..< 24) { hour in
  336. Text("\(hour) hr").tag(hour)
  337. }
  338. }
  339. .pickerStyle(WheelPickerStyle())
  340. .frame(maxWidth: .infinity)
  341. .onChange(of: durationHours) {
  342. state.overrideDuration = state.convertToMinutes(durationHours, durationMinutes)
  343. }
  344. Picker("Minutes", selection: $durationMinutes) {
  345. ForEach(Array(stride(from: 0, through: 55, by: 5)), id: \.self) { minute in
  346. Text("\(minute) min").tag(minute)
  347. }
  348. }
  349. .pickerStyle(WheelPickerStyle())
  350. .frame(maxWidth: .infinity)
  351. .onChange(of: durationMinutes) {
  352. state.overrideDuration = state.convertToMinutes(durationHours, durationMinutes)
  353. }
  354. }
  355. .listRowSeparator(.hidden, edges: .top)
  356. }
  357. }
  358. }
  359. .listRowBackground(Color.chart)
  360. }
  361. }
  362. private var saveButton: some View {
  363. let (isInvalid, errorMessage) = isOverrideInvalid()
  364. return Group {
  365. Section(
  366. header:
  367. HStack {
  368. Spacer()
  369. Text(errorMessage ?? "").textCase(nil)
  370. .foregroundColor(colorScheme == .dark ? .orange : .accentColor)
  371. Spacer()
  372. },
  373. content: {
  374. Button(action: {
  375. Task {
  376. if state.indefinite { state.overrideDuration = 0 }
  377. state.isOverrideEnabled.toggle()
  378. await state.saveCustomOverride()
  379. await state.resetStateVariables()
  380. dismiss()
  381. }
  382. }, label: {
  383. Text("Start Override")
  384. })
  385. .disabled(isInvalid)
  386. .frame(maxWidth: .infinity, alignment: .center)
  387. .tint(.white)
  388. }
  389. ).listRowBackground(isInvalid ? Color(.systemGray4) : Color(.systemBlue))
  390. Section {
  391. Button(action: {
  392. Task {
  393. await state.saveOverridePreset()
  394. dismiss()
  395. }
  396. }, label: {
  397. Text("Save as Preset")
  398. })
  399. .disabled(isInvalid)
  400. .frame(maxWidth: .infinity, alignment: .center)
  401. .tint(.white)
  402. }
  403. .listRowBackground(
  404. isInvalid ? Color(.systemGray4) : Color.secondary
  405. )
  406. }
  407. }
  408. private func toggleScrollWheel(_ toggle: Bool) -> Bool {
  409. displayPickerDuration = false
  410. displayPickerPercentage = false
  411. displayPickerTarget = false
  412. displayPickerDisableSmbSchedule = false
  413. displayPickerSmbMinutes = false
  414. return !toggle
  415. }
  416. private func isOverrideInvalid() -> (Bool, String?) {
  417. let noDurationSpecified = !state.indefinite && state.overrideDuration == 0
  418. let targetZeroWithOverride = state.shouldOverrideTarget && state.target == 0
  419. let allSettingsDefault = state.overridePercentage == 100 && !state.shouldOverrideTarget &&
  420. !state.advancedSettings && !state.smbIsOff && !state.smbIsScheduledOff
  421. if noDurationSpecified {
  422. return (true, "Enable indefinitely or set a duration.")
  423. }
  424. if targetZeroWithOverride {
  425. return (true, "Target glucose is out of range (\(state.units == .mgdL ? "72-270" : "4-14")).")
  426. }
  427. if allSettingsDefault {
  428. return (true, "All settings are at default values.")
  429. }
  430. return (false, nil)
  431. }
  432. }