AddOverrideForm.swift 20 KB

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