HomeRootView.swift 50 KB

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