| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063 |
- import Charts
- import CoreData
- import SwiftUI
- import Swinject
- extension Bolus {
- struct AlternativeBolusCalcRootView: BaseView {
- let resolver: Resolver
- let waitForSuggestion: Bool
- let fetch: Bool
- let editMode: Bool
- let override: Bool
- @StateObject var state: StateModel
- @State private var showInfo = false
- @State private var showAlert = false
- @State private var exceededMaxBolus = false
- @State private var keepForNextWiew: Bool = false
- @State private var calcButtonPressed: Bool = false
- @State private var autofocus: Bool = true
- @State private var calculatorDetent = PresentationDetent.medium
- @State var pushed = false
- @State var isPromptPresented = false
- @State var dish: String = ""
- @State var saved = false
- @State private var treatmentsViewMode: TreatmentsViewMode = .calcMode
- @FocusState private var isFocused: Bool
- @Environment(\.managedObjectContext) var moc
- private enum Config {
- static let dividerHeight: CGFloat = 2
- static let spacing: CGFloat = 3
- }
- private enum TreatmentsViewMode {
- case editMode
- case calcMode
- }
- @Environment(\.colorScheme) var colorScheme
- @FetchRequest(
- entity: Meals.entity(),
- sortDescriptors: [NSSortDescriptor(key: "createdAt", ascending: false)]
- ) var meal: FetchedResults<Meals>
- @FetchRequest(
- entity: Presets.entity(),
- sortDescriptors: [NSSortDescriptor(key: "dish", ascending: true)]
- ) var carbPresets: FetchedResults<Presets>
- private var formatter: NumberFormatter {
- let formatter = NumberFormatter()
- formatter.numberStyle = .decimal
- formatter.maximumFractionDigits = 2
- return formatter
- }
- private var mealFormatter: NumberFormatter {
- let formatter = NumberFormatter()
- formatter.numberStyle = .decimal
- formatter.maximumFractionDigits = 1
- return formatter
- }
- private var gluoseFormatter: NumberFormatter {
- let formatter = NumberFormatter()
- formatter.numberStyle = .decimal
- if state.units == .mmolL {
- formatter.maximumFractionDigits = 1
- } else { formatter.maximumFractionDigits = 0 }
- 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
- )
- }
- private var empty: Bool {
- state.carbs <= 0 && state.fat <= 0 && state.protein <= 0
- }
- private var presetPopover: some View {
- Form {
- Section {
- TextField("Name Of Dish", text: $dish)
- Button {
- saved = true
- if dish != "", saved {
- let preset = Presets(context: moc)
- preset.dish = dish
- preset.fat = state.fat as NSDecimalNumber
- preset.protein = state.protein as NSDecimalNumber
- preset.carbs = state.carbs as NSDecimalNumber
- try? moc.save()
- state.addNewPresetToWaitersNotepad(dish)
- saved = false
- isPromptPresented = false
- }
- }
- label: { Text("Save") }
- Button {
- dish = ""
- saved = false
- isPromptPresented = false }
- label: { Text("Cancel") }
- } header: { Text("Enter Meal Preset Name") }
- }
- }
- private var minusButton: some View {
- Button {
- if state.carbs != 0,
- (state.carbs - (((state.selection?.carbs ?? 0) as NSDecimalNumber) as Decimal) as Decimal) >= 0
- {
- state.carbs -= (((state.selection?.carbs ?? 0) as NSDecimalNumber) as Decimal)
- } else { state.carbs = 0 }
- if state.fat != 0,
- (state.fat - (((state.selection?.fat ?? 0) as NSDecimalNumber) as Decimal) as Decimal) >= 0
- {
- state.fat -= (((state.selection?.fat ?? 0) as NSDecimalNumber) as Decimal)
- } else { state.fat = 0 }
- if state.protein != 0,
- (state.protein - (((state.selection?.protein ?? 0) as NSDecimalNumber) as Decimal) as Decimal) >= 0
- {
- state.protein -= (((state.selection?.protein ?? 0) as NSDecimalNumber) as Decimal)
- } else { state.protein = 0 }
- state.removePresetFromNewMeal()
- if state.carbs == 0, state.fat == 0, state.protein == 0 { state.summation = [] }
- }
- label: { Image(systemName: "minus.circle.fill")
- .font(.system(size: 20))
- }
- .disabled(
- state
- .selection == nil ||
- (
- !state.summation
- .contains(state.selection?.dish ?? "") && (state.selection?.dish ?? "") != ""
- )
- )
- .buttonStyle(.borderless)
- .tint(.blue)
- }
- private var plusButton: some View {
- Button {
- state.carbs += ((state.selection?.carbs ?? 0) as NSDecimalNumber) as Decimal
- state.fat += ((state.selection?.fat ?? 0) as NSDecimalNumber) as Decimal
- state.protein += ((state.selection?.protein ?? 0) as NSDecimalNumber) as Decimal
- state.addPresetToNewMeal()
- }
- label: { Image(systemName: "plus.circle.fill")
- .font(.system(size: 20))
- }
- .disabled(state.selection == nil)
- .buttonStyle(.borderless)
- .tint(.blue)
- }
- private var mealPresets: some View {
- Section {
- HStack {
- if state.selection != nil {
- minusButton
- }
- Picker("Preset", selection: $state.selection) {
- Text("Saved Food").tag(nil as Presets?)
- ForEach(carbPresets, id: \.self) { (preset: Presets) in
- Text(preset.dish ?? "").tag(preset as Presets?)
- }
- }
- .labelsHidden()
- .frame(maxWidth: .infinity, alignment: .center)
- ._onBindingChange($state.selection) { _ in
- state.carbs += ((state.selection?.carbs ?? 0) as NSDecimalNumber) as Decimal
- state.fat += ((state.selection?.fat ?? 0) as NSDecimalNumber) as Decimal
- state.protein += ((state.selection?.protein ?? 0) as NSDecimalNumber) as Decimal
- state.addToSummation()
- }
- if state.selection != nil {
- plusButton
- }
- }
- HStack {
- Button("Delete Preset") {
- showAlert.toggle()
- }
- .disabled(state.selection == nil)
- .tint(.orange)
- .buttonStyle(.borderless)
- .alert(
- "Delete preset '\(state.selection?.dish ?? "")'?",
- isPresented: $showAlert,
- actions: {
- Button("No", role: .cancel) {}
- Button("Yes", role: .destructive) {
- state.deletePreset()
- state.carbs += ((state.selection?.carbs ?? 0) as NSDecimalNumber) as Decimal
- state.fat += ((state.selection?.fat ?? 0) as NSDecimalNumber) as Decimal
- state.protein += ((state.selection?.protein ?? 0) as NSDecimalNumber) as Decimal
- state.addPresetToNewMeal()
- }
- }
- )
- Spacer()
- Button {
- isPromptPresented = true
- }
- label: { Text("Save as Preset") }
- .buttonStyle(.borderless)
- .disabled(
- empty ||
- (
- (((state.selection?.carbs ?? 0) as NSDecimalNumber) as Decimal) == state
- .carbs && (((state.selection?.fat ?? 0) as NSDecimalNumber) as Decimal) == state
- .fat && (((state.selection?.protein ?? 0) as NSDecimalNumber) as Decimal) == state
- .protein
- )
- )
- }
- }
- }
- @ViewBuilder private func proteinAndFat() -> some View {
- HStack {
- Text("Fat").foregroundColor(.orange)
- Spacer()
- DecimalTextField(
- "0",
- value: $state.fat,
- formatter: formatter,
- autofocus: false,
- cleanInput: true
- )
- Text("g").foregroundColor(.secondary)
- }
- HStack {
- Text("Protein").foregroundColor(.red)
- Spacer()
- DecimalTextField(
- "0",
- value: $state.protein,
- formatter: formatter,
- autofocus: false,
- cleanInput: true
- ).foregroundColor(.loopRed)
- Text("g").foregroundColor(.secondary)
- }
- }
- var body: some View {
- Form {
- // MARK: ADDED
- Section {
- HStack {
- Text("Carbs").fontWeight(.semibold)
- Spacer()
- DecimalTextField(
- "0",
- value: $state.carbs,
- formatter: formatter,
- autofocus: true,
- cleanInput: true
- )
- Text("g").foregroundColor(.secondary)
- }
- if state.useFPUconversion {
- proteinAndFat()
- }
- // Summary when combining presets
- if state.waitersNotepad() != "" {
- HStack {
- Text("Total")
- let test = state.waitersNotepad().components(separatedBy: ", ").removeDublicates()
- HStack(spacing: 0) {
- ForEach(test, id: \.self) {
- Text($0).foregroundStyle(Color.randomGreen()).font(.footnote)
- Text($0 == test[test.count - 1] ? "" : ", ")
- }
- }.frame(maxWidth: .infinity, alignment: .trailing)
- }
- }
- // Time
- HStack {
- Text("Time").foregroundStyle(Color.secondary)
- Spacer()
- if !pushed {
- Button {
- pushed = true
- } label: { Text("Now") }.buttonStyle(.borderless).foregroundColor(.secondary).padding(.trailing, 5)
- } else {
- Button { state.date = state.date.addingTimeInterval(-15.minutes.timeInterval) }
- label: { Image(systemName: "minus.circle") }.tint(.blue).buttonStyle(.borderless)
- DatePicker(
- "Time",
- selection: $state.date,
- displayedComponents: [.hourAndMinute]
- ).controlSize(.mini)
- .labelsHidden()
- Button {
- state.date = state.date.addingTimeInterval(15.minutes.timeInterval)
- }
- label: { Image(systemName: "plus.circle") }.tint(.blue).buttonStyle(.borderless)
- }
- }
- // Optional meal note
- // HStack {
- // Image(systemName: "note.text.badge.plus").foregroundColor(.secondary)
- // TextField("", text: $state.note).multilineTextAlignment(.trailing)
- // if state.note != "", isFocused {
- // Button { isFocused = false } label: { Image(systemName: "keyboard.chevron.compact.down") }
- // .controlSize(.mini)
- // }
- // }
- // .focused($isFocused)
- .popover(isPresented: $isPromptPresented) {
- presetPopover
- }
- HStack {
- Spacer()
- Button {
- if treatmentsViewMode == .calcMode {
- state.addCarbs(override, fetch: editMode)
- treatmentsViewMode = .editMode
- calcButtonPressed.toggle()
- } else {
- state.backToCarbsView(complexEntry: true, meal, override: false)
- treatmentsViewMode = .calcMode
- }
- }
- label: {
- // Text((state.skipBolus && !override && !editMode) ? "Save" : "Calculate Bolus")
- // if carbs > 0 and it is the first entry then go into edit mode
- // conditionally change text to 'edit meal'
- // Text(!editMode ? "Calculate" : "Edit Meal")
- if treatmentsViewMode == .calcMode {
- Text("Calculate")
- } else {
- Text("Edit meal")
- }
- }.disabled(empty)
- Spacer()
- }
- } header: { Text("Carbs") }.listRowBackground(Color.chart)
- Section {
- mealPresets
- }.listRowBackground(Color.chart)
- // MARK: ADDING END
- Section {
- HStack {
- Button(action: {
- showInfo.toggle()
- }, label: {
- Image(systemName: "info.circle")
- Text("Calculations")
- })
- .foregroundStyle(.blue)
- .font(.footnote)
- .buttonStyle(PlainButtonStyle())
- .frame(maxWidth: .infinity, alignment: .leading)
- if state.fattyMeals {
- Spacer()
- Toggle(isOn: $state.useFattyMealCorrectionFactor) {
- Text("Fatty Meal")
- }
- .toggleStyle(CheckboxToggleStyle())
- .font(.footnote)
- .onChange(of: state.useFattyMealCorrectionFactor) { _ in
- state.insulinCalculated = state.calculateInsulin()
- if state.useFattyMealCorrectionFactor {
- state.useSuperBolus = false
- }
- }
- }
- if state.sweetMeals {
- Spacer()
- Toggle(isOn: $state.useSuperBolus) {
- Text("Super Bolus")
- }
- .toggleStyle(CheckboxToggleStyle())
- .font(.footnote)
- .onChange(of: state.useSuperBolus) { _ in
- state.insulinCalculated = state.calculateInsulin()
- if state.useSuperBolus {
- state.useFattyMealCorrectionFactor = false
- }
- }
- }
- }
- if state.waitForSuggestion {
- HStack {
- Text("Wait please").foregroundColor(.secondary)
- Spacer()
- ActivityIndicator(isAnimating: .constant(true), style: .medium) // fix iOS 15 bug
- }
- } else {
- HStack {
- Text("Recommended Bolus")
- Spacer()
- Text(
- formatter
- .string(from: Double(state.insulinCalculated) as NSNumber) ?? ""
- )
- Text(
- NSLocalizedString(" U", comment: "Unit in number of units delivered (keep the space character!)")
- ).foregroundColor(.secondary)
- }.contentShape(Rectangle())
- .onTapGesture { state.amount = state.insulinCalculated }
- }
- HStack {
- Text("Bolus")
- Spacer()
- DecimalTextField(
- "0",
- value: $state.amount,
- formatter: formatter,
- autofocus: false,
- cleanInput: true
- )
- Text(exceededMaxBolus ? "😵" : " U").foregroundColor(.secondary)
- }
- .onChange(of: state.amount) { newValue in
- if newValue > state.maxBolus {
- exceededMaxBolus = true
- } else {
- exceededMaxBolus = false
- }
- }
- } header: { Text("Bolus") }.listRowBackground(Color.chart)
- if state.amount > 0 {
- Section {
- Button {
- keepForNextWiew = true
- state.add()
- state.hideModal()
- /// check if user pressed the calc button or just wanted to enter carbs
- /// otherwise carb entry is doubled
- if !calcButtonPressed {
- state.addCarbs(override, fetch: editMode)
- }
- }
- label: { Text(exceededMaxBolus ? "Max Bolus exceeded!" : "Enact bolus") }
- .frame(maxWidth: .infinity, alignment: .center)
- .disabled(disabled)
- .listRowBackground(!disabled ? Color(.systemBlue) : Color(.systemGray4))
- .tint(.white)
- }
- }
- if state.amount <= 0 {
- Section {
- Button {
- keepForNextWiew = true
- state.hideModal()
- /// check if user pressed the calc button or just wanted to enter carbs
- /// otherwise carb entry is doubled
- if !calcButtonPressed {
- state.addCarbs(override, fetch: editMode)
- }
- }
- label: { Text("Continue without bolus") }.frame(maxWidth: .infinity, alignment: .center)
- }.listRowBackground(Color.chart)
- }
- }.scrollContentBackground(.hidden).background(color)
- .blur(radius: showInfo ? 3 : 0)
- .navigationTitle("Treatments")
- .navigationBarTitleDisplayMode(.large)
- .toolbar(content: {
- ToolbarItem(placement: .topBarLeading) {
- Button {
- state.hideModal()
- } label: {
- Text("Close")
- }
- }
- })
- .onAppear {
- configureView {
- state.waitForSuggestionInitial = waitForSuggestion
- state.waitForSuggestion = waitForSuggestion
- state.insulinCalculated = state.calculateInsulin()
- }
- }
- .onDisappear {
- if hasFatOrProtein, !keepForNextWiew, state.useCalc, treatmentsViewMode == .editMode {
- state.delete(deleteTwice: true, meal: meal)
- } else if !keepForNextWiew, state.useCalc, treatmentsViewMode == .editMode {
- state.delete(deleteTwice: false, meal: meal)
- }
- }
- .sheet(isPresented: $showInfo) {
- calculationsDetailView
- .presentationDetents(
- [fetch ? .large : .fraction(0.9), .large],
- selection: $calculatorDetent
- )
- }
- }
- var predictionChart: some View {
- ZStack {
- PredictionView(
- predictions: $state.predictions, units: $state.units, eventualBG: $state.evBG, target: $state.target,
- displayPredictions: $state.displayPredictions
- )
- }
- }
- var calcSettingsFirstRow: some View {
- GridRow {
- Group {
- Text("Carb Ratio:")
- .foregroundColor(.secondary)
- }.gridCellAnchor(.leading)
- Group {
- Text("ISF:")
- .foregroundColor(.secondary)
- }.gridCellAnchor(.leading)
- VStack {
- Text("Target:")
- .foregroundColor(.secondary)
- }.gridCellAnchor(.leading)
- }
- }
- var calcSettingsSecondRow: some View {
- GridRow {
- Text(state.carbRatio.formatted() + " " + NSLocalizedString("g/U", comment: " grams per Unit"))
- .gridCellAnchor(.leading)
- Text(
- state.isf.formatted() + " " + state.units
- .rawValue + NSLocalizedString("/U", comment: "/Insulin unit")
- ).gridCellAnchor(.leading)
- let target = state.units == .mmolL ? state.target.asMmolL : state.target
- Text(
- target
- .formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits))) +
- " " + state.units.rawValue
- ).gridCellAnchor(.leading)
- }
- }
- var calcGlucoseFirstRow: some View {
- GridRow(alignment: .center) {
- let currentBG = state.units == .mmolL ? state.currentBG.asMmolL : state.currentBG
- let target = state.units == .mmolL ? state.target.asMmolL : state.target
- Text("Glucose:").foregroundColor(.secondary)
- let firstRow = currentBG
- .formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits)))
- + " - " +
- target
- .formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits)))
- + " = " +
- state.targetDifference
- .formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits)))
- Text(firstRow).frame(minWidth: 0, alignment: .leading).foregroundColor(.secondary)
- .gridColumnAlignment(.leading)
- HStack {
- Text(
- self.insulinRounder(state.targetDifferenceInsulin).formatted()
- )
- Text("U").foregroundColor(.secondary)
- }.fontWeight(.bold)
- .gridColumnAlignment(.trailing)
- }
- }
- var calcGlucoseSecondRow: some View {
- GridRow(alignment: .center) {
- let currentBG = state.units == .mmolL ? state.currentBG.asMmolL : state.currentBG
- Text(
- currentBG
- .formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits))) +
- " " +
- state.units.rawValue
- )
- let secondRow = state.targetDifference
- .formatted(
- .number.grouping(.never).rounded()
- .precision(.fractionLength(fractionDigits))
- )
- + " / " +
- state.isf.formatted()
- + " ≈ " +
- self.insulinRounder(state.targetDifferenceInsulin).formatted()
- Text(secondRow).foregroundColor(.secondary).gridColumnAlignment(.leading)
- Color.clear.gridCellUnsizedAxes([.horizontal, .vertical])
- }
- }
- var calcGlucoseFormulaRow: some View {
- GridRow(alignment: .top) {
- Color.clear.gridCellUnsizedAxes([.horizontal, .vertical])
- Text("(Current - Target) / ISF").foregroundColor(.secondary.opacity(colorScheme == .dark ? 0.65 : 0.8))
- .gridColumnAlignment(.leading)
- .gridCellColumns(2)
- }
- .font(.caption)
- }
- var calcIOBRow: some View {
- GridRow(alignment: .center) {
- HStack {
- Text("IOB:").foregroundColor(.secondary)
- Text(
- self.insulinRounder(state.iob).formatted()
- )
- }
- Text("Subtract IOB").foregroundColor(.secondary.opacity(colorScheme == .dark ? 0.65 : 0.8)).font(.footnote)
- let iobFormatted = self.insulinRounder(state.iob).formatted()
- HStack {
- Text((state.iob != 0 ? "-" : "") + (state.iob >= 0 ? iobFormatted : "(" + iobFormatted + ")"))
- Text("U").foregroundColor(.secondary)
- }.fontWeight(.bold)
- .gridColumnAlignment(.trailing)
- }
- }
- var calcCOBRow: some View {
- GridRow(alignment: .center) {
- HStack {
- Text("COB:").foregroundColor(.secondary)
- Text(
- state.cob
- .formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits))) +
- NSLocalizedString(" g", comment: "grams")
- )
- }
- Text(
- state.cob
- .formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits)))
- + " / " +
- state.carbRatio.formatted()
- + " ≈ " +
- self.insulinRounder(state.wholeCobInsulin).formatted()
- )
- .foregroundColor(.secondary)
- .gridColumnAlignment(.leading)
- HStack {
- Text(
- self.insulinRounder(state.wholeCobInsulin).formatted()
- )
- Text("U").foregroundColor(.secondary)
- }.fontWeight(.bold)
- .gridColumnAlignment(.trailing)
- }
- }
- var calcCOBFormulaRow: some View {
- GridRow(alignment: .center) {
- Color.clear.gridCellUnsizedAxes([.horizontal, .vertical])
- Text("COB / Carb Ratio").foregroundColor(.secondary.opacity(colorScheme == .dark ? 0.65 : 0.8))
- .gridColumnAlignment(.leading)
- .gridCellColumns(2)
- }
- .font(.caption)
- }
- var calcDeltaRow: some View {
- GridRow(alignment: .center) {
- Text("Delta:").foregroundColor(.secondary)
- let deltaBG = state.units == .mmolL ? state.deltaBG.asMmolL : state.deltaBG
- Text(
- deltaBG
- .formatted(
- .number.grouping(.never).rounded()
- .precision(.fractionLength(fractionDigits))
- )
- + " / " +
- state.isf.formatted()
- + " ≈ " +
- self.insulinRounder(state.fifteenMinInsulin).formatted()
- )
- .foregroundColor(.secondary)
- .gridColumnAlignment(.leading)
- HStack {
- Text(
- self.insulinRounder(state.fifteenMinInsulin).formatted()
- )
- Text("U").foregroundColor(.secondary)
- }.fontWeight(.bold)
- .gridColumnAlignment(.trailing)
- }
- }
- var calcDeltaFormulaRow: some View {
- GridRow(alignment: .center) {
- let deltaBG = state.units == .mmolL ? state.deltaBG.asMmolL : state.deltaBG
- Text(
- deltaBG
- .formatted(
- .number.grouping(.never).rounded()
- .precision(.fractionLength(fractionDigits))
- ) + " " +
- state.units.rawValue
- )
- Text("15min Delta / ISF").font(.caption).foregroundColor(.secondary.opacity(colorScheme == .dark ? 0.65 : 0.8))
- .gridColumnAlignment(.leading)
- .gridCellColumns(2).padding(.top, 5)
- }
- }
- var calcFullBolusRow: some View {
- GridRow(alignment: .center) {
- Text("Full Bolus")
- .foregroundColor(.secondary)
- Color.clear.gridCellUnsizedAxes([.horizontal, .vertical])
- HStack {
- Text(self.insulinRounder(state.wholeCalc).formatted())
- .foregroundStyle(state.wholeCalc < 0 ? Color.loopRed : Color.primary)
- Text("U").foregroundColor(.secondary)
- }.gridColumnAlignment(.trailing)
- .fontWeight(.bold)
- }
- }
- var calcSuperBolusRow: some View {
- GridRow(alignment: .center) {
- Text("Super Bolus")
- .foregroundColor(.secondary)
- Text("Added to Result").foregroundColor(.secondary.opacity(colorScheme == .dark ? 0.65 : 0.8)).font(.footnote)
- HStack {
- Text("+" + self.insulinRounder(state.superBolusInsulin).formatted())
- .foregroundStyle(Color.loopRed)
- Text("U").foregroundColor(.secondary)
- }.gridColumnAlignment(.trailing)
- .fontWeight(.bold)
- }
- }
- var calcResultRow: some View {
- GridRow(alignment: .center) {
- Text("Result").fontWeight(.bold)
- HStack {
- Text(state.useSuperBolus ? "(" : "")
- .foregroundColor(.loopRed)
- + Text(state.fraction.formatted())
- + Text(" x ")
- .foregroundColor(.secondary)
- // if fatty meal is chosen
- + Text(state.useFattyMealCorrectionFactor ? state.fattyMealFactor.formatted() : "")
- .foregroundColor(.orange)
- + Text(state.useFattyMealCorrectionFactor ? " x " : "")
- .foregroundColor(.secondary)
- // endif fatty meal is chosen
- + Text(self.insulinRounder(state.wholeCalc).formatted())
- .foregroundColor(state.wholeCalc < 0 ? Color.loopRed : Color.primary)
- // if superbolus is chosen
- + Text(state.useSuperBolus ? ")" : "")
- .foregroundColor(.loopRed)
- + Text(state.useSuperBolus ? " + " : "")
- .foregroundColor(.secondary)
- + Text(state.useSuperBolus ? state.superBolusInsulin.formatted() : "")
- .foregroundColor(.loopRed)
- // endif superbolus is chosen
- + Text(" ≈ ")
- .foregroundColor(.secondary)
- }
- .gridColumnAlignment(.leading)
- HStack {
- Text(self.insulinRounder(state.insulinCalculated).formatted())
- .fontWeight(.bold)
- .foregroundColor(.blue)
- Text("U").foregroundColor(.secondary)
- }
- .gridColumnAlignment(.trailing)
- .fontWeight(.bold)
- }
- }
- var calcResultFormulaRow: some View {
- GridRow(alignment: .bottom) {
- if state.useFattyMealCorrectionFactor {
- Text("Factor x Fatty Meal Factor x Full Bolus")
- .foregroundColor(.secondary.opacity(colorScheme == .dark ? 0.65 : 0.8))
- .font(.caption)
- .gridCellAnchor(.center)
- .gridCellColumns(3)
- } else if state.useSuperBolus {
- Text("(Factor x Full Bolus) + Super Bolus")
- .foregroundColor(.secondary.opacity(colorScheme == .dark ? 0.65 : 0.8))
- .font(.caption)
- .gridCellAnchor(.center)
- .gridCellColumns(3)
- } else {
- Color.clear.gridCellUnsizedAxes([.horizontal, .vertical])
- Text("Factor x Full Bolus")
- .foregroundColor(.secondary.opacity(colorScheme == .dark ? 0.65 : 0.8))
- .font(.caption)
- .padding(.top, 5)
- .gridCellAnchor(.leading)
- .gridCellColumns(2)
- }
- }
- }
- var calculationsDetailView: some View {
- NavigationStack {
- ScrollView {
- Grid(alignment: .topLeading, horizontalSpacing: 3, verticalSpacing: 0) {
- GridRow {
- Text("Calculations").fontWeight(.bold).gridCellColumns(3).gridCellAnchor(.center).padding(.vertical)
- }
- calcSettingsFirstRow
- calcSettingsSecondRow
- DividerCustom()
- if fetch {
- // meal entries as grid rows
- GridRow {
- if let carbs = meal.first?.carbs, carbs > 0 {
- Text("Carbs").foregroundColor(.secondary)
- Color.clear.gridCellUnsizedAxes([.horizontal, .vertical])
- HStack {
- Text(carbs.formatted())
- Text("g").foregroundColor(.secondary)
- }.gridCellAnchor(.trailing)
- }
- }
- GridRow {
- if let fat = meal.first?.fat, fat > 0 {
- Text("Fat").foregroundColor(.secondary)
- Color.clear.gridCellUnsizedAxes([.horizontal, .vertical])
- HStack {
- Text(fat.formatted())
- Text("g").foregroundColor(.secondary)
- }.gridCellAnchor(.trailing)
- }
- }
- GridRow {
- if let protein = meal.first?.protein, protein > 0 {
- Text("Protein").foregroundColor(.secondary)
- Color.clear.gridCellUnsizedAxes([.horizontal, .vertical])
- HStack {
- Text(protein.formatted())
- Text("g").foregroundColor(.secondary)
- }.gridCellAnchor(.trailing)
- }
- }
- GridRow {
- if let note = meal.first?.note, note != "" {
- Text("Note").foregroundColor(.secondary)
- Text(note).foregroundColor(.secondary).gridCellColumns(2).gridCellAnchor(.trailing)
- }
- }
- DividerCustom()
- }
- GridRow {
- Text("Detailed Calculation Steps").gridCellColumns(3).gridCellAnchor(.center)
- .padding(.bottom, 10)
- }
- calcGlucoseFirstRow
- calcGlucoseSecondRow.padding(.bottom, 5)
- calcGlucoseFormulaRow
- DividerCustom()
- calcIOBRow
- DividerCustom()
- calcCOBRow.padding(.bottom, 5)
- calcCOBFormulaRow
- DividerCustom()
- calcDeltaRow
- calcDeltaFormulaRow
- DividerCustom()
- calcFullBolusRow
- if state.useSuperBolus {
- DividerCustom()
- calcSuperBolusRow
- }
- DividerDouble()
- calcResultRow
- calcResultFormulaRow
- }
- Spacer()
- Button { showInfo = false }
- label: { Text("Got it!").frame(maxWidth: .infinity, alignment: .center) }
- .buttonStyle(.bordered)
- .padding(.top)
- }
- .padding([.horizontal, .bottom])
- .font(.system(size: 15))
- }
- }
- private func insulinRounder(_ value: Decimal) -> Decimal {
- let toRound = NSDecimalNumber(decimal: value).doubleValue
- return Decimal(floor(100 * toRound) / 100)
- }
- private var disabled: Bool {
- state.amount <= 0 || state.amount > state.maxBolus
- }
- 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").foregroundColor(.secondary)
- Spacer()
- Text(carbs.formatted())
- Text("g").foregroundColor(.secondary)
- }
- }
- if let fat = meal.first?.fat, fat > 0 {
- HStack {
- Text("Fat").foregroundColor(.secondary)
- Spacer()
- Text(fat.formatted())
- Text("g").foregroundColor(.secondary)
- }
- }
- if let protein = meal.first?.protein, protein > 0 {
- HStack {
- Text("Protein").foregroundColor(.secondary)
- Spacer()
- Text(protein.formatted())
- Text("g").foregroundColor(.secondary)
- }
- }
- if let note = meal.first?.note, note != "" {
- HStack {
- Text("Note").foregroundColor(.secondary)
- Spacer()
- Text(note).foregroundColor(.secondary)
- }
- }
- }
- }
- }
- struct DividerDouble: View {
- var body: some View {
- VStack(spacing: 2) {
- Rectangle()
- .frame(height: 1)
- .foregroundColor(.gray.opacity(0.65))
- Rectangle()
- .frame(height: 1)
- .foregroundColor(.gray.opacity(0.65))
- }
- .frame(height: 4)
- .padding(.vertical)
- }
- }
- struct DividerCustom: View {
- var body: some View {
- Rectangle()
- .frame(height: 1)
- .foregroundColor(.gray.opacity(0.65))
- .padding(.vertical)
- }
- }
- }
|