AddTempTargetForm.swift 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  1. import Foundation
  2. import SwiftUI
  3. struct AddTempTargetForm: View {
  4. // settings for picker steps
  5. let smallMgdL = 1.0
  6. let bigMgdL = 5.0
  7. let smallMmolL = 0.1 / 0.0555
  8. let bigMmolL = 0.5 / 0.0555
  9. init(state: OverrideConfig.StateModel) {
  10. _state = StateObject(wrappedValue: state)
  11. _targetStep = State(initialValue: state.units == .mgdL ? bigMgdL : bigMmolL)
  12. }
  13. @State var toggleBigStepOn = true
  14. @StateObject var state: OverrideConfig.StateModel
  15. @Environment(\.presentationMode) var presentationMode
  16. @Environment(\.colorScheme) var colorScheme
  17. @Environment(\.dismiss) var dismiss
  18. @State private var displayPickerDuration: Bool = false
  19. @State private var durationHours = 0
  20. @State private var durationMinutes = 0
  21. @State private var targetStep: Double
  22. @State private var displayPickerTarget: Bool = false
  23. @State private var showAlert = false
  24. @State private var showPresetAlert = false
  25. @State private var alertString = ""
  26. @State private var isUsingSlider = false
  27. @State private var didPressSave =
  28. false // only used for fixing the Disclaimer showing up after pressing save (after the state was resetted), maybe refactor this...
  29. @State private var shouldDisplayHint = false
  30. @State var hintDetent = PresentationDetent.large
  31. @State var selectedVerboseHint: String?
  32. @State var hintLabel: String?
  33. var color: LinearGradient {
  34. colorScheme == .dark ? LinearGradient(
  35. gradient: Gradient(colors: [
  36. Color.bgDarkBlue,
  37. Color.bgDarkerDarkBlue
  38. ]),
  39. startPoint: .top,
  40. endPoint: .bottom
  41. )
  42. :
  43. LinearGradient(
  44. gradient: Gradient(colors: [Color.gray.opacity(0.1)]),
  45. startPoint: .top,
  46. endPoint: .bottom
  47. )
  48. }
  49. private var formatter: NumberFormatter {
  50. let formatter = NumberFormatter()
  51. formatter.numberStyle = .decimal
  52. formatter.maximumFractionDigits = 0
  53. return formatter
  54. }
  55. private var glucoseFormatter: NumberFormatter {
  56. let formatter = NumberFormatter()
  57. formatter.numberStyle = .decimal
  58. formatter.maximumFractionDigits = 0
  59. if state.units == .mmolL {
  60. formatter.maximumFractionDigits = 1
  61. }
  62. formatter.roundingMode = .halfUp
  63. return formatter
  64. }
  65. var isSliderEnabled: Bool {
  66. state.computeSliderHigh() > state.computeSliderLow()
  67. }
  68. var body: some View {
  69. NavigationView {
  70. List {
  71. addTempTarget()
  72. saveButton
  73. }
  74. .listSectionSpacing(10)
  75. .listRowSpacing(10)
  76. .padding(.top, 30)
  77. .ignoresSafeArea(edges: .top)
  78. .scrollContentBackground(.hidden).background(color)
  79. .navigationTitle("Add Temp Target")
  80. .navigationBarTitleDisplayMode(.inline)
  81. .toolbar {
  82. ToolbarItem(placement: .topBarLeading) {
  83. Button(action: {
  84. presentationMode.wrappedValue.dismiss()
  85. }, label: {
  86. Text("Cancel")
  87. })
  88. }
  89. }
  90. .sheet(isPresented: $shouldDisplayHint) {
  91. SettingInputHintView(
  92. hintDetent: $hintDetent,
  93. shouldDisplayHint: $shouldDisplayHint,
  94. hintLabel: hintLabel ?? "",
  95. hintText: selectedVerboseHint ?? "",
  96. sheetTitle: "Help"
  97. )
  98. }
  99. }
  100. }
  101. @ViewBuilder private func addTempTarget() -> some View {
  102. Section {
  103. let pad: CGFloat = 3
  104. HStack {
  105. Text("Name")
  106. Spacer()
  107. TextField("Enter Name (optional)", text: $state.tempTargetName)
  108. .multilineTextAlignment(.trailing)
  109. }
  110. VStack {
  111. HStack {
  112. Text("Duration")
  113. Spacer()
  114. Text(formatHrMin(Int(state.tempTargetDuration)))
  115. .foregroundColor(!displayPickerDuration ? .primary : .accentColor)
  116. }
  117. .padding(.vertical, pad)
  118. .onTapGesture {
  119. displayPickerDuration.toggle()
  120. }
  121. if displayPickerDuration {
  122. HStack {
  123. Picker("Hours", selection: $durationHours) {
  124. ForEach(0 ..< 24) { hour in
  125. Text("\(hour) hr").tag(hour)
  126. }
  127. }
  128. .pickerStyle(WheelPickerStyle())
  129. .frame(maxWidth: .infinity)
  130. .onChange(of: durationHours) {
  131. state.tempTargetDuration = Decimal(totalDurationInMinutes())
  132. }
  133. Picker("Minutes", selection: $durationMinutes) {
  134. ForEach(Array(stride(from: 0, through: 55, by: 5)), id: \.self) { minute in
  135. Text("\(minute) min").tag(minute)
  136. }
  137. }
  138. .pickerStyle(WheelPickerStyle())
  139. .frame(maxWidth: .infinity)
  140. .onChange(of: durationMinutes) {
  141. state.tempTargetDuration = Decimal(totalDurationInMinutes())
  142. }
  143. }
  144. }
  145. }
  146. VStack {
  147. HStack {
  148. Text("Target Glucose")
  149. Spacer()
  150. Text(formattedGlucose(glucose: state.tempTargetTarget))
  151. .foregroundColor(!displayPickerTarget ? .primary : .accentColor)
  152. }
  153. .padding(.vertical, pad)
  154. .onTapGesture {
  155. displayPickerTarget.toggle()
  156. }
  157. if displayPickerTarget {
  158. HStack {
  159. VStack(alignment: .leading) {
  160. // Toggle for step iteration
  161. VStack {
  162. Text(formattedGlucose(glucose: Decimal(state.units == .mgdL ? smallMgdL : smallMmolL)))
  163. .tag(Int(state.units == .mgdL ? smallMgdL : smallMmolL))
  164. .foregroundColor(toggleBigStepOn ? .primary : .tabBar)
  165. ZStack {
  166. Group {
  167. Capsule()
  168. .frame(width: 22, height: 40)
  169. .foregroundColor(Color.loopGray)
  170. ZStack {
  171. Circle()
  172. .frame(width: 20, height: 22)
  173. Image(systemName: toggleBigStepOn ? "forward.circle.fill" : "play.circle.fill")
  174. .foregroundStyle(Color.white, Color.tabBar)
  175. }
  176. .shadow(color: .black.opacity(0.14), radius: 4, x: 0, y: 2)
  177. .offset(y: toggleBigStepOn ? 9 : -9)
  178. .padding(12)
  179. }
  180. }
  181. .onTapGesture {
  182. // Toggling between small and big step
  183. toggleBigStepOn.toggle()
  184. targetStep = toggleBigStepOn ? (state.units == .mgdL ? bigMgdL : bigMmolL) :
  185. (state.units == .mgdL ? smallMgdL : smallMmolL)
  186. }
  187. Text(formattedGlucose(glucose: Decimal(state.units == .mgdL ? bigMgdL : bigMmolL)))
  188. .tag(Int(state.units == .mgdL ? bigMgdL : bigMmolL))
  189. .foregroundColor(toggleBigStepOn ? .tabBar : .primary)
  190. }
  191. .padding(.top, 10)
  192. }
  193. .frame(maxWidth: .infinity)
  194. Spacer()
  195. // Picker on the right side
  196. Picker(
  197. selection: Binding(
  198. get: { Int(truncating: state.tempTargetTarget as NSNumber) },
  199. set: { state.tempTargetTarget = Decimal($0) }
  200. ), label: Text("")
  201. ) {
  202. ForEach(
  203. Array(stride(from: 80, through: 270, by: targetStep)),
  204. id: \.self
  205. ) { glucoseTarget in
  206. Text(formattedGlucose(glucose: Decimal(glucoseTarget)))
  207. .tag(Int(glucoseTarget))
  208. }
  209. }
  210. .pickerStyle(WheelPickerStyle())
  211. .frame(maxWidth: .infinity)
  212. .onChange(of: state.tempTargetTarget) { _ in
  213. state.percentage = Double(state.computeAdjustedPercentage() * 100)
  214. }
  215. }
  216. .frame(maxWidth: .infinity)
  217. }
  218. }
  219. DatePicker("Date", selection: $state.date)
  220. }
  221. if isSliderEnabled && state.tempTargetTarget != 0 {
  222. if state.tempTargetTarget > 100 {
  223. Section {
  224. VStack(alignment: .leading) {
  225. Text("Raised Sensitivity:")
  226. .font(.footnote)
  227. .fontWeight(.bold)
  228. Text("Insulin reduced to \(formattedPercentage(state.percentage))% of regular amount.")
  229. .font(.footnote)
  230. .lineLimit(1)
  231. }
  232. }.listRowBackground(Color.tabBar)
  233. Section {
  234. VStack {
  235. Toggle("Adjust Sensitivity", isOn: $state.didAdjustSens).padding(.top)
  236. HStack(alignment: .top) {
  237. Text(
  238. "Temp Target raises Sensitivity. Further adjust if desired!"
  239. )
  240. .font(.footnote)
  241. .foregroundColor(.secondary)
  242. .lineLimit(nil)
  243. Spacer()
  244. Button(
  245. action: {
  246. hintLabel = "Adjust Sensitivity for high Temp Target "
  247. selectedVerboseHint =
  248. "You have enabled High TempTarget Raises Sensitivity in Target Behaviour settings. Therefore current high Temp Target of \(state.tempTargetTarget) would raise your sensitivity, hence reduce Insulin dosing to \(formattedPercentage(state.percentage)) % of regular amount. This can be adjusted to another desired Insulin percentage!"
  249. shouldDisplayHint.toggle()
  250. },
  251. label: {
  252. HStack {
  253. Image(systemName: "questionmark.circle")
  254. }
  255. }
  256. ).buttonStyle(BorderlessButtonStyle())
  257. }.padding(.top)
  258. }.padding(.bottom)
  259. }.listRowBackground(Color.chart)
  260. } else if state.tempTargetTarget < 100 {
  261. Section {
  262. VStack(alignment: .leading) {
  263. Text("Lowered Sensitivity:")
  264. .font(.footnote)
  265. .fontWeight(.bold)
  266. Text("Insulin increased to \(formattedPercentage(state.percentage))% of regular amount.")
  267. .font(.footnote)
  268. .lineLimit(1)
  269. }
  270. }.listRowBackground(Color.tabBar)
  271. Section {
  272. VStack {
  273. Toggle("Adjust Insulin %", isOn: $state.didAdjustSens).padding(.top)
  274. HStack(alignment: .top) {
  275. Text(
  276. "Temp Target lowers Sensitivity. Further adjust if desired!"
  277. )
  278. .font(.footnote)
  279. .foregroundColor(.secondary)
  280. .lineLimit(nil)
  281. Spacer()
  282. Button(
  283. action: {
  284. hintLabel = "Adjust Sensitivity for low Temp Target "
  285. selectedVerboseHint =
  286. "You have enabled Low TempTarget Lowers Sensitivity in Target Behaviour settings and set autosens Max > 1. Therefore current low Temp Target of \(state.tempTargetTarget) would lower your sensitivity, hence increase Insulin dosing to \(formattedPercentage(state.percentage)) % of regular amount. This can be adjusted to another desired Insulin percentage!"
  287. shouldDisplayHint.toggle()
  288. },
  289. label: {
  290. HStack {
  291. Image(systemName: "questionmark.circle")
  292. }
  293. }
  294. ).buttonStyle(BorderlessButtonStyle())
  295. }.padding(.top)
  296. }.padding(.bottom)
  297. }.listRowBackground(Color.chart)
  298. }
  299. if state.didAdjustSens && state.tempTargetTarget != 100 {
  300. Section {
  301. VStack {
  302. Text("\(Int(state.percentage)) % Insulin")
  303. .foregroundColor(isUsingSlider ? .orange : Color.tabBar)
  304. .font(.largeTitle)
  305. Slider(
  306. value: $state.percentage,
  307. in: state.computeSliderLow() ... state.computeSliderHigh(),
  308. step: 5
  309. ) {} minimumValueLabel: {
  310. Text("\(state.computeSliderLow(), specifier: "%.0f")%")
  311. } maximumValueLabel: {
  312. Text("\(state.computeSliderHigh(), specifier: "%.0f")%")
  313. } onEditingChanged: { editing in
  314. isUsingSlider = editing
  315. state.halfBasalTarget = Decimal(state.computeHalfBasalTarget())
  316. }
  317. .disabled(!isSliderEnabled)
  318. Divider()
  319. HStack {
  320. Text(
  321. "Half Basal Exercise Target at: \(formattedGlucose(glucose: Decimal(state.computeHalfBasalTarget())))"
  322. )
  323. .lineLimit(1)
  324. .minimumScaleFactor(0.5)
  325. .foregroundColor(.secondary)
  326. Spacer()
  327. }
  328. }
  329. }.listRowBackground(Color.chart)
  330. }
  331. }
  332. }
  333. private func isTempTargetInvalid() -> (Bool, String?) {
  334. let noDurationSpecified = state.tempTargetDuration == 0
  335. let targetZero = state.tempTargetTarget < 80
  336. if noDurationSpecified {
  337. return (true, "Set a duration!")
  338. }
  339. if targetZero {
  340. return (
  341. true,
  342. "\(state.units == .mgdL ? "80 " : "4.4 ")" + state.units.rawValue + " needed as min. Glucose Target!"
  343. )
  344. }
  345. return (false, nil)
  346. }
  347. private var saveButton: some View {
  348. let (isInvalid, errorMessage) = isTempTargetInvalid()
  349. let noNameSpecified = state.tempTargetName == ""
  350. return Group {
  351. Section(
  352. header:
  353. HStack {
  354. Spacer()
  355. Text(errorMessage ?? "").textCase(nil)
  356. .foregroundColor(colorScheme == .dark ? .orange : .accentColor)
  357. Spacer()
  358. },
  359. content: {
  360. Button(action: {
  361. Task {
  362. if noNameSpecified { state.tempTargetName = "Custom Target" }
  363. didPressSave.toggle()
  364. state.isTempTargetEnabled.toggle()
  365. await state.saveCustomTempTarget()
  366. await state.resetTempTargetState()
  367. dismiss()
  368. }
  369. }, label: {
  370. Text("Enact Temp Target")
  371. })
  372. .disabled(isInvalid)
  373. .frame(maxWidth: .infinity, alignment: .center)
  374. .tint(.white)
  375. }
  376. ).listRowBackground(isInvalid ? Color(.systemGray4) : Color(.systemBlue))
  377. Section {
  378. Button(action: {
  379. Task {
  380. if noNameSpecified { state.tempTargetName = "Custom Target" }
  381. didPressSave.toggle()
  382. await state.saveTempTargetPreset()
  383. dismiss()
  384. }
  385. }, label: {
  386. Text("Save as Preset")
  387. })
  388. .disabled(isInvalid)
  389. .frame(maxWidth: .infinity, alignment: .center)
  390. .tint(.white)
  391. }
  392. .listRowBackground(
  393. isInvalid ? Color(.systemGray4) : Color.secondary
  394. )
  395. }
  396. }
  397. private func totalDurationInMinutes() -> Int {
  398. let durationTotal = (durationHours * 60) + durationMinutes
  399. return max(0, durationTotal)
  400. }
  401. private func formattedPercentage(_ value: Double) -> String {
  402. let percentageNumber = NSNumber(value: value)
  403. return formatter.string(from: percentageNumber) ?? "\(value)"
  404. }
  405. private func formattedGlucose(glucose: Decimal) -> String {
  406. let formattedValue: String
  407. if state.units == .mgdL {
  408. formattedValue = glucoseFormatter.string(from: glucose as NSDecimalNumber) ?? "\(glucose)"
  409. } else {
  410. formattedValue = glucose.formattedAsMmolL
  411. }
  412. return "\(formattedValue) \(state.units.rawValue)"
  413. }
  414. }
  415. func formatHrMin(_ durationInMinutes: Int) -> String {
  416. let hours = durationInMinutes / 60
  417. let minutes = durationInMinutes % 60
  418. switch (hours, minutes) {
  419. case let (0, m):
  420. return "\(m) min"
  421. case let (h, 0):
  422. return "\(h) hr"
  423. default:
  424. return "\(hours) hr \(minutes) min"
  425. }
  426. }