AddTempTargetForm.swift 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. import Foundation
  2. import SwiftUI
  3. struct AddTempTargetForm: View {
  4. @StateObject var state: OverrideConfig.StateModel
  5. @Environment(\.presentationMode) var presentationMode
  6. @Environment(\.colorScheme) var colorScheme
  7. @Environment(\.dismiss) var dismiss
  8. @State private var showAlert = false
  9. @State private var showPresetAlert = false
  10. @State private var alertString = ""
  11. @State private var isUsingSlider = false
  12. @State private var adjustSens = false
  13. @State private var didPressSave =
  14. false // only used for fixing the Disclaimer showing up after pressing save (after the state was resetted), maybe refactor this...
  15. @State private var shouldDisplayHint: Bool = false
  16. @State var hintDetent = PresentationDetent.large
  17. @State var selectedVerboseHint: String?
  18. @State var hintLabel: String?
  19. var color: LinearGradient {
  20. colorScheme == .dark ? LinearGradient(
  21. gradient: Gradient(colors: [
  22. Color.bgDarkBlue,
  23. Color.bgDarkerDarkBlue
  24. ]),
  25. startPoint: .top,
  26. endPoint: .bottom
  27. )
  28. :
  29. LinearGradient(
  30. gradient: Gradient(colors: [Color.gray.opacity(0.1)]),
  31. startPoint: .top,
  32. endPoint: .bottom
  33. )
  34. }
  35. private var formatter: NumberFormatter {
  36. let formatter = NumberFormatter()
  37. formatter.numberStyle = .decimal
  38. formatter.maximumFractionDigits = 0
  39. return formatter
  40. }
  41. private var glucoseFormatter: NumberFormatter {
  42. let formatter = NumberFormatter()
  43. formatter.numberStyle = .decimal
  44. formatter.maximumFractionDigits = 0
  45. if state.units == .mmolL {
  46. formatter.maximumFractionDigits = 1
  47. }
  48. formatter.roundingMode = .halfUp
  49. return formatter
  50. }
  51. var sliderEnabled: Bool {
  52. state.computeSliderHigh() > state.computeSliderLow()
  53. }
  54. var body: some View {
  55. NavigationView {
  56. Form {
  57. addTempTarget()
  58. }.scrollContentBackground(.hidden).background(color)
  59. .navigationTitle("Add Temp Target")
  60. .navigationBarTitleDisplayMode(.inline)
  61. .navigationBarItems(leading: Button("Close") {
  62. presentationMode.wrappedValue.dismiss()
  63. })
  64. .alert(
  65. "Start Temp Target",
  66. isPresented: $showAlert,
  67. actions: {
  68. Button("Cancel", role: .cancel) { state.isTempTargetEnabled = false }
  69. Button("Start Temp Target", role: .destructive) {
  70. Task {
  71. didPressSave.toggle()
  72. await setupAlertString()
  73. state.isTempTargetEnabled.toggle()
  74. await state.saveCustomTempTarget()
  75. await state.resetTempTargetState()
  76. dismiss()
  77. }
  78. }
  79. },
  80. message: {
  81. Text(alertString)
  82. }
  83. )
  84. .sheet(isPresented: $shouldDisplayHint) {
  85. SettingInputHintView(
  86. hintDetent: $hintDetent,
  87. shouldDisplayHint: $shouldDisplayHint,
  88. hintLabel: hintLabel ?? "",
  89. hintText: selectedVerboseHint ?? "",
  90. sheetTitle: "Help"
  91. )
  92. }
  93. }
  94. }
  95. @ViewBuilder private func addTempTarget() -> some View {
  96. Section(
  97. header: Text("Configure Temp Target"),
  98. content: {
  99. HStack {
  100. Text("Name")
  101. Spacer()
  102. TextField("Enter Name (optional)", text: $state.tempTargetName)
  103. .multilineTextAlignment(.trailing)
  104. }
  105. HStack {
  106. Text("Target")
  107. Spacer()
  108. TextFieldWithToolBar(text: $state.tempTargetTarget, placeholder: "0", numberFormatter: glucoseFormatter)
  109. .onChange(of: state.tempTargetTarget) { _ in
  110. // Recalculate the percentage when tempTargetTarget changes
  111. state.percentage = Double(state.computePercentage() * 100)
  112. }
  113. Text(state.units.rawValue).foregroundColor(.secondary)
  114. }
  115. HStack {
  116. Text("Duration")
  117. Spacer()
  118. TextFieldWithToolBar(text: $state.tempTargetDuration, placeholder: "0", numberFormatter: formatter)
  119. Text("minutes").foregroundColor(.secondary)
  120. }
  121. DatePicker("Date", selection: $state.date)
  122. }
  123. ).listRowBackground(Color.chart)
  124. if sliderEnabled && state.tempTargetTarget != 0 {
  125. if state.tempTargetTarget > 100 {
  126. Section {
  127. VStack {
  128. HStack(alignment: .top) {
  129. Text(
  130. "The current high Temp Target of \(state.tempTargetTarget) would raise your sensitivity to \(round(state.percentage)) % Insulin."
  131. )
  132. .font(.footnote)
  133. .foregroundColor(.secondary)
  134. .lineLimit(nil)
  135. Spacer()
  136. Button(
  137. action: {
  138. hintLabel = "Ajust Sensitivity for high Temp Target "
  139. selectedVerboseHint =
  140. "You have enabled High TempTarget Raises Sensitivity in your Target Behaviour setting. Therefore current high Temp Target of \(state.tempTargetTarget) would raise your sensitivity, therefore reduce Insulin dosing to \(round(state.percentage)) % of regular amount. This can be adjusted to another desired Insulin percentage!"
  141. shouldDisplayHint.toggle()
  142. },
  143. label: {
  144. HStack {
  145. Image(systemName: "questionmark.circle")
  146. }
  147. }
  148. ).buttonStyle(BorderlessButtonStyle())
  149. }.padding(.top)
  150. Toggle("Adjust sensitivity change for Temp Target?", isOn: $adjustSens).padding(.top)
  151. }.padding(.bottom)
  152. }.listRowBackground(Color.chart)
  153. } else if state.tempTargetTarget < 100 {
  154. Section {
  155. VStack {
  156. HStack(alignment: .top) {
  157. Text(
  158. "The current low Temp Target of \(state.tempTargetTarget) would lower your sensitivity to \(round(state.percentage)) % Insulin."
  159. )
  160. .font(.footnote)
  161. .foregroundColor(.secondary)
  162. .lineLimit(nil)
  163. Spacer()
  164. Button(
  165. action: {
  166. hintLabel = "Ajust Sensitivity for low Temp Target "
  167. selectedVerboseHint =
  168. "You have enabled Low TempTarget Lowers Sensitivity and autosens Max >1 in your Target Behaviour setting. Therefore current low Temp Target of \(state.tempTargetTarget) would lower your sensitivity, therefore increase Insulin dosing to \(round(state.percentage)) % of regular amount. This can be adjusted to another desired Insulin percentage!"
  169. shouldDisplayHint.toggle()
  170. },
  171. label: {
  172. HStack {
  173. Image(systemName: "questionmark.circle")
  174. }
  175. }
  176. ).buttonStyle(BorderlessButtonStyle())
  177. }.padding(.top)
  178. Toggle("Adjust sensitivity change for Temp Target?", isOn: $adjustSens).padding(.top)
  179. }.padding(.bottom)
  180. }.listRowBackground(Color.chart)
  181. }
  182. // TODO: if adjustSens goes to false the state.halfBasalTarget needs to revert to HBT in settings
  183. if adjustSens && state.tempTargetTarget != 100 {
  184. Section {
  185. VStack {
  186. // Display the percentage in large text
  187. Text("\(Int(state.percentage)) % Insulin")
  188. .foregroundColor(isUsingSlider ? .orange : Color.tabBar)
  189. .font(.largeTitle)
  190. // Bind the slider to the percentage
  191. Slider(
  192. value: $state.percentage,
  193. in: state.computeSliderLow() ... state.computeSliderHigh(),
  194. step: 5
  195. ) {} minimumValueLabel: {
  196. Text("\(state.computeSliderLow(), specifier: "%.0f")%")
  197. } maximumValueLabel: {
  198. Text("\(state.computeSliderHigh(), specifier: "%.0f")%")
  199. } onEditingChanged: { editing in
  200. isUsingSlider = editing
  201. state.halfBasalTarget = Decimal(state.computeHalfBasalTarget())
  202. }
  203. .disabled(!sliderEnabled)
  204. Divider()
  205. Text(
  206. state
  207. .units == .mgdL ?
  208. "Half Basal Exercise Target at: \(state.computeHalfBasalTarget().formatted(.number.precision(.fractionLength(0)))) mg/dl" :
  209. "Half Basal Exercise Target at: \(state.computeHalfBasalTarget().asMmolL.formatted(.number.grouping(.never).rounded().precision(.fractionLength(1)))) mmol/L"
  210. )
  211. .foregroundColor(.secondary)
  212. .font(.caption).italic()
  213. }
  214. }.listRowBackground(Color.chart)
  215. }
  216. }
  217. // TODO: with iOS 17 we can change the body content wrapper from FORM to LIST and apply the .listSpacing modifier to make this all nice and small.
  218. Section {
  219. Button(action: {
  220. showAlert.toggle()
  221. }, label: {
  222. Text("Enact Temp Target")
  223. })
  224. .disabled(state.tempTargetDuration == 0)
  225. .frame(maxWidth: .infinity, alignment: .center)
  226. .tint(.white)
  227. }.listRowBackground(state.tempTargetDuration == 0 ? Color(.systemGray4) : Color(.systemBlue))
  228. Section {
  229. Button(action: {
  230. Task {
  231. didPressSave.toggle()
  232. await state.saveTempTargetPreset()
  233. dismiss()
  234. }
  235. }, label: {
  236. Text("Save as Preset")
  237. })
  238. .disabled(state.tempTargetDuration == 0)
  239. .frame(maxWidth: .infinity, alignment: .center)
  240. .tint(.white)
  241. }.listRowBackground(state.tempTargetDuration == 0 ? Color(.systemGray4) : Color(.orange))
  242. }
  243. private func setupAlertString() async {
  244. alertString =
  245. (
  246. state.tempTargetDuration > 0 ?
  247. (
  248. state
  249. .tempTargetDuration
  250. .formatted(.number.grouping(.never).rounded().precision(.fractionLength(0))) +
  251. " min."
  252. ) :
  253. NSLocalizedString(" infinite duration.", comment: "")
  254. ) +
  255. (
  256. state.tempTargetTarget == 0 ? "" :
  257. (" Target: " + state.tempTargetTarget.formatted() + " " + state.units.rawValue + ".")
  258. )
  259. +
  260. "\n\n"
  261. +
  262. NSLocalizedString(
  263. "Starting this Temp Target will change your profiles and/or your Target Glucose used for looping during the entire selected duration. Tapping ”Start Temp Target” will start your new Temp Target or edit your current active Temp Target.",
  264. comment: ""
  265. )
  266. }
  267. }