AddOverrideForm.swift 23 KB

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