AddTempTargetForm.swift 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  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. }
  210. .frame(maxWidth: .infinity)
  211. }
  212. DatePicker("Date", selection: $state.date)
  213. }
  214. }
  215. ).listRowBackground(Color.chart)
  216. if isSliderEnabled && state.tempTargetTarget != 0 {
  217. if state.tempTargetTarget > 100 {
  218. Section {
  219. VStack(alignment: .leading) {
  220. Text("Raised Sensitivity:")
  221. .font(.footnote)
  222. .fontWeight(.bold)
  223. Text("Insulin reduced to \(formattedPercentage(state.percentage))% of regular amount.")
  224. .font(.footnote)
  225. .lineLimit(1)
  226. }
  227. }.listRowBackground(Color.tabBar)
  228. Section {
  229. VStack {
  230. Toggle("Adjust Sensitivity", isOn: $state.didAdjustSens).padding(.top)
  231. HStack(alignment: .top) {
  232. Text(
  233. "Temp Target raises Sensitivity. Further adjust if desired!"
  234. )
  235. .font(.footnote)
  236. .foregroundColor(.secondary)
  237. .lineLimit(nil)
  238. Spacer()
  239. Button(
  240. action: {
  241. hintLabel = "Adjust Sensitivity for high Temp Target "
  242. selectedVerboseHint =
  243. "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!"
  244. shouldDisplayHint.toggle()
  245. },
  246. label: {
  247. HStack {
  248. Image(systemName: "questionmark.circle")
  249. }
  250. }
  251. ).buttonStyle(BorderlessButtonStyle())
  252. }.padding(.top)
  253. }.padding(.bottom)
  254. }.listRowBackground(Color.chart)
  255. } else if state.tempTargetTarget < 100 {
  256. Section {
  257. VStack(alignment: .leading) {
  258. Text("Lowered Sensitivity:")
  259. .font(.footnote)
  260. .fontWeight(.bold)
  261. Text("Insulin increased to \(formattedPercentage(state.percentage))% of regular amount.")
  262. .font(.footnote)
  263. .lineLimit(1)
  264. }
  265. }.listRowBackground(Color.tabBar)
  266. Section {
  267. VStack {
  268. Toggle("Adjust Insulin %", isOn: $state.didAdjustSens).padding(.top)
  269. HStack(alignment: .top) {
  270. Text(
  271. "Temp Target lowers Sensitivity. Further adjust if desired!"
  272. )
  273. .font(.footnote)
  274. .foregroundColor(.secondary)
  275. .lineLimit(nil)
  276. Spacer()
  277. Button(
  278. action: {
  279. hintLabel = "Adjust Sensitivity for low Temp Target "
  280. selectedVerboseHint =
  281. "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!"
  282. shouldDisplayHint.toggle()
  283. },
  284. label: {
  285. HStack {
  286. Image(systemName: "questionmark.circle")
  287. }
  288. }
  289. ).buttonStyle(BorderlessButtonStyle())
  290. }.padding(.top)
  291. }.padding(.bottom)
  292. }.listRowBackground(Color.chart)
  293. }
  294. if state.didAdjustSens && state.tempTargetTarget != 100 {
  295. Section {
  296. VStack {
  297. Text("\(Int(state.percentage)) % Insulin")
  298. .foregroundColor(isUsingSlider ? .orange : Color.tabBar)
  299. .font(.largeTitle)
  300. Slider(
  301. value: $state.percentage,
  302. in: state.computeSliderLow() ... state.computeSliderHigh(),
  303. step: 5
  304. ) {} minimumValueLabel: {
  305. Text("\(state.computeSliderLow(), specifier: "%.0f")%")
  306. } maximumValueLabel: {
  307. Text("\(state.computeSliderHigh(), specifier: "%.0f")%")
  308. } onEditingChanged: { editing in
  309. isUsingSlider = editing
  310. state.halfBasalTarget = Decimal(state.computeHalfBasalTarget())
  311. }
  312. .disabled(!isSliderEnabled)
  313. Divider()
  314. HStack {
  315. Text(
  316. "Half Basal Exercise Target at: \(formattedGlucose(glucose: Decimal(state.computeHalfBasalTarget())))"
  317. )
  318. .lineLimit(1)
  319. .minimumScaleFactor(0.5)
  320. .foregroundColor(.secondary)
  321. Spacer()
  322. }
  323. }
  324. }.listRowBackground(Color.chart)
  325. }
  326. }
  327. }
  328. private func isTempTargetInvalid() -> (Bool, String?) {
  329. let noDurationSpecified = state.tempTargetDuration == 0
  330. let targetZero = state.tempTargetTarget < 80
  331. if noDurationSpecified {
  332. return (true, "Set a duration!")
  333. }
  334. if targetZero {
  335. return (
  336. true,
  337. "\(state.units == .mgdL ? "80 " : "4.4 ")" + state.units.rawValue + " needed as min. Glucose Target!"
  338. )
  339. }
  340. return (false, nil)
  341. }
  342. private var saveButton: some View {
  343. let (isInvalid, errorMessage) = isTempTargetInvalid()
  344. let noNameSpecified = state.tempTargetName == ""
  345. return Group {
  346. Section(
  347. header:
  348. HStack {
  349. Spacer()
  350. Text(errorMessage ?? "").textCase(nil)
  351. .foregroundColor(colorScheme == .dark ? .orange : .accentColor)
  352. Spacer()
  353. },
  354. content: {
  355. Button(action: {
  356. Task {
  357. if noNameSpecified { state.tempTargetName = "Custom Target" }
  358. didPressSave.toggle()
  359. state.isTempTargetEnabled.toggle()
  360. await state.saveCustomTempTarget()
  361. await state.resetTempTargetState()
  362. dismiss()
  363. }
  364. }, label: {
  365. Text("Enact Temp Target")
  366. })
  367. .disabled(isInvalid)
  368. .frame(maxWidth: .infinity, alignment: .center)
  369. .tint(.white)
  370. }
  371. ).listRowBackground(isInvalid ? Color(.systemGray4) : Color(.systemBlue))
  372. Section {
  373. Button(action: {
  374. Task {
  375. if noNameSpecified { state.tempTargetName = "Custom Target" }
  376. didPressSave.toggle()
  377. await state.saveTempTargetPreset()
  378. dismiss()
  379. }
  380. }, label: {
  381. Text("Save as Preset")
  382. })
  383. .disabled(isInvalid)
  384. .frame(maxWidth: .infinity, alignment: .center)
  385. .tint(.white)
  386. }
  387. .listRowBackground(
  388. isInvalid ? Color(.systemGray4) : Color.secondary
  389. )
  390. }
  391. }
  392. private func totalDurationInMinutes() -> Int {
  393. let durationTotal = (durationHours * 60) + durationMinutes
  394. return max(0, durationTotal)
  395. }
  396. private func formattedPercentage(_ value: Double) -> String {
  397. let percentageNumber = NSNumber(value: value)
  398. return formatter.string(from: percentageNumber) ?? "\(value)"
  399. }
  400. private func formattedGlucose(glucose: Decimal) -> String {
  401. let formattedValue: String
  402. if state.units == .mgdL {
  403. formattedValue = glucoseFormatter.string(from: glucose as NSDecimalNumber) ?? "\(glucose)"
  404. } else {
  405. formattedValue = glucose.formattedAsMmolL
  406. }
  407. return "\(formattedValue) \(state.units.rawValue)"
  408. }
  409. }
  410. func formatHrMin(_ durationInMinutes: Int) -> String {
  411. let hours = durationInMinutes / 60
  412. let minutes = durationInMinutes % 60
  413. switch (hours, minutes) {
  414. case let (0, m):
  415. return "\(m) min"
  416. case let (h, 0):
  417. return "\(h) hr"
  418. default:
  419. return "\(hours) hr \(minutes) min"
  420. }
  421. }