HomeRootView.swift 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224
  1. import CoreData
  2. import SpriteKit
  3. import SwiftDate
  4. import SwiftUI
  5. import Swinject
  6. struct TimePicker: Identifiable {
  7. var active: Bool
  8. let hours: Int16
  9. var id: String { hours.description }
  10. }
  11. extension Home {
  12. struct RootView: BaseView {
  13. let resolver: Resolver
  14. let safeAreaSize: CGFloat = 0.08
  15. @Environment(\.managedObjectContext) var moc
  16. @Environment(\.colorScheme) var colorScheme
  17. @Environment(AppState.self) var appState
  18. @State var state = StateModel()
  19. @State var settingsPath = NavigationPath()
  20. @State var isStatusPopupPresented = false
  21. @State var showCancelAlert = false
  22. @State var showCancelConfirmDialog = false
  23. @State var isConfirmStopOverrideShown = false
  24. @State var isConfirmStopOverridePresented = false
  25. @State var isConfirmStopTempTargetShown = false
  26. @State var isMenuPresented = false
  27. @State var showTreatments = false
  28. @State var selectedTab: Int = 0
  29. @State var showPumpSelection: Bool = false
  30. @State var showCGMSelection: Bool = false
  31. @State var notificationsDisabled = false
  32. @State var timeButtons: [TimePicker] = [
  33. TimePicker(active: false, hours: 4),
  34. TimePicker(active: false, hours: 6),
  35. TimePicker(active: false, hours: 12),
  36. TimePicker(active: false, hours: 24)
  37. ]
  38. @FetchRequest(fetchRequest: OverrideStored.fetch(
  39. NSPredicate.lastActiveOverride,
  40. ascending: false,
  41. fetchLimit: 1
  42. )) var latestOverride: FetchedResults<OverrideStored>
  43. @FetchRequest(fetchRequest: TempTargetStored.fetch(
  44. NSPredicate.lastActiveTempTarget,
  45. ascending: false,
  46. fetchLimit: 1
  47. )) var latestTempTarget: FetchedResults<TempTargetStored>
  48. var bolusProgressFormatter: NumberFormatter {
  49. let fractionDigits: Int = switch state.settingsManager.preferences.bolusIncrement {
  50. case 0.1: 1
  51. case 0.025: 3
  52. default: 2
  53. }
  54. let formatter = NumberFormatter()
  55. formatter.numberStyle = .decimal
  56. formatter.minimum = 0
  57. formatter.maximumFractionDigits = fractionDigits
  58. formatter.minimumFractionDigits = fractionDigits
  59. formatter.allowsFloats = true
  60. formatter.roundingIncrement = Double(state.settingsManager.preferences.bolusIncrement) as NSNumber
  61. return formatter
  62. }
  63. private var fetchedTargetFormatter: NumberFormatter {
  64. let formatter = NumberFormatter()
  65. formatter.numberStyle = .decimal
  66. if state.units == .mmolL {
  67. formatter.maximumFractionDigits = 1
  68. } else { formatter.maximumFractionDigits = 0 }
  69. return formatter
  70. }
  71. private var historySFSymbol: String {
  72. if #available(iOS 17.0, *) {
  73. return "book.pages"
  74. } else {
  75. return "book"
  76. }
  77. }
  78. @ViewBuilder func pumpTimezoneView(_ badgeImage: UIImage, _ badgeColor: Color) -> some View {
  79. HStack {
  80. Image(uiImage: badgeImage.withRenderingMode(.alwaysTemplate))
  81. .font(.system(size: 14))
  82. .colorMultiply(badgeColor)
  83. Text(String(localized: "Time Change Detected", comment: ""))
  84. .bold()
  85. .font(.system(size: 14))
  86. .foregroundStyle(badgeColor)
  87. }
  88. .onTapGesture {
  89. if state.pumpDisplayState != nil {
  90. // sends user to pump settings
  91. state.shouldDisplayPumpSetupSheet.toggle()
  92. }
  93. }
  94. .frame(maxWidth: .infinity, alignment: .center)
  95. .padding(.vertical, 5)
  96. .padding(.horizontal, 10)
  97. .overlay(
  98. Capsule()
  99. .stroke(badgeColor.opacity(0.4), lineWidth: 2)
  100. )
  101. }
  102. var cgmSelectionButtons: some View {
  103. ForEach(cgmOptions, id: \.name) { option in
  104. if let cgm = state.listOfCGM.first(where: option.predicate) {
  105. Button(option.name) {
  106. state.addCGM(cgm: cgm)
  107. }
  108. }
  109. }
  110. }
  111. var glucoseView: some View {
  112. CurrentGlucoseView(
  113. timerDate: state.timerDate,
  114. units: state.units,
  115. alarm: state.alarm,
  116. lowGlucose: state.lowGlucose,
  117. highGlucose: state.highGlucose,
  118. cgmAvailable: state.cgmAvailable,
  119. currentGlucoseTarget: state.currentGlucoseTarget,
  120. glucoseColorScheme: state.glucoseColorScheme,
  121. glucose: state.latestTwoGlucoseValues
  122. ).scaleEffect(0.9)
  123. .onTapGesture {
  124. if !state.cgmAvailable {
  125. showCGMSelection.toggle()
  126. } else {
  127. state.shouldDisplayCGMSetupSheet.toggle()
  128. }
  129. }
  130. .onLongPressGesture {
  131. let impactHeavy = UIImpactFeedbackGenerator(style: .heavy)
  132. impactHeavy.impactOccurred()
  133. state.showModal(for: .snooze)
  134. }
  135. }
  136. var pumpView: some View {
  137. PumpView(
  138. reservoir: state.reservoir,
  139. name: state.pumpName,
  140. expiresAtDate: state.pumpExpiresAtDate,
  141. timerDate: state.timerDate,
  142. pumpStatusHighlightMessage: state.pumpStatusHighlightMessage,
  143. battery: state.batteryFromPersistence
  144. )
  145. .onTapGesture {
  146. if state.pumpDisplayState == nil {
  147. // shows user confirmation dialog with pump model choices, then proceeds to setup
  148. showPumpSelection.toggle()
  149. } else {
  150. // sends user to pump settings
  151. state.shouldDisplayPumpSetupSheet.toggle()
  152. }
  153. }
  154. }
  155. var basalString: String? {
  156. var rate: NSNumber = 0
  157. var manualBasalString = ""
  158. guard let apsManager = state.apsManager else {
  159. return nil
  160. }
  161. if apsManager.isScheduledBasal == true {
  162. guard let scheduledRate = scheduledBasalDeliveryRate(at: Date()) else {
  163. return nil
  164. }
  165. rate = scheduledRate
  166. } else {
  167. guard let lastTempBasal = state.tempBasals.last?.tempBasal, let tempRate = lastTempBasal.rate else {
  168. return nil
  169. }
  170. if apsManager.isManualTempBasal {
  171. manualBasalString = String(
  172. localized: " - Manual Basal ⚠️",
  173. comment: "Manual Temp basal"
  174. )
  175. }
  176. rate = tempRate
  177. }
  178. let rateString = Formatter.decimalFormatterWithThreeFractionDigits.string(from: rate) ?? "0"
  179. return rateString + String(localized: " U/hr", comment: "Unit per hour with space") +
  180. manualBasalString
  181. }
  182. // Returns the scheduled basal rate for the current time based on the saved basal scheduled.
  183. // Would be better if in the future BasalDeliveryStatus could be updated to include this info.
  184. func scheduledBasalDeliveryRate(at when: Date) -> NSNumber? {
  185. let calendar = Calendar(identifier: .gregorian)
  186. // calendar.timeZone = timeZone /// should come from pumpManager in case it's different!
  187. let hours = calendar.component(.hour, from: when)
  188. let minutes = calendar.component(.minute, from: when)
  189. let totalMinutes = hours * 60 + minutes
  190. if let rate = findBasalRateForOffset(for: totalMinutes, in: state.basalProfile) {
  191. return NSDecimalNumber(decimal: rate)
  192. }
  193. return nil
  194. }
  195. var overrideString: String? {
  196. guard let latestOverride = latestOverride.first else {
  197. return nil
  198. }
  199. let percent = latestOverride.percentage
  200. let percentString = percent == 100 ? "" : "\(percent.formatted(.number)) %"
  201. let unit = state.units
  202. var target = (latestOverride.target ?? 100) as Decimal
  203. target = unit == .mmolL ? target.asMmolL : target
  204. var targetString = target == 0 ? "" : (fetchedTargetFormatter.string(from: target as NSNumber) ?? "") + " " + unit
  205. .rawValue
  206. if tempTargetString != nil {
  207. targetString = ""
  208. }
  209. let duration = latestOverride.duration ?? 0
  210. let addedMinutes = Int(truncating: duration)
  211. let date = latestOverride.date ?? Date()
  212. let newDuration = max(
  213. Decimal(Date().distance(to: date.addingTimeInterval(addedMinutes.minutes.timeInterval)).minutes),
  214. 0
  215. )
  216. let indefinite = latestOverride.indefinite
  217. var durationString = ""
  218. if !indefinite {
  219. if newDuration >= 1 {
  220. durationString = formatHrMin(Int(newDuration))
  221. } else if newDuration > 0 {
  222. durationString = "\(Int(newDuration * 60)) s"
  223. } else {
  224. /// Do not show the Override anymore
  225. Task {
  226. guard let objectID = self.latestOverride.first?.objectID else { return }
  227. await state.cancelOverride(withID: objectID)
  228. }
  229. }
  230. }
  231. let smbScheduleString = latestOverride
  232. .smbIsScheduledOff && ((latestOverride.start?.stringValue ?? "") != (latestOverride.end?.stringValue ?? ""))
  233. ? " \(formatTimeRange(start: latestOverride.start?.stringValue, end: latestOverride.end?.stringValue))"
  234. : ""
  235. let smbToggleString = latestOverride.smbIsOff || latestOverride
  236. .smbIsScheduledOff ? "SMBs Off\(smbScheduleString)" : ""
  237. let components = [durationString, percentString, targetString, smbToggleString].filter { !$0.isEmpty }
  238. return components.isEmpty ? nil : components.joined(separator: ", ")
  239. }
  240. var tempTargetString: String? {
  241. guard let latestTempTarget = latestTempTarget.first else {
  242. return nil
  243. }
  244. let duration = latestTempTarget.duration
  245. let addedMinutes = Int(truncating: duration ?? 0)
  246. let date = latestTempTarget.date ?? Date()
  247. let newDuration = max(
  248. Decimal(Date().distance(to: date.addingTimeInterval(addedMinutes.minutes.timeInterval)).minutes),
  249. 0
  250. )
  251. var durationString = ""
  252. var percentageString = ""
  253. var target = (latestTempTarget.target ?? 100) as Decimal
  254. // Use TempTargetCalculations to get effective HBT (handles both custom and auto-adjusted standard TT)
  255. let effectiveHBT = TempTargetCalculations.computeEffectiveHBT(
  256. tempTargetHalfBasalTarget: latestTempTarget.halfBasalTarget?.decimalValue,
  257. settingHalfBasalTarget: state.settingHalfBasalTarget,
  258. target: target,
  259. autosensMax: state.autosensMax
  260. ) ?? state.settingHalfBasalTarget
  261. var showPercentage = false
  262. if target > 100, state.isExerciseModeActive || state.highTTraisesSens { showPercentage = true }
  263. if target < 100, state.lowTTlowersSens, state.autosensMax > 1 { showPercentage = true }
  264. if showPercentage {
  265. percentageString =
  266. " \(Int(TempTargetCalculations.computeAdjustedPercentage(halfBasalTarget: effectiveHBT, target: target, autosensMax: state.autosensMax)))%"
  267. }
  268. target = state.units == .mmolL ? target.asMmolL : target
  269. let targetString = target == 0 ? "" : (fetchedTargetFormatter.string(from: target as NSNumber) ?? "") + " " +
  270. state.units.rawValue + percentageString
  271. if newDuration >= 1 {
  272. durationString =
  273. "\(newDuration.formatted(.number.grouping(.never).rounded().precision(.fractionLength(0)))) min"
  274. } else if newDuration > 0 {
  275. durationString =
  276. "\((newDuration * 60).formatted(.number.grouping(.never).rounded().precision(.fractionLength(0)))) s"
  277. } else {
  278. /// Do not show the Temp Target anymore
  279. Task {
  280. guard let objectID = self.latestTempTarget.first?.objectID else { return }
  281. await state.cancelTempTarget(withID: objectID)
  282. }
  283. }
  284. let components = [targetString, durationString].filter { !$0.isEmpty }
  285. return components.isEmpty ? nil : components.joined(separator: ", ")
  286. }
  287. var timeIntervalButtons: some View {
  288. let buttonColor = (colorScheme == .dark ? Color.white : Color.black).opacity(0.8)
  289. return HStack(alignment: .center) {
  290. ForEach(timeButtons) { button in
  291. Button(action: {
  292. state.hours = button.hours
  293. }) {
  294. Group {
  295. if button.active {
  296. Text(
  297. button.hours.description + "\u{00A0}" +
  298. String(localized: "h", comment: "h")
  299. )
  300. } else {
  301. Text(button.hours.description)
  302. }
  303. }
  304. .font(.footnote)
  305. .fontWeight(button.active ? .semibold : .regular)
  306. .padding(.vertical, 5)
  307. .padding(.horizontal, 10)
  308. .foregroundColor(
  309. button
  310. .active ? (colorScheme == .dark ? Color.bgDarkerDarkBlue : Color.white) : buttonColor
  311. )
  312. .background(button.active ? buttonColor.opacity(colorScheme == .dark ? 1 : 0.8) : Color.clear)
  313. .clipShape(Capsule())
  314. .overlay(
  315. Capsule()
  316. .stroke(button.active ? buttonColor.opacity(0.4) : Color.clear, lineWidth: 2)
  317. )
  318. }
  319. }
  320. }
  321. }
  322. var statsIconString: String {
  323. if #available(iOS 18, *) {
  324. return "chart.line.text.clipboard"
  325. } else {
  326. return "list.clipboard"
  327. }
  328. }
  329. @ViewBuilder private func tappableButton(
  330. buttonColor: Color,
  331. label: String,
  332. iconString: String,
  333. action: @escaping () -> Void
  334. ) -> some View {
  335. Button(action: {
  336. action()
  337. }) {
  338. HStack {
  339. Image(systemName: iconString)
  340. Text(label)
  341. }
  342. .font(.footnote)
  343. .padding(.vertical, 5)
  344. .padding(.horizontal, 10)
  345. .foregroundStyle(buttonColor)
  346. .overlay(
  347. Capsule()
  348. .stroke(buttonColor.opacity(0.4), lineWidth: 2)
  349. )
  350. }
  351. }
  352. @ViewBuilder func mainChart(geo: GeometryProxy) -> some View {
  353. ZStack {
  354. MainChartView(
  355. geo: geo,
  356. safeAreaSize: notificationsDisabled == true ? safeAreaSize : 0,
  357. units: state.units,
  358. hours: state.filteredHours,
  359. highGlucose: state.highGlucose,
  360. lowGlucose: state.lowGlucose,
  361. currentGlucoseTarget: state.currentGlucoseTarget,
  362. glucoseColorScheme: state.glucoseColorScheme,
  363. screenHours: state.hours,
  364. displayXgridLines: state.displayXgridLines,
  365. displayYgridLines: state.displayYgridLines,
  366. thresholdLines: state.thresholdLines,
  367. state: state
  368. )
  369. }
  370. .padding(.bottom, UIDevice.adjustPadding(min: 0, max: nil))
  371. }
  372. func highlightButtons() {
  373. for i in 0 ..< timeButtons.count {
  374. timeButtons[i].active = timeButtons[i].hours == state.hours
  375. }
  376. }
  377. @ViewBuilder func rightHeaderPanel(_: GeometryProxy) -> some View {
  378. VStack(alignment: .leading, spacing: 20) {
  379. /// Loop view at bottomLeading
  380. LoopView(
  381. closedLoop: state.closedLoop,
  382. timerDate: state.timerDate,
  383. isLooping: state.isLooping,
  384. lastLoopDate: state.lastLoopDate,
  385. manualTempBasal: state.manualTempBasal,
  386. determination: state.determinationsFromPersistence
  387. )
  388. .onTapGesture {
  389. state.isLoopStatusPresented = true
  390. }
  391. .onLongPressGesture {
  392. let impactHeavy = UIImpactFeedbackGenerator(style: .heavy)
  393. impactHeavy.impactOccurred()
  394. state.runLoop()
  395. }
  396. /// eventualBG string at bottomTrailing
  397. if let eventualBG = state.enactedAndNonEnactedDeterminations.first?.eventualBG {
  398. let eventualGlucose = eventualBG as Decimal
  399. HStack {
  400. Image(systemName: "arrow.right.circle")
  401. .font(.callout)
  402. .fontWeight(.bold)
  403. Text(state.units == .mgdL ? eventualGlucose.description : eventualGlucose.formattedAsMmolL)
  404. .font(.callout)
  405. .fontWeight(.bold)
  406. .fontDesign(.rounded)
  407. }
  408. // aligns the evBG icon exactly with the first pixel of loop status icon
  409. .padding(.leading, 12)
  410. } else {
  411. HStack {
  412. Image(systemName: "arrow.right.circle")
  413. .font(.callout).fontWeight(.bold)
  414. Text("--")
  415. .font(.callout).fontWeight(.bold).fontDesign(.rounded)
  416. }
  417. }
  418. }
  419. }
  420. @ViewBuilder func mealPanel(_: GeometryProxy) -> some View {
  421. HStack {
  422. HStack {
  423. Image(systemName: "syringe.fill")
  424. .font(.callout)
  425. .foregroundColor(Color.insulin)
  426. Text(
  427. (
  428. Formatter.decimalFormatterWithTwoFractionDigits
  429. .string(from: state.currentIOB as NSNumber) ?? "0"
  430. ) +
  431. String(localized: " U", comment: "Insulin unit")
  432. )
  433. .font(.callout).fontWeight(.bold).fontDesign(.rounded)
  434. }
  435. Spacer()
  436. HStack {
  437. Image(systemName: "fork.knife")
  438. .font(.callout)
  439. .foregroundColor(.loopYellow)
  440. Text(
  441. (
  442. Formatter.decimalFormatterWithTwoFractionDigits.string(
  443. from: NSNumber(value: state.enactedAndNonEnactedDeterminations.first?.cob ?? 0)
  444. ) ?? "0"
  445. ) +
  446. String(localized: " g", comment: "gram of carbs")
  447. )
  448. .font(.callout).fontWeight(.bold).fontDesign(.rounded)
  449. }
  450. Spacer()
  451. if state.maxIOB == 0.0 {
  452. HStack {
  453. Image(systemName: "exclamationmark.circle.fill")
  454. Text("MaxIOB: 0 U")
  455. }.bold()
  456. .foregroundStyle(Color.red)
  457. .font(.callout)
  458. } else {
  459. HStack {
  460. /// Only display the insulin delivery rate info if the pump is not
  461. /// suspended and is available (e.g., pod is paired & not faulted).
  462. let pumpAvailable = state.apsManager.isScheduledBasal != nil
  463. if !state.apsManager.isSuspended && pumpAvailable {
  464. Image(systemName: "drop.circle")
  465. .font(.callout)
  466. .foregroundColor(.insulinTintColor)
  467. if let basalString = self.basalString {
  468. /// Adjust opacity when displaying a scheduled basal rate
  469. let opacity = state.apsManager?.isScheduledBasal == true ? 0.6 : 1.0
  470. if basalString.count > 5 {
  471. Text(basalString)
  472. .font(.callout).fontWeight(.bold).fontDesign(.rounded)
  473. .lineLimit(1)
  474. .minimumScaleFactor(0.85)
  475. .truncationMode(.tail)
  476. .allowsTightening(true)
  477. .opacity(opacity)
  478. } else {
  479. // Short strings can just display normally
  480. Text(basalString)
  481. .font(.callout).fontWeight(.bold).fontDesign(.rounded)
  482. .opacity(opacity)
  483. }
  484. } else {
  485. Text("No Data")
  486. .font(.callout).fontWeight(.bold).fontDesign(.rounded)
  487. }
  488. }
  489. }
  490. }
  491. }.padding(.horizontal)
  492. }
  493. @ViewBuilder func adjustmentsOverrideView(_ overrideString: String) -> some View {
  494. Group {
  495. Image(systemName: "clock.arrow.2.circlepath")
  496. .font(.title2)
  497. .foregroundStyle(Color.primary, Color.purple)
  498. VStack(alignment: .leading) {
  499. Text(latestOverride.first?.name ?? String(localized: "Custom Override"))
  500. .font(.subheadline)
  501. .frame(alignment: .leading)
  502. Text(overrideString)
  503. .font(.caption)
  504. }
  505. }
  506. .onTapGesture {
  507. selectedTab = 2
  508. }
  509. }
  510. @ViewBuilder func adjustmentsTempTargetView(_ tempTargetString: String) -> some View {
  511. Group {
  512. Image(systemName: "target")
  513. .font(.title2)
  514. .foregroundStyle(Color.loopGreen)
  515. VStack(alignment: .leading) {
  516. Text(latestTempTarget.first?.name ?? String(localized: "Temp Target"))
  517. .font(.subheadline)
  518. Text(tempTargetString)
  519. .font(.caption)
  520. }
  521. }
  522. .onTapGesture {
  523. selectedTab = 2
  524. }
  525. }
  526. @ViewBuilder func adjustmentsCancelView(_ cancelAction: @escaping () -> Void) -> some View {
  527. Image(systemName: "xmark.app")
  528. .font(.title)
  529. .onTapGesture {
  530. cancelAction()
  531. }
  532. }
  533. @ViewBuilder func adjustmentsCancelTempTargetView() -> some View {
  534. Image(systemName: "xmark.app")
  535. .font(.title)
  536. .confirmationDialog(
  537. "Stop the Temp Target \"\(latestTempTarget.first?.name ?? "")\"?",
  538. isPresented: $isConfirmStopTempTargetShown,
  539. titleVisibility: .visible
  540. ) {
  541. Button("Stop", role: .destructive) {
  542. Task {
  543. guard let objectID = latestTempTarget.first?.objectID else { return }
  544. await state.cancelTempTarget(withID: objectID)
  545. }
  546. }
  547. Button("Cancel", role: .cancel) {}
  548. }
  549. .padding(.trailing, 8)
  550. .onTapGesture {
  551. if !latestTempTarget.isEmpty {
  552. isConfirmStopTempTargetShown = true
  553. }
  554. }
  555. }
  556. @ViewBuilder func adjustmentsCancelOverrideView() -> some View {
  557. Image(systemName: "xmark.app")
  558. .font(.title)
  559. .confirmationDialog(
  560. "Stop the Override \"\(latestOverride.first?.name ?? "")\"?",
  561. isPresented: $isConfirmStopOverridePresented,
  562. titleVisibility: .visible
  563. ) {
  564. Button("Stop", role: .destructive) {
  565. Task {
  566. guard let objectID = latestOverride.first?.objectID else { return }
  567. await state.cancelOverride(withID: objectID)
  568. }
  569. }
  570. Button("Cancel", role: .cancel) {}
  571. }
  572. .padding(.trailing, 8)
  573. .onTapGesture {
  574. if !latestOverride.isEmpty {
  575. isConfirmStopOverridePresented = true
  576. }
  577. }
  578. }
  579. @ViewBuilder func noActiveAdjustmentsView() -> some View {
  580. Group {
  581. VStack {
  582. Text("No Active Adjustment")
  583. .font(.subheadline)
  584. .frame(maxWidth: .infinity, alignment: .leading)
  585. Text("Profile at 100 %")
  586. .font(.caption)
  587. .frame(maxWidth: .infinity, alignment: .leading)
  588. }.padding(.leading, 10)
  589. Spacer()
  590. /// to ensure the same position....
  591. Image(systemName: "xmark.app")
  592. .font(.title)
  593. // clear color for the icon
  594. .foregroundStyle(Color.clear)
  595. }.onTapGesture {
  596. selectedTab = 2
  597. }
  598. }
  599. @ViewBuilder func adjustmentView(geo: GeometryProxy) -> some View {
  600. // let background = colorScheme == .dark ? Material.ultraThinMaterial.opacity(0.5) : Color.black.opacity(0.2)
  601. ZStack {
  602. /// rectangle as background
  603. RoundedRectangle(cornerRadius: 15)
  604. .fill(
  605. (overrideString != nil || tempTargetString != nil) ?
  606. (
  607. colorScheme == .dark ?
  608. Color(red: 0.03921568627, green: 0.133333333, blue: 0.2156862745) :
  609. Color.insulin.opacity(0.1)
  610. ) : Color.clear // Use clear and add the Material in the background
  611. )
  612. .background(colorScheme == .dark ? Color.chart.opacity(0.25) : Color.black.opacity(0.075))
  613. .clipShape(RoundedRectangle(cornerRadius: 15))
  614. .frame(height: geo.size.height * 0.08)
  615. .shadow(
  616. color: (overrideString != nil || tempTargetString != nil) ?
  617. (
  618. colorScheme == .dark ? Color(red: 0.02745098039, green: 0.1098039216, blue: 0.1411764706) :
  619. Color.black.opacity(0.33)
  620. ) : Color.clear,
  621. radius: 3
  622. )
  623. HStack {
  624. if let overrideString = overrideString, let tempTargetString = tempTargetString {
  625. HStack {
  626. adjustmentsOverrideView(overrideString)
  627. Spacer()
  628. Divider()
  629. .frame(height: geo.size.height * 0.05)
  630. .padding(.horizontal, 2)
  631. adjustmentsTempTargetView(tempTargetString)
  632. Spacer()
  633. adjustmentsCancelView({
  634. if !latestTempTarget.isEmpty, !latestOverride.isEmpty {
  635. showCancelConfirmDialog = true
  636. } else if !latestOverride.isEmpty {
  637. showCancelAlert = true
  638. } else if !latestTempTarget.isEmpty {
  639. showCancelAlert = true
  640. }
  641. })
  642. }
  643. } else if let overrideString = overrideString {
  644. adjustmentsOverrideView(overrideString)
  645. Spacer()
  646. adjustmentsCancelOverrideView()
  647. } else if let tempTargetString = tempTargetString {
  648. HStack {
  649. adjustmentsTempTargetView(tempTargetString)
  650. Spacer()
  651. adjustmentsCancelTempTargetView()
  652. }
  653. } else {
  654. noActiveAdjustmentsView()
  655. }
  656. }.padding(.horizontal, 10)
  657. .confirmationDialog("Adjustment to Stop", isPresented: $showCancelConfirmDialog) {
  658. Button("Stop Override", role: .destructive) {
  659. Task {
  660. guard let objectID = latestOverride.first?.objectID else { return }
  661. await state.cancelOverride(withID: objectID)
  662. }
  663. }
  664. Button("Stop Temp Target", role: .destructive) {
  665. Task {
  666. guard let objectID = latestTempTarget.first?.objectID else { return }
  667. await state.cancelTempTarget(withID: objectID)
  668. }
  669. }
  670. Button("Stop All Adjustments", role: .destructive) {
  671. Task {
  672. guard let overrideObjectID = latestOverride.first?.objectID else { return }
  673. await state.cancelOverride(withID: overrideObjectID)
  674. guard let tempTargetObjectID = latestTempTarget.first?.objectID else { return }
  675. await state.cancelTempTarget(withID: tempTargetObjectID)
  676. }
  677. }
  678. } message: {
  679. Text("Select Adjustment")
  680. }
  681. }.padding(.horizontal, 10).padding(.bottom, UIDevice.adjustPadding(min: nil, max: 10))
  682. }
  683. @ViewBuilder func bolusProgressBar(_ progress: Decimal) -> some View {
  684. GeometryReader { geo in
  685. RoundedRectangle(cornerRadius: 15)
  686. .frame(height: 6)
  687. .foregroundColor(.clear)
  688. .background(
  689. LinearGradient(colors: [
  690. Color(red: 0.7215686275, green: 0.3411764706, blue: 1),
  691. Color(red: 0.6235294118, green: 0.4235294118, blue: 0.9803921569),
  692. Color(red: 0.4862745098, green: 0.5450980392, blue: 0.9529411765),
  693. Color(red: 0.3411764706, green: 0.6666666667, blue: 0.9254901961),
  694. Color(red: 0.262745098, green: 0.7333333333, blue: 0.9137254902)
  695. ], startPoint: .leading, endPoint: .trailing)
  696. .mask(alignment: .leading) {
  697. RoundedRectangle(cornerRadius: 15)
  698. .frame(width: geo.size.width * CGFloat(progress))
  699. }
  700. )
  701. }
  702. }
  703. @ViewBuilder func bolusView(geo: GeometryProxy, _ progress: Decimal) -> some View {
  704. /// ensure that state.lastPumpBolus has a value, i.e. there is a last bolus done by the pump and not an external bolus
  705. /// - TRUE: show the pump bolus
  706. /// - FALSE: do not show a progress bar at all
  707. if let bolusTotal = state.lastPumpBolus?.bolus?.amount {
  708. let bolusFraction = progress * (bolusTotal as Decimal)
  709. let bolusString =
  710. (bolusProgressFormatter.string(from: bolusFraction as NSNumber) ?? "0")
  711. + String(localized: " of ", comment: "Bolus string partial message: 'x U of y U' in home view") +
  712. (Formatter.decimalFormatterWithThreeFractionDigits.string(from: bolusTotal as NSNumber) ?? "0")
  713. + String(localized: " U", comment: "Insulin unit")
  714. ZStack {
  715. /// rectangle as background
  716. RoundedRectangle(cornerRadius: 15)
  717. .fill(
  718. colorScheme == .dark ? Color(red: 0.03921568627, green: 0.133333333, blue: 0.2156862745) : Color
  719. .insulin
  720. .opacity(0.2)
  721. )
  722. .clipShape(RoundedRectangle(cornerRadius: 15))
  723. .frame(height: geo.size.height * 0.08)
  724. .shadow(
  725. color: colorScheme == .dark ? Color(red: 0.02745098039, green: 0.1098039216, blue: 0.1411764706) :
  726. Color.black.opacity(0.33),
  727. radius: 3
  728. )
  729. /// actual bolus view
  730. HStack {
  731. Image(systemName: "cross.vial.fill")
  732. .font(.system(size: 25))
  733. Spacer()
  734. VStack {
  735. Text("Bolusing")
  736. .font(.subheadline)
  737. .frame(maxWidth: .infinity, alignment: .leading)
  738. Text(bolusString)
  739. .font(.caption)
  740. .frame(maxWidth: .infinity, alignment: .leading)
  741. }.padding(.leading, 5)
  742. Spacer()
  743. Button {
  744. state.showProgressView()
  745. state.cancelBolus()
  746. } label: {
  747. Image(systemName: "xmark.app")
  748. .font(.system(size: 25))
  749. }
  750. }.padding(.horizontal, 10)
  751. .padding(.trailing, 8)
  752. }.padding(.horizontal, 10).padding(.bottom, UIDevice.adjustPadding(min: nil, max: 10))
  753. .overlay(alignment: .bottom) {
  754. // Use a geo-based offset here to position progress bar independent of device size
  755. let offset = geo.size.height * 0.0725
  756. bolusProgressBar(progress).padding(.horizontal, 18)
  757. .offset(y: offset)
  758. }.clipShape(RoundedRectangle(cornerRadius: 15))
  759. }
  760. }
  761. @ViewBuilder func alertSafetyNotificationsView(geo: GeometryProxy) -> some View {
  762. ZStack {
  763. /// rectangle as background
  764. RoundedRectangle(cornerRadius: 15)
  765. .fill(
  766. Color(
  767. red: 0.9,
  768. green: 0.133333333,
  769. blue: 0.2156862745
  770. )
  771. )
  772. .clipShape(RoundedRectangle(cornerRadius: 15))
  773. .frame(height: geo.size.height * safeAreaSize)
  774. .coordinateSpace(name: "alertSafetyNotificationsView")
  775. .shadow(
  776. color: colorScheme == .dark ? Color(red: 0.02745098039, green: 0.1098039216, blue: 0.1411764706) :
  777. Color.black.opacity(0.33),
  778. radius: 3
  779. )
  780. HStack {
  781. Spacer()
  782. VStack {
  783. Text("⚠️ Safety Notifications are OFF")
  784. .font(.headline)
  785. .fontWeight(.bold)
  786. .fontDesign(.rounded)
  787. .foregroundStyle(.white.gradient)
  788. .frame(maxWidth: .infinity, alignment: .leading)
  789. Text("Fix now by turning Notifications ON.")
  790. .font(.footnote)
  791. .fontDesign(.rounded)
  792. .foregroundStyle(.white.gradient)
  793. .frame(maxWidth: .infinity, alignment: .leading)
  794. }.padding(.leading, 5)
  795. Spacer()
  796. Image(systemName: "chevron.right").foregroundColor(.white)
  797. .font(.headline)
  798. }.padding(.horizontal, 10)
  799. .padding(.trailing, 8)
  800. .onTapGesture {
  801. UIApplication.shared.open(URL(string: UIApplication.openSettingsURLString)!)
  802. }
  803. }.padding(.horizontal, 10)
  804. .padding(.top, 0)
  805. }
  806. @ViewBuilder func mainViewElements(_ geo: GeometryProxy) -> some View {
  807. VStack(spacing: 0) {
  808. ZStack {
  809. if let apsManager = state.apsManager, let bluetoothManager = apsManager.bluetoothManager,
  810. bluetoothManager.bluetoothAuthorization != .authorized
  811. {
  812. BluetoothRequiredView()
  813. } else {
  814. /// right panel with loop status and evBG
  815. HStack {
  816. Spacer()
  817. rightHeaderPanel(geo)
  818. }.padding(.trailing, 20)
  819. /// glucose bobble
  820. glucoseView
  821. /// left panel with pump related info
  822. HStack {
  823. pumpView
  824. Spacer()
  825. }.padding(.leading, 20)
  826. }
  827. }
  828. .padding(.top, 10)
  829. .safeAreaInset(edge: .top, spacing: 0) {
  830. if notificationsDisabled {
  831. alertSafetyNotificationsView(geo: geo)
  832. }
  833. if let badgeImage = state.pumpStatusBadgeImage, let badgeColor = state.pumpStatusBadgeColor {
  834. pumpTimezoneView(badgeImage, badgeColor)
  835. .padding(.horizontal, 20)
  836. }
  837. }
  838. mealPanel(geo).padding(.top, UIDevice.adjustPadding(min: nil, max: 30))
  839. .padding(.bottom, UIDevice.adjustPadding(min: nil, max: 20))
  840. mainChart(geo: geo)
  841. HStack {
  842. tappableButton(
  843. buttonColor: (colorScheme == .dark ? Color.white : Color.black).opacity(0.8),
  844. label: String(localized: "Stats", comment: "Stats icon in main view"),
  845. iconString: statsIconString,
  846. action: { state.showModal(for: .statistics) }
  847. )
  848. Spacer()
  849. timeIntervalButtons.padding(.top, UIDevice.adjustPadding(min: 0, max: 10))
  850. .padding(.bottom, UIDevice.adjustPadding(min: 0, max: 10))
  851. Spacer()
  852. tappableButton(
  853. buttonColor: (colorScheme == .dark ? Color.white : Color.black).opacity(0.8),
  854. label: String(localized: "Info", comment: "Info icon in main view"),
  855. iconString: "info",
  856. action: { state.isLegendPresented.toggle() }
  857. )
  858. }.padding([.horizontal, .bottom])
  859. if let progress = state.bolusProgress {
  860. bolusView(geo: geo, progress)
  861. .padding(.bottom, UIDevice.adjustPadding(min: nil, max: 40))
  862. } else {
  863. adjustmentView(geo: geo).padding(.bottom, UIDevice.adjustPadding(min: nil, max: 40))
  864. }
  865. }
  866. .background(appState.trioBackgroundColor(for: colorScheme))
  867. .onReceive(
  868. resolver.resolve(AlertPermissionsChecker.self)!.$notificationsDisabled,
  869. perform: {
  870. if notificationsDisabled != $0 {
  871. notificationsDisabled = $0
  872. if notificationsDisabled {
  873. debug(.default, "notificationsDisabled")
  874. }
  875. }
  876. }
  877. )
  878. }
  879. @ViewBuilder func mainView() -> some View {
  880. GeometryReader { geo in
  881. mainViewElements(geo)
  882. }
  883. .onChange(of: state.hours) {
  884. highlightButtons()
  885. }
  886. .onAppear {
  887. configureView {
  888. highlightButtons()
  889. }
  890. }
  891. .navigationTitle("Home")
  892. .navigationBarHidden(true)
  893. .ignoresSafeArea(.keyboard)
  894. .blur(radius: state.isLoopStatusPresented ? 3 : 0)
  895. .sheet(isPresented: $state.isLoopStatusPresented) {
  896. LoopStatusView(state: state)
  897. }
  898. .sheet(isPresented: $state.isLegendPresented) {
  899. ChartLegendView(state: state)
  900. }
  901. // PUMP RELATED
  902. .confirmationDialog("Pump Model", isPresented: $showPumpSelection) {
  903. Button("Medtronic") { state.addPump(.minimed) }
  904. Button("Omnipod Eros") { state.addPump(.omnipod) }
  905. Button("Omnipod DASH") { state.addPump(.omnipodBLE) }
  906. Button("Dana(RS/-i)") { state.addPump(.dana) }
  907. Button("Pump Simulator") { state.addPump(.simulator) }
  908. } message: { Text("Select Pump Model") }
  909. .sheet(isPresented: $state.shouldDisplayPumpSetupSheet) {
  910. if let pumpManager = state.provider.apsManager.pumpManager {
  911. PumpConfig.PumpSettingsView(
  912. pumpManager: pumpManager,
  913. bluetoothManager: state.provider.apsManager.bluetoothManager!,
  914. completionDelegate: state,
  915. setupDelegate: state
  916. )
  917. } else {
  918. PumpConfig.PumpSetupView(
  919. pumpType: state.setupPumpType,
  920. pumpInitialSettings: state.pumpInitialSettings,
  921. bluetoothManager: state.provider.apsManager.bluetoothManager!,
  922. completionDelegate: state,
  923. setupDelegate: state
  924. )
  925. }
  926. }
  927. // CGM RELATED
  928. .confirmationDialog("CGM Model", isPresented: $showCGMSelection) {
  929. cgmSelectionButtons
  930. } message: {
  931. Text("Select CGM Model")
  932. }
  933. .sheet(isPresented: $state.shouldDisplayCGMSetupSheet) {
  934. switch state.cgmCurrent.type {
  935. case .enlite,
  936. .nightscout,
  937. .none,
  938. .simulator,
  939. .xdrip:
  940. CGMSettings.CustomCGMOptionsView(
  941. resolver: self.resolver,
  942. state: state.cgmStateModel,
  943. cgmCurrent: state.cgmCurrent,
  944. deleteCGM: state.deleteCGM
  945. )
  946. case .plugin:
  947. if let fetchGlucoseManager = state.fetchGlucoseManager,
  948. let cgmManager = fetchGlucoseManager.cgmManager,
  949. state.cgmCurrent.type == fetchGlucoseManager.cgmGlucoseSourceType,
  950. state.cgmCurrent.id == fetchGlucoseManager.cgmGlucosePluginId
  951. {
  952. CGMSettings.CGMSettingsView(
  953. cgmManager: cgmManager,
  954. bluetoothManager: state.provider.apsManager.bluetoothManager!,
  955. unit: state.settingsManager.settings.units,
  956. completionDelegate: state
  957. )
  958. } else {
  959. CGMSettings.CGMSetupView(
  960. CGMType: state.cgmCurrent,
  961. bluetoothManager: state.provider.apsManager.bluetoothManager!,
  962. unit: state.settingsManager.settings.units,
  963. completionDelegate: state,
  964. setupDelegate: state,
  965. pluginCGMManager: self.state.pluginCGMManager
  966. )
  967. }
  968. }
  969. }
  970. }
  971. @ViewBuilder func tabBar() -> some View {
  972. ZStack(alignment: .bottom) {
  973. TabView(selection: $selectedTab) {
  974. let carbsRequiredBadge: String? = {
  975. guard let carbsRequired = state.enactedAndNonEnactedDeterminations.first?.carbsRequired,
  976. state.showCarbsRequiredBadge
  977. else {
  978. return nil
  979. }
  980. let carbsRequiredDecimal = Decimal(carbsRequired)
  981. if carbsRequiredDecimal > state.settingsManager.settings.carbsRequiredThreshold {
  982. let numberAsNSNumber = NSDecimalNumber(decimal: carbsRequiredDecimal)
  983. return (Formatter.decimalFormatterWithTwoFractionDigits.string(from: numberAsNSNumber) ?? "") + " g"
  984. }
  985. return nil
  986. }()
  987. NavigationStack { mainView() }
  988. .tabItem { Label("Main", systemImage: "chart.xyaxis.line") }
  989. .badge(carbsRequiredBadge).tag(0)
  990. NavigationStack { DataTable.RootView(resolver: resolver) }
  991. .tabItem { Label("History", systemImage: historySFSymbol) }.tag(1)
  992. Spacer()
  993. NavigationStack { Adjustments.RootView(resolver: resolver) }
  994. .tabItem {
  995. Label(
  996. "Adjustments",
  997. systemImage: "slider.horizontal.2.gobackward"
  998. ) }.tag(2)
  999. NavigationStack(path: self.$settingsPath) {
  1000. Settings.RootView(resolver: resolver) }
  1001. .tabItem { Label(
  1002. "Settings",
  1003. systemImage: "gear"
  1004. ) }.tag(3)
  1005. }
  1006. .tint(Color.tabBar)
  1007. Button(
  1008. action: {
  1009. state.showModal(for: .treatmentView) },
  1010. label: {
  1011. Image(systemName: "plus.circle.fill")
  1012. .font(.system(size: 40))
  1013. .foregroundStyle(Color.tabBar)
  1014. .padding(.vertical, 2)
  1015. .padding(.horizontal, 24)
  1016. }
  1017. )
  1018. }.ignoresSafeArea(.keyboard, edges: .bottom).blur(radius: state.waitForSuggestion ? 8 : 0)
  1019. .onChange(of: selectedTab) {
  1020. if !settingsPath.isEmpty {
  1021. settingsPath = NavigationPath()
  1022. }
  1023. }
  1024. }
  1025. var body: some View {
  1026. ZStack(alignment: .center) {
  1027. tabBar()
  1028. if state.waitForSuggestion {
  1029. CustomProgressView(text: String(localized: "Updating IOB...", comment: "Progress text when updating IOB"))
  1030. }
  1031. }
  1032. }
  1033. }
  1034. }
  1035. extension UIDevice {
  1036. public enum DeviceSize: CGFloat {
  1037. case smallDevice = 667 // Height for 4" iPhone SE
  1038. case largeDevice = 852 // Height for 6.1" iPhone 15 Pro
  1039. }
  1040. @usableFromInline static func adjustPadding(
  1041. min: CGFloat? = nil,
  1042. max: CGFloat? = nil
  1043. ) -> CGFloat? {
  1044. if UIScreen.screenHeight > UIDevice.DeviceSize.smallDevice.rawValue {
  1045. if UIScreen.screenHeight >= UIDevice.DeviceSize.largeDevice.rawValue {
  1046. return max
  1047. } else {
  1048. return min != nil ?
  1049. (max != nil ? max! * (UIScreen.screenHeight / UIDevice.DeviceSize.largeDevice.rawValue) : nil) : nil
  1050. }
  1051. } else {
  1052. return min
  1053. }
  1054. }
  1055. }
  1056. extension UIScreen {
  1057. static var screenHeight: CGFloat {
  1058. UIScreen.main.bounds.height
  1059. }
  1060. static var screenWidth: CGFloat {
  1061. UIScreen.main.bounds.width
  1062. }
  1063. }
  1064. /// Checks if the device is using a 24-hour time format.
  1065. func is24HourFormat() -> Bool {
  1066. let formatter = DateFormatter()
  1067. formatter.locale = Locale.current
  1068. formatter.dateStyle = .none
  1069. formatter.timeStyle = .short
  1070. let dateString = formatter.string(from: Date())
  1071. return !dateString.contains("AM") && !dateString.contains("PM")
  1072. }
  1073. /// Converts a duration in minutes to a formatted string (e.g., "1 h 30 m").
  1074. func formatHrMin(_ durationInMinutes: Int) -> String {
  1075. let hours = durationInMinutes / 60
  1076. let minutes = durationInMinutes % 60
  1077. switch (hours, minutes) {
  1078. case let (0, m):
  1079. return "\(m)\u{00A0}" + String(localized: "m", comment: "Abbreviation for Minutes")
  1080. case let (h, 0):
  1081. return "\(h)\u{00A0}" + String(localized: "h", comment: "h")
  1082. default:
  1083. return hours.description + "\u{00A0}" + String(localized: "h", comment: "h") + "\u{00A0}" + minutes
  1084. .description + "\u{00A0}" + String(localized: "m", comment: "Abbreviation for Minutes")
  1085. }
  1086. }
  1087. // Helper function to convert a start and end hour to either 24-hour or AM/PM format
  1088. func formatTimeRange(start: String?, end: String?) -> String {
  1089. guard let start = start, let end = end else {
  1090. return ""
  1091. }
  1092. // Check if the format is 24-hour or AM/PM
  1093. if is24HourFormat() {
  1094. // Return the original 24-hour format
  1095. return "\(start)-\(end)"
  1096. } else {
  1097. // Convert to AM/PM format using DateFormatter
  1098. let formatter = DateFormatter()
  1099. formatter.dateFormat = "HH"
  1100. if let startHour = Int(start), let endHour = Int(end) {
  1101. let startDate = Calendar.current.date(bySettingHour: startHour, minute: 0, second: 0, of: Date()) ?? Date()
  1102. let endDate = Calendar.current.date(bySettingHour: endHour, minute: 0, second: 0, of: Date()) ?? Date()
  1103. // Customize the format to "2p" or "2a"
  1104. formatter.dateFormat = "ha"
  1105. let startFormatted = formatter.string(from: startDate).lowercased().replacingOccurrences(of: "m", with: "")
  1106. let endFormatted = formatter.string(from: endDate).lowercased().replacingOccurrences(of: "m", with: "")
  1107. return "\(startFormatted)-\(endFormatted)"
  1108. } else {
  1109. return ""
  1110. }
  1111. }
  1112. }