AddTempTargetForm.swift 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  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 didPressSave =
  13. false // only used for fixing the Disclaimer showing up after pressing save (after the state was resetted), maybe refactor this...
  14. @State private var shouldDisplayHint = false
  15. @State var hintDetent = PresentationDetent.large
  16. @State var selectedVerboseHint: String?
  17. @State var hintLabel: String?
  18. var color: LinearGradient {
  19. colorScheme == .dark ? LinearGradient(
  20. gradient: Gradient(colors: [
  21. Color.bgDarkBlue,
  22. Color.bgDarkerDarkBlue
  23. ]),
  24. startPoint: .top,
  25. endPoint: .bottom
  26. )
  27. :
  28. LinearGradient(
  29. gradient: Gradient(colors: [Color.gray.opacity(0.1)]),
  30. startPoint: .top,
  31. endPoint: .bottom
  32. )
  33. }
  34. private var formatter: NumberFormatter {
  35. let formatter = NumberFormatter()
  36. formatter.numberStyle = .decimal
  37. formatter.maximumFractionDigits = 0
  38. return formatter
  39. }
  40. private var glucoseFormatter: NumberFormatter {
  41. let formatter = NumberFormatter()
  42. formatter.numberStyle = .decimal
  43. formatter.maximumFractionDigits = 0
  44. if state.units == .mmolL {
  45. formatter.maximumFractionDigits = 1
  46. }
  47. formatter.roundingMode = .halfUp
  48. return formatter
  49. }
  50. var sliderEnabled: Bool {
  51. state.computeSliderHigh() > state.computeSliderLow()
  52. }
  53. var body: some View {
  54. NavigationView {
  55. Form {
  56. addTempTarget()
  57. }.scrollContentBackground(.hidden).background(color)
  58. .navigationTitle("Add Temp Target")
  59. .navigationBarTitleDisplayMode(.inline)
  60. .navigationBarItems(leading: Button("Close") {
  61. presentationMode.wrappedValue.dismiss()
  62. })
  63. .alert(
  64. "Start Temp Target",
  65. isPresented: $showAlert,
  66. actions: {
  67. Button("Cancel", role: .cancel) { state.isTempTargetEnabled = false }
  68. Button("Start Temp Target", role: .destructive) {
  69. Task {
  70. didPressSave.toggle()
  71. await setupAlertString()
  72. state.isTempTargetEnabled.toggle()
  73. await state.saveCustomTempTarget()
  74. await state.resetTempTargetState()
  75. dismiss()
  76. }
  77. }
  78. },
  79. message: {
  80. Text(alertString)
  81. }
  82. )
  83. .sheet(isPresented: $shouldDisplayHint) {
  84. SettingInputHintView(
  85. hintDetent: $hintDetent,
  86. shouldDisplayHint: $shouldDisplayHint,
  87. hintLabel: hintLabel ?? "",
  88. hintText: selectedVerboseHint ?? "",
  89. sheetTitle: "Help"
  90. )
  91. }
  92. }
  93. }
  94. @ViewBuilder private func addTempTarget() -> some View {
  95. Section(
  96. header: Text("Configure Temp Target"),
  97. content: {
  98. HStack {
  99. Text("Name")
  100. Spacer()
  101. TextField("Enter Name (optional)", text: $state.tempTargetName)
  102. .multilineTextAlignment(.trailing)
  103. }
  104. HStack {
  105. Text("Target")
  106. Spacer()
  107. TextFieldWithToolBar(text: $state.tempTargetTarget, placeholder: "0", numberFormatter: glucoseFormatter)
  108. .onChange(of: state.tempTargetTarget) { _ in
  109. // Recalculate the percentage when tempTargetTarget changes
  110. state.percentage = Double(state.computeAdjustedPercentage() * 100)
  111. }
  112. Text(state.units.rawValue).foregroundColor(.secondary)
  113. }
  114. HStack {
  115. Text("Duration")
  116. Spacer()
  117. TextFieldWithToolBar(text: $state.tempTargetDuration, placeholder: "0", numberFormatter: formatter)
  118. Text("minutes").foregroundColor(.secondary)
  119. }
  120. DatePicker("Date", selection: $state.date)
  121. }
  122. ).listRowBackground(Color.chart)
  123. if sliderEnabled && state.tempTargetTarget != 0 {
  124. if state.tempTargetTarget > 100 {
  125. Section {
  126. VStack(alignment: .leading) {
  127. Text("Raised Sensitivity:")
  128. .font(.footnote)
  129. .fontWeight(.bold)
  130. Text("Insulin reduced to \(formattedPercentage(state.percentage))% of regular amount.")
  131. .font(.footnote)
  132. .lineLimit(1)
  133. }
  134. }.listRowBackground(Color.tabBar)
  135. Section {
  136. VStack {
  137. Toggle("Adjust Sensitivity", isOn: $state.didAdjustSens).padding(.top)
  138. HStack(alignment: .top) {
  139. Text(
  140. "Temp Target raises Sensitivity. Further adjust if desired!"
  141. )
  142. .font(.footnote)
  143. .foregroundColor(.secondary)
  144. .lineLimit(nil)
  145. Spacer()
  146. Button(
  147. action: {
  148. hintLabel = "Adjust Sensitivity for high Temp Target "
  149. selectedVerboseHint =
  150. "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!"
  151. shouldDisplayHint.toggle()
  152. },
  153. label: {
  154. HStack {
  155. Image(systemName: "questionmark.circle")
  156. }
  157. }
  158. ).buttonStyle(BorderlessButtonStyle())
  159. }.padding(.top)
  160. }.padding(.bottom)
  161. }.listRowBackground(Color.chart)
  162. } else if state.tempTargetTarget < 100 {
  163. Section {
  164. VStack(alignment: .leading) {
  165. Text("Lowered Sensitivity:")
  166. .font(.footnote)
  167. .fontWeight(.bold)
  168. Text("Insulin increased to \(formattedPercentage(state.percentage))% of regular amount.")
  169. .font(.footnote)
  170. .lineLimit(1)
  171. }
  172. }.listRowBackground(Color.tabBar)
  173. Section {
  174. VStack {
  175. Toggle("Adjust Insulin %", isOn: $state.didAdjustSens).padding(.top)
  176. HStack(alignment: .top) {
  177. Text(
  178. "Temp Target lowers Sensitivity. Further adjust if desired!"
  179. )
  180. .font(.footnote)
  181. .foregroundColor(.secondary)
  182. .lineLimit(nil)
  183. Spacer()
  184. Button(
  185. action: {
  186. hintLabel = "Adjust Sensitivity for low Temp Target "
  187. selectedVerboseHint =
  188. "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!"
  189. shouldDisplayHint.toggle()
  190. },
  191. label: {
  192. HStack {
  193. Image(systemName: "questionmark.circle")
  194. }
  195. }
  196. ).buttonStyle(BorderlessButtonStyle())
  197. }.padding(.top)
  198. }.padding(.bottom)
  199. }.listRowBackground(Color.chart)
  200. }
  201. if state.didAdjustSens && state.tempTargetTarget != 100 {
  202. Section {
  203. VStack {
  204. // Display the percentage in large text
  205. Text("\(Int(state.percentage)) % Insulin")
  206. .foregroundColor(isUsingSlider ? .orange : Color.tabBar)
  207. .font(.largeTitle)
  208. // Bind the slider to the percentage
  209. Slider(
  210. value: $state.percentage,
  211. in: state.computeSliderLow() ... state.computeSliderHigh(),
  212. step: 5
  213. ) {} minimumValueLabel: {
  214. Text("\(state.computeSliderLow(), specifier: "%.0f")%")
  215. } maximumValueLabel: {
  216. Text("\(state.computeSliderHigh(), specifier: "%.0f")%")
  217. } onEditingChanged: { editing in
  218. isUsingSlider = editing
  219. state.halfBasalTarget = Decimal(state.computeHalfBasalTarget())
  220. }
  221. .disabled(!sliderEnabled)
  222. Divider()
  223. Text(
  224. state
  225. .units == .mgdL ?
  226. "Half Basal Exercise Target at: \(state.computeHalfBasalTarget().formatted(.number.precision(.fractionLength(0)))) mg/dl" :
  227. "Half Basal Exercise Target at: \(state.computeHalfBasalTarget().asMmolL.formatted(.number.grouping(.never).rounded().precision(.fractionLength(1)))) mmol/L"
  228. )
  229. .foregroundColor(.secondary)
  230. .font(.caption).italic()
  231. }
  232. }.listRowBackground(Color.chart)
  233. }
  234. }
  235. // 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.
  236. Section {
  237. Button(action: {
  238. showAlert.toggle()
  239. }, label: {
  240. Text("Enact Temp Target")
  241. })
  242. .disabled(state.tempTargetDuration == 0)
  243. .frame(maxWidth: .infinity, alignment: .center)
  244. .tint(.white)
  245. }.listRowBackground(state.tempTargetDuration == 0 ? Color(.systemGray4) : Color(.systemBlue))
  246. Section {
  247. Button(action: {
  248. Task {
  249. didPressSave.toggle()
  250. await state.saveTempTargetPreset()
  251. dismiss()
  252. }
  253. }, label: {
  254. Text("Save as Preset")
  255. })
  256. .disabled(state.tempTargetDuration == 0)
  257. .frame(maxWidth: .infinity, alignment: .center)
  258. .tint(.white)
  259. }.listRowBackground(state.tempTargetDuration == 0 ? Color(.systemGray4) : Color(.orange))
  260. }
  261. private func formattedPercentage(_ value: Double) -> String {
  262. let percentageNumber = NSNumber(value: value)
  263. return formatter.string(from: percentageNumber) ?? "\(value)"
  264. }
  265. private func setupAlertString() async {
  266. alertString =
  267. (
  268. state.tempTargetDuration > 0 ?
  269. (
  270. state
  271. .tempTargetDuration
  272. .formatted(.number.grouping(.never).rounded().precision(.fractionLength(0))) +
  273. " min."
  274. ) :
  275. NSLocalizedString(" infinite duration.", comment: "")
  276. ) +
  277. (
  278. state.tempTargetTarget == 0 ? "" :
  279. (" Target: " + state.tempTargetTarget.formatted() + " " + state.units.rawValue + ".")
  280. )
  281. +
  282. "\n\n"
  283. +
  284. NSLocalizedString(
  285. "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.",
  286. comment: ""
  287. )
  288. }
  289. }