AddOverrideForm.swift 20 KB

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