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