AddTempTargetForm.swift 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  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 targetStep: Int = 5
  9. @State private var displayPickerTarget: Bool = false
  10. @State private var showAlert = false
  11. @State private var showPresetAlert = false
  12. @State private var alertString = ""
  13. @State private var isUsingSlider = false
  14. @State private var didPressSave =
  15. false // only used for fixing the Disclaimer showing up after pressing save (after the state was resetted), maybe refactor this...
  16. @State private var shouldDisplayHint = false
  17. @State var hintDetent = PresentationDetent.large
  18. @State var selectedVerboseHint: String?
  19. @State var hintLabel: String?
  20. var color: LinearGradient {
  21. colorScheme == .dark ? LinearGradient(
  22. gradient: Gradient(colors: [
  23. Color.bgDarkBlue,
  24. Color.bgDarkerDarkBlue
  25. ]),
  26. startPoint: .top,
  27. endPoint: .bottom
  28. )
  29. :
  30. LinearGradient(
  31. gradient: Gradient(colors: [Color.gray.opacity(0.1)]),
  32. startPoint: .top,
  33. endPoint: .bottom
  34. )
  35. }
  36. private var formatter: NumberFormatter {
  37. let formatter = NumberFormatter()
  38. formatter.numberStyle = .decimal
  39. formatter.maximumFractionDigits = 0
  40. return formatter
  41. }
  42. private var glucoseFormatter: NumberFormatter {
  43. let formatter = NumberFormatter()
  44. formatter.numberStyle = .decimal
  45. formatter.maximumFractionDigits = 0
  46. if state.units == .mmolL {
  47. formatter.maximumFractionDigits = 1
  48. }
  49. formatter.roundingMode = .halfUp
  50. return formatter
  51. }
  52. var isSliderEnabled: Bool {
  53. state.computeSliderHigh() > state.computeSliderLow()
  54. }
  55. var body: some View {
  56. NavigationView {
  57. Form {
  58. addTempTarget()
  59. saveButton
  60. }.scrollContentBackground(.hidden).background(color)
  61. .navigationTitle("Add Temp Target")
  62. .navigationBarTitleDisplayMode(.inline)
  63. .navigationBarItems(leading: Button("Close") {
  64. presentationMode.wrappedValue.dismiss()
  65. })
  66. .sheet(isPresented: $shouldDisplayHint) {
  67. SettingInputHintView(
  68. hintDetent: $hintDetent,
  69. shouldDisplayHint: $shouldDisplayHint,
  70. hintLabel: hintLabel ?? "",
  71. hintText: selectedVerboseHint ?? "",
  72. sheetTitle: "Help"
  73. )
  74. }
  75. }
  76. }
  77. @ViewBuilder private func addTempTarget() -> some View {
  78. let pad: CGFloat = 3
  79. VStack {
  80. HStack {
  81. Text("Name")
  82. Spacer()
  83. TextField("(Optional)", text: $state.overrideName).multilineTextAlignment(.trailing)
  84. }
  85. .padding(.vertical, pad)
  86. }
  87. Section(
  88. header: Text("Configure Temp Target"),
  89. content: {
  90. HStack {
  91. Text("Name")
  92. Spacer()
  93. TextField("Enter Name (optional)", text: $state.tempTargetName)
  94. .multilineTextAlignment(.trailing)
  95. }
  96. HStack {
  97. Text("Duration")
  98. Spacer()
  99. TextFieldWithToolBar(text: $state.tempTargetDuration, placeholder: "0", numberFormatter: formatter)
  100. Text("minutes").foregroundColor(.secondary)
  101. }
  102. VStack {
  103. HStack {
  104. Text("Target Glucose")
  105. Spacer()
  106. Text(formattedGlucose(glucose: state.tempTargetTarget))
  107. .foregroundColor(!displayPickerTarget ? .primary : .accentColor)
  108. }
  109. .padding(.vertical, pad)
  110. .onTapGesture {
  111. displayPickerTarget.toggle()
  112. }
  113. if displayPickerTarget {
  114. HStack {
  115. // Radio buttons and text on the left side
  116. let factor = state.units == .mgdL ? 1 : 2
  117. VStack(alignment: .leading) {
  118. // Radio buttons for step iteration
  119. ForEach([1, 5], id: \.self) { step in
  120. RadioButton(
  121. isSelected: targetStep == step * factor,
  122. label: "\(formattedGlucose(glucose: Decimal(step)))"
  123. ) {
  124. targetStep = step * factor
  125. roundTargetToStep()
  126. }
  127. .padding(.top, 10)
  128. }
  129. }
  130. .frame(maxWidth: .infinity)
  131. Spacer()
  132. // Picker on the right side
  133. Picker(
  134. selection: Binding(
  135. get: { Int(truncating: state.tempTargetTarget as NSNumber) },
  136. set: { state.tempTargetTarget = Decimal($0) }
  137. ), label: Text("")
  138. ) {
  139. ForEach(
  140. Array(stride(from: 80, through: 270, by: targetStep)),
  141. id: \.self
  142. ) { glucose in
  143. Text(formattedGlucose(glucose: Decimal(glucose)))
  144. .tag(glucose)
  145. }
  146. }
  147. .pickerStyle(WheelPickerStyle())
  148. .frame(maxWidth: .infinity)
  149. }
  150. .frame(maxWidth: .infinity)
  151. }
  152. DatePicker("Date", selection: $state.date)
  153. }
  154. }
  155. ).listRowBackground(Color.chart)
  156. if isSliderEnabled && state.tempTargetTarget != 0 {
  157. if state.tempTargetTarget > 100 {
  158. Section {
  159. VStack(alignment: .leading) {
  160. Text("Raised Sensitivity:")
  161. .font(.footnote)
  162. .fontWeight(.bold)
  163. Text("Insulin reduced to \(formattedPercentage(state.percentage))% of regular amount.")
  164. .font(.footnote)
  165. .lineLimit(1)
  166. }
  167. }.listRowBackground(Color.tabBar)
  168. Section {
  169. VStack {
  170. Toggle("Adjust Sensitivity", isOn: $state.didAdjustSens).padding(.top)
  171. HStack(alignment: .top) {
  172. Text(
  173. "Temp Target raises Sensitivity. Further adjust if desired!"
  174. )
  175. .font(.footnote)
  176. .foregroundColor(.secondary)
  177. .lineLimit(nil)
  178. Spacer()
  179. Button(
  180. action: {
  181. hintLabel = "Adjust Sensitivity for high Temp Target "
  182. selectedVerboseHint =
  183. "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!"
  184. shouldDisplayHint.toggle()
  185. },
  186. label: {
  187. HStack {
  188. Image(systemName: "questionmark.circle")
  189. }
  190. }
  191. ).buttonStyle(BorderlessButtonStyle())
  192. }.padding(.top)
  193. }.padding(.bottom)
  194. }.listRowBackground(Color.chart)
  195. } else if state.tempTargetTarget < 100 {
  196. Section {
  197. VStack(alignment: .leading) {
  198. Text("Lowered Sensitivity:")
  199. .font(.footnote)
  200. .fontWeight(.bold)
  201. Text("Insulin increased to \(formattedPercentage(state.percentage))% of regular amount.")
  202. .font(.footnote)
  203. .lineLimit(1)
  204. }
  205. }.listRowBackground(Color.tabBar)
  206. Section {
  207. VStack {
  208. Toggle("Adjust Insulin %", isOn: $state.didAdjustSens).padding(.top)
  209. HStack(alignment: .top) {
  210. Text(
  211. "Temp Target lowers Sensitivity. Further adjust if desired!"
  212. )
  213. .font(.footnote)
  214. .foregroundColor(.secondary)
  215. .lineLimit(nil)
  216. Spacer()
  217. Button(
  218. action: {
  219. hintLabel = "Adjust Sensitivity for low Temp Target "
  220. selectedVerboseHint =
  221. "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!"
  222. shouldDisplayHint.toggle()
  223. },
  224. label: {
  225. HStack {
  226. Image(systemName: "questionmark.circle")
  227. }
  228. }
  229. ).buttonStyle(BorderlessButtonStyle())
  230. }.padding(.top)
  231. }.padding(.bottom)
  232. }.listRowBackground(Color.chart)
  233. }
  234. if state.didAdjustSens && state.tempTargetTarget != 100 {
  235. Section {
  236. VStack {
  237. Text("\(Int(state.percentage)) % Insulin")
  238. .foregroundColor(isUsingSlider ? .orange : Color.tabBar)
  239. .font(.largeTitle)
  240. Slider(
  241. value: $state.percentage,
  242. in: state.computeSliderLow() ... state.computeSliderHigh(),
  243. step: 5
  244. ) {} minimumValueLabel: {
  245. Text("\(state.computeSliderLow(), specifier: "%.0f")%")
  246. } maximumValueLabel: {
  247. Text("\(state.computeSliderHigh(), specifier: "%.0f")%")
  248. } onEditingChanged: { editing in
  249. isUsingSlider = editing
  250. state.halfBasalTarget = Decimal(state.computeHalfBasalTarget())
  251. }
  252. .disabled(!isSliderEnabled)
  253. Divider()
  254. HStack {
  255. Text(
  256. state
  257. .units == .mgdL ?
  258. "Half Basal Exercise Target at: \(state.computeHalfBasalTarget().formatted(.number.precision(.fractionLength(0)))) mg/dl" :
  259. "Half Basal Exercise Target at: \(state.computeHalfBasalTarget().asMmolL.formatted(.number.grouping(.never).rounded().precision(.fractionLength(1)))) mmol/L"
  260. )
  261. .lineLimit(1)
  262. .minimumScaleFactor(0.5)
  263. .foregroundColor(.secondary)
  264. Spacer()
  265. }
  266. }
  267. }.listRowBackground(Color.chart)
  268. }
  269. }
  270. // 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.
  271. // Section {
  272. // Button(action: {
  273. // showAlert.toggle()
  274. // }, label: {
  275. // Text("Enact Temp Target")
  276. //
  277. // })
  278. // .disabled(state.tempTargetDuration == 0)
  279. // .frame(maxWidth: .infinity, alignment: .center)
  280. // .tint(.white)
  281. // }.listRowBackground(state.tempTargetDuration == 0 ? Color(.systemGray4) : Color(.systemBlue))
  282. //
  283. // Section {
  284. // Button(action: {
  285. // Task {
  286. // didPressSave.toggle()
  287. // await state.saveTempTargetPreset()
  288. // dismiss()
  289. // }
  290. // }, label: {
  291. // Text("Save as Preset")
  292. //
  293. // })
  294. // .disabled(state.tempTargetDuration == 0)
  295. // .frame(maxWidth: .infinity, alignment: .center)
  296. // .tint(.white)
  297. // }.listRowBackground(state.tempTargetDuration == 0 ? Color(.systemGray4) : Color(.orange))
  298. }
  299. private func isTempTargetInvalid() -> (Bool, String?) {
  300. let noDurationSpecified = state.tempTargetDuration == 0
  301. let targetZero = state.tempTargetTarget < 80
  302. if noDurationSpecified {
  303. return (true, "Set a duration!")
  304. }
  305. if targetZero {
  306. return (
  307. true,
  308. "\(state.units == .mgdL ? "80 " : "4.4 ")" + state.units.rawValue + " needed as min. Glucose Target!"
  309. )
  310. }
  311. return (false, nil)
  312. }
  313. private var saveButton: some View {
  314. let (isInvalid, errorMessage) = isTempTargetInvalid()
  315. let noNameSpecified = state.tempTargetName == ""
  316. return Group {
  317. Section(
  318. header:
  319. HStack {
  320. Spacer()
  321. Text(errorMessage ?? "").textCase(nil)
  322. .foregroundColor(colorScheme == .dark ? .orange : .accentColor)
  323. Spacer()
  324. },
  325. content: {
  326. Button(action: {
  327. Task {
  328. if noNameSpecified { state.tempTargetName = "Custom Target" }
  329. didPressSave.toggle()
  330. state.isTempTargetEnabled.toggle()
  331. await state.saveCustomTempTarget()
  332. await state.resetTempTargetState()
  333. dismiss()
  334. }
  335. }, label: {
  336. Text("Enact Temp Target")
  337. })
  338. .disabled(isInvalid)
  339. .frame(maxWidth: .infinity, alignment: .center)
  340. .tint(.white)
  341. }
  342. ).listRowBackground(isInvalid ? Color(.systemGray4) : Color(.systemBlue))
  343. Section {
  344. Button(action: {
  345. Task {
  346. if noNameSpecified { state.tempTargetName = "Custom Target" }
  347. didPressSave.toggle()
  348. await state.saveTempTargetPreset()
  349. dismiss()
  350. }
  351. }, label: {
  352. Text("Save as Preset")
  353. })
  354. .disabled(isInvalid)
  355. .frame(maxWidth: .infinity, alignment: .center)
  356. .tint(.white)
  357. }
  358. .listRowBackground(
  359. isInvalid ? Color(.systemGray4) : Color.secondary
  360. )
  361. }
  362. }
  363. private func formattedPercentage(_ value: Double) -> String {
  364. let percentageNumber = NSNumber(value: value)
  365. return formatter.string(from: percentageNumber) ?? "\(value)"
  366. }
  367. private func formattedGlucose(glucose: Decimal) -> String {
  368. let formattedValue: String
  369. if state.units == .mgdL {
  370. formattedValue = glucoseFormatter.string(from: glucose as NSDecimalNumber) ?? "\(glucose)"
  371. } else {
  372. formattedValue = glucose.formattedAsMmolL
  373. }
  374. return "\(formattedValue) \(state.units.rawValue)"
  375. }
  376. private func roundTargetToStep() {
  377. // Check if tempTargetTarget is not divisible by the selected step
  378. if let tempTarget = state.tempTargetTarget as? Double,
  379. tempTarget.truncatingRemainder(dividingBy: Double(targetStep)) != 0
  380. {
  381. let roundedValue: Double
  382. if state.tempTargetTarget > 100 {
  383. // Round down to the nearest valid step away from 100
  384. let stepCount = (Double(state.tempTargetTarget) - 100) / Double(targetStep)
  385. roundedValue = 100 + floor(stepCount) * Double(targetStep)
  386. } else {
  387. // Round up to the nearest valid step away from 100
  388. let stepCount = (100 - Double(state.tempTargetTarget)) / Double(targetStep)
  389. roundedValue = 100 - floor(stepCount) * Double(targetStep)
  390. }
  391. // Ensure the value stays higher than 79
  392. state.tempTargetTarget = Decimal(max(80, roundedValue))
  393. }
  394. }
  395. }
  396. struct RadioButton: View {
  397. var isSelected: Bool
  398. var label: String
  399. var action: () -> Void
  400. var body: some View {
  401. Button(action: {
  402. action()
  403. }) {
  404. HStack {
  405. Image(systemName: isSelected ? "largecircle.fill.circle" : "circle")
  406. Text(label) // Add label inside the button to make it tappable
  407. }
  408. }
  409. .buttonStyle(PlainButtonStyle())
  410. }
  411. }