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(footer: percentageDescription(state.overridePercentage)) {
  100. // Percentage Picker
  101. HStack {
  102. Text("Change Basal Rate by")
  103. Spacer()
  104. Text("\(state.overridePercentage.formatted(.number)) %")
  105. .foregroundColor(!displayPickerPercentage ? .primary : .accentColor)
  106. }
  107. .onTapGesture {
  108. displayPickerPercentage = toggleScrollWheel(displayPickerPercentage)
  109. }
  110. if displayPickerPercentage {
  111. HStack {
  112. // Radio buttons and text on the left side
  113. VStack(alignment: .leading) {
  114. // Radio buttons for step iteration
  115. ForEach([1, 5], id: \.self) { step in
  116. RadioButton(isSelected: percentageStep == step, label: "\(step) %") {
  117. percentageStep = step
  118. state.overridePercentage = OverrideConfig.StateModel.roundOverridePercentageToStep(
  119. state.overridePercentage,
  120. step
  121. )
  122. }
  123. .padding(.top, 10)
  124. }
  125. }
  126. .frame(maxWidth: .infinity)
  127. Spacer()
  128. // Picker on the right side
  129. Picker(
  130. selection: Binding(
  131. get: { Int(truncating: state.overridePercentage as NSNumber) },
  132. set: { state.overridePercentage = Double($0) }
  133. ), label: Text("")
  134. ) {
  135. ForEach(Array(stride(from: 40, through: 150, by: percentageStep)), id: \.self) { percent in
  136. Text("\(percent) %").tag(percent)
  137. }
  138. }
  139. .pickerStyle(WheelPickerStyle())
  140. .frame(maxWidth: .infinity)
  141. }
  142. .frame(maxWidth: .infinity)
  143. .listRowSeparator(.hidden, edges: .top)
  144. }
  145. // Picker for ISF/CR settings
  146. Picker("Also Inversely Change", selection: $selectedIsfCrOption) {
  147. ForEach(IsfAndOrCrOptions.allCases, id: \.self) { option in
  148. Text(option.rawValue).tag(option)
  149. }
  150. }
  151. .pickerStyle(MenuPickerStyle())
  152. .onChange(of: selectedIsfCrOption) { _, newValue in
  153. switch newValue {
  154. case .isfAndCr:
  155. state.isfAndCr = true
  156. state.isf = true
  157. state.cr = true
  158. case .isf:
  159. state.isfAndCr = false
  160. state.isf = true
  161. state.cr = false
  162. case .cr:
  163. state.isfAndCr = false
  164. state.isf = false
  165. state.cr = true
  166. case .nothing:
  167. state.isfAndCr = false
  168. state.isf = false
  169. state.cr = false
  170. }
  171. }
  172. }
  173. .listRowBackground(Color.chart)
  174. Section {
  175. Toggle(isOn: $state.shouldOverrideTarget) {
  176. Text("Override Target")
  177. }
  178. if state.shouldOverrideTarget {
  179. let settingsProvider = PickerSettingsProvider.shared
  180. let glucoseSetting = PickerSetting(value: 0, step: targetStep, min: 72, max: 270, type: .glucose)
  181. TargetPicker(
  182. label: "Target Glucose",
  183. selection: Binding(
  184. get: { state.target },
  185. set: { state.target = $0 }
  186. ),
  187. options: settingsProvider.generatePickerValues(
  188. from: glucoseSetting,
  189. units: state.units,
  190. roundMinToStep: true
  191. ),
  192. units: state.units,
  193. targetStep: $targetStep,
  194. displayPickerTarget: $displayPickerTarget,
  195. toggleScrollWheel: toggleScrollWheel
  196. )
  197. .onAppear {
  198. if state.target == 0 {
  199. state.target = 100
  200. }
  201. }
  202. }
  203. }
  204. .listRowBackground(Color.chart)
  205. Section {
  206. // Picker for ISF/CR settings
  207. Picker("Disable SMBs", selection: $selectedDisableSmbOption) {
  208. ForEach(DisableSmbOptions.allCases, id: \.self) { option in
  209. Text(option.rawValue).tag(option)
  210. }
  211. }
  212. .pickerStyle(MenuPickerStyle())
  213. .onChange(of: selectedDisableSmbOption) { _, newValue in
  214. switch newValue {
  215. case .dontDisable:
  216. state.smbIsOff = false
  217. state.smbIsScheduledOff = false
  218. case .disable:
  219. state.smbIsOff = true
  220. state.smbIsScheduledOff = false
  221. case .disableOnSchedule:
  222. state.smbIsOff = false
  223. state.smbIsScheduledOff = true
  224. }
  225. }
  226. if state.smbIsScheduledOff {
  227. // First Hour SMBs Are Disabled
  228. HStack {
  229. Text("From")
  230. Spacer()
  231. Text(
  232. is24HourFormat() ? format24Hour(Int(truncating: state.start as NSNumber)) + ":00" :
  233. convertTo12HourFormat(Int(truncating: state.start as NSNumber))
  234. )
  235. .foregroundColor(!displayPickerDisableSmbSchedule ? .primary : .accentColor)
  236. Spacer()
  237. Divider().frame(width: 1, height: 20)
  238. Spacer()
  239. Text("To")
  240. Spacer()
  241. Text(
  242. is24HourFormat() ? format24Hour(Int(truncating: state.end as NSNumber)) + ":00" :
  243. convertTo12HourFormat(Int(truncating: state.end as NSNumber))
  244. )
  245. .foregroundColor(!displayPickerDisableSmbSchedule ? .primary : .accentColor)
  246. Spacer()
  247. }
  248. .onTapGesture {
  249. displayPickerDisableSmbSchedule = toggleScrollWheel(displayPickerDisableSmbSchedule)
  250. }
  251. if displayPickerDisableSmbSchedule {
  252. HStack {
  253. // From Picker
  254. Picker(selection: Binding(
  255. get: { Int(truncating: state.start as NSNumber) },
  256. set: { state.start = Decimal($0) }
  257. ), label: Text("")) {
  258. ForEach(0 ..< 24, id: \.self) { hour in
  259. Text(is24HourFormat() ? format24Hour(hour) + ":00" : convertTo12HourFormat(hour))
  260. .tag(hour)
  261. }
  262. }
  263. .pickerStyle(WheelPickerStyle())
  264. .frame(maxWidth: .infinity)
  265. // To Picker
  266. Picker(selection: Binding(
  267. get: { Int(truncating: state.end as NSNumber) },
  268. set: { state.end = Decimal($0) }
  269. ), label: Text("")) {
  270. ForEach(0 ..< 24, id: \.self) { hour in
  271. Text(is24HourFormat() ? format24Hour(hour) + ":00" : convertTo12HourFormat(hour))
  272. .tag(hour)
  273. }
  274. }
  275. .pickerStyle(WheelPickerStyle())
  276. .frame(maxWidth: .infinity)
  277. }
  278. .listRowSeparator(.hidden, edges: .top)
  279. }
  280. }
  281. }
  282. .listRowBackground(Color.chart)
  283. if !state.smbIsOff {
  284. Section {
  285. Toggle(isOn: $state.advancedSettings) {
  286. Text("Override Max SMB Minutes")
  287. }
  288. if state.advancedSettings {
  289. // SMB Minutes Picker
  290. HStack {
  291. Text("SMB")
  292. Spacer()
  293. Text("\(state.smbMinutes.formatted(.number)) min")
  294. .foregroundColor(!displayPickerSmbMinutes ? .primary : .accentColor)
  295. Spacer()
  296. Divider().frame(width: 1, height: 20)
  297. Spacer()
  298. Text("UAM")
  299. Spacer()
  300. Text("\(state.uamMinutes.formatted(.number)) min")
  301. .foregroundColor(!displayPickerSmbMinutes ? .primary : .accentColor)
  302. }
  303. .onTapGesture {
  304. displayPickerSmbMinutes = toggleScrollWheel(displayPickerSmbMinutes)
  305. }
  306. if displayPickerSmbMinutes {
  307. HStack {
  308. Picker(selection: Binding(
  309. get: { Int(truncating: state.smbMinutes as NSNumber) },
  310. set: { state.smbMinutes = Decimal($0) }
  311. ), label: Text("")) {
  312. ForEach(Array(stride(from: 0, through: 180, by: 5)), id: \.self) { minute in
  313. Text("\(minute) min").tag(minute)
  314. }
  315. }
  316. .pickerStyle(WheelPickerStyle())
  317. .frame(maxWidth: .infinity)
  318. Picker(selection: Binding(
  319. get: { Int(truncating: state.uamMinutes as NSNumber) },
  320. set: { state.uamMinutes = Decimal($0) }
  321. ), label: Text("")) {
  322. ForEach(Array(stride(from: 0, through: 180, by: 5)), id: \.self) { minute in
  323. Text("\(minute) min").tag(minute)
  324. }
  325. }
  326. .pickerStyle(WheelPickerStyle())
  327. .frame(maxWidth: .infinity)
  328. }
  329. .listRowSeparator(.hidden, edges: .top)
  330. }
  331. }
  332. }
  333. .listRowBackground(Color.chart)
  334. }
  335. Section {
  336. Toggle(isOn: $state.indefinite) {
  337. Text("Enable Indefinitely")
  338. }
  339. if !state.indefinite {
  340. HStack {
  341. Text("Duration")
  342. Spacer()
  343. Text(formatHrMin(Int(state.overrideDuration)))
  344. .foregroundColor(!displayPickerDuration ? .primary : .accentColor)
  345. }
  346. .onTapGesture {
  347. displayPickerDuration = toggleScrollWheel(displayPickerDuration)
  348. }
  349. if displayPickerDuration {
  350. HStack {
  351. Picker("Hours", selection: $durationHours) {
  352. ForEach(0 ..< 24) { hour in
  353. Text("\(hour) hr").tag(hour)
  354. }
  355. }
  356. .pickerStyle(WheelPickerStyle())
  357. .frame(maxWidth: .infinity)
  358. .onChange(of: durationHours) {
  359. state.overrideDuration = convertToMinutes(durationHours, durationMinutes)
  360. }
  361. Picker("Minutes", selection: $durationMinutes) {
  362. ForEach(Array(stride(from: 0, through: 55, by: 5)), id: \.self) { minute in
  363. Text("\(minute) min").tag(minute)
  364. }
  365. }
  366. .pickerStyle(WheelPickerStyle())
  367. .frame(maxWidth: .infinity)
  368. .onChange(of: durationMinutes) {
  369. state.overrideDuration = convertToMinutes(durationHours, durationMinutes)
  370. }
  371. }
  372. .listRowSeparator(.hidden, edges: .top)
  373. }
  374. }
  375. }
  376. .listRowBackground(Color.chart)
  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("Start 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. }