HomeRootView.swift 45 KB

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