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 isSliderEnabled: 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. state.percentage = Double(state.computeAdjustedPercentage() * 100)
  110. }
  111. Text(state.units.rawValue).foregroundColor(.secondary)
  112. }
  113. HStack {
  114. Text("Duration")
  115. Spacer()
  116. TextFieldWithToolBar(text: $state.tempTargetDuration, placeholder: "0", numberFormatter: formatter)
  117. Text("minutes").foregroundColor(.secondary)
  118. }
  119. DatePicker("Date", selection: $state.date)
  120. }
  121. ).listRowBackground(Color.chart)
  122. if isSliderEnabled && state.tempTargetTarget != 0 {
  123. if state.tempTargetTarget > 100 {
  124. Section {
  125. VStack(alignment: .leading) {
  126. Text("Raised Sensitivity:")
  127. .font(.footnote)
  128. .fontWeight(.bold)
  129. Text("Insulin reduced to \(formattedPercentage(state.percentage))% of regular amount.")
  130. .font(.footnote)
  131. .lineLimit(1)
  132. }
  133. }.listRowBackground(Color.tabBar)
  134. Section {
  135. VStack {
  136. Toggle("Adjust Sensitivity", isOn: $state.didAdjustSens).padding(.top)
  137. HStack(alignment: .top) {
  138. Text(
  139. "Temp Target raises Sensitivity. Further adjust if desired!"
  140. )
  141. .font(.footnote)
  142. .foregroundColor(.secondary)
  143. .lineLimit(nil)
  144. Spacer()
  145. Button(
  146. action: {
  147. hintLabel = "Adjust Sensitivity for high Temp Target "
  148. selectedVerboseHint =
  149. "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!"
  150. shouldDisplayHint.toggle()
  151. },
  152. label: {
  153. HStack {
  154. Image(systemName: "questionmark.circle")
  155. }
  156. }
  157. ).buttonStyle(BorderlessButtonStyle())
  158. }.padding(.top)
  159. }.padding(.bottom)
  160. }.listRowBackground(Color.chart)
  161. } else if state.tempTargetTarget < 100 {
  162. Section {
  163. VStack(alignment: .leading) {
  164. Text("Lowered Sensitivity:")
  165. .font(.footnote)
  166. .fontWeight(.bold)
  167. Text("Insulin increased to \(formattedPercentage(state.percentage))% of regular amount.")
  168. .font(.footnote)
  169. .lineLimit(1)
  170. }
  171. }.listRowBackground(Color.tabBar)
  172. Section {
  173. VStack {
  174. Toggle("Adjust Insulin %", isOn: $state.didAdjustSens).padding(.top)
  175. HStack(alignment: .top) {
  176. Text(
  177. "Temp Target lowers Sensitivity. Further adjust if desired!"
  178. )
  179. .font(.footnote)
  180. .foregroundColor(.secondary)
  181. .lineLimit(nil)
  182. Spacer()
  183. Button(
  184. action: {
  185. hintLabel = "Adjust Sensitivity for low Temp Target "
  186. selectedVerboseHint =
  187. "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!"
  188. shouldDisplayHint.toggle()
  189. },
  190. label: {
  191. HStack {
  192. Image(systemName: "questionmark.circle")
  193. }
  194. }
  195. ).buttonStyle(BorderlessButtonStyle())
  196. }.padding(.top)
  197. }.padding(.bottom)
  198. }.listRowBackground(Color.chart)
  199. }
  200. if state.didAdjustSens && state.tempTargetTarget != 100 {
  201. Section {
  202. VStack {
  203. Text("\(Int(state.percentage)) % Insulin")
  204. .foregroundColor(isUsingSlider ? .orange : Color.tabBar)
  205. .font(.largeTitle)
  206. Slider(
  207. value: $state.percentage,
  208. in: state.computeSliderLow() ... state.computeSliderHigh(),
  209. step: 5
  210. ) {} minimumValueLabel: {
  211. Text("\(state.computeSliderLow(), specifier: "%.0f")%")
  212. } maximumValueLabel: {
  213. Text("\(state.computeSliderHigh(), specifier: "%.0f")%")
  214. } onEditingChanged: { editing in
  215. isUsingSlider = editing
  216. state.halfBasalTarget = Decimal(state.computeHalfBasalTarget())
  217. }
  218. .disabled(!isSliderEnabled)
  219. Divider()
  220. HStack {
  221. Text(
  222. state
  223. .units == .mgdL ?
  224. "Half Basal Exercise Target at: \(state.computeHalfBasalTarget().formatted(.number.precision(.fractionLength(0)))) mg/dl" :
  225. "Half Basal Exercise Target at: \(state.computeHalfBasalTarget().asMmolL.formatted(.number.grouping(.never).rounded().precision(.fractionLength(1)))) mmol/L"
  226. )
  227. .lineLimit(1)
  228. .minimumScaleFactor(0.5)
  229. .foregroundColor(.secondary)
  230. Spacer()
  231. }
  232. }
  233. }.listRowBackground(Color.chart)
  234. }
  235. }
  236. // 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.
  237. Section {
  238. Button(action: {
  239. showAlert.toggle()
  240. }, label: {
  241. Text("Enact Temp Target")
  242. })
  243. .disabled(state.tempTargetDuration == 0)
  244. .frame(maxWidth: .infinity, alignment: .center)
  245. .tint(.white)
  246. }.listRowBackground(state.tempTargetDuration == 0 ? Color(.systemGray4) : Color(.systemBlue))
  247. Section {
  248. Button(action: {
  249. Task {
  250. didPressSave.toggle()
  251. await state.saveTempTargetPreset()
  252. dismiss()
  253. }
  254. }, label: {
  255. Text("Save as Preset")
  256. })
  257. .disabled(state.tempTargetDuration == 0)
  258. .frame(maxWidth: .infinity, alignment: .center)
  259. .tint(.white)
  260. }.listRowBackground(state.tempTargetDuration == 0 ? Color(.systemGray4) : Color(.orange))
  261. }
  262. private func formattedPercentage(_ value: Double) -> String {
  263. let percentageNumber = NSNumber(value: value)
  264. return formatter.string(from: percentageNumber) ?? "\(value)"
  265. }
  266. private func setupAlertString() async {
  267. alertString =
  268. (
  269. state.tempTargetDuration > 0 ?
  270. (
  271. state
  272. .tempTargetDuration
  273. .formatted(.number.grouping(.never).rounded().precision(.fractionLength(0))) +
  274. " min."
  275. ) :
  276. NSLocalizedString(" infinite duration.", comment: "")
  277. ) +
  278. (
  279. state.tempTargetTarget == 0 ? "" :
  280. (" Target: " + state.tempTargetTarget.formatted() + " " + state.units.rawValue + ".")
  281. )
  282. +
  283. "\n\n"
  284. +
  285. NSLocalizedString(
  286. "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.",
  287. comment: ""
  288. )
  289. }
  290. }