| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248 |
- import CoreData
- import SpriteKit
- import SwiftDate
- import SwiftUI
- import Swinject
- struct TimePicker: Identifiable {
- var active: Bool
- let hours: Int16
- var id: String { hours.description }
- }
- extension Home {
- struct RootView: BaseView {
- let resolver: Resolver
- let safeAreaSize: CGFloat = 0.08
- @Environment(\.managedObjectContext) var moc
- @Environment(\.colorScheme) var colorScheme
- @Environment(AppState.self) var appState
- @State var state = StateModel()
- @State var settingsPath = NavigationPath()
- @State var isStatusPopupPresented = false
- @State var showCancelAlert = false
- @State var showCancelConfirmDialog = false
- @State var isConfirmStopOverrideShown = false
- @State var isConfirmStopOverridePresented = false
- @State var isConfirmStopTempTargetShown = false
- @State var isMenuPresented = false
- @State var showTreatments = false
- @State var selectedTab: Int = 0
- @State var showPumpSelection: Bool = false
- @State var showCGMSelection: Bool = false
- @State var notificationsDisabled = false
- @State var timeButtons: [TimePicker] = [
- TimePicker(active: false, hours: 4),
- TimePicker(active: false, hours: 6),
- TimePicker(active: false, hours: 12),
- TimePicker(active: false, hours: 24)
- ]
- @FetchRequest(fetchRequest: OverrideStored.fetch(
- NSPredicate.lastActiveOverride,
- ascending: false,
- fetchLimit: 1
- )) var latestOverride: FetchedResults<OverrideStored>
- @FetchRequest(fetchRequest: TempTargetStored.fetch(
- NSPredicate.lastActiveTempTarget,
- ascending: false,
- fetchLimit: 1
- )) var latestTempTarget: FetchedResults<TempTargetStored>
- var bolusProgressFormatter: NumberFormatter {
- let fractionDigits: Int = switch state.settingsManager.preferences.bolusIncrement {
- case 0.1: 1
- case 0.025: 3
- default: 2
- }
- let formatter = NumberFormatter()
- formatter.numberStyle = .decimal
- formatter.minimum = 0
- formatter.maximumFractionDigits = fractionDigits
- formatter.minimumFractionDigits = fractionDigits
- formatter.allowsFloats = true
- formatter.roundingIncrement = Double(state.settingsManager.preferences.bolusIncrement) as NSNumber
- return formatter
- }
- private var fetchedTargetFormatter: NumberFormatter {
- let formatter = NumberFormatter()
- formatter.numberStyle = .decimal
- if state.units == .mmolL {
- formatter.maximumFractionDigits = 1
- } else { formatter.maximumFractionDigits = 0 }
- return formatter
- }
- private var historySFSymbol: String {
- if #available(iOS 17.0, *) {
- return "book.pages"
- } else {
- return "book"
- }
- }
- @ViewBuilder func pumpTimezoneView(_ badgeImage: UIImage, _ badgeColor: Color) -> some View {
- HStack {
- Image(uiImage: badgeImage.withRenderingMode(.alwaysTemplate))
- .font(.system(size: 14))
- .colorMultiply(badgeColor)
- Text(String(localized: "Time Change Detected", comment: ""))
- .bold()
- .font(.system(size: 14))
- .foregroundStyle(badgeColor)
- }
- .onTapGesture {
- if state.pumpDisplayState != nil {
- // sends user to pump settings
- state.shouldDisplayPumpSetupSheet.toggle()
- }
- }
- .frame(maxWidth: .infinity, alignment: .center)
- .padding(.vertical, 5)
- .padding(.horizontal, 10)
- .overlay(
- Capsule()
- .stroke(badgeColor.opacity(0.4), lineWidth: 2)
- )
- }
- var cgmSelectionButtons: some View {
- ForEach(cgmOptions, id: \.name) { option in
- if let cgm = state.listOfCGM.first(where: option.predicate) {
- Button(option.name) {
- state.addCGM(cgm: cgm)
- }
- }
- }
- }
- var glucoseView: some View {
- CurrentGlucoseView(
- timerDate: state.timerDate,
- units: state.units,
- alarm: state.alarm,
- lowGlucose: state.lowGlucose,
- highGlucose: state.highGlucose,
- cgmAvailable: state.cgmAvailable,
- currentGlucoseTarget: state.currentGlucoseTarget,
- glucoseColorScheme: state.glucoseColorScheme,
- glucose: state.latestTwoGlucoseValues
- ).scaleEffect(0.9)
- .onTapGesture {
- if !state.cgmAvailable {
- showCGMSelection.toggle()
- } else {
- state.shouldDisplayCGMSetupSheet.toggle()
- }
- }
- .onLongPressGesture {
- let impactHeavy = UIImpactFeedbackGenerator(style: .heavy)
- impactHeavy.impactOccurred()
- state.showModal(for: .snooze)
- }
- }
- var pumpView: some View {
- PumpView(
- reservoir: state.reservoir,
- name: state.pumpName,
- expiresAtDate: state.pumpExpiresAtDate,
- timerDate: state.timerDate,
- pumpStatusHighlightMessage: state.pumpStatusHighlightMessage,
- battery: state.batteryFromPersistence
- )
- .onTapGesture {
- if state.pumpDisplayState == nil {
- // shows user confirmation dialog with pump model choices, then proceeds to setup
- showPumpSelection.toggle()
- } else {
- // sends user to pump settings
- state.shouldDisplayPumpSetupSheet.toggle()
- }
- }
- }
- var basalString: String? {
- var rate: NSNumber = 0
- var manualBasalString = ""
- guard let apsManager = state.apsManager else {
- return nil
- }
- if apsManager.isScheduledBasal == true {
- guard let scheduledRate = scheduledBasalDeliveryRate(at: Date()) else {
- return nil
- }
- rate = scheduledRate
- } else {
- guard let lastTempBasal = state.tempBasals.last?.tempBasal, let tempRate = lastTempBasal.rate else {
- return nil
- }
- if apsManager.isManualTempBasal {
- manualBasalString = String(
- localized: " - Manual Basal ⚠️",
- comment: "Manual Temp basal"
- )
- }
- rate = tempRate
- }
- let rateString = Formatter.decimalFormatterWithThreeFractionDigits.string(from: rate) ?? "0"
- return rateString + String(localized: " U/hr", comment: "Unit per hour with space") +
- manualBasalString
- }
- // Returns the scheduled basal rate for the current time based on the saved basal scheduled.
- // Would be better if in the future BasalDeliveryStatus could be updated to include this info.
- func scheduledBasalDeliveryRate(at when: Date) -> NSNumber? {
- let calendar = Calendar(identifier: .gregorian)
- // calendar.timeZone = timeZone /// should come from pumpManager in case it's different!
- let hours = calendar.component(.hour, from: when)
- let minutes = calendar.component(.minute, from: when)
- let totalMinutes = hours * 60 + minutes
- if let rate = findBasalRateForOffset(for: totalMinutes, in: state.basalProfile) {
- return NSDecimalNumber(decimal: rate)
- }
- return nil
- }
- var overrideString: String? {
- guard let latestOverride = latestOverride.first else {
- return nil
- }
- guard let settingsManager = state.settingsManager else {
- return nil
- }
- let percent = latestOverride.percentage
- let percentString = percent == 100 ? "" : "\(percent.formatted(.number)) %"
- let unit = state.units
- var target = (latestOverride.target ?? 0) as Decimal
- target = unit == .mmolL ? target.asMmolL : target
- var targetString = target == 0 ? "" : (fetchedTargetFormatter.string(from: target as NSNumber) ?? "") + " " + unit
- .rawValue
- if tempTargetString != nil {
- targetString = ""
- }
- let duration = latestOverride.duration ?? 0
- let addedMinutes = Int(truncating: duration)
- let date = latestOverride.date ?? Date()
- let newDuration = max(
- Decimal(Date().distance(to: date.addingTimeInterval(addedMinutes.minutes.timeInterval)).minutes),
- 0
- )
- let indefinite = latestOverride.indefinite
- var durationString = ""
- if !indefinite {
- if newDuration >= 1 {
- durationString = formatHrMin(Int(newDuration))
- } else if newDuration > 0 {
- durationString = "\(Int(newDuration * 60)) s"
- } else {
- /// Do not show the Override anymore
- Task {
- guard let objectID = self.latestOverride.first?.objectID else { return }
- await state.cancelOverride(withID: objectID)
- }
- }
- }
- let smbScheduleString = latestOverride
- .smbIsScheduledOff && ((latestOverride.start?.stringValue ?? "") != (latestOverride.end?.stringValue ?? ""))
- ? " \(formatTimeRange(start: latestOverride.start?.stringValue, end: latestOverride.end?.stringValue))"
- : ""
- let smbToggleString = latestOverride.smbIsOff || latestOverride
- .smbIsScheduledOff ? String(localized: "SMBs Off\(smbScheduleString)") : ""
- var smbMinuteString: String = ""
- var uamMinuteString: String = ""
- if !latestOverride.smbIsOff, latestOverride.advancedSettings {
- if let smbMinutes = latestOverride.smbMinutes,
- smbMinutes.decimalValue != settingsManager.preferences.maxSMBBasalMinutes
- {
- smbMinuteString = "SMB\u{00A0}\(smbMinutes)\u{00A0}" +
- String(localized: "m", comment: "Abbreviation for Minutes")
- }
- if let uamMinutes = latestOverride.uamMinutes,
- uamMinutes.decimalValue != settingsManager.preferences.maxUAMSMBBasalMinutes
- {
- uamMinuteString = "UAM\u{00A0}\(uamMinutes)\u{00A0}" +
- String(localized: "m", comment: "Abbreviation for Minutes")
- }
- }
- let components = [durationString, percentString, targetString, smbToggleString, smbMinuteString, uamMinuteString]
- .filter { !$0.isEmpty }
- return components.isEmpty ? nil : components.joined(separator: ", ")
- }
- var tempTargetString: String? {
- guard let latestTempTarget = latestTempTarget.first else {
- return nil
- }
- let duration = latestTempTarget.duration
- let addedMinutes = Int(truncating: duration ?? 0)
- let date = latestTempTarget.date ?? Date()
- let newDuration = max(
- Decimal(Date().distance(to: date.addingTimeInterval(addedMinutes.minutes.timeInterval)).minutes),
- 0
- )
- var durationString = ""
- var percentageString = ""
- var target = (latestTempTarget.target ?? 100) as Decimal
- // Use TempTargetCalculations to get effective HBT (handles both custom and auto-adjusted standard TT)
- let effectiveHBT = TempTargetCalculations.computeEffectiveHBT(
- tempTargetHalfBasalTarget: latestTempTarget.halfBasalTarget?.decimalValue,
- settingHalfBasalTarget: state.settingHalfBasalTarget,
- target: target,
- autosensMax: state.autosensMax
- ) ?? state.settingHalfBasalTarget
- var showPercentage = false
- if target > 100, state.isExerciseModeActive || state.highTTraisesSens { showPercentage = true }
- if target < 100, state.lowTTlowersSens, state.autosensMax > 1 { showPercentage = true }
- if showPercentage {
- percentageString =
- " \(Int(TempTargetCalculations.computeAdjustedPercentage(halfBasalTarget: effectiveHBT, target: target, autosensMax: state.autosensMax)))%"
- }
- target = state.units == .mmolL ? target.asMmolL : target
- let targetString = target == 0 ? "" : (fetchedTargetFormatter.string(from: target as NSNumber) ?? "") + " " +
- state.units.rawValue + percentageString
- if newDuration >= 1 {
- durationString =
- "\(newDuration.formatted(.number.grouping(.never).rounded().precision(.fractionLength(0)))) min"
- } else if newDuration > 0 {
- durationString =
- "\((newDuration * 60).formatted(.number.grouping(.never).rounded().precision(.fractionLength(0)))) s"
- } else {
- /// Do not show the Temp Target anymore
- Task {
- guard let objectID = self.latestTempTarget.first?.objectID else { return }
- await state.cancelTempTarget(withID: objectID)
- }
- }
- let components = [targetString, durationString].filter { !$0.isEmpty }
- return components.isEmpty ? nil : components.joined(separator: ", ")
- }
- var timeIntervalButtons: some View {
- let buttonColor = (colorScheme == .dark ? Color.white : Color.black).opacity(0.8)
- return HStack(alignment: .center) {
- ForEach(timeButtons) { button in
- Button(action: {
- state.hours = button.hours
- }) {
- Group {
- if button.active {
- Text(
- button.hours.description + "\u{00A0}" +
- String(localized: "h", comment: "h")
- )
- } else {
- Text(button.hours.description)
- }
- }
- .font(.footnote)
- .fontWeight(button.active ? .semibold : .regular)
- .padding(.vertical, 5)
- .padding(.horizontal, 10)
- .foregroundColor(
- button
- .active ? (colorScheme == .dark ? Color.bgDarkerDarkBlue : Color.white) : buttonColor
- )
- .background(button.active ? buttonColor.opacity(colorScheme == .dark ? 1 : 0.8) : Color.clear)
- .clipShape(Capsule())
- .overlay(
- Capsule()
- .stroke(button.active ? buttonColor.opacity(0.4) : Color.clear, lineWidth: 2)
- )
- }
- }
- }
- }
- var statsIconString: String {
- if #available(iOS 18, *) {
- return "chart.line.text.clipboard"
- } else {
- return "list.clipboard"
- }
- }
- @ViewBuilder private func tappableButton(
- buttonColor: Color,
- label: String,
- iconString: String,
- action: @escaping () -> Void
- ) -> some View {
- Button(action: {
- action()
- }) {
- HStack {
- Image(systemName: iconString)
- Text(label)
- }
- .font(.footnote)
- .padding(.vertical, 5)
- .padding(.horizontal, 10)
- .foregroundStyle(buttonColor)
- .overlay(
- Capsule()
- .stroke(buttonColor.opacity(0.4), lineWidth: 2)
- )
- }
- }
- @ViewBuilder func mainChart(geo: GeometryProxy) -> some View {
- ZStack {
- MainChartView(
- geo: geo,
- safeAreaSize: notificationsDisabled == true ? safeAreaSize : 0,
- units: state.units,
- hours: state.filteredHours,
- highGlucose: state.highGlucose,
- lowGlucose: state.lowGlucose,
- currentGlucoseTarget: state.currentGlucoseTarget,
- glucoseColorScheme: state.glucoseColorScheme,
- screenHours: state.hours,
- displayXgridLines: state.displayXgridLines,
- displayYgridLines: state.displayYgridLines,
- thresholdLines: state.thresholdLines,
- state: state
- )
- }
- .padding(.bottom, UIDevice.adjustPadding(min: 0, max: nil))
- }
- func highlightButtons() {
- for i in 0 ..< timeButtons.count {
- timeButtons[i].active = timeButtons[i].hours == state.hours
- }
- }
- @ViewBuilder func rightHeaderPanel(_: GeometryProxy) -> some View {
- VStack(alignment: .leading, spacing: 20) {
- /// Loop view at bottomLeading
- LoopView(
- closedLoop: state.closedLoop,
- timerDate: state.timerDate,
- isLooping: state.isLooping,
- lastLoopDate: state.lastLoopDate,
- manualTempBasal: state.manualTempBasal,
- determination: state.determinationsFromPersistence
- )
- .onTapGesture {
- state.isLoopStatusPresented = true
- }
- .onLongPressGesture {
- let impactHeavy = UIImpactFeedbackGenerator(style: .heavy)
- impactHeavy.impactOccurred()
- state.runLoop()
- }
- /// eventualBG string at bottomTrailing
- if let eventualBG = state.enactedAndNonEnactedDeterminations.first?.eventualBG {
- let eventualGlucose = eventualBG as Decimal
- HStack {
- Image(systemName: "arrow.right.circle")
- .font(.callout)
- .fontWeight(.bold)
- Text(state.units == .mgdL ? eventualGlucose.description : eventualGlucose.formattedAsMmolL)
- .font(.callout)
- .fontWeight(.bold)
- .fontDesign(.rounded)
- }
- // aligns the evBG icon exactly with the first pixel of loop status icon
- .padding(.leading, 12)
- } else {
- HStack {
- Image(systemName: "arrow.right.circle")
- .font(.callout).fontWeight(.bold)
- Text("--")
- .font(.callout).fontWeight(.bold).fontDesign(.rounded)
- }
- }
- }
- }
- @ViewBuilder func mealPanel(_: GeometryProxy) -> some View {
- HStack {
- HStack {
- Image(systemName: "syringe.fill")
- .font(.callout)
- .foregroundColor(Color.insulin)
- Text(
- (
- Formatter.decimalFormatterWithTwoFractionDigits
- .string(from: state.currentIOB as NSNumber) ?? "0"
- ) +
- String(localized: " U", comment: "Insulin unit")
- )
- .font(.callout).fontWeight(.bold).fontDesign(.rounded)
- }
- Spacer()
- HStack {
- Image(systemName: "fork.knife")
- .font(.callout)
- .foregroundColor(.loopYellow)
- Text(
- (
- Formatter.decimalFormatterWithTwoFractionDigits.string(
- from: NSNumber(value: state.enactedAndNonEnactedDeterminations.first?.cob ?? 0)
- ) ?? "0"
- ) +
- String(localized: " g", comment: "gram of carbs")
- )
- .font(.callout).fontWeight(.bold).fontDesign(.rounded)
- }
- Spacer()
- if state.maxIOB == 0.0 {
- HStack {
- Image(systemName: "exclamationmark.circle.fill")
- Text("MaxIOB: 0 U")
- }.bold()
- .foregroundStyle(Color.red)
- .font(.callout)
- } else {
- HStack {
- /// Only display the insulin delivery rate info if the pump is not
- /// suspended and is available (e.g., pod is paired & not faulted).
- let pumpAvailable = state.apsManager.isScheduledBasal != nil
- if !state.apsManager.isSuspended && pumpAvailable {
- Image(systemName: "drop.circle")
- .font(.callout)
- .foregroundColor(.insulinTintColor)
- if let basalString = self.basalString {
- /// Adjust opacity when displaying a scheduled basal rate
- let opacity = state.apsManager?.isScheduledBasal == true ? 0.6 : 1.0
- if basalString.count > 5 {
- Text(basalString)
- .font(.callout).fontWeight(.bold).fontDesign(.rounded)
- .lineLimit(1)
- .minimumScaleFactor(0.85)
- .truncationMode(.tail)
- .allowsTightening(true)
- .opacity(opacity)
- } else {
- // Short strings can just display normally
- Text(basalString)
- .font(.callout).fontWeight(.bold).fontDesign(.rounded)
- .opacity(opacity)
- }
- } else {
- Text("No Data")
- .font(.callout).fontWeight(.bold).fontDesign(.rounded)
- }
- }
- }
- }
- }.padding(.horizontal)
- }
- @ViewBuilder func adjustmentsOverrideView(_ overrideString: String) -> some View {
- Group {
- Image(systemName: "clock.arrow.2.circlepath")
- .font(.title2)
- .foregroundStyle(Color.primary, Color.purple)
- VStack(alignment: .leading) {
- Text(latestOverride.first?.name ?? String(localized: "Custom Override"))
- .font(.subheadline)
- .frame(alignment: .leading)
- Text(overrideString)
- .font(.caption)
- }
- }
- .onTapGesture {
- selectedTab = 2
- }
- }
- @ViewBuilder func adjustmentsTempTargetView(_ tempTargetString: String) -> some View {
- Group {
- Image(systemName: "target")
- .font(.title2)
- .foregroundStyle(Color.loopGreen)
- VStack(alignment: .leading) {
- Text(latestTempTarget.first?.name ?? String(localized: "Temp Target"))
- .font(.subheadline)
- Text(tempTargetString)
- .font(.caption)
- }
- }
- .onTapGesture {
- selectedTab = 2
- }
- }
- @ViewBuilder func adjustmentsCancelView(_ cancelAction: @escaping () -> Void) -> some View {
- Image(systemName: "xmark.app")
- .font(.title)
- .onTapGesture {
- cancelAction()
- }
- }
- @ViewBuilder func adjustmentsCancelTempTargetView() -> some View {
- Image(systemName: "xmark.app")
- .font(.title)
- .confirmationDialog(
- "Stop the Temp Target \"\(latestTempTarget.first?.name ?? "")\"?",
- isPresented: $isConfirmStopTempTargetShown,
- titleVisibility: .visible
- ) {
- Button("Stop", role: .destructive) {
- Task {
- guard let objectID = latestTempTarget.first?.objectID else { return }
- await state.cancelTempTarget(withID: objectID)
- }
- }
- Button("Cancel", role: .cancel) {}
- }
- .padding(.trailing, 8)
- .onTapGesture {
- if !latestTempTarget.isEmpty {
- isConfirmStopTempTargetShown = true
- }
- }
- }
- @ViewBuilder func adjustmentsCancelOverrideView() -> some View {
- Image(systemName: "xmark.app")
- .font(.title)
- .confirmationDialog(
- "Stop the Override \"\(latestOverride.first?.name ?? "")\"?",
- isPresented: $isConfirmStopOverridePresented,
- titleVisibility: .visible
- ) {
- Button("Stop", role: .destructive) {
- Task {
- guard let objectID = latestOverride.first?.objectID else { return }
- await state.cancelOverride(withID: objectID)
- }
- }
- Button("Cancel", role: .cancel) {}
- }
- .padding(.trailing, 8)
- .onTapGesture {
- if !latestOverride.isEmpty {
- isConfirmStopOverridePresented = true
- }
- }
- }
- @ViewBuilder func noActiveAdjustmentsView() -> some View {
- Group {
- VStack {
- Text("No Active Adjustment")
- .font(.subheadline)
- .frame(maxWidth: .infinity, alignment: .leading)
- Text("Profile at 100 %")
- .font(.caption)
- .frame(maxWidth: .infinity, alignment: .leading)
- }.padding(.leading, 10)
- Spacer()
- /// to ensure the same position....
- Image(systemName: "xmark.app")
- .font(.title)
- // clear color for the icon
- .foregroundStyle(Color.clear)
- }.onTapGesture {
- selectedTab = 2
- }
- }
- @ViewBuilder func adjustmentView(geo: GeometryProxy) -> some View {
- // let background = colorScheme == .dark ? Material.ultraThinMaterial.opacity(0.5) : Color.black.opacity(0.2)
- ZStack {
- /// rectangle as background
- RoundedRectangle(cornerRadius: 15)
- .fill(
- (overrideString != nil || tempTargetString != nil) ?
- (
- colorScheme == .dark ?
- Color(red: 0.03921568627, green: 0.133333333, blue: 0.2156862745) :
- Color.insulin.opacity(0.1)
- ) : Color.clear // Use clear and add the Material in the background
- )
- .background(colorScheme == .dark ? Color.chart.opacity(0.25) : Color.black.opacity(0.075))
- .clipShape(RoundedRectangle(cornerRadius: 15))
- .frame(height: geo.size.height * 0.08)
- .shadow(
- color: (overrideString != nil || tempTargetString != nil) ?
- (
- colorScheme == .dark ? Color(red: 0.02745098039, green: 0.1098039216, blue: 0.1411764706) :
- Color.black.opacity(0.33)
- ) : Color.clear,
- radius: 3
- )
- HStack {
- if let overrideString = overrideString, let tempTargetString = tempTargetString {
- HStack {
- adjustmentsOverrideView(overrideString)
- Spacer()
- Divider()
- .frame(height: geo.size.height * 0.05)
- .padding(.horizontal, 2)
- adjustmentsTempTargetView(tempTargetString)
- Spacer()
- adjustmentsCancelView({
- if !latestTempTarget.isEmpty, !latestOverride.isEmpty {
- showCancelConfirmDialog = true
- } else if !latestOverride.isEmpty {
- showCancelAlert = true
- } else if !latestTempTarget.isEmpty {
- showCancelAlert = true
- }
- })
- }
- } else if let overrideString = overrideString {
- adjustmentsOverrideView(overrideString)
- Spacer()
- adjustmentsCancelOverrideView()
- } else if let tempTargetString = tempTargetString {
- HStack {
- adjustmentsTempTargetView(tempTargetString)
- Spacer()
- adjustmentsCancelTempTargetView()
- }
- } else {
- noActiveAdjustmentsView()
- }
- }.padding(.horizontal, 10)
- .confirmationDialog("Adjustment to Stop", isPresented: $showCancelConfirmDialog) {
- Button("Stop Override", role: .destructive) {
- Task {
- guard let objectID = latestOverride.first?.objectID else { return }
- await state.cancelOverride(withID: objectID)
- }
- }
- Button("Stop Temp Target", role: .destructive) {
- Task {
- guard let objectID = latestTempTarget.first?.objectID else { return }
- await state.cancelTempTarget(withID: objectID)
- }
- }
- Button("Stop All Adjustments", role: .destructive) {
- Task {
- guard let overrideObjectID = latestOverride.first?.objectID else { return }
- await state.cancelOverride(withID: overrideObjectID)
- guard let tempTargetObjectID = latestTempTarget.first?.objectID else { return }
- await state.cancelTempTarget(withID: tempTargetObjectID)
- }
- }
- } message: {
- Text("Select Adjustment")
- }
- }.padding(.horizontal, 10).padding(.bottom, UIDevice.adjustPadding(min: nil, max: 10))
- }
- @ViewBuilder func bolusProgressBar(_ progress: Decimal) -> some View {
- GeometryReader { geo in
- RoundedRectangle(cornerRadius: 15)
- .frame(height: 6)
- .foregroundColor(.clear)
- .background(
- LinearGradient(colors: [
- Color(red: 0.7215686275, green: 0.3411764706, blue: 1),
- Color(red: 0.6235294118, green: 0.4235294118, blue: 0.9803921569),
- Color(red: 0.4862745098, green: 0.5450980392, blue: 0.9529411765),
- Color(red: 0.3411764706, green: 0.6666666667, blue: 0.9254901961),
- Color(red: 0.262745098, green: 0.7333333333, blue: 0.9137254902)
- ], startPoint: .leading, endPoint: .trailing)
- .mask(alignment: .leading) {
- RoundedRectangle(cornerRadius: 15)
- .frame(width: geo.size.width * CGFloat(progress))
- }
- )
- }
- }
- @ViewBuilder func bolusView(geo: GeometryProxy, _ progress: Decimal) -> some View {
- /// ensure that state.lastPumpBolus has a value, i.e. there is a last bolus done by the pump and not an external bolus
- /// - TRUE: show the pump bolus
- /// - FALSE: do not show a progress bar at all
- if let bolusTotal = state.lastPumpBolus?.bolus?.amount {
- let bolusFraction = progress * (bolusTotal as Decimal)
- let bolusString =
- (bolusProgressFormatter.string(from: bolusFraction as NSNumber) ?? "0")
- + String(localized: " of ", comment: "Bolus string partial message: 'x U of y U' in home view") +
- (Formatter.decimalFormatterWithThreeFractionDigits.string(from: bolusTotal as NSNumber) ?? "0")
- + String(localized: " U", comment: "Insulin unit")
- ZStack {
- /// rectangle as background
- RoundedRectangle(cornerRadius: 15)
- .fill(
- colorScheme == .dark ? Color(red: 0.03921568627, green: 0.133333333, blue: 0.2156862745) : Color
- .insulin
- .opacity(0.2)
- )
- .clipShape(RoundedRectangle(cornerRadius: 15))
- .frame(height: geo.size.height * 0.08)
- .shadow(
- color: colorScheme == .dark ? Color(red: 0.02745098039, green: 0.1098039216, blue: 0.1411764706) :
- Color.black.opacity(0.33),
- radius: 3
- )
- /// actual bolus view
- HStack {
- Image(systemName: "cross.vial.fill")
- .font(.system(size: 25))
- Spacer()
- VStack {
- Text("Bolusing")
- .font(.subheadline)
- .frame(maxWidth: .infinity, alignment: .leading)
- Text(bolusString)
- .font(.caption)
- .frame(maxWidth: .infinity, alignment: .leading)
- }.padding(.leading, 5)
- Spacer()
- Button {
- state.showProgressView()
- state.cancelBolus()
- } label: {
- Image(systemName: "xmark.app")
- .font(.system(size: 25))
- }
- }.padding(.horizontal, 10)
- .padding(.trailing, 8)
- }.padding(.horizontal, 10).padding(.bottom, UIDevice.adjustPadding(min: nil, max: 10))
- .overlay(alignment: .bottom) {
- // Use a geo-based offset here to position progress bar independent of device size
- let offset = geo.size.height * 0.0725
- bolusProgressBar(progress).padding(.horizontal, 18)
- .offset(y: offset)
- }.clipShape(RoundedRectangle(cornerRadius: 15))
- }
- }
- @ViewBuilder func alertSafetyNotificationsView(geo: GeometryProxy) -> some View {
- ZStack {
- /// rectangle as background
- RoundedRectangle(cornerRadius: 15)
- .fill(
- Color(
- red: 0.9,
- green: 0.133333333,
- blue: 0.2156862745
- )
- )
- .clipShape(RoundedRectangle(cornerRadius: 15))
- .frame(height: geo.size.height * safeAreaSize)
- .coordinateSpace(name: "alertSafetyNotificationsView")
- .shadow(
- color: colorScheme == .dark ? Color(red: 0.02745098039, green: 0.1098039216, blue: 0.1411764706) :
- Color.black.opacity(0.33),
- radius: 3
- )
- HStack {
- Spacer()
- VStack {
- Text("⚠️ Safety Notifications are OFF")
- .font(.headline)
- .fontWeight(.bold)
- .fontDesign(.rounded)
- .foregroundStyle(.white.gradient)
- .frame(maxWidth: .infinity, alignment: .leading)
- Text("Fix now by turning Notifications ON.")
- .font(.footnote)
- .fontDesign(.rounded)
- .foregroundStyle(.white.gradient)
- .frame(maxWidth: .infinity, alignment: .leading)
- }.padding(.leading, 5)
- Spacer()
- Image(systemName: "chevron.right").foregroundColor(.white)
- .font(.headline)
- }.padding(.horizontal, 10)
- .padding(.trailing, 8)
- .onTapGesture {
- UIApplication.shared.open(URL(string: UIApplication.openSettingsURLString)!)
- }
- }.padding(.horizontal, 10)
- .padding(.top, 0)
- }
- @ViewBuilder func mainViewElements(_ geo: GeometryProxy) -> some View {
- VStack(spacing: 0) {
- ZStack {
- if let apsManager = state.apsManager, let bluetoothManager = apsManager.bluetoothManager,
- bluetoothManager.bluetoothAuthorization != .authorized
- {
- BluetoothRequiredView()
- } else {
- /// right panel with loop status and evBG
- HStack {
- Spacer()
- rightHeaderPanel(geo)
- }.padding(.trailing, 20)
- /// glucose bobble
- glucoseView
- /// left panel with pump related info
- HStack {
- pumpView
- Spacer()
- }.padding(.leading, 20)
- }
- }
- .padding(.top, 10)
- .safeAreaInset(edge: .top, spacing: 0) {
- if notificationsDisabled {
- alertSafetyNotificationsView(geo: geo)
- }
- if let badgeImage = state.pumpStatusBadgeImage, let badgeColor = state.pumpStatusBadgeColor {
- pumpTimezoneView(badgeImage, badgeColor)
- .padding(.horizontal, 20)
- }
- }
- mealPanel(geo).padding(.top, UIDevice.adjustPadding(min: nil, max: 30))
- .padding(.bottom, UIDevice.adjustPadding(min: nil, max: 20))
- mainChart(geo: geo)
- HStack {
- tappableButton(
- buttonColor: (colorScheme == .dark ? Color.white : Color.black).opacity(0.8),
- label: String(localized: "Stats", comment: "Stats icon in main view"),
- iconString: statsIconString,
- action: { state.showModal(for: .statistics) }
- )
- Spacer()
- timeIntervalButtons.padding(.top, UIDevice.adjustPadding(min: 0, max: 10))
- .padding(.bottom, UIDevice.adjustPadding(min: 0, max: 10))
- Spacer()
- tappableButton(
- buttonColor: (colorScheme == .dark ? Color.white : Color.black).opacity(0.8),
- label: String(localized: "Info", comment: "Info icon in main view"),
- iconString: "info",
- action: { state.isLegendPresented.toggle() }
- )
- }.padding([.horizontal, .bottom])
- if let progress = state.bolusProgress {
- bolusView(geo: geo, progress)
- .padding(.bottom, UIDevice.adjustPadding(min: nil, max: 40))
- } else {
- adjustmentView(geo: geo).padding(.bottom, UIDevice.adjustPadding(min: nil, max: 40))
- }
- }
- .background(appState.trioBackgroundColor(for: colorScheme))
- .onReceive(
- resolver.resolve(AlertPermissionsChecker.self)!.$notificationsDisabled,
- perform: {
- if notificationsDisabled != $0 {
- notificationsDisabled = $0
- if notificationsDisabled {
- debug(.default, "notificationsDisabled")
- }
- }
- }
- )
- }
- @ViewBuilder func mainView() -> some View {
- GeometryReader { geo in
- mainViewElements(geo)
- }
- .onChange(of: state.hours) {
- highlightButtons()
- }
- .onAppear {
- configureView {
- highlightButtons()
- }
- }
- .navigationTitle("Home")
- .navigationBarHidden(true)
- .ignoresSafeArea(.keyboard)
- .blur(radius: state.isLoopStatusPresented ? 3 : 0)
- .sheet(isPresented: $state.isLoopStatusPresented) {
- LoopStatusView(state: state)
- }
- .sheet(isPresented: $state.isLegendPresented) {
- ChartLegendView(state: state)
- }
- // PUMP RELATED
- .confirmationDialog("Pump Model", isPresented: $showPumpSelection) {
- Button("Medtronic") { state.addPump(.minimed) }
- Button("Omnipod Eros") { state.addPump(.omnipod) }
- Button("Omnipod DASH") { state.addPump(.omnipodBLE) }
- Button("Dana(RS/-i)") { state.addPump(.dana) }
- Button("Pump Simulator") { state.addPump(.simulator) }
- } message: { Text("Select Pump Model") }
- .sheet(isPresented: $state.shouldDisplayPumpSetupSheet) {
- if let pumpManager = state.provider.apsManager.pumpManager {
- PumpConfig.PumpSettingsView(
- pumpManager: pumpManager,
- bluetoothManager: state.provider.apsManager.bluetoothManager!,
- completionDelegate: state,
- setupDelegate: state
- )
- } else {
- PumpConfig.PumpSetupView(
- pumpType: state.setupPumpType,
- pumpInitialSettings: state.pumpInitialSettings,
- bluetoothManager: state.provider.apsManager.bluetoothManager!,
- completionDelegate: state,
- setupDelegate: state
- )
- }
- }
- // CGM RELATED
- .confirmationDialog("CGM Model", isPresented: $showCGMSelection) {
- cgmSelectionButtons
- } message: {
- Text("Select CGM Model")
- }
- .sheet(isPresented: $state.shouldDisplayCGMSetupSheet) {
- switch state.cgmCurrent.type {
- case .enlite,
- .nightscout,
- .none,
- .simulator,
- .xdrip:
- CGMSettings.CustomCGMOptionsView(
- resolver: self.resolver,
- state: state.cgmStateModel,
- cgmCurrent: state.cgmCurrent,
- deleteCGM: state.deleteCGM
- )
- case .plugin:
- if let fetchGlucoseManager = state.fetchGlucoseManager,
- let cgmManager = fetchGlucoseManager.cgmManager,
- state.cgmCurrent.type == fetchGlucoseManager.cgmGlucoseSourceType,
- state.cgmCurrent.id == fetchGlucoseManager.cgmGlucosePluginId
- {
- CGMSettings.CGMSettingsView(
- cgmManager: cgmManager,
- bluetoothManager: state.provider.apsManager.bluetoothManager!,
- unit: state.settingsManager.settings.units,
- completionDelegate: state
- )
- } else {
- CGMSettings.CGMSetupView(
- CGMType: state.cgmCurrent,
- bluetoothManager: state.provider.apsManager.bluetoothManager!,
- unit: state.settingsManager.settings.units,
- completionDelegate: state,
- setupDelegate: state,
- pluginCGMManager: self.state.pluginCGMManager
- )
- }
- }
- }
- }
- @ViewBuilder func tabBar() -> some View {
- ZStack(alignment: .bottom) {
- TabView(selection: $selectedTab) {
- let carbsRequiredBadge: String? = {
- guard let carbsRequired = state.enactedAndNonEnactedDeterminations.first?.carbsRequired,
- state.showCarbsRequiredBadge
- else {
- return nil
- }
- let carbsRequiredDecimal = Decimal(carbsRequired)
- if carbsRequiredDecimal > state.settingsManager.settings.carbsRequiredThreshold {
- let numberAsNSNumber = NSDecimalNumber(decimal: carbsRequiredDecimal)
- return (Formatter.decimalFormatterWithTwoFractionDigits.string(from: numberAsNSNumber) ?? "") + " g"
- }
- return nil
- }()
- NavigationStack { mainView() }
- .tabItem { Label("Main", systemImage: "chart.xyaxis.line") }
- .badge(carbsRequiredBadge).tag(0)
- NavigationStack { History.RootView(resolver: resolver) }
- .tabItem { Label("History", systemImage: historySFSymbol) }.tag(1)
- Spacer()
- NavigationStack { Adjustments.RootView(resolver: resolver) }
- .tabItem {
- Label(
- "Adjustments",
- systemImage: "slider.horizontal.2.gobackward"
- ) }.tag(2)
- NavigationStack(path: self.$settingsPath) {
- Settings.RootView(resolver: resolver) }
- .tabItem { Label(
- "Settings",
- systemImage: "gear"
- ) }.tag(3)
- }
- .tint(Color.tabBar)
- Button(
- action: {
- state.showModal(for: .treatmentView) },
- label: {
- Image(systemName: "plus.circle.fill")
- .font(.system(size: 40))
- .foregroundStyle(Color.tabBar)
- .padding(.vertical, 2)
- .padding(.horizontal, 24)
- }
- )
- }.ignoresSafeArea(.keyboard, edges: .bottom).blur(radius: state.waitForSuggestion ? 8 : 0)
- .onChange(of: selectedTab) {
- if !settingsPath.isEmpty {
- settingsPath = NavigationPath()
- }
- }
- }
- var body: some View {
- ZStack(alignment: .center) {
- tabBar()
- if state.waitForSuggestion {
- CustomProgressView(text: String(localized: "Updating IOB...", comment: "Progress text when updating IOB"))
- }
- }
- }
- }
- }
- extension UIDevice {
- public enum DeviceSize: CGFloat {
- case smallDevice = 667 // Height for 4" iPhone SE
- case largeDevice = 852 // Height for 6.1" iPhone 15 Pro
- }
- @usableFromInline static func adjustPadding(
- min: CGFloat? = nil,
- max: CGFloat? = nil
- ) -> CGFloat? {
- if UIScreen.screenHeight > UIDevice.DeviceSize.smallDevice.rawValue {
- if UIScreen.screenHeight >= UIDevice.DeviceSize.largeDevice.rawValue {
- return max
- } else {
- return min != nil ?
- (max != nil ? max! * (UIScreen.screenHeight / UIDevice.DeviceSize.largeDevice.rawValue) : nil) : nil
- }
- } else {
- return min
- }
- }
- }
- extension UIScreen {
- static var screenHeight: CGFloat {
- UIScreen.main.bounds.height
- }
- static var screenWidth: CGFloat {
- UIScreen.main.bounds.width
- }
- }
- /// Checks if the device is using a 24-hour time format.
- func is24HourFormat() -> Bool {
- let formatter = DateFormatter()
- formatter.locale = Locale.current
- formatter.dateStyle = .none
- formatter.timeStyle = .short
- let dateString = formatter.string(from: Date())
- return !dateString.contains("AM") && !dateString.contains("PM")
- }
- /// Converts a duration in minutes to a formatted string (e.g., "1 h 30 m").
- func formatHrMin(_ durationInMinutes: Int) -> String {
- let hours = durationInMinutes / 60
- let minutes = durationInMinutes % 60
- switch (hours, minutes) {
- case let (0, m):
- return "\(m)\u{00A0}" + String(localized: "m", comment: "Abbreviation for Minutes")
- case let (h, 0):
- return "\(h)\u{00A0}" + String(localized: "h", comment: "h")
- default:
- return hours.description + "\u{00A0}" + String(localized: "h", comment: "h") + "\u{00A0}" + minutes
- .description + "\u{00A0}" + String(localized: "m", comment: "Abbreviation for Minutes")
- }
- }
- // Helper function to convert a start and end hour to either 24-hour or AM/PM format
- func formatTimeRange(start: String?, end: String?) -> String {
- guard let start = start, let end = end else {
- return ""
- }
- // Check if the format is 24-hour or AM/PM
- if is24HourFormat() {
- // Return the original 24-hour format
- return "\(start)-\(end)"
- } else {
- // Convert to AM/PM format using DateFormatter
- let formatter = DateFormatter()
- formatter.dateFormat = "HH"
- if let startHour = Int(start), let endHour = Int(end) {
- let startDate = Calendar.current.date(bySettingHour: startHour, minute: 0, second: 0, of: Date()) ?? Date()
- let endDate = Calendar.current.date(bySettingHour: endHour, minute: 0, second: 0, of: Date()) ?? Date()
- // Customize the format to "2p" or "2a"
- formatter.dateFormat = "ha"
- let startFormatted = formatter.string(from: startDate).lowercased().replacingOccurrences(of: "m", with: "")
- let endFormatted = formatter.string(from: endDate).lowercased().replacingOccurrences(of: "m", with: "")
- return "\(startFormatted)-\(endFormatted)"
- } else {
- return ""
- }
- }
- }
|