HomeRootView.swift 46 KB

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