| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404 |
- import Charts
- import CoreData
- import SwiftUI
- import Swinject
- extension Bolus {
- struct DefaultBolusCalcRootView: BaseView {
- let resolver: Resolver
- let waitForSuggestion: Bool
- let fetch: Bool
- @StateObject var state = StateModel()
- @State private var isAddInsulinAlertPresented = false
- @State private var presentInfo = false
- @State private var displayError = false
- @State private var keepForNextWiew: Bool = false
- @Environment(\.colorScheme) var colorScheme
- @FetchRequest(
- entity: Meals.entity(),
- sortDescriptors: [NSSortDescriptor(key: "createdAt", ascending: false)]
- ) var meal: FetchedResults<Meals>
- private var formatter: NumberFormatter {
- let formatter = NumberFormatter()
- formatter.numberStyle = .decimal
- formatter.maximumFractionDigits = 2
- return formatter
- }
- private var fractionDigits: Int {
- if state.units == .mmolL {
- return 1
- } else { return 0 }
- }
- private var color: LinearGradient {
- colorScheme == .dark ? LinearGradient(
- gradient: Gradient(colors: [
- Color.bgDarkBlue,
- Color.bgDarkerDarkBlue
- ]),
- startPoint: .top,
- endPoint: .bottom
- )
- :
- LinearGradient(
- gradient: Gradient(colors: [Color.gray.opacity(0.1)]),
- startPoint: .top,
- endPoint: .bottom
- )
- }
- var body: some View {
- Form {
- Section {
- if state.waitForSuggestion {
- Text("Please wait")
- } else {
- predictionChart
- }
- } header: { Text("Predictions") }
- if fetch {
- Section {
- mealEntries
- } header: { Text("Meal Summary") }
- }
- Section {
- if state.waitForSuggestion {
- HStack {
- Text("Wait please").foregroundColor(.secondary)
- Spacer()
- ActivityIndicator(isAnimating: .constant(true), style: .medium) // fix iOS 15 bug
- }
- } else {
- HStack {
- Text("Insulin recommended")
- Image(systemName: "info.bubble")
- .symbolRenderingMode(.palette)
- .foregroundStyle(.primary, .blue)
- .onTapGesture {
- presentInfo.toggle()
- }
- Spacer()
- Text(
- formatter
- .string(from: state.insulinRecommended as NSNumber)! +
- NSLocalizedString(" U", comment: "Insulin unit")
- ).foregroundColor((state.error && state.insulinRecommended > 0) ? .red : .secondary)
- .onTapGesture {
- if state.error, state.insulinRecommended > 0 { displayError = true }
- else { state.amount = state.insulinRecommended }
- }
- }.contentShape(Rectangle())
- }
- HStack {
- Text("Amount")
- Spacer()
- DecimalTextField(
- "0",
- value: $state.amount,
- formatter: formatter,
- autofocus: true,
- cleanInput: true
- )
- Text(!(state.amount > state.maxBolus) ? "U" : "😵").foregroundColor(.secondary)
- }
- } header: { Text("Bolus") }
- if state.amount > 0 {
- Section {
- Button {
- keepForNextWiew = true
- state.add()
- }
- label: { Text(!(state.amount > state.maxBolus) ? "Enact bolus" : "Max Bolus exceeded!") }
- .frame(maxWidth: .infinity, alignment: .center)
- .disabled(disabled)
- .listRowBackground(!disabled ? Color(.systemBlue) : Color(.systemGray4))
- .tint(.white)
- }
- }
- if state.amount <= 0 {
- Section {
- Button {
- keepForNextWiew = true
- state.showModal(for: nil)
- }
- label: { Text("Continue without bolus") }.frame(maxWidth: .infinity, alignment: .center)
- }
- }
- }.scrollContentBackground(.hidden).background(color)
- .alert(isPresented: $displayError) {
- Alert(
- title: Text("Warning!"),
- message: Text("\n" + alertString() + "\n"),
- primaryButton: .destructive(
- Text("Add"),
- action: {
- state.amount = state.insulinRecommended
- displayError = false
- }
- ),
- secondaryButton: .cancel()
- )
- }.onAppear {
- configureView {
- state.waitForSuggestionInitial = waitForSuggestion
- state.waitForSuggestion = waitForSuggestion
- }
- }
- .onDisappear {
- if fetch, hasFatOrProtein, !keepForNextWiew, !state.useCalc {
- state.delete(deleteTwice: true, meal: meal)
- } else if fetch, !keepForNextWiew, !state.useCalc {
- state.delete(deleteTwice: false, meal: meal)
- }
- }
- .navigationTitle("Enact Bolus")
- .navigationBarTitleDisplayMode(.inline)
- .toolbar {
- ToolbarItem(placement: .topBarLeading) {
- if !fetch {
- Button("Close") {
- state.hideModal()
- }
- } else {
- Button {
- keepForNextWiew = true
- state.backToCarbsView(complexEntry: true, meal, override: false)
- } label: {
- HStack {
- Image(systemName: "chevron.backward")
- Text("Meal")
- }
- }
- }
- }
- }
- .popup(isPresented: presentInfo, alignment: .center, direction: .bottom) {
- bolusInfo
- }
- }
- var disabled: Bool {
- state.amount <= 0 || state.amount > state.maxBolus
- }
- var predictionChart: some View {
- ZStack {
- PredictionView(
- predictions: $state.predictions, units: $state.units, eventualBG: $state.evBG, target: $state.target,
- displayPredictions: $state.displayPredictions
- )
- }
- }
- var changed: Bool {
- ((meal.first?.carbs ?? 0) > 0) || ((meal.first?.fat ?? 0) > 0) || ((meal.first?.protein ?? 0) > 0)
- }
- var hasFatOrProtein: Bool {
- ((meal.first?.fat ?? 0) > 0) || ((meal.first?.protein ?? 0) > 0)
- }
- var mealEntries: some View {
- VStack {
- if let carbs = meal.first?.carbs, carbs > 0 {
- HStack {
- Text("Carbs")
- Spacer()
- Text(carbs.formatted())
- Text("g")
- }.foregroundColor(.secondary)
- }
- if let fat = meal.first?.fat, fat > 0 {
- HStack {
- Text("Fat")
- Spacer()
- Text(fat.formatted())
- Text("g")
- }.foregroundColor(.secondary)
- }
- if let protein = meal.first?.protein, protein > 0 {
- HStack {
- Text("Protein")
- Spacer()
- Text(protein.formatted())
- Text("g")
- }.foregroundColor(.secondary)
- }
- if let note = meal.first?.note, note != "" {
- HStack {
- Text("Note")
- Spacer()
- Text(note)
- }.foregroundColor(.secondary)
- }
- }
- }
- var bolusInfo: some View {
- VStack {
- // Variables
- VStack(spacing: 3) {
- HStack {
- Text("Eventual Glucose").foregroundColor(.secondary)
- let evg = state.units == .mmolL ? Decimal(state.evBG).asMmolL : Decimal(state.evBG)
- Text(evg.formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits))))
- Text(state.units.rawValue).foregroundColor(.secondary)
- }
- HStack {
- Text("Target Glucose").foregroundColor(.secondary)
- let target = state.units == .mmolL ? state.target.asMmolL : state.target
- Text(target.formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits))))
- Text(state.units.rawValue).foregroundColor(.secondary)
- }
- HStack {
- Text("ISF").foregroundColor(.secondary)
- let isf = state.isf
- Text(isf.formatted())
- Text(state.units.rawValue + NSLocalizedString("/U", comment: "/Insulin unit"))
- .foregroundColor(.secondary)
- }
- HStack {
- Text("ISF:")
- Text("Insulin Sensitivity")
- }.foregroundColor(.secondary).italic()
- if state.percentage != 100 {
- HStack {
- Text("Percentage setting").foregroundColor(.secondary)
- let percentage = state.percentage
- Text(percentage.formatted())
- Text("%").foregroundColor(.secondary)
- }
- }
- HStack {
- Text("Formula:")
- Text("(Eventual Glucose - Target) / ISF")
- }.foregroundColor(.secondary).italic().padding(.top, 5)
- }
- .font(.footnote)
- .padding(.top, 10)
- Divider()
- // Formula
- VStack(spacing: 5) {
- let unit = NSLocalizedString(
- " U",
- comment: "Unit in number of units delivered (keep the space character!)"
- )
- let color: Color = (state.percentage != 100 && state.insulin > 0) ? .secondary : .blue
- let fontWeight: Font.Weight = (state.percentage != 100 && state.insulin > 0) ? .regular : .bold
- HStack {
- Text(NSLocalizedString("Insulin recommended", comment: "") + ":").font(.callout)
- Text(state.insulin.formatted() + unit).font(.callout).foregroundColor(color).fontWeight(fontWeight)
- }
- if state.percentage != 100, state.insulin > 0 {
- Divider()
- HStack { Text(state.percentage.formatted() + " % ->").font(.callout).foregroundColor(.secondary)
- Text(
- state.insulinRecommended.formatted() + unit
- ).font(.callout).foregroundColor(.blue).bold()
- }
- }
- }
- // Warning
- if state.error, state.insulinRecommended > 0 {
- VStack(spacing: 5) {
- Divider()
- Text("Warning!").font(.callout).bold().foregroundColor(.orange)
- Text(alertString()).font(.footnote)
- Divider()
- }.padding(.horizontal, 10)
- }
- // Footer
- if !(state.error && state.insulinRecommended > 0) {
- VStack {
- Text(
- "Carbs and previous insulin are included in the glucose prediction, but if the Eventual Glucose is lower than the Target Glucose, a bolus will not be recommended."
- ).font(.caption2).foregroundColor(.secondary)
- }.padding(20)
- }
- // Hide button
- VStack {
- Button { presentInfo = false }
- label: { Text("Hide") }.frame(maxWidth: .infinity, alignment: .center).font(.callout)
- .foregroundColor(.blue)
- }.padding(.bottom, 10)
- }
- .background(
- RoundedRectangle(cornerRadius: 8, style: .continuous)
- .fill(Color(colorScheme == .dark ? UIColor.systemGray4 : UIColor.systemGray4))
- )
- }
- // Localize the Oref0 error/warning strings. The default should never be returned
- private func alertString() -> String {
- switch state.errorString {
- case 1,
- 2:
- return NSLocalizedString(
- "Eventual Glucose > Target Glucose, but glucose is predicted to first drop down to ",
- comment: "Bolus pop-up / Alert string. Make translations concise!"
- ) + state.minGuardBG
- .formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits))) + " " + state.units
- .rawValue + ", " +
- NSLocalizedString(
- "which is below your Threshold (",
- comment: "Bolus pop-up / Alert string. Make translations concise!"
- ) + state
- .threshold.formatted() + " " + state.units.rawValue + ")"
- case 3:
- return NSLocalizedString(
- "Eventual Glucose > Target Glucose, but glucose is climbing slower than expected. Expected: ",
- comment: "Bolus pop-up / Alert string. Make translations concise!"
- ) +
- state.expectedDelta
- .formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits))) +
- NSLocalizedString(". Climbing: ", comment: "Bolus pop-up / Alert string. Make translatons concise!") + state
- .minDelta.formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits)))
- case 4:
- return NSLocalizedString(
- "Eventual Glucose > Target Glucose, but glucose is falling faster than expected. Expected: ",
- comment: "Bolus pop-up / Alert string. Make translations concise!"
- ) +
- state.expectedDelta
- .formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits))) +
- NSLocalizedString(". Falling: ", comment: "Bolus pop-up / Alert string. Make translations concise!") + state
- .minDelta.formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits)))
- case 5:
- return NSLocalizedString(
- "Eventual Glucose > Target Glucose, but glucose is changing faster than expected. Expected: ",
- comment: "Bolus pop-up / Alert string. Make translations concise!"
- ) +
- state.expectedDelta
- .formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits))) +
- NSLocalizedString(". Changing: ", comment: "Bolus pop-up / Alert string. Make translations concise!") + state
- .minDelta.formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits)))
- case 6:
- return NSLocalizedString(
- "Eventual Glucose > Target Glucose, but glucose is predicted to first drop down to ",
- comment: "Bolus pop-up / Alert string. Make translations concise!"
- ) + state
- .minPredBG
- .formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits))) + " " + state
- .units
- .rawValue
- default:
- return "Ignore Warning..."
- }
- }
- }
- }
|